]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/classes/HubSub.php
Merge branch 'fixtests' into 'nightly'
[quix0rs-gnu-social.git] / plugins / OStatus / classes / HubSub.php
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 if (!defined('GNUSOCIAL')) { exit(1); }
21
22 /**
23  * PuSH feed subscription record
24  * @package Hub
25  * @author Brion Vibber <brion@status.net>
26  */
27 class HubSub extends Managed_DataObject
28 {
29     public $__table = 'hubsub';
30
31     public $hashkey; // sha1(topic . '|' . $callback); (topic, callback) key is too long for myisam in utf8
32     public $topic;      // varchar(191)   not 255 because utf8mb4 takes more space
33     public $callback;   // varchar(191)   not 255 because utf8mb4 takes more space
34     public $secret;
35     public $sub_start;
36     public $sub_end;
37     public $created;
38     public $modified;
39
40     static function hashkey($topic, $callback)
41     {
42         return sha1($topic . '|' . $callback);
43     }
44
45     public static function getByHashkey($topic, $callback)
46     {
47         return self::getKV('hashkey', self::hashkey($topic, $callback));
48     }
49
50     public static function schemaDef()
51     {
52         return array(
53             'fields' => array(
54                 'hashkey' => array('type' => 'char', 'not null' => true, 'length' => 40, 'description' => 'HubSub hashkey'),
55                 'topic' => array('type' => 'varchar', 'not null' => true, 'length' => 191, 'description' => 'HubSub topic'),
56                 'callback' => array('type' => 'varchar', 'not null' => true, 'length' => 191, 'description' => 'HubSub callback'),
57                 'secret' => array('type' => 'text', 'description' => 'HubSub stored secret'),
58                 'sub_start' => array('type' => 'datetime', 'description' => 'subscription start'),
59                 'sub_end' => array('type' => 'datetime', 'description' => 'subscription end'),
60                 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
61                 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
62             ),
63             'primary key' => array('hashkey'),
64             'indexes' => array(
65                 'hubsub_callback_idx' => array('callback'),
66                 'hubsub_topic_idx' => array('topic'),
67             ),
68         );
69     }
70
71     /**
72      * Validates a requested lease length, sets length plus
73      * subscription start & end dates.
74      *
75      * Does not save to database -- use before insert() or update().
76      *
77      * @param int $length in seconds
78      */
79     function setLease($length)
80     {
81         common_debug('PuSH hub got requested lease_seconds=='._ve($length));
82         assert(is_int($length));
83
84         $min = 86400;   // 3600*24 (one day)
85         $max = 86400 * 30;
86
87         if ($length == 0) {
88             // We want to garbage collect dead subscriptions!
89             $length = $max;
90         } elseif( $length < $min) {
91             $length = $min;
92         } else if ($length > $max) {
93             $length = $max;
94         }
95
96         common_debug('PuSH hub after sanitation: lease_seconds=='._ve($length));
97         $this->sub_start = common_sql_now();
98         $this->sub_end = common_sql_date(time() + $length);
99     }
100
101     function getLeaseTime()
102     {
103         if (empty($this->sub_start) || empty($this->sub_end)) {
104             return null;
105         }
106         $length = strtotime($this->sub_end) - strtotime($this->sub_start);
107         assert($length > 0);
108         return $length;
109     }
110
111     function getLeaseRemaining()
112     {
113         if (empty($this->sub_end)) {
114             return null;
115         }
116         return strtotime($this->sub_end) - time();
117     }
118
119     /**
120      * Schedule a future verification ping to the subscriber.
121      * If queues are disabled, will be immediate.
122      *
123      * @param string $mode 'subscribe' or 'unsubscribe'
124      * @param string $token hub.verify_token value, if provided by client
125      */
126     function scheduleVerify($mode, $token=null, $retries=null)
127     {
128         if ($retries === null) {
129             $retries = intval(common_config('ostatus', 'hub_retries'));
130         }
131         $data = array('sub' => clone($this),
132                       'mode' => $mode,
133                       'token' => $token,    // let's put it in there if remote uses PuSH <0.4
134                       'retries' => $retries);
135         $qm = QueueManager::get();
136         $qm->enqueue($data, 'hubconf');
137     }
138
139     public function getTopic()
140     {
141         return $this->topic;
142     }
143
144     /**
145      * Send a verification ping to subscriber, and if confirmed apply the changes.
146      * This may create, update, or delete the database record.
147      *
148      * @param string $mode 'subscribe' or 'unsubscribe'
149      * @param string $token hub.verify_token value, if provided by client
150      * @throws ClientException on failure
151      */
152     function verify($mode, $token=null)
153     {
154         assert($mode == 'subscribe' || $mode == 'unsubscribe');
155
156         $challenge = common_random_hexstr(32);
157         $params = array('hub.mode' => $mode,
158                         'hub.topic' => $this->getTopic(),
159                         'hub.challenge' => $challenge);
160         if ($mode == 'subscribe') {
161             $params['hub.lease_seconds'] = $this->getLeaseTime();
162         }
163         if ($token !== null) {  // TODO: deprecated in PuSH 0.4
164             $params['hub.verify_token'] = $token;   // let's put it in there if remote uses PuSH <0.4
165         }
166
167         // Any existing query string parameters must be preserved
168         $url = $this->callback;
169         if (strpos($url, '?') !== false) {
170             $url .= '&';
171         } else {
172             $url .= '?';
173         }
174         $url .= http_build_query($params, '', '&');
175
176         $request = new HTTPClient();
177         $response = $request->get($url);
178         $status = $response->getStatus();
179
180         if ($status >= 200 && $status < 300) {
181             common_log(LOG_INFO, "Verified {$mode} of {$this->callback}:{$this->getTopic()}");
182         } else {
183             // TRANS: Client exception. %s is a HTTP status code.
184             throw new ClientException(sprintf(_m('Hub subscriber verification returned HTTP %s.'),$status));
185         }
186
187         $old = HubSub::getByHashkey($this->getTopic(), $this->callback);
188         if ($mode == 'subscribe') {
189             if ($old instanceof HubSub) {
190                 $this->update($old);
191             } else {
192                 $ok = $this->insert();
193             }
194         } else if ($mode == 'unsubscribe') {
195             if ($old instanceof HubSub) {
196                 $old->delete();
197             } else {
198                 // That's ok, we're already unsubscribed.
199             }
200         }
201     }
202
203     // set the hashkey automagically on insert
204     protected function onInsert()
205     {
206         $this->setHashkey();
207         $this->created = common_sql_now();
208         $this->modified = common_sql_now();
209     }
210
211     // update the hashkey automagically if needed
212     protected function onUpdateKeys(Managed_DataObject $orig)
213     {
214         if ($this->topic !== $orig->topic || $this->callback !== $orig->callback) {
215             $this->setHashkey();
216         }
217     }
218
219     protected function setHashkey()
220     {
221         $this->hashkey = self::hashkey($this->topic, $this->callback);
222     }
223
224     /**
225      * Schedule delivery of a 'fat ping' to the subscriber's callback
226      * endpoint. If queues are disabled, this will run immediately.
227      *
228      * @param string $atom well-formed Atom feed
229      * @param int $retries optional count of retries if POST fails; defaults to hub_retries from config or 0 if unset
230      */
231     function distribute($atom, $retries=null)
232     {
233         if ($retries === null) {
234             $retries = intval(common_config('ostatus', 'hub_retries'));
235         }
236
237         // We dare not clone() as when the clone is discarded it'll
238         // destroy the result data for the parent query.
239         // @fixme use clone() again when it's safe to copy an
240         // individual item from a multi-item query again.
241         $sub = HubSub::getByHashkey($this->getTopic(), $this->callback);
242         $data = array('sub' => $sub,
243                       'atom' => $atom,
244                       'retries' => $retries);
245         common_log(LOG_INFO, "Queuing PuSH: {$this->getTopic()} to {$this->callback}");
246         $qm = QueueManager::get();
247         $qm->enqueue($data, 'hubout');
248     }
249
250     /**
251      * Queue up a large batch of pushes to multiple subscribers
252      * for this same topic update.
253      *
254      * If queues are disabled, this will run immediately.
255      *
256      * @param string $atom well-formed Atom feed
257      * @param array $pushCallbacks list of callback URLs
258      */
259     function bulkDistribute($atom, array $pushCallbacks)
260     {
261         if (empty($pushCallbacks)) {
262             common_log(LOG_ERR, 'Callback list empty for bulkDistribute.');
263             return false;
264         }
265         $data = array('atom' => $atom,
266                       'topic' => $this->getTopic(),
267                       'pushCallbacks' => $pushCallbacks);
268         common_log(LOG_INFO, "Queuing PuSH batch: {$this->getTopic()} to ".count($pushCallbacks)." sites");
269         $qm = QueueManager::get();
270         $qm->enqueue($data, 'hubprep');
271         return true;
272     }
273
274     /**
275      * Send a 'fat ping' to the subscriber's callback endpoint
276      * containing the given Atom feed chunk.
277      *
278      * Determination of which items to send should be done at
279      * a higher level; don't just shove in a complete feed!
280      *
281      * @param string $atom well-formed Atom feed
282      * @throws Exception (HTTP or general)
283      */
284     function push($atom)
285     {
286         $headers = array('Content-Type: application/atom+xml');
287         if ($this->secret) {
288             $hmac = hash_hmac('sha1', $atom, $this->secret);
289             $headers[] = "X-Hub-Signature: sha1=$hmac";
290         } else {
291             $hmac = '(none)';
292         }
293         common_log(LOG_INFO, "About to push feed to $this->callback for {$this->getTopic()}, HMAC $hmac");
294
295         $request = new HTTPClient();
296         $request->setConfig(array('follow_redirects' => false));
297         $request->setBody($atom);
298         try {
299             $response = $request->post($this->callback, $headers);
300
301             if ($response->isOk()) {
302                 return true;
303             }
304         } catch (Exception $e) {
305             $response = null;
306
307             common_debug('PuSH callback to '._ve($this->callback).' for '._ve($this->getTopic()).' failed with exception: '._ve($e->getMessage()));
308         }
309
310         // XXX: DO NOT trust a Location header here, _especially_ from 'http' protocols,
311         // but not 'https' either at least if we don't do proper CA verification. Trust that
312         // the most common change here is simply switching 'http' to 'https' and we will
313         // solve 99% of all of these issues for now. There should be a proper mechanism
314         // if we want to change the callback URLs, preferrably just manual resubscriptions
315         // from the remote side, combined with implemented PuSH subscription timeouts.
316
317         // We failed the PuSH, but it might be that the remote site has changed their configuration to HTTPS
318         if ('http' === parse_url($this->callback, PHP_URL_SCHEME)) {
319             // Test if the feed callback for this node has migrated to HTTPS
320             $httpscallback = preg_replace('/^http/', 'https', $this->callback, 1);
321             $alreadyreplaced = self::getByHashKey($this->getTopic(), $httpscallback);
322             if ($alreadyreplaced instanceof HubSub) {
323                 $this->delete();
324                 throw new AlreadyFulfilledException('The remote side has already established an HTTPS callback, deleting the legacy HTTP entry.');
325             }
326
327             common_debug('PuSH callback to '._ve($this->callback).' for '._ve($this->getTopic()).' trying HTTPS callback: '._ve($httpscallback));
328             $response = $request->post($httpscallback, $headers);
329             if ($response->isOk()) {
330                 $orig = clone($this);
331                 $this->callback = $httpscallback;
332                 // NOTE: hashkey will be set in $this->onUpdateKeys($orig) through updateWithKeys
333                 $this->updateWithKeys($orig);
334                 return true;
335             }
336         }
337
338         // FIXME: Add 'failed' incremental count for this callback.
339
340         if (is_null($response)) {
341             // This means we got a lower-than-HTTP level error, like domain not found or maybe connection refused
342             // This should be using a more distinguishable exception class, but for now this will do.
343             throw new Exception(sprintf(_m('HTTP request failed without response to URL: %s'), _ve(isset($httpscallback) ? $httpscallback : $this->callback)));
344         }
345
346         // TRANS: Exception. %1$s is a response status code, %2$s is the body of the response.
347         throw new Exception(sprintf(_m('Callback returned status: %1$s. Body: %2$s'),
348                             $response->getStatus(),trim($response->getBody())));
349     }
350 }