3 * @copyright Copyright (C) 2010-2022, 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/>.
22 namespace Friendica\Module\OStatus;
25 use Friendica\Core\Config\Capability\IManageConfigValues;
26 use Friendica\Core\L10n;
27 use Friendica\Database\Database;
28 use Friendica\Model\PushSubscriber;
29 use Friendica\Module\Response;
30 use Friendica\Network\HTTPClient\Capability\ICanSendHttpRequests;
31 use Friendica\Network\HTTPException;
32 use Friendica\Util\Profiler;
33 use Friendica\Util\Strings;
34 use Psr\Log\LoggerInterface;
37 * An open, simple, web-scale and decentralized pubsub protocol.
39 * Part of the OStatus stack.
41 * See https://pubsubhubbub.github.io/PubSubHubbub/pubsubhubbub-core-0.4.html
45 class PubSubHubBub extends \Friendica\BaseModule
47 /** @var IManageConfigValues */
51 /** @var ICanSendHttpRequests */
53 /** @var App\Request */
56 public function __construct(App\Request $request, ICanSendHttpRequests $httpClient, Database $database, IManageConfigValues $config, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, array $server, array $parameters = [])
58 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
60 $this->config = $config;
61 $this->database = $database;
62 $this->httpClient = $httpClient;
63 $this->request = $request;
66 protected function post(array $request = [])
68 // PuSH subscription must be considered "public" so just block it
69 // if public access isn't enabled.
70 if ($this->config->get('system', 'block_public')) {
71 throw new HTTPException\ForbiddenException();
74 // Subscription request from subscriber
75 // https://pubsubhubbub.github.io/PubSubHubbub/pubsubhubbub-core-0.4.html#rfc.section.5.1
76 // Example from GNU Social:
77 // [hub_mode] => subscribe
78 // [hub_callback] => http://status.local/main/push/callback/1
79 // [hub_verify] => sync
80 // [hub_verify_token] => af11...
81 // [hub_secret] => af11...
82 // [hub_topic] => http://friendica.local/dfrn_poll/sazius
84 $hub_mode = $request['hub_mode'] ?? '';
85 $hub_callback = $request['hub_callback'] ?? '';
86 $hub_verify_token = $request['hub_verify_token'] ?? '';
87 $hub_secret = $request['hub_secret'] ?? '';
88 $hub_topic = $request['hub_topic'] ?? '';
90 // check for valid hub_mode
91 if ($hub_mode === 'subscribe') {
93 } elseif ($hub_mode === 'unsubscribe') {
96 $this->logger->notice('Invalid hub_mod - ignored.', ['mode' => $hub_mode]);
97 throw new HTTPException\NotFoundException();
100 $this->logger->info('hub_mode request details.', ['from' => $this->request->getRemoteAddress(), 'mode' => $hub_mode]);
102 $nickname = $this->parameters['nickname'] ?? $hub_topic;
104 // Extract nickname and strip any .atom extension
105 $nickname = basename($nickname, '.atom');
107 $this->logger->notice('Empty nick, ignoring.');
108 throw new HTTPException\NotFoundException();
111 // fetch user from database given the nickname
112 $condition = ['nickname' => $nickname, 'account_expired' => false, 'account_removed' => false];
113 $owner = $this->database->selectFirst('user', ['uid', 'nickname'], $condition);
115 $this->logger->notice('Local account not found', ['nickname' => $nickname, 'topic' => $hub_topic, 'callback' => $hub_callback]);
116 throw new HTTPException\NotFoundException();
119 // get corresponding row from contact table
120 $condition = ['uid' => $owner['uid'], 'blocked' => false, 'pending' => false, 'self' => true];
121 $contact = $this->database->selectFirst('contact', ['poll'], $condition);
123 $this->logger->notice('Self contact for user not found.', ['uid' => $owner['uid']]);
124 throw new HTTPException\NotFoundException();
127 // sanity check that topic URLs are the same
128 $hub_topic2 = str_replace('/feed/', '/dfrn_poll/', $hub_topic);
129 $self = $this->baseUrl . '/api/statuses/user_timeline/' . $owner['nickname'] . '.atom';
131 if (!Strings::compareLink($hub_topic, $contact['poll']) && !Strings::compareLink($hub_topic2, $contact['poll']) && !Strings::compareLink($hub_topic, $self)) {
132 $this->logger->notice('Hub topic invalid', ['hub_topic' => $hub_topic, 'poll' => $contact['poll']]);
133 throw new HTTPException\NotFoundException();
136 // do subscriber verification according to the PuSH protocol
137 $hub_challenge = Strings::getRandomHex(40);
139 $params = http_build_query([
140 'hub.mode' => $subscribe == 1 ? 'subscribe' : 'unsubscribe',
141 'hub.topic' => $hub_topic,
142 'hub.challenge' => $hub_challenge,
143 'hub.verify_token' => $hub_verify_token,
145 // lease time is hard coded to one week (in seconds)
146 // we don't actually enforce the lease time because GNU
147 // Social/StatusNet doesn't honour it (yet)
148 'hub.lease_seconds' => 604800,
151 $hub_callback = rtrim($hub_callback, ' ?&#');
152 $separator = parse_url($hub_callback, PHP_URL_QUERY) === null ? '?' : '&';
154 $fetchResult = $this->httpClient->fetchFull($hub_callback . $separator . $params);
155 $body = $fetchResult->getBody();
156 $returnCode = $fetchResult->getReturnCode();
158 // give up if the HTTP return code wasn't a success (2xx)
159 if ($returnCode < 200 || $returnCode > 299) {
160 $this->logger->notice('Subscriber verification ignored', ['hub_topic' => $hub_topic, 'callback' => $hub_callback, 'returnCode' => $returnCode]);
161 throw new HTTPException\NotFoundException();
164 // check that the correct hub_challenge code was echoed back
165 if (trim($body) !== $hub_challenge) {
166 $this->logger->notice('Subscriber did not echo back hub.challenge, ignoring.', ['hub_challenge' => $hub_challenge, 'body' => trim($body)]);
167 throw new HTTPException\NotFoundException();
170 PushSubscriber::renew($owner['uid'], $nickname, $subscribe, $hub_callback, $hub_topic, $hub_secret);
172 throw new HTTPException\AcceptedException();