FeedSub.php 26 KB

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