aboutsummaryrefslogtreecommitdiff
path: root/testdata/logs/1
diff options
context:
space:
mode:
Diffstat (limited to 'testdata/logs/1')
-rw-r--r--testdata/logs/1/logTest.log10
1 files changed, 10 insertions, 0 deletions
diff --git a/testdata/logs/1/logTest.log b/testdata/logs/1/logTest.log
new file mode 100644
index 0000000..6bf31c3
--- /dev/null
+++ b/testdata/logs/1/logTest.log
@@ -0,0 +1,10 @@
+2019-06-05T20:13 [INFO] testInfoString (LogTest.java:52)
+2019-06-05T20:13 [INFO][YO] testInfoString (LogTest.java:57)
+2019-06-05T20:13 [INFO] testInfoString (LogTest.java:52)
+2019-06-05T20:13 [INFO][YO] testInfoString (LogTest.java:57)
+2019-06-05T20:51 [INFO] testInfoString (LogTest.java:52)
+2019-06-05T20:51 [INFO][YO] testInfoString (LogTest.java:57)
+2019-06-05T22:41 [INFO] testInfoString (LogTest.java:52)
+2019-06-05T22:41 [INFO][YO] testInfoString (LogTest.java:57)
+2019-06-05T23:02 [INFO] testInfoString (LogTest.java:52)
+2019-06-05T23:02 [INFO][YO] testInfoString (LogTest.java:57)
href='#n135'>135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
// SPDX-FileCopyrightText: 2015 Felix Rohrbach <kde@fxrh.de>
// SPDX-FileCopyrightText: 2016 Kitsune Ral <Kitsune-Ral@users.sf.net>
// SPDX-License-Identifier: LGPL-2.1-or-later

#include "basejob.h"

#include "connectiondata.h"

#include <QtCore/QRegularExpression>
#include <QtCore/QTimer>
#include <QtCore/QMetaEnum>
#include <QtCore/QPointer>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>
#include <QtNetwork/QNetworkRequest>

using namespace Quotient;
using std::chrono::seconds, std::chrono::milliseconds;
using namespace std::chrono_literals;

BaseJob::StatusCode BaseJob::Status::fromHttpCode(int httpCode)
{
    // Based on https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
    if (httpCode / 10 == 41) // 41x errors
        return httpCode == 410 ? IncorrectRequest : NotFound;
    switch (httpCode) {
    case 401:
        return Unauthorised;
        // clang-format off
    case 403: case 407: // clang-format on
        return ContentAccessError;
    case 404:
        return NotFound;
        // clang-format off
    case 400: case 405: case 406: case 426: case 428: case 505: // clang-format on
    case 494: // Unofficial nginx "Request header too large"
    case 497: // Unofficial nginx "HTTP request sent to HTTPS port"
        return IncorrectRequest;
    case 429:
        return TooManyRequests;
    case 501:
    case 510:
        return RequestNotImplemented;
    case 511:
        return NetworkAuthRequired;
    default:
        return NetworkError;
    }
}

QDebug BaseJob::Status::dumpToLog(QDebug dbg) const
{
    QDebugStateSaver _s(dbg);
    dbg.noquote().nospace();
    if (auto* const k = QMetaEnum::fromType<StatusCode>().valueToKey(code)) {
        const QByteArray b = k;
        dbg << b.mid(b.lastIndexOf(':'));
    } else
        dbg << code;
    return dbg << ": " << message;
}

class BaseJob::Private {
public:
    struct JobTimeoutConfig {
        seconds jobTimeout;
        seconds nextRetryInterval;
    };

    // Using an idiom from clang-tidy:
    // http://clang.llvm.org/extra/clang-tidy/checks/modernize-pass-by-value.html
    Private(HttpVerb v, QByteArray endpoint, const QUrlQuery& q,
            RequestData&& data, bool nt)
        : verb(v)
        , apiEndpoint(std::move(endpoint))
        , requestQuery(q)
        , requestData(std::move(data))
        , needsToken(nt)
    {
        timer.setSingleShot(true);
        retryTimer.setSingleShot(true);
    }

    ~Private()
    {
        if (reply) {
            if (reply->isRunning()) {
                reply->abort();
            }
            delete reply;
        }
    }

    void sendRequest();
    /*! \brief Parse the response byte array into JSON
     *
     * This calls QJsonDocument::fromJson() on rawResponse, converts
     * the QJsonParseError result to BaseJob::Status and stores the resulting
     * JSON in jsonResponse.
     */
    Status parseJson();

