3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 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('GNUSOCIAL')) { exit(1); }
23 * WebSub (previously PuSH) feed subscription record
25 * @author Brion Vibber <brion@status.net>
27 class HubSub extends Managed_DataObject
29 public $__table = 'hubsub';
31 public $hashkey; // sha1(topic . '|' . $callback); (topic, callback) key is too long for myisam in utf8
32 public $topic; // varchar(191) not 255 because utf8mb4 takes more space
33 public $callback; // varchar(191) not 255 because utf8mb4 takes more space
40 static function hashkey($topic, $callback)
42 return sha1($topic . '|' . $callback);
45 public static function getByHashkey($topic, $callback)
47 return self::getKV('hashkey', self::hashkey($topic, $callback));
50 public static function schemaDef()
54 'hashkey' => array('type' => 'char', 'not null' => true, 'length' => 40, 'description' => 'HubSub hashkey'),
55 'topic' => array('type' => 'varchar', 'not null' => true, 'length' => 191, 'description' => 'HubSub topic'),
56 'callback' => array('type' => 'varchar', 'not null' => true, 'length' => 191, 'description' => 'HubSub callback'),
57 'secret' => array('type' => 'text', 'description' => 'HubSub stored secret'),
58 'sub_start' => array('type' => 'datetime', 'description' => 'subscription start'),
59 'sub_end' => array('type' => 'datetime', 'description' => 'subscription end'),
60 'errors' => array('type' => 'integer', 'not null' => true, 'default' => 0, 'description' => 'Queue handling error count, is reset on success.'),
61 'error_start' => array('type' => 'datetime', 'default' => null, 'description' => 'time of first error since latest success, should be null if no errors have been counted'),
62 'last_error' => array('type' => 'datetime', 'default' => null, 'description' => 'time of last failure, if ever'),
63 'last_error_msg' => array('type' => 'text', 'default' => null, 'description' => 'Last error _message_'),
64 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
65 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
67 'primary key' => array('hashkey'),
69 'hubsub_callback_idx' => array('callback'),
70 'hubsub_topic_idx' => array('topic'),
77 return intval($this->errors);
80 // $msg is only set if $error_count is 0
81 function setErrors($error_count, $msg=null)
83 assert(is_int($error_count));
84 if (!is_int($error_count) || $error_count < 0) {
85 common_log(LOG_ERR, 'HubSub->setErrors was given a bad value: '._ve($error_count));
86 throw new ServerException('HubSub error count must be an integer higher or equal to 0.');
90 $now = common_sql_now();
92 if ($error_count === 1) {
93 // Record when the errors started
94 $this->error_start = $now;
96 if ($error_count > 0) {
97 // Record this error's occurrence in time
98 $this->last_error = $now;
99 $this->last_error_msg = $msg;
101 $this->error_start = null;
102 $this->last_error = null;
103 $this->last_error_msg = null;
106 $this->errors = $error_count;
107 $this->update($orig);
110 function resetErrors()
112 return $this->setErrors(0);
115 function incrementErrors($msg=null)
117 return $this->setErrors($this->getErrors()+1, $msg);
121 * Validates a requested lease length, sets length plus
122 * subscription start & end dates.
124 * Does not save to database -- use before insert() or update().
126 * @param int $length in seconds
128 function setLease($length)
130 common_debug('WebSub hub got requested lease_seconds=='._ve($length));
131 assert(is_int($length));
133 $min = 86400; // 3600*24 (one day)
137 // We want to garbage collect dead subscriptions!
139 } elseif( $length < $min) {
141 } else if ($length > $max) {
145 common_debug('WebSub hub after sanitation: lease_seconds=='._ve($length));
146 $this->sub_start = common_sql_now();
147 $this->sub_end = common_sql_date(time() + $length);
150 function getLeaseTime()
152 if (empty($this->sub_start) || empty($this->sub_end)) {
155 $length = strtotime($this->sub_end) - strtotime($this->sub_start);
160 function getLeaseRemaining()
162 if (empty($this->sub_end)) {
165 return strtotime($this->sub_end) - time();
169 * Schedule a future verification ping to the subscriber.
170 * If queues are disabled, will be immediate.
172 * @param string $mode 'subscribe' or 'unsubscribe'
173 * @param string $token hub.verify_token value, if provided by client
175 function scheduleVerify($mode, $token=null, $retries=null)
177 if ($retries === null) {
178 $retries = intval(common_config('ostatus', 'hub_retries'));
180 $data = array('sub' => clone($this),
182 'token' => $token, // let's put it in there if remote uses PuSH <0.4
183 'retries' => $retries);
184 $qm = QueueManager::get();
185 $qm->enqueue($data, 'hubconf');
188 public function getTopic()
194 * Send a verification ping to subscriber, and if confirmed apply the changes.
195 * This may create, update, or delete the database record.
197 * @param string $mode 'subscribe' or 'unsubscribe'
198 * @param string $token hub.verify_token value, if provided by client
199 * @throws ClientException on failure
201 function verify($mode, $token=null)
203 assert($mode == 'subscribe' || $mode == 'unsubscribe');
205 $challenge = common_random_hexstr(32);
206 $params = array('hub.mode' => $mode,
207 'hub.topic' => $this->getTopic(),
208 'hub.challenge' => $challenge);
209 if ($mode == 'subscribe') {
210 $params['hub.lease_seconds'] = $this->getLeaseTime();
212 if ($token !== null) { // TODO: deprecated in PuSH 0.4
213 $params['hub.verify_token'] = $token; // let's put it in there if remote uses PuSH <0.4
216 // Any existing query string parameters must be preserved
217 $url = $this->callback;
218 if (strpos($url, '?') !== false) {
223 $url .= http_build_query($params, '', '&');
225 $request = new HTTPClient();
226 $response = $request->get($url);
227 $status = $response->getStatus();
229 if ($status >= 200 && $status < 300) {
230 common_log(LOG_INFO, "Verified {$mode} of {$this->callback}:{$this->getTopic()}");
232 // TRANS: Client exception. %s is a HTTP status code.
233 throw new ClientException(sprintf(_m('Hub subscriber verification returned HTTP %s.'),$status));
236 $old = HubSub::getByHashkey($this->getTopic(), $this->callback);
237 if ($mode == 'subscribe') {
238 if ($old instanceof HubSub) {
241 $ok = $this->insert();
243 } else if ($mode == 'unsubscribe') {
244 if ($old instanceof HubSub) {
247 // That's ok, we're already unsubscribed.
252 // set the hashkey automagically on insert
253 protected function onInsert()
256 $this->created = common_sql_now();
257 $this->modified = common_sql_now();
260 // update the hashkey automagically if needed
261 protected function onUpdateKeys(Managed_DataObject $orig)
263 if ($this->topic !== $orig->topic || $this->callback !== $orig->callback) {
268 protected function setHashkey()
270 $this->hashkey = self::hashkey($this->topic, $this->callback);
274 * Schedule delivery of a 'fat ping' to the subscriber's callback
275 * endpoint. If queues are disabled, this will run immediately.
277 * @param string $atom well-formed Atom feed
278 * @param int $retries optional count of retries if POST fails; defaults to hub_retries from config or 0 if unset
280 function distribute($atom, $retries=null)
282 if ($retries === null) {
283 $retries = intval(common_config('ostatus', 'hub_retries'));
286 $data = array('topic' => $this->getTopic(),
287 'callback' => $this->callback,
289 'retries' => $retries);
290 common_log(LOG_INFO, sprintf('Queuing WebSub: %s to %s', _ve($data['topic']), _ve($data['callback'])));
291 $qm = QueueManager::get();
292 $qm->enqueue($data, 'hubout');
296 * Queue up a large batch of pushes to multiple subscribers
297 * for this same topic update.
299 * If queues are disabled, this will run immediately.
301 * @param string $atom well-formed Atom feed
302 * @param array $pushCallbacks list of callback URLs
304 function bulkDistribute($atom, array $pushCallbacks)
306 if (empty($pushCallbacks)) {
307 common_log(LOG_ERR, 'Callback list empty for bulkDistribute.');
310 $data = array('atom' => $atom,
311 'topic' => $this->getTopic(),
312 'pushCallbacks' => $pushCallbacks);
313 common_log(LOG_INFO, "Queuing WebSub batch: {$this->getTopic()} to ".count($pushCallbacks)." sites");
314 $qm = QueueManager::get();
315 $qm->enqueue($data, 'hubprep');
320 * @return boolean true/false for HTTP response
321 * @throws Exception for lower-than-HTTP errors (such as NS lookup failure, connection refused...)
323 public static function pushAtom($topic, $callback, $atom, $secret=null, $hashalg='sha1')
325 $headers = array('Content-Type: application/atom+xml');
327 $hmac = hash_hmac($hashalg, $atom, $secret);
328 $headers[] = "X-Hub-Signature: {$hashalg}={$hmac}";
332 common_log(LOG_INFO, sprintf('About to WebSub-push feed to %s for %s, HMAC %s', _ve($callback), _ve($topic), _ve($hmac)));
334 $request = new HTTPClient();
335 $request->setConfig(array('follow_redirects' => false));
336 $request->setBody($atom);
338 // This will throw exception on non-HTTP failures
340 $response = $request->post($callback, $headers);
341 } catch (Exception $e) {
342 common_debug(sprintf('WebSub callback to %s for %s failed with exception %s: %s', _ve($callback), _ve($topic), _ve(get_class($e)), _ve($e->getMessage())));
346 return $response->isOk();
350 * Send a 'fat ping' to the subscriber's callback endpoint
351 * containing the given Atom feed chunk.
353 * Determination of which feed items to send should be done at
354 * a higher level; don't just shove in a complete feed!
356 * FIXME: Add 'failed' incremental count.
358 * @param string $atom well-formed Atom feed
359 * @return boolean Whether the PuSH was accepted or not.
360 * @throws Exception (HTTP or general)
365 $success = self::pushAtom($this->getTopic(), $this->callback, $atom, $this->secret);
368 } elseif ('https' === parse_url($this->callback, PHP_URL_SCHEME)) {
369 // Already HTTPS, no need to check remote http/https migration issues
372 // if pushAtom returned false and we didn't try an HTTPS endpoint,
373 // let's try HTTPS too (assuming only http:// and https:// are used ;))
375 } catch (Exception $e) {
376 if ('https' === parse_url($this->callback, PHP_URL_SCHEME)) {
377 // Already HTTPS, no need to check remote http/https migration issues
383 // We failed the WebSub push, but it might be that the remote site has changed their configuration to HTTPS
384 common_debug('WebSub HTTPSFIX: push failed, so we need to see if it can be the remote http->https migration issue.');
386 // XXX: DO NOT trust a Location header here, _especially_ from 'http' protocols,
387 // but not 'https' either at least if we don't do proper CA verification. Trust that
388 // the most common change here is simply switching 'http' to 'https' and we will
389 // solve 99% of all of these issues for now. There should be a proper mechanism
390 // if we want to change the callback URLs, preferrably just manual resubscriptions
391 // from the remote side, combined with implemented WebSub subscription timeouts.
393 // Test if the feed callback for this node has already been migrated to HTTPS in our database
394 // (otherwise we'd get collisions when inserting it further down)
395 $httpscallback = preg_replace('/^http/', 'https', $this->callback, 1);
396 $alreadyreplaced = self::getByHashKey($this->getTopic(), $httpscallback);
397 if ($alreadyreplaced instanceof HubSub) {
398 // Let's remove the old HTTP callback object.
401 // XXX: I think this means we might lose a message or two when
402 // remote side migrates to HTTPS because we only try _once_
403 // for _one_ WebSub push. The rest of the posts already
404 // stored in our queue (if any) will not find a HubSub
405 // object. This could maybe be fixed by handling migration
406 // in HubOutQueueHandler while handling the item there.
407 common_debug('WebSub HTTPSFIX: Pushing Atom to HTTPS callback instead of HTTP, because of switch to HTTPS since enrolled in queue.');
408 return self::pushAtom($this->getTopic(), $httpscallback, $atom, $this->secret);
411 common_debug('WebSub HTTPSFIX: callback to '._ve($this->callback).' for '._ve($this->getTopic()).' trying HTTPS callback: '._ve($httpscallback));
412 $success = self::pushAtom($this->getTopic(), $httpscallback, $atom, $this->secret);
414 // Yay, we made a successful push to https://, let's remember this in the future!
415 $orig = clone($this);
416 $this->callback = $httpscallback;
417 // NOTE: hashkey will be set in $this->onUpdateKeys($orig) through updateWithKeys
418 $this->updateWithKeys($orig);
422 // If there have been any exceptions thrown before, they're handled
423 // higher up. This function's return value is just whether the WebSub
424 // push was accepted or not.