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