    ConnectionData* connection = nullptr;

    // Contents for the network request
    HttpVerb verb;
    QByteArray apiEndpoint;
    QHash<QByteArray, QByteArray> requestHeaders;
    QUrlQuery requestQuery;
    RequestData requestData;
    bool needsToken;

    bool inBackground = false;

    // There's no use of QMimeType here because we don't want to match
    // content types against the known MIME type hierarchy; and at the same
    // type QMimeType is of little help with MIME type globs (`text/*` etc.)
    QByteArrayList expectedContentTypes { "application/json" };

    QByteArrayList expectedKeys;

    // When the QNetworkAccessManager is destroyed it destroys all pending replies.
    // Using QPointer allows us to know when that happend.
    QPointer<QNetworkReply> reply;

    Status status = Unprepared;
    QByteArray rawResponse;
    /// Contains a null document in case of non-JSON body (for a successful
    /// or unsuccessful response); a document with QJsonObject or QJsonArray
    /// in case of a successful response with JSON payload, as per the API
    /// definition (including an empty JSON object - QJsonObject{});
    /// and QJsonObject in case of an API error.
    QJsonDocument jsonResponse;
    QUrl errorUrl; //< May contain a URL to help with some errors

    LoggingCategory logCat = JOBS;

    QTimer timer;
    QTimer retryTimer;

    static constexpr auto errorStrategy = std::to_array<const JobTimeoutConfig>(
        { { 90s, 5s }, { 90s, 10s }, { 120s, 30s } });
    int maxRetries = int(errorStrategy.size());
    int retriesTaken = 0;

    [[nodiscard]] const JobTimeoutConfig& getCurrentTimeoutConfig() const
    {
        return errorStrategy[std::min(size_t(retriesTaken),
                                      errorStrategy.size() - 1)];
    }

    [[nodiscard]] QString dumpRequest() const
    {
        static const std::array verbs { "GET"_ls, "PUT"_ls, "POST"_ls,
                                        "DELETE"_ls };
        const auto verbWord = verbs.at(size_t(verb));
        return verbWord % ' '
               % (reply ? reply->url().toString(QUrl::RemoveQuery)
                        : makeRequestUrl(connection->baseUrl(), apiEndpoint)
                              .toString());
    }
};

inline bool isHex(QChar c)
{
    return c.isDigit() || (c >= u'A' && c <= u'F') || (c >= u'a' && c <= u'f');
}

QByteArray BaseJob::encodeIfParam(const QString& paramPart)
{
    const auto percentIndex = paramPart.indexOf('%');
    if (percentIndex != -1 && paramPart.size() > percentIndex + 2
        && isHex(paramPart[percentIndex + 1])
        && isHex(paramPart[percentIndex + 2])) {
        qCWarning(JOBS)
            << "Developers, upfront percent-encoding of job parameters is "
               "deprecated since libQuotient 0.7; the string involved is"
            << paramPart;
        return QUrl(paramPart, QUrl::TolerantMode).toEncoded();
    }
    return QUrl::toPercentEncoding(paramPart);
}

BaseJob::BaseJob(HttpVerb verb, const QString& name, QByteArray endpoint,
                 bool needsToken)
    : BaseJob(verb, name, std::move(endpoint), QUrlQuery {}, RequestData {},
              needsToken)
{}

BaseJob::BaseJob(HttpVerb verb, const QString& name, QByteArray endpoint,
                 const QUrlQuery& query, RequestData&& data, bool needsToken)
    : d(makeImpl<Private>(verb, std::move(endpoint), query, std::move(data),
                          needsToken))
{
    setObjectName(name);
    connect(&d->timer, &QTimer::timeout, this, &BaseJob::timeout);
    connect(&d->retryTimer, &QTimer::timeout, this, [this] {
        qCDebug(d->logCat) << "Retrying" << this;
        d->connection->submit(this);
    });
}

BaseJob::~BaseJob()
{
    stop();
    d->retryTimer.stop(); // See #398
    qCDebug(d->logCat) << this << "destroyed";
}

QUrl BaseJob::requestUrl() const { return d->reply ? d->reply->url() : QUrl(); }

bool BaseJob::isBackground() const { return d->inBackground; }

const BaseJob::headers_t& BaseJob::requestHeaders() const
{
    return d->requestHeaders;
}

void BaseJob::setRequestHeader(const headers_t::key_type& headerName,
                               const headers_t::mapped_type& headerValue)
{
    d->requestHeaders[headerName] = headerValue;
}

