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