3 * @copyright Copyright (C) 2010-2021, the Friendica project
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\Session;
25 use Friendica\Core\System;
26 use Friendica\Database\DBA;
28 use Friendica\Protocol\DFRN;
29 use Friendica\Protocol\OStatus;
30 use Friendica\Util\Strings;
31 use Friendica\Util\XML;
33 function dfrn_poll_init(App $a)
35 DI::auth()->withSession($a);
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']);
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);
57 if (strpos($dfrn_id, ':') == 1) {
58 $direction = intval(substr($dfrn_id, 0, 1));
59 $dfrn_id = substr($dfrn_id, 2);
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();
71 $r = q("SELECT `hidewall`,`nickname` FROM `user` WHERE `user`.`nickname` = '%s' LIMIT 1",
72 DBA::escape($a->argv[1])
75 throw new \Friendica\Network\HTTPException\NotFoundException();
78 $hidewall = ($r[0]['hidewall'] && !local_user());
80 $user = $r[0]['nickname'];
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);
89 if (($type === 'profile') && (!strlen($sec))) {
93 $sql_extra = sprintf(" AND ( `dfrn-id` = '%s' OR `issued-id` = '%s' ) ", DBA::escape($dfrn_id), DBA::escape($dfrn_id));
97 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
98 $my_id = '1:' . $dfrn_id;
101 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
102 $my_id = '0:' . $dfrn_id;
105 DI::baseUrl()->redirect();
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])
116 if (DBA::isResult($r)) {
117 $s = DI::httpRequest()->fetch($r[0]['poll'] . '?dfrn_id=' . $my_id . '&type=profile-check');
119 Logger::log("dfrn_poll: old profile returns " . $s, Logger::DATA);
122 $xml = XML::parseString($s);
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'];
132 Session::setVisitorsContacts();
135 info(DI::l10n()->t('%1$s welcomes %2$s', $r[0]['username'], $r[0]['name']));
138 // Visitors get 1 day session.
139 $session_id = session_id();
140 $expire = time() + 86400;
141 q("UPDATE `session` SET `expire` = '%s' WHERE `sid` = '%s'",
142 DBA::escape($expire),
143 DBA::escape($session_id)
148 $profile = (count($r) > 0 && isset($r[0]['nickname']) ? $r[0]['nickname'] : '');
149 if (!empty($destination_url)) {
150 System::externalRedirect($destination_url);
152 DI::baseUrl()->redirect('profile/' . $profile);
155 DI::baseUrl()->redirect();
158 if ($type === 'profile-check' && $dfrn_version < 2.2) {
159 if ((strlen($challenge)) && (strlen($sec))) {
160 DBA::delete('profile_check', ["`expire` < ?", time()]);
161 $r = q("SELECT * FROM `profile_check` WHERE `sec` = '%s' ORDER BY `expire` DESC LIMIT 1",
164 if (!DBA::isResult($r)) {
165 System::xmlExit(3, 'No ticket');
169 $orig_id = $r[0]['dfrn_id'];
170 if (strpos($orig_id, ':')) {
171 $orig_id = substr($orig_id, 2);
174 $c = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
177 if (!DBA::isResult($c)) {
178 System::xmlExit(3, 'No profile');
183 $sent_dfrn_id = hex2bin($dfrn_id);
184 $challenge = hex2bin($challenge);
188 if (($contact['duplex']) && strlen($contact['prvkey'])) {
189 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
190 openssl_private_decrypt($challenge, $decoded_challenge, $contact['prvkey']);
192 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
193 openssl_public_decrypt($challenge, $decoded_challenge, $contact['pubkey']);
196 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
198 if (strpos($final_dfrn_id, ':') == 1) {
199 $final_dfrn_id = substr($final_dfrn_id, 2);
202 if ($final_dfrn_id != $orig_id) {
203 Logger::log('profile_check: ' . $final_dfrn_id . ' != ' . $orig_id, Logger::DEBUG);
204 // did not decode properly - cannot trust this site
205 System::xmlExit(3, 'Bad decryption');
208 header("Content-type: text/xml");
209 echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?><dfrn_poll><status>0</status><challenge>$decoded_challenge</challenge><sec>$sec</sec></dfrn_poll>";
214 switch ($direction) {
216 $dfrn_id = '0:' . $dfrn_id;
219 $dfrn_id = '1:' . $dfrn_id;
225 DBA::delete('profile_check', ["`expire` < ?", time()]);
226 $r = q("SELECT * FROM `profile_check` WHERE `dfrn_id` = '%s' ORDER BY `expire` DESC",
227 DBA::escape($dfrn_id));
228 if (DBA::isResult($r)) {
230 return; // NOTREACHED
233 return; // NOTREACHED
238 function dfrn_poll_post(App $a)
240 $dfrn_id = $_POST['dfrn_id'] ?? '';
241 $challenge = $_POST['challenge'] ?? '';
242 $sec = $_POST['sec'] ?? '';
243 $ptype = $_POST['type'] ?? '';
244 $perm = ($_POST['perm'] ?? '') ?: 'r';
245 $dfrn_version = floatval(($_GET['dfrn_version'] ?? 0.0) ?: 2.0);
247 if ($ptype === 'profile-check') {
248 if (strlen($challenge) && strlen($sec)) {
249 Logger::log('dfrn_poll: POST: profile-check');
251 DBA::delete('profile_check', ["`expire` < ?", time()]);
252 $r = q("SELECT * FROM `profile_check` WHERE `sec` = '%s' ORDER BY `expire` DESC LIMIT 1",
255 if (!DBA::isResult($r)) {
256 System::xmlExit(3, 'No ticket');
260 $orig_id = $r[0]['dfrn_id'];
261 if (strpos($orig_id, ':')) {
262 $orig_id = substr($orig_id, 2);
265 $c = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
268 if (!DBA::isResult($c)) {
269 System::xmlExit(3, 'No profile');
274 $sent_dfrn_id = hex2bin($dfrn_id);
275 $challenge = hex2bin($challenge);
279 if ($contact['duplex'] && strlen($contact['prvkey'])) {
280 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
281 openssl_private_decrypt($challenge, $decoded_challenge, $contact['prvkey']);
283 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
284 openssl_public_decrypt($challenge, $decoded_challenge, $contact['pubkey']);
287 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
289 if (strpos($final_dfrn_id, ':') == 1) {
290 $final_dfrn_id = substr($final_dfrn_id, 2);
293 if ($final_dfrn_id != $orig_id) {
294 Logger::log('profile_check: ' . $final_dfrn_id . ' != ' . $orig_id, Logger::DEBUG);
295 // did not decode properly - cannot trust this site
296 System::xmlExit(3, 'Bad decryption');
299 header("Content-type: text/xml");
300 echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?><dfrn_poll><status>0</status><challenge>$decoded_challenge</challenge><sec>$sec</sec></dfrn_poll>";
307 if (strpos($dfrn_id, ':') == 1) {
308 $direction = intval(substr($dfrn_id, 0, 1));
309 $dfrn_id = substr($dfrn_id, 2);
312 $r = q("SELECT * FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s' LIMIT 1",
313 DBA::escape($dfrn_id),
314 DBA::escape($challenge)
317 if (!DBA::isResult($r)) {
321 $last_update = $r[0]['last_update'];
323 DBA::delete('challenge', ['dfrn-id' => $dfrn_id, 'challenge' => $challenge]);
326 switch ($direction) {
328 $sql_extra = sprintf(" AND `issued-id` = '%s' ", DBA::escape($dfrn_id));
331 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
334 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
337 DI::baseUrl()->redirect();
341 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 $sql_extra LIMIT 1");
342 if (!DBA::isResult($r)) {
347 $contact_id = $r[0]['id'];
349 // Update the writable flag if it changed
350 Logger::debug('post request feed', ['post' => $_POST]);
351 if ($dfrn_version >= 2.21) {
352 if ($perm === 'rw') {
358 if ($writable != $contact['writable']) {
359 q("UPDATE `contact` SET `writable` = %d WHERE `id` = %d",
366 header("Content-type: application/atom+xml");
367 $o = DFRN::feed($dfrn_id, $a->argv[1], $last_update, $direction);
372 function dfrn_poll_content(App $a)
374 $dfrn_id = $_GET['dfrn_id'] ?? '';
375 $type = ($_GET['type'] ?? '') ?: 'data';
376 $last_update = $_GET['last_update'] ?? '';
377 $destination_url = $_GET['destination_url'] ?? '';
378 $sec = $_GET['sec'] ?? '';
379 $dfrn_version = floatval(($_GET['dfrn_version'] ?? 0.0) ?: 2.0);
380 $quiet = !empty($_GET['quiet']);
383 if (strpos($dfrn_id, ':') == 1) {
384 $direction = intval(substr($dfrn_id, 0, 1));
385 $dfrn_id = substr($dfrn_id, 2);
388 if ($dfrn_id != '') {
389 // initial communication from external contact
390 $hash = Strings::getRandomHex();
394 DBA::delete('challenge', ["`expire` < ?", time()]);
396 if ($type !== 'profile') {
397 q("INSERT INTO `challenge` ( `challenge`, `dfrn-id`, `expire` , `type`, `last_update` )
398 VALUES( '%s', '%s', '%s', '%s', '%s' ) ",
400 DBA::escape($dfrn_id),
401 intval(time() + 60 ),
403 DBA::escape($last_update)
408 switch ($direction) {
410 if ($type === 'profile') {
411 $sql_extra = sprintf(" AND (`dfrn-id` = '%s' OR `issued-id` = '%s') ", DBA::escape($dfrn_id), DBA::escape($dfrn_id));
413 $sql_extra = sprintf(" AND `issued-id` = '%s' ", DBA::escape($dfrn_id));
419 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
420 $my_id = '1:' . $dfrn_id;
423 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
424 $my_id = '0:' . $dfrn_id;
427 DI::baseUrl()->redirect();
431 $nickname = $a->argv[1];
433 $r = q("SELECT `contact`.*, `user`.`username`, `user`.`nickname`
434 FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
435 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
436 AND `user`.`nickname` = '%s' $sql_extra LIMIT 1",
437 DBA::escape($nickname)
439 if (DBA::isResult($r)) {
442 $id_str = $my_id . '.' . mt_rand(1000, 9999);
444 if (($r[0]['duplex'] && strlen($r[0]['pubkey'])) || !strlen($r[0]['prvkey'])) {
445 openssl_public_encrypt($hash, $challenge, $r[0]['pubkey']);
446 openssl_public_encrypt($id_str, $encrypted_id, $r[0]['pubkey']);
448 openssl_private_encrypt($hash, $challenge, $r[0]['prvkey']);
449 openssl_private_encrypt($id_str, $encrypted_id, $r[0]['prvkey']);
452 $challenge = bin2hex($challenge);
453 $encrypted_id = bin2hex($encrypted_id);
460 if (($type === 'profile') && (strlen($sec))) {
461 // heluecht: I don't know why we don't fail immediately when the user or contact hadn't been found.
462 // Since it doesn't make sense to continue from this point on, we now fail here. This should be safe.
463 if (!DBA::isResult($r)) {
464 throw new \Friendica\Network\HTTPException\NotFoundException();
468 if ($dfrn_version < 2.2) {
469 $s = DI::httpRequest()->fetch($r[0]['poll']
470 . '?dfrn_id=' . $encrypted_id
471 . '&type=profile-check'
472 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
473 . '&challenge=' . $challenge
477 $s = DI::httpRequest()->post($r[0]['poll'], [
478 'dfrn_id' => $encrypted_id,
479 'type' => 'profile-check',
480 'dfrn_version' => DFRN_PROTOCOL_VERSION,
481 'challenge' => $challenge,
486 Logger::log("dfrn_poll: sec profile: " . $s, Logger::DATA);
488 if (strlen($s) && strstr($s, '<?xml')) {
489 $xml = XML::parseString($s);
491 Logger::debug(' profile: parsed', ['xml' => $xml]);
493 Logger::log('dfrn_poll: secure profile: challenge: ' . $xml->challenge . ' expecting ' . $hash);
494 Logger::log('dfrn_poll: secure profile: sec: ' . $xml->sec . ' expecting ' . $sec);
496 if (((int) $xml->status == 0) && ($xml->challenge == $hash) && ($xml->sec == $sec)) {
497 $_SESSION['authenticated'] = 1;
498 $_SESSION['visitor_id'] = $r[0]['id'];
499 $_SESSION['visitor_home'] = $r[0]['url'];
500 $_SESSION['visitor_visiting'] = $r[0]['uid'];
501 $_SESSION['my_url'] = $r[0]['url'];
503 Session::setVisitorsContacts();
506 info(DI::l10n()->t('%1$s welcomes %2$s', $r[0]['username'], $r[0]['name']));
509 // Visitors get 1 day session.
510 $session_id = session_id();
511 $expire = time() + 86400;
512 q("UPDATE `session` SET `expire` = '%s' WHERE `sid` = '%s'",
513 DBA::escape($expire),
514 DBA::escape($session_id)
519 $profile = ((DBA::isResult($r) && $r[0]['nickname']) ? $r[0]['nickname'] : $nickname);
521 switch ($destination_url) {
523 DI::baseUrl()->redirect('profile/' . $profile . '/profile');
526 DI::baseUrl()->redirect('photos/' . $profile);
530 DI::baseUrl()->redirect('profile/' . $profile);
533 $appendix = (strstr($destination_url, '?') ? '&redir=1' : '?redir=1');
534 DI::baseUrl()->redirect($destination_url . $appendix);
540 header("Content-type: text/xml");
541 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n"
542 . '<dfrn_poll>' . "\r\n"
543 . "\t" . '<status>' . $status . '</status>' . "\r\n"
544 . "\t" . '<dfrn_version>' . DFRN_PROTOCOL_VERSION . '</dfrn_version>' . "\r\n"
545 . "\t" . '<dfrn_id>' . $encrypted_id . '</dfrn_id>' . "\r\n"
546 . "\t" . '<challenge>' . $challenge . '</challenge>' . "\r\n"
547 . '</dfrn_poll>' . "\r\n";