void BaseJob::setRequestHeaders(const BaseJob::headers_t& headers)
{
    d->requestHeaders = headers;
}

QUrlQuery BaseJob::query() const { return d->requestQuery; }

void BaseJob::setRequestQuery(const QUrlQuery& query)
{
    d->requestQuery = query;
}

const RequestData& BaseJob::requestData() const { return d->requestData; }

void BaseJob::setRequestData(RequestData&& data)
{
    std::swap(d->requestData, data);
}

const QByteArrayList& BaseJob::expectedContentTypes() const
{
    return d->expectedContentTypes;
}

void BaseJob::addExpectedContentType(const QByteArray& contentType)
{
    d->expectedContentTypes << contentType;
}

void BaseJob::setExpectedContentTypes(const QByteArrayList& contentTypes)
{
    d->expectedContentTypes = contentTypes;
}

QByteArrayList BaseJob::expectedKeys() const { return d->expectedKeys; }

void BaseJob::addExpectedKey(const QByteArray& key) { d->expectedKeys << key; }

void BaseJob::setExpectedKeys(const QByteArrayList& keys)
{
    d->expectedKeys = keys;
}

const QNetworkReply* BaseJob::reply() const { return d->reply.data(); }

QNetworkReply* BaseJob::reply() { return d->reply.data(); }

QUrl BaseJob::makeRequestUrl(QUrl baseUrl, const QByteArray& encodedPath,
                             const QUrlQuery& query)
{
    // Make sure the added path is relative even if it's not (the official
    // API definitions have the leading slash though it's not really correct).
    const auto pathUrl =
        QUrl::fromEncoded(encodedPath.mid(encodedPath.startsWith('/')),
                          QUrl::StrictMode);
    Q_ASSERT_X(pathUrl.isValid(), __FUNCTION__,
               qPrintable(pathUrl.errorString()));
    baseUrl = baseUrl.resolved(pathUrl);
    baseUrl.setQuery(query);
    return baseUrl;
}

void BaseJob::Private::sendRequest()
{
    QNetworkRequest req { makeRequestUrl(connection->baseUrl(), apiEndpoint,
                                         requestQuery) };
    if (!requestHeaders.contains("Content-Type"))
        req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    if (needsToken)
        req.setRawHeader("Authorization",
                         QByteArray("Bearer ") + connection->accessToken());
    req.setAttribute(QNetworkRequest::BackgroundRequestAttribute, inBackground);
    req.setAttribute(QNetworkRequest::RedirectPolicyAttribute,
                     QNetworkRequest::NoLessSafeRedirectPolicy);
    req.setMaximumRedirectsAllowed(10);
    req.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, true);
    // Qt doesn't combine HTTP2 with SSL quite right, occasionally crashing at
    // what seems like an attempt to write to a closed channel. If/when that
    // changes, false should be turned to true below.
    req.setAttribute(QNetworkRequest::Http2AllowedAttribute, false);
    Q_ASSERT(req.url().isValid());
    for (auto it = requestHeaders.cbegin(); it != requestHeaders.cend(); ++it)
        req.setRawHeader(it.key(), it.value());

    switch (verb) {
    case HttpVerb::Get:
        reply = connection->nam()->get(req);
        break;
    case HttpVerb::Post:
        reply = connection->nam()->post(req, requestData.source());
        break;
    case HttpVerb::Put:
        reply = connection->nam()->put(req, requestData.source());
        break;
    case HttpVerb::Delete:
        reply = connection->nam()->sendCustomRequest(req, "DELETE", requestData.source());
        break;
    }
}

void BaseJob::doPrepare() { }

void BaseJob::onSentRequest(QNetworkReply*) { }

void BaseJob::beforeAbandon() { }

void BaseJob::initiate(ConnectionData* connData, bool inBackground)
{
    if (Q_LIKELY(connData && connData->baseUrl().isValid())) {
        d->inBackground = inBackground;
        d->connection = connData;
        doPrepare();

        if (d->needsToken && d->connection->accessToken().isEmpty())
            setStatus(Unauthorised);
        else if ((d->verb == HttpVerb::Post || d->verb == HttpVerb::Put)
            && d->requestData.source()
            && !d->requestData.source()->isReadable()) {
            setStatus(FileError, "Request data not ready");
        }
        Q_ASSERT(status().code != Pending); // doPrepare() must NOT set this
        if (Q_LIKELY(status().code == Unprepared)) {
            d->connection->submit(this);
            return;
        }
        qCWarning(d->logCat).noquote()
            << "Request failed preparation and won't be sent:"
            << d->dumpRequest();
    } else {
        qCCritical(d->logCat)
            << "Developers, ensure the Connection is valid before using it";
        Q_ASSERT(false);
        setStatus(IncorrectRequest, tr("Invalid server connection"));
    }
    // The status is no good, finalise
    QTimer::singleShot(0, this, &BaseJob::finishJob);
}

