]> git.mxchange.org Git - friendica.git/blob - mod/salmon.php
721eae4371f6b278e6f12b83c45827763e7f90c3
[friendica.git] / mod / salmon.php
1 <?php
2
3
4 // There is a lot of debug stuff in here because this is quite a
5 // complicated process to try and sort out. 
6
7 require_once('include/salmon.php');
8 require_once('library/simplepie/simplepie.inc');
9
10 function salmon_return($val) {
11
12         if($val >= 400)
13                 $err = 'Error';
14         if($val >= 200 && $val < 300)
15                 $err = 'OK';
16
17         logger('mod-salmon returns ' . $val);   
18         header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
19         killme();
20
21 }
22
23 function salmon_post(&$a) {
24
25         $xml = file_get_contents('php://input');
26
27         logger('mod-salmon: new salmon ' . $xml);
28
29         $nick       = (($a->argc > 1) ? notags(trim($a->argv[1])) : '');
30         $mentions   = (($a->argc > 2 && $a->argv[2] === 'mention') ? true : false);
31
32         $r = q("SELECT * FROM `user` WHERE `nickname` = '%s' LIMIT 1",
33                 dbesc($nick)
34         );
35         if(! count($r))
36                 salmon_return(500);
37
38         $importer = $r[0];
39
40         // parse the xml
41
42         $dom = simplexml_load_string($xml,'SimpleXMLElement',0,NAMESPACE_SALMON_ME);
43
44         // figure out where in the DOM tree our data is hiding
45
46         if($dom->provenance->data)
47                 $base = $dom->provenance;
48         elseif($dom->env->data)
49                 $base = $dom->env;
50         elseif($dom->data)
51                 $base = $dom;
52         
53         if(! $base) {
54                 logger('mod-salmon: unable to locate salmon data in xml ');
55                 salmon_return(400);
56         }
57
58         // Stash the signature away for now. We have to find their key or it won't be good for anything.
59
60
61         $signature = base64url_decode($base->sig);
62
63         // unpack the  data
64
65         // strip whitespace so our data element will return to one big base64 blob
66         $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
67
68         // stash away some other stuff for later
69
70         $type = $base->data[0]->attributes()->type[0];
71         $keyhash = $base->sig[0]->attributes()->keyhash[0];
72         $encoding = $base->encoding;
73         $alg = $base->alg;
74
75         // If we're talking to status.net or one of their ilk, they aren't following the magic envelope spec
76         // and only signed the data element. We'll be nice and let them validate anyway. 
77
78         $stnet_signed_data = $data;
79         $signed_data = $data  . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
80
81         // decode the data
82         $data = base64url_decode($data);
83
84         // Remove the xml declaration
85         $data = preg_replace('/\<\?xml[^\?].*\?\>/','',$data);
86
87         // Create a fake feed wrapper so simplepie doesn't choke
88
89         $tpl = get_markup_template('fake_feed.tpl');
90         
91         $base = substr($data,strpos($data,'<entry'));
92
93         $feedxml = $tpl . $base . '</feed>';
94
95         logger('mod-salmon: Processed feed: ' . $feedxml);
96
97         // Now parse it like a normal atom feed to scrape out the author URI
98         
99     $feed = new SimplePie();
100     $feed->set_raw_data($feedxml);
101     $feed->enable_order_by_date(false);
102     $feed->init();
103
104         logger('mod-salmon: Feed parsed.');
105
106         if($feed->get_item_quantity()) {
107                 foreach($feed->get_items() as $item) {
108                         $author = $item->get_author();
109                         $author_link = unxmlify($author->get_link());
110                         break;
111                 }
112         }
113
114         if(! $author_link) {
115                 logger('mod-salmon: Could not retrieve author URI.');
116                 salmon_return(400);
117         }
118
119         // Once we have the author URI, go to the web and try to find their public key
120
121         logger('mod-salmon: Fetching key for ' . $author_link );
122
123
124         $key = get_salmon_key($author_link,$keyhash);
125
126         if(! $key) {
127                 logger('mod-salmon: Could not retrieve author key.');
128                 salmon_return(400);
129         }
130
131         // Setup RSA stuff to verify the signature
132
133         set_include_path(get_include_path() . PATH_SEPARATOR . 'library' . PATH_SEPARATOR . 'phpsec');
134
135         require_once('library/phpsec/Crypt/RSA.php');
136
137         $key_info = explode('.',$key);
138
139         $m = base64url_decode($key_info[1]);
140         $e = base64url_decode($key_info[2]);
141
142         logger('mod-salmon: key details: ' . print_r($key_info,true));
143
144     $rsa = new CRYPT_RSA();
145     $rsa->signatureMode = CRYPT_RSA_SIGNATURE_PKCS1;
146     $rsa->setHash('sha256');
147
148     $rsa->modulus = new Math_BigInteger($m, 256);
149     $rsa->k = strlen($rsa->modulus->toBytes());
150     $rsa->exponent = new Math_BigInteger($e, 256);
151
152         // We should have everything we need now. Let's see if it verifies.
153         // If it fails with the proper data format, try again using just the data
154         // (e.g. status.net)
155
156     $verify = $rsa->verify($signed_data,$signature);
157
158         if(! $verify) {
159                 logger('mod-salmon: message did not verify using protocol. Trying statusnet hack.');
160             $verify = $rsa->verify($stnet_signed_data,$signature);
161     }
162
163         if(! $verify) {
164                 logger('mod-salmon: Message did not verify. Discarding.');
165                 salmon_return(400);
166         }
167
168         logger('mod-salmon: Message verified.');
169
170
171         /*
172         *
173         * If we reached this point, the message is good. Now let's figure out if the author is allowed to send us stuff.
174         *
175         */
176
177         $r = q("SELECT * FROM `contact` WHERE `network` = 'stat' AND ( `url` = '%s' OR `alias` = '%s') 
178                 AND `uid` = %d LIMIT 1",
179                 dbesc($author_link),
180                 dbesc($author_link),
181                 intval($importer['uid'])
182         );
183         if(! count($r)) {
184                 logger('mod-salmon: Author unknown to us.');
185         }       
186
187         // is this a follower? Or have we ignored the person?
188         // If so we can not accept this post.
189
190         if((count($r)) && (($r[0]['readonly']) || ($r[0]['rel'] == REL_VIP) || ($r[0]['blocked']))) {
191                 logger('mod-salmon: Ignoring this author.');
192                 salmon_return(202);
193                 // NOTREACHED
194         }
195
196         require_once('include/items.php');
197
198         // Placeholder for hub discovery. We shouldn't find any hubs
199         // since we supplied the fake feed header - and it doesn't have any.
200
201         $hub = '';
202
203         /**
204          *
205          * anti-spam measure: consume_feed will accept a follow activity from 
206          * this person (and nothing else) if there is no existing contact record.
207          *
208          */
209
210         $contact_rec = ((count($r)) ? $r[0] : null);
211
212         consume_feed($feedxml,$importer,$contact_rec,$hub);
213
214         salmon_return(200);
215 }
216
217
218
219