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