Burn notices, burn
[friendica.git/.git] / mod / dfrn_notify.php
1 <?php
2
3 /**
4  * @file mod/dfrn_notify.php
5  * @brief The dfrn notify endpoint
6  * @see PDF with dfrn specs: https://github.com/friendica/friendica/blob/master/spec/dfrn2.pdf
7  */
8
9 use Friendica\App;
10 use Friendica\Core\Config;
11 use Friendica\Core\System;
12 use Friendica\Database\DBA;
13 use Friendica\Model\Contact;
14 use Friendica\Protocol\DFRN;
15 use Friendica\Protocol\Diaspora;
16
17 require_once 'include/items.php';
18
19 function dfrn_notify_post(App $a) {
20         logger(__function__, LOGGER_TRACE);
21
22         $postdata = file_get_contents('php://input');
23
24         if (empty($_POST) || !empty($postdata)) {
25                 $data = json_decode($postdata);
26                 if (is_object($data)) {
27                         $nick = defaults($a->argv, 1, '');
28
29                         $user = DBA::selectFirst('user', [], ['nickname' => $nick, 'account_expired' => false, 'account_removed' => false]);
30                         if (!DBA::isResult($user)) {
31                                 System::httpExit(500);
32                         }
33                         dfrn_dispatch_private($user, $postdata);
34                 } elseif (!dfrn_dispatch_public($postdata)) {
35                         require_once 'mod/salmon.php';
36                         salmon_post($a, $postdata);
37                 }
38         }
39
40         $dfrn_id      = ((x($_POST,'dfrn_id'))      ? notags(trim($_POST['dfrn_id']))   : '');
41         $dfrn_version = ((x($_POST,'dfrn_version')) ? (float) $_POST['dfrn_version']    : 2.0);
42         $challenge    = ((x($_POST,'challenge'))    ? notags(trim($_POST['challenge'])) : '');
43         $data         = ((x($_POST,'data'))         ? $_POST['data']                    : '');
44         $key          = ((x($_POST,'key'))          ? $_POST['key']                     : '');
45         $rino_remote  = ((x($_POST,'rino'))         ? intval($_POST['rino'])            :  0);
46         $dissolve     = ((x($_POST,'dissolve'))     ? intval($_POST['dissolve'])        :  0);
47         $perm         = ((x($_POST,'perm'))         ? notags(trim($_POST['perm']))      : 'r');
48         $ssl_policy   = ((x($_POST,'ssl_policy'))   ? notags(trim($_POST['ssl_policy'])): 'none');
49         $page         = ((x($_POST,'page'))         ? intval($_POST['page'])            :  0);
50
51         $forum = (($page == 1) ? 1 : 0);
52         $prv   = (($page == 2) ? 1 : 0);
53
54         $writable = (-1);
55         if ($dfrn_version >= 2.21) {
56                 $writable = (($perm === 'rw') ? 1 : 0);
57         }
58
59         $direction = (-1);
60         if (strpos($dfrn_id, ':') == 1) {
61                 $direction = intval(substr($dfrn_id, 0, 1));
62                 $dfrn_id = substr($dfrn_id, 2);
63         }
64
65         if (!DBA::exists('challenge', ['dfrn-id' => $dfrn_id, 'challenge' => $challenge])) {
66                 logger('could not match challenge to dfrn_id ' . $dfrn_id . ' challenge=' . $challenge);
67                 System::xmlExit(3, 'Could not match challenge');
68         }
69
70         DBA::delete('challenge', ['dfrn-id' => $dfrn_id, 'challenge' => $challenge]);
71
72         $user = DBA::selectFirst('user', ['uid'], ['nickname' => $a->argv[1]]);
73         if (!DBA::isResult($user)) {
74                 logger('User not found for nickname ' . $a->argv[1]);
75                 System::xmlExit(3, 'User not found');
76         }
77
78         // find the local user who owns this relationship.
79         $condition = [];
80         switch ($direction) {
81                 case (-1):
82                         $condition = ["`issued-id` = ? OR `dfrn-id` = ?", $dfrn_id, $dfrn_id];
83                         break;
84                 case 0:
85                         $condition = ['issued-id' => $dfrn_id, 'duplex' => true];
86                         break;
87                 case 1:
88                         $condition = ['dfrn-id' => $dfrn_id, 'duplex' => true];
89                         break;
90                 default:
91                         System::xmlExit(3, 'Invalid direction');
92                         break; // NOTREACHED
93         }
94
95         $contact = DBA::selectFirst('contact', ['id'], $condition);
96         if (!DBA::isResult($contact)) {
97                 logger('contact not found for dfrn_id ' . $dfrn_id);
98                 System::xmlExit(3, 'Contact not found');
99         }
100
101         // $importer in this case contains the contact record for the remote contact joined with the user record of our user.
102         $importer = DFRN::getImporter($contact['id'], $user['uid']);
103
104         if ((($writable != (-1)) && ($writable != $importer['writable'])) || ($importer['forum'] != $forum) || ($importer['prv'] != $prv)) {
105                 $fields = ['writable' => ($writable == (-1)) ? $importer['writable'] : $writable,
106                         'forum' => $forum, 'prv' => $prv];
107                 DBA::update('contact', $fields, ['id' => $importer['id']]);
108
109                 if ($writable != (-1)) {
110                         $importer['writable'] = $writable;
111                 }
112                 $importer['forum'] = $page;
113         }
114
115
116         // if contact's ssl policy changed, update our links
117
118         $importer = Contact::updateSslPolicy($importer, $ssl_policy);
119
120         logger('data: ' . $data, LOGGER_DATA);
121
122         if ($dissolve == 1) {
123                 // Relationship is dissolved permanently
124                 Contact::remove($importer['id']);
125                 logger('relationship dissolved : ' . $importer['name'] . ' dissolved ' . $importer['username']);
126                 System::xmlExit(0, 'relationship dissolved');
127         }
128
129         $rino = Config::get('system', 'rino_encrypt');
130         $rino = intval($rino);
131
132         if (strlen($key)) {
133
134                 // if local rino is lower than remote rino, abort: should not happen!
135                 // but only for $remote_rino > 1, because old code did't send rino version
136                 if ($rino_remote > 1 && $rino < $rino_remote) {
137                         logger("rino version '$rino_remote' is lower than supported '$rino'");
138                         System::xmlExit(0, "rino version '$rino_remote' is lower than supported '$rino'");
139                 }
140
141                 $rawkey = hex2bin(trim($key));
142                 logger('rino: md5 raw key: ' . md5($rawkey), LOGGER_DATA);
143
144                 $final_key = '';
145
146                 if ($dfrn_version >= 2.1) {
147                         if (($importer['duplex'] && strlen($importer['cprvkey'])) || !strlen($importer['cpubkey'])) {
148                                 openssl_private_decrypt($rawkey, $final_key, $importer['cprvkey']);
149                         } else {
150                                 openssl_public_decrypt($rawkey, $final_key, $importer['cpubkey']);
151                         }
152                 } else {
153                         if (($importer['duplex'] && strlen($importer['cpubkey'])) || !strlen($importer['cprvkey'])) {
154                                 openssl_public_decrypt($rawkey, $final_key, $importer['cpubkey']);
155                         } else {
156                                 openssl_private_decrypt($rawkey, $final_key, $importer['cprvkey']);
157                         }
158                 }
159
160                 switch ($rino_remote) {
161                         case 0:
162                         case 1:
163                                 // we got a key. old code send only the key, without RINO version.
164                                 // we assume RINO 1 if key and no RINO version
165                                 $data = DFRN::aesDecrypt(hex2bin($data), $final_key);
166                                 break;
167                         default:
168                                 logger("rino: invalid sent version '$rino_remote'");
169                                 System::xmlExit(0, "Invalid sent version '$rino_remote'");
170                 }
171
172                 logger('rino: decrypted data: ' . $data, LOGGER_DATA);
173         }
174
175         logger('Importing post from ' . $importer['addr'] . ' to ' . $importer['nickname'] . ' with the RINO ' . $rino_remote . ' encryption.', LOGGER_DEBUG);
176
177         $ret = DFRN::import($data, $importer);
178         System::xmlExit($ret, 'Processed');
179
180         // NOTREACHED
181 }
182
183 function dfrn_dispatch_public($postdata)
184 {
185         $msg = Diaspora::decodeRaw([], $postdata, true);
186         if (!$msg) {
187                 // We have to fail silently to be able to hand it over to the salmon parser
188                 return false;
189         }
190
191         // Fetch the corresponding public contact
192         $contact = Contact::getDetailsByAddr($msg['author'], 0);
193         if (!$contact) {
194                 logger('Contact not found for address ' . $msg['author']);
195                 System::xmlExit(3, 'Contact ' . $msg['author'] . ' not found');
196         }
197
198         $importer = DFRN::getImporter($contact['id']);
199
200         // This should never fail
201         if (empty($importer)) {
202                 logger('Contact not found for address ' . $msg['author']);
203                 System::xmlExit(3, 'Contact ' . $msg['author'] . ' not found');
204         }
205
206         logger('Importing post from ' . $msg['author'] . ' with the public envelope.', LOGGER_DEBUG);
207
208         // Now we should be able to import it
209         $ret = DFRN::import($msg['message'], $importer);
210         System::xmlExit($ret, 'Done');
211 }
212
213 function dfrn_dispatch_private($user, $postdata)
214 {
215         $msg = Diaspora::decodeRaw($user, $postdata);
216         if (!$msg) {
217                 System::xmlExit(4, 'Unable to parse message');
218         }
219
220         // Check if the user has got this contact
221         $cid = Contact::getIdForURL($msg['author'], $user['uid']);
222         if (!$cid) {
223                 // Otherwise there should be a public contact
224                 $cid = Contact::getIdForURL($msg['author']);
225                 if (!$cid) {
226                         logger('Contact not found for address ' . $msg['author']);
227                         System::xmlExit(3, 'Contact ' . $msg['author'] . ' not found');
228                 }
229         }
230
231         $importer = DFRN::getImporter($cid, $user['uid']);
232
233         // This should never fail
234         if (empty($importer)) {
235                 logger('Contact not found for address ' . $msg['author']);
236                 System::xmlExit(3, 'Contact ' . $msg['author'] . ' not found');
237         }
238
239         logger('Importing post from ' . $msg['author'] . ' to ' . $user['nickname'] . ' with the private envelope.', LOGGER_DEBUG);
240
241         // Now we should be able to import it
242         $ret = DFRN::import($msg['message'], $importer);
243         System::xmlExit($ret, 'Done');
244 }
245
246 function dfrn_notify_content(App $a) {
247
248         if (x($_GET,'dfrn_id')) {
249
250                 /*
251                  * initial communication from external contact, $direction is their direction.
252                  * If this is a duplex communication, ours will be the opposite.
253                  */
254
255                 $dfrn_id = notags(trim($_GET['dfrn_id']));
256                 $dfrn_version = (float) $_GET['dfrn_version'];
257                 $rino_remote = ((x($_GET,'rino')) ? intval($_GET['rino']) : 0);
258                 $type = "";
259                 $last_update = "";
260
261                 logger('new notification dfrn_id=' . $dfrn_id);
262
263                 $direction = (-1);
264                 if (strpos($dfrn_id,':') == 1) {
265                         $direction = intval(substr($dfrn_id,0,1));
266                         $dfrn_id = substr($dfrn_id,2);
267                 }
268
269                 $hash = random_string();
270
271                 $status = 0;
272
273                 DBA::delete('challenge', ["`expire` < ?", time()]);
274
275                 $fields = ['challenge' => $hash, 'dfrn-id' => $dfrn_id, 'expire' => time() + 90,
276                         'type' => $type, 'last_update' => $last_update];
277                 DBA::insert('challenge', $fields);
278
279                 logger('challenge=' . $hash, LOGGER_DATA);
280
281                 $user = DBA::selectFirst('user', ['uid'], ['nickname' => $a->argv[1]]);
282                 if (!DBA::isResult($user)) {
283                         logger('User not found for nickname ' . $a->argv[1]);
284                         killme();
285                 }
286
287                 $condition = [];
288                 switch ($direction) {
289                         case (-1):
290                                 $condition = ["`issued-id` = ? OR `dfrn-id` = ?", $dfrn_id, $dfrn_id];
291                                 $my_id = $dfrn_id;
292                                 break;
293                         case 0:
294                                 $condition = ['issued-id' => $dfrn_id, 'duplex' => true];
295                                 $my_id = '1:' . $dfrn_id;
296                                 break;
297                         case 1:
298                                 $condition = ['dfrn-id' => $dfrn_id, 'duplex' => true];
299                                 $my_id = '0:' . $dfrn_id;
300                                 break;
301                         default:
302                                 $status = 1;
303                                 break;
304                 }
305
306                 $contact = DBA::selectFirst('contact', ['id'], $condition);
307                 if (!DBA::isResult($contact)) {
308                         logger('contact not found for dfrn_id ' . $dfrn_id);
309                         System::xmlExit(3, 'Contact not found');
310                 }
311
312                 // $importer in this case contains the contact record for the remote contact joined with the user record of our user.
313                 $importer = DFRN::getImporter($contact['id'], $user['uid']);
314                 if (empty($importer)) {
315                         logger('No importer data found for user ' . $a->argv[1] . ' and contact ' . $dfrn_id);
316                         killme();
317                 }
318
319                 logger("Remote rino version: ".$rino_remote." for ".$importer["url"], LOGGER_DATA);
320
321                 $challenge    = '';
322                 $encrypted_id = '';
323                 $id_str       = $my_id . '.' . mt_rand(1000,9999);
324
325                 $prv_key = trim($importer['cprvkey']);
326                 $pub_key = trim($importer['cpubkey']);
327                 $dplx    = intval($importer['duplex']);
328
329                 if (($dplx && strlen($prv_key)) || (strlen($prv_key) && !strlen($pub_key))) {
330                         openssl_private_encrypt($hash, $challenge, $prv_key);
331                         openssl_private_encrypt($id_str, $encrypted_id, $prv_key);
332                 } elseif (strlen($pub_key)) {
333                         openssl_public_encrypt($hash, $challenge, $pub_key);
334                         openssl_public_encrypt($id_str, $encrypted_id, $pub_key);
335                 } else {
336                         /// @TODO these kind of else-blocks are making the code harder to understand
337                         $status = 1;
338                 }
339
340                 $challenge    = bin2hex($challenge);
341                 $encrypted_id = bin2hex($encrypted_id);
342
343
344                 $rino = Config::get('system', 'rino_encrypt');
345                 $rino = intval($rino);
346
347                 logger("Local rino version: ". $rino, LOGGER_DATA);
348
349                 // if requested rino is lower than enabled local rino, lower local rino version
350                 // if requested rino is higher than enabled local rino, reply with local rino
351                 if ($rino_remote < $rino) {
352                         $rino = $rino_remote;
353                 }
354
355                 if (($importer['rel'] && ($importer['rel'] != Contact::SHARING)) || ($importer['page-flags'] == Contact::PAGE_COMMUNITY)) {
356                         $perm = 'rw';
357                 } else {
358                         $perm = 'r';
359                 }
360
361                 header("Content-type: text/xml");
362
363                 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n"
364                         . '<dfrn_notify>' . "\r\n"
365                         . "\t" . '<status>' . $status . '</status>' . "\r\n"
366                         . "\t" . '<dfrn_version>' . DFRN_PROTOCOL_VERSION . '</dfrn_version>' . "\r\n"
367                         . "\t" . '<rino>' . $rino . '</rino>' . "\r\n"
368                         . "\t" . '<perm>' . $perm . '</perm>' . "\r\n"
369                         . "\t" . '<dfrn_id>' . $encrypted_id . '</dfrn_id>' . "\r\n"
370                         . "\t" . '<challenge>' . $challenge . '</challenge>' . "\r\n"
371                         . '</dfrn_notify>' . "\r\n" ;
372
373                 killme();
374         }
375 }