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/>.
21 * @package OStatusPlugin
22 * @maintainer Brion Vibber <brion@status.net>
26 PuSH subscription flow:
29 generate random verification token
31 sends a sub request to the hub...
34 hub sends confirmation back to us via GET
35 We verify the request, then echo back the challenge.
36 On our end, we save the time we subscribed and the lease expiration
39 hub sends us updates via POST
42 class FeedDBException extends FeedSubException
46 function __construct($obj)
48 parent::__construct('Database insert failure');
54 * FeedSub handles low-level PubHubSubbub (PuSH) subscriptions.
55 * Higher-level behavior building OStatus stuff on top is handled
56 * under Ostatus_profile.
58 class FeedSub extends Memcached_DataObject
60 public $__table = 'feedsub';
65 // PuSH subscription data
69 public $sub_state; // subscribe, active, unsubscribe, inactive
77 public /*static*/ function staticGet($k, $v=null)
79 return parent::staticGet(__CLASS__, $k, $v);
83 * return table definition for DB_DataObject
85 * DB_DataObject needs to know something about the table to manipulate
86 * instances. This method provides all the DB_DataObject needs to know.
88 * @return array array of column definitions
92 return array('id' => DB_DATAOBJECT_INT + DB_DATAOBJECT_NOTNULL,
93 'uri' => DB_DATAOBJECT_STR + DB_DATAOBJECT_NOTNULL,
94 'huburi' => DB_DATAOBJECT_STR,
95 'secret' => DB_DATAOBJECT_STR,
96 'verify_token' => DB_DATAOBJECT_STR,
97 'sub_state' => DB_DATAOBJECT_STR + DB_DATAOBJECT_NOTNULL,
98 'sub_start' => DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME,
99 'sub_end' => DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME,
100 'last_update' => DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME,
101 'created' => DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME + DB_DATAOBJECT_NOTNULL,
102 'modified' => DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME + DB_DATAOBJECT_NOTNULL);
105 static function schemaDef()
107 return array(new ColumnDef('id', 'integer',
113 /*auto_increment*/ true),
114 new ColumnDef('uri', 'varchar',
116 new ColumnDef('huburi', 'text',
118 new ColumnDef('verify_token', 'text',
120 new ColumnDef('secret', 'text',
122 new ColumnDef('sub_state', "enum('subscribe','active','unsubscribe','inactive')",
124 new ColumnDef('sub_start', 'datetime',
126 new ColumnDef('sub_end', 'datetime',
128 new ColumnDef('last_update', 'datetime',
130 new ColumnDef('created', 'datetime',
132 new ColumnDef('modified', 'datetime',
137 * return key definitions for DB_DataObject
139 * DB_DataObject needs to know about keys that the table has; this function
142 * @return array key definitions
146 return array_keys($this->keyTypes());
150 * return key definitions for Memcached_DataObject
152 * Our caching system uses the same key definitions, but uses a different
153 * method to get them.
155 * @return array key definitions
159 return array('id' => 'K', 'uri' => 'U');
162 function sequenceKey()
164 return array('id', true, false);
168 * Fetch the StatusNet-side profile for this feed
171 public function localProfile()
173 if ($this->profile_id) {
174 return Profile::staticGet('id', $this->profile_id);
180 * Fetch the StatusNet-side profile for this feed
183 public function localGroup()
185 if ($this->group_id) {
186 return User_group::staticGet('id', $this->group_id);
192 * @param string $feeduri
194 * @throws FeedSubException if feed is invalid or lacks PuSH setup
196 public static function ensureFeed($feeduri)
198 $current = self::staticGet('uri', $feeduri);
203 $discover = new FeedDiscovery();
204 $discover->discoverFromFeedURL($feeduri);
206 $huburi = $discover->getHubLink();
207 if (!$huburi && !common_config('feedsub', 'fallback_hub')) {
208 throw new FeedSubNoHubException();
211 $feedsub = new FeedSub();
212 $feedsub->uri = $feeduri;
213 $feedsub->huburi = $huburi;
214 $feedsub->sub_state = 'inactive';
216 $feedsub->created = common_sql_now();
217 $feedsub->modified = common_sql_now();
219 $result = $feedsub->insert();
220 if (empty($result)) {
221 throw new FeedDBException($feedsub);
228 * Send a subscription request to the hub for this feed.
229 * The hub will later send us a confirmation POST to /main/push/callback.
231 * @return bool true on success, false on failure
232 * @throws ServerException if feed state is not valid
234 public function subscribe($mode='subscribe')
236 if ($this->sub_state && $this->sub_state != 'inactive') {
237 common_log(LOG_WARNING, "Attempting to (re)start PuSH subscription to $this->uri in unexpected state $this->sub_state");
239 if (empty($this->huburi)) {
240 if (common_config('feedsub', 'fallback_hub')) {
241 // No native hub on this feed?
242 // Use our fallback hub, which handles polling on our behalf.
243 } else if (common_config('feedsub', 'nohub')) {
244 // Fake it! We're just testing remote feeds w/o hubs.
245 // We'll never actually get updates in this mode.
248 throw new ServerException(_m('Attempting to start PuSH subscription for feed with no hub.'));
252 return $this->doSubscribe('subscribe');
256 * Send a PuSH unsubscription request to the hub for this feed.
257 * The hub will later send us a confirmation POST to /main/push/callback.
258 * Warning: this will cancel the subscription even if someone else in
259 * the system is using it. Most callers will want garbageCollect() instead,
260 * which confirms there's no uses left.
262 * @return bool true on success, false on failure
263 * @throws ServerException if feed state is not valid
265 public function unsubscribe() {
266 if ($this->sub_state != 'active') {
267 common_log(LOG_WARNING, "Attempting to (re)end PuSH subscription to $this->uri in unexpected state $this->sub_state");
269 if (empty($this->huburi)) {
270 if (common_config('feedsub', 'fallback_hub')) {
271 // No native hub on this feed?
272 // Use our fallback hub, which handles polling on our behalf.
273 } else if (common_config('feedsub', 'nohub')) {
274 // Fake it! We're just testing remote feeds w/o hubs.
275 // We'll never actually get updates in this mode.
278 throw new ServerException(_m('Attempting to end PuSH subscription for feed with no hub.'));
282 return $this->doSubscribe('unsubscribe');
286 * Check if there are any active local uses of this feed, and if not then
287 * make sure it's inactive, unsubscribing if necessary.
289 * @return boolean true if the subscription is now inactive, false if still active.
291 public function garbageCollect()
293 if ($this->sub_state == '' || $this->sub_state == 'inactive') {
294 // No active PuSH subscription, we can just leave it be.
297 // PuSH subscription is either active or in an indeterminate state.
298 // Check if we're out of subscribers, and if so send an unsubscribe.
300 Event::handle('FeedSubSubscriberCount', array($this, &$count));
303 common_log(LOG_INFO, __METHOD__ . ': ok, ' . $count . ' user(s) left for ' . $this->uri);
306 common_log(LOG_INFO, __METHOD__ . ': unsubscribing, no users left for ' . $this->uri);
307 return $this->unsubscribe();
312 protected function doSubscribe($mode)
314 $orig = clone($this);
315 $this->verify_token = common_good_rand(16);
316 if ($mode == 'subscribe') {
317 $this->secret = common_good_rand(32);
319 $this->sub_state = $mode;
320 $this->update($orig);
324 $callback = common_local_url('pushcallback', array('feed' => $this->id));
325 $headers = array('Content-Type: application/x-www-form-urlencoded');
326 $post = array('hub.mode' => $mode,
327 'hub.callback' => $callback,
328 'hub.verify' => 'sync',
329 'hub.verify_token' => $this->verify_token,
330 'hub.secret' => $this->secret,
331 'hub.topic' => $this->uri);
332 $client = new HTTPClient();
334 $hub = $this->huburi;
336 if (common_config('feedsub', 'fallback_hub')) {
337 $hub = common_config('feedsub', 'fallback_hub');
338 if (common_config('feedsub', 'hub_user')) {
339 $u = common_config('feedsub', 'hub_user');
340 $p = common_config('feedsub', 'hub_pass');
341 $client->setAuth($u, $p);
344 throw new FeedSubException('WTF?');
347 $response = $client->post($hub, $headers, $post);
348 $status = $response->getStatus();
349 if ($status == 202) {
350 common_log(LOG_INFO, __METHOD__ . ': sub req ok, awaiting verification callback');
352 } else if ($status == 204) {
353 common_log(LOG_INFO, __METHOD__ . ': sub req ok and verified');
355 } else if ($status >= 200 && $status < 300) {
356 common_log(LOG_ERR, __METHOD__ . ": sub req returned unexpected HTTP $status: " . $response->getBody());
359 common_log(LOG_ERR, __METHOD__ . ": sub req failed with HTTP $status: " . $response->getBody());
362 } catch (Exception $e) {
364 common_log(LOG_ERR, __METHOD__ . ": error \"{$e->getMessage()}\" hitting hub $this->huburi subscribing to $this->uri");
366 $orig = clone($this);
367 $this->verify_token = '';
368 $this->sub_state = 'inactive';
369 $this->update($orig);
377 * Save PuSH subscription confirmation.
378 * Sets approximate lease start and end times and finalizes state.
380 * @param int $lease_seconds provided hub.lease_seconds parameter, if given
382 public function confirmSubscribe($lease_seconds=0)
384 $original = clone($this);
386 $this->sub_state = 'active';
387 $this->sub_start = common_sql_date(time());
388 if ($lease_seconds > 0) {
389 $this->sub_end = common_sql_date(time() + $lease_seconds);
391 $this->sub_end = null;
393 $this->modified = common_sql_now();
395 return $this->update($original);
399 * Save PuSH unsubscription confirmation.
400 * Wipes active PuSH sub info and resets state.
402 public function confirmUnsubscribe()
404 $original = clone($this);
406 // @fixme these should all be null, but DB_DataObject doesn't save null values...?????
407 $this->verify_token = '';
409 $this->sub_state = '';
410 $this->sub_start = '';
412 $this->modified = common_sql_now();
414 return $this->update($original);
418 * Accept updates from a PuSH feed. If validated, this object and the
419 * feed (as a DOMDocument) will be passed to the StartFeedSubHandleFeed
420 * and EndFeedSubHandleFeed events for processing.
422 * Not guaranteed to be running in an immediate POST context; may be run
423 * from a queue handler.
425 * Side effects: the feedsub record's lastupdate field will be updated
426 * to the current time (not published time) if we got a legit update.
428 * @param string $post source of Atom or RSS feed
429 * @param string $hmac X-Hub-Signature header, if present
431 public function receive($post, $hmac)
433 common_log(LOG_INFO, __METHOD__ . ": packet for \"$this->uri\"! $hmac $post");
435 if ($this->sub_state != 'active') {
436 common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH for inactive feed $this->uri (in state '$this->sub_state')");
441 common_log(LOG_ERR, __METHOD__ . ": ignoring empty post");
445 if (!$this->validatePushSig($post, $hmac)) {
446 // Per spec we silently drop input with a bad sig,
447 // while reporting receipt to the server.
451 $feed = new DOMDocument();
452 if (!$feed->loadXML($post)) {
453 // @fixme might help to include the err message
454 common_log(LOG_ERR, __METHOD__ . ": ignoring invalid XML");
458 $orig = clone($this);
459 $this->last_update = common_sql_now();
460 $this->update($orig);
462 Event::handle('StartFeedSubReceive', array($this, $feed));
463 Event::handle('EndFeedSubReceive', array($this, $feed));
467 * Validate the given Atom chunk and HMAC signature against our
468 * shared secret that was set up at subscription time.
470 * If we don't have a shared secret, there should be no signature.
471 * If we we do, our the calculated HMAC should match theirs.
473 * @param string $post raw XML source as POSTed to us
474 * @param string $hmac X-Hub-Signature HTTP header value, or empty
475 * @return boolean true for a match
477 protected function validatePushSig($post, $hmac)
480 if (preg_match('/^sha1=([0-9a-fA-F]{40})$/', $hmac, $matches)) {
481 $their_hmac = strtolower($matches[1]);
482 $our_hmac = hash_hmac('sha1', $post, $this->secret);
483 if ($their_hmac === $our_hmac) {
486 common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH with bad SHA-1 HMAC: got $their_hmac, expected $our_hmac");
488 common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH with bogus HMAC '$hmac'");
494 common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH with unexpected HMAC '$hmac'");