]> git.mxchange.org Git - friendica.git/blob - src/Module/OStatus/PubSubHubBub.php
Merge remote-tracking branch 'upstream/develop' into inbox-gsid
[friendica.git] / src / Module / OStatus / PubSubHubBub.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, 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 namespace Friendica\Module\OStatus;
23
24 use Friendica\App;
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;
35
36 /**
37  * An open, simple, web-scale and decentralized pubsub protocol.
38  *
39  * Part of the OStatus stack.
40  *
41  * See https://pubsubhubbub.github.io/PubSubHubbub/pubsubhubbub-core-0.4.html
42  *
43  * @version 0.4
44  */
45 class PubSubHubBub extends \Friendica\BaseModule
46 {
47         /** @var IManageConfigValues */
48         private $config;
49         /** @var Database */
50         private $database;
51         /** @var ICanSendHttpRequests */
52         private $httpClient;
53         /** @var App\Request */
54         private $request;
55
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 = [])
57         {
58                 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
59
60                 $this->config     = $config;
61                 $this->database   = $database;
62                 $this->httpClient = $httpClient;
63                 $this->request    = $request;
64         }
65
66         protected function post(array $request = [])
67         {
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();
72                 }
73
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
83
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']        ?? '';
89
90                 // check for valid hub_mode
91                 if ($hub_mode === 'subscribe') {
92                         $subscribe = 1;
93                 } elseif ($hub_mode === 'unsubscribe') {
94                         $subscribe = 0;
95                 } else {
96                         $this->logger->notice('Invalid hub_mod - ignored.', ['mode' => $hub_mode]);
97                         throw new HTTPException\NotFoundException();
98                 }
99
100                 $this->logger->info('hub_mode request details.', ['from' => $this->request->getRemoteAddress(), 'mode' => $hub_mode]);
101
102                 $nickname = $this->parameters['nickname'] ?? $hub_topic;
103
104                 // Extract nickname and strip any .atom extension
105                 $nickname = basename($nickname, '.atom');
106                 if (!$nickname) {
107                         $this->logger->notice('Empty nick, ignoring.');
108                         throw new HTTPException\NotFoundException();
109                 }
110
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);
114                 if (!$owner) {
115                         $this->logger->notice('Local account not found', ['nickname' => $nickname, 'topic' => $hub_topic, 'callback' => $hub_callback]);
116                         throw new HTTPException\NotFoundException();
117                 }
118
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);
122                 if (!$contact) {
123                         $this->logger->notice('Self contact for user not found.', ['uid' => $owner['uid']]);
124                         throw new HTTPException\NotFoundException();
125                 }
126
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';
130
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();
134                 }
135
136                 // do subscriber verification according to the PuSH protocol
137                 $hub_challenge = Strings::getRandomHex(40);
138
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,
144
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,
149                 ]);
150
151                 $hub_callback = rtrim($hub_callback, ' ?&#');
152                 $separator    = parse_url($hub_callback, PHP_URL_QUERY) === null ? '?' : '&';
153
154                 $fetchResult = $this->httpClient->fetchFull($hub_callback . $separator . $params);
155                 $body        = $fetchResult->getBody();
156                 $returnCode  = $fetchResult->getReturnCode();
157
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();
162                 }
163
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();
168                 }
169
170                 PushSubscriber::renew($owner['uid'], $nickname, $subscribe, $hub_callback, $hub_topic, $hub_secret);
171
172                 throw new HTTPException\AcceptedException();
173         }
174 }