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