void BaseJob::sendRequest()
{
    if (status().code == Abandoned) {
        qCDebug(d->logCat) << "Won't proceed with the abandoned request:"
                           << d->dumpRequest();
        return;
    }
    Q_ASSERT(d->connection && status().code == Pending);
    qCDebug(d->logCat).noquote() << "Making" << d->dumpRequest();
    d->needsToken |= d->connection->needsToken(objectName());
    emit aboutToSendRequest();
    d->sendRequest();
    Q_ASSERT(d->reply);
    connect(reply(), &QNetworkReply::finished, this, [this] {
        gotReply();
        finishJob();
    });
    if (d->reply->isRunning()) {
        connect(reply(), &QNetworkReply::metaDataChanged, this,
                [this] { checkReply(reply()); });
        connect(reply(), &QNetworkReply::uploadProgress, this,
                &BaseJob::uploadProgress);
        connect(reply(), &QNetworkReply::downloadProgress, this,
                &BaseJob::downloadProgress);
        d->timer.start(getCurrentTimeout());
        qCInfo(d->logCat).noquote() << "Sent" << d->dumpRequest();
        onSentRequest(reply());
        emit sentRequest();
    } else
        qCCritical(d->logCat).noquote()
            << "Request could not start:" << d->dumpRequest();
}

BaseJob::Status BaseJob::Private::parseJson()
{
    QJsonParseError error { 0, QJsonParseError::MissingObject };
    jsonResponse = QJsonDocument::fromJson(rawResponse, &error);
    return { error.error == QJsonParseError::NoError ? NoError
                                                     : IncorrectResponse,
             error.errorString() };
}

void BaseJob::gotReply()
{
    // Defer actually updating the status until it's finalised
    auto statusSoFar = checkReply(reply());
    if (statusSoFar.good()
        && d->expectedContentTypes == QByteArrayList { "application/json" }) //
    {
        d->rawResponse = reply()->readAll();
        statusSoFar = d->parseJson();
        if (statusSoFar.good() && !expectedKeys().empty()) {
            const auto& responseObject = jsonData();
            QByteArrayList missingKeys;
            for (const auto& k: expectedKeys())
                if (!responseObject.contains(k))
                    missingKeys.push_back(k);
            if (!missingKeys.empty())
                statusSoFar = { IncorrectResponse,
                                tr("Required JSON keys missing: ")
                                    + missingKeys.join() };
        }
        setStatus(statusSoFar);
        if (!status().good()) // Bad JSON in a "good" reply: bail out
            return;
    }
    // If the endpoint expects anything else than just (API-related) JSON
    // reply()->readAll() is not performed and the whole reply processing
    // is left to derived job classes: they may read it piecemeal or customise
    // per content type in prepareResult(), or even have read it already
    // (see, e.g., DownloadFileJob).
    if (statusSoFar.good()) {
        setStatus(prepareResult());
        return;
    }

    d->rawResponse = reply()->readAll();
    qCDebug(d->logCat).noquote()
        << "Error body (truncated if long):" << rawDataSample(500);
    setStatus(prepareError(statusSoFar));
}

bool checkContentType(const QByteArray& type, const QByteArrayList& patterns)
{
    if (patterns.isEmpty())
        return true;

    // ignore possible appendixes of the content type
    const auto ctype = type.split(';').front();

    for (const auto& pattern: patterns) {
        if (pattern.startsWith('*') || ctype == pattern) // Fast lane
            return true;

        auto patternParts = pattern.split('/');
        Q_ASSERT_X(patternParts.size() <= 2, __FUNCTION__,
                   "BaseJob: Expected content type should have up to two"
                   " /-separated parts; violating pattern: "
                       + pattern);

        if (ctype.split('/').front() == patternParts.front()
            && patternParts.back() == "*")
            return true; // Exact match already went on fast lane
    }

    return false;
}

