HubSub.php 16 KB

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