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