BaseJob::Status BaseJob::checkReply(const QNetworkReply* reply) const
{
    // QNetworkReply error codes are insufficient for our purposes (e.g. they
    // don't allow to discern HTTP code 429) so check the original code instead
    const auto httpCodeHeader =
        reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    if (!httpCodeHeader.isValid()) {
        qCWarning(d->logCat).noquote()
            << "No valid HTTP headers from" << d->dumpRequest();
        return { NetworkError, reply->errorString() };
    }

    const auto httpCode = httpCodeHeader.toInt();
    if (httpCode / 100 == 2) // 2xx
    {
        if (reply->isFinished())
            qCInfo(d->logCat).noquote() << httpCode << "<-" << d->dumpRequest();
        if (!checkContentType(reply->rawHeader("Content-Type"),
                              d->expectedContentTypes))
            return { UnexpectedResponseTypeWarning,
                     "Unexpected content type of the response" };
        return NoError;
    }
    if (reply->isFinished())
        qCWarning(d->logCat).noquote() << httpCode << "<-" << d->dumpRequest();

    auto message = reply->errorString();
    if (message.isEmpty())
        message = reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute)
                      .toString();

    return Status::fromHttpCode(httpCode, message);
}

BaseJob::Status BaseJob::prepareResult() { return Success; }

BaseJob::Status BaseJob::prepareError(Status currentStatus)
{
    // Try to make sense of the error payload but be prepared for all kinds
    // of unexpected stuff (raw HTML, plain text, foreign JSON among those)
    if (!d->rawResponse.isEmpty()
        && reply()->rawHeader("Content-Type") == "application/json")
        d->parseJson();

    // By now, if d->parseJson() above succeeded then jsonData() will return
    // a valid JSON object - or an empty object otherwise (in which case most
    // of if's below will fall through retaining the current status)
    const auto& errorJson = jsonData();
    const auto errCode = errorJson.value("errcode"_ls).toString();
    if (error() == TooManyRequests || errCode == "M_LIMIT_EXCEEDED") {
        QString msg = tr("Too many requests");
        int64_t retryAfterMs = errorJson.value("retry_after_ms"_ls).toInt(-1);
        if (retryAfterMs >= 0)
            msg += tr(", next retry advised after %1 ms").arg(retryAfterMs);
        else // We still have to figure some reasonable interval
            retryAfterMs = getNextRetryMs();

        d->connection->limitRate(milliseconds(retryAfterMs));

        return { TooManyRequests, msg };
    }

    if (errCode == "M_CONSENT_NOT_GIVEN") {
        d->errorUrl = QUrl(errorJson.value("consent_uri"_ls).toString());
        return { UserConsentRequired };
    }
    if (errCode == "M_UNSUPPORTED_ROOM_VERSION"
        || errCode == "M_INCOMPATIBLE_ROOM_VERSION")
        return { UnsupportedRoomVersion,
                 errorJson.contains("room_version"_ls)
                     ? tr("Requested room version: %1")
                           .arg(errorJson.value("room_version"_ls).toString())
                     : errorJson.value("error"_ls).toString() };
    if (errCode == "M_CANNOT_LEAVE_SERVER_NOTICE_ROOM")
        return { CannotLeaveRoom,
                 tr("It's not allowed to leave a server notices room") };
    if (errCode == "M_USER_DEACTIVATED")
        return { UserDeactivated };

    // Not localisable on the client side
    if (errorJson.contains("error"_ls)) // Keep the code, update the message
        return { currentStatus.code, errorJson.value("error"_ls).toString() };

    return currentStatus; // The error payload is not recognised
}

QJsonValue BaseJob::takeValueFromJson(const QString& key)
{
    if (!d->jsonResponse.isObject())
        return QJsonValue::Undefined;
    auto o = d->jsonResponse.object();
    auto v = o.take(key);
    d->jsonResponse.setObject(o);
    return v;
}

void BaseJob::stop()
{
    // This method is (also) used to semi-finalise the job before retrying; so
    // stop the timeout timer but keep the retry timer running.
    d->timer.stop();
    if (d->reply) {
        d->reply->disconnect(this); // Ignore whatever comes from the reply
        if (d->reply->isRunning()) {
            qCWarning(d->logCat)
                << this << "stopped without ready network reply";
            d->reply->abort(); // Keep the reply object in case clients need it
        }
    } else
        qCWarning(d->logCat) << this << "stopped with empty network reply";
}

void BaseJob::finishJob()
{
    stop();
    switch(error()) {
    case TooManyRequests:
        emit rateLimited();
        d->connection->submit(this);
        return;
    case Unauthorised:
        if (!d->needsToken && !d->connection->accessToken().isEmpty()) {
            // Rerun with access token (extension of the spec while
            // https://github.com/matrix-org/matrix-doc/issues/701 is pending)