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