FeedSub.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. <?php
  2. /*
  3. * StatusNet - the distributed open-source microblogging tool
  4. * Copyright (C) 2009-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. * @package OStatusPlugin
  24. * @maintainer Brion Vibber <brion@status.net>
  25. */
  26. /*
  27. PuSH subscription flow:
  28. $profile->subscribe()
  29. sends a sub request to the hub...
  30. main/push/callback
  31. hub sends confirmation back to us via GET
  32. We verify the request, then echo back the challenge.
  33. On our end, we save the time we subscribed and the lease expiration
  34. main/push/callback
  35. hub sends us updates via POST
  36. */
  37. class FeedDBException extends FeedSubException
  38. {
  39. public $obj;
  40. function __construct($obj)
  41. {
  42. parent::__construct('Database insert failure');
  43. $this->obj = $obj;
  44. }
  45. }
  46. /**
  47. * FeedSub handles low-level PubHubSubbub (PuSH) subscriptions.
  48. * Higher-level behavior building OStatus stuff on top is handled
  49. * under Ostatus_profile.
  50. */
  51. class FeedSub extends Managed_DataObject
  52. {
  53. public $__table = 'feedsub';
  54. public $id;
  55. public $uri;
  56. // PuSH subscription data
  57. public $huburi;
  58. public $secret;
  59. public $sub_state; // subscribe, active, unsubscribe, inactive, nohub
  60. public $sub_start;
  61. public $sub_end;
  62. public $last_update;
  63. public $created;
  64. public $modified;
  65. public static function schemaDef()
  66. {
  67. return array(
  68. 'fields' => array(
  69. 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'FeedSub local unique id'),
  70. 'uri' => array('type' => 'varchar', 'not null' => true, 'length' => 255, 'description' => 'FeedSub uri'),
  71. 'huburi' => array('type' => 'text', 'description' => 'FeedSub hub-uri'),
  72. 'secret' => array('type' => 'text', 'description' => 'FeedSub stored secret'),
  73. 'sub_state' => array('type' => 'enum("subscribe","active","unsubscribe","inactive","nohub")', 'not null' => true, 'description' => 'subscription state'),
  74. 'sub_start' => array('type' => 'datetime', 'description' => 'subscription start'),
  75. 'sub_end' => array('type' => 'datetime', 'description' => 'subscription end'),
  76. 'last_update' => array('type' => 'datetime', 'description' => 'when this record was last updated'),
  77. 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
  78. 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
  79. ),
  80. 'primary key' => array('id'),
  81. 'unique keys' => array(
  82. 'feedsub_uri_key' => array('uri'),
  83. ),
  84. );
  85. }
  86. /**
  87. * Get the feed uri (http/https)
  88. */
  89. public function getUri()
  90. {
  91. if (empty($this->uri)) {
  92. throw new NoUriException($this);
  93. }
  94. return $this->uri;
  95. }
  96. /**
  97. * Do we have a hub? Then we are a PuSH feed.
  98. * https://en.wikipedia.org/wiki/PubSubHubbub
  99. *
  100. * If huburi is empty, then doublecheck that we are not using
  101. * a fallback hub. If there is a fallback hub, it is only if the
  102. * sub_state is "nohub" that we assume it's not a PuSH feed.
  103. */
  104. public function isPuSH()
  105. {
  106. if (empty($this->huburi)
  107. && (!common_config('feedsub', 'fallback_hub')
  108. || $this->sub_state === 'nohub')) {
  109. // Here we have no huburi set. Also, either there is no
  110. // fallback hub configured or sub_state is "nohub".
  111. return false;
  112. }
  113. return true;
  114. }
  115. /**
  116. * Fetch the StatusNet-side profile for this feed
  117. * @return Profile
  118. */
  119. public function localProfile()
  120. {
  121. if ($this->profile_id) {
  122. return Profile::getKV('id', $this->profile_id);
  123. }
  124. return null;
  125. }
  126. /**
  127. * Fetch the StatusNet-side profile for this feed
  128. * @return Profile
  129. */
  130. public function localGroup()
  131. {
  132. if ($this->group_id) {
  133. return User_group::getKV('id', $this->group_id);
  134. }
  135. return null;
  136. }
  137. /**
  138. * @param string $feeduri
  139. * @return FeedSub
  140. * @throws FeedSubException if feed is invalid or lacks PuSH setup
  141. */
  142. public static function ensureFeed($feeduri)
  143. {
  144. $current = self::getKV('uri', $feeduri);
  145. if ($current instanceof FeedSub) {
  146. return $current;
  147. }
  148. $discover = new FeedDiscovery();
  149. $discover->discoverFromFeedURL($feeduri);
  150. $huburi = $discover->getHubLink();
  151. if (!$huburi && !common_config('feedsub', 'fallback_hub') && !common_config('feedsub', 'nohub')) {
  152. throw new FeedSubNoHubException();
  153. }
  154. $feedsub = new FeedSub();
  155. $feedsub->uri = $feeduri;
  156. $feedsub->huburi = $huburi;
  157. $feedsub->sub_state = 'inactive';
  158. $feedsub->created = common_sql_now();
  159. $feedsub->modified = common_sql_now();
  160. $result = $feedsub->insert();
  161. if ($result === false) {
  162. throw new FeedDBException($feedsub);
  163. }
  164. return $feedsub;
  165. }
  166. /**
  167. * Send a subscription request to the hub for this feed.
  168. * The hub will later send us a confirmation POST to /main/push/callback.
  169. *
  170. * @return void
  171. * @throws ServerException if feed state is not valid
  172. */
  173. public function subscribe()
  174. {
  175. if ($this->sub_state && $this->sub_state != 'inactive') {
  176. common_log(LOG_WARNING, sprintf('Attempting to (re)start PuSH subscription to %s in unexpected state %s', $this->getUri(), $this->sub_state));
  177. }
  178. if (!Event::handle('FeedSubscribe', array($this))) {
  179. // A plugin handled it
  180. return;
  181. }
  182. if (empty($this->huburi)) {
  183. if (common_config('feedsub', 'fallback_hub')) {
  184. // No native hub on this feed?
  185. // Use our fallback hub, which handles polling on our behalf.
  186. } else if (common_config('feedsub', 'nohub')) {
  187. // For this to actually work, we'll need some polling mechanism.
  188. // The FeedPoller plugin should take care of it.
  189. return;
  190. } else {
  191. // TRANS: Server exception.
  192. throw new ServerException(_m('Attempting to start PuSH subscription for feed with no hub.'));
  193. }
  194. }
  195. $this->doSubscribe('subscribe');
  196. }
  197. /**
  198. * Send a PuSH unsubscription request to the hub for this feed.
  199. * The hub will later send us a confirmation POST to /main/push/callback.
  200. * Warning: this will cancel the subscription even if someone else in
  201. * the system is using it. Most callers will want garbageCollect() instead,
  202. * which confirms there's no uses left.
  203. *
  204. * @throws ServerException if feed state is not valid
  205. */
  206. public function unsubscribe() {
  207. if ($this->sub_state != 'active') {
  208. common_log(LOG_WARNING, sprintf('Attempting to (re)end PuSH subscription to %s in unexpected state %s', $this->getUri(), $this->sub_state));
  209. }
  210. if (!Event::handle('FeedUnsubscribe', array($this))) {
  211. // A plugin handled it
  212. return;
  213. }
  214. if (empty($this->huburi)) {
  215. if (common_config('feedsub', 'fallback_hub')) {
  216. // No native hub on this feed?
  217. // Use our fallback hub, which handles polling on our behalf.
  218. } else if (common_config('feedsub', 'nohub')) {
  219. // We need a feedpolling plugin (like FeedPoller) active so it will
  220. // set the 'nohub' state to 'inactive' for us.
  221. return;
  222. } else {
  223. // TRANS: Server exception.
  224. throw new ServerException(_m('Attempting to end PuSH subscription for feed with no hub.'));
  225. }
  226. }
  227. $this->doSubscribe('unsubscribe');
  228. }
  229. /**
  230. * Check if there are any active local uses of this feed, and if not then
  231. * make sure it's inactive, unsubscribing if necessary.
  232. *
  233. * @return boolean true if the subscription is now inactive, false if still active.
  234. * @throws NoProfileException in FeedSubSubscriberCount for missing Profile entries
  235. * @throws Exception if something goes wrong in unsubscribe() method
  236. */
  237. public function garbageCollect()
  238. {
  239. if ($this->sub_state == '' || $this->sub_state == 'inactive') {
  240. // No active PuSH subscription, we can just leave it be.
  241. return true;
  242. }
  243. // PuSH subscription is either active or in an indeterminate state.
  244. // Check if we're out of subscribers, and if so send an unsubscribe.
  245. $count = 0;
  246. Event::handle('FeedSubSubscriberCount', array($this, &$count));
  247. if ($count > 0) {
  248. common_log(LOG_INFO, __METHOD__ . ': ok, ' . $count . ' user(s) left for ' . $this->getUri());
  249. return false;
  250. }
  251. common_log(LOG_INFO, __METHOD__ . ': unsubscribing, no users left for ' . $this->getUri());
  252. // Unsubscribe throws various Exceptions on failure
  253. $this->unsubscribe();
  254. return true;
  255. }
  256. static public function renewalCheck()
  257. {
  258. $fs = new FeedSub();
  259. // the "" empty string check is because we historically haven't saved unsubscribed feeds as NULL
  260. $fs->whereAdd('sub_end IS NOT NULL AND sub_end!="" AND sub_end < NOW() - INTERVAL 1 day');
  261. if (!$fs->find()) { // find can be both false and 0, depending on why nothing was found
  262. throw new NoResultException($fs);
  263. }
  264. return $fs;
  265. }
  266. public function renew()
  267. {
  268. $this->subscribe();
  269. }
  270. /**
  271. * Setting to subscribe means it is _waiting_ to become active. This
  272. * cannot be done in a transaction because there is a chance that the
  273. * remote script we're calling (as in the case of PuSHpress) performs
  274. * the lookup _while_ we're POSTing data, which means the transaction
  275. * never completes (PushcallbackAction gets an 'inactive' state).
  276. *
  277. * @return boolean true when everything is ok (throws Exception on fail)
  278. * @throws Exception on failure, can be HTTPClient's or our own.
  279. */
  280. protected function doSubscribe($mode)
  281. {
  282. $orig = clone($this);
  283. if ($mode == 'subscribe') {
  284. $this->secret = common_random_hexstr(32);
  285. }
  286. $this->sub_state = $mode;
  287. $this->update($orig);
  288. unset($orig);
  289. try {
  290. $callback = common_local_url('pushcallback', array('feed' => $this->id));
  291. $headers = array('Content-Type: application/x-www-form-urlencoded');
  292. $post = array('hub.mode' => $mode,
  293. 'hub.callback' => $callback,
  294. 'hub.verify' => 'async', // TODO: deprecated, remove when noone uses PuSH <0.4 (only 'async' method used there)
  295. 'hub.verify_token' => 'Deprecated-since-PuSH-0.4', // TODO: rm!
  296. 'hub.secret' => $this->secret,
  297. 'hub.topic' => $this->getUri());
  298. $client = new HTTPClient();
  299. if ($this->huburi) {
  300. $hub = $this->huburi;
  301. } else {
  302. if (common_config('feedsub', 'fallback_hub')) {
  303. $hub = common_config('feedsub', 'fallback_hub');
  304. if (common_config('feedsub', 'hub_user')) {
  305. $u = common_config('feedsub', 'hub_user');
  306. $p = common_config('feedsub', 'hub_pass');
  307. $client->setAuth($u, $p);
  308. }
  309. } else {
  310. throw new FeedSubException('Server could not find a usable PuSH hub.');
  311. }
  312. }
  313. $response = $client->post($hub, $headers, $post);
  314. $status = $response->getStatus();
  315. // PuSH specificed response status code
  316. if ($status == 202) {
  317. common_log(LOG_INFO, __METHOD__ . ': sub req ok, awaiting verification callback');
  318. return;
  319. } else if ($status >= 200 && $status < 300) {
  320. common_log(LOG_ERR, __METHOD__ . ": sub req returned unexpected HTTP $status: " . $response->getBody());
  321. } else {
  322. common_log(LOG_ERR, __METHOD__ . ": sub req failed with HTTP $status: " . $response->getBody());
  323. }
  324. } catch (Exception $e) {
  325. common_log(LOG_ERR, __METHOD__ . ": error \"{$e->getMessage()}\" hitting hub {$this->huburi} subscribing to {$this->getUri()}");
  326. // Reset the subscription state.
  327. $orig = clone($this);
  328. $this->sub_state = 'inactive';
  329. $this->update($orig);
  330. // Throw the Exception again.
  331. throw $e;
  332. }
  333. throw new ServerException("{$mode} request failed.");
  334. }
  335. /**
  336. * Save PuSH subscription confirmation.
  337. * Sets approximate lease start and end times and finalizes state.
  338. *
  339. * @param int $lease_seconds provided hub.lease_seconds parameter, if given
  340. */
  341. public function confirmSubscribe($lease_seconds)
  342. {
  343. $original = clone($this);
  344. $this->sub_state = 'active';
  345. $this->sub_start = common_sql_date(time());
  346. if ($lease_seconds > 0) {
  347. $this->sub_end = common_sql_date(time() + $lease_seconds);
  348. } else {
  349. $this->sub_end = null; // Backwards compatibility to StatusNet (PuSH <0.4 supported permanent subs)
  350. }
  351. $this->modified = common_sql_now();
  352. return $this->update($original);
  353. }
  354. /**
  355. * Save PuSH unsubscription confirmation.
  356. * Wipes active PuSH sub info and resets state.
  357. */
  358. public function confirmUnsubscribe()
  359. {
  360. $original = clone($this);
  361. // @fixme these should all be null, but DB_DataObject doesn't save null values...?????
  362. $this->secret = '';
  363. $this->sub_state = '';
  364. $this->sub_start = '';
  365. $this->sub_end = '';
  366. $this->modified = common_sql_now();
  367. return $this->update($original);
  368. }
  369. /**
  370. * Accept updates from a PuSH feed. If validated, this object and the
  371. * feed (as a DOMDocument) will be passed to the StartFeedSubHandleFeed
  372. * and EndFeedSubHandleFeed events for processing.
  373. *
  374. * Not guaranteed to be running in an immediate POST context; may be run
  375. * from a queue handler.
  376. *
  377. * Side effects: the feedsub record's lastupdate field will be updated
  378. * to the current time (not published time) if we got a legit update.
  379. *
  380. * @param string $post source of Atom or RSS feed
  381. * @param string $hmac X-Hub-Signature header, if present
  382. */
  383. public function receive($post, $hmac)
  384. {
  385. common_log(LOG_INFO, __METHOD__ . ": packet for \"" . $this->getUri() . "\"! $hmac $post");
  386. if (!in_array($this->sub_state, array('active', 'nohub'))) {
  387. common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH for inactive feed " . $this->getUri() . " (in state '$this->sub_state')");
  388. return;
  389. }
  390. if ($post === '') {
  391. common_log(LOG_ERR, __METHOD__ . ": ignoring empty post");
  392. return;
  393. }
  394. if (!$this->validatePushSig($post, $hmac)) {
  395. // Per spec we silently drop input with a bad sig,
  396. // while reporting receipt to the server.
  397. return;
  398. }
  399. $feed = new DOMDocument();
  400. if (!$feed->loadXML($post)) {
  401. // @fixme might help to include the err message
  402. common_log(LOG_ERR, __METHOD__ . ": ignoring invalid XML");
  403. return;
  404. }
  405. $orig = clone($this);
  406. $this->last_update = common_sql_now();
  407. $this->update($orig);
  408. Event::handle('StartFeedSubReceive', array($this, $feed));
  409. Event::handle('EndFeedSubReceive', array($this, $feed));
  410. }
  411. /**
  412. * Validate the given Atom chunk and HMAC signature against our
  413. * shared secret that was set up at subscription time.
  414. *
  415. * If we don't have a shared secret, there should be no signature.
  416. * If we we do, our the calculated HMAC should match theirs.
  417. *
  418. * @param string $post raw XML source as POSTed to us
  419. * @param string $hmac X-Hub-Signature HTTP header value, or empty
  420. * @return boolean true for a match
  421. */
  422. protected function validatePushSig($post, $hmac)
  423. {
  424. if ($this->secret) {
  425. if (preg_match('/^sha1=([0-9a-fA-F]{40})$/', $hmac, $matches)) {
  426. $their_hmac = strtolower($matches[1]);
  427. $our_hmac = hash_hmac('sha1', $post, $this->secret);
  428. if ($their_hmac === $our_hmac) {
  429. return true;
  430. }
  431. if (common_config('feedsub', 'debug')) {
  432. $tempfile = tempnam(sys_get_temp_dir(), 'feedsub-receive');
  433. if ($tempfile) {
  434. file_put_contents($tempfile, $post);
  435. }
  436. common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH with bad SHA-1 HMAC: got $their_hmac, expected $our_hmac for feed " . $this->getUri() . " on $this->huburi; saved to $tempfile");
  437. } else {
  438. common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH with bad SHA-1 HMAC: got $their_hmac, expected $our_hmac for feed " . $this->getUri() . " on $this->huburi");
  439. }
  440. } else {
  441. common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH with bogus HMAC '$hmac'");
  442. }
  443. } else {
  444. if (empty($hmac)) {
  445. return true;
  446. } else {
  447. common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH with unexpected HMAC '$hmac'");
  448. }
  449. }
  450. return false;
  451. }
  452. public function delete($useWhere=false)
  453. {
  454. try {
  455. $oprofile = Ostatus_profile::getKV('feeduri', $this->getUri());
  456. if ($oprofile instanceof Ostatus_profile) {
  457. // Check if there's a profile. If not, handle the NoProfileException below
  458. $profile = $oprofile->localProfile();
  459. }
  460. } catch (NoProfileException $e) {
  461. // If the Ostatus_profile has no local Profile bound to it, let's clean it out at the same time
  462. $oprofile->delete();
  463. } catch (NoUriException $e) {
  464. // FeedSub->getUri() can throw a NoUriException, let's just go ahead and delete it
  465. }
  466. return parent::delete($useWhere);
  467. }
  468. }