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