We are no longer offering accounts on this server. Consider https://gitlab.freedesktop.org/ as a place to host projects.

FeedSub.php 19.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
<?php
/*
 * StatusNet - the distributed open-source microblogging tool
 * Copyright (C) 2009-2010, StatusNet, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

20 21 22 23
if (!defined('STATUSNET')) {
    exit(1);
}

24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
/**
 * @package OStatusPlugin
 * @maintainer Brion Vibber <brion@status.net>
 */

/*
PuSH subscription flow:

    $profile->subscribe()
        sends a sub request to the hub...

    main/push/callback
        hub sends confirmation back to us via GET
        We verify the request, then echo back the challenge.
        On our end, we save the time we subscribed and the lease expiration

    main/push/callback
        hub sends us updates via POST

*/
class FeedDBException extends FeedSubException
{
    public $obj;

    function __construct($obj)
    {
        parent::__construct('Database insert failure');
        $this->obj = $obj;
    }
}

/**
 * FeedSub handles low-level PubHubSubbub (PuSH) subscriptions.
 * Higher-level behavior building OStatus stuff on top is handled
 * under Ostatus_profile.
 */
60
class FeedSub extends Managed_DataObject
61 62 63 64
{
    public $__table = 'feedsub';

    public $id;
65
    public $uri;    // varchar(191)   not 255 because utf8mb4 takes more space
66 67 68 69

    // PuSH subscription data
    public $huburi;
    public $secret;
70
    public $sub_state; // subscribe, active, unsubscribe, inactive, nohub
71 72 73 74 75 76 77
    public $sub_start;
    public $sub_end;
    public $last_update;

    public $created;
    public $modified;

78
    public static function schemaDef()
79
    {
80 81
        return array(
            'fields' => array(
82
                'id' => array('type' => 'serial', 'not null' => true, 'description' => 'FeedSub local unique id'),
83
                'uri' => array('type' => 'varchar', 'not null' => true, 'length' => 191, 'description' => 'FeedSub uri'),
84 85
                'huburi' => array('type' => 'text', 'description' => 'FeedSub hub-uri'),
                'secret' => array('type' => 'text', 'description' => 'FeedSub stored secret'),
86
                'sub_state' => array('type' => 'enum("subscribe","active","unsubscribe","inactive","nohub")', 'not null' => true, 'description' => 'subscription state'),
87 88
                'sub_start' => array('type' => 'datetime', 'description' => 'subscription start'),
                'sub_end' => array('type' => 'datetime', 'description' => 'subscription end'),
89
                'last_update' => array('type' => 'datetime', 'description' => 'when this record was last updated'),
90 91 92 93 94 95 96 97
                'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
                'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
            ),
            'primary key' => array('id'),
            'unique keys' => array(
                'feedsub_uri_key' => array('uri'),
            ),
        );
98 99
    }

100 101 102 103 104 105
    /**
     * Get the feed uri (http/https)
     */
    public function getUri()
    {
        if (empty($this->uri)) {
106
            throw new NoUriException($this);
107 108 109 110
        }
        return $this->uri;
    }

mattl's avatar
mattl committed
111 112 113 114 115 116 117 118
    function getLeaseRemaining()
    {
        if (empty($this->sub_end)) {
            return null;
        }
        return strtotime($this->sub_end) - time();
    }

119 120 121 122
    /**
     * Do we have a hub? Then we are a PuSH feed.
     * https://en.wikipedia.org/wiki/PubSubHubbub
     *
123 124 125
     * If huburi is empty, then doublecheck that we are not using
     * a fallback hub. If there is a fallback hub, it is only if the
     * sub_state is "nohub" that we assume it's not a PuSH feed.
126 127 128
     */
    public function isPuSH()
    {
129 130 131 132 133 134 135 136
        if (empty($this->huburi)
                && (!common_config('feedsub', 'fallback_hub')
                    || $this->sub_state === 'nohub')) {
                // Here we have no huburi set. Also, either there is no 
                // fallback hub configured or sub_state is "nohub".
            return false;
        }
        return true;
137 138
    }

139 140 141 142 143 144 145
    /**
     * Fetch the StatusNet-side profile for this feed
     * @return Profile
     */
    public function localProfile()
    {
        if ($this->profile_id) {
146
            return Profile::getKV('id', $this->profile_id);
147 148 149 150 151 152 153 154 155 156 157
        }
        return null;
    }

    /**
     * Fetch the StatusNet-side profile for this feed
     * @return Profile
     */
    public function localGroup()
    {
        if ($this->group_id) {
158
            return User_group::getKV('id', $this->group_id);
159 160 161 162 163 164 165 166 167 168 169
        }
        return null;
    }

    /**
     * @param string $feeduri
     * @return FeedSub
     * @throws FeedSubException if feed is invalid or lacks PuSH setup
     */
    public static function ensureFeed($feeduri)
    {
170
        $current = self::getKV('uri', $feeduri);
171
        if ($current instanceof FeedSub) {
172 173 174 175 176 177
            return $current;
        }

        $discover = new FeedDiscovery();
        $discover->discoverFromFeedURL($feeduri);

178
        $huburi = $discover->getHubLink();
179
        if (!$huburi && !common_config('feedsub', 'fallback_hub') && !common_config('feedsub', 'nohub')) {
180 181 182 183 184 185 186 187 188 189 190 191
            throw new FeedSubNoHubException();
        }

        $feedsub = new FeedSub();
        $feedsub->uri = $feeduri;
        $feedsub->huburi = $huburi;
        $feedsub->sub_state = 'inactive';

        $feedsub->created = common_sql_now();
        $feedsub->modified = common_sql_now();

        $result = $feedsub->insert();
192
        if ($result === false) {
193 194 195 196 197 198 199 200 201 202
            throw new FeedDBException($feedsub);
        }

        return $feedsub;
    }

    /**
     * Send a subscription request to the hub for this feed.
     * The hub will later send us a confirmation POST to /main/push/callback.
     *
203
     * @return void
204 205
     * @throws ServerException if feed state is not valid
     */
206
    public function subscribe()
207 208
    {
        if ($this->sub_state && $this->sub_state != 'inactive') {
209
            common_log(LOG_WARNING, sprintf('Attempting to (re)start PuSH subscription to %s in unexpected state %s', $this->getUri(), $this->sub_state));
210
        }
211 212 213

        if (!Event::handle('FeedSubscribe', array($this))) {
            // A plugin handled it
214
            return;
215 216
        }

217
        if (empty($this->huburi)) {
218 219 220 221
            if (common_config('feedsub', 'fallback_hub')) {
                // No native hub on this feed?
                // Use our fallback hub, which handles polling on our behalf.
            } else if (common_config('feedsub', 'nohub')) {
222 223
                // For this to actually work, we'll need some polling mechanism.
                // The FeedPoller plugin should take care of it.
224
                return;
225
            } else {
226
                // TRANS: Server exception.
Siebrand Mazeland's avatar
Siebrand Mazeland committed
227
                throw new ServerException(_m('Attempting to start PuSH subscription for feed with no hub.'));
228 229 230
            }
        }

231
        $this->doSubscribe('subscribe');
232 233 234 235 236
    }

    /**
     * Send a PuSH unsubscription request to the hub for this feed.
     * The hub will later send us a confirmation POST to /main/push/callback.
237 238 239
     * Warning: this will cancel the subscription even if someone else in
     * the system is using it. Most callers will want garbageCollect() instead,
     * which confirms there's no uses left.
240 241 242 243 244
     *
     * @throws ServerException if feed state is not valid
     */
    public function unsubscribe() {
        if ($this->sub_state != 'active') {
245
            common_log(LOG_WARNING, sprintf('Attempting to (re)end PuSH subscription to %s in unexpected state %s', $this->getUri(), $this->sub_state));
246
        }
247 248 249

        if (!Event::handle('FeedUnsubscribe', array($this))) {
            // A plugin handled it
250
            return;
251 252
        }

253
        if (empty($this->huburi)) {
254 255 256 257
            if (common_config('feedsub', 'fallback_hub')) {
                // No native hub on this feed?
                // Use our fallback hub, which handles polling on our behalf.
            } else if (common_config('feedsub', 'nohub')) {
258 259
                // We need a feedpolling plugin (like FeedPoller) active so it will
                // set the 'nohub' state to 'inactive' for us.
260
                return;
261
            } else {
262
                // TRANS: Server exception.
Siebrand Mazeland's avatar
Siebrand Mazeland committed
263
                throw new ServerException(_m('Attempting to end PuSH subscription for feed with no hub.'));
264 265 266
            }
        }

267
        $this->doSubscribe('unsubscribe');
268 269
    }

270 271 272 273 274
    /**
     * Check if there are any active local uses of this feed, and if not then
     * make sure it's inactive, unsubscribing if necessary.
     *
     * @return boolean true if the subscription is now inactive, false if still active.
275
     * @throws NoProfileException in FeedSubSubscriberCount for missing Profile entries
276
     * @throws Exception if something goes wrong in unsubscribe() method
277 278 279 280 281 282 283
     */
    public function garbageCollect()
    {
        if ($this->sub_state == '' || $this->sub_state == 'inactive') {
            // No active PuSH subscription, we can just leave it be.
            return true;
        }
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299

        // PuSH subscription is either active or in an indeterminate state.
        // Check if we're out of subscribers, and if so send an unsubscribe.
        $count = 0;
        Event::handle('FeedSubSubscriberCount', array($this, &$count));

        if ($count > 0) {
            common_log(LOG_INFO, __METHOD__ . ': ok, ' . $count . ' user(s) left for ' . $this->getUri());
            return false;
        }

        common_log(LOG_INFO, __METHOD__ . ': unsubscribing, no users left for ' . $this->getUri());
        // Unsubscribe throws various Exceptions on failure
        $this->unsubscribe();

        return true;
300 301
    }

302 303 304 305
    static public function renewalCheck()
    {
        $fs = new FeedSub();
        // the "" empty string check is because we historically haven't saved unsubscribed feeds as NULL
306
        $fs->whereAdd('sub_end IS NOT NULL AND sub_end!="" AND sub_end < NOW() + INTERVAL 1 day');
307
        if (!$fs->find()) { // find can be both false and 0, depending on why nothing was found
308 309 310 311 312 313 314 315 316 317 318
            throw new NoResultException($fs);
        }
        return $fs;
    }

    public function renew()
    {
        $this->subscribe();
    }

    /**
319 320 321 322 323 324
     * Setting to subscribe means it is _waiting_ to become active. This
     * cannot be done in a transaction because there is a chance that the
     * remote script we're calling (as in the case of PuSHpress) performs
     * the lookup _while_ we're POSTing data, which means the transaction
     * never completes (PushcallbackAction gets an 'inactive' state).
     *
325 326
     * @return boolean true when everything is ok (throws Exception on fail)
     * @throws Exception on failure, can be HTTPClient's or our own.
327
     */
328 329 330 331
    protected function doSubscribe($mode)
    {
        $orig = clone($this);
        if ($mode == 'subscribe') {
332
            $this->secret = common_random_hexstr(32);
333 334 335 336 337 338 339 340 341 342
        }
        $this->sub_state = $mode;
        $this->update($orig);
        unset($orig);

        try {
            $callback = common_local_url('pushcallback', array('feed' => $this->id));
            $headers = array('Content-Type: application/x-www-form-urlencoded');
            $post = array('hub.mode' => $mode,
                          'hub.callback' => $callback,
mattl's avatar
mattl committed
343
                          'hub.verify' => 'async',  // TODO: deprecated, remove when noone uses PuSH <0.4 (only 'async' method used there)
344 345
                          'hub.verify_token' => 'Deprecated-since-PuSH-0.4', // TODO: rm!

346
                          'hub.lease_seconds' => 2592000,   // 3600*24*30, request approximately month long lease (may be changed by hub)
347
                          'hub.secret' => $this->secret,
348
                          'hub.topic' => $this->getUri());
349
            $client = new HTTPClient();
350 351 352 353 354 355 356 357 358 359 360
            if ($this->huburi) {
                $hub = $this->huburi;
            } else {
                if (common_config('feedsub', 'fallback_hub')) {
                    $hub = common_config('feedsub', 'fallback_hub');
                    if (common_config('feedsub', 'hub_user')) {
                        $u = common_config('feedsub', 'hub_user');
                        $p = common_config('feedsub', 'hub_pass');
                        $client->setAuth($u, $p);
                    }
                } else {
361
                    throw new FeedSubException('Server could not find a usable PuSH hub.');
362 363 364
                }
            }
            $response = $client->post($hub, $headers, $post);
365
            $status = $response->getStatus();
366
            // PuSH specificed response status code
367
            if ($status == 202  || $status == 204) {
368
                common_log(LOG_INFO, __METHOD__ . ': sub req ok, awaiting verification callback');
369
                return;
370 371 372 373 374 375
            } else if ($status >= 200 && $status < 300) {
                common_log(LOG_ERR, __METHOD__ . ": sub req returned unexpected HTTP $status: " . $response->getBody());
            } else {
                common_log(LOG_ERR, __METHOD__ . ": sub req failed with HTTP $status: " . $response->getBody());
            }
        } catch (Exception $e) {
376
            common_log(LOG_ERR, __METHOD__ . ": error \"{$e->getMessage()}\" hitting hub {$this->huburi} subscribing to {$this->getUri()}");
377

378
            // Reset the subscription state.
379
            $orig = clone($this);
Brion Vibber's avatar
Brion Vibber committed
380
            $this->sub_state = 'inactive';
381
            $this->update($orig);
382 383 384

            // Throw the Exception again.
            throw $e;
385
        }
386
        throw new ServerException("{$mode} request failed.");
387 388 389 390 391 392 393 394
    }

    /**
     * Save PuSH subscription confirmation.
     * Sets approximate lease start and end times and finalizes state.
     *
     * @param int $lease_seconds provided hub.lease_seconds parameter, if given
     */
395
    public function confirmSubscribe($lease_seconds)
396 397 398 399 400 401 402 403
    {
        $original = clone($this);

        $this->sub_state = 'active';
        $this->sub_start = common_sql_date(time());
        if ($lease_seconds > 0) {
            $this->sub_end = common_sql_date(time() + $lease_seconds);
        } else {
404
            $this->sub_end = null;  // Backwards compatibility to StatusNet (PuSH <0.4 supported permanent subs)
405
        }
Brion Vibber's avatar
Brion Vibber committed
406
        $this->modified = common_sql_now();
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423

        return $this->update($original);
    }

    /**
     * Save PuSH unsubscription confirmation.
     * Wipes active PuSH sub info and resets state.
     */
    public function confirmUnsubscribe()
    {
        $original = clone($this);

        // @fixme these should all be null, but DB_DataObject doesn't save null values...?????
        $this->secret = '';
        $this->sub_state = '';
        $this->sub_start = '';
        $this->sub_end = '';
Brion Vibber's avatar
Brion Vibber committed
424
        $this->modified = common_sql_now();
425 426 427 428 429 430 431 432 433

        return $this->update($original);
    }

    /**
     * Accept updates from a PuSH feed. If validated, this object and the
     * feed (as a DOMDocument) will be passed to the StartFeedSubHandleFeed
     * and EndFeedSubHandleFeed events for processing.
     *
Brion Vibber's avatar
Brion Vibber committed
434 435 436 437 438 439
     * Not guaranteed to be running in an immediate POST context; may be run
     * from a queue handler.
     *
     * Side effects: the feedsub record's lastupdate field will be updated
     * to the current time (not published time) if we got a legit update.
     *
440 441 442 443 444
     * @param string $post source of Atom or RSS feed
     * @param string $hmac X-Hub-Signature header, if present
     */
    public function receive($post, $hmac)
    {
445
        common_log(LOG_INFO, __METHOD__ . ": packet for \"" . $this->getUri() . "\"! $hmac $post");
446

mattl's avatar
mattl committed
447
        if (!in_array($this->sub_state, array('active', 'nohub'))) {
448
            common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH for inactive feed " . $this->getUri() . " (in state '$this->sub_state')");
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
            return;
        }

        if ($post === '') {
            common_log(LOG_ERR, __METHOD__ . ": ignoring empty post");
            return;
        }

        if (!$this->validatePushSig($post, $hmac)) {
            // Per spec we silently drop input with a bad sig,
            // while reporting receipt to the server.
            return;
        }

        $feed = new DOMDocument();
        if (!$feed->loadXML($post)) {
            // @fixme might help to include the err message
            common_log(LOG_ERR, __METHOD__ . ": ignoring invalid XML");
            return;
        }

Brion Vibber's avatar
Brion Vibber committed
470 471 472 473
        $orig = clone($this);
        $this->last_update = common_sql_now();
        $this->update($orig);

474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
        Event::handle('StartFeedSubReceive', array($this, $feed));
        Event::handle('EndFeedSubReceive', array($this, $feed));
    }

    /**
     * Validate the given Atom chunk and HMAC signature against our
     * shared secret that was set up at subscription time.
     *
     * If we don't have a shared secret, there should be no signature.
     * If we we do, our the calculated HMAC should match theirs.
     *
     * @param string $post raw XML source as POSTed to us
     * @param string $hmac X-Hub-Signature HTTP header value, or empty
     * @return boolean true for a match
     */
    protected function validatePushSig($post, $hmac)
    {
        if ($this->secret) {
            if (preg_match('/^sha1=([0-9a-fA-F]{40})$/', $hmac, $matches)) {
                $their_hmac = strtolower($matches[1]);
494
                $our_hmac = hash_hmac('sha1', $post, $this->secret);
495 496 497
                if ($their_hmac === $our_hmac) {
                    return true;
                }
498 499 500 501 502
                if (common_config('feedsub', 'debug')) {
                    $tempfile = tempnam(sys_get_temp_dir(), 'feedsub-receive');
                    if ($tempfile) {
                        file_put_contents($tempfile, $post);
                    }
503
                    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");
504
                } else {
505
                    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");
506
                }
507 508 509 510 511 512 513 514 515 516 517 518
            } else {
                common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH with bogus HMAC '$hmac'");
            }
        } else {
            if (empty($hmac)) {
                return true;
            } else {
                common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH with unexpected HMAC '$hmac'");
            }
        }
        return false;
    }
519 520 521 522 523

    public function delete($useWhere=false)
    {
        try {
            $oprofile = Ostatus_profile::getKV('feeduri', $this->getUri());
524 525 526 527
            if ($oprofile instanceof Ostatus_profile) {
                // Check if there's a profile. If not, handle the NoProfileException below
                $profile = $oprofile->localProfile();
            }
528 529 530 531 532 533 534 535
        } catch (NoProfileException $e) {
            // If the Ostatus_profile has no local Profile bound to it, let's clean it out at the same time
            $oprofile->delete();
        } catch (NoUriException $e) {
            // FeedSub->getUri() can throw a NoUriException, let's just go ahead and delete it
        }
        return parent::delete($useWhere);
    }
536
}