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
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")', '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 * NOTE: does not respect if we have a fallback_hub configured
117 public function isPuSH()
119 return !empty($this->huburi);
123 * Fetch the StatusNet-side profile for this feed
126 public function localProfile()
128 if ($this->profile_id) {
129 return Profile::getKV('id', $this->profile_id);
135 * Fetch the StatusNet-side profile for this feed
138 public function localGroup()
140 if ($this->group_id) {
141 return User_group::getKV('id', $this->group_id);
147 * @param string $feeduri
149 * @throws FeedSubException if feed is invalid or lacks PuSH setup
151 public static function ensureFeed($feeduri)
153 $current = self::getKV('uri', $feeduri);
154 if ($current instanceof FeedSub) {
158 $discover = new FeedDiscovery();
159 $discover->discoverFromFeedURL($feeduri);
161 $huburi = $discover->getHubLink();
162 if (!$huburi && !common_config('feedsub', 'fallback_hub')) {
163 throw new FeedSubNoHubException();
166 $feedsub = new FeedSub();
167 $feedsub->uri = $feeduri;
168 $feedsub->huburi = $huburi;
169 $feedsub->sub_state = 'inactive';
171 $feedsub->created = common_sql_now();
172 $feedsub->modified = common_sql_now();
174 $result = $feedsub->insert();
175 if ($result === false) {
176 throw new FeedDBException($feedsub);
183 * Send a subscription request to the hub for this feed.
184 * The hub will later send us a confirmation POST to /main/push/callback.
186 * @return bool true on success, false on failure
187 * @throws ServerException if feed state is not valid
189 public function subscribe()
191 if ($this->sub_state && $this->sub_state != 'inactive') {
192 common_log(LOG_WARNING, "Attempting to (re)start PuSH subscription to {$this->uri} in unexpected state {$this->sub_state}");
195 if (!Event::handle('FeedSubscribe', array($this))) {
196 // A plugin handled it
200 if (empty($this->huburi)) {
201 if (common_config('feedsub', 'fallback_hub')) {
202 // No native hub on this feed?
203 // Use our fallback hub, which handles polling on our behalf.
204 } else if (common_config('feedsub', 'nohub')) {
205 // Fake it! We're just testing remote feeds w/o hubs.
206 // We'll never actually get updates in this mode.
209 // TRANS: Server exception.
210 throw new ServerException(_m('Attempting to start PuSH subscription for feed with no hub.'));
214 return $this->doSubscribe('subscribe');
218 * Send a PuSH unsubscription request to the hub for this feed.
219 * The hub will later send us a confirmation POST to /main/push/callback.
220 * Warning: this will cancel the subscription even if someone else in
221 * the system is using it. Most callers will want garbageCollect() instead,
222 * which confirms there's no uses left.
224 * @return bool true on success, false on failure
225 * @throws ServerException if feed state is not valid
227 public function unsubscribe() {
228 if ($this->sub_state != 'active') {
229 common_log(LOG_WARNING, "Attempting to (re)end PuSH subscription to {$this->uri} in unexpected state {$this->sub_state}");
232 if (!Event::handle('FeedUnsubscribe', array($this))) {
233 // A plugin handled it
237 if (empty($this->huburi)) {
238 if (common_config('feedsub', 'fallback_hub')) {
239 // No native hub on this feed?
240 // Use our fallback hub, which handles polling on our behalf.
241 } else if (common_config('feedsub', 'nohub')) {
242 // Fake it! We're just testing remote feeds w/o hubs.
243 // We'll never actually get updates in this mode.
246 // TRANS: Server exception.
247 throw new ServerException(_m('Attempting to end PuSH subscription for feed with no hub.'));
251 return $this->doSubscribe('unsubscribe');
255 * Check if there are any active local uses of this feed, and if not then
256 * make sure it's inactive, unsubscribing if necessary.
258 * @return boolean true if the subscription is now inactive, false if still active.
260 public function garbageCollect()
262 if ($this->sub_state == '' || $this->sub_state == 'inactive') {
263 // No active PuSH subscription, we can just leave it be.
266 // PuSH subscription is either active or in an indeterminate state.
267 // Check if we're out of subscribers, and if so send an unsubscribe.
269 Event::handle('FeedSubSubscriberCount', array($this, &$count));
272 common_log(LOG_INFO, __METHOD__ . ': ok, ' . $count . ' user(s) left for ' . $this->uri);
275 common_log(LOG_INFO, __METHOD__ . ': unsubscribing, no users left for ' . $this->uri);
276 return $this->unsubscribe();
281 static public function renewalCheck()
284 // the "" empty string check is because we historically haven't saved unsubscribed feeds as NULL
285 $fs->whereAdd('sub_end IS NOT NULL AND sub_end!="" AND sub_end < NOW() - INTERVAL 1 day');
286 if (!$fs->find()) { // find can be both false and 0, depending on why nothing was found
287 throw new NoResultException($fs);
292 public function renew()
298 * Setting to subscribe means it is _waiting_ to become active. This
299 * cannot be done in a transaction because there is a chance that the
300 * remote script we're calling (as in the case of PuSHpress) performs
301 * the lookup _while_ we're POSTing data, which means the transaction
302 * never completes (PushcallbackAction gets an 'inactive' state).
304 * @return boolean true on successful sub/unsub, false on failure
306 protected function doSubscribe($mode)
308 $orig = clone($this);
309 if ($mode == 'subscribe') {
310 $this->secret = common_random_hexstr(32);
312 $this->sub_state = $mode;
313 $this->update($orig);
317 $callback = common_local_url('pushcallback', array('feed' => $this->id));
318 $headers = array('Content-Type: application/x-www-form-urlencoded');
319 $post = array('hub.mode' => $mode,
320 'hub.callback' => $callback,
321 'hub.verify' => 'async', // TODO: deprecated, remove when noone uses PuSH <0.4 (only 'async' method used there)
322 'hub.verify_token' => 'Deprecated-since-PuSH-0.4', // TODO: rm!
324 'hub.secret' => $this->secret,
325 'hub.topic' => $this->uri);
326 $client = new HTTPClient();
328 $hub = $this->huburi;
330 if (common_config('feedsub', 'fallback_hub')) {
331 $hub = common_config('feedsub', 'fallback_hub');
332 if (common_config('feedsub', 'hub_user')) {
333 $u = common_config('feedsub', 'hub_user');
334 $p = common_config('feedsub', 'hub_pass');
335 $client->setAuth($u, $p);
338 throw new FeedSubException('WTF?');
341 $response = $client->post($hub, $headers, $post);
342 $status = $response->getStatus();
343 if ($status == 202) {
344 common_log(LOG_INFO, __METHOD__ . ': sub req ok, awaiting verification callback');
346 } else if ($status >= 200 && $status < 300) {
347 common_log(LOG_ERR, __METHOD__ . ": sub req returned unexpected HTTP $status: " . $response->getBody());
349 common_log(LOG_ERR, __METHOD__ . ": sub req failed with HTTP $status: " . $response->getBody());
351 } catch (Exception $e) {
353 common_log(LOG_ERR, __METHOD__ . ": error \"{$e->getMessage()}\" hitting hub $this->huburi subscribing to $this->uri");
355 $orig = clone($this);
356 $this->sub_state = 'inactive';
357 $this->update($orig);
364 * Save PuSH subscription confirmation.
365 * Sets approximate lease start and end times and finalizes state.
367 * @param int $lease_seconds provided hub.lease_seconds parameter, if given
369 public function confirmSubscribe($lease_seconds)
371 $original = clone($this);
373 $this->sub_state = 'active';
374 $this->sub_start = common_sql_date(time());
375 if ($lease_seconds > 0) {
376 $this->sub_end = common_sql_date(time() + $lease_seconds);
378 $this->sub_end = null; // Backwards compatibility to StatusNet (PuSH <0.4 supported permanent subs)
380 $this->modified = common_sql_now();
382 return $this->update($original);
386 * Save PuSH unsubscription confirmation.
387 * Wipes active PuSH sub info and resets state.
389 public function confirmUnsubscribe()
391 $original = clone($this);
393 // @fixme these should all be null, but DB_DataObject doesn't save null values...?????
395 $this->sub_state = '';
396 $this->sub_start = '';
398 $this->modified = common_sql_now();
400 return $this->update($original);
404 * Accept updates from a PuSH feed. If validated, this object and the
405 * feed (as a DOMDocument) will be passed to the StartFeedSubHandleFeed
406 * and EndFeedSubHandleFeed events for processing.
408 * Not guaranteed to be running in an immediate POST context; may be run
409 * from a queue handler.
411 * Side effects: the feedsub record's lastupdate field will be updated
412 * to the current time (not published time) if we got a legit update.
414 * @param string $post source of Atom or RSS feed
415 * @param string $hmac X-Hub-Signature header, if present
417 public function receive($post, $hmac)
419 common_log(LOG_INFO, __METHOD__ . ": packet for \"$this->uri\"! $hmac $post");
421 if ($this->sub_state != 'active') {
422 common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH for inactive feed $this->uri (in state '$this->sub_state')");
427 common_log(LOG_ERR, __METHOD__ . ": ignoring empty post");
431 if (!$this->validatePushSig($post, $hmac)) {
432 // Per spec we silently drop input with a bad sig,
433 // while reporting receipt to the server.
437 $feed = new DOMDocument();
438 if (!$feed->loadXML($post)) {
439 // @fixme might help to include the err message
440 common_log(LOG_ERR, __METHOD__ . ": ignoring invalid XML");
444 $orig = clone($this);
445 $this->last_update = common_sql_now();
446 $this->update($orig);
448 Event::handle('StartFeedSubReceive', array($this, $feed));
449 Event::handle('EndFeedSubReceive', array($this, $feed));
453 * Validate the given Atom chunk and HMAC signature against our
454 * shared secret that was set up at subscription time.
456 * If we don't have a shared secret, there should be no signature.
457 * If we we do, our the calculated HMAC should match theirs.
459 * @param string $post raw XML source as POSTed to us
460 * @param string $hmac X-Hub-Signature HTTP header value, or empty
461 * @return boolean true for a match
463 protected function validatePushSig($post, $hmac)
466 if (preg_match('/^sha1=([0-9a-fA-F]{40})$/', $hmac, $matches)) {
467 $their_hmac = strtolower($matches[1]);
468 $our_hmac = hash_hmac('sha1', $post, $this->secret);
469 if ($their_hmac === $our_hmac) {
472 if (common_config('feedsub', 'debug')) {
473 $tempfile = tempnam(sys_get_temp_dir(), 'feedsub-receive');
475 file_put_contents($tempfile, $post);
477 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");
479 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");
482 common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH with bogus HMAC '$hmac'");
488 common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH with unexpected HMAC '$hmac'");