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