pushhub.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. <?php
  2. /*
  3. * StatusNet - the distributed open-source microblogging tool
  4. * Copyright (C) 2010, StatusNet, Inc.
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU Affero General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Affero General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. /**
  20. * Integrated WebSub hub; lets us only ping them what need it.
  21. * @package Hub
  22. * @maintainer Brion Vibber <brion@status.net>
  23. */
  24. if (!defined('STATUSNET')) {
  25. exit(1);
  26. }
  27. /**
  28. * Things to consider...
  29. * should we purge incomplete subscriptions that never get a verification pingback?
  30. * when can we send subscription renewal checks?
  31. * - at next send time probably ok
  32. * when can we handle trimming of subscriptions?
  33. * - at next send time probably ok
  34. * should we keep a fail count?
  35. */
  36. class PushHubAction extends Action
  37. {
  38. function arg($arg, $def=null)
  39. {
  40. // PHP converts '.'s in incoming var names to '_'s.
  41. // It also merges multiple values, which'll break hub.verify and hub.topic for publishing
  42. // @fixme handle multiple args
  43. $arg = str_replace('hub.', 'hub_', $arg);
  44. return parent::arg($arg, $def);
  45. }
  46. protected function prepare(array $args=array())
  47. {
  48. GNUsocial::setApi(true); // reduce exception reports to aid in debugging
  49. return parent::prepare($args);
  50. }
  51. protected function handle()
  52. {
  53. $mode = $this->trimmed('hub.mode');
  54. switch ($mode) {
  55. case "subscribe":
  56. case "unsubscribe":
  57. $this->subunsub($mode);
  58. break;
  59. case "publish":
  60. // TRANS: Client exception.
  61. throw new ClientException(_m('Publishing outside feeds not supported.'), 400);
  62. default:
  63. // TRANS: Client exception. %s is a mode.
  64. throw new ClientException(sprintf(_m('Unrecognized mode "%s".'),$mode), 400);
  65. }
  66. }
  67. /**
  68. * Process a request for a new or modified WebSub feed subscription.
  69. * If asynchronous verification is requested, updates won't be saved immediately.
  70. *
  71. * HTTP return codes:
  72. * 202 Accepted - request saved and awaiting verification
  73. * 204 No Content - already subscribed
  74. * 400 Bad Request - rejecting this (not specifically spec'd)
  75. */
  76. function subunsub($mode)
  77. {
  78. $callback = $this->argUrl('hub.callback');
  79. common_debug('New WebSub hub request ('._ve($mode).') for callback '._ve($callback));
  80. $topic = $this->argUrl('hub.topic');
  81. if (!$this->recognizedFeed($topic)) {
  82. common_debug('WebSub hub request had unrecognized feed topic=='._ve($topic));
  83. // TRANS: Client exception. %s is a topic.
  84. throw new ClientException(sprintf(_m('Unsupported hub.topic %s this hub only serves local user and group Atom feeds.'),$topic));
  85. }
  86. $lease = $this->arg('hub.lease_seconds', null);
  87. if ($mode == 'subscribe' && $lease != '' && !preg_match('/^\d+$/', $lease)) {
  88. common_debug('WebSub hub request had invalid lease_seconds=='._ve($lease));
  89. // TRANS: Client exception. %s is the invalid lease value.
  90. throw new ClientException(sprintf(_m('Invalid hub.lease "%s". It must be empty or positive integer.'),$lease));
  91. }
  92. $secret = $this->arg('hub.secret', null);
  93. if ($secret != '' && strlen($secret) >= 200) {
  94. common_debug('WebSub hub request had invalid secret=='._ve($secret));
  95. // TRANS: Client exception. %s is the invalid hub secret.
  96. throw new ClientException(sprintf(_m('Invalid hub.secret "%s". It must be under 200 bytes.'),$secret));
  97. }
  98. $sub = HubSub::getByHashkey($topic, $callback);
  99. if (!$sub instanceof HubSub) {
  100. // Creating a new one!
  101. common_debug('WebSub creating new HubSub entry for topic=='._ve($topic).' to remote callback '._ve($callback));
  102. $sub = new HubSub();
  103. $sub->topic = $topic;
  104. $sub->callback = $callback;
  105. }
  106. if ($mode == 'subscribe') {
  107. if ($secret) {
  108. $sub->secret = $secret;
  109. }
  110. if ($lease) {
  111. $sub->setLease(intval($lease));
  112. }
  113. }
  114. $verify = $this->arg('hub.verify'); // TODO: deprecated
  115. $token = $this->arg('hub.verify_token', null); // TODO: deprecated
  116. if ($verify == 'sync') { // pre-0.4 PuSH
  117. $sub->verify($mode, $token);
  118. header('HTTP/1.1 204 No Content');
  119. } else { // If $verify is not "sync", we might be using WebSub or PuSH 0.4
  120. $sub->scheduleVerify($mode, $token); // If we were certain it's WebSub or PuSH 0.4, token could be removed
  121. header('HTTP/1.1 202 Accepted');
  122. }
  123. }
  124. /**
  125. * Check whether the given URL represents one of our canonical
  126. * user or group Atom feeds.
  127. *
  128. * @param string $feed URL
  129. * @return boolean true if it matches, false if not a recognized local feed
  130. * @throws exception if local entity does not exist
  131. */
  132. protected function recognizedFeed($feed)
  133. {
  134. $matches = array();
  135. // Simple mapping to local ID for user or group
  136. if (preg_match('!/(\d+)\.atom$!', $feed, $matches)) {
  137. $id = $matches[1];
  138. $params = array('id' => $id, 'format' => 'atom');
  139. // Double-check against locally generated URLs
  140. switch ($feed) {
  141. case common_local_url('ApiTimelineUser', $params):
  142. $user = User::getKV('id', $id);
  143. if (!$user instanceof User) {
  144. // TRANS: Client exception. %s is a feed URL.
  145. throw new ClientException(sprintf(_m('Invalid hub.topic "%s". User does not exist.'),$feed));
  146. }
  147. return true;
  148. case common_local_url('ApiTimelineGroup', $params):
  149. $group = Local_group::getKV('group_id', $id);
  150. if (!$group instanceof Local_group) {
  151. // TRANS: Client exception. %s is a feed URL.
  152. throw new ClientException(sprintf(_m('Invalid hub.topic "%s". Local_group does not exist.'),$feed));
  153. }
  154. return true;
  155. }
  156. common_debug("Feed was not recognized by any local User or Group Atom feed URLs: {$feed}");
  157. return false;
  158. }
  159. // Profile lists are unique per user, so we need both IDs
  160. if (preg_match('!/(\d+)/lists/(\d+)/statuses\.atom$!', $feed, $matches)) {
  161. $user = $matches[1];
  162. $id = $matches[2];
  163. $params = array('user' => $user, 'id' => $id, 'format' => 'atom');
  164. // Double-check against locally generated URLs
  165. switch ($feed) {
  166. case common_local_url('ApiTimelineList', $params):
  167. $list = Profile_list::getKV('id', $id);
  168. $user = User::getKV('id', $user);
  169. if (!$list instanceof Profile_list || !$user instanceof User || $list->tagger != $user->id) {
  170. // TRANS: Client exception. %s is a feed URL.
  171. throw new ClientException(sprintf(_m('Invalid hub.topic %s; list does not exist.'),$feed));
  172. }
  173. return true;
  174. }
  175. common_debug("Feed was not recognized by any local Profile_list Atom feed URL: {$feed}");
  176. return false;
  177. }
  178. common_debug("Unknown feed URL structure, can't match against local user, group or profile_list: {$feed}");
  179. return false;
  180. }
  181. /**
  182. * Grab and validate a URL from POST parameters.
  183. * @throws ClientException for malformed or non-http/https or blacklisted URLs
  184. */
  185. protected function argUrl($arg)
  186. {
  187. $url = $this->arg($arg);
  188. $params = array('domain_check' => false, // otherwise breaks my local tests :P
  189. 'allowed_schemes' => array('http', 'https'));
  190. $validate = new Validate();
  191. if (!$validate->uri($url, $params)) {
  192. // TRANS: Client exception.
  193. // TRANS: %1$s is this argument to the method this exception occurs in, %2$s is a URL.
  194. throw new ClientException(sprintf(_m('Invalid URL passed for %1$s: "%2$s"'),$arg,$url));
  195. }
  196. Event::handle('UrlBlacklistTest', array($url));
  197. return $url;
  198. }
  199. /**
  200. * Get HubSub subscription record for a given feed & subscriber.
  201. *
  202. * @param string $feed
  203. * @param string $callback
  204. * @return mixed HubSub or false
  205. */
  206. protected function getSub($feed, $callback)
  207. {
  208. return HubSub::getByHashkey($feed, $callback);
  209. }
  210. }