HubSub.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. <?php
  2. /*
  3. * StatusNet - the distributed open-source microblogging tool
  4. * Copyright (C) 2010, StatusNet, Inc.
  5. *
  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.
  10. *
  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.
  15. *
  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/>.
  18. */
  19. if (!defined('GNUSOCIAL')) { exit(1); }
  20. /**
  21. * WebSub (previously PuSH) feed subscription record
  22. * @package Hub
  23. * @author Brion Vibber <brion@status.net>
  24. */
  25. class HubSub extends Managed_DataObject
  26. {
  27. public $__table = 'hubsub';
  28. public $hashkey; // sha1(topic . '|' . $callback); (topic, callback) key is too long for myisam in utf8
  29. public $topic; // varchar(191) not 255 because utf8mb4 takes more space
  30. public $callback; // varchar(191) not 255 because utf8mb4 takes more space
  31. public $secret;
  32. public $sub_start;
  33. public $sub_end;
  34. public $created;
  35. public $modified;
  36. static function hashkey($topic, $callback)
  37. {
  38. return sha1($topic . '|' . $callback);
  39. }
  40. public static function getByHashkey($topic, $callback)
  41. {
  42. return self::getKV('hashkey', self::hashkey($topic, $callback));
  43. }
  44. public static function schemaDef()
  45. {
  46. return array(
  47. 'fields' => array(
  48. 'hashkey' => array('type' => 'char', 'not null' => true, 'length' => 40, 'description' => 'HubSub hashkey'),
  49. 'topic' => array('type' => 'varchar', 'not null' => true, 'length' => 191, 'description' => 'HubSub topic'),
  50. 'callback' => array('type' => 'varchar', 'not null' => true, 'length' => 191, 'description' => 'HubSub callback'),
  51. 'secret' => array('type' => 'text', 'description' => 'HubSub stored secret'),
  52. 'sub_start' => array('type' => 'datetime', 'description' => 'subscription start'),
  53. 'sub_end' => array('type' => 'datetime', 'description' => 'subscription end'),
  54. 'errors' => array('type' => 'int', 'not null' => true, 'default' => 0, 'description' => 'Queue handling error count, is reset on success.'),
  55. 'error_start' => array('type' => 'datetime', 'default' => null, 'description' => 'time of first error since latest success, should be null if no errors have been counted'),
  56. 'last_error' => array('type' => 'datetime', 'default' => null, 'description' => 'time of last failure, if ever'),
  57. 'last_error_msg' => array('type' => 'text', 'default' => null, 'description' => 'Last error _message_'),
  58. 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
  59. 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
  60. ),
  61. 'primary key' => array('hashkey'),
  62. 'indexes' => array(
  63. 'hubsub_callback_idx' => array('callback'),
  64. 'hubsub_topic_idx' => array('topic'),
  65. ),
  66. );
  67. }
  68. function getErrors()
  69. {
  70. return intval($this->errors);
  71. }
  72. // $msg is only set if $error_count is 0
  73. function setErrors($error_count, $msg=null)
  74. {
  75. assert(is_int($error_count));
  76. if (!is_int($error_count) || $error_count < 0) {
  77. common_log(LOG_ERR, 'HubSub->setErrors was given a bad value: '._ve($error_count));
  78. throw new ServerException('HubSub error count must be an integer higher or equal to 0.');
  79. }
  80. $orig = clone($this);
  81. $now = common_sql_now();
  82. if ($error_count === 1) {
  83. // Record when the errors started
  84. $this->error_start = $now;
  85. }
  86. if ($error_count > 0) {
  87. // Record this error's occurrence in time
  88. $this->last_error = $now;
  89. $this->last_error_msg = $msg;
  90. } else {
  91. $this->error_start = null;
  92. $this->last_error = null;
  93. $this->last_error_msg = null;
  94. }
  95. $this->errors = $error_count;
  96. $this->update($orig);
  97. }
  98. function resetErrors()
  99. {
  100. return $this->setErrors(0);
  101. }
  102. function incrementErrors($msg=null)
  103. {
  104. return $this->setErrors($this->getErrors()+1, $msg);
  105. }
  106. /**
  107. * Validates a requested lease length, sets length plus
  108. * subscription start & end dates.
  109. *
  110. * Does not save to database -- use before insert() or update().
  111. *
  112. * @param int $length in seconds
  113. */
  114. function setLease($length)
  115. {
  116. common_debug('WebSub hub got requested lease_seconds=='._ve($length));
  117. assert(is_int($length));
  118. $min = 86400; // 3600*24 (one day)
  119. $max = 86400 * 30;
  120. if ($length == 0) {
  121. // We want to garbage collect dead subscriptions!
  122. $length = $max;
  123. } elseif( $length < $min) {
  124. $length = $min;
  125. } else if ($length > $max) {
  126. $length = $max;
  127. }
  128. common_debug('WebSub hub after sanitation: lease_seconds=='._ve($length));
  129. $this->sub_start = common_sql_now();
  130. $this->sub_end = common_sql_date(time() + $length);
  131. }
  132. function getLeaseTime()
  133. {
  134. if (empty($this->sub_start) || empty($this->sub_end)) {
  135. return null;
  136. }
  137. $length = strtotime($this->sub_end) - strtotime($this->sub_start);
  138. assert($length > 0);
  139. return $length;
  140. }
  141. function getLeaseRemaining()
  142. {
  143. if (empty($this->sub_end)) {
  144. return null;
  145. }
  146. return strtotime($this->sub_end) - time();
  147. }
  148. /**
  149. * Schedule a future verification ping to the subscriber.
  150. * If queues are disabled, will be immediate.
  151. *
  152. * @param string $mode 'subscribe' or 'unsubscribe'
  153. * @param string $token hub.verify_token value, if provided by client
  154. */
  155. function scheduleVerify($mode, $token=null, $retries=null)
  156. {
  157. if ($retries === null) {
  158. $retries = intval(common_config('ostatus', 'hub_retries'));
  159. }
  160. $data = array('sub' => clone($this),
  161. 'mode' => $mode,
  162. 'token' => $token, // let's put it in there if remote uses PuSH <0.4
  163. 'retries' => $retries);
  164. $qm = QueueManager::get();
  165. $qm->enqueue($data, 'hubconf');
  166. }
  167. public function getTopic()
  168. {
  169. return $this->topic;
  170. }
  171. /**
  172. * Send a verification ping to subscriber, and if confirmed apply the changes.
  173. * This may create, update, or delete the database record.
  174. *
  175. * @param string $mode 'subscribe' or 'unsubscribe'
  176. * @param string $token hub.verify_token value, if provided by client
  177. * @throws ClientException on failure
  178. */
  179. function verify($mode, $token=null)
  180. {
  181. assert($mode == 'subscribe' || $mode == 'unsubscribe');
  182. $challenge = common_random_hexstr(32);
  183. $params = array('hub.mode' => $mode,
  184. 'hub.topic' => $this->getTopic(),
  185. 'hub.challenge' => $challenge);
  186. if ($mode == 'subscribe') {
  187. $params['hub.lease_seconds'] = $this->getLeaseTime();
  188. }
  189. if ($token !== null) { // TODO: deprecated in PuSH 0.4
  190. $params['hub.verify_token'] = $token; // let's put it in there if remote uses PuSH <0.4
  191. }
  192. // Any existing query string parameters must be preserved
  193. $url = $this->callback;
  194. if (strpos($url, '?') !== false) {
  195. $url .= '&';
  196. } else {
  197. $url .= '?';
  198. }
  199. $url .= http_build_query($params, '', '&');
  200. $request = new HTTPClient();
  201. $response = $request->get($url);
  202. $status = $response->getStatus();
  203. if ($status >= 200 && $status < 300) {
  204. common_log(LOG_INFO, "Verified {$mode} of {$this->callback}:{$this->getTopic()}");
  205. } else {
  206. // TRANS: Client exception. %s is a HTTP status code.
  207. throw new ClientException(sprintf(_m('Hub subscriber verification returned HTTP %s.'),$status));
  208. }
  209. $old = HubSub::getByHashkey($this->getTopic(), $this->callback);
  210. if ($mode == 'subscribe') {
  211. if ($old instanceof HubSub) {
  212. $this->update($old);
  213. } else {
  214. $ok = $this->insert();
  215. }
  216. } else if ($mode == 'unsubscribe') {
  217. if ($old instanceof HubSub) {
  218. $old->delete();
  219. } else {
  220. // That's ok, we're already unsubscribed.
  221. }
  222. }
  223. }
  224. // set the hashkey automagically on insert
  225. protected function onInsert()
  226. {
  227. $this->setHashkey();
  228. $this->created = common_sql_now();
  229. $this->modified = common_sql_now();
  230. }
  231. // update the hashkey automagically if needed
  232. protected function onUpdateKeys(Managed_DataObject $orig)
  233. {
  234. if ($this->topic !== $orig->topic || $this->callback !== $orig->callback) {
  235. $this->setHashkey();
  236. }
  237. }
  238. protected function setHashkey()
  239. {
  240. $this->hashkey = self::hashkey($this->topic, $this->callback);
  241. }
  242. /**
  243. * Schedule delivery of a 'fat ping' to the subscriber's callback
  244. * endpoint. If queues are disabled, this will run immediately.
  245. *
  246. * @param string $atom well-formed Atom feed
  247. * @param int $retries optional count of retries if POST fails; defaults to hub_retries from config or 0 if unset
  248. */
  249. function distribute($atom, $retries=null)
  250. {
  251. if ($retries === null) {
  252. $retries = intval(common_config('ostatus', 'hub_retries'));
  253. }
  254. $data = array('topic' => $this->getTopic(),
  255. 'callback' => $this->callback,
  256. 'atom' => $atom,
  257. 'retries' => $retries);
  258. common_log(LOG_INFO, sprintf('Queuing WebSub: %s to %s', _ve($data['topic']), _ve($data['callback'])));
  259. $qm = QueueManager::get();
  260. $qm->enqueue($data, 'hubout');
  261. }
  262. /**
  263. * Queue up a large batch of pushes to multiple subscribers
  264. * for this same topic update.
  265. *
  266. * If queues are disabled, this will run immediately.
  267. *
  268. * @param string $atom well-formed Atom feed
  269. * @param array $pushCallbacks list of callback URLs
  270. */
  271. function bulkDistribute($atom, array $pushCallbacks)
  272. {
  273. if (empty($pushCallbacks)) {
  274. common_log(LOG_ERR, 'Callback list empty for bulkDistribute.');
  275. return false;
  276. }
  277. $data = array('atom' => $atom,
  278. 'topic' => $this->getTopic(),
  279. 'pushCallbacks' => $pushCallbacks);
  280. common_log(LOG_INFO, "Queuing WebSub batch: {$this->getTopic()} to ".count($pushCallbacks)." sites");
  281. $qm = QueueManager::get();
  282. $qm->enqueue($data, 'hubprep');
  283. return true;
  284. }
  285. /**
  286. * @return boolean true/false for HTTP response
  287. * @throws Exception for lower-than-HTTP errors (such as NS lookup failure, connection refused...)
  288. */
  289. public static function pushAtom($topic, $callback, $atom, $secret=null, $hashalg='sha1')
  290. {
  291. $headers = array('Content-Type: application/atom+xml');
  292. if ($secret) {
  293. $hmac = hash_hmac($hashalg, $atom, $secret);
  294. $headers[] = "X-Hub-Signature: {$hashalg}={$hmac}";
  295. } else {
  296. $hmac = '(none)';
  297. }
  298. common_log(LOG_INFO, sprintf('About to WebSub-push feed to %s for %s, HMAC %s', _ve($callback), _ve($topic), _ve($hmac)));
  299. $request = new HTTPClient();
  300. $request->setConfig(array('follow_redirects' => false));
  301. $request->setBody($atom);
  302. // This will throw exception on non-HTTP failures
  303. try {
  304. $response = $request->post($callback, $headers);
  305. } catch (Exception $e) {
  306. 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())));
  307. throw $e;
  308. }
  309. return $response->isOk();
  310. }
  311. /**
  312. * Send a 'fat ping' to the subscriber's callback endpoint
  313. * containing the given Atom feed chunk.
  314. *
  315. * Determination of which feed items to send should be done at
  316. * a higher level; don't just shove in a complete feed!
  317. *
  318. * FIXME: Add 'failed' incremental count.
  319. *
  320. * @param string $atom well-formed Atom feed
  321. * @return boolean Whether the PuSH was accepted or not.
  322. * @throws Exception (HTTP or general)
  323. */
  324. function push($atom)
  325. {
  326. try {
  327. $success = self::pushAtom($this->getTopic(), $this->callback, $atom, $this->secret);
  328. if ($success) {
  329. return true;
  330. } elseif ('https' === parse_url($this->callback, PHP_URL_SCHEME)) {
  331. // Already HTTPS, no need to check remote http/https migration issues
  332. return false;
  333. }
  334. // if pushAtom returned false and we didn't try an HTTPS endpoint,
  335. // let's try HTTPS too (assuming only http:// and https:// are used ;))
  336. } catch (Exception $e) {
  337. if ('https' === parse_url($this->callback, PHP_URL_SCHEME)) {
  338. // Already HTTPS, no need to check remote http/https migration issues
  339. throw $e;
  340. }
  341. }
  342. // We failed the WebSub push, but it might be that the remote site has changed their configuration to HTTPS
  343. common_debug('WebSub HTTPSFIX: push failed, so we need to see if it can be the remote http->https migration issue.');
  344. // XXX: DO NOT trust a Location header here, _especially_ from 'http' protocols,
  345. // but not 'https' either at least if we don't do proper CA verification. Trust that
  346. // the most common change here is simply switching 'http' to 'https' and we will
  347. // solve 99% of all of these issues for now. There should be a proper mechanism
  348. // if we want to change the callback URLs, preferrably just manual resubscriptions
  349. // from the remote side, combined with implemented WebSub subscription timeouts.
  350. // Test if the feed callback for this node has already been migrated to HTTPS in our database
  351. // (otherwise we'd get collisions when inserting it further down)
  352. $httpscallback = preg_replace('/^http/', 'https', $this->callback, 1);
  353. $alreadyreplaced = self::getByHashKey($this->getTopic(), $httpscallback);
  354. if ($alreadyreplaced instanceof HubSub) {
  355. // Let's remove the old HTTP callback object.
  356. $this->delete();
  357. // XXX: I think this means we might lose a message or two when
  358. // remote side migrates to HTTPS because we only try _once_
  359. // for _one_ WebSub push. The rest of the posts already
  360. // stored in our queue (if any) will not find a HubSub
  361. // object. This could maybe be fixed by handling migration
  362. // in HubOutQueueHandler while handling the item there.
  363. common_debug('WebSub HTTPSFIX: Pushing Atom to HTTPS callback instead of HTTP, because of switch to HTTPS since enrolled in queue.');
  364. return self::pushAtom($this->getTopic(), $httpscallback, $atom, $this->secret);
  365. }
  366. common_debug('WebSub HTTPSFIX: callback to '._ve($this->callback).' for '._ve($this->getTopic()).' trying HTTPS callback: '._ve($httpscallback));
  367. $success = self::pushAtom($this->getTopic(), $httpscallback, $atom, $this->secret);
  368. if ($success) {
  369. // Yay, we made a successful push to https://, let's remember this in the future!
  370. $orig = clone($this);
  371. $this->callback = $httpscallback;
  372. // NOTE: hashkey will be set in $this->onUpdateKeys($orig) through updateWithKeys
  373. $this->updateWithKeys($orig);
  374. return true;
  375. }
  376. // If there have been any exceptions thrown before, they're handled
  377. // higher up. This function's return value is just whether the WebSub
  378. // push was accepted or not.
  379. return $success;
  380. }
  381. }