Issue 8254: Length restriction for "title" and "uri"
[friendica.git/.git] / mod / pubsubhubbub.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
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 use Friendica\App;
23 use Friendica\Core\Logger;
24 use Friendica\Database\DBA;
25 use Friendica\DI;
26 use Friendica\Model\PushSubscriber;
27 use Friendica\Util\Network;
28 use Friendica\Util\Strings;
29
30 function post_var($name) {
31         return !empty($_POST[$name]) ? Strings::escapeTags(trim($_POST[$name])) : '';
32 }
33
34 function pubsubhubbub_init(App $a) {
35         // PuSH subscription must be considered "public" so just block it
36         // if public access isn't enabled.
37         if (DI::config()->get('system', 'block_public')) {
38                 throw new \Friendica\Network\HTTPException\ForbiddenException();
39         }
40
41         // Subscription request from subscriber
42         // https://pubsubhubbub.googlecode.com/git/pubsubhubbub-core-0.4.html#anchor4
43         // Example from GNU Social:
44         // [hub_mode] => subscribe
45         // [hub_callback] => http://status.local/main/push/callback/1
46         // [hub_verify] => sync
47         // [hub_verify_token] => af11...
48         // [hub_secret] => af11...
49         // [hub_topic] => http://friendica.local/dfrn_poll/sazius
50
51         if ($_SERVER['REQUEST_METHOD'] === 'POST') {
52                 $hub_mode = post_var('hub_mode');
53                 $hub_callback = post_var('hub_callback');
54                 $hub_verify_token = post_var('hub_verify_token');
55                 $hub_secret = post_var('hub_secret');
56                 $hub_topic = post_var('hub_topic');
57
58                 // check for valid hub_mode
59                 if ($hub_mode === 'subscribe') {
60                         $subscribe = 1;
61                 } elseif ($hub_mode === 'unsubscribe') {
62                         $subscribe = 0;
63                 } else {
64                         Logger::log("Invalid hub_mode=$hub_mode, ignoring.");
65                         throw new \Friendica\Network\HTTPException\NotFoundException();
66                 }
67
68                 Logger::log("$hub_mode request from " . $_SERVER['REMOTE_ADDR']);
69
70                 if ($a->argc > 1) {
71                         // Normally the url should now contain the nick name as last part of the url
72                         $nick = $a->argv[1];
73                 } else {
74                         // Get the nick name from the topic as a fallback
75                         $nick = $hub_topic;
76                 }
77                 // Extract nick name and strip any .atom extension
78                 $nick = basename($nick, '.atom');
79
80                 if (!$nick) {
81                         Logger::log('Bad hub_topic=$hub_topic, ignoring.');
82                         throw new \Friendica\Network\HTTPException\NotFoundException();
83                 }
84
85                 // fetch user from database given the nickname
86                 $condition = ['nickname' => $nick, 'account_expired' => false, 'account_removed' => false];
87                 $owner = DBA::selectFirst('user', ['uid', 'nickname'], $condition);
88                 if (!DBA::isResult($owner)) {
89                         Logger::log('Local account not found: ' . $nick . ' - topic: ' . $hub_topic . ' - callback: ' . $hub_callback);
90                         throw new \Friendica\Network\HTTPException\NotFoundException();
91                 }
92
93                 // get corresponding row from contact table
94                 $condition = ['uid' => $owner['uid'], 'blocked' => false,
95                         'pending' => false, 'self' => true];
96                 $contact = DBA::selectFirst('contact', ['poll'], $condition);
97                 if (!DBA::isResult($contact)) {
98                         Logger::log('Self contact for user ' . $owner['uid'] . ' not found.');
99                         throw new \Friendica\Network\HTTPException\NotFoundException();
100                 }
101
102                 // sanity check that topic URLs are the same
103                 $hub_topic2 = str_replace('/feed/', '/dfrn_poll/', $hub_topic);
104                 $self = DI::baseUrl() . '/api/statuses/user_timeline/' . $owner['nickname'] . '.atom';
105
106                 if (!Strings::compareLink($hub_topic, $contact['poll']) && !Strings::compareLink($hub_topic2, $contact['poll']) && !Strings::compareLink($hub_topic, $self)) {
107                         Logger::log('Hub topic ' . $hub_topic . ' != ' . $contact['poll']);
108                         throw new \Friendica\Network\HTTPException\NotFoundException();
109                 }
110
111                 // do subscriber verification according to the PuSH protocol
112                 $hub_challenge = Strings::getRandomHex(40);
113
114                 $params = http_build_query([
115                         'hub.mode' => $subscribe == 1 ? 'subscribe' : 'unsubscribe',
116                         'hub.topic' => $hub_topic,
117                         'hub.challenge' => $hub_challenge,
118                         'hub.verify_token' => $hub_verify_token,
119
120                         // lease time is hard coded to one week (in seconds)
121                         // we don't actually enforce the lease time because GNU
122                         // Social/StatusNet doesn't honour it (yet)
123                         'hub.lease_seconds' => 604800,
124                 ]);
125
126                 $hub_callback = rtrim($hub_callback, ' ?&#');
127                 $separator = parse_url($hub_callback, PHP_URL_QUERY) === null ? '?' : '&';
128
129                 $fetchResult = Network::fetchUrlFull($hub_callback . $separator . $params);
130                 $body = $fetchResult->getBody();
131                 $ret = $fetchResult->getReturnCode();
132
133                 // give up if the HTTP return code wasn't a success (2xx)
134                 if ($ret < 200 || $ret > 299) {
135                         Logger::log("Subscriber verification for $hub_topic at $hub_callback returned $ret, ignoring.");
136                         throw new \Friendica\Network\HTTPException\NotFoundException();
137                 }
138
139                 // check that the correct hub_challenge code was echoed back
140                 if (trim($body) !== $hub_challenge) {
141                         Logger::log("Subscriber did not echo back hub.challenge, ignoring.");
142                         Logger::log("\"$hub_challenge\" != \"".trim($body)."\"");
143                         throw new \Friendica\Network\HTTPException\NotFoundException();
144                 }
145
146                 PushSubscriber::renew($owner['uid'], $nick, $subscribe, $hub_callback, $hub_topic, $hub_secret);
147
148                 throw new \Friendica\Network\HTTPException\AcceptedException();
149         }
150         exit();
151 }