]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/classes/FeedSub.php
Merge branch 'fixtests' into 'nightly'
[quix0rs-gnu-social.git] / plugins / OStatus / classes / FeedSub.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2009-2010, StatusNet, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 if (!defined('STATUSNET')) {
21     exit(1);
22 }
23
24 /**
25  * @package OStatusPlugin
26  * @maintainer Brion Vibber <brion@status.net>
27  */
28
29 /*
30 PuSH subscription flow:
31
32     $profile->subscribe()
33         sends a sub request to the hub...
34
35     main/push/callback
36         hub sends confirmation back to us via GET
37         We verify the request, then echo back the challenge.
38         On our end, we save the time we subscribed and the lease expiration
39
40     main/push/callback
41         hub sends us updates via POST
42
43 */
44 class FeedDBException extends FeedSubException
45 {
46     public $obj;
47
48     function __construct($obj)
49     {
50         parent::__construct('Database insert failure');
51         $this->obj = $obj;
52     }
53 }
54
55 /**
56  * FeedSub handles low-level PubHubSubbub (PuSH) subscriptions.
57  * Higher-level behavior building OStatus stuff on top is handled
58  * under Ostatus_profile.
59  */
60 class FeedSub extends Managed_DataObject
61 {
62     public $__table = 'feedsub';
63
64     public $id;
65     public $uri;    // varchar(191)   not 255 because utf8mb4 takes more space
66
67     // PuSH subscription data
68     public $huburi;
69     public $secret;
70     public $sub_state; // subscribe, active, unsubscribe, inactive, nohub
71     public $sub_start;
72     public $sub_end;
73     public $last_update;
74
75     public $created;
76     public $modified;
77
78     public static function schemaDef()
79     {
80         return array(
81             'fields' => array(
82                 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'FeedSub local unique id'),
83                 'uri' => array('type' => 'varchar', 'not null' => true, 'length' => 191, 'description' => 'FeedSub uri'),
84                 'huburi' => array('type' => 'text', 'description' => 'FeedSub hub-uri'),
85                 'secret' => array('type' => 'text', 'description' => 'FeedSub stored secret'),
86                 'sub_state' => array('type' => 'enum("subscribe","active","unsubscribe","inactive","nohub")', 'not null' => true, 'description' => 'subscription state'),
87                 'sub_start' => array('type' => 'datetime', 'description' => 'subscription start'),
88                 'sub_end' => array('type' => 'datetime', 'description' => 'subscription end'),
89                 'last_update' => array('type' => 'datetime', 'description' => 'when this record was last updated'),
90                 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
91                 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
92             ),
93             'primary key' => array('id'),
94             'unique keys' => array(
95                 'feedsub_uri_key' => array('uri'),
96             ),
97         );
98     }
99
100     /**
101      * Get the feed uri (http/https)
102      */
103     public function getUri()
104     {
105         if (empty($this->uri)) {
106             throw new NoUriException($this);
107         }
108         return $this->uri;
109     }
110
111     function getLeaseRemaining()
112     {
113         if (empty($this->sub_end)) {
114             return null;
115         }
116         return strtotime($this->sub_end) - time();
117     }
118
119     /**
120      * Do we have a hub? Then we are a PuSH feed.
121      * https://en.wikipedia.org/wiki/PubSubHubbub
122      *
123      * If huburi is empty, then doublecheck that we are not using
124      * a fallback hub. If there is a fallback hub, it is only if the
125      * sub_state is "nohub" that we assume it's not a PuSH feed.
126      */
127     public function isPuSH()
128     {
129         if (empty($this->huburi)
130                 && (!common_config('feedsub', 'fallback_hub')
131                     || $this->sub_state === 'nohub')) {
132                 // Here we have no huburi set. Also, either there is no 
133                 // fallback hub configured or sub_state is "nohub".
134             return false;
135         }
136         return true;
137     }
138
139     /**
140      * Fetch the StatusNet-side profile for this feed
141      * @return Profile
142      */
143     public function localProfile()
144     {
145         if ($this->profile_id) {
146             return Profile::getKV('id', $this->profile_id);
147         }
148         return null;
149     }
150
151     /**
152      * Fetch the StatusNet-side profile for this feed
153      * @return Profile
154      */
155     public function localGroup()
156     {
157         if ($this->group_id) {
158             return User_group::getKV('id', $this->group_id);
159         }
160         return null;
161     }
162
163     /**
164      * @param string $feeduri
165      * @return FeedSub
166      * @throws FeedSubException if feed is invalid or lacks PuSH setup
167      */
168     public static function ensureFeed($feeduri)
169     {
170         $current = self::getKV('uri', $feeduri);
171         if ($current instanceof FeedSub) {
172             return $current;
173         }
174
175         $discover = new FeedDiscovery();
176         $discover->discoverFromFeedURL($feeduri);
177
178         $huburi = $discover->getHubLink();
179         if (!$huburi && !common_config('feedsub', 'fallback_hub') && !common_config('feedsub', 'nohub')) {
180             throw new FeedSubNoHubException();
181         }
182
183         $feedsub = new FeedSub();
184         $feedsub->uri = $feeduri;
185         $feedsub->huburi = $huburi;
186         $feedsub->sub_state = 'inactive';
187
188         $feedsub->created = common_sql_now();
189         $feedsub->modified = common_sql_now();
190
191         $result = $feedsub->insert();
192         if ($result === false) {
193             throw new FeedDBException($feedsub);
194         }
195
196         return $feedsub;
197     }
198
199     /**
200      * Send a subscription request to the hub for this feed.
201      * The hub will later send us a confirmation POST to /main/push/callback.
202      *
203      * @return void
204      * @throws ServerException if feed state is not valid
205      */
206     public function subscribe()
207     {
208         if ($this->sub_state && $this->sub_state != 'inactive') {
209             common_log(LOG_WARNING, sprintf('Attempting to (re)start PuSH subscription to %s in unexpected state %s', $this->getUri(), $this->sub_state));
210         }
211
212         if (!Event::handle('FeedSubscribe', array($this))) {
213             // A plugin handled it
214             return;
215         }
216
217         if (empty($this->huburi)) {
218             if (common_config('feedsub', 'fallback_hub')) {
219                 // No native hub on this feed?
220                 // Use our fallback hub, which handles polling on our behalf.
221             } else if (common_config('feedsub', 'nohub')) {
222                 // For this to actually work, we'll need some polling mechanism.
223                 // The FeedPoller plugin should take care of it.
224                 return;
225             } else {
226                 // TRANS: Server exception.
227                 throw new ServerException(_m('Attempting to start PuSH subscription for feed with no hub.'));
228             }
229         }
230
231         $this->doSubscribe('subscribe');
232     }
233
234     /**
235      * Send a PuSH unsubscription request to the hub for this feed.
236      * The hub will later send us a confirmation POST to /main/push/callback.
237      * Warning: this will cancel the subscription even if someone else in
238      * the system is using it. Most callers will want garbageCollect() instead,
239      * which confirms there's no uses left.
240      *
241      * @throws ServerException if feed state is not valid
242      */
243     public function unsubscribe() {
244         if ($this->sub_state != 'active') {
245             common_log(LOG_WARNING, sprintf('Attempting to (re)end PuSH subscription to %s in unexpected state %s', $this->getUri(), $this->sub_state));
246         }
247
248         if (!Event::handle('FeedUnsubscribe', array($this))) {
249             // A plugin handled it
250             return;
251         }
252
253         if (empty($this->huburi)) {
254             if (common_config('feedsub', 'fallback_hub')) {
255                 // No native hub on this feed?
256                 // Use our fallback hub, which handles polling on our behalf.
257             } else if (common_config('feedsub', 'nohub')) {
258                 // We need a feedpolling plugin (like FeedPoller) active so it will
259                 // set the 'nohub' state to 'inactive' for us.
260                 return;
261             } else {
262                 // TRANS: Server exception.
263                 throw new ServerException(_m('Attempting to end PuSH subscription for feed with no hub.'));
264             }
265         }
266
267         $this->doSubscribe('unsubscribe');
268     }
269
270     /**
271      * Check if there are any active local uses of this feed, and if not then
272      * make sure it's inactive, unsubscribing if necessary.
273      *
274      * @return boolean true if the subscription is now inactive, false if still active.
275      * @throws NoProfileException in FeedSubSubscriberCount for missing Profile entries
276      * @throws Exception if something goes wrong in unsubscribe() method
277      */
278     public function garbageCollect()
279     {
280         if ($this->sub_state == '' || $this->sub_state == 'inactive') {
281             // No active PuSH subscription, we can just leave it be.
282             return true;
283         }
284
285         // PuSH subscription is either active or in an indeterminate state.
286         // Check if we're out of subscribers, and if so send an unsubscribe.
287         $count = 0;
288         Event::handle('FeedSubSubscriberCount', array($this, &$count));
289
290         if ($count > 0) {
291             common_log(LOG_INFO, __METHOD__ . ': ok, ' . $count . ' user(s) left for ' . $this->getUri());
292             return false;
293         }
294
295         common_log(LOG_INFO, __METHOD__ . ': unsubscribing, no users left for ' . $this->getUri());
296         // Unsubscribe throws various Exceptions on failure
297         $this->unsubscribe();
298
299         return true;
300     }
301
302     static public function renewalCheck()
303     {
304         $fs = new FeedSub();
305         // the "" empty string check is because we historically haven't saved unsubscribed feeds as NULL
306         $fs->whereAdd('sub_end IS NOT NULL AND sub_end!="" AND sub_end < NOW() + INTERVAL 1 day');
307         if (!$fs->find()) { // find can be both false and 0, depending on why nothing was found
308             throw new NoResultException($fs);
309         }
310         return $fs;
311     }
312
313     public function renew()
314     {
315         $this->subscribe();
316     }
317
318     /**
319      * Setting to subscribe means it is _waiting_ to become active. This
320      * cannot be done in a transaction because there is a chance that the
321      * remote script we're calling (as in the case of PuSHpress) performs
322      * the lookup _while_ we're POSTing data, which means the transaction
323      * never completes (PushcallbackAction gets an 'inactive' state).
324      *
325      * @return boolean true when everything is ok (throws Exception on fail)
326      * @throws Exception on failure, can be HTTPClient's or our own.
327      */
328     protected function doSubscribe($mode)
329     {
330         $orig = clone($this);
331         if ($mode == 'subscribe') {
332             $this->secret = common_random_hexstr(32);
333         }
334         $this->sub_state = $mode;
335         $this->update($orig);
336         unset($orig);
337
338         try {
339             $callback = common_local_url('pushcallback', array('feed' => $this->id));
340             $headers = array('Content-Type: application/x-www-form-urlencoded');
341             $post = array('hub.mode' => $mode,
342                           'hub.callback' => $callback,
343                           'hub.verify' => 'async',  // TODO: deprecated, remove when noone uses PuSH <0.4 (only 'async' method used there)
344                           'hub.verify_token' => 'Deprecated-since-PuSH-0.4', // TODO: rm!
345
346                           'hub.lease_seconds' => 2592000,   // 3600*24*30, request approximately month long lease (may be changed by hub)
347                           'hub.secret' => $this->secret,
348                           'hub.topic' => $this->getUri());
349             $client = new HTTPClient();
350             if ($this->huburi) {
351                 $hub = $this->huburi;
352             } else {
353                 if (common_config('feedsub', 'fallback_hub')) {
354                     $hub = common_config('feedsub', 'fallback_hub');
355                     if (common_config('feedsub', 'hub_user')) {
356                         $u = common_config('feedsub', 'hub_user');
357                         $p = common_config('feedsub', 'hub_pass');
358                         $client->setAuth($u, $p);
359                     }
360                 } else {
361                     throw new FeedSubException('Server could not find a usable PuSH hub.');
362                 }
363             }
364             $response = $client->post($hub, $headers, $post);
365             $status = $response->getStatus();
366             // PuSH specificed response status code
367             if ($status == 202  || $status == 204) {
368                 common_log(LOG_INFO, __METHOD__ . ': sub req ok, awaiting verification callback');
369                 return;
370             } else if ($status >= 200 && $status < 300) {
371                 common_log(LOG_ERR, __METHOD__ . ": sub req returned unexpected HTTP $status: " . $response->getBody());
372             } else {
373                 common_log(LOG_ERR, __METHOD__ . ": sub req failed with HTTP $status: " . $response->getBody());
374             }
375         } catch (Exception $e) {
376             common_log(LOG_ERR, __METHOD__ . ": error \"{$e->getMessage()}\" hitting hub {$this->huburi} subscribing to {$this->getUri()}");
377
378             // Reset the subscription state.
379             $orig = clone($this);
380             $this->sub_state = 'inactive';
381             $this->update($orig);
382
383             // Throw the Exception again.
384             throw $e;
385         }
386         throw new ServerException("{$mode} request failed.");
387     }
388
389     /**
390      * Save PuSH subscription confirmation.
391      * Sets approximate lease start and end times and finalizes state.
392      *
393      * @param int $lease_seconds provided hub.lease_seconds parameter, if given
394      */
395     public function confirmSubscribe($lease_seconds)
396     {
397         $original = clone($this);
398
399         $this->sub_state = 'active';
400         $this->sub_start = common_sql_date(time());
401         if ($lease_seconds > 0) {
402             $this->sub_end = common_sql_date(time() + $lease_seconds);
403         } else {
404             $this->sub_end = null;  // Backwards compatibility to StatusNet (PuSH <0.4 supported permanent subs)
405         }
406         $this->modified = common_sql_now();
407
408         return $this->update($original);
409     }
410
411     /**
412      * Save PuSH unsubscription confirmation.
413      * Wipes active PuSH sub info and resets state.
414      */
415     public function confirmUnsubscribe()
416     {
417         $original = clone($this);
418
419         // @fixme these should all be null, but DB_DataObject doesn't save null values...?????
420         $this->secret = '';
421         $this->sub_state = '';
422         $this->sub_start = '';
423         $this->sub_end = '';
424         $this->modified = common_sql_now();
425
426         return $this->update($original);
427     }
428
429     /**
430      * Accept updates from a PuSH feed. If validated, this object and the
431      * feed (as a DOMDocument) will be passed to the StartFeedSubHandleFeed
432      * and EndFeedSubHandleFeed events for processing.
433      *
434      * Not guaranteed to be running in an immediate POST context; may be run
435      * from a queue handler.
436      *
437      * Side effects: the feedsub record's lastupdate field will be updated
438      * to the current time (not published time) if we got a legit update.
439      *
440      * @param string $post source of Atom or RSS feed
441      * @param string $hmac X-Hub-Signature header, if present
442      */
443     public function receive($post, $hmac)
444     {
445         common_log(LOG_INFO, sprintf(__METHOD__.': packet for %s with HMAC %s', _ve($this->getUri()), _ve($hmac)));
446
447         if (!in_array($this->sub_state, array('active', 'nohub'))) {
448             common_log(LOG_ERR, sprintf(__METHOD__.': ignoring PuSH for inactive feed %s (in state %s)', _ve($this->getUri()), _ve($this->sub_state)));
449             return;
450         }
451
452         if ($post === '') {
453             common_log(LOG_ERR, __METHOD__ . ": ignoring empty post");
454             return;
455         }
456
457         if (!$this->validatePushSig($post, $hmac)) {
458             // Per spec we silently drop input with a bad sig,
459             // while reporting receipt to the server.
460             return;
461         }
462
463         $feed = new DOMDocument();
464         if (!$feed->loadXML($post)) {
465             // @fixme might help to include the err message
466             common_log(LOG_ERR, __METHOD__ . ": ignoring invalid XML");
467             return;
468         }
469
470         $orig = clone($this);
471         $this->last_update = common_sql_now();
472         $this->update($orig);
473
474         Event::handle('StartFeedSubReceive', array($this, $feed));
475         Event::handle('EndFeedSubReceive', array($this, $feed));
476     }
477
478     /**
479      * Validate the given Atom chunk and HMAC signature against our
480      * shared secret that was set up at subscription time.
481      *
482      * If we don't have a shared secret, there should be no signature.
483      * If we do, our calculated HMAC should match theirs.
484      *
485      * @param string $post raw XML source as POSTed to us
486      * @param string $hmac X-Hub-Signature HTTP header value, or empty
487      * @return boolean true for a match
488      */
489     protected function validatePushSig($post, $hmac)
490     {
491         if ($this->secret) {
492             // {3,16} because shortest hash algorithm name is 3 characters (md2,md4,md5) and longest
493             // is currently 11 characters, but we'll leave some margin in the end...
494             if (preg_match('/^([0-9a-zA-Z\-\,]{3,16})=([0-9a-fA-F]+)$/', $hmac, $matches)) {
495                 $hash_algo  = strtolower($matches[1]);
496                 $their_hmac = strtolower($matches[2]);
497                 common_debug(sprintf(__METHOD__ . ': PuSH from feed %s uses HMAC algorithm %s with value: %s', _ve($this->getUri()), _ve($hash_algo), _ve($their_hmac)));
498
499                 if (!in_array($hash_algo, hash_algos())) {
500                     // We can't handle this at all, PHP doesn't recognize the algorithm name ('md5', 'sha1', 'sha256' etc: https://secure.php.net/manual/en/function.hash-algos.php)
501                     common_log(LOG_ERR, sprintf(__METHOD__.': HMAC algorithm %s unsupported, not found in PHP hash_algos()', _ve($hash_algo)));
502                     return false;
503                 } elseif (!is_null(common_config('security', 'hash_algos')) && !in_array($hash_algo, common_config('security', 'hash_algos'))) {
504                     // We _won't_ handle this because there is a list of accepted hash algorithms and this one is not in it.
505                     common_log(LOG_ERR, sprintf(__METHOD__.': Whitelist for HMAC algorithms exist, but %s is not included.', _ve($hash_algo)));
506                     return false;
507                 }
508
509                 $our_hmac = hash_hmac($hash_algo, $post, $this->secret);
510                 if ($their_hmac === $our_hmac) {
511                     return true;
512                 }
513                 common_log(LOG_ERR, sprintf(__METHOD__.': ignoring PuSH with bad HMAC hash: got %s, expected %s for feed %s from hub %s', _ve($their_hmac), _ve($our_hmac), _ve($this->getUri()), _ve($this->huburi)));
514             } else {
515                 common_log(LOG_ERR, sprintf(__METHOD__.': ignoring PuSH with bogus HMAC==', _ve($hmac)));
516             }
517         } else {
518             if (empty($hmac)) {
519                 return true;
520             } else {
521                 common_log(LOG_ERR, sprintf(__METHOD__.': ignoring PuSH with unexpected HMAC==%s', _ve($hmac)));
522             }
523         }
524         return false;
525     }
526
527     public function delete($useWhere=false)
528     {
529         try {
530             $oprofile = Ostatus_profile::getKV('feeduri', $this->getUri());
531             if ($oprofile instanceof Ostatus_profile) {
532                 // Check if there's a profile. If not, handle the NoProfileException below
533                 $profile = $oprofile->localProfile();
534             }
535         } catch (NoProfileException $e) {
536             // If the Ostatus_profile has no local Profile bound to it, let's clean it out at the same time
537             $oprofile->delete();
538         } catch (NoUriException $e) {
539             // FeedSub->getUri() can throw a NoUriException, let's just go ahead and delete it
540         }
541         return parent::delete($useWhere);
542     }
543 }