Merge pull request #6703 from tobiasd/2019.03-CHANGELOG
[friendica.git/.git] / mod / dfrn_poll.php
1 <?php
2
3 /**
4  * @file mod/dfrn_poll.php
5  */
6
7 use Friendica\App;
8 use Friendica\Core\Config;
9 use Friendica\Core\L10n;
10 use Friendica\Core\Logger;
11 use Friendica\Core\System;
12 use Friendica\Database\DBA;
13 use Friendica\Module\Login;
14 use Friendica\Protocol\DFRN;
15 use Friendica\Protocol\OStatus;
16 use Friendica\Util\Network;
17 use Friendica\Util\Strings;
18 use Friendica\Util\XML;
19
20 function dfrn_poll_init(App $a)
21 {
22         Login::sessionAuth();
23
24         $dfrn_id         = defaults($_GET, 'dfrn_id'        , '');
25         $type            = defaults($_GET, 'type'           , 'data');
26         $last_update     = defaults($_GET, 'last_update'    , '');
27         $destination_url = defaults($_GET, 'destination_url', '');
28         $challenge       = defaults($_GET, 'challenge'      , '');
29         $sec             = defaults($_GET, 'sec'            , '');
30         $dfrn_version    = (float) defaults($_GET, 'dfrn_version'   , 2.0);
31         $quiet                   = !empty($_GET['quiet']);
32
33         // Possibly it is an OStatus compatible server that requests a user feed
34         $user_agent = defaults($_SERVER, 'HTTP_USER_AGENT', '');
35         if (($a->argc > 1) && ($dfrn_id == '') && !strstr($user_agent, 'Friendica')) {
36                 $nickname = $a->argv[1];
37                 header("Content-type: application/atom+xml");
38                 echo OStatus::feed($nickname, $last_update, 10);
39                 exit();
40         }
41
42         $direction = -1;
43
44         if (strpos($dfrn_id, ':') == 1) {
45                 $direction = intval(substr($dfrn_id, 0, 1));
46                 $dfrn_id = substr($dfrn_id, 2);
47         }
48
49         $hidewall = false;
50
51         if (($dfrn_id === '') && empty($_POST['dfrn_id'])) {
52                 if (Config::get('system', 'block_public') && !local_user() && !remote_user()) {
53                         System::httpExit(403);
54                 }
55
56                 $user = '';
57                 if ($a->argc > 1) {
58                         $r = q("SELECT `hidewall`,`nickname` FROM `user` WHERE `user`.`nickname` = '%s' LIMIT 1",
59                                 DBA::escape($a->argv[1])
60                         );
61                         if (!$r) {
62                                 System::httpExit(404);
63                         }
64
65                         $hidewall = ($r[0]['hidewall'] && !local_user());
66
67                         $user = $r[0]['nickname'];
68                 }
69
70                 Logger::log('dfrn_poll: public feed request from ' . $_SERVER['REMOTE_ADDR'] . ' for ' . $user);
71                 header("Content-type: application/atom+xml");
72                 echo DFRN::feed('', $user, $last_update, 0, $hidewall);
73                 exit();
74         }
75
76         if (($type === 'profile') && (!strlen($sec))) {
77                 $sql_extra = '';
78                 switch ($direction) {
79                         case -1:
80                                 $sql_extra = sprintf(" AND ( `dfrn-id` = '%s' OR `issued-id` = '%s' ) ", DBA::escape($dfrn_id), DBA::escape($dfrn_id));
81                                 $my_id = $dfrn_id;
82                                 break;
83                         case 0:
84                                 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
85                                 $my_id = '1:' . $dfrn_id;
86                                 break;
87                         case 1:
88                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
89                                 $my_id = '0:' . $dfrn_id;
90                                 break;
91                         default:
92                                 $a->internalRedirect();
93                                 break; // NOTREACHED
94                 }
95
96                 $r = q("SELECT `contact`.*, `user`.`username`, `user`.`nickname`
97                         FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
98                         WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
99                         AND `user`.`nickname` = '%s' $sql_extra LIMIT 1",
100                         DBA::escape($a->argv[1])
101                 );
102
103                 if (DBA::isResult($r)) {
104                         $s = Network::fetchUrl($r[0]['poll'] . '?dfrn_id=' . $my_id . '&type=profile-check');
105
106                         Logger::log("dfrn_poll: old profile returns " . $s, Logger::DATA);
107
108                         if (strlen($s)) {
109                                 $xml = XML::parseString($s);
110
111                                 if ((int)$xml->status === 1) {
112                                         $_SESSION['authenticated'] = 1;
113                                         if (empty($_SESSION['remote'])) {
114                                                 $_SESSION['remote'] = [];
115                                         }
116
117                                         $_SESSION['remote'][] = ['cid' => $r[0]['id'], 'uid' => $r[0]['uid'], 'url' => $r[0]['url']];
118
119                                         $_SESSION['visitor_id'] = $r[0]['id'];
120                                         $_SESSION['visitor_home'] = $r[0]['url'];
121                                         $_SESSION['visitor_handle'] = $r[0]['addr'];
122                                         $_SESSION['visitor_visiting'] = $r[0]['uid'];
123                                         $_SESSION['my_url'] = $r[0]['url'];
124                                         if (!$quiet) {
125                                                 info(L10n::t('%1$s welcomes %2$s', $r[0]['username'], $r[0]['name']) . EOL);
126                                         }
127
128                                         // Visitors get 1 day session.
129                                         $session_id = session_id();
130                                         $expire = time() + 86400;
131                                         q("UPDATE `session` SET `expire` = '%s' WHERE `sid` = '%s'",
132                                                 DBA::escape($expire),
133                                                 DBA::escape($session_id)
134                                         );
135                                 }
136                         }
137
138                         $profile = (count($r) > 0 && isset($r[0]['nickname']) ? $r[0]['nickname'] : '');
139                         if (!empty($destination_url)) {
140                                 System::externalRedirect($destination_url);
141                         } else {
142                                 $a->internalRedirect('profile/' . $profile);
143                         }
144                 }
145                 $a->internalRedirect();
146         }
147
148         if ($type === 'profile-check' && $dfrn_version < 2.2) {
149                 if ((strlen($challenge)) && (strlen($sec))) {
150                         DBA::delete('profile_check', ["`expire` < ?", time()]);
151                         $r = q("SELECT * FROM `profile_check` WHERE `sec` = '%s' ORDER BY `expire` DESC LIMIT 1",
152                                 DBA::escape($sec)
153                         );
154                         if (!DBA::isResult($r)) {
155                                 System::xmlExit(3, 'No ticket');
156                                 // NOTREACHED
157                         }
158
159                         $orig_id = $r[0]['dfrn_id'];
160                         if (strpos($orig_id, ':')) {
161                                 $orig_id = substr($orig_id, 2);
162                         }
163
164                         $c = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
165                                 intval($r[0]['cid'])
166                         );
167                         if (!DBA::isResult($c)) {
168                                 System::xmlExit(3, 'No profile');
169                         }
170
171                         $contact = $c[0];
172
173                         $sent_dfrn_id = hex2bin($dfrn_id);
174                         $challenge = hex2bin($challenge);
175
176                         $final_dfrn_id = '';
177
178                         if (($contact['duplex']) && strlen($contact['prvkey'])) {
179                                 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
180                                 openssl_private_decrypt($challenge, $decoded_challenge, $contact['prvkey']);
181                         } else {
182                                 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
183                                 openssl_public_decrypt($challenge, $decoded_challenge, $contact['pubkey']);
184                         }
185
186                         $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
187
188                         if (strpos($final_dfrn_id, ':') == 1) {
189                                 $final_dfrn_id = substr($final_dfrn_id, 2);
190                         }
191
192                         if ($final_dfrn_id != $orig_id) {
193                                 Logger::log('profile_check: ' . $final_dfrn_id . ' != ' . $orig_id, Logger::DEBUG);
194                                 // did not decode properly - cannot trust this site
195                                 System::xmlExit(3, 'Bad decryption');
196                         }
197
198                         header("Content-type: text/xml");
199                         echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?><dfrn_poll><status>0</status><challenge>$decoded_challenge</challenge><sec>$sec</sec></dfrn_poll>";
200                         exit();
201                         // NOTREACHED
202                 } else {
203                         // old protocol
204                         switch ($direction) {
205                                 case 1:
206                                         $dfrn_id = '0:' . $dfrn_id;
207                                         break;
208                                 case 0:
209                                         $dfrn_id = '1:' . $dfrn_id;
210                                         break;
211                                 default:
212                                         break;
213                         }
214
215                         DBA::delete('profile_check', ["`expire` < ?", time()]);
216                         $r = q("SELECT * FROM `profile_check` WHERE `dfrn_id` = '%s' ORDER BY `expire` DESC",
217                                 DBA::escape($dfrn_id));
218                         if (DBA::isResult($r)) {
219                                 System::xmlExit(1);
220                                 return; // NOTREACHED
221                         }
222                         System::xmlExit(0);
223                         return; // NOTREACHED
224                 }
225         }
226 }
227
228 function dfrn_poll_post(App $a)
229 {
230         $dfrn_id      = defaults($_POST, 'dfrn_id'  , '');
231         $challenge    = defaults($_POST, 'challenge', '');
232         $url          = defaults($_POST, 'url'      , '');
233         $sec          = defaults($_POST, 'sec'      , '');
234         $ptype        = defaults($_POST, 'type'     , '');
235         $perm         = defaults($_POST, 'perm'     , 'r');
236         $dfrn_version = !empty($_POST['dfrn_version']) ? (float) $_POST['dfrn_version'] : 2.0;
237
238         if ($ptype === 'profile-check') {
239                 if (strlen($challenge) && strlen($sec)) {
240                         Logger::log('dfrn_poll: POST: profile-check');
241
242                         DBA::delete('profile_check', ["`expire` < ?", time()]);
243                         $r = q("SELECT * FROM `profile_check` WHERE `sec` = '%s' ORDER BY `expire` DESC LIMIT 1",
244                                 DBA::escape($sec)
245                         );
246                         if (!DBA::isResult($r)) {
247                                 System::xmlExit(3, 'No ticket');
248                                 // NOTREACHED
249                         }
250
251                         $orig_id = $r[0]['dfrn_id'];
252                         if (strpos($orig_id, ':')) {
253                                 $orig_id = substr($orig_id, 2);
254                         }
255
256                         $c = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
257                                 intval($r[0]['cid'])
258                         );
259                         if (!DBA::isResult($c)) {
260                                 System::xmlExit(3, 'No profile');
261                         }
262
263                         $contact = $c[0];
264
265                         $sent_dfrn_id = hex2bin($dfrn_id);
266                         $challenge = hex2bin($challenge);
267
268                         $final_dfrn_id = '';
269
270                         if ($contact['duplex'] && strlen($contact['prvkey'])) {
271                                 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
272                                 openssl_private_decrypt($challenge, $decoded_challenge, $contact['prvkey']);
273                         } else {
274                                 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
275                                 openssl_public_decrypt($challenge, $decoded_challenge, $contact['pubkey']);
276                         }
277
278                         $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
279
280                         if (strpos($final_dfrn_id, ':') == 1) {
281                                 $final_dfrn_id = substr($final_dfrn_id, 2);
282                         }
283
284                         if ($final_dfrn_id != $orig_id) {
285                                 Logger::log('profile_check: ' . $final_dfrn_id . ' != ' . $orig_id, Logger::DEBUG);
286                                 // did not decode properly - cannot trust this site
287                                 System::xmlExit(3, 'Bad decryption');
288                         }
289
290                         header("Content-type: text/xml");
291                         echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?><dfrn_poll><status>0</status><challenge>$decoded_challenge</challenge><sec>$sec</sec></dfrn_poll>";
292                         exit();
293                         // NOTREACHED
294                 }
295         }
296
297         $direction = -1;
298         if (strpos($dfrn_id, ':') == 1) {
299                 $direction = intval(substr($dfrn_id, 0, 1));
300                 $dfrn_id = substr($dfrn_id, 2);
301         }
302
303         $r = q("SELECT * FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s' LIMIT 1",
304                 DBA::escape($dfrn_id),
305                 DBA::escape($challenge)
306         );
307
308         if (!DBA::isResult($r)) {
309                 exit();
310         }
311
312         $type = $r[0]['type'];
313         $last_update = $r[0]['last_update'];
314
315         DBA::delete('challenge', ['dfrn-id' => $dfrn_id, 'challenge' => $challenge]);
316
317         $sql_extra = '';
318         switch ($direction) {
319                 case -1:
320                         $sql_extra = sprintf(" AND `issued-id` = '%s' ", DBA::escape($dfrn_id));
321                         break;
322                 case 0:
323                         $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
324                         break;
325                 case 1:
326                         $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
327                         break;
328                 default:
329                         $a->internalRedirect();
330                         break; // NOTREACHED
331         }
332
333         $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 $sql_extra LIMIT 1");
334         if (!DBA::isResult($r)) {
335                 exit();
336         }
337
338         $contact = $r[0];
339         $owner_uid = $r[0]['uid'];
340         $contact_id = $r[0]['id'];
341
342         if ($type === 'reputation' && strlen($url)) {
343                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
344                         DBA::escape($url),
345                         intval($owner_uid)
346                 );
347                 $reputation = 0;
348                 $text = '';
349
350                 if (DBA::isResult($r)) {
351                         $reputation = $r[0]['rating'];
352                         $text = $r[0]['reason'];
353
354                         if ($r[0]['id'] == $contact_id) { // inquiring about own reputation not allowed
355                                 $reputation = 0;
356                                 $text = '';
357                         }
358                 }
359
360                 echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
361                 <reputation>
362                         <url>$url</url>
363                         <rating>$reputation</rating>
364                         <description>$text</description>
365                 </reputation>
366                 ";
367                 exit();
368                 // NOTREACHED
369         } else {
370                 // Update the writable flag if it changed
371                 Logger::log('dfrn_poll: post request feed: ' . print_r($_POST, true), Logger::DATA);
372                 if ($dfrn_version >= 2.21) {
373                         if ($perm === 'rw') {
374                                 $writable = 1;
375                         } else {
376                                 $writable = 0;
377                         }
378
379                         if ($writable != $contact['writable']) {
380                                 q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d",
381                                         intval($writable),
382                                         intval($contact_id)
383                                 );
384                         }
385                 }
386
387                 header("Content-type: application/atom+xml");
388                 $o = DFRN::feed($dfrn_id, $a->argv[1], $last_update, $direction);
389                 echo $o;
390                 exit();
391         }
392 }
393
394 function dfrn_poll_content(App $a)
395 {
396         $dfrn_id         = defaults($_GET, 'dfrn_id'        , '');
397         $type            = defaults($_GET, 'type'           , 'data');
398         $last_update     = defaults($_GET, 'last_update'    , '');
399         $destination_url = defaults($_GET, 'destination_url', '');
400         $sec             = defaults($_GET, 'sec'            , '');
401         $dfrn_version    = !empty($_GET['dfrn_version'])    ? (float) $_GET['dfrn_version'] : 2.0;
402         $quiet           = !empty($_GET['quiet']);
403
404         $direction = -1;
405         if (strpos($dfrn_id, ':') == 1) {
406                 $direction = intval(substr($dfrn_id, 0, 1));
407                 $dfrn_id = substr($dfrn_id, 2);
408         }
409
410         if ($dfrn_id != '') {
411                 // initial communication from external contact
412                 $hash = Strings::getRandomHex();
413
414                 $status = 0;
415
416                 DBA::delete('challenge', ["`expire` < ?", time()]);
417
418                 if ($type !== 'profile') {
419                         q("INSERT INTO `challenge` ( `challenge`, `dfrn-id`, `expire` , `type`, `last_update` )
420                                 VALUES( '%s', '%s', '%s', '%s', '%s' ) ",
421                                 DBA::escape($hash),
422                                 DBA::escape($dfrn_id),
423                                 intval(time() + 60 ),
424                                 DBA::escape($type),
425                                 DBA::escape($last_update)
426                         );
427                 }
428
429                 $sql_extra = '';
430                 switch ($direction) {
431                         case -1:
432                                 if ($type === 'profile') {
433                                         $sql_extra = sprintf(" AND (`dfrn-id` = '%s' OR `issued-id` = '%s') ", DBA::escape($dfrn_id), DBA::escape($dfrn_id));
434                                 } else {
435                                         $sql_extra = sprintf(" AND `issued-id` = '%s' ", DBA::escape($dfrn_id));
436                                 }
437
438                                 $my_id = $dfrn_id;
439                                 break;
440                         case 0:
441                                 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
442                                 $my_id = '1:' . $dfrn_id;
443                                 break;
444                         case 1:
445                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
446                                 $my_id = '0:' . $dfrn_id;
447                                 break;
448                         default:
449                                 $a->internalRedirect();
450                                 break; // NOTREACHED
451                 }
452
453                 $nickname = $a->argv[1];
454
455                 $r = q("SELECT `contact`.*, `user`.`username`, `user`.`nickname`
456                         FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
457                         WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
458                         AND `user`.`nickname` = '%s' $sql_extra LIMIT 1",
459                         DBA::escape($nickname)
460                 );
461                 if (DBA::isResult($r)) {
462                         $challenge = '';
463                         $encrypted_id = '';
464                         $id_str = $my_id . '.' . mt_rand(1000, 9999);
465
466                         if (($r[0]['duplex'] && strlen($r[0]['pubkey'])) || !strlen($r[0]['prvkey'])) {
467                                 openssl_public_encrypt($hash, $challenge, $r[0]['pubkey']);
468                                 openssl_public_encrypt($id_str, $encrypted_id, $r[0]['pubkey']);
469                         } else {
470                                 openssl_private_encrypt($hash, $challenge, $r[0]['prvkey']);
471                                 openssl_private_encrypt($id_str, $encrypted_id, $r[0]['prvkey']);
472                         }
473
474                         $challenge = bin2hex($challenge);
475                         $encrypted_id = bin2hex($encrypted_id);
476                 } else {
477                         $status = 1;
478                         $challenge = '';
479                         $encrypted_id = '';
480                 }
481
482                 if (($type === 'profile') && (strlen($sec))) {
483                         // heluecht: I don't know why we don't fail immediately when the user or contact hadn't been found.
484                         // Since it doesn't make sense to continue from this point on, we now fail here. This should be safe.
485                         if (!DBA::isResult($r)) {
486                                 System::httpExit(404, ["title" => L10n::t('Page not found.')]);
487                         }
488
489                         // URL reply
490                         if ($dfrn_version < 2.2) {
491                                 $s = Network::fetchUrl($r[0]['poll']
492                                         . '?dfrn_id=' . $encrypted_id
493                                         . '&type=profile-check'
494                                         . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
495                                         . '&challenge=' . $challenge
496                                         . '&sec=' . $sec
497                                 );
498                         } else {
499                                 $s = Network::post($r[0]['poll'], [
500                                         'dfrn_id' => $encrypted_id,
501                                         'type' => 'profile-check',
502                                         'dfrn_version' => DFRN_PROTOCOL_VERSION,
503                                         'challenge' => $challenge,
504                                         'sec' => $sec
505                                 ])->getBody();
506                         }
507
508                         Logger::log("dfrn_poll: sec profile: " . $s, Logger::DATA);
509
510                         if (strlen($s) && strstr($s, '<?xml')) {
511                                 $xml = XML::parseString($s);
512
513                                 Logger::log('dfrn_poll: profile: parsed xml: ' . print_r($xml, true), Logger::DATA);
514
515                                 Logger::log('dfrn_poll: secure profile: challenge: ' . $xml->challenge . ' expecting ' . $hash);
516                                 Logger::log('dfrn_poll: secure profile: sec: ' . $xml->sec . ' expecting ' . $sec);
517
518                                 if (((int) $xml->status == 0) && ($xml->challenge == $hash) && ($xml->sec == $sec)) {
519                                         $_SESSION['authenticated'] = 1;
520                                         if (empty($_SESSION['remote'])) {
521                                                 $_SESSION['remote'] = [];
522                                         }
523
524                                         $_SESSION['remote'][] = ['cid' => $r[0]['id'], 'uid' => $r[0]['uid'], 'url' => $r[0]['url']];
525                                         $_SESSION['visitor_id'] = $r[0]['id'];
526                                         $_SESSION['visitor_home'] = $r[0]['url'];
527                                         $_SESSION['visitor_visiting'] = $r[0]['uid'];
528                                         $_SESSION['my_url'] = $r[0]['url'];
529                                         if (!$quiet) {
530                                                 info(L10n::t('%1$s welcomes %2$s', $r[0]['username'], $r[0]['name']) . EOL);
531                                         }
532
533                                         // Visitors get 1 day session.
534                                         $session_id = session_id();
535                                         $expire = time() + 86400;
536                                         q("UPDATE `session` SET `expire` = '%s' WHERE `sid` = '%s'",
537                                                 DBA::escape($expire),
538                                                 DBA::escape($session_id)
539                                         );
540                                 }
541                         }
542
543                         $profile = ((DBA::isResult($r) && $r[0]['nickname']) ? $r[0]['nickname'] : $nickname);
544
545                         switch ($destination_url) {
546                                 case 'profile':
547                                         $a->internalRedirect('profile/' . $profile . '?f=&tab=profile');
548                                         break;
549                                 case 'photos':
550                                         $a->internalRedirect('photos/' . $profile);
551                                         break;
552                                 case 'status':
553                                 case '':
554                                         $a->internalRedirect('profile/' . $profile);
555                                         break;
556                                 default:
557                                         $appendix = (strstr($destination_url, '?') ? '&f=&redir=1' : '?f=&redir=1');
558                                         $a->redirect($destination_url . $appendix);
559                                         break;
560                         }
561                         // NOTREACHED
562                 } else {
563                         // XML reply
564                         header("Content-type: text/xml");
565                         echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n"
566                                 . '<dfrn_poll>' . "\r\n"
567                                 . "\t" . '<status>' . $status . '</status>' . "\r\n"
568                                 . "\t" . '<dfrn_version>' . DFRN_PROTOCOL_VERSION . '</dfrn_version>' . "\r\n"
569                                 . "\t" . '<dfrn_id>' . $encrypted_id . '</dfrn_id>' . "\r\n"
570                                 . "\t" . '<challenge>' . $challenge . '</challenge>' . "\r\n"
571                                 . '</dfrn_poll>' . "\r\n";
572                         exit();
573                         // NOTREACHED
574                 }
575         }
576 }