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('STATUSNET')) {
25 * PuSH feed subscription record
27 * @author Brion Vibber <brion@status.net>
29 class HubSub extends Managed_DataObject
31 public $__table = 'hubsub';
33 public $hashkey; // sha1(topic . '|' . $callback); (topic, callback) key is too long for myisam in utf8
34 public $topic; // varchar(191) not 255 because utf8mb4 takes more space
35 public $callback; // varchar(191) not 255 because utf8mb4 takes more space
42 static function hashkey($topic, $callback)
44 return sha1($topic . '|' . $callback);
47 public static function getByHashkey($topic, $callback)
49 return self::getKV('hashkey', self::hashkey($topic, $callback));
52 public static function schemaDef()
56 'hashkey' => array('type' => 'char', 'not null' => true, 'length' => 40, 'description' => 'HubSub hashkey'),
57 'topic' => array('type' => 'varchar', 'not null' => true, 'length' => 191, 'description' => 'HubSub topic'),
58 'callback' => array('type' => 'varchar', 'not null' => true, 'length' => 191, 'description' => 'HubSub callback'),
59 'secret' => array('type' => 'text', 'description' => 'HubSub stored secret'),
60 'sub_start' => array('type' => 'datetime', 'description' => 'subscription start'),
61 'sub_end' => array('type' => 'datetime', 'description' => 'subscription end'),
62 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
63 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
65 'primary key' => array('hashkey'),
67 'hubsub_callback_idx' => array('callback'),
68 'hubsub_topic_idx' => array('topic'),
74 * Validates a requested lease length, sets length plus
75 * subscription start & end dates.
77 * Does not save to database -- use before insert() or update().
79 * @param int $length in seconds
81 function setLease($length)
83 common_debug('PuSH hub got requested lease_seconds=='._ve($length));
84 assert(is_int($length));
86 $min = 86400; // 3600*24 (one day)
90 // We want to garbage collect dead subscriptions!
92 } elseif( $length < $min) {
94 } else if ($length > $max) {
98 common_debug('PuSH hub after sanitation: lease_seconds=='._ve($length));
99 $this->sub_start = common_sql_now();
100 $this->sub_end = common_sql_date(time() + $length);
103 function getLeaseTime()
105 if (empty($this->sub_start) || empty($this->sub_end)) {
108 $length = strtotime($this->sub_end) - strtotime($this->sub_start);
113 function getLeaseRemaining()
115 if (empty($this->sub_end)) {
118 return strtotime($this->sub_end) - time();
122 * Schedule a future verification ping to the subscriber.
123 * If queues are disabled, will be immediate.
125 * @param string $mode 'subscribe' or 'unsubscribe'
126 * @param string $token hub.verify_token value, if provided by client
128 function scheduleVerify($mode, $token=null, $retries=null)
130 if ($retries === null) {
131 $retries = intval(common_config('ostatus', 'hub_retries'));
133 $data = array('sub' => clone($this),
135 'token' => $token, // let's put it in there if remote uses PuSH <0.4
136 'retries' => $retries);
137 $qm = QueueManager::get();
138 $qm->enqueue($data, 'hubconf');
141 public function getTopic()
147 * Send a verification ping to subscriber, and if confirmed apply the changes.
148 * This may create, update, or delete the database record.
150 * @param string $mode 'subscribe' or 'unsubscribe'
151 * @param string $token hub.verify_token value, if provided by client
152 * @throws ClientException on failure
154 function verify($mode, $token=null)
156 assert($mode == 'subscribe' || $mode == 'unsubscribe');
158 $challenge = common_random_hexstr(32);
159 $params = array('hub.mode' => $mode,
160 'hub.topic' => $this->getTopic(),
161 'hub.challenge' => $challenge);
162 if ($mode == 'subscribe') {
163 $params['hub.lease_seconds'] = $this->getLeaseTime();
165 if ($token !== null) { // TODO: deprecated in PuSH 0.4
166 $params['hub.verify_token'] = $token; // let's put it in there if remote uses PuSH <0.4
169 // Any existing query string parameters must be preserved
170 $url = $this->callback;
171 if (strpos($url, '?') !== false) {
176 $url .= http_build_query($params, '', '&');
178 $request = new HTTPClient();
179 $response = $request->get($url);
180 $status = $response->getStatus();
182 if ($status >= 200 && $status < 300) {
183 common_log(LOG_INFO, "Verified {$mode} of {$this->callback}:{$this->getTopic()}");
185 // TRANS: Client exception. %s is a HTTP status code.
186 throw new ClientException(sprintf(_m('Hub subscriber verification returned HTTP %s.'),$status));
189 $old = HubSub::getByHashkey($this->getTopic(), $this->callback);
190 if ($mode == 'subscribe') {
191 if ($old instanceof HubSub) {
194 $ok = $this->insert();
196 } else if ($mode == 'unsubscribe') {
197 if ($old instanceof HubSub) {
200 // That's ok, we're already unsubscribed.
206 * Insert wrapper; transparently set the hash key from topic and callback columns.
207 * @return mixed success
211 $this->hashkey = self::hashkey($this->getTopic(), $this->callback);
212 $this->created = common_sql_now();
213 $this->modified = common_sql_now();
214 return parent::insert();
218 * Schedule delivery of a 'fat ping' to the subscriber's callback
219 * endpoint. If queues are disabled, this will run immediately.
221 * @param string $atom well-formed Atom feed
222 * @param int $retries optional count of retries if POST fails; defaults to hub_retries from config or 0 if unset
224 function distribute($atom, $retries=null)
226 if ($retries === null) {
227 $retries = intval(common_config('ostatus', 'hub_retries'));
230 // We dare not clone() as when the clone is discarded it'll
231 // destroy the result data for the parent query.
232 // @fixme use clone() again when it's safe to copy an
233 // individual item from a multi-item query again.
234 $sub = HubSub::getByHashkey($this->getTopic(), $this->callback);
235 $data = array('sub' => $sub,
237 'retries' => $retries);
238 common_log(LOG_INFO, "Queuing PuSH: {$this->getTopic()} to {$this->callback}");
239 $qm = QueueManager::get();
240 $qm->enqueue($data, 'hubout');
244 * Queue up a large batch of pushes to multiple subscribers
245 * for this same topic update.
247 * If queues are disabled, this will run immediately.
249 * @param string $atom well-formed Atom feed
250 * @param array $pushCallbacks list of callback URLs
252 function bulkDistribute($atom, array $pushCallbacks)
254 if (empty($pushCallbacks)) {
255 common_log(LOG_ERR, 'Callback list empty for bulkDistribute.');
258 $data = array('atom' => $atom,
259 'topic' => $this->getTopic(),
260 'pushCallbacks' => $pushCallbacks);
261 common_log(LOG_INFO, "Queuing PuSH batch: {$this->getTopic()} to ".count($pushCallbacks)." sites");
262 $qm = QueueManager::get();
263 $qm->enqueue($data, 'hubprep');
268 * Send a 'fat ping' to the subscriber's callback endpoint
269 * containing the given Atom feed chunk.
271 * Determination of which items to send should be done at
272 * a higher level; don't just shove in a complete feed!
274 * @param string $atom well-formed Atom feed
275 * @throws Exception (HTTP or general)
279 $headers = array('Content-Type: application/atom+xml');
281 $hmac = hash_hmac('sha1', $atom, $this->secret);
282 $headers[] = "X-Hub-Signature: sha1=$hmac";
286 common_log(LOG_INFO, "About to push feed to $this->callback for {$this->getTopic()}, HMAC $hmac");
288 $request = new HTTPClient();
289 $request->setConfig(array('follow_redirects' => false));
290 $request->setBody($atom);
292 $response = $request->post($this->callback, $headers);
294 if ($response->isOk()) {
297 } catch (Exception $e) {
300 common_debug('PuSH callback to '._ve($this->callback).' for '._ve($this->getTopic()).' failed with exception: '._ve($e->getMessage()));
303 // XXX: DO NOT trust a Location header here, _especially_ from 'http' protocols,
304 // but not 'https' either at least if we don't do proper CA verification. Trust that
305 // the most common change here is simply switching 'http' to 'https' and we will
306 // solve 99% of all of these issues for now. There should be a proper mechanism
307 // if we want to change the callback URLs, preferrably just manual resubscriptions
308 // from the remote side, combined with implemented PuSH subscription timeouts.
310 // We failed the PuSH, but it might be that the remote site has changed their configuration to HTTPS
311 if ('http' === parse_url($this->callback, PHP_URL_SCHEME)) {
312 // Test if the feed callback for this node has migrated to HTTPS
313 $httpscallback = preg_replace('/^http/', 'https', $this->callback, 1);
314 $alreadyreplaced = self::getByHashKey($this->getTopic(), $httpscallback);
315 if ($alreadyreplaced instanceof HubSub) {
317 throw new AlreadyFulfilledException('The remote side has already established an HTTPS callback, deleting the legacy HTTP entry.');
320 common_debug('PuSH callback to '._ve($this->callback).' for '._ve($this->getTopic()).' trying HTTPS callback: '._ve($httpscallback));
321 $response = $request->post($httpscallback, $headers);
322 if ($response->isOk()) {
323 $orig = clone($this);
324 $this->callback = $httpscallback;
325 $this->hashkey = self::hashkey($this->getTopic(), $this->callback);
326 $this->updateWithKeys($orig);
331 // FIXME: Add 'failed' incremental count for this callback.
333 if (is_null($response)) {
334 // This means we got a lower-than-HTTP level error, like domain not found or maybe connection refused
335 // This should be using a more distinguishable exception class, but for now this will do.
336 throw new Exception(sprintf(_m('HTTP request failed without response to URL: %s'), _ve(isset($httpscallback) ? $httpscallback : $this->callback)));
339 // TRANS: Exception. %1$s is a response status code, %2$s is the body of the response.
340 throw new Exception(sprintf(_m('Callback returned status: %1$s. Body: %2$s'),
341 $response->getStatus(),trim($response->getBody())));