HubSub.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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('STATUSNET')) {
  20. exit(1);
  21. }
  22. /**
  23. * 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. 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. 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
  57. 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
  58. ),
  59. 'primary key' => array('hashkey'),
  60. 'indexes' => array(
  61. 'hubsub_callback_idx' => array('callback'),
  62. 'hubsub_topic_idx' => array('topic'),
  63. ),
  64. );
  65. }
  66. /**
  67. * Validates a requested lease length, sets length plus
  68. * subscription start & end dates.
  69. *
  70. * Does not save to database -- use before insert() or update().
  71. *
  72. * @param int $length in seconds
  73. */
  74. function setLease($length)
  75. {
  76. common_debug('PuSH hub got requested lease_seconds=='._ve($length));
  77. assert(is_int($length));
  78. $min = 86400; // 3600*24 (one day)
  79. $max = 86400 * 30;
  80. if ($length == 0) {
  81. // We want to garbage collect dead subscriptions!
  82. $length = $max;
  83. } elseif( $length < $min) {
  84. $length = $min;
  85. } else if ($length > $max) {
  86. $length = $max;
  87. }
  88. common_debug('PuSH hub after sanitation: lease_seconds=='._ve($length));
  89. $this->sub_start = common_sql_now();
  90. $this->sub_end = common_sql_date(time() + $length);
  91. }
  92. function getLeaseTime()
  93. {
  94. if (empty($this->sub_start) || empty($this->sub_end)) {
  95. return null;
  96. }
  97. $length = strtotime($this->sub_end) - strtotime($this->sub_start);
  98. assert($length > 0);
  99. return $length;
  100. }
  101. function getLeaseRemaining()
  102. {
  103. if (empty($this->sub_end)) {
  104. return null;
  105. }
  106. return strtotime($this->sub_end) - time();
  107. }
  108. /**
  109. * Schedule a future verification ping to the subscriber.
  110. * If queues are disabled, will be immediate.
  111. *
  112. * @param string $mode 'subscribe' or 'unsubscribe'
  113. * @param string $token hub.verify_token value, if provided by client
  114. */
  115. function scheduleVerify($mode, $token=null, $retries=null)
  116. {
  117. if ($retries === null) {
  118. $retries = intval(common_config('ostatus', 'hub_retries'));
  119. }
  120. $data = array('sub' => clone($this),
  121. 'mode' => $mode,
  122. 'token' => $token, // let's put it in there if remote uses PuSH <0.4
  123. 'retries' => $retries);
  124. $qm = QueueManager::get();
  125. $qm->enqueue($data, 'hubconf');
  126. }
  127. public function getTopic()
  128. {
  129. return $this->topic;
  130. }
  131. /**
  132. * Send a verification ping to subscriber, and if confirmed apply the changes.
  133. * This may create, update, or delete the database record.
  134. *
  135. * @param string $mode 'subscribe' or 'unsubscribe'
  136. * @param string $token hub.verify_token value, if provided by client
  137. * @throws ClientException on failure
  138. */
  139. function verify($mode, $token=null)
  140. {
  141. assert($mode == 'subscribe' || $mode == 'unsubscribe');
  142. $challenge = common_random_hexstr(32);
  143. $params = array('hub.mode' => $mode,
  144. 'hub.topic' => $this->getTopic(),
  145. 'hub.challenge' => $challenge);
  146. if ($mode == 'subscribe') {
  147. $params['hub.lease_seconds'] = $this->getLeaseTime();
  148. }
  149. if ($token !== null) { // TODO: deprecated in PuSH 0.4
  150. $params['hub.verify_token'] = $token; // let's put it in there if remote uses PuSH <0.4
  151. }
  152. // Any existing query string parameters must be preserved
  153. $url = $this->callback;
  154. if (strpos($url, '?') !== false) {
  155. $url .= '&';
  156. } else {
  157. $url .= '?';
  158. }
  159. $url .= http_build_query($params, '', '&');
  160. $request = new HTTPClient();
  161. $response = $request->get($url);
  162. $status = $response->getStatus();
  163. if ($status >= 200 && $status < 300) {
  164. common_log(LOG_INFO, "Verified {$mode} of {$this->callback}:{$this->getTopic()}");
  165. } else {
  166. // TRANS: Client exception. %s is a HTTP status code.
  167. throw new ClientException(sprintf(_m('Hub subscriber verification returned HTTP %s.'),$status));
  168. }
  169. $old = HubSub::getByHashkey($this->getTopic(), $this->callback);
  170. if ($mode == 'subscribe') {
  171. if ($old instanceof HubSub) {
  172. $this->update($old);
  173. } else {
  174. $ok = $this->insert();
  175. }
  176. } else if ($mode == 'unsubscribe') {
  177. if ($old instanceof HubSub) {
  178. $old->delete();
  179. } else {
  180. // That's ok, we're already unsubscribed.
  181. }
  182. }
  183. }
  184. /**
  185. * Insert wrapper; transparently set the hash key from topic and callback columns.
  186. * @return mixed success
  187. */
  188. function insert()
  189. {
  190. $this->hashkey = self::hashkey($this->getTopic(), $this->callback);
  191. $this->created = common_sql_now();
  192. $this->modified = common_sql_now();
  193. return parent::insert();
  194. }
  195. /**
  196. * Schedule delivery of a 'fat ping' to the subscriber's callback
  197. * endpoint. If queues are disabled, this will run immediately.
  198. *
  199. * @param string $atom well-formed Atom feed
  200. * @param int $retries optional count of retries if POST fails; defaults to hub_retries from config or 0 if unset
  201. */
  202. function distribute($atom, $retries=null)
  203. {
  204. if ($retries === null) {
  205. $retries = intval(common_config('ostatus', 'hub_retries'));
  206. }
  207. // We dare not clone() as when the clone is discarded it'll
  208. // destroy the result data for the parent query.
  209. // @fixme use clone() again when it's safe to copy an
  210. // individual item from a multi-item query again.
  211. $sub = HubSub::getByHashkey($this->getTopic(), $this->callback);
  212. $data = array('sub' => $sub,
  213. 'atom' => $atom,
  214. 'retries' => $retries);
  215. common_log(LOG_INFO, "Queuing PuSH: {$this->getTopic()} to {$this->callback}");
  216. $qm = QueueManager::get();
  217. $qm->enqueue($data, 'hubout');
  218. }
  219. /**
  220. * Queue up a large batch of pushes to multiple subscribers
  221. * for this same topic update.
  222. *
  223. * If queues are disabled, this will run immediately.
  224. *
  225. * @param string $atom well-formed Atom feed
  226. * @param array $pushCallbacks list of callback URLs
  227. */
  228. function bulkDistribute($atom, array $pushCallbacks)
  229. {
  230. if (empty($pushCallbacks)) {
  231. common_log(LOG_ERR, 'Callback list empty for bulkDistribute.');
  232. return false;
  233. }
  234. $data = array('atom' => $atom,
  235. 'topic' => $this->getTopic(),
  236. 'pushCallbacks' => $pushCallbacks);
  237. common_log(LOG_INFO, "Queuing PuSH batch: {$this->getTopic()} to ".count($pushCallbacks)." sites");
  238. $qm = QueueManager::get();
  239. $qm->enqueue($data, 'hubprep');
  240. return true;
  241. }
  242. /**
  243. * Send a 'fat ping' to the subscriber's callback endpoint
  244. * containing the given Atom feed chunk.
  245. *
  246. * Determination of which items to send should be done at
  247. * a higher level; don't just shove in a complete feed!
  248. *
  249. * @param string $atom well-formed Atom feed
  250. * @throws Exception (HTTP or general)
  251. */
  252. function push($atom)
  253. {
  254. $headers = array('Content-Type: application/atom+xml');
  255. if ($this->secret) {
  256. $hmac = hash_hmac('sha1', $atom, $this->secret);
  257. $headers[] = "X-Hub-Signature: sha1=$hmac";
  258. } else {
  259. $hmac = '(none)';
  260. }
  261. common_log(LOG_INFO, "About to push feed to $this->callback for {$this->getTopic()}, HMAC $hmac");
  262. $request = new HTTPClient();
  263. $request->setConfig(array('follow_redirects' => false));
  264. $request->setBody($atom);
  265. try {
  266. $response = $request->post($this->callback, $headers);
  267. if ($response->isOk()) {
  268. return true;
  269. }
  270. } catch (Exception $e) {
  271. $response = null;
  272. common_debug('PuSH callback to '._ve($this->callback).' for '._ve($this->getTopic()).' failed with exception: '._ve($e->getMessage()));
  273. }
  274. // XXX: DO NOT trust a Location header here, _especially_ from 'http' protocols,
  275. // but not 'https' either at least if we don't do proper CA verification. Trust that
  276. // the most common change here is simply switching 'http' to 'https' and we will
  277. // solve 99% of all of these issues for now. There should be a proper mechanism
  278. // if we want to change the callback URLs, preferrably just manual resubscriptions
  279. // from the remote side, combined with implemented PuSH subscription timeouts.
  280. // We failed the PuSH, but it might be that the remote site has changed their configuration to HTTPS
  281. if ('http' === parse_url($this->callback, PHP_URL_SCHEME)) {
  282. // Test if the feed callback for this node has migrated to HTTPS
  283. $httpscallback = preg_replace('/^http/', 'https', $this->callback, 1);
  284. $alreadyreplaced = self::getByHashKey($this->getTopic(), $httpscallback);
  285. if ($alreadyreplaced instanceof HubSub) {
  286. $this->delete();
  287. throw new AlreadyFulfilledException('The remote side has already established an HTTPS callback, deleting the legacy HTTP entry.');
  288. }
  289. common_debug('PuSH callback to '._ve($this->callback).' for '._ve($this->getTopic()).' trying HTTPS callback: '._ve($httpscallback));
  290. $response = $request->post($httpscallback, $headers);
  291. if ($response->isOk()) {
  292. $orig = clone($this);
  293. $this->callback = $httpscallback;
  294. $this->hashkey = self::hashkey($this->getTopic(), $this->callback);
  295. $this->updateWithKeys($orig);
  296. return true;
  297. }
  298. }
  299. // FIXME: Add 'failed' incremental count for this callback.
  300. if (is_null($response)) {
  301. // This means we got a lower-than-HTTP level error, like domain not found or maybe connection refused
  302. // This should be using a more distinguishable exception class, but for now this will do.
  303. throw new Exception(sprintf(_m('HTTP request failed without response to URL: %s'), _ve(isset($httpscallback) ? $httpscallback : $this->callback)));
  304. }
  305. // TRANS: Exception. %1$s is a response status code, %2$s is the body of the response.
  306. throw new Exception(sprintf(_m('Callback returned status: %1$s. Body: %2$s'),
  307. $response->getStatus(),trim($response->getBody())));
  308. }
  309. }