3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
23 use Friendica\Core\Logger;
24 use Friendica\Core\System;
25 use Friendica\Core\Session;
26 use Friendica\Database\DBA;
28 use Friendica\Protocol\DFRN;
29 use Friendica\Protocol\OStatus;
30 use Friendica\Util\Network;
31 use Friendica\Util\Strings;
32 use Friendica\Util\XML;
34 function dfrn_poll_init(App $a)
36 DI::auth()->withSession($a);
38 $dfrn_id = $_GET['dfrn_id'] ?? '';
39 $type = ($_GET['type'] ?? '') ?: 'data';
40 $last_update = $_GET['last_update'] ?? '';
41 $destination_url = $_GET['destination_url'] ?? '';
42 $challenge = $_GET['challenge'] ?? '';
43 $sec = $_GET['sec'] ?? '';
44 $dfrn_version = floatval(($_GET['dfrn_version'] ?? 0.0) ?: 2.0);
45 $quiet = !empty($_GET['quiet']);
47 // Possibly it is an OStatus compatible server that requests a user feed
48 $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
49 if (($a->argc > 1) && ($dfrn_id == '') && !strstr($user_agent, 'Friendica')) {
50 $nickname = $a->argv[1];
51 header("Content-type: application/atom+xml");
52 echo OStatus::feed($nickname, $last_update, 10);
58 if (strpos($dfrn_id, ':') == 1) {
59 $direction = intval(substr($dfrn_id, 0, 1));
60 $dfrn_id = substr($dfrn_id, 2);
65 if (($dfrn_id === '') && empty($_POST['dfrn_id'])) {
66 if (DI::config()->get('system', 'block_public') && !Session::isAuthenticated()) {
67 throw new \Friendica\Network\HTTPException\ForbiddenException();
72 $r = q("SELECT `hidewall`,`nickname` FROM `user` WHERE `user`.`nickname` = '%s' LIMIT 1",
73 DBA::escape($a->argv[1])
76 throw new \Friendica\Network\HTTPException\NotFoundException();
79 $hidewall = ($r[0]['hidewall'] && !local_user());
81 $user = $r[0]['nickname'];
84 Logger::log('dfrn_poll: public feed request from ' . $_SERVER['REMOTE_ADDR'] . ' for ' . $user);
85 header("Content-type: application/atom+xml");
86 echo DFRN::feed('', $user, $last_update, 0, $hidewall);
90 if (($type === 'profile') && (!strlen($sec))) {
94 $sql_extra = sprintf(" AND ( `dfrn-id` = '%s' OR `issued-id` = '%s' ) ", DBA::escape($dfrn_id), DBA::escape($dfrn_id));
98 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
99 $my_id = '1:' . $dfrn_id;
102 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
103 $my_id = '0:' . $dfrn_id;
106 DI::baseUrl()->redirect();
110 $r = q("SELECT `contact`.*, `user`.`username`, `user`.`nickname`
111 FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
112 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
113 AND `user`.`nickname` = '%s' $sql_extra LIMIT 1",
114 DBA::escape($a->argv[1])
117 if (DBA::isResult($r)) {
118 $s = Network::fetchUrl($r[0]['poll'] . '?dfrn_id=' . $my_id . '&type=profile-check');
120 Logger::log("dfrn_poll: old profile returns " . $s, Logger::DATA);
123 $xml = XML::parseString($s);
125 if ((int)$xml->status === 1) {
126 $_SESSION['authenticated'] = 1;
127 $_SESSION['visitor_id'] = $r[0]['id'];
128 $_SESSION['visitor_home'] = $r[0]['url'];
129 $_SESSION['visitor_handle'] = $r[0]['addr'];
130 $_SESSION['visitor_visiting'] = $r[0]['uid'];
131 $_SESSION['my_url'] = $r[0]['url'];
133 Session::setVisitorsContacts();
136 info(DI::l10n()->t('%1$s welcomes %2$s', $r[0]['username'], $r[0]['name']) . EOL);
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)
149 $profile = (count($r) > 0 && isset($r[0]['nickname']) ? $r[0]['nickname'] : '');
150 if (!empty($destination_url)) {
151 System::externalRedirect($destination_url);
153 DI::baseUrl()->redirect('profile/' . $profile);
156 DI::baseUrl()->redirect();
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",
165 if (!DBA::isResult($r)) {
166 System::xmlExit(3, 'No ticket');
170 $orig_id = $r[0]['dfrn_id'];
171 if (strpos($orig_id, ':')) {
172 $orig_id = substr($orig_id, 2);
175 $c = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
178 if (!DBA::isResult($c)) {
179 System::xmlExit(3, 'No profile');
184 $sent_dfrn_id = hex2bin($dfrn_id);
185 $challenge = hex2bin($challenge);
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']);
193 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
194 openssl_public_decrypt($challenge, $decoded_challenge, $contact['pubkey']);
197 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
199 if (strpos($final_dfrn_id, ':') == 1) {
200 $final_dfrn_id = substr($final_dfrn_id, 2);
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');
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>";
215 switch ($direction) {
217 $dfrn_id = '0:' . $dfrn_id;
220 $dfrn_id = '1:' . $dfrn_id;
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)) {
231 return; // NOTREACHED
234 return; // NOTREACHED
239 function dfrn_poll_post(App $a)
241 $dfrn_id = $_POST['dfrn_id'] ?? '';
242 $challenge = $_POST['challenge'] ?? '';
243 $url = $_POST['url'] ?? '';
244 $sec = $_POST['sec'] ?? '';
245 $ptype = $_POST['type'] ?? '';
246 $perm = ($_POST['perm'] ?? '') ?: 'r';
247 $dfrn_version = floatval(($_GET['dfrn_version'] ?? 0.0) ?: 2.0);
249 if ($ptype === 'profile-check') {
250 if (strlen($challenge) && strlen($sec)) {
251 Logger::log('dfrn_poll: POST: profile-check');
253 DBA::delete('profile_check', ["`expire` < ?", time()]);
254 $r = q("SELECT * FROM `profile_check` WHERE `sec` = '%s' ORDER BY `expire` DESC LIMIT 1",
257 if (!DBA::isResult($r)) {
258 System::xmlExit(3, 'No ticket');
262 $orig_id = $r[0]['dfrn_id'];
263 if (strpos($orig_id, ':')) {
264 $orig_id = substr($orig_id, 2);
267 $c = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
270 if (!DBA::isResult($c)) {
271 System::xmlExit(3, 'No profile');
276 $sent_dfrn_id = hex2bin($dfrn_id);
277 $challenge = hex2bin($challenge);
281 if ($contact['duplex'] && strlen($contact['prvkey'])) {
282 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
283 openssl_private_decrypt($challenge, $decoded_challenge, $contact['prvkey']);
285 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
286 openssl_public_decrypt($challenge, $decoded_challenge, $contact['pubkey']);
289 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
291 if (strpos($final_dfrn_id, ':') == 1) {
292 $final_dfrn_id = substr($final_dfrn_id, 2);
295 if ($final_dfrn_id != $orig_id) {
296 Logger::log('profile_check: ' . $final_dfrn_id . ' != ' . $orig_id, Logger::DEBUG);
297 // did not decode properly - cannot trust this site
298 System::xmlExit(3, 'Bad decryption');
301 header("Content-type: text/xml");
302 echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?><dfrn_poll><status>0</status><challenge>$decoded_challenge</challenge><sec>$sec</sec></dfrn_poll>";
309 if (strpos($dfrn_id, ':') == 1) {
310 $direction = intval(substr($dfrn_id, 0, 1));
311 $dfrn_id = substr($dfrn_id, 2);
314 $r = q("SELECT * FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s' LIMIT 1",
315 DBA::escape($dfrn_id),
316 DBA::escape($challenge)
319 if (!DBA::isResult($r)) {
323 $type = $r[0]['type'];
324 $last_update = $r[0]['last_update'];
326 DBA::delete('challenge', ['dfrn-id' => $dfrn_id, 'challenge' => $challenge]);
329 switch ($direction) {
331 $sql_extra = sprintf(" AND `issued-id` = '%s' ", DBA::escape($dfrn_id));
334 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
337 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
340 DI::baseUrl()->redirect();
344 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 $sql_extra LIMIT 1");
345 if (!DBA::isResult($r)) {
350 $owner_uid = $r[0]['uid'];
351 $contact_id = $r[0]['id'];
353 if ($type === 'reputation' && strlen($url)) {
354 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
361 if (DBA::isResult($r)) {
362 $reputation = $r[0]['rating'];
363 $text = $r[0]['reason'];
365 if ($r[0]['id'] == $contact_id) { // inquiring about own reputation not allowed
371 echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
374 <rating>$reputation</rating>
375 <description>$text</description>
381 // Update the writable flag if it changed
382 Logger::log('dfrn_poll: post request feed: ' . print_r($_POST, true), Logger::DATA);
383 if ($dfrn_version >= 2.21) {
384 if ($perm === 'rw') {
390 if ($writable != $contact['writable']) {
391 q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d",
398 header("Content-type: application/atom+xml");
399 $o = DFRN::feed($dfrn_id, $a->argv[1], $last_update, $direction);
405 function dfrn_poll_content(App $a)
407 $dfrn_id = $_GET['dfrn_id'] ?? '';
408 $type = ($_GET['type'] ?? '') ?: 'data';
409 $last_update = $_GET['last_update'] ?? '';
410 $destination_url = $_GET['destination_url'] ?? '';
411 $sec = $_GET['sec'] ?? '';
412 $dfrn_version = floatval(($_GET['dfrn_version'] ?? 0.0) ?: 2.0);
413 $quiet = !empty($_GET['quiet']);
416 if (strpos($dfrn_id, ':') == 1) {
417 $direction = intval(substr($dfrn_id, 0, 1));
418 $dfrn_id = substr($dfrn_id, 2);
421 if ($dfrn_id != '') {
422 // initial communication from external contact
423 $hash = Strings::getRandomHex();
427 DBA::delete('challenge', ["`expire` < ?", time()]);
429 if ($type !== 'profile') {
430 q("INSERT INTO `challenge` ( `challenge`, `dfrn-id`, `expire` , `type`, `last_update` )
431 VALUES( '%s', '%s', '%s', '%s', '%s' ) ",
433 DBA::escape($dfrn_id),
434 intval(time() + 60 ),
436 DBA::escape($last_update)
441 switch ($direction) {
443 if ($type === 'profile') {
444 $sql_extra = sprintf(" AND (`dfrn-id` = '%s' OR `issued-id` = '%s') ", DBA::escape($dfrn_id), DBA::escape($dfrn_id));
446 $sql_extra = sprintf(" AND `issued-id` = '%s' ", DBA::escape($dfrn_id));
452 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
453 $my_id = '1:' . $dfrn_id;
456 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
457 $my_id = '0:' . $dfrn_id;
460 DI::baseUrl()->redirect();
464 $nickname = $a->argv[1];
466 $r = q("SELECT `contact`.*, `user`.`username`, `user`.`nickname`
467 FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
468 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
469 AND `user`.`nickname` = '%s' $sql_extra LIMIT 1",
470 DBA::escape($nickname)
472 if (DBA::isResult($r)) {
475 $id_str = $my_id . '.' . mt_rand(1000, 9999);
477 if (($r[0]['duplex'] && strlen($r[0]['pubkey'])) || !strlen($r[0]['prvkey'])) {
478 openssl_public_encrypt($hash, $challenge, $r[0]['pubkey']);
479 openssl_public_encrypt($id_str, $encrypted_id, $r[0]['pubkey']);
481 openssl_private_encrypt($hash, $challenge, $r[0]['prvkey']);
482 openssl_private_encrypt($id_str, $encrypted_id, $r[0]['prvkey']);
485 $challenge = bin2hex($challenge);
486 $encrypted_id = bin2hex($encrypted_id);
493 if (($type === 'profile') && (strlen($sec))) {
494 // heluecht: I don't know why we don't fail immediately when the user or contact hadn't been found.
495 // Since it doesn't make sense to continue from this point on, we now fail here. This should be safe.
496 if (!DBA::isResult($r)) {
497 throw new \Friendica\Network\HTTPException\NotFoundException();
501 if ($dfrn_version < 2.2) {
502 $s = Network::fetchUrl($r[0]['poll']
503 . '?dfrn_id=' . $encrypted_id
504 . '&type=profile-check'
505 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
506 . '&challenge=' . $challenge
510 $s = Network::post($r[0]['poll'], [
511 'dfrn_id' => $encrypted_id,
512 'type' => 'profile-check',
513 'dfrn_version' => DFRN_PROTOCOL_VERSION,
514 'challenge' => $challenge,
519 Logger::log("dfrn_poll: sec profile: " . $s, Logger::DATA);
521 if (strlen($s) && strstr($s, '<?xml')) {
522 $xml = XML::parseString($s);
524 Logger::log('dfrn_poll: profile: parsed xml: ' . print_r($xml, true), Logger::DATA);
526 Logger::log('dfrn_poll: secure profile: challenge: ' . $xml->challenge . ' expecting ' . $hash);
527 Logger::log('dfrn_poll: secure profile: sec: ' . $xml->sec . ' expecting ' . $sec);
529 if (((int) $xml->status == 0) && ($xml->challenge == $hash) && ($xml->sec == $sec)) {
530 $_SESSION['authenticated'] = 1;
531 $_SESSION['visitor_id'] = $r[0]['id'];
532 $_SESSION['visitor_home'] = $r[0]['url'];
533 $_SESSION['visitor_visiting'] = $r[0]['uid'];
534 $_SESSION['my_url'] = $r[0]['url'];
536 Session::setVisitorsContacts();
539 info(DI::l10n()->t('%1$s welcomes %2$s', $r[0]['username'], $r[0]['name']) . EOL);
542 // Visitors get 1 day session.
543 $session_id = session_id();
544 $expire = time() + 86400;
545 q("UPDATE `session` SET `expire` = '%s' WHERE `sid` = '%s'",
546 DBA::escape($expire),
547 DBA::escape($session_id)
552 $profile = ((DBA::isResult($r) && $r[0]['nickname']) ? $r[0]['nickname'] : $nickname);
554 switch ($destination_url) {
556 DI::baseUrl()->redirect('profile/' . $profile . '/profile');
559 DI::baseUrl()->redirect('photos/' . $profile);
563 DI::baseUrl()->redirect('profile/' . $profile);
566 $appendix = (strstr($destination_url, '?') ? '&redir=1' : '?redir=1');
567 DI::baseUrl()->redirect($destination_url . $appendix);
573 header("Content-type: text/xml");
574 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n"
575 . '<dfrn_poll>' . "\r\n"
576 . "\t" . '<status>' . $status . '</status>' . "\r\n"
577 . "\t" . '<dfrn_version>' . DFRN_PROTOCOL_VERSION . '</dfrn_version>' . "\r\n"
578 . "\t" . '<dfrn_id>' . $encrypted_id . '</dfrn_id>' . "\r\n"
579 . "\t" . '<challenge>' . $challenge . '</challenge>' . "\r\n"
580 . '</dfrn_poll>' . "\r\n";