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