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