3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2009-2010, StatusNet, Inc.
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.
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.
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/>.
20 if (!defined('STATUSNET')) {
25 * @package OStatusPlugin
26 * @maintainer Brion Vibber <brion@status.net>
30 PuSH subscription flow:
33 sends a sub request to the hub...
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
41 hub sends us updates via POST
44 class FeedDBException extends FeedSubException
48 function __construct($obj)
50 parent::__construct('Database insert failure');
56 * FeedSub handles low-level PubHubSubbub (PuSH) subscriptions.
57 * Higher-level behavior building OStatus stuff on top is handled
58 * under Ostatus_profile.
60 class FeedSub extends Managed_DataObject
62 public $__table = 'feedsub';
67 // PuSH subscription data
70 public $sub_state; // subscribe, active, unsubscribe, inactive, nohub
78 public static function schemaDef()
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","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', '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'),
93 'primary key' => array('id'),
94 'unique keys' => array(
95 'feedsub_uri_key' => array('uri'),
101 * Get the feed uri (http/https)
103 public function getUri()
105 if (empty($this->uri)) {
106 throw new ServerException('No URI for FeedSub entry');
112 * Do we have a hub? Then we are a PuSH feed.
113 * https://en.wikipedia.org/wiki/PubSubHubbub
115 * If huburi is empty, then doublecheck that we are not using
116 * a fallback hub. If there is a fallback hub, it is only if the
117 * sub_state is "nohub" that we assume it's not a PuSH feed.
119 public function isPuSH()
121 if (empty($this->huburi)
122 && (!common_config('feedsub', 'fallback_hub')
123 || $this->sub_state === 'nohub')) {
124 // Here we have no huburi set. Also, either there is no
125 // fallback hub configured or sub_state is "nohub".
132 * Fetch the StatusNet-side profile for this feed
135 public function localProfile()
137 if ($this->profile_id) {
138 return Profile::getKV('id', $this->profile_id);
144 * Fetch the StatusNet-side profile for this feed
147 public function localGroup()
149 if ($this->group_id) {
150 return User_group::getKV('id', $this->group_id);
156 * @param string $feeduri
158 * @throws FeedSubException if feed is invalid or lacks PuSH setup
160 public static function ensureFeed($feeduri)
162 $current = self::getKV('uri', $feeduri);
163 if ($current instanceof FeedSub) {
167 $discover = new FeedDiscovery();
168 $discover->discoverFromFeedURL($feeduri);
170 $huburi = $discover->getHubLink();
171 if (!$huburi && !common_config('feedsub', 'fallback_hub')) {
172 throw new FeedSubNoHubException();
175 $feedsub = new FeedSub();
176 $feedsub->uri = $feeduri;
177 $feedsub->huburi = $huburi;
178 $feedsub->sub_state = 'inactive';
180 $feedsub->created = common_sql_now();
181 $feedsub->modified = common_sql_now();
183 $result = $feedsub->insert();
184 if ($result === false) {
185 throw new FeedDBException($feedsub);
192 * Send a subscription request to the hub for this feed.
193 * The hub will later send us a confirmation POST to /main/push/callback.
195 * @return bool true on success, false on failure
196 * @throws ServerException if feed state is not valid
198 public function subscribe()
200 if ($this->sub_state && $this->sub_state != 'inactive') {
201 common_log(LOG_WARNING, "Attempting to (re)start PuSH subscription to {$this->uri} in unexpected state {$this->sub_state}");
204 if (!Event::handle('FeedSubscribe', array($this))) {
205 // A plugin handled it
209 if (empty($this->huburi)) {
210 if (common_config('feedsub', 'fallback_hub')) {
211 // No native hub on this feed?
212 // Use our fallback hub, which handles polling on our behalf.
213 } else if (common_config('feedsub', 'nohub')) {
214 // Fake it! We're just testing remote feeds w/o hubs.
215 // We'll never actually get updates in this mode.
218 // TRANS: Server exception.
219 throw new ServerException(_m('Attempting to start PuSH subscription for feed with no hub.'));
223 return $this->doSubscribe('subscribe');
227 * Send a PuSH unsubscription request to the hub for this feed.
228 * The hub will later send us a confirmation POST to /main/push/callback.
229 * Warning: this will cancel the subscription even if someone else in
230 * the system is using it. Most callers will want garbageCollect() instead,
231 * which confirms there's no uses left.
233 * @return bool true on success, false on failure
234 * @throws ServerException if feed state is not valid
236 public function unsubscribe() {
237 if ($this->sub_state != 'active') {
238 common_log(LOG_WARNING, "Attempting to (re)end PuSH subscription to {$this->uri} in unexpected state {$this->sub_state}");
241 if (!Event::handle('FeedUnsubscribe', array($this))) {
242 // A plugin handled it
246 if (empty($this->huburi)) {
247 if (common_config('feedsub', 'fallback_hub')) {
248 // No native hub on this feed?
249 // Use our fallback hub, which handles polling on our behalf.
250 } else if (common_config('feedsub', 'nohub')) {
251 // Fake it! We're just testing remote feeds w/o hubs.
252 // We'll never actually get updates in this mode.
255 // TRANS: Server exception.
256 throw new ServerException(_m('Attempting to end PuSH subscription for feed with no hub.'));
260 return $this->doSubscribe('unsubscribe');
264 * Check if there are any active local uses of this feed, and if not then
265 * make sure it's inactive, unsubscribing if necessary.
267 * @return boolean true if the subscription is now inactive, false if still active.
269 public function garbageCollect()
271 if ($this->sub_state == '' || $this->sub_state == 'inactive') {
272 // No active PuSH subscription, we can just leave it be.
275 // PuSH subscription is either active or in an indeterminate state.
276 // Check if we're out of subscribers, and if so send an unsubscribe.
278 Event::handle('FeedSubSubscriberCount', array($this, &$count));
281 common_log(LOG_INFO, __METHOD__ . ': ok, ' . $count . ' user(s) left for ' . $this->uri);
284 common_log(LOG_INFO, __METHOD__ . ': unsubscribing, no users left for ' . $this->uri);
285 return $this->unsubscribe();
290 static public function renewalCheck()
293 // the "" empty string check is because we historically haven't saved unsubscribed feeds as NULL
294 $fs->whereAdd('sub_end IS NOT NULL AND sub_end!="" AND sub_end < NOW() - INTERVAL 1 day');
295 if (!$fs->find()) { // find can be both false and 0, depending on why nothing was found
296 throw new NoResultException($fs);
301 public function renew()
307 * Setting to subscribe means it is _waiting_ to become active. This
308 * cannot be done in a transaction because there is a chance that the
309 * remote script we're calling (as in the case of PuSHpress) performs
310 * the lookup _while_ we're POSTing data, which means the transaction
311 * never completes (PushcallbackAction gets an 'inactive' state).
313 * @return boolean true on successful sub/unsub, false on failure
315 protected function doSubscribe($mode)
317 $orig = clone($this);
318 if ($mode == 'subscribe') {
319 $this->secret = common_random_hexstr(32);
321 $this->sub_state = $mode;
322 $this->update($orig);
326 $callback = common_local_url('pushcallback', array('feed' => $this->id));
327 $headers = array('Content-Type: application/x-www-form-urlencoded');
328 $post = array('hub.mode' => $mode,
329 'hub.callback' => $callback,
330 'hub.verify' => 'async', // TODO: deprecated, remove when noone uses PuSH <0.4 (only 'async' method used there)
331 'hub.verify_token' => 'Deprecated-since-PuSH-0.4', // TODO: rm!
333 'hub.secret' => $this->secret,
334 'hub.topic' => $this->uri);
335 $client = new HTTPClient();
337 $hub = $this->huburi;
339 if (common_config('feedsub', 'fallback_hub')) {
340 $hub = common_config('feedsub', 'fallback_hub');
341 if (common_config('feedsub', 'hub_user')) {
342 $u = common_config('feedsub', 'hub_user');
343 $p = common_config('feedsub', 'hub_pass');
344 $client->setAuth($u, $p);
347 throw new FeedSubException('WTF?');
350 $response = $client->post($hub, $headers, $post);
351 $status = $response->getStatus();
352 if ($status == 202) {
353 common_log(LOG_INFO, __METHOD__ . ': sub req ok, awaiting verification callback');
355 } else if ($status >= 200 && $status < 300) {
356 common_log(LOG_ERR, __METHOD__ . ": sub req returned unexpected HTTP $status: " . $response->getBody());
358 common_log(LOG_ERR, __METHOD__ . ": sub req failed with HTTP $status: " . $response->getBody());
360 } catch (Exception $e) {
362 common_log(LOG_ERR, __METHOD__ . ": error \"{$e->getMessage()}\" hitting hub $this->huburi subscribing to $this->uri");
364 $orig = clone($this);
365 $this->sub_state = 'inactive';
366 $this->update($orig);
373 * Save PuSH subscription confirmation.
374 * Sets approximate lease start and end times and finalizes state.
376 * @param int $lease_seconds provided hub.lease_seconds parameter, if given
378 public function confirmSubscribe($lease_seconds)
380 $original = clone($this);
382 $this->sub_state = 'active';
383 $this->sub_start = common_sql_date(time());
384 if ($lease_seconds > 0) {
385 $this->sub_end = common_sql_date(time() + $lease_seconds);
387 $this->sub_end = null; // Backwards compatibility to StatusNet (PuSH <0.4 supported permanent subs)
389 $this->modified = common_sql_now();
391 return $this->update($original);
395 * Save PuSH unsubscription confirmation.
396 * Wipes active PuSH sub info and resets state.
398 public function confirmUnsubscribe()
400 $original = clone($this);
402 // @fixme these should all be null, but DB_DataObject doesn't save null values...?????
404 $this->sub_state = '';
405 $this->sub_start = '';
407 $this->modified = common_sql_now();
409 return $this->update($original);
413 * Accept updates from a PuSH feed. If validated, this object and the
414 * feed (as a DOMDocument) will be passed to the StartFeedSubHandleFeed
415 * and EndFeedSubHandleFeed events for processing.
417 * Not guaranteed to be running in an immediate POST context; may be run
418 * from a queue handler.
420 * Side effects: the feedsub record's lastupdate field will be updated
421 * to the current time (not published time) if we got a legit update.
423 * @param string $post source of Atom or RSS feed
424 * @param string $hmac X-Hub-Signature header, if present
426 public function receive($post, $hmac)
428 common_log(LOG_INFO, __METHOD__ . ": packet for \"$this->uri\"! $hmac $post");
430 if ($this->sub_state != 'active') {
431 common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH for inactive feed $this->uri (in state '$this->sub_state')");
436 common_log(LOG_ERR, __METHOD__ . ": ignoring empty post");
440 if (!$this->validatePushSig($post, $hmac)) {
441 // Per spec we silently drop input with a bad sig,
442 // while reporting receipt to the server.
446 $feed = new DOMDocument();
447 if (!$feed->loadXML($post)) {
448 // @fixme might help to include the err message
449 common_log(LOG_ERR, __METHOD__ . ": ignoring invalid XML");
453 $orig = clone($this);
454 $this->last_update = common_sql_now();
455 $this->update($orig);
457 Event::handle('StartFeedSubReceive', array($this, $feed));
458 Event::handle('EndFeedSubReceive', array($this, $feed));
462 * Validate the given Atom chunk and HMAC signature against our
463 * shared secret that was set up at subscription time.
465 * If we don't have a shared secret, there should be no signature.
466 * If we we do, our the calculated HMAC should match theirs.
468 * @param string $post raw XML source as POSTed to us
469 * @param string $hmac X-Hub-Signature HTTP header value, or empty
470 * @return boolean true for a match
472 protected function validatePushSig($post, $hmac)
475 if (preg_match('/^sha1=([0-9a-fA-F]{40})$/', $hmac, $matches)) {
476 $their_hmac = strtolower($matches[1]);
477 $our_hmac = hash_hmac('sha1', $post, $this->secret);
478 if ($their_hmac === $our_hmac) {
481 if (common_config('feedsub', 'debug')) {
482 $tempfile = tempnam(sys_get_temp_dir(), 'feedsub-receive');
484 file_put_contents($tempfile, $post);
486 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");
488 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");
491 common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH with bogus HMAC '$hmac'");
497 common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH with unexpected HMAC '$hmac'");