Browse Source

Legacy DFRN transport layer is removed

pull/10503/head
Michael 2 months ago
parent
commit
3a5523820c
  1. 46
      database.sql
  2. 9
      doc/API-Friendica.md
  3. 1
      doc/database.md
  4. 27
      doc/database/db_challenge.md
  5. 14
      doc/database/db_contact.md
  6. 64
      include/api.php
  7. 563
      mod/dfrn_confirm.php
  8. 276
      mod/dfrn_notify.php
  9. 527
      mod/dfrn_poll.php
  10. 653
      mod/dfrn_request.php
  11. 22
      mod/follow.php
  12. 29
      mod/redir.php
  13. 3
      mod/unfollow.php
  14. 2
      src/Database/DBStructure.php
  15. 38
      src/Model/Contact.php
  16. 2
      src/Model/Conversation.php
  17. 8
      src/Module/Notifications/Introductions.php
  18. 2
      src/Object/Notification/Introduction.php
  19. 441
      src/Protocol/DFRN.php
  20. 10
      src/Worker/Delivery.php
  21. 1
      src/Worker/OptimizeTables.php
  22. 31
      static/dbstructure.config.php
  23. 16
      static/dbview.config.php
  24. 485
      view/lang/C/messages.po
  25. 22
      view/templates/dfrn_req_confirm.tpl
  26. 38
      view/templates/dfrn_request.tpl
  27. 40
      view/theme/frio/templates/dfrn_request.tpl

46
database.sql

@ -1,6 +1,6 @@
-- ------------------------------------------
-- Friendica 2021.09-dev (Siberian Iris)
-- DB_UPDATE_VERSION 1429
-- DB_UPDATE_VERSION 1430
-- ------------------------------------------
@ -117,7 +117,7 @@ CREATE TABLE IF NOT EXISTS `contact` (
`self` boolean NOT NULL DEFAULT '0' COMMENT '1 if the contact is the user him/her self',
`remote_self` boolean NOT NULL DEFAULT '0' COMMENT '',
`rel` tinyint unsigned NOT NULL DEFAULT 0 COMMENT 'The kind of the relation between the user and the contact',
`duplex` boolean NOT NULL DEFAULT '0' COMMENT '',
`duplex` boolean NOT NULL DEFAULT '0' COMMENT 'Deprecated',
`network` char(4) NOT NULL DEFAULT '' COMMENT 'Network of the contact',
`protocol` char(4) NOT NULL DEFAULT '' COMMENT 'Protocol of the contact',
`name` varchar(255) NOT NULL DEFAULT '' COMMENT 'Name that this contact is known by',
@ -133,9 +133,9 @@ CREATE TABLE IF NOT EXISTS `contact` (
`thumb` varchar(255) DEFAULT '' COMMENT 'Link to the profile photo (thumb size)',
`micro` varchar(255) DEFAULT '' COMMENT 'Link to the profile photo (micro size)',
`header` varchar(255) COMMENT 'Header picture',
`site-pubkey` text COMMENT '',
`issued-id` varchar(255) NOT NULL DEFAULT '' COMMENT '',
`dfrn-id` varchar(255) NOT NULL DEFAULT '' COMMENT '',
`site-pubkey` text COMMENT 'Deprecated',
`issued-id` varchar(255) NOT NULL DEFAULT '' COMMENT 'Deprecated',
`dfrn-id` varchar(255) NOT NULL DEFAULT '' COMMENT 'Deprecated',
`url` varchar(255) NOT NULL DEFAULT '' COMMENT '',
`nurl` varchar(255) NOT NULL DEFAULT '' COMMENT '',
`uri-id` int unsigned COMMENT 'Id of the item-uri table entry that contains the contact url',
@ -150,8 +150,8 @@ CREATE TABLE IF NOT EXISTS `contact` (
`confirm` varchar(255) COMMENT '',
`subscribe` varchar(255) COMMENT '',
`poco` varchar(255) COMMENT '',
`aes_allow` boolean NOT NULL DEFAULT '0' COMMENT '',
`ret-aes` boolean NOT NULL DEFAULT '0' COMMENT '',
`aes_allow` boolean NOT NULL DEFAULT '0' COMMENT 'Deprecated',
`ret-aes` boolean NOT NULL DEFAULT '0' COMMENT 'Deprecated',
`usehub` boolean NOT NULL DEFAULT '0' COMMENT '',
`subhub` boolean NOT NULL DEFAULT '0' COMMENT '',
`hub-verify` varchar(255) NOT NULL DEFAULT '' COMMENT '',
@ -205,8 +205,6 @@ CREATE TABLE IF NOT EXISTS `contact` (
INDEX `nurl_uid` (`nurl`(128),`uid`),
INDEX `nick_uid` (`nick`(128),`uid`),
INDEX `attag_uid` (`attag`(96),`uid`),
INDEX `dfrn-id` (`dfrn-id`(64)),
INDEX `issued-id` (`issued-id`(64)),
INDEX `network_uid_lastupdate` (`network`,`uid`,`last-update`),
INDEX `uid_network_self_lastupdate` (`uid`,`network`,`self`,`last-update`),
INDEX `uid_lastitem` (`uid`,`last-item`),
@ -462,20 +460,6 @@ CREATE TABLE IF NOT EXISTS `cache` (
INDEX `k_expires` (`k`,`expires`)
) DEFAULT COLLATE utf8mb4_general_ci COMMENT='Stores temporary data';
--
-- TABLE challenge
--
CREATE TABLE IF NOT EXISTS `challenge` (
`id` int unsigned NOT NULL auto_increment COMMENT 'sequential ID',
`challenge` varchar(255) NOT NULL DEFAULT '' COMMENT '',
`dfrn-id` varchar(255) NOT NULL DEFAULT '' COMMENT '',
`expire` int unsigned NOT NULL DEFAULT 0 COMMENT '',
`type` varchar(255) NOT NULL DEFAULT '' COMMENT '',
`last_update` varchar(255) NOT NULL DEFAULT '' COMMENT '',
PRIMARY KEY(`id`),
INDEX `expire` (`expire`)
) DEFAULT COLLATE utf8mb4_general_ci COMMENT='';
--
-- TABLE config
--
@ -1684,7 +1668,6 @@ CREATE VIEW `post-user-view` AS SELECT
`contact`.`uri-date` AS `uri-date`,
`contact`.`avatar-date` AS `avatar-date`,
`contact`.`thumb` AS `thumb`,
`contact`.`dfrn-id` AS `dfrn-id`,
`post-user`.`author-id` AS `author-id`,
`author`.`url` AS `author-link`,
`author`.`addr` AS `author-addr`,
@ -1846,7 +1829,6 @@ CREATE VIEW `post-thread-user-view` AS SELECT
`contact`.`uri-date` AS `uri-date`,
`contact`.`avatar-date` AS `avatar-date`,
`contact`.`thumb` AS `thumb`,
`contact`.`dfrn-id` AS `dfrn-id`,
`post-thread-user`.`author-id` AS `author-id`,
`author`.`url` AS `author-link`,
`author`.`addr` AS `author-addr`,
@ -1993,7 +1975,6 @@ CREATE VIEW `post-view` AS SELECT
`author`.`uri-date` AS `uri-date`,
`author`.`avatar-date` AS `avatar-date`,
`author`.`thumb` AS `thumb`,
`author`.`dfrn-id` AS `dfrn-id`,
`post`.`author-id` AS `author-id`,
`author`.`url` AS `author-link`,
`author`.`addr` AS `author-addr`,
@ -2115,7 +2096,6 @@ CREATE VIEW `post-thread-view` AS SELECT
`author`.`uri-date` AS `uri-date`,
`author`.`avatar-date` AS `avatar-date`,
`author`.`thumb` AS `thumb`,
`author`.`dfrn-id` AS `dfrn-id`,
`post-thread`.`author-id` AS `author-id`,
`author`.`url` AS `author-link`,
`author`.`addr` AS `author-addr`,
@ -2270,7 +2250,6 @@ CREATE VIEW `owner-view` AS SELECT
`contact`.`self` AS `self`,
`contact`.`remote_self` AS `remote_self`,
`contact`.`rel` AS `rel`,
`contact`.`duplex` AS `duplex`,
`contact`.`network` AS `network`,
`contact`.`protocol` AS `protocol`,
`contact`.`name` AS `name`,
@ -2286,9 +2265,6 @@ CREATE VIEW `owner-view` AS SELECT
`contact`.`thumb` AS `thumb`,
`contact`.`micro` AS `micro`,
`contact`.`header` AS `header`,
`contact`.`site-pubkey` AS `site-pubkey`,
`contact`.`issued-id` AS `issued-id`,
`contact`.`dfrn-id` AS `dfrn-id`,
`contact`.`url` AS `url`,
`contact`.`nurl` AS `nurl`,
`contact`.`uri-id` AS `uri-id`,
@ -2302,8 +2278,6 @@ CREATE VIEW `owner-view` AS SELECT
`contact`.`poll` AS `poll`,
`contact`.`confirm` AS `confirm`,
`contact`.`poco` AS `poco`,
`contact`.`aes_allow` AS `aes_allow`,
`contact`.`ret-aes` AS `ret-aes`,
`contact`.`usehub` AS `usehub`,
`contact`.`subhub` AS `subhub`,
`contact`.`hub-verify` AS `hub-verify`,
@ -2547,12 +2521,6 @@ CREATE VIEW `account-user-view` AS SELECT
`ucontact`.`subhub` AS `subhub`,
`ucontact`.`hub-verify` AS `hub-verify`,
`ucontact`.`reason` AS `reason`,
`ucontact`.`duplex` AS `dfrn-duplex`,
`ucontact`.`ret-aes` AS `dfrn-ret-aes`,
`ucontact`.`site-pubkey` AS `dfrn-site-pubkey`,
`ucontact`.`issued-id` AS `dfrn-issued-id`,
`ucontact`.`dfrn-id` AS `dfrn-id`,
`ucontact`.`aes_allow` AS `dfrn-aes_allow`,
`contact`.`request` AS `dfrn-request`,
`contact`.`notify` AS `dfrn-notify`,
`contact`.`poll` AS `dfrn-poll`,

9
doc/API-Friendica.md

@ -689,15 +689,6 @@ General description of profile data in API returns:
---
### GET api/friendica/remoteauth
Similar as /redir, redirects to `url` after DFRN authentication.
#### Parameters
- `c_url`: url of remote contact to auth to
- `url`: string, url to redirect after auth
## Deprecated endpoints
- POST api/statuses/mediap

1
doc/database.md

@ -15,7 +15,6 @@ Database Tables
| [attach](help/database/db_attach) | file attachments |
| [auth_codes](help/database/db_auth_codes) | OAuth usage |
| [cache](help/database/db_cache) | Stores temporary data |
| [challenge](help/database/db_challenge) | |
| [clients](help/database/db_clients) | OAuth usage |
| [config](help/database/db_config) | main configuration storage |
| [contact](help/database/db_contact) | contact table |

27
doc/database/db_challenge.md

@ -1,27 +0,0 @@
Table challenge
===========
Fields
------
| Field | Description | Type | Null | Key | Default | Extra |
| ----------- | ------------- | ------------ | ---- | --- | ------- | -------------- |
| id | sequential ID | int unsigned | NO | PRI | NULL | auto_increment |
| challenge | | varchar(255) | NO | | | |
| dfrn-id | | varchar(255) | NO | | | |
| expire | | int unsigned | NO | | 0 | |
| type | | varchar(255) | NO | | | |
| last_update | | varchar(255) | NO | | | |
Indexes
------------
| Name | Fields |
| ------- | ------ |
| PRIMARY | id |
| expire | expire |
Return to [database documentation](help/database)

14
doc/database/db_contact.md

@ -15,7 +15,7 @@ Fields
| self | 1 if the contact is the user him/her self | boolean | NO | | 0 | |
| remote_self | | boolean | NO | | 0 | |
| rel | The kind of the relation between the user and the contact | tinyint unsigned | NO | | 0 | |
| duplex | | boolean | NO | | 0 | |
| duplex | Deprecated | boolean | NO | | 0 | |
| network | Network of the contact | char(4) | NO | | | |
| protocol | Protocol of the contact | char(4) | NO | | | |
| name | Name that this contact is known by | varchar(255) | NO | | | |
@ -31,9 +31,9 @@ Fields
| thumb | Link to the profile photo (thumb size) | varchar(255) | YES | | | |
| micro | Link to the profile photo (micro size) | varchar(255) | YES | | | |
| header | Header picture | varchar(255) | YES | | NULL | |
| site-pubkey | | text | YES | | NULL | |
| issued-id | | varchar(255) | NO | | | |
| dfrn-id | | varchar(255) | NO | | | |
| site-pubkey | Deprecated | text | YES | | NULL | |
| issued-id | Deprecated | varchar(255) | NO | | | |
| dfrn-id | Deprecated | varchar(255) | NO | | | |
| url | | varchar(255) | NO | | | |
| nurl | | varchar(255) | NO | | | |
| uri-id | Id of the item-uri table entry that contains the contact url | int unsigned | YES | | NULL | |
@ -48,8 +48,8 @@ Fields
| confirm | | varchar(255) | YES | | NULL | |
| subscribe | | varchar(255) | YES | | NULL | |
| poco | | varchar(255) | YES | | NULL | |
| aes_allow | | boolean | NO | | 0 | |
| ret-aes | | boolean | NO | | 0 | |
| aes_allow | Deprecated | boolean | NO | | 0 | |
| ret-aes | Deprecated | boolean | NO | | 0 | |
| usehub | | boolean | NO | | 0 | |
| subhub | | boolean | NO | | 0 | |
| hub-verify | | varchar(255) | NO | | | |
@ -109,8 +109,6 @@ Indexes
| nurl_uid | nurl(128), uid |
| nick_uid | nick(128), uid |
| attag_uid | attag(96), uid |
| dfrn-id | dfrn-id(64) |
| issued-id | issued-id(64) |
| network_uid_lastupdate | network, uid, last-update |
| uid_network_self_lastupdate | uid, network, self, last-update |
| uid_lastitem | uid, last-item |

64
include/api.php

@ -4950,70 +4950,6 @@ function prepare_photo_data($type, $scale, $photo_id)
return $data;
}
/**
* Similar as /mod/redir.php
* redirect to 'url' after dfrn auth
*
* Why this when there is mod/redir.php already?
* This use api_user() and api_login()
*
* params
* c_url: url of remote contact to auth to
* url: string, url to redirect after auth
*/
function api_friendica_remoteauth()
{
$url = $_GET['url'] ?? '';
$c_url = $_GET['c_url'] ?? '';
if ($url === '' || $c_url === '') {
throw new BadRequestException("Wrong parameters.");
}
$c_url = Strings::normaliseLink($c_url);
// traditional DFRN
$contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
if (!DBA::isResult($contact)) {
throw new BadRequestException("Unknown contact");
}
$cid = $contact['id'];
$dfrn_id = $contact['issued-id'] ?: $contact['dfrn-id'];
if (($contact['network'] !== Protocol::DFRN) || empty($dfrn_id)) {
System::externalRedirect($url ?: $c_url);
}
if ($contact['duplex'] && $contact['issued-id']) {
$orig_id = $contact['issued-id'];
$dfrn_id = '1:' . $orig_id;
}
if ($contact['duplex'] && $contact['dfrn-id']) {
$orig_id = $contact['dfrn-id'];
$dfrn_id = '0:' . $orig_id;
}
$sec = Strings::getRandomHex();
$fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
'sec' => $sec, 'expire' => time() + 45];
DBA::insert('profile_check', $fields);
Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
$dest = ($url ? '&destination_url=' . $url : '');
System::externalRedirect(
$contact['poll'] . '?dfrn_id=' . $dfrn_id
. '&dfrn_version=' . DFRN_PROTOCOL_VERSION
. '&type=profile&sec=' . $sec . $dest
);
}
api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
/**
* Return an item with announcer data if it had been announced
*

563
mod/dfrn_confirm.php

@ -1,563 +0,0 @@
<?php
/**
* @copyright Copyright (C) 2010-2021, the Friendica project
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* Friendship acceptance for DFRN contacts
*
* There are two possible entry points and three scenarios.
*
* 1. A form was submitted by our user approving a friendship that originated elsewhere.
* This may also be called from dfrn_request to automatically approve a friendship.
*
* 2. We may be the target or other side of the conversation to scenario 1, and will
* interact with that process on our own user's behalf.
*
* @see PDF with dfrn specs: https://github.com/friendica/friendica/blob/stable/spec/dfrn2.pdf
* You also find a graphic which describes the confirmation process at
* https://github.com/friendica/friendica/blob/stable/spec/dfrn2_contact_confirmation.png
*/
use Friendica\App;
use Friendica\Core\Logger;
use Friendica\Core\Protocol;
use Friendica\Core\System;
use Friendica\Database\DBA;
use Friendica\DI;
use Friendica\Model\Contact;
use Friendica\Model\Group;
use Friendica\Model\Notification;
use Friendica\Model\User;
use Friendica\Protocol\Activity;
use Friendica\Util\Crypto;
use Friendica\Util\DateTimeFormat;
use Friendica\Util\Strings;
use Friendica\Util\XML;
function dfrn_confirm_post(App $a, $handsfree = null)
{
$node = null;
if (is_array($handsfree)) {
/*
* We were called directly from dfrn_request due to automatic friend acceptance.
* Any $_POST parameters we may require are supplied in the $handsfree array.
*
*/
$node = $handsfree['node'];
$a->interactive = false; // notice() becomes a no-op since nobody is there to see it
} elseif ($a->argc > 1) {
$node = $a->argv[1];
}
/*
* Main entry point. Scenario 1. Our user received a friend request notification (perhaps
* from another site) and clicked 'Approve'.
* $POST['source_url'] is not set. If it is, it indicates Scenario 2.
*
* We may also have been called directly from dfrn_request ($handsfree != null) due to
* this being a page type which supports automatic friend acceptance. That is also Scenario 1
* since we are operating on behalf of our registered user to approve a friendship.
*/
if (empty($_POST['source_url'])) {
$uid = ($handsfree['uid'] ?? 0) ?: local_user();
if (!$uid) {
notice(DI::l10n()->t('Permission denied.'));
return;
}
$user = DBA::selectFirst('user', [], ['uid' => $uid]);
if (!DBA::isResult($user)) {
notice(DI::l10n()->t('Profile not found.'));
return;
}
// These data elements may come from either the friend request notification form or $handsfree array.
if (is_array($handsfree)) {
Logger::log('Confirm in handsfree mode');
$dfrn_id = $handsfree['dfrn_id'];
$intro_id = $handsfree['intro_id'];
$duplex = $handsfree['duplex'];
$cid = 0;
$hidden = intval($handsfree['hidden'] ?? 0);
} else {
$dfrn_id = Strings::escapeTags(trim($_POST['dfrn_id'] ?? ''));
$intro_id = intval($_POST['intro_id'] ?? 0);
$duplex = intval($_POST['duplex'] ?? 0);
$cid = intval($_POST['contact_id'] ?? 0);
$hidden = intval($_POST['hidden'] ?? 0);
}
/*
* Ensure that dfrn_id has precedence when we go to find the contact record.
* We only want to search based on contact id if there is no dfrn_id,
* e.g. for OStatus network followers.
*/
if (strlen($dfrn_id)) {
$cid = 0;
}
Logger::log('Confirming request for dfrn_id (issued) ' . $dfrn_id);
if ($cid) {
Logger::log('Confirming follower with contact_id: ' . $cid);
}
/*
* The other person will have been issued an ID when they first requested friendship.
* Locate their record. At this time, their record will have both pending and blocked set to 1.
* There won't be any dfrn_id if this is a network follower, so use the contact_id instead.
*/
$r = q("SELECT *
FROM `contact`
WHERE (
(`issued-id` != '' AND `issued-id` = '%s')
OR
(`id` = %d AND `id` != 0)
)
AND `uid` = %d
AND `duplex` = 0
LIMIT 1",
DBA::escape($dfrn_id),
intval($cid),
intval($uid)
);
if (!DBA::isResult($r)) {
Logger::log('Contact not found in DB.');
notice(DI::l10n()->t('Contact not found.'));
notice(DI::l10n()->t('This may occasionally happen if contact was requested by both persons and it has already been approved.'));
return;
}
$contact = $r[0];
$contact_id = $contact['id'];
$relation = $contact['rel'];
$site_pubkey = $contact['site-pubkey'];
$dfrn_confirm = $contact['confirm'];
$aes_allow = $contact['aes_allow'];
$protocol = $contact['network'];
/*
* Generate a key pair for all further communications with this person.
* We have a keypair for every contact, and a site key for unknown people.
* This provides a means to carry on relationships with other people if
* any single key is compromised. It is a robust key. We're much more
* worried about key leakage than anybody cracking it.
*/
$res = Crypto::newKeypair(4096);
$private_key = $res['prvkey'];
$public_key = $res['pubkey'];
// Save the private key. Send them the public key.
$fields = ['prvkey' => $private_key, 'protocol' => Protocol::DFRN];
DBA::update('contact', $fields, ['id' => $contact_id]);
$params = [];
/*
* Per the DFRN protocol, we will verify both ends by encrypting the dfrn_id with our
* site private key (person on the other end can decrypt it with our site public key).
* Then encrypt our profile URL with the other person's site public key. They can decrypt
* it with their site private key. If the decryption on the other end fails for either
* item, it indicates tampering or key failure on at least one site and we will not be
* able to provide a secure communication pathway.
*
* If other site is willing to accept full encryption, (aes_allow is 1 AND we have php5.3
* or later) then we encrypt the personal public key we send them using AES-256-CBC and a
* random key which is encrypted with their site public key.
*/
$src_aes_key = random_bytes(64);
$result = '';
openssl_private_encrypt($dfrn_id, $result, $user['prvkey']);
$params['dfrn_id'] = bin2hex($result);
$params['public_key'] = $public_key;
$my_url = DI::baseUrl() . '/profile/' . $user['nickname'];
openssl_public_encrypt($my_url, $params['source_url'], $site_pubkey);
$params['source_url'] = bin2hex($params['source_url']);
if ($aes_allow && function_exists('openssl_encrypt')) {
openssl_public_encrypt($src_aes_key, $params['aes_key'], $site_pubkey);
$params['aes_key'] = bin2hex($params['aes_key']);
$params['public_key'] = bin2hex(openssl_encrypt($public_key, 'AES-256-CBC', $src_aes_key));
}
$params['dfrn_version'] = DFRN_PROTOCOL_VERSION;
if ($duplex == 1) {
$params['duplex'] = 1;
}
if ($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY) {
$params['page'] = 1;
}
if ($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
$params['page'] = 2;
}
Logger::debug('Confirm: posting data', ['confirm' => $dfrn_confirm, 'parameter' => $params]);
/*
*
* POST all this stuff to the other site.
* Temporarily raise the network timeout to 120 seconds because the default 60
* doesn't always give the other side quite enough time to decrypt everything.
*
*/
$res = DI::httpRequest()->post($dfrn_confirm, $params, [], 120)->getBody();
Logger::log(' Confirm: received data: ' . $res, Logger::DATA);
// Now figure out what they responded. Try to be robust if the remote site is
// having difficulty and throwing up errors of some kind.
$leading_junk = substr($res, 0, strpos($res, '<?xml'));
$res = substr($res, strpos($res, '<?xml'));
if (!strlen($res)) {
// No XML at all, this exchange is messed up really bad.
// We shouldn't proceed, because the xml parser might choke,
// and $status is going to be zero, which indicates success.
// We can hardly call this a success.
notice(DI::l10n()->t('Response from remote site was not understood.'));
return;
}
if (strlen($leading_junk) && DI::config()->get('system', 'debugging')) {
// This might be more common. Mixed error text and some XML.
// If we're configured for debugging, show the text. Proceed in either case.
notice(DI::l10n()->t('Unexpected response from remote site: ') . $leading_junk);
}
if (stristr($res, "<status") === false) {
// wrong xml! stop here!
Logger::log('Unexpected response posting to ' . $dfrn_confirm);
notice(DI::l10n()->t('Unexpected response from remote site: ') . EOL . htmlspecialchars($res));
return;
}
$xml = XML::parseString($res);
$status = (int) $xml->status;
$message = XML::unescape($xml->message); // human readable text of what may have gone wrong.
switch ($status) {
case 0:
info(DI::l10n()->t("Confirmation completed successfully."));
break;
case 1:
// birthday paradox - generate new dfrn-id and fall through.
$new_dfrn_id = Strings::getRandomHex();
q("UPDATE contact SET `issued-id` = '%s' WHERE `id` = %d AND `uid` = %d",
DBA::escape($new_dfrn_id),
intval($contact_id),
intval($uid)
);
case 2:
notice(DI::l10n()->t("Temporary failure. Please wait and try again."));
break;
case 3:
notice(DI::l10n()->t("Introduction failed or was revoked."));
break;
}
if (strlen($message)) {
notice(DI::l10n()->t('Remote site reported: ') . $message);
}
if (($status == 0) && $intro_id) {
$intro = DBA::selectFirst('intro', ['note'], ['id' => $intro_id]);
if (DBA::isResult($intro)) {
DBA::update('contact', ['reason' => $intro['note']], ['id' => $contact_id]);
}
// Success. Delete the notification.
DBA::delete('intro', ['id' => $intro_id]);
}
if ($status != 0) {
return;
}
/*
* We have now established a relationship with the other site.
* Let's make our own personal copy of their profile photo so we don't have
* to always load it from their site.
*
* We will also update the contact record with the nature and scope of the relationship.
*/
Contact::updateAvatar($contact_id, $contact['photo']);
Logger::log('dfrn_confirm: confirm - imported photos');
$new_relation = Contact::FOLLOWER;
if (($relation == Contact::SHARING) || ($duplex)) {
$new_relation = Contact::FRIEND;
}
if (($relation == Contact::SHARING) && ($duplex)) {
$duplex = 0;
}
$r = q("UPDATE `contact` SET `rel` = %d,
`name-date` = '%s',
`uri-date` = '%s',
`blocked` = 0,
`pending` = 0,
`duplex` = %d,
`hidden` = %d,
`network` = '%s' WHERE `id` = %d
",
intval($new_relation),
DBA::escape(DateTimeFormat::utcNow()),
DBA::escape(DateTimeFormat::utcNow()),
intval($duplex),
intval($hidden),
DBA::escape(Protocol::DFRN),
intval($contact_id)
);
// reload contact info
$contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact['id']);
// Let's send our user to the contact editor in case they want to
// do anything special with this new friend.
if ($handsfree === null) {
DI::baseUrl()->redirect('contact/' . intval($contact_id));
} else {
return;
}
//NOTREACHED
}
/*
* End of Scenario 1. [Local confirmation of remote friend request].
*
* Begin Scenario 2. This is the remote response to the above scenario.
* This will take place on the site that originally initiated the friend request.
* In the section above where the confirming party makes a POST and
* retrieves xml status information, they are communicating with the following code.
*/
if (!empty($_POST['source_url'])) {
// We are processing an external confirmation to an introduction created by our user.
$public_key = $_POST['public_key'] ?? '';
$dfrn_id = hex2bin($_POST['dfrn_id'] ?? '');
$source_url = hex2bin($_POST['source_url'] ?? '');
$aes_key = $_POST['aes_key'] ?? '';
$duplex = intval($_POST['duplex'] ?? 0);
$page = intval($_POST['page'] ?? 0);
$forum = (($page == 1) ? 1 : 0);
$prv = (($page == 2) ? 1 : 0);
Logger::notice('requestee contacted', ['node' => $node]);
Logger::debug('request', ['POST' => $_POST]);
// If $aes_key is set, both of these items require unpacking from the hex transport encoding.
if (!empty($aes_key)) {
$aes_key = hex2bin($aes_key);
$public_key = hex2bin($public_key);
}
// Find our user's account
$user = DBA::selectFirst('user', [], ['nickname' => $node]);
if (!DBA::isResult($user)) {
$message = DI::l10n()->t('No user record found for \'%s\' ', $node);
System::xmlExit(3, $message); // failure
// NOTREACHED
}
$my_prvkey = $user['prvkey'];
$local_uid = $user['uid'];
if (!strstr($my_prvkey, 'PRIVATE KEY')) {
$message = DI::l10n()->t('Our site encryption key is apparently messed up.');
System::xmlExit(3, $message);
}
// verify everything
$decrypted_source_url = "";
openssl_private_decrypt($source_url, $decrypted_source_url, $my_prvkey);
if (!strlen($decrypted_source_url)) {
$message = DI::l10n()->t('Empty site URL was provided or URL could not be decrypted by us.');
System::xmlExit(3, $message);
// NOTREACHED
}
$contact = DBA::selectFirst('contact', [], ['url' => $decrypted_source_url, 'uid' => $local_uid]);
if (!DBA::isResult($contact)) {
if (strstr($decrypted_source_url, 'http:')) {
$newurl = str_replace('http:', 'https:', $decrypted_source_url);
} else {
$newurl = str_replace('https:', 'http:', $decrypted_source_url);
}
$contact = DBA::selectFirst('contact', [], ['url' => $newurl, 'uid' => $local_uid]);
if (!DBA::isResult($contact)) {
// this is either a bogus confirmation (?) or we deleted the original introduction.
$message = DI::l10n()->t('Contact record was not found for you on our site.');
System::xmlExit(3, $message);
return; // NOTREACHED
}
}
$relation = $contact['rel'];
// Decrypt all this stuff we just received
$foreign_pubkey = $contact['site-pubkey'];
$dfrn_record = $contact['id'];
if (!$foreign_pubkey) {
$message = DI::l10n()->t('Site public key not available in contact record for URL %s.', $decrypted_source_url);
System::xmlExit(3, $message);
}
$decrypted_dfrn_id = "";
openssl_public_decrypt($dfrn_id, $decrypted_dfrn_id, $foreign_pubkey);
if (strlen($aes_key)) {
$decrypted_aes_key = "";
openssl_private_decrypt($aes_key, $decrypted_aes_key, $my_prvkey);
$dfrn_pubkey = openssl_decrypt($public_key, 'AES-256-CBC', $decrypted_aes_key);
} else {
$dfrn_pubkey = $public_key;
}
if (DBA::exists('contact', ['dfrn-id' => $decrypted_dfrn_id])) {
$message = DI::l10n()->t('The ID provided by your system is a duplicate on our system. It should work if you try again.');
System::xmlExit(1, $message); // Birthday paradox - duplicate dfrn-id
// NOTREACHED
}
$r = q("UPDATE `contact` SET `dfrn-id` = '%s', `pubkey` = '%s' WHERE `id` = %d",
DBA::escape($decrypted_dfrn_id),
DBA::escape($dfrn_pubkey),
intval($dfrn_record)
);
if (!DBA::isResult($r)) {
$message = DI::l10n()->t('Unable to set your contact credentials on our system.');
System::xmlExit(3, $message);
}
// It's possible that the other person also requested friendship.
// If it is a duplex relationship, ditch the issued-id if one exists.
if ($duplex) {
q("UPDATE `contact` SET `issued-id` = '' WHERE `id` = %d",
intval($dfrn_record)
);
}
// We're good but now we have to scrape the profile photo and send notifications.
$contact = DBA::selectFirst('contact', ['photo'], ['id' => $dfrn_record]);
if (DBA::isResult($contact)) {
$photo = $contact['photo'];
} else {
$photo = DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO;
}
Contact::updateAvatar($dfrn_record, $photo);
Logger::log('dfrn_confirm: request - photos imported');
$new_relation = Contact::SHARING;
if (($relation == Contact::FOLLOWER) || ($duplex)) {
$new_relation = Contact::FRIEND;
}
if (($relation == Contact::FOLLOWER) && ($duplex)) {
$duplex = 0;
}
$r = q("UPDATE `contact` SET
`rel` = %d,
`name-date` = '%s',
`uri-date` = '%s',
`blocked` = 0,
`pending` = 0,
`duplex` = %d,
`forum` = %d,
`prv` = %d,
`network` = '%s' WHERE `id` = %d
",
intval($new_relation),
DBA::escape(DateTimeFormat::utcNow()),
DBA::escape(DateTimeFormat::utcNow()),
intval($duplex),
intval($forum),
intval($prv),
DBA::escape(Protocol::DFRN),
intval($dfrn_record)
);
if (!DBA::isResult($r)) { // indicates schema is messed up or total db failure
$message = DI::l10n()->t('Unable to update your contact profile details on our system');
System::xmlExit(3, $message);
}
// Otherwise everything seems to have worked and we are almost done. Yay!
// Send an email notification
Logger::log('dfrn_confirm: request: info updated');
$combined = null;
$r = q("SELECT `contact`.*, `user`.*
FROM `contact`
LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
WHERE `contact`.`id` = %d
LIMIT 1",
intval($dfrn_record)
);
if (DBA::isResult($r)) {
$combined = $r[0];
if ($combined['notify-flags'] & Notification\Type::CONFIRM) {
$mutual = ($new_relation == Contact::FRIEND);
notification([
'type' => Notification\Type::CONFIRM,
'otype' => Notification\ObjectType::INTRO,
'verb' => ($mutual ? Activity::FRIEND : Activity::FOLLOW),
'uid' => $combined['uid'],
'cid' => $combined['id'],
'link' => DI::baseUrl() . '/contact/' . $dfrn_record,
]);
}
}
System::xmlExit(0); // Success
return; // NOTREACHED
////////////////////// End of this scenario ///////////////////////////////////////////////
}
// somebody arrived here by mistake or they are fishing. Send them to the homepage.
DI::baseUrl()->redirect();
// NOTREACHED
}

276
mod/dfrn_notify.php

@ -26,14 +26,12 @@ use Friendica\App;
use Friendica\Core\Logger;
use Friendica\Core\System;
use Friendica\Database\DBA;
use Friendica\DI;
use Friendica\Model\Contact;
use Friendica\Model\Conversation;
use Friendica\Model\User;
use Friendica\Network\HTTPException;
use Friendica\Protocol\DFRN;
use Friendica\Protocol\Diaspora;
use Friendica\Util\Network;
use Friendica\Util\Strings;
function dfrn_notify_post(App $a) {
$postdata = Network::postdata();
@ -53,148 +51,7 @@ function dfrn_notify_post(App $a) {
salmon_post($a, $postdata);
}
}
$dfrn_id = (!empty($_POST['dfrn_id']) ? Strings::escapeTags(trim($_POST['dfrn_id'])) : '');
$dfrn_version = (!empty($_POST['dfrn_version']) ? (float) $_POST['dfrn_version'] : 2.0);
$challenge = (!empty($_POST['challenge']) ? Strings::escapeTags(trim($_POST['challenge'])) : '');
$data = $_POST['data'] ?? '';
$key = $_POST['key'] ?? '';
$rino_remote = (!empty($_POST['rino']) ? intval($_POST['rino']) : 0);
$dissolve = (!empty($_POST['dissolve']) ? intval($_POST['dissolve']) : 0);
$perm = (!empty($_POST['perm']) ? Strings::escapeTags(trim($_POST['perm'])) : 'r');
$ssl_policy = (!empty($_POST['ssl_policy']) ? Strings::escapeTags(trim($_POST['ssl_policy'])): 'none');
$page = (!empty($_POST['page']) ? intval($_POST['page']) : 0);
$forum = (($page == 1) ? 1 : 0);
$prv = (($page == 2) ? 1 : 0);
$writable = (-1);
if ($dfrn_version >= 2.21) {
$writable = (($perm === 'rw') ? 1 : 0);
}
$direction = (-1);
if (strpos($dfrn_id, ':') == 1) {
$direction = intval(substr($dfrn_id, 0, 1));
$dfrn_id = substr($dfrn_id, 2);
}
if (!DBA::exists('challenge', ['dfrn-id' => $dfrn_id, 'challenge' => $challenge])) {
Logger::log('could not match challenge to dfrn_id ' . $dfrn_id . ' challenge=' . $challenge);
System::xmlExit(3, 'Could not match challenge');
}
DBA::delete('challenge', ['dfrn-id' => $dfrn_id, 'challenge' => $challenge]);
$user = DBA::selectFirst('user', ['uid'], ['nickname' => $a->argv[1]]);
if (!DBA::isResult($user)) {
Logger::log('User not found for nickname ' . $a->argv[1]);
System::xmlExit(3, 'User not found');
}
// find the local user who owns this relationship.
$condition = [];
switch ($direction) {
case (-1):
$condition = ["(`issued-id` = ? OR `dfrn-id` = ?) AND `uid` = ?", $dfrn_id, $dfrn_id, $user['uid']];
break;
case 0:
$condition = ['issued-id' => $dfrn_id, 'duplex' => true, 'uid' => $user['uid']];
break;
case 1:
$condition = ['dfrn-id' => $dfrn_id, 'duplex' => true, 'uid' => $user['uid']];
break;
default:
System::xmlExit(3, 'Invalid direction');
break; // NOTREACHED
}
$contact = DBA::selectFirst('contact', ['id'], $condition);
if (!DBA::isResult($contact)) {
Logger::log('contact not found for dfrn_id ' . $dfrn_id);
System::xmlExit(3, 'Contact not found');
}
// $importer in this case contains the contact record for the remote contact joined with the user record of our user.
$importer = DFRN::getImporter($contact['id'], $user['uid']);
if ((($writable != (-1)) && ($writable != $importer['writable'])) || ($importer['forum'] != $forum) || ($importer['prv'] != $prv)) {
$fields = ['writable' => ($writable == (-1)) ? $importer['writable'] : $writable,
'forum' => $forum, 'prv' => $prv];
DBA::update('contact', $fields, ['id' => $importer['id']]);
if ($writable != (-1)) {
$importer['writable'] = $writable;
}
$importer['forum'] = $page;
}
// if contact's ssl policy changed, update our links
$importer = Contact::updateSslPolicy($importer, $ssl_policy);
Logger::log('data: ' . $data, Logger::DATA);
if ($dissolve == 1) {
// Relationship is dissolved permanently
Contact::remove($importer['id']);
Logger::log('relationship dissolved : ' . $importer['name'] . ' dissolved ' . $importer['username']);
System::xmlExit(0, 'relationship dissolved');
}
$rino = DI::config()->get('system', 'rino_encrypt');
$rino = intval($rino);
if (strlen($key)) {
// if local rino is lower than remote rino, abort: should not happen!
// but only for $remote_rino > 1, because old code did't send rino version
if ($rino_remote > 1 && $rino < $rino_remote) {
Logger::log("rino version '$rino_remote' is lower than supported '$rino'");
System::xmlExit(0, "rino version '$rino_remote' is lower than supported '$rino'");
}
$rawkey = hex2bin(trim($key));
Logger::log('rino: md5 raw key: ' . md5($rawkey), Logger::DATA);
$final_key = '';
if ($dfrn_version >= 2.1) {
if (($importer['duplex'] && strlen($importer['cprvkey'])) || !strlen($importer['cpubkey'])) {
openssl_private_decrypt($rawkey, $final_key, $importer['cprvkey']);
} else {
openssl_public_decrypt($rawkey, $final_key, $importer['cpubkey']);
}
} else {
if (($importer['duplex'] && strlen($importer['cpubkey'])) || !strlen($importer['cprvkey'])) {
openssl_public_decrypt($rawkey, $final_key, $importer['cpubkey']);
} else {
openssl_private_decrypt($rawkey, $final_key, $importer['cprvkey']);
}
}
switch ($rino_remote) {
case 0:
case 1:
// we got a key. old code send only the key, without RINO version.
// we assume RINO 1 if key and no RINO version
$data = DFRN::aesDecrypt(hex2bin($data), $final_key);
break;
default:
Logger::log("rino: invalid sent version '$rino_remote'");
System::xmlExit(0, "Invalid sent version '$rino_remote'");
}
Logger::log('rino: decrypted data: ' . $data, Logger::DATA);
}
Logger::log('Importing post from ' . $importer['addr'] . ' to ' . $importer['nickname'] . ' with the RINO ' . $rino_remote . ' encryption.', Logger::DEBUG);
$ret = DFRN::import($data, $importer, Conversation::PARCEL_LEGACY_DFRN, Conversation::PUSH);
System::xmlExit($ret, 'Processed');
// NOTREACHED
throw new HTTPException\BadRequestException();
}
function dfrn_dispatch_public($postdata)
@ -261,132 +118,5 @@ function dfrn_dispatch_private($user, $postdata)
}
function dfrn_notify_content(App $a) {
if (!empty($_GET['dfrn_id'])) {
/*
* initial communication from external contact, $direction is their direction.
* If this is a duplex communication, ours will be the opposite.
*/
$dfrn_id = Strings::escapeTags(trim($_GET['dfrn_id']));
$rino_remote = (!empty($_GET['rino']) ? intval($_GET['rino']) : 0);
$type = "";
$last_update = "";
Logger::log('new notification dfrn_id=' . $dfrn_id);
$direction = (-1);
if (strpos($dfrn_id,':') == 1) {
$direction = intval(substr($dfrn_id,0,1));
$dfrn_id = substr($dfrn_id,2);
}
$hash = Strings::getRandomHex();
$status = 0;
DBA::delete('challenge', ["`expire` < ?", time()]);
$fields = ['challenge' => $hash, 'dfrn-id' => $dfrn_id, 'expire' => time() + 90,
'type' => $type, 'last_update' => $last_update];
DBA::insert('challenge', $fields);
Logger::log('challenge=' . $hash, Logger::DATA);
$user = DBA::selectFirst('user', ['uid'], ['nickname' => $a->argv[1]]);
if (!DBA::isResult($user)) {
Logger::log('User not found for nickname ' . $a->argv[1]);
exit();
}
$condition = [];
switch ($direction) {
case (-1):
$condition = ["(`issued-id` = ? OR `dfrn-id` = ?) AND `uid` = ?", $dfrn_id, $dfrn_id, $user['uid']];
$my_id = $dfrn_id;
break;
case 0:
$condition = ['issued-id' => $dfrn_id, 'duplex' => true, 'uid' => $user['uid']];
$my_id = '1:' . $dfrn_id;
break;
case 1:
$condition = ['dfrn-id' => $dfrn_id, 'duplex' => true, 'uid' => $user['uid']];
$my_id = '0:' . $dfrn_id;
break;
default:
$status = 1;
$my_id = '';
break;
}
$contact = DBA::selectFirst('contact', ['id'], $condition);
if (!DBA::isResult($contact)) {
Logger::log('contact not found for dfrn_id ' . $dfrn_id);
System::xmlExit(3, 'Contact not found');
}
// $importer in this case contains the contact record for the remote contact joined with the user record of our user.
$importer = DFRN::getImporter($contact['id'], $user['uid']);
if (empty($importer)) {
Logger::log('No importer data found for user ' . $a->argv[1] . ' and contact ' . $dfrn_id);
exit();
}
Logger::log("Remote rino version: ".$rino_remote." for ".$importer["url"], Logger::DATA);
$challenge = '';
$encrypted_id = '';
$id_str = $my_id . '.' . mt_rand(1000,9999);
$prv_key = trim($importer['cprvkey']);
$pub_key = trim($importer['cpubkey']);
$dplx = intval($importer['duplex']);
if (($dplx && strlen($prv_key)) || (strlen($prv_key) && !strlen($pub_key))) {
openssl_private_encrypt($hash, $challenge, $prv_key);
openssl_private_encrypt($id_str, $encrypted_id, $prv_key);
} elseif (strlen($pub_key)) {
openssl_public_encrypt($hash, $challenge, $pub_key);
openssl_public_encrypt($id_str, $encrypted_id, $pub_key);
} else {
/// @TODO these kind of else-blocks are making the code harder to understand
$status = 1;
}
$challenge = bin2hex($challenge);
$encrypted_id = bin2hex($encrypted_id);
$rino = DI::config()->get('system', 'rino_encrypt');
$rino = intval($rino);
Logger::log("Local rino version: ". $rino, Logger::DATA);
// if requested rino is lower than enabled local rino, lower local rino version
// if requested rino is higher than enabled local rino, reply with local rino
if ($rino_remote < $rino) {
$rino = $rino_remote;
}
if (($importer['rel'] && ($importer['rel'] != Contact::SHARING)) || ($importer['page-flags'] == User::PAGE_FLAGS_COMMUNITY)) {
$perm = 'rw';
} else {
$perm = 'r';
}
header("Content-type: text/xml");
echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n"
. '<dfrn_notify>' . "\r\n"
. "\t" . '<status>' . $status . '</status>' . "\r\n"
. "\t" . '<dfrn_version>' . DFRN_PROTOCOL_VERSION . '</dfrn_version>' . "\r\n"
. "\t" . '<rino>' . $rino . '</rino>' . "\r\n"
. "\t" . '<perm>' . $perm . '</perm>' . "\r\n"
. "\t" . '<dfrn_id>' . $encrypted_id . '</dfrn_id>' . "\r\n"
. "\t" . '<challenge>' . $challenge . '</challenge>' . "\r\n"
. '</dfrn_notify>' . "\r\n";
exit();
}
throw new HTTPException\NotFoundException();
}

527
mod/dfrn_poll.php

@ -20,536 +20,17 @@
*/
use Friendica\App;
use Friendica\Core\Logger;
use Friendica\Core\Session;
use Friendica\Core\System;
use Friendica\Database\DBA;
use Friendica\DI;
use Friendica\Protocol\DFRN;
use Friendica\Protocol\OStatus;
use Friendica\Util\Strings;
use Friendica\Util\XML;
use Friendica\Network\HTTPException;
function dfrn_poll_init(App $a)
{
DI::auth()->withSession($a);
$dfrn_id = $_GET['dfrn_id'] ?? '';
$type = ($_GET['type'] ?? '') ?: 'data';
$last_update = $_GET['last_update'] ?? '';
$destination_url = $_GET['destination_url'] ?? '';
$challenge = $_GET['challenge'] ?? '';
$sec = $_GET['sec'] ?? '';
$dfrn_version = floatval(($_GET['dfrn_version'] ?? 0.0) ?: 2.0);
$quiet = !empty($_GET['quiet']);
// Possibly it is an OStatus compatible server that requests a user feed
$user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
if (($a->argc > 1) && ($dfrn_id == '') && !strstr($user_agent, 'Friendica')) {
if ($a->argc > 1) {
$nickname = $a->argv[1];
header("Content-type: application/atom+xml");
$last_update = $_GET['last_update'] ?? '';
echo OStatus::feed($nickname, $last_update, 10);
exit();
}
$direction = -1;
if (strpos($dfrn_id, ':') == 1) {
$direction = intval(substr($dfrn_id, 0, 1));
$dfrn_id = substr($dfrn_id, 2);
}
$hidewall = false;
if (($dfrn_id === '') && empty($_POST['dfrn_id'])) {
if (DI::config()->get('system', 'block_public') && !Session::isAuthenticated()) {
throw new \Friendica\Network\HTTPException\ForbiddenException();
}
$user = '';
if ($a->argc > 1) {
$r = q("SELECT `hidewall`,`nickname` FROM `user` WHERE `user`.`nickname` = '%s' LIMIT 1",
DBA::escape($a->argv[1])
);
if (!$r) {
throw new \Friendica\Network\HTTPException\NotFoundException();
}
$hidewall = ($r[0]['hidewall'] && !local_user());
$user = $r[0]['nickname'];
}
Logger::log('dfrn_poll: public feed request from ' . $_SERVER['REMOTE_ADDR'] . ' for ' . $user);
header("Content-type: application/atom+xml");
echo DFRN::feed('', $user, $last_update, 0, $hidewall);
exit();
}
if (($type === 'profile') && (!strlen($sec))) {
$sql_extra = '';
switch ($direction) {
case -1:
$sql_extra = sprintf(" AND ( `dfrn-id` = '%s' OR `issued-id` = '%s' ) ", DBA::escape($dfrn_id), DBA::escape($dfrn_id));
$my_id = $dfrn_id;
break;
case 0:
$sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
$my_id = '1:' . $dfrn_id;
break;
case 1:
$sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
$my_id = '0:' . $dfrn_id;
break;
default:
DI::baseUrl()->redirect();
break; // NOTREACHED
}
$r = q("SELECT `contact`.*, `user`.`username`, `user`.`nickname`
FROM `contact` LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
AND `user`.`nickname` = '%s' $sql_extra LIMIT 1",
DBA::escape($a->argv[1])
);
if (DBA::isResult($r)) {
$s = DI::httpRequest()->fetch($r[0]['poll'] . '?dfrn_id=' . $my_id . '&type=profile-check');
Logger::log("dfrn_poll: old profile returns " . $s, Logger::DATA);
if (strlen($s)) {
$xml = XML::parseString($s);
if ((int)$xml->status === 1) {
$_SESSION['authenticated'] = 1;
$_SESSION['visitor_id'] = $r[0]['id'];
$_SESSION['visitor_home'] = $r[0]['url'];
$_SESSION['visitor_handle'] = $r[0]['addr'];
$_SESSION['visitor_visiting'] = $r[0]['uid'];
$_SESSION['my_url'] = $r[0]['url'];
$_SESSION['remote_comment'] = $r[0]['subscribe'];
Session::setVisitorsContacts();
if (!$quiet) {
info(DI::l10n()->t('%1$s welcomes %2$s', $r[0]['username'], $r[0]['name']));
}
// Visitors get 1 day session.
$session_id = session_id();
$expire = time() + 86400;
q("UPDATE `session` SET `expire` = '%s' WHERE `sid` = '%s'",
DBA::escape($expire),
DBA::escape($session_id)
);
}
}
$profile = (count($r) > 0 && isset($r[0]['nickname']) ? $r[0]['nickname'] : '');
if (!empty($destination_url)) {
System::externalRedirect($destination_url);
} else {
DI::baseUrl()->redirect('profile/' . $profile);
}
}
DI::baseUrl()->redirect();
}
if ($type === 'profile-check' && $dfrn_version < 2.2) {
if ((strlen($challenge)) && (strlen($sec))) {
DBA::delete('profile_check', ["`expire` < ?", time()]);
$r = q("SELECT * FROM `profile_check` WHERE `sec` = '%s' ORDER BY `expire` DESC LIMIT 1",
DBA::escape($sec)
);
if (!DBA::isResult($r)) {
System::xmlExit(3, 'No ticket');
// NOTREACHED
}
$orig_id = $r[0]['dfrn_id'];
if (strpos($orig_id, ':')) {
$orig_id = substr($orig_id, 2);
}
$c = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
intval($r[0]['cid'])
);
if (!DBA::isResult($c)) {
System::xmlExit(3, 'No profile');
}
$contact = $c[0];
$sent_dfrn_id = hex2bin($dfrn_id);
$challenge = hex2bin($challenge);
$final_dfrn_id = '';
if (($contact['duplex']) && strlen($contact['prvkey'])) {
openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
openssl_private_decrypt($challenge, $decoded_challenge, $contact['prvkey']);
} else {
openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
openssl_public_decrypt($challenge, $decoded_challenge, $contact['pubkey']);
}
$final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
if (strpos($final_dfrn_id, ':') == 1) {
$final_dfrn_id = substr($final_dfrn_id, 2);
}
if ($final_dfrn_id != $orig_id) {
Logger::log('profile_check: ' . $final_dfrn_id . ' != ' . $orig_id, Logger::DEBUG);
// did not decode properly - cannot trust this site
System::xmlExit(3, 'Bad decryption');
}
header("Content-type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?><dfrn_poll><status>0</status><challenge>$decoded_challenge</challenge><sec>$sec</sec></dfrn_poll>";
exit();
// NOTREACHED
} else {
// old protocol
switch ($direction) {
case 1:
$dfrn_id = '0:' . $dfrn_id;
break;
case 0:
$dfrn_id = '1:' . $dfrn_id;
break;
default:
break;
}
DBA::delete('profile_check', ["`expire` < ?", time()]);
$r = q("SELECT * FROM `profile_check` WHERE `dfrn_id` = '%s' ORDER BY `expire` DESC",
DBA::escape($dfrn_id));
if (DBA::isResult($r)) {
System::xmlExit(1);
return; // NOTREACHED
}
System::xmlExit(0);
return; // NOTREACHED
}
}
}
function dfrn_poll_post(App $a)
{
$dfrn_id = $_POST['dfrn_id'] ?? '';
$challenge = $_POST['challenge'] ?? '';
$sec = $_POST['sec'] ?? '';
$ptype = $_POST['type'] ?? '';
$perm = ($_POST['perm'] ?? '') ?: 'r';
$dfrn_version = floatval(($_GET['dfrn_version'] ?? 0.0) ?: 2.0);
if ($ptype === 'profile-check') {
if (strlen($challenge) && strlen($sec)) {
Logger::log('dfrn_poll: POST: profile-check');
DBA::delete('profile_check', ["`expire` < ?", time()]);
$r = q("SELECT * FROM `profile_check` WHERE `sec` = '%s' ORDER BY `expire` DESC LIMIT 1",
DBA::escape($sec)
);
if (!DBA::isResult($r)) {
System::xmlExit(3, 'No ticket');
// NOTREACHED
}
$orig_id = $r[0]['dfrn_id'];
if (strpos($orig_id, ':')) {