FeedSub.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  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('GNUSOCIAL')) { exit(1); }
  20. /**
  21. * @package OStatusPlugin
  22. * @maintainer Brion Vibber <brion@status.net>
  23. */
  24. /*
  25. WebSub (previously PubSubHubbub/PuSH) subscription flow:
  26. $profile->subscribe()
  27. sends a sub request to the hub...
  28. main/push/callback
  29. hub sends confirmation back to us via GET
  30. We verify the request, then echo back the challenge.
  31. On our end, we save the time we subscribed and the lease expiration
  32. main/push/callback
  33. hub sends us updates via POST
  34. */
  35. /**
  36. * FeedSub handles low-level WebSub (PubSubHubbub/PuSH) subscriptions.
  37. * Higher-level behavior building OStatus stuff on top is handled
  38. * under Ostatus_profile.
  39. */
  40. class FeedSub extends Managed_DataObject
  41. {
  42. public $__table = 'feedsub';
  43. public $id;
  44. public $uri; // varchar(191) not 255 because utf8mb4 takes more space
  45. // WebSub subscription data
  46. public $huburi;
  47. public $secret;
  48. public $sub_state; // subscribe, active, unsubscribe, inactive, nohub
  49. public $sub_start;
  50. public $sub_end;
  51. public $last_update;
  52. public $created;
  53. public $modified;
  54. public static function schemaDef()
  55. {
  56. return array(
  57. 'fields' => array(
  58. 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'FeedSub local unique id'),
  59. 'uri' => array('type' => 'varchar', 'not null' => true, 'length' => 191, 'description' => 'FeedSub uri'),
  60. 'huburi' => array('type' => 'text', 'description' => 'FeedSub hub-uri'),
  61. 'secret' => array('type' => 'text', 'description' => 'FeedSub stored secret'),
  62. 'sub_state' => array('type' => 'enum("subscribe","active","unsubscribe","inactive","nohub")', 'not null' => true, 'description' => 'subscription state'),
  63. 'sub_start' => array('type' => 'datetime', 'description' => 'subscription start'),
  64. 'sub_end' => array('type' => 'datetime', 'description' => 'subscription end'),
  65. 'last_update' => array('type' => 'datetime', 'description' => 'when this record was last updated'),
  66. 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
  67. 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
  68. ),
  69. 'primary key' => array('id'),
  70. 'unique keys' => array(
  71. 'feedsub_uri_key' => array('uri'),
  72. ),
  73. );
  74. }
  75. /**
  76. * Get the feed uri (http/https)
  77. */
  78. public function getUri()
  79. {
  80. if (empty($this->uri)) {
  81. throw new NoUriException($this);
  82. }
  83. return $this->uri;
  84. }
  85. function getLeaseRemaining()
  86. {
  87. if (empty($this->sub_end)) {
  88. return null;
  89. }
  90. return strtotime($this->sub_end) - time();
  91. }
  92. /**
  93. * Do we have a hub? Then we are a WebSub feed.
  94. * WebSub standard: https://www.w3.org/TR/websub/
  95. * old: https://en.wikipedia.org/wiki/PubSubHubbub
  96. *
  97. * If huburi is empty, then doublecheck that we are not using
  98. * a fallback hub. If there is a fallback hub, it is only if the
  99. * sub_state is "nohub" that we assume it's not a WebSub feed.
  100. */
  101. public function isWebSub()
  102. {
  103. if (empty($this->huburi)
  104. && (!common_config('feedsub', 'fallback_hub')
  105. || $this->sub_state === 'nohub')) {
  106. // Here we have no huburi set. Also, either there is no
  107. // fallback hub configured or sub_state is "nohub".
  108. return false;
  109. }
  110. return true;
  111. }
  112. /**
  113. * Fetch the StatusNet-side profile for this feed
  114. * @return Profile
  115. */
  116. public function localProfile()
  117. {
  118. if ($this->profile_id) {
  119. return Profile::getKV('id', $this->profile_id);
  120. }
  121. return null;
  122. }
  123. /**
  124. * Fetch the StatusNet-side profile for this feed
  125. * @return Profile
  126. */
  127. public function localGroup()
  128. {
  129. if ($this->group_id) {
  130. return User_group::getKV('id', $this->group_id);
  131. }
  132. return null;
  133. }
  134. /**
  135. * @param string $feeduri
  136. * @return FeedSub
  137. * @throws FeedSubException if feed is invalid or lacks WebSub setup
  138. */
  139. public static function ensureFeed($feeduri)
  140. {
  141. $feedsub = self::getKV('uri', $feeduri);
  142. if ($feedsub instanceof FeedSub) {
  143. if (!empty($feedsub->huburi)) {
  144. // If there is already a huburi we don't
  145. // rediscover it on ensureFeed, call
  146. // ensureHub to do that (compare ->modified
  147. // to see if it might be time to do it).
  148. return $feedsub;
  149. }
  150. if ($feedsub->sub_state !== 'inactive') {
  151. throw new ServerException('Can only ensure WebSub hub for inactive (unsubscribed) feeds.');
  152. }
  153. // If huburi is empty we continue with ensureHub
  154. } else {
  155. // If we don't have that local feed URI
  156. // stored then we create a new DB object.
  157. $feedsub = new FeedSub();
  158. $feedsub->uri = $feeduri;
  159. $feedsub->sub_state = 'inactive';
  160. }
  161. try {
  162. // discover the hub uri
  163. $feedsub->ensureHub();
  164. } catch (FeedSubNoHubException $e) {
  165. // Only throw this exception if we can't handle huburi-less feeds
  166. // (i.e. we have a fallback hub or we can do feed polling (nohub)
  167. if (!common_config('feedsub', 'fallback_hub') && !common_config('feedsub', 'nohub')) {
  168. throw $e;
  169. }
  170. }
  171. if (empty($feedsub->id)) {
  172. // if $feedsub doesn't have an id we'll insert it into the db here
  173. $feedsub->created = common_sql_now();
  174. $feedsub->modified = common_sql_now();
  175. $result = $feedsub->insert();
  176. if ($result === false) {
  177. throw new FeedDBException($feedsub);
  178. }
  179. }
  180. return $feedsub;
  181. }
  182. /**
  183. * ensureHub will only do $this->update if !empty($this->id)
  184. * because otherwise the object has not been created yet.
  185. *
  186. * @param bool $rediscovered Whether the hub info is rediscovered (to avoid endless loop nesting)
  187. *
  188. * @return null if actively avoiding the database
  189. * int number of rows updated in the database (0 means untouched)
  190. *
  191. * @throws ServerException if something went wrong when updating the database
  192. * FeedSubNoHubException if no hub URL was discovered
  193. */
  194. public function ensureHub($rediscovered=false)
  195. {
  196. common_debug('Now inside ensureHub again, $rediscovered=='._ve($rediscovered));
  197. if ($this->sub_state !== 'inactive') {
  198. common_log(LOG_INFO, sprintf(__METHOD__ . ': Running hub discovery a possibly active feed in %s state for URI %s', _ve($this->sub_state), _ve($this->uri)));
  199. }
  200. $discover = new FeedDiscovery();
  201. $discover->discoverFromFeedURL($this->uri);
  202. $huburi = $discover->getHubLink();
  203. if (empty($huburi)) {
  204. // Will be caught and treated with if statements in regards to
  205. // fallback hub and feed polling (nohub) configuration.
  206. throw new FeedSubNoHubException();
  207. }
  208. // if we've already got a DB object stored, we want to UPDATE, not INSERT
  209. $orig = !empty($this->id) ? clone($this) : null;
  210. $old_huburi = $this->huburi; // most likely null if we're INSERTing
  211. $this->huburi = $huburi;
  212. if (!empty($this->id)) {
  213. common_debug(sprintf(__METHOD__ . ': Feed uri==%s huburi before=%s after=%s (identical==%s)', _ve($this->uri), _ve($old_huburi), _ve($this->huburi), _ve($old_huburi===$this->huburi)));
  214. $result = $this->update($orig);
  215. if ($result === false) {
  216. // TODO: Get a DB exception class going...
  217. common_debug('Database update failed for FeedSub id=='._ve($this->id).' with new huburi: '._ve($this->huburi));
  218. throw new ServerException('Database update failed for FeedSub.');
  219. }
  220. if (!$rediscovered) {
  221. $this->renew();
  222. }
  223. return $result;
  224. }
  225. return null; // we haven't done anything with the database
  226. }
  227. /**
  228. * Send a subscription request to the hub for this feed.
  229. * The hub will later send us a confirmation POST to /main/push/callback.
  230. *
  231. * @return void
  232. * @throws ServerException if feed state is not valid
  233. */
  234. public function subscribe($rediscovered=false)
  235. {
  236. if ($this->sub_state && $this->sub_state != 'inactive') {
  237. common_log(LOG_WARNING, sprintf('Attempting to (re)start WebSub subscription to %s in unexpected state %s', $this->getUri(), $this->sub_state));
  238. }
  239. if (!Event::handle('FeedSubscribe', array($this))) {
  240. // A plugin handled it
  241. return;
  242. }
  243. if (empty($this->huburi)) {
  244. if (common_config('feedsub', 'fallback_hub')) {
  245. // No native hub on this feed?
  246. // Use our fallback hub, which handles polling on our behalf.
  247. } else if (common_config('feedsub', 'nohub')) {
  248. // For this to actually work, we'll need some polling mechanism.
  249. // The FeedPoller plugin should take care of it.
  250. return;
  251. } else {
  252. // TRANS: Server exception.
  253. throw new ServerException(_m('Attempting to start WebSub subscription for feed with no hub.'));
  254. }
  255. }
  256. $this->doSubscribe('subscribe', $rediscovered);
  257. }
  258. /**
  259. * Send a WebSub unsubscription request to the hub for this feed.
  260. * The hub will later send us a confirmation POST to /main/push/callback.
  261. * Warning: this will cancel the subscription even if someone else in
  262. * the system is using it. Most callers will want garbageCollect() instead,
  263. * which confirms there's no uses left.
  264. *
  265. * @throws ServerException if feed state is not valid
  266. */
  267. public function unsubscribe() {
  268. if ($this->sub_state != 'active') {
  269. common_log(LOG_WARNING, sprintf('Attempting to (re)end WebSub subscription to %s in unexpected state %s', $this->getUri(), $this->sub_state));
  270. }
  271. if (!Event::handle('FeedUnsubscribe', array($this))) {
  272. // A plugin handled it
  273. return;
  274. }
  275. if (empty($this->huburi) && !common_config('feedsub', 'fallback_hub')) {
  276. /**
  277. * If the huburi is empty and we don't have a fallback hub,
  278. * there is nowhere we can send an unsubscribe to.
  279. *
  280. * A plugin should handle the FeedSub above and set the proper state
  281. * if there is no hub. (instead of 'nohub' it should be 'inactive' if
  282. * the instance has enabled feed polling for feeds that don't publish
  283. * WebSub/PuSH hubs. FeedPoller is a plugin which enables polling.
  284. *
  285. * Secondly, if we don't have the setting "nohub" enabled (i.e.)
  286. * we're ready to poll ourselves, there is something odd with the
  287. * database, such as a polling plugin that has been disabled.
  288. */
  289. if (!common_config('feedsub', 'nohub')) {
  290. // TRANS: Server exception.
  291. throw new ServerException(_m('Attempting to end WebSub subscription for feed with no hub.'));
  292. }
  293. return;
  294. }
  295. $this->doSubscribe('unsubscribe');
  296. }
  297. /**
  298. * Check if there are any active local uses of this feed, and if not then
  299. * make sure it's inactive, unsubscribing if necessary.
  300. *
  301. * @return boolean true if the subscription is now inactive, false if still active.
  302. * @throws NoProfileException in FeedSubSubscriberCount for missing Profile entries
  303. * @throws Exception if something goes wrong in unsubscribe() method
  304. */
  305. public function garbageCollect()
  306. {
  307. if ($this->sub_state == '' || $this->sub_state == 'inactive') {
  308. // No active WebSub subscription, we can just leave it be.
  309. return true;
  310. }
  311. // WebSub subscription is either active or in an indeterminate state.
  312. // Check if we're out of subscribers, and if so send an unsubscribe.
  313. $count = 0;
  314. Event::handle('FeedSubSubscriberCount', array($this, &$count));
  315. if ($count > 0) {
  316. common_log(LOG_INFO, __METHOD__ . ': ok, ' . $count . ' user(s) left for ' . $this->getUri());
  317. return false;
  318. }
  319. common_log(LOG_INFO, __METHOD__ . ': unsubscribing, no users left for ' . $this->getUri());
  320. // Unsubscribe throws various Exceptions on failure
  321. $this->unsubscribe();
  322. return true;
  323. }
  324. static public function renewalCheck()
  325. {
  326. $fs = new FeedSub();
  327. // the "" empty string check is because we historically haven't saved unsubscribed feeds as NULL
  328. $fs->whereAdd('sub_end IS NOT NULL AND sub_end!="" AND sub_end < NOW() + INTERVAL 1 day');
  329. if (!$fs->find()) { // find can be both false and 0, depending on why nothing was found
  330. throw new NoResultException($fs);
  331. }
  332. return $fs;
  333. }
  334. public function renew($rediscovered=false)
  335. {
  336. common_debug('FeedSub is being renewed for uri=='._ve($this->uri).' on huburi=='._ve($this->huburi));
  337. $this->subscribe($rediscovered);
  338. }
  339. /**
  340. * Setting to subscribe means it is _waiting_ to become active. This
  341. * cannot be done in a transaction because there is a chance that the
  342. * remote script we're calling (as in the case of PuSHpress) performs
  343. * the lookup _while_ we're POSTing data, which means the transaction
  344. * never completes (PushcallbackAction gets an 'inactive' state).
  345. *
  346. * @return boolean true when everything is ok (throws Exception on fail)
  347. * @throws Exception on failure, can be HTTPClient's or our own.
  348. */
  349. protected function doSubscribe($mode, $rediscovered=false)
  350. {
  351. $msg = null; // carries descriptive error message to enduser (no remote data strings!)
  352. $orig = clone($this);
  353. if ($mode == 'subscribe') {
  354. $this->secret = common_random_hexstr(32);
  355. }
  356. $this->sub_state = $mode;
  357. $this->update($orig);
  358. unset($orig);
  359. try {
  360. $callback = common_local_url('pushcallback', array('feed' => $this->id));
  361. $headers = array('Content-Type: application/x-www-form-urlencoded');
  362. $post = array('hub.mode' => $mode,
  363. 'hub.callback' => $callback,
  364. 'hub.verify' => 'async', // TODO: deprecated, remove when noone uses PuSH <0.4 (only 'async' method used there)
  365. 'hub.verify_token' => 'Deprecated-since-PuSH-0.4', // TODO: rm!
  366. 'hub.lease_seconds' => 2592000, // 3600*24*30, request approximately month long lease (may be changed by hub)
  367. 'hub.secret' => $this->secret,
  368. 'hub.topic' => $this->getUri());
  369. $client = new HTTPClient();
  370. if ($this->huburi) {
  371. $hub = $this->huburi;
  372. } else {
  373. if (common_config('feedsub', 'fallback_hub')) {
  374. $hub = common_config('feedsub', 'fallback_hub');
  375. if (common_config('feedsub', 'hub_user')) {
  376. $u = common_config('feedsub', 'hub_user');
  377. $p = common_config('feedsub', 'hub_pass');
  378. $client->setAuth($u, $p);
  379. }
  380. } else {
  381. throw new FeedSubException('Server could not find a usable WebSub hub.');
  382. }
  383. }
  384. $response = $client->post($hub, $headers, $post);
  385. $status = $response->getStatus();
  386. // WebSub specificed response status code
  387. if ($status == 202 || $status == 204) {
  388. common_log(LOG_INFO, __METHOD__ . ': sub req ok, awaiting verification callback');
  389. return;
  390. } else if ($status >= 200 && $status < 300) {
  391. common_log(LOG_ERR, __METHOD__ . ": sub req returned unexpected HTTP $status: " . $response->getBody());
  392. $msg = sprintf(_m("Unexpected HTTP status: %d"), $status);
  393. } else if ($status == 422 && !$rediscovered) {
  394. // Error code regarding something wrong in the data (it seems
  395. // that we're talking to a WebSub hub at least, so let's check
  396. // our own data to be sure we're not mistaken somehow, which
  397. // means rediscovering hub data (the boolean parameter means
  398. // we avoid running this part over and over and over and over):
  399. common_debug('Running ensureHub again due to 422 status, $rediscovered=='._ve($rediscovered));
  400. $discoveryResult = $this->ensureHub(true);
  401. common_debug('ensureHub is now done and its result was: '._ve($discoveryResult));
  402. } else {
  403. common_log(LOG_ERR, __METHOD__ . ": sub req failed with HTTP $status: " . $response->getBody());
  404. }
  405. } catch (Exception $e) {
  406. common_log(LOG_ERR, __METHOD__ . ": error \"{$e->getMessage()}\" hitting hub {$this->huburi} subscribing to {$this->getUri()}");
  407. // Reset the subscription state.
  408. $orig = clone($this);
  409. $this->sub_state = 'inactive';
  410. $this->update($orig);
  411. // Throw the Exception again.
  412. throw $e;
  413. }
  414. throw new ServerException("{$mode} request failed" . (!is_null($msg) ? " ($msg)" : '.'));
  415. }
  416. /**
  417. * Save WebSub subscription confirmation.
  418. * Sets approximate lease start and end times and finalizes state.
  419. *
  420. * @param int $lease_seconds provided hub.lease_seconds parameter, if given
  421. */
  422. public function confirmSubscribe($lease_seconds)
  423. {
  424. $original = clone($this);
  425. $this->sub_state = 'active';
  426. $this->sub_start = common_sql_date(time());
  427. if ($lease_seconds > 0) {
  428. $this->sub_end = common_sql_date(time() + $lease_seconds);
  429. } else {
  430. $this->sub_end = null; // Backwards compatibility to StatusNet (PuSH <0.4 supported permanent subs)
  431. }
  432. $this->modified = common_sql_now();
  433. common_debug(__METHOD__ . ': Updating sub state and metadata for '.$this->getUri());
  434. return $this->update($original);
  435. }
  436. /**
  437. * Save WebSub unsubscription confirmation.
  438. * Wipes active WebSub sub info and resets state.
  439. */
  440. public function confirmUnsubscribe()
  441. {
  442. $original = clone($this);
  443. // @fixme these should all be null, but DB_DataObject doesn't save null values...?????
  444. $this->secret = '';
  445. $this->sub_state = '';
  446. $this->sub_start = '';
  447. $this->sub_end = '';
  448. $this->modified = common_sql_now();
  449. return $this->update($original);
  450. }
  451. /**
  452. * Accept updates from a WebSub feed. If validated, this object and the
  453. * feed (as a DOMDocument) will be passed to the StartFeedSubHandleFeed
  454. * and EndFeedSubHandleFeed events for processing.
  455. *
  456. * Not guaranteed to be running in an immediate POST context; may be run
  457. * from a queue handler.
  458. *
  459. * Side effects: the feedsub record's lastupdate field will be updated
  460. * to the current time (not published time) if we got a legit update.
  461. *
  462. * @param string $post source of Atom or RSS feed
  463. * @param string $hmac X-Hub-Signature header, if present
  464. */
  465. public function receive($post, $hmac)
  466. {
  467. common_log(LOG_INFO, sprintf(__METHOD__.': packet for %s with HMAC %s', _ve($this->getUri()), _ve($hmac)));
  468. if (!in_array($this->sub_state, array('active', 'nohub'))) {
  469. common_log(LOG_ERR, sprintf(__METHOD__.': ignoring WebSub for inactive feed %s (in state %s)', _ve($this->getUri()), _ve($this->sub_state)));
  470. return;
  471. }
  472. if ($post === '') {
  473. common_log(LOG_ERR, __METHOD__ . ": ignoring empty post");
  474. return;
  475. }
  476. try {
  477. if (!$this->validatePushSig($post, $hmac)) {
  478. // Per spec we silently drop input with a bad sig,
  479. // while reporting receipt to the server.
  480. return;
  481. }
  482. $this->receiveFeed($post);
  483. } catch (FeedSubBadPushSignatureException $e) {
  484. // We got a signature, so something could be wrong. Let's check to see if
  485. // maybe upstream has switched to another hub. Let's fetch feed and then
  486. // compare rel="hub" with $this->huburi, which is done in $this->ensureHub()
  487. $this->ensureHub(true);
  488. }
  489. }
  490. /**
  491. * All our feed URIs should be URLs.
  492. */
  493. public function importFeed()
  494. {
  495. $feed_url = $this->getUri();
  496. // Fetch the URL
  497. try {
  498. common_log(LOG_INFO, sprintf('Importing feed backlog from %s', $feed_url));
  499. $feed_xml = HTTPClient::quickGet($feed_url, 'application/atom+xml');
  500. } catch (Exception $e) {
  501. throw new FeedSubException("Could not fetch feed from URL '%s': %s (%d).\n", $feed_url, $e->getMessage(), $e->getCode());
  502. }
  503. return $this->receiveFeed($feed_xml);
  504. }
  505. protected function receiveFeed($feed_xml)
  506. {
  507. // We're passed the XML for the Atom feed as $feed_xml,
  508. // so read it into a DOMDocument and process.
  509. $feed = new DOMDocument();
  510. if (!$feed->loadXML($feed_xml)) {
  511. // @fixme might help to include the err message
  512. common_log(LOG_ERR, __METHOD__ . ": ignoring invalid XML");
  513. return;
  514. }
  515. $orig = clone($this);
  516. $this->last_update = common_sql_now();
  517. $this->update($orig);
  518. Event::handle('StartFeedSubReceive', array($this, $feed));
  519. Event::handle('EndFeedSubReceive', array($this, $feed));
  520. }
  521. /**
  522. * Validate the given Atom chunk and HMAC signature against our
  523. * shared secret that was set up at subscription time.
  524. *
  525. * If we don't have a shared secret, there should be no signature.
  526. * If we do, our calculated HMAC should match theirs.
  527. *
  528. * @param string $post raw XML source as POSTed to us
  529. * @param string $hmac X-Hub-Signature HTTP header value, or empty
  530. * @return boolean true for a match
  531. */
  532. protected function validatePushSig($post, $hmac)
  533. {
  534. if ($this->secret) {
  535. // {3,16} because shortest hash algorithm name is 3 characters (md2,md4,md5) and longest
  536. // is currently 11 characters, but we'll leave some margin in the end...
  537. if (preg_match('/^([0-9a-zA-Z\-\,]{3,16})=([0-9a-fA-F]+)$/', $hmac, $matches)) {
  538. $hash_algo = strtolower($matches[1]);
  539. $their_hmac = strtolower($matches[2]);
  540. common_debug(sprintf(__METHOD__ . ': WebSub push from feed %s uses HMAC algorithm %s with value: %s', _ve($this->getUri()), _ve($hash_algo), _ve($their_hmac)));
  541. if (!in_array($hash_algo, hash_algos())) {
  542. // We can't handle this at all, PHP doesn't recognize the algorithm name ('md5', 'sha1', 'sha256' etc: https://secure.php.net/manual/en/function.hash-algos.php)
  543. common_log(LOG_ERR, sprintf(__METHOD__.': HMAC algorithm %s unsupported, not found in PHP hash_algos()', _ve($hash_algo)));
  544. return false;
  545. } elseif (!is_null(common_config('security', 'hash_algos')) && !in_array($hash_algo, common_config('security', 'hash_algos'))) {
  546. // We _won't_ handle this because there is a list of accepted hash algorithms and this one is not in it.
  547. common_log(LOG_ERR, sprintf(__METHOD__.': Whitelist for HMAC algorithms exist, but %s is not included.', _ve($hash_algo)));
  548. return false;
  549. }
  550. $our_hmac = hash_hmac($hash_algo, $post, $this->secret);
  551. if ($their_hmac !== $our_hmac) {
  552. common_log(LOG_ERR, sprintf(__METHOD__.': ignoring WebSub push with bad HMAC hash: got %s, expected %s for feed %s from hub %s', _ve($their_hmac), _ve($our_hmac), _ve($this->getUri()), _ve($this->huburi)));
  553. throw new FeedSubBadPushSignatureException('Incoming WebSub push signature did not match expected HMAC hash.');
  554. }
  555. return true;
  556. } else {
  557. common_log(LOG_ERR, sprintf(__METHOD__.': ignoring WebSub push with bogus HMAC==', _ve($hmac)));
  558. }
  559. } else {
  560. if (empty($hmac)) {
  561. return true;
  562. } else {
  563. common_log(LOG_ERR, sprintf(__METHOD__.': ignoring WebSub push with unexpected HMAC==%s', _ve($hmac)));
  564. }
  565. }
  566. return false;
  567. }
  568. public function delete($useWhere=false)
  569. {
  570. try {
  571. $oprofile = Ostatus_profile::getKV('feeduri', $this->getUri());
  572. if ($oprofile instanceof Ostatus_profile) {
  573. // Check if there's a profile. If not, handle the NoProfileException below
  574. $profile = $oprofile->localProfile();
  575. }
  576. } catch (NoProfileException $e) {
  577. // If the Ostatus_profile has no local Profile bound to it, let's clean it out at the same time
  578. $oprofile->delete();
  579. } catch (NoUriException $e) {
  580. // FeedSub->getUri() can throw a NoUriException, let's just go ahead and delete it
  581. }
  582. return parent::delete($useWhere);
  583. }
  584. }