FeedSub.php 19 KB

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