]> git.mxchange.org Git - friendica.git/blob - mod/receive.php
Merge pull request #144 from fabrixxm/newacl
[friendica.git] / mod / receive.php
1 <?php
2
3 /**
4  * Diaspora endpoint
5  */
6
7
8 require_once('include/salmon.php');
9 require_once('library/simplepie/simplepie.inc');
10
11 function receive_return($val) {
12
13         if($val >= 400)
14                 $err = 'Error';
15         if($val >= 200 && $val < 300)
16                 $err = 'OK';
17
18         logger('mod-diaspora returns ' . $val); 
19         header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
20         killme();
21
22 }
23
24 function receive_post(&$a) {
25
26         if($a->argc != 3 || $a->argv[1] !== 'users')
27                 receive_return(500);
28
29         $guid = $a->argv[2];
30
31         $r = q("SELECT * FROM `user` WHERE `guid` = '%s' LIMIT 1",
32                 dbesc($guid)
33         );
34         if(! count($r))
35                 salmon_return(500);
36
37         $importer = $r[0];
38
39         $xml = $_POST['xml'];
40
41         logger('mod-diaspora: new salmon ' . $xml, LOGGER_DATA);
42
43         if(! $xml)
44                 receive_return(500);
45
46         // parse the xml
47
48         $dom = simplexml_load_string($xml,'SimpleXMLElement',0,NAMESPACE_SALMON_ME);
49
50         // figure out where in the DOM tree our data is hiding
51
52         if($dom->provenance->data)
53                 $base = $dom->provenance;
54         elseif($dom->env->data)
55                 $base = $dom->env;
56         elseif($dom->data)
57                 $base = $dom;
58         
59         if(! $base) {
60                 logger('mod-diaspora: unable to locate salmon data in xml ');
61                 receive_return(400);
62         }
63
64         // Stash the signature away for now. We have to find their key or it won't be good for anything.
65         $signature = base64url_decode($base->sig);
66
67         // unpack the  data
68
69         // strip whitespace so our data element will return to one big base64 blob
70         $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
71
72         // stash away some other stuff for later
73
74         $type = $base->data[0]->attributes()->type[0];
75         $keyhash = $base->sig[0]->attributes()->keyhash[0];
76         $encoding = $base->encoding;
77         $alg = $base->alg;
78
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-diaspora: 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-diaspora: 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-diaspora: Could not retrieve author URI.');
116                 receive_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                 receive_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     $verify = $rsa->verify($signed_data,$signature);
153
154         if(! $verify) {
155                 logger('mod-diaspora: Message did not verify. Discarding.');
156                 receive_return(400);
157         }
158
159         logger('mod-diaspora: Message verified.');
160
161         /* decrypt the sucker */
162         /*
163                 // TODO
164         */
165
166         /*
167         *
168         * If we reached this point, the message is good. Now let's figure out if the author is allowed to send us stuff.
169         *
170         */
171
172         $r = q("SELECT * FROM `contact` WHERE `network` = 'dspr' AND ( `url` = '%s' OR `alias` = '%s') 
173                 AND `uid` = %d LIMIT 1",
174                 dbesc($author_link),
175                 dbesc($author_link),
176                 intval($importer['uid'])
177         );
178         if(! count($r)) {
179                 logger('mod-diaspora: Author unknown to us.');
180         }       
181
182         // is this a follower? Or have we ignored the person?
183         // If so we can not accept this post.
184
185         if((count($r)) && (($r[0]['readonly']) || ($r[0]['rel'] == REL_VIP) || ($r[0]['blocked']))) {
186                 logger('mod-diaspora: Ignoring this author.');
187                 receive_return(202);
188                 // NOTREACHED
189         }
190
191         require_once('include/items.php');
192
193         // Placeholder for hub discovery. We shouldn't find any hubs
194         // since we supplied the fake feed header - and it doesn't have any.
195
196         $hub = '';
197
198         /**
199          *
200          * anti-spam measure: consume_feed will accept a follow activity from 
201          * this person (and nothing else) if there is no existing contact record.
202          *
203          */
204
205         $contact_rec = ((count($r)) ? $r[0] : null);
206
207         consume_feed($feedxml,$importer,$contact_rec,$hub);
208
209         receive_return(200);
210 }
211
212
213
214