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 generate random verification token
35 sends a sub request to the hub...
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
43 hub sends us updates via POST
46 class FeedDBException extends FeedSubException
50 function __construct($obj)
52 parent::__construct('Database insert failure');
58 * FeedSub handles low-level PubHubSubbub (PuSH) subscriptions.
59 * Higher-level behavior building OStatus stuff on top is handled
60 * under Ostatus_profile.
62 class FeedSub extends Managed_DataObject
64 public $__table = 'feedsub';
69 // PuSH subscription data
73 public $sub_state; // subscribe, active, unsubscribe, inactive
81 public static function schemaDef()
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'),
97 'primary key' => array('id'),
98 'unique keys' => array(
99 'feedsub_uri_key' => array('uri'),
105 * Fetch the StatusNet-side profile for this feed
108 public function localProfile()
110 if ($this->profile_id) {
111 return Profile::getKV('id', $this->profile_id);
117 * Fetch the StatusNet-side profile for this feed
120 public function localGroup()
122 if ($this->group_id) {
123 return User_group::getKV('id', $this->group_id);
129 * @param string $feeduri
131 * @throws FeedSubException if feed is invalid or lacks PuSH setup
133 public static function ensureFeed($feeduri)
135 $current = self::getKV('uri', $feeduri);
140 $discover = new FeedDiscovery();
141 $discover->discoverFromFeedURL($feeduri);
143 $huburi = $discover->getHubLink();
144 if (!$huburi && !common_config('feedsub', 'fallback_hub')) {
145 throw new FeedSubNoHubException();
148 $feedsub = new FeedSub();
149 $feedsub->uri = $feeduri;
150 $feedsub->huburi = $huburi;
151 $feedsub->sub_state = 'inactive';
153 $feedsub->created = common_sql_now();
154 $feedsub->modified = common_sql_now();
156 $result = $feedsub->insert();
157 if (empty($result)) {
158 throw new FeedDBException($feedsub);
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.
168 * @return bool true on success, false on failure
169 * @throws ServerException if feed state is not valid
171 public function subscribe($mode='subscribe')
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");
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.
185 // TRANS: Server exception.
186 throw new ServerException(_m('Attempting to start PuSH subscription for feed with no hub.'));
190 return $this->doSubscribe('subscribe');
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.
200 * @return bool true on success, false on failure
201 * @throws ServerException if feed state is not valid
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");
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.
216 // TRANS: Server exception.
217 throw new ServerException(_m('Attempting to end PuSH subscription for feed with no hub.'));
221 return $this->doSubscribe('unsubscribe');
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.
228 * @return boolean true if the subscription is now inactive, false if still active.
230 public function garbageCollect()
232 if ($this->sub_state == '' || $this->sub_state == 'inactive') {
233 // No active PuSH subscription, we can just leave it be.
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.
239 Event::handle('FeedSubSubscriberCount', array($this, &$count));
242 common_log(LOG_INFO, __METHOD__ . ': ok, ' . $count . ' user(s) left for ' . $this->uri);
245 common_log(LOG_INFO, __METHOD__ . ': unsubscribing, no users left for ' . $this->uri);
246 return $this->unsubscribe();
251 protected function doSubscribe($mode)
253 $orig = clone($this);
254 $this->verify_token = common_random_hexstr(16);
255 if ($mode == 'subscribe') {
256 $this->secret = common_random_hexstr(32);
258 $this->sub_state = $mode;
259 $this->update($orig);
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();
273 $hub = $this->huburi;
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);
283 throw new FeedSubException('WTF?');
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');
291 } else if ($status == 204) {
292 common_log(LOG_INFO, __METHOD__ . ': sub req ok and verified');
294 } else if ($status >= 200 && $status < 300) {
295 common_log(LOG_ERR, __METHOD__ . ": sub req returned unexpected HTTP $status: " . $response->getBody());
298 common_log(LOG_ERR, __METHOD__ . ": sub req failed with HTTP $status: " . $response->getBody());
301 } catch (Exception $e) {
303 common_log(LOG_ERR, __METHOD__ . ": error \"{$e->getMessage()}\" hitting hub $this->huburi subscribing to $this->uri");
305 $orig = clone($this);
306 $this->verify_token = '';
307 $this->sub_state = 'inactive';
308 $this->update($orig);
316 * Save PuSH subscription confirmation.
317 * Sets approximate lease start and end times and finalizes state.
319 * @param int $lease_seconds provided hub.lease_seconds parameter, if given
321 public function confirmSubscribe($lease_seconds=0)
323 $original = clone($this);
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);
330 $this->sub_end = null;
332 $this->modified = common_sql_now();
334 return $this->update($original);
338 * Save PuSH unsubscription confirmation.
339 * Wipes active PuSH sub info and resets state.
341 public function confirmUnsubscribe()
343 $original = clone($this);
345 // @fixme these should all be null, but DB_DataObject doesn't save null values...?????
346 $this->verify_token = '';
348 $this->sub_state = '';
349 $this->sub_start = '';
351 $this->modified = common_sql_now();
353 return $this->update($original);
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.
361 * Not guaranteed to be running in an immediate POST context; may be run
362 * from a queue handler.
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.
367 * @param string $post source of Atom or RSS feed
368 * @param string $hmac X-Hub-Signature header, if present
370 public function receive($post, $hmac)
372 common_log(LOG_INFO, __METHOD__ . ": packet for \"$this->uri\"! $hmac $post");
374 if ($this->sub_state != 'active') {
375 common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH for inactive feed $this->uri (in state '$this->sub_state')");
380 common_log(LOG_ERR, __METHOD__ . ": ignoring empty post");
384 if (!$this->validatePushSig($post, $hmac)) {
385 // Per spec we silently drop input with a bad sig,
386 // while reporting receipt to the server.
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");
397 $orig = clone($this);
398 $this->last_update = common_sql_now();
399 $this->update($orig);
401 Event::handle('StartFeedSubReceive', array($this, $feed));
402 Event::handle('EndFeedSubReceive', array($this, $feed));
406 * Validate the given Atom chunk and HMAC signature against our
407 * shared secret that was set up at subscription time.
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.
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
416 protected function validatePushSig($post, $hmac)
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) {
425 if (common_config('feedsub', 'debug')) {
426 $tempfile = tempnam(sys_get_temp_dir(), 'feedsub-receive');
428 file_put_contents($tempfile, $post);
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");
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");
435 common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH with bogus HMAC '$hmac'");
441 common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH with unexpected HMAC '$hmac'");