]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/classes/FeedSub.php
better comment for PuSH <0.4 hack
[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;
66
67     // PuSH subscription data
68     public $huburi;
69     public $secret;
70     public $sub_state; // subscribe, active, unsubscribe, inactive
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' => 255, '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")', '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', 'not null' => true, '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      * Fetch the StatusNet-side profile for this feed
102      * @return Profile
103      */
104     public function localProfile()
105     {
106         if ($this->profile_id) {
107             return Profile::getKV('id', $this->profile_id);
108         }
109         return null;
110     }
111
112     /**
113      * Fetch the StatusNet-side profile for this feed
114      * @return Profile
115      */
116     public function localGroup()
117     {
118         if ($this->group_id) {
119             return User_group::getKV('id', $this->group_id);
120         }
121         return null;
122     }
123
124     /**
125      * @param string $feeduri
126      * @return FeedSub
127      * @throws FeedSubException if feed is invalid or lacks PuSH setup
128      */
129     public static function ensureFeed($feeduri)
130     {
131         $current = self::getKV('uri', $feeduri);
132         if ($current instanceof FeedSub) {
133             return $current;
134         }
135
136         $discover = new FeedDiscovery();
137         $discover->discoverFromFeedURL($feeduri);
138
139         $huburi = $discover->getHubLink();
140         if (!$huburi && !common_config('feedsub', 'fallback_hub')) {
141             throw new FeedSubNoHubException();
142         }
143
144         $feedsub = new FeedSub();
145         $feedsub->uri = $feeduri;
146         $feedsub->huburi = $huburi;
147         $feedsub->sub_state = 'inactive';
148
149         $feedsub->created = common_sql_now();
150         $feedsub->modified = common_sql_now();
151
152         $result = $feedsub->insert();
153         if ($result === false) {
154             throw new FeedDBException($feedsub);
155         }
156
157         return $feedsub;
158     }
159
160     /**
161      * Send a subscription request to the hub for this feed.
162      * The hub will later send us a confirmation POST to /main/push/callback.
163      *
164      * @return bool true on success, false on failure
165      * @throws ServerException if feed state is not valid
166      */
167     public function subscribe()
168     {
169         if ($this->sub_state && $this->sub_state != 'inactive') {
170             common_log(LOG_WARNING, "Attempting to (re)start PuSH subscription to {$this->uri} in unexpected state {$this->sub_state}");
171         }
172         if (empty($this->huburi)) {
173             if (common_config('feedsub', 'fallback_hub')) {
174                 // No native hub on this feed?
175                 // Use our fallback hub, which handles polling on our behalf.
176             } else if (common_config('feedsub', 'nohub')) {
177                 // Fake it! We're just testing remote feeds w/o hubs.
178                 // We'll never actually get updates in this mode.
179                 return true;
180             } else {
181                 // TRANS: Server exception.
182                 throw new ServerException(_m('Attempting to start PuSH subscription for feed with no hub.'));
183             }
184         }
185
186         return $this->doSubscribe('subscribe');
187     }
188
189     /**
190      * Send a PuSH unsubscription request to the hub for this feed.
191      * The hub will later send us a confirmation POST to /main/push/callback.
192      * Warning: this will cancel the subscription even if someone else in
193      * the system is using it. Most callers will want garbageCollect() instead,
194      * which confirms there's no uses left.
195      *
196      * @return bool true on success, false on failure
197      * @throws ServerException if feed state is not valid
198      */
199     public function unsubscribe() {
200         if ($this->sub_state != 'active') {
201             common_log(LOG_WARNING, "Attempting to (re)end PuSH subscription to {$this->uri} in unexpected state {$this->sub_state}");
202         }
203         if (empty($this->huburi)) {
204             if (common_config('feedsub', 'fallback_hub')) {
205                 // No native hub on this feed?
206                 // Use our fallback hub, which handles polling on our behalf.
207             } else if (common_config('feedsub', 'nohub')) {
208                 // Fake it! We're just testing remote feeds w/o hubs.
209                 // We'll never actually get updates in this mode.
210                 return true;
211             } else {
212                 // TRANS: Server exception.
213                 throw new ServerException(_m('Attempting to end PuSH subscription for feed with no hub.'));
214             }
215         }
216
217         return $this->doSubscribe('unsubscribe');
218     }
219
220     /**
221      * Check if there are any active local uses of this feed, and if not then
222      * make sure it's inactive, unsubscribing if necessary.
223      *
224      * @return boolean true if the subscription is now inactive, false if still active.
225      */
226     public function garbageCollect()
227     {
228         if ($this->sub_state == '' || $this->sub_state == 'inactive') {
229             // No active PuSH subscription, we can just leave it be.
230             return true;
231         } else {
232             // PuSH subscription is either active or in an indeterminate state.
233             // Check if we're out of subscribers, and if so send an unsubscribe.
234             $count = 0;
235             Event::handle('FeedSubSubscriberCount', array($this, &$count));
236
237             if ($count) {
238                 common_log(LOG_INFO, __METHOD__ . ': ok, ' . $count . ' user(s) left for ' . $this->uri);
239                 return false;
240             } else {
241                 common_log(LOG_INFO, __METHOD__ . ': unsubscribing, no users left for ' . $this->uri);
242                 return $this->unsubscribe();
243             }
244         }
245     }
246
247     static public function renewalCheck()
248     {
249         $fs = new FeedSub();
250         // the "" empty string check is because we historically haven't saved unsubscribed feeds as NULL
251         $fs->whereAdd('sub_end IS NOT NULL AND sub_end!="" AND sub_end < NOW() - INTERVAL 1 day');
252         if (!$fs->find()) { // find can be both false and 0, depending on why nothing was found
253             throw new NoResultException($fs);
254         }
255         return $fs;
256     }
257
258     public function renew()
259     {
260         $this->subscribe();
261     }
262
263     /**
264      * @return boolean  true on successful sub/unsub, false on failure
265      */
266     protected function doSubscribe($mode)
267     {
268         $this->query('BEGIN');
269         $orig = clone($this);
270         if ($mode == 'subscribe') {
271             $this->secret = common_random_hexstr(32);
272         }
273         $this->sub_state = $mode;
274         $this->update($orig);
275         unset($orig);
276
277         try {
278             $callback = common_local_url('pushcallback', array('feed' => $this->id));
279             $headers = array('Content-Type: application/x-www-form-urlencoded');
280             $post = array('hub.mode' => $mode,
281                           'hub.callback' => $callback,
282                           'hub.verify' => 'async',  // TODO: deprecated, remove when noone uses PuSH <0.4 (only 'async' method used there)
283                           'hub.verify_token' => 'Deprecated-since-PuSH-0.4', // TODO: rm!
284
285                           'hub.secret' => $this->secret,
286                           'hub.topic' => $this->uri);
287             $client = new HTTPClient();
288             if ($this->huburi) {
289                 $hub = $this->huburi;
290             } else {
291                 if (common_config('feedsub', 'fallback_hub')) {
292                     $hub = common_config('feedsub', 'fallback_hub');
293                     if (common_config('feedsub', 'hub_user')) {
294                         $u = common_config('feedsub', 'hub_user');
295                         $p = common_config('feedsub', 'hub_pass');
296                         $client->setAuth($u, $p);
297                     }
298                 } else {
299                     throw new FeedSubException('WTF?');
300                 }
301             }
302             $response = $client->post($hub, $headers, $post);
303             $status = $response->getStatus();
304             if ($status == 202) {
305                 $this->query('COMMIT');
306                 common_log(LOG_INFO, __METHOD__ . ': sub req ok, awaiting verification callback');
307                 return true;
308             } else if ($status >= 200 && $status < 300) {
309                 common_log(LOG_ERR, __METHOD__ . ": sub req returned unexpected HTTP $status: " . $response->getBody());
310             } else {
311                 common_log(LOG_ERR, __METHOD__ . ": sub req failed with HTTP $status: " . $response->getBody());
312             }
313             $this->query('ROLLBACK');
314         } catch (Exception $e) {
315             $this->query('ROLLBACK');
316             // wtf!
317             common_log(LOG_ERR, __METHOD__ . ": error \"{$e->getMessage()}\" hitting hub $this->huburi subscribing to $this->uri");
318
319             $orig = clone($this);
320             $this->sub_state = 'inactive';
321             $this->update($orig);
322             unset($orig);
323         }
324         return false;
325     }
326
327     /**
328      * Save PuSH subscription confirmation.
329      * Sets approximate lease start and end times and finalizes state.
330      *
331      * @param int $lease_seconds provided hub.lease_seconds parameter, if given
332      */
333     public function confirmSubscribe($lease_seconds)
334     {
335         $original = clone($this);
336
337         $this->sub_state = 'active';
338         $this->sub_start = common_sql_date(time());
339         if ($lease_seconds > 0) {
340             $this->sub_end = common_sql_date(time() + $lease_seconds);
341         } else {
342             $this->sub_end = null;  // Backwards compatibility to StatusNet (PuSH <0.4 supported permanent subs)
343         }
344         $this->modified = common_sql_now();
345
346         return $this->update($original);
347     }
348
349     /**
350      * Save PuSH unsubscription confirmation.
351      * Wipes active PuSH sub info and resets state.
352      */
353     public function confirmUnsubscribe()
354     {
355         $original = clone($this);
356
357         // @fixme these should all be null, but DB_DataObject doesn't save null values...?????
358         $this->secret = '';
359         $this->sub_state = '';
360         $this->sub_start = '';
361         $this->sub_end = '';
362         $this->modified = common_sql_now();
363
364         return $this->update($original);
365     }
366
367     /**
368      * Accept updates from a PuSH feed. If validated, this object and the
369      * feed (as a DOMDocument) will be passed to the StartFeedSubHandleFeed
370      * and EndFeedSubHandleFeed events for processing.
371      *
372      * Not guaranteed to be running in an immediate POST context; may be run
373      * from a queue handler.
374      *
375      * Side effects: the feedsub record's lastupdate field will be updated
376      * to the current time (not published time) if we got a legit update.
377      *
378      * @param string $post source of Atom or RSS feed
379      * @param string $hmac X-Hub-Signature header, if present
380      */
381     public function receive($post, $hmac)
382     {
383         common_log(LOG_INFO, __METHOD__ . ": packet for \"$this->uri\"! $hmac $post");
384
385         if ($this->sub_state != 'active') {
386             common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH for inactive feed $this->uri (in state '$this->sub_state')");
387             return;
388         }
389
390         if ($post === '') {
391             common_log(LOG_ERR, __METHOD__ . ": ignoring empty post");
392             return;
393         }
394
395         if (!$this->validatePushSig($post, $hmac)) {
396             // Per spec we silently drop input with a bad sig,
397             // while reporting receipt to the server.
398             return;
399         }
400
401         $feed = new DOMDocument();
402         if (!$feed->loadXML($post)) {
403             // @fixme might help to include the err message
404             common_log(LOG_ERR, __METHOD__ . ": ignoring invalid XML");
405             return;
406         }
407
408         $orig = clone($this);
409         $this->last_update = common_sql_now();
410         $this->update($orig);
411
412         Event::handle('StartFeedSubReceive', array($this, $feed));
413         Event::handle('EndFeedSubReceive', array($this, $feed));
414     }
415
416     /**
417      * Validate the given Atom chunk and HMAC signature against our
418      * shared secret that was set up at subscription time.
419      *
420      * If we don't have a shared secret, there should be no signature.
421      * If we we do, our the calculated HMAC should match theirs.
422      *
423      * @param string $post raw XML source as POSTed to us
424      * @param string $hmac X-Hub-Signature HTTP header value, or empty
425      * @return boolean true for a match
426      */
427     protected function validatePushSig($post, $hmac)
428     {
429         if ($this->secret) {
430             if (preg_match('/^sha1=([0-9a-fA-F]{40})$/', $hmac, $matches)) {
431                 $their_hmac = strtolower($matches[1]);
432                 $our_hmac = hash_hmac('sha1', $post, $this->secret);
433                 if ($their_hmac === $our_hmac) {
434                     return true;
435                 }
436                 if (common_config('feedsub', 'debug')) {
437                     $tempfile = tempnam(sys_get_temp_dir(), 'feedsub-receive');
438                     if ($tempfile) {
439                         file_put_contents($tempfile, $post);
440                     }
441                     common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH with bad SHA-1 HMAC: got $their_hmac, expected $our_hmac for feed $this->uri on $this->huburi; saved to $tempfile");
442                 } else {
443                     common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH with bad SHA-1 HMAC: got $their_hmac, expected $our_hmac for feed $this->uri on $this->huburi");
444                 }
445             } else {
446                 common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH with bogus HMAC '$hmac'");
447             }
448         } else {
449             if (empty($hmac)) {
450                 return true;
451             } else {
452                 common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH with unexpected HMAC '$hmac'");
453             }
454         }
455         return false;
456     }
457 }