carddav.cpp 55.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/*
 * This file is part of buteo-sync-plugin-carddav package
 *
 * Copyright (C) 2014 Jolla Ltd. and/or its subsidiary(-ies).
 *
 * Contributors: Chris Adams <chris.adams@jolla.com>
 *
 * This program/library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * version 2.1 as published by the Free Software Foundation.
 *
 * This program/library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program/library; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 */

#include "carddav_p.h"
#include "syncer_p.h"

26 27
#include <LogMacros.h>

28 29 30 31 32 33 34 35
#include <QRegularExpression>
#include <QUuid>
#include <QByteArray>
#include <QBuffer>
#include <QTimer>

#include <QContact>
#include <QContactGuid>
36
#include <QContactAvatar>
37 38 39
#include <QContactDisplayLabel>
#include <QContactName>
#include <QContactNickname>
40 41 42
#include <QContactBirthday>
#include <QContactTimestamp>
#include <QContactGender>
43 44 45 46 47 48 49 50

#include <QVersitWriter>
#include <QVersitDocument>
#include <QVersitProperty>
#include <QVersitContactExporter>
#include <QVersitReader>
#include <QVersitContactImporter>

51
#ifdef USE_LIBCONTACTS
52
#include <seasidepropertyhandler.h>
chriadam's avatar
chriadam committed
53
#include <seasidecache.h>
54
#endif
55

56 57
#include <qtcontacts-extensions.h>

58 59 60
namespace {
    void debugDumpData(const QString &data)
    {
61 62 63 64
        if (Buteo::Logger::instance()->getLogLevel() < 7) {
            return;
        }

65 66 67 68
        QString dbgout;
        Q_FOREACH (const QChar &c, data) {
            if (c == '\r' || c == '\n') {
                if (!dbgout.isEmpty()) {
69
                    LOG_DEBUG(dbgout);
70 71 72 73 74 75 76
                    dbgout.clear();
                }
            } else {
                dbgout += c;
            }
        }
        if (!dbgout.isEmpty()) {
77
            LOG_DEBUG(dbgout);
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
        }
    }
}

CardDavVCardConverter::CardDavVCardConverter()
{
}

CardDavVCardConverter::~CardDavVCardConverter()
{
}

QStringList CardDavVCardConverter::supportedPropertyNames()
{
    // We only support a small number of (core) vCard properties
    // in this sync adapter.  The rest of the properties will
    // be cached so that we can stitch them back into the vCard
    // we upload on modification.
    QStringList supportedProperties;
    supportedProperties << "VERSION" << "PRODID" << "REV"
                        << "N" << "FN" << "NICKNAME" << "BDAY" << "X-GENDER"
99
                        << "EMAIL" << "TEL" << "ADR" << "URL" << "PHOTO"
100
                        << "ORG" << "TITLE" << "ROLE"
101
                        << "NOTE" << "UID";
102 103 104 105 106 107 108 109 110 111 112
    return supportedProperties;
}

QPair<QContact, QStringList> CardDavVCardConverter::convertVCardToContact(const QString &vcard, bool *ok)
{
    m_unsupportedProperties.clear();
    QVersitReader reader(vcard.toUtf8());
    reader.startReading();
    reader.waitForFinished();
    QList<QVersitDocument> vdocs = reader.results();
    if (vdocs.size() != 1) {
113
        LOG_WARNING(Q_FUNC_INFO
114
                   << "invalid results during vcard import, got"
115
                   << vdocs.size() << "output from input:\n" << vcard);
116 117 118 119 120 121 122 123 124 125
        *ok = false;
        return QPair<QContact, QStringList>();
    }

    // convert the vCard into a QContact
    QVersitContactImporter importer;
    importer.setPropertyHandler(this);
    importer.importDocuments(vdocs);
    QList<QContact> importedContacts = importer.contacts();
    if (importedContacts.size() != 1) {
126
        LOG_WARNING(Q_FUNC_INFO
127
                   << "invalid results during vcard conversion, got"
128
                   << importedContacts.size() << "output from input:\n" << vcard);
129 130 131 132 133 134 135 136
        *ok = false;
        return QPair<QContact, QStringList>();
    }

    QContact importedContact = importedContacts.first();
    QStringList unsupportedProperties = m_unsupportedProperties.value(importedContact.detail<QContactGuid>().guid());
    m_unsupportedProperties.clear();

137 138
    // If the contact has no structured name data, create a best-guess name for it.
    // This may be the case if the server provides an FN property but no N property.
139
    // Also, some detail types should be unique, so remove duplicates if present.
140 141
    QString displaylabelField, nicknameField;
    QContactName nameDetail;
142 143 144
    QSet<QContactDetail::DetailType> seenUniqueDetailTypes;
    QList<QContactDetail> importedContactDetails = importedContact.details();
    Q_FOREACH (const QContactDetail &d, importedContactDetails) {
145 146 147 148 149 150
        if (d.type() == QContactDetail::TypeName) {
            nameDetail = d;
        } else if (d.type() == QContactDetail::TypeDisplayLabel) {
            displaylabelField = d.value(QContactDisplayLabel::FieldLabel).toString().trimmed();
        } else if (d.type() == QContactDetail::TypeNickname) {
            nicknameField = d.value(QContactNickname::FieldNickname).toString().trimmed();
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
        } else if (d.type() == QContactDetail::TypeBirthday) {
            if (seenUniqueDetailTypes.contains(QContactDetail::TypeBirthday)) {
                // duplicated BDAY field seen from vCard.
                // remove this duplicate, else save will fail.
                QContactBirthday dupBday(d);
                importedContact.removeDetail(&dupBday);
                LOG_DEBUG("Removed duplicate BDAY detail:" << dupBday);
            } else {
                seenUniqueDetailTypes.insert(QContactDetail::TypeBirthday);
            }
        } else if (d.type() == QContactDetail::TypeTimestamp) {
            if (seenUniqueDetailTypes.contains(QContactDetail::TypeTimestamp)) {
                // duplicated REV field seen from vCard.
                // remove this duplicate, else save will fail.
                QContactTimestamp dupRev(d);
                importedContact.removeDetail(&dupRev);
                LOG_DEBUG("Removed duplicate REV detail:" << dupRev);
            } else {
                seenUniqueDetailTypes.insert(QContactDetail::TypeTimestamp);
            }
        } else if (d.type() == QContactDetail::TypeGuid) {
            if (seenUniqueDetailTypes.contains(QContactDetail::TypeGuid)) {
                // duplicated UID field seen from vCard.
                // remove this duplicate, else save will fail.
                QContactGuid dupUid(d);
                importedContact.removeDetail(&dupUid);
                LOG_DEBUG("Removed duplicate UID detail:" << dupUid);
            } else {
                seenUniqueDetailTypes.insert(QContactDetail::TypeGuid);
            }
        } else if (d.type() == QContactDetail::TypeGender) {
            if (seenUniqueDetailTypes.contains(QContactDetail::TypeGender)) {
                // duplicated X-GENDER field seen from vCard.
                // remove this duplicate, else save will fail.
                QContactGender dupGender(d);
                importedContact.removeDetail(&dupGender);
                LOG_DEBUG("Removed duplicate X-GENDER detail:" << dupGender);
            } else {
                seenUniqueDetailTypes.insert(QContactDetail::TypeGender);
            }
191 192 193 194
        }
    }
    if (nameDetail.isEmpty() || (nameDetail.firstName().isEmpty() && nameDetail.lastName().isEmpty())) {
        // we have no valid name data but we may have display label or nickname data which we can decompose.
195
#ifdef USE_LIBCONTACTS
196 197 198 199 200 201 202 203 204 205 206
        if (!displaylabelField.isEmpty()) {
            SeasideCache::decomposeDisplayLabel(displaylabelField, &nameDetail);
            importedContact.saveDetail(&nameDetail);
            LOG_DEBUG("Decomposed vCard display name into structured name:" << nameDetail);
        } else if (!nicknameField.isEmpty()) {
            SeasideCache::decomposeDisplayLabel(nicknameField, &nameDetail);
            importedContact.saveDetail(&nameDetail);
            LOG_DEBUG("Decomposed vCard nickname into structured name:" << nameDetail);
        } else {
            LOG_WARNING("No structured name data exists in the vCard, contact will be unnamed!");
        }
207 208 209
#else
        LOG_WARNING("No structured name data exists in the vCard, contact will be unnamed!");
#endif
210 211
    }

212 213 214 215 216 217
    // mark each detail of the contact as modifiable
    Q_FOREACH (QContactDetail det, importedContact.details()) {
        det.setValue(QContactDetail__FieldModifiable, true);
        importedContact.saveDetail(&det);
    }

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
    *ok = true;
    return qMakePair(importedContact, unsupportedProperties);
}

QString CardDavVCardConverter::convertContactToVCard(const QContact &c, const QStringList &unsupportedProperties)
{
    QList<QContact> exportList; exportList << c;
    QVersitContactExporter e;
    e.setDetailHandler(this);
    e.exportContacts(exportList);
    QByteArray output;
    QBuffer vCardBuffer(&output);
    vCardBuffer.open(QBuffer::WriteOnly);
    QVersitWriter writer(&vCardBuffer);
    writer.startWriting(e.documents());
    writer.waitForFinished();
    QString retn = QString::fromUtf8(output);

    // now add back the unsupported properties.
    Q_FOREACH (const QString &propStr, unsupportedProperties) {
        int endIdx = retn.lastIndexOf(QStringLiteral("END:VCARD"));
        if (endIdx > 0) {
            QString ecrlf = propStr + '\r' + '\n';
            retn.insert(endIdx, ecrlf);
        }
    }

245
    LOG_DEBUG("generated vcard:");
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
    debugDumpData(retn);

    return retn;
}

QString CardDavVCardConverter::convertPropertyToString(const QVersitProperty &p) const
{
    QVersitDocument d(QVersitDocument::VCard30Type);
    d.addProperty(p);
    QByteArray out;
    QBuffer bout(&out);
    bout.open(QBuffer::WriteOnly);
    QVersitWriter w(&bout);
    w.startWriting(d);
    w.waitForFinished();
    QString retn = QString::fromLatin1(out);

    // strip out the BEGIN:VCARD\r\nVERSION:3.0\r\n and END:VCARD\r\n\r\n bits.
    int headerIdx = retn.indexOf(QStringLiteral("VERSION:3.0")) + 11;
    int footerIdx = retn.indexOf(QStringLiteral("END:VCARD"));
    if (headerIdx > 11 && footerIdx > 0 && footerIdx > headerIdx) {
        retn = retn.mid(headerIdx, footerIdx - headerIdx).trimmed();
        return retn;
    }

271
    LOG_WARNING(Q_FUNC_INFO << "no string conversion possible for versit property:" << p.name());
272 273 274 275 276 277 278 279 280
    return QString();
}

void CardDavVCardConverter::propertyProcessed(const QVersitDocument &, const QVersitProperty &property,
                                               const QContact &, bool *alreadyProcessed,
                                               QList<QContactDetail> *updatedDetails)
{
    static QStringList supportedProperties(supportedPropertyNames());
    const QString propertyName(property.name().toUpper());
281
    if (propertyName == QLatin1String("PHOTO")) {
282
#ifdef USE_LIBCONTACTS
283 284
        // use the standard PHOTO handler from Seaside libcontacts
        QContactAvatar newAvatar = SeasidePropertyHandler::avatarFromPhotoProperty(property);
285 286 287 288 289 290 291
#else
        QContactAvatar newAvatar;
        QUrl url(property.variantValue().toString());
        if (url.isValid() && !url.isLocalFile()) {
            newAvatar.setImageUrl(url);
        }
#endif
292 293 294 295 296 297 298
        if (!newAvatar.isEmpty()) {
            updatedDetails->append(newAvatar);
        }
        // don't let the default PHOTO handler import it, even if we failed above.
        *alreadyProcessed = true;
        return;
    } else if (supportedProperties.contains(propertyName)) {
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
        // do nothing, let the default handler import them.
        *alreadyProcessed = true;
        return;
    }

    // cache the unsupported property string, and remove any detail
    // which was added by the default handler for this property.
    *alreadyProcessed = true;
    QString unsupportedProperty = convertPropertyToString(property);
    m_tempUnsupportedProperties.append(unsupportedProperty);
    updatedDetails->clear();
}

void CardDavVCardConverter::documentProcessed(const QVersitDocument &, QContact *c)
{
    // the UID of the contact will be contained in the QContactGuid detail.
    QString uid = c->detail<QContactGuid>().guid();
    if (uid.isEmpty()) {
317
        LOG_WARNING(Q_FUNC_INFO << "imported contact has no UID, discarding unsupported properties!");
318 319 320 321 322 323 324 325
    } else {
        m_unsupportedProperties.insert(uid, m_tempUnsupportedProperties);
    }

    // get ready for the next import.
    m_tempUnsupportedProperties.clear();
}

chriadam's avatar
chriadam committed
326
void CardDavVCardConverter::contactProcessed(const QContact &c, QVersitDocument *d)
327
{
328
    // FN is a required field in vCard 3.0 and 4.0.  Add it if it does not exist.
chriadam's avatar
chriadam committed
329 330 331 332 333 334 335
    bool foundFN = false;
    Q_FOREACH (const QVersitProperty &p, d->properties()) {
        if (p.name() == QStringLiteral("FN")) {
            foundFN = true;
            break;
        }
    }
336 337 338 339 340 341 342 343 344 345 346

    // N is also a required field in vCard 3.0.  Add it if it does not exist.
    bool foundN = false;
    Q_FOREACH (const QVersitProperty &p, d->properties()) {
        if (p.name() == QStringLiteral("N")) {
            foundN = true;
            break;
        }
    }

    if (!foundFN || !foundN) {
347
#ifdef USE_LIBCONTACTS
348
        QString displaylabel = SeasideCache::generateDisplayLabel(c);
349 350 351 352 353 354 355 356
#else
        QContactName name = c.detail<QContactName>();
        QString displaylabel = QStringList {
            name.firstName(),
            name.middleName(),
            name.lastName(),
        }.join(' ');
#endif
357 358 359 360 361 362 363 364
        if (!foundFN) {
            QVersitProperty fnProp;
            fnProp.setName("FN");
            fnProp.setValue(displaylabel);
            d->addProperty(fnProp);
        }
        if (!foundN) {
            QContactName name = c.detail<QContactName>();
365
#ifdef USE_LIBCONTACTS
366
            SeasideCache::decomposeDisplayLabel(displaylabel, &name);
367
#endif
368 369 370 371 372
            if (name.firstName().isEmpty()) {
                // If we could not decompose the display label (e.g., only one token)
                // then just assume that the display label is a useful first name.
                name.setFirstName(displaylabel);
            }
373
            static const QStringList nvalue = { "", "", "", "", "" };
374 375
            QVersitProperty nProp;
            nProp.setName("N");
376
            nProp.setValueType(QVersitProperty::CompoundType);
377 378 379
            nProp.setValue(nvalue);
            d->addProperty(nProp);
        }
chriadam's avatar
chriadam committed
380
    }
381 382 383 384 385 386 387 388
}

void CardDavVCardConverter::detailProcessed(const QContact &, const QContactDetail &,
                                            const QVersitDocument &, QSet<int> *,
                                            QList<QVersitProperty> *, QList<QVersitProperty> *toBeAdded)
{
    static QStringList supportedProperties(supportedPropertyNames());
    for (int i = toBeAdded->size() - 1; i >= 0; --i) {
chriadam's avatar
chriadam committed
389 390
        const QString propName = toBeAdded->at(i).name().toUpper();
        if (!supportedProperties.contains(propName)) {
391 392 393
            // we don't support importing these properties, so we shouldn't
            // attempt to export them.
            toBeAdded->removeAt(i);
chriadam's avatar
chriadam committed
394 395 396 397
        } else if (propName == QStringLiteral("X-GENDER")
                && toBeAdded->at(i).value().toUpper() == QStringLiteral("UNSPECIFIED")) {
            // this is probably added "by default" since qtcontacts-sqlite always stores a gender.
            toBeAdded->removeAt(i);
398 399 400 401 402 403
        }
    }
}

CardDav::CardDav(Syncer *parent,
                 const QString &serverUrl,
404
                 const QString &addressbookPath,
405 406 407 408 409 410 411 412
                 const QString &username,
                 const QString &password)
    : QObject(parent)
    , q(parent)
    , m_converter(new CardDavVCardConverter)
    , m_request(new RequestGenerator(q, username, password))
    , m_parser(new ReplyParser(q, m_converter))
    , m_serverUrl(serverUrl)
413
    , m_addressbookPath(addressbookPath)
414
    , m_discoveryStage(CardDav::DiscoveryStarted)
415
    , m_addressbooksListOnly(false)
416
    , m_triedAddressbookPathAsHomeSetUrl(false)
417 418 419 420 421 422 423
    , m_downsyncRequests(0)
    , m_upsyncRequests(0)
{
}

CardDav::CardDav(Syncer *parent,
                 const QString &serverUrl,
424
                 const QString &addressbookPath,
425 426 427 428 429 430 431
                 const QString &accessToken)
    : QObject(parent)
    , q(parent)
    , m_converter(new CardDavVCardConverter)
    , m_request(new RequestGenerator(q, accessToken))
    , m_parser(new ReplyParser(q, m_converter))
    , m_serverUrl(serverUrl)
432
    , m_addressbookPath(addressbookPath)
433
    , m_discoveryStage(CardDav::DiscoveryStarted)
434
    , m_addressbooksListOnly(false)
435 436 437 438 439 440 441 442 443 444 445 446
    , m_downsyncRequests(0)
    , m_upsyncRequests(0)
{
}

CardDav::~CardDav()
{
    delete m_converter;
    delete m_parser;
    delete m_request;
}

447
void CardDav::errorOccurred(int httpError)
448
{
449
    emit error(httpError);
450 451
}

452 453 454 455 456 457
void CardDav::determineAddressbooksList()
{
    m_addressbooksListOnly = true;
    determineRemoteAMR();
}

458 459
void CardDav::determineRemoteAMR()
{
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
    if (m_addressbookPath.isEmpty()) {
        // The CardDAV sequence for determining the A/M/R delta is:
        // a)  fetch user information from the principal URL
        // b)  fetch addressbooks home url
        // c)  fetch addressbook information
        // d)  for each addressbook, either:
        //     i)  perform immediate delta sync (if webdav-sync enabled) OR
        //     ii) fetch etags, manually calculate delta
        // e) fetch full contacts for delta.

        // We start by fetching user information.
        fetchUserInformation();
    } else {
        // we can skip to step (c) of the discovery.
        fetchAddressbooksInformation(m_addressbookPath);
    }
476 477
}

478
void CardDav::fetchUserInformation()
479
{
480
    LOG_DEBUG(Q_FUNC_INFO << "requesting principal urls for user");
481 482 483 484

    // we need to specify the .well-known/carddav endpoint if it's the first
    // request (so we have not yet been redirected to the correct endpoint)
    // and if the path is empty/unknown.
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508

    /*
        RFC 6764 section 6.5:

        * The client does a "PROPFIND" [RFC4918] request with the
          request URI set to the initial "context path".  The body of
          the request SHOULD include the DAV:current-user-principal
          [RFC5397] property as one of the properties to return.  Note
          that clients MUST properly handle HTTP redirect responses for
          the request.  The server will use the HTTP authentication
          procedure outlined in [RFC2617] or use some other appropriate
          authentication schemes to authenticate the user.

        * When an initial "context path" has not been determined from a
          TXT record, the initial "context path" is taken to be
          "/.well-known/caldav" (for CalDAV) or "/.well-known/carddav"
          (for CardDAV).

        * If the server returns a 404 ("Not Found") HTTP status response
          to the request on the initial "context path", clients MAY try
          repeating the request on the "root" URI "/" or prompt the user
          for a suitable path.
    */

509
    QUrl serverUrl(m_serverUrl);
510 511 512 513 514
    if (serverUrl.scheme().isEmpty() && (serverUrl.host().isEmpty() || serverUrl.path().isEmpty())) {
        // assume the supplied server url is like: "carddav.server.tld"
        m_serverUrl = QStringLiteral("https://%1/").arg(m_serverUrl);
        serverUrl = QUrl(m_serverUrl);
    }
515 516 517
    const QString wellKnownUrl = serverUrl.port() == -1
                               ? QStringLiteral("%1://%2/.well-known/carddav").arg(serverUrl.scheme()).arg(serverUrl.host())
                               : QStringLiteral("%1://%2:%3/.well-known/carddav").arg(serverUrl.scheme()).arg(serverUrl.host()).arg(serverUrl.port());
518 519 520 521 522
    bool firstRequest = m_discoveryStage == CardDav::DiscoveryStarted;
    m_serverUrl = firstRequest && (serverUrl.path().isEmpty() || serverUrl.path() == QStringLiteral("/"))
                ? wellKnownUrl
                : m_serverUrl;
    QNetworkReply *reply = m_request->currentUserInformation(m_serverUrl);
523 524 525 526 527
    if (!reply) {
        emit error();
        return;
    }

528
    connect(reply, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(sslErrorsOccurred(QList<QSslError>)));
529 530 531
    connect(reply, SIGNAL(finished()), this, SLOT(userInformationResponse()));
}

532 533 534 535 536 537 538 539 540 541 542 543
void CardDav::sslErrorsOccurred(const QList<QSslError> &errors)
{
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
    if (q->m_ignoreSslErrors) {
        LOG_DEBUG(Q_FUNC_INFO << "ignoring SSL errors due to account policy:" << errors);
        reply->ignoreSslErrors(errors);
    } else {
        LOG_WARNING(Q_FUNC_INFO << "SSL errors occurred, aborting:" << errors);
        errorOccurred(401);
    }
}

544 545 546 547 548
void CardDav::userInformationResponse()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
    QByteArray data = reply->readAll();
    if (reply->error() != QNetworkReply::NoError) {
549
        int httpError = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
550
        LOG_WARNING(Q_FUNC_INFO << "error:" << reply->error() << "(" << httpError << ") to request" << m_serverUrl);
551
        debugDumpData(QString::fromUtf8(data));
552 553 554 555 556 557 558 559
        QUrl oldServerUrl(m_serverUrl);
        if (m_discoveryStage == CardDav::DiscoveryStarted && (httpError == 404 || httpError == 405)) {
            if (!oldServerUrl.path().endsWith(QStringLiteral(".well-known/carddav"))) {
                // From RFC 6764: If the initial "context path" derived from a TXT record
                // generates HTTP errors when targeted by requests, the client
                // SHOULD repeat its "bootstrapping" procedure using the
                // appropriate ".well-known" URI instead.
                LOG_DEBUG(Q_FUNC_INFO << "got HTTP response" << httpError << "to initial discovery request; trying well-known URI");
560 561 562
                m_serverUrl = oldServerUrl.port() == -1
                            ? QStringLiteral("%1://%2/.well-known/carddav").arg(oldServerUrl.scheme()).arg(oldServerUrl.host())
                            : QStringLiteral("%1://%2:%3/.well-known/carddav").arg(oldServerUrl.scheme()).arg(oldServerUrl.host()).arg(oldServerUrl.port());
563 564 565 566 567 568 569 570
                fetchUserInformation(); // set initial context path to well-known URI.
            } else {
                // From RFC 6764: if the server returns a 404 HTTP status response to the
                // request on the initial context path, clients may try repeating the request
                // on the root URI.
                // We also do this on HTTP 405 in case some implementation is non-spec-conformant.
                LOG_DEBUG(Q_FUNC_INFO << "got HTTP response" << httpError << "to well-known request; trying root URI");
                m_discoveryStage = CardDav::DiscoveryTryRoot;
571 572 573
                m_serverUrl = oldServerUrl.port() == -1
                            ? QStringLiteral("%1://%2/").arg(oldServerUrl.scheme()).arg(oldServerUrl.host())
                            : QStringLiteral("%1://%2:%3/").arg(oldServerUrl.scheme()).arg(oldServerUrl.host()).arg(oldServerUrl.port());
574 575 576 577
                fetchUserInformation();
            }
            return;
        }
578
        errorOccurred(httpError);
579 580 581
        return;
    }

582 583 584 585 586 587 588 589
    // if the request was to the /.well-known/carddav path, then we need to redirect
    QUrl redir = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
    if (!redir.isEmpty()) {
        QUrl orig = reply->url();
        if (orig.path() != redir.path()) {
            if (orig.path().endsWith(QStringLiteral(".well-known/carddav"))) {
                // redirect as required, and change our server URL to point to the redirect URL.
                LOG_DEBUG(Q_FUNC_INFO << "redirecting from:" << orig.toString() << "to:" << redir.toString());
590 591 592 593 594 595 596 597 598
                QString redirPort;
                if (redir.port() != -1) {
                    // the redirect was a url, and includes a port.  use it.
                    redirPort = QStringLiteral(":%1").arg(redir.port());
                } else if (redir.host().isEmpty() && orig.port() != -1) {
                    // the redirect was a path, not a url.  use the original port.
                    redirPort = QStringLiteral(":%1").arg(orig.port());
                }
                m_serverUrl = QStringLiteral("%1://%2%3%4")
599 600
                        .arg(redir.scheme().isEmpty() ? orig.scheme() : redir.scheme())
                        .arg(redir.host().isEmpty() ? orig.host() : redir.host())
601
                        .arg(redirPort)
602
                        .arg(redir.path());
603 604
                m_discoveryStage = CardDav::DiscoveryRedirected;
                fetchUserInformation();
605 606 607 608 609 610 611 612 613 614 615 616 617
            } else {
                // possibly unsafe redirect.  for security, assume it's malicious and abort sync.
                LOG_WARNING(Q_FUNC_INFO << "unexpected redirect from:" << orig.toString() << "to:" << redir.toString());
                errorOccurred(301);
            }
        } else {
            // circular redirect, avoid the endless loop by aborting sync.
            LOG_WARNING(Q_FUNC_INFO << "redirect specified is circular:" << redir.toString());
            errorOccurred(301);
        }
        return;
    }

618 619 620 621 622 623 624 625 626 627 628 629 630
    ReplyParser::ResponseType responseType = ReplyParser::UserPrincipalResponse;
    QString userPath = m_parser->parseUserPrincipal(data, &responseType);
    if (responseType == ReplyParser::UserPrincipalResponse) {
        // the server responded with the expected user principal information.
        if (userPath.isEmpty()) {
            LOG_WARNING(Q_FUNC_INFO << "unable to parse user principal from response");
            emit error();
            return;
        }
        fetchAddressbookUrls(userPath);
    } else if (responseType == ReplyParser::AddressbookInformationResponse) {
        // the server responded with addressbook information instead
        // of user principal information.  Skip the next discovery step.
631
        QList<ReplyParser::AddressBookInformation> infos = m_parser->parseAddressbookInformation(data, QString());
632 633 634 635 636 637 638 639
        if (infos.isEmpty()) {
            LOG_WARNING(Q_FUNC_INFO << "unable to parse addressbook info from user principal response");
            emit error();
            return;
        }
        downsyncAddressbookContent(infos);
    } else {
        LOG_WARNING(Q_FUNC_INFO << "unknown response from user principal request");
640 641 642 643 644 645
        emit error();
    }
}

void CardDav::fetchAddressbookUrls(const QString &userPath)
{
646
    LOG_DEBUG(Q_FUNC_INFO << "requesting addressbook urls for user");
647 648 649 650 651 652
    QNetworkReply *reply = m_request->addressbookUrls(m_serverUrl, userPath);
    if (!reply) {
        emit error();
        return;
    }

653
    connect(reply, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(sslErrorsOccurred(QList<QSslError>)));
654 655 656 657 658 659 660 661
    connect(reply, SIGNAL(finished()), this, SLOT(addressbookUrlsResponse()));
}

void CardDav::addressbookUrlsResponse()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
    QByteArray data = reply->readAll();
    if (reply->error() != QNetworkReply::NoError) {
662
        int httpError = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
663
        LOG_WARNING(Q_FUNC_INFO << "error:" << reply->error()
664
                   << "(" << httpError << ")");
665
        debugDumpData(QString::fromUtf8(data));
666
        errorOccurred(httpError);
667 668 669 670 671
        return;
    }

    QString addressbooksHomePath = m_parser->parseAddressbookHome(data);
    if (addressbooksHomePath.isEmpty()) {
672
        LOG_WARNING(Q_FUNC_INFO << "unable to parse addressbook home from response");
673 674 675 676 677 678 679 680 681
        emit error();
        return;
    }

    fetchAddressbooksInformation(addressbooksHomePath);
}

void CardDav::fetchAddressbooksInformation(const QString &addressbooksHomePath)
{
682
    LOG_DEBUG(Q_FUNC_INFO << "requesting addressbook sync information from" << addressbooksHomePath);
683
    QNetworkReply *reply = m_request->addressbooksInformation(m_serverUrl, addressbooksHomePath);
684
    reply->setProperty("addressbooksHomePath", addressbooksHomePath);
685 686 687 688 689
    if (!reply) {
        emit error();
        return;
    }

690
    connect(reply, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(sslErrorsOccurred(QList<QSslError>)));
691 692 693 694 695 696
    connect(reply, SIGNAL(finished()), this, SLOT(addressbooksInformationResponse()));
}

void CardDav::addressbooksInformationResponse()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
697
    QString addressbooksHomePath = reply->property("addressbooksHomePath").toString();
698 699
    QByteArray data = reply->readAll();
    if (reply->error() != QNetworkReply::NoError) {
700
        int httpError = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
701
        LOG_WARNING(Q_FUNC_INFO << "error:" << reply->error()
702
                   << "(" << httpError << ")");
703
        debugDumpData(QString::fromUtf8(data));
704
        errorOccurred(httpError);
705 706 707
        return;
    }

708 709 710 711 712 713
    // if we didn't parse the addressbooks home path via discovery, but instead were provided it by the user,
    // then don't pass the path to the parser, as it uses it for cycle detection.
    if (m_addressbookPath == addressbooksHomePath) {
        addressbooksHomePath = QString();
    }

714
    QList<ReplyParser::AddressBookInformation> infos = m_parser->parseAddressbookInformation(data, addressbooksHomePath);
715
    if (infos.isEmpty()) {
716 717 718 719 720 721 722 723 724 725 726
        if (!m_addressbookPath.isEmpty() && !m_triedAddressbookPathAsHomeSetUrl) {
            // the user provided an addressbook path during account creation, which didn't work.
            // it may not be an addressbook path but instead the home set url; try that.
            LOG_DEBUG(Q_FUNC_INFO << "Given path is not addressbook path; trying as home set url");
            m_triedAddressbookPathAsHomeSetUrl = true;
            fetchAddressbookUrls(m_addressbookPath);
        } else {
            LOG_WARNING(Q_FUNC_INFO << "unable to parse addressbook info from response");
            emit error();
            return;
        }
727 728
    }

729 730 731 732 733 734 735 736 737 738 739
    if (m_addressbooksListOnly) {
        QStringList paths;
        for (QList<ReplyParser::AddressBookInformation>::const_iterator it = infos.constBegin(); it != infos.constEnd(); ++it) {
            if (!paths.contains(it->url)) {
                paths.append(it->url);
            }
        }
        emit addressbooksList(paths);
    } else {
        downsyncAddressbookContent(infos);
    }
740 741 742 743
}

void CardDav::downsyncAddressbookContent(const QList<ReplyParser::AddressBookInformation> &infos)
{
744 745 746 747 748 749 750 751
    // for addressbooks which support sync-token syncing, use that style.
    for (int i = 0; i < infos.size(); ++i) {
        // set a default addressbook if we haven't seen one yet.
        // we will store newly added local contacts to that addressbook.
        if (q->m_defaultAddressbook.isEmpty()) {
            q->m_defaultAddressbook = infos[i].url;
        }

752 753 754 755 756 757 758
        if (infos[i].syncToken.isEmpty() && infos[i].ctag.isEmpty()) {
            // we cannot use either sync-token or ctag for this addressbook.
            // we need to manually calculate the complete delta.
            LOG_DEBUG("No sync-token or ctag given for addressbook:" << infos[i].url << ", manual delta detection required");
            q->m_addressbookCtags[infos[i].url] = infos[i].ctag; // ctag is empty :. we will use manual detection.
            fetchContactMetadata(infos[i].url);
        } else if (infos[i].syncToken.isEmpty()) {
759
            // we cannot use sync-token for this addressbook, but instead ctag.
760
            const QString existingCtag(q->m_addressbookCtags[infos[i].url]); // from OOB
761 762 763 764 765 766 767 768 769 770 771 772
            if (existingCtag.isEmpty()) {
                // first time sync
                q->m_addressbookCtags[infos[i].url] = infos[i].ctag; // insert
                // now do etag request, the delta will be all remote additions
                fetchContactMetadata(infos[i].url);
            } else if (existingCtag != infos[i].ctag) {
                // changes have occurred since last sync
                q->m_addressbookCtags[infos[i].url] = infos[i].ctag; // update
                // perform etag request and then manually calculate deltas.
                fetchContactMetadata(infos[i].url);
            } else {
                // no changes have occurred in this addressbook since last sync
773 774
                LOG_DEBUG(Q_FUNC_INFO << "no changes since last sync for"
                         << infos[i].url << "from account" << q->m_accountId);
775 776 777 778 779
                m_downsyncRequests += 1;
                QTimer::singleShot(0, this, SLOT(downsyncComplete()));
            }
        } else {
            // the server supports webdav-sync for this addressbook.
780
            const QString existingSyncToken(q->m_addressbookSyncTokens[infos[i].url]); // from OOB
781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
            // store the ctag anyway just in case the server has
            // forgotten the syncToken we cached from last time.
            if (!infos[i].ctag.isEmpty()) {
                q->m_addressbookCtags[infos[i].url] = infos[i].ctag;
            }
            // attempt to perform synctoken sync
            if (existingSyncToken.isEmpty()) {
                // first time sync
                q->m_addressbookSyncTokens[infos[i].url] = infos[i].syncToken; // insert
                // perform slow sync / full report
                fetchContactMetadata(infos[i].url);
            } else if (existingSyncToken != infos[i].syncToken) {
                // changes have occurred since last sync.
                q->m_addressbookSyncTokens[infos[i].url] = infos[i].syncToken; // update
                // perform immediate delta sync, by passing the old sync token to the server.
                fetchImmediateDelta(infos[i].url, existingSyncToken);
            } else {
                // no changes have occurred in this addressbook since last sync
799 800
                LOG_DEBUG(Q_FUNC_INFO << "no changes since last sync for"
                         << infos[i].url << "from account" << q->m_accountId);
801 802 803 804 805 806 807 808 809
                m_downsyncRequests += 1;
                QTimer::singleShot(0, this, SLOT(downsyncComplete()));
            }
        }
    }
}

void CardDav::fetchImmediateDelta(const QString &addressbookUrl, const QString &syncToken)
{
810
    LOG_DEBUG(Q_FUNC_INFO
811
             << "requesting immediate delta for addressbook" << addressbookUrl
812
             << "with sync token" << syncToken);
813 814 815 816 817 818 819 820 821

    QNetworkReply *reply = m_request->syncTokenDelta(m_serverUrl, addressbookUrl, syncToken);
    if (!reply) {
        emit error();
        return;
    }

    m_downsyncRequests += 1; // when this reaches zero, we've finished all addressbook deltas
    reply->setProperty("addressbookUrl", addressbookUrl);
822
    connect(reply, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(sslErrorsOccurred(QList<QSslError>)));
823 824 825 826 827 828 829 830 831
    connect(reply, SIGNAL(finished()), this, SLOT(immediateDeltaResponse()));
}

void CardDav::immediateDeltaResponse()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
    QString addressbookUrl = reply->property("addressbookUrl").toString();
    QByteArray data = reply->readAll();
    if (reply->error() != QNetworkReply::NoError) {
832 833
        LOG_WARNING(Q_FUNC_INFO << "error:" << reply->error()
                   << "(" << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() << ")");
834 835 836 837 838 839 840 841 842 843 844 845 846 847 848
        debugDumpData(QString::fromUtf8(data));
        // The server is allowed to forget the syncToken by the
        // carddav protocol.  Try a full report sync just in case.
        fetchContactMetadata(addressbookUrl);
        return;
    }

    QString newSyncToken;
    QList<ReplyParser::ContactInformation> infos = m_parser->parseSyncTokenDelta(data, &newSyncToken);
    q->m_addressbookSyncTokens[addressbookUrl] = newSyncToken;
    fetchContacts(addressbookUrl, infos);
}

void CardDav::fetchContactMetadata(const QString &addressbookUrl)
{
849
    LOG_DEBUG(Q_FUNC_INFO << "requesting contact metadata for addressbook" << addressbookUrl);
850 851 852 853 854 855 856 857
    QNetworkReply *reply = m_request->contactEtags(m_serverUrl, addressbookUrl);
    if (!reply) {
        emit error();
        return;
    }

    m_downsyncRequests += 1; // when this reaches zero, we've finished all addressbook deltas
    reply->setProperty("addressbookUrl", addressbookUrl);
858
    connect(reply, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(sslErrorsOccurred(QList<QSslError>)));
859 860 861 862 863 864 865 866 867
    connect(reply, SIGNAL(finished()), this, SLOT(contactMetadataResponse()));
}

void CardDav::contactMetadataResponse()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
    QString addressbookUrl = reply->property("addressbookUrl").toString();
    QByteArray data = reply->readAll();
    if (reply->error() != QNetworkReply::NoError) {
868
        int httpError = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
869
        LOG_WARNING(Q_FUNC_INFO << "error:" << reply->error()
870
                   << "(" << httpError << ")");
871
        debugDumpData(QString::fromUtf8(data));
872
        errorOccurred(httpError);
873 874 875 876 877 878 879 880 881
        return;
    }

    QList<ReplyParser::ContactInformation> infos = m_parser->parseContactMetadata(data, addressbookUrl);
    fetchContacts(addressbookUrl, infos);
}

void CardDav::fetchContacts(const QString &addressbookUrl, const QList<ReplyParser::ContactInformation> &amrInfo)
{
882
    LOG_DEBUG(Q_FUNC_INFO << "requesting full contact information from addressbook" << addressbookUrl);
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897

    // split into A/M/R request sets
    QStringList contactUris;
    Q_FOREACH (const ReplyParser::ContactInformation &info, amrInfo) {
        if (info.modType == ReplyParser::ContactInformation::Addition) {
            q->m_serverAdditionIndices[addressbookUrl].insert(info.uri, q->m_serverAdditions[addressbookUrl].size());
            q->m_serverAdditions[addressbookUrl].append(info);
            contactUris.append(info.uri);
        } else if (info.modType == ReplyParser::ContactInformation::Modification) {
            q->m_serverModificationIndices[addressbookUrl].insert(info.uri, q->m_serverModifications[addressbookUrl].size());
            q->m_serverModifications[addressbookUrl].append(info);
            contactUris.append(info.uri);
        } else if (info.modType == ReplyParser::ContactInformation::Deletion) {
            q->m_serverDeletions[addressbookUrl].append(info);
        } else {
898
            LOG_WARNING(Q_FUNC_INFO << "no modification type in info for:" << info.uri);
899 900 901
        }
    }

902
    LOG_DEBUG(Q_FUNC_INFO << "Have calculated AMR:"
903 904 905
             << q->m_serverAdditions[addressbookUrl].size()
             << q->m_serverModifications[addressbookUrl].size()
             << q->m_serverDeletions[addressbookUrl].size()
906
             << "for addressbook:" << addressbookUrl);
907 908 909

    if (contactUris.isEmpty()) {
        // no additions or modifications to fetch.
910
        LOG_DEBUG(Q_FUNC_INFO << "no further data to fetch");
911 912 913
        contactAddModsComplete(addressbookUrl);
    } else {
        // fetch the full contact data for additions/modifications.
914
        LOG_DEBUG(Q_FUNC_INFO << "fetching vcard data for" << contactUris.size() << "contacts");
915 916 917 918 919 920 921
        QNetworkReply *reply = m_request->contactMultiget(m_serverUrl, addressbookUrl, contactUris);
        if (!reply) {
            emit error();
            return;
        }

        reply->setProperty("addressbookUrl", addressbookUrl);
922
        connect(reply, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(sslErrorsOccurred(QList<QSslError>)));
923 924 925 926 927 928 929 930 931 932
        connect(reply, SIGNAL(finished()), this, SLOT(contactsResponse()));
    }
}

void CardDav::contactsResponse()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
    QString addressbookUrl = reply->property("addressbookUrl").toString();
    QByteArray data = reply->readAll();
    if (reply->error() != QNetworkReply::NoError) {
933
        int httpError = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
934
        LOG_WARNING(Q_FUNC_INFO << "error:" << reply->error()
935
                   << "(" << httpError << ")");
936
        debugDumpData(QString::fromUtf8(data));
937
        errorOccurred(httpError);
938 939 940 941 942 943 944 945
        return;
    }

    QList<QContact> added;
    QList<QContact> modified;

    // fill out added/modified.  Also keep our addressbookContactGuids state up-to-date.
    // The addMods map is a map from server contact uri to <contact/unsupportedProperties/etag>.
946
    QMap<QString, ReplyParser::FullContactInformation> addMods = m_parser->parseContactData(data, addressbookUrl);
947 948 949
    QMap<QString, ReplyParser::FullContactInformation>::const_iterator it = addMods.constBegin();
    for ( ; it != addMods.constEnd(); ++it) {
        if (q->m_serverAdditionIndices[addressbookUrl].contains(it.key())) {
950 951
            QContact c = it.value().contact;
            QString guid = c.detail<QContactGuid>().guid();
952 953 954 955 956 957
            q->m_serverAdditions[addressbookUrl][q->m_serverAdditionIndices[addressbookUrl].value(it.key())].guid = guid;
            q->m_contactEtags[guid] = it.value().etag;
            q->m_contactUris[guid] = it.key();
            q->m_contactUnsupportedProperties[guid] = it.value().unsupportedProperties;
            // Note: for additions, q->m_contactUids will have been filled out by the reply parser.
            q->m_addressbookContactGuids[addressbookUrl].append(guid);
958 959 960
            // Check to see if this server-side addition is actually just
            // a reported previously-upsynced local-side addition.
            if (q->m_contactIds.contains(guid)) {
961
                QContact previouslyUpsynced = c;
962 963 964 965
                previouslyUpsynced.setId(QContactId::fromString(q->m_contactIds[guid]));
                added.append(previouslyUpsynced);
            } else {
                // pure server-side addition.
966
                added.append(c);
967
            }
968
            q->m_serverAddModsByUid.insert(q->m_contactUids[guid], qMakePair(addressbookUrl, c));
969 970 971 972 973 974
        } else if (q->m_serverModificationIndices[addressbookUrl].contains(it.key())) {
            QContact c = it.value().contact;
            QString guid = c.detail<QContactGuid>().guid();
            q->m_contactUnsupportedProperties[guid] = it.value().unsupportedProperties;
            q->m_contactEtags[guid] = it.value().etag;
            if (!q->m_contactIds.contains(guid)) {
975
                LOG_WARNING(Q_FUNC_INFO << "modified contact has no id");
976 977 978 979
            } else {
                c.setId(QContactId::fromString(q->m_contactIds[guid]));
            }
            modified.append(c);
980
            q->m_serverAddModsByUid.insert(q->m_contactUids[guid], qMakePair(addressbookUrl, c));
981
        } else {
982
            LOG_WARNING(Q_FUNC_INFO << "ignoring unknown addition/modification:" << it.key());
983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
        }
    }

    // coalesce the added/modified contacts from this addressbook into the complete AMR
    m_remoteAdditions.append(added);
    m_remoteModifications.append(modified);

    // now handle removals
    contactAddModsComplete(addressbookUrl);
}

void CardDav::contactAddModsComplete(const QString &addressbookUrl)
{
    QList<QContact> removed;

    // fill out removed set, and remove any state data associated with removed contacts
    for (int i = 0; i < q->m_serverDeletions[addressbookUrl].size(); ++i) {
        QString guid = q->m_serverDeletions[addressbookUrl][i].guid;
1001 1002 1003 1004 1005 1006 1007 1008
        if (!q->m_contactIds.contains(guid)) {
            // check to see if we have an entry which matches the "old" guid form.
            // if so, use the "old" guid form instead.
            QString prefix = QStringLiteral("%1:AB:%2:").arg(QString::number(q->m_accountId), addressbookUrl);
            if (guid.startsWith(prefix)) {
                guid = QStringLiteral("%1:%2").arg(QString::number(q->m_accountId), guid.mid(prefix.length()));
            }
        }
1009 1010 1011 1012 1013 1014 1015

        // create the contact to remove
        QContact doomed;
        QContactGuid cguid;
        cguid.setGuid(guid);
        doomed.saveDetail(&cguid);
        if (!q->m_contactIds.contains(guid)) {
1016
            LOG_WARNING(Q_FUNC_INFO << "removed contact has no id");
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
            continue; // cannot remove it if we don't know the id
        }
        doomed.setId(QContactId::fromString(q->m_contactIds[guid]));
        removed.append(doomed);

        // update the state data
        q->m_contactUids.remove(guid);
        q->m_contactUris.remove(guid);
        q->m_contactEtags.remove(guid);
        q->m_contactIds.remove(guid);
        q->m_contactUnsupportedProperties.remove(guid);
        q->m_addressbookContactGuids[addressbookUrl].removeOne(guid);
    }

    // coalesce the removed contacts from this addressbook into the complete AMR
    m_remoteRemovals.append(removed);

    // downsync complete for this addressbook.
    // we use a singleshot to ensure that the m_deltaRequests count isn't
    // decremented synchronously to zero if the first addressbook didn't
    // have any remote additions or modifications (requiring async request).
    QTimer::singleShot(0, this, SLOT(downsyncComplete()));
}

void CardDav::downsyncComplete()
{
    // downsync complete for this addressbook
    // if this was the last outstanding addressbook, we're finished.
    m_downsyncRequests -= 1;
    if (m_downsyncRequests == 0) {
1047
        LOG_DEBUG(Q_FUNC_INFO
1048 1049 1050
                 << "downsync complete with total AMR:"
                 << m_remoteAdditions.size() << ","
                 << m_remoteModifications.size() << ","
1051
                 << m_remoteRemovals.size());
1052 1053 1054 1055
        emit remoteChanges(m_remoteAdditions, m_remoteModifications, m_remoteRemovals);
    }
}

1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
static QString transformIntoAddressbookSpecificGuid(const QString &guidstr, int accountId, const QString &addressbookUrl)
{
    QString retn;
    if (guidstr.startsWith(QStringLiteral("%1:AB:%2:").arg(QString::number(accountId), addressbookUrl))) {
        // nothing to do, already a guid for this addressbook
        return guidstr;
    } else if (guidstr.startsWith(QStringLiteral("%1:AB:").arg(accountId))) {
        // guid for a different addressbook.
        LOG_WARNING("error: guid for different addressbook:" << guidstr);
        return guidstr; // return it anyway, rather than attempt to mangle it with this addressbookUrl also.
    } else {
        // transform into addressbook-url style GUID.
        if (guidstr.startsWith(QStringLiteral("%1:").arg(accountId))) {
            // already accountId prefixed (e.g., from a previous sync cycle prior to when we supported addressbookUrl-prefixed-guids
            retn = QStringLiteral("%1:AB:%2:%3").arg(QString::number(accountId), addressbookUrl, guidstr.mid(guidstr.indexOf(':')+1));
        } else {
            // non-prefixed, device-side guid (e.g., a local contact addition)
            retn = QStringLiteral("%1:AB:%2:%3").arg(QString::number(accountId), addressbookUrl, guidstr);
        }
    }
    return retn;
}

static void setUpsyncContactGuid(QContact *c, const QString &uid)
{
    // in the case where the exact same contact is contained
    // in multiple remote addressbooks, the syncContact generated
    // locally may contain duplicated GUID data.  Filter these out
    // and instead set the UID as the guid field for upsync.
    QList<QContactGuid> guids = c->details<QContactGuid>();
    for (int i = guids.size(); i > 1; --i) {
        QContactGuid &g(guids[i-1]);
        c->removeDetail(&g);
    }

    QContactGuid newGuid = c->detail<QContactGuid>();
    newGuid.setGuid(uid);
    c->saveDetail(&newGuid);
}

1096 1097
void CardDav::upsyncUpdates(const QString &addressbookUrl, const QList<QContact> &added, const QList<QContact> &modified, const QList<QContact> &removed)
{
1098
    LOG_DEBUG(Q_FUNC_INFO
1099
             << "upsyncing updates to addressbook:" << addressbookUrl
1100
             << ":" << added.count() << modified.count() << removed.count());
1101

1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
    bool hadNonSpuriousChanges = false;
    int spuriousModifications = 0;

    // put local additions
    for (int i = 0; i < added.size(); ++i) {
        QContact c = added.at(i);
        // generate a server-side uid
        QString uid = QUuid::createUuid().toString().replace(QRegularExpression(QStringLiteral("[\\-{}]")), QString());
        // transform into local-device guid
        QString guid = QStringLiteral("%1:AB:%2:%3").arg(QString::number(q->m_accountId), addressbookUrl, uid);
        // generate a valid uri
1113
        QString uri = addressbookUrl + (addressbookUrl.endsWith('/') ? QString() : QStringLiteral("/")) + uid + QStringLiteral(".vcf");
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
        // update our state data
        q->m_contactUids[guid] = uid;
        q->m_contactUris[guid] = uri;
        q->m_contactIds[guid] = c.id().toString();
        // set the uid not guid so that the VCF UID is generated.
        setUpsyncContactGuid(&c, uid);
        // generate a vcard
        QString vcard = m_converter->convertContactToVCard(c, QStringList());
        // upload
        QNetworkReply *reply = m_request->upsyncAddMod(m_serverUrl, uri, QString(), vcard);
        if (!reply) {
            emit error();
            return;
        }

1129
        m_upsyncRequests += 1;
1130 1131 1132 1133 1134 1135
        hadNonSpuriousChanges = true;
        reply->setProperty("addressbookUrl", addressbookUrl);
        reply->setProperty("contactGuid", guid);
        connect(reply, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(sslErrorsOccurred(QList<QSslError>)));
        connect(reply, SIGNAL(finished()), this, SLOT(upsyncResponse()));
    }
1136

1137 1138 1139 1140 1141 1142 1143 1144
    // put local modifications
    for (int i = 0; i < modified.size(); ++i) {
        QContact c = modified.at(i);
        // reinstate the server-side UID into the guid detail
        QString guidstr = c.detail<QContactGuid>().guid();
        if (guidstr.isEmpty()) {
            LOG_WARNING(Q_FUNC_INFO << "modified contact has no guid:" << c.id().toString());
            continue; // TODO: this is actually an error.
1145
        }
1146
        QString oldguidstr = guidstr;
1147 1148 1149
        guidstr = transformIntoAddressbookSpecificGuid(guidstr, q->m_accountId, addressbookUrl);
        QString uidstr = q->m_contactUids[guidstr];
        if (uidstr.isEmpty()) {
1150 1151 1152 1153 1154 1155 1156 1157 1158
            // check to see if the old guid was used previously.
            // this should only occur after the package upgrade, and not normally.
            if (!q->m_contactUids.value(oldguidstr).isEmpty()) {
                q->migrateGuidData(oldguidstr, guidstr, addressbookUrl);
                uidstr = q->m_contactUids.value(guidstr);
            } else {
                LOG_WARNING(Q_FUNC_INFO << "modified contact server uid unknown:" << c.id().toString() << guidstr);
                continue; // TODO: this is actually an error.
            }
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
        }
        setUpsyncContactGuid(&c, uidstr);
        // now check to see if it's a spurious change caused by downsync of a remote addition/modification
        // perhaps to the same contact in a different addressbook.
        if (q->m_serverAddModsByUid.contains(uidstr)) {
            bool spurious = true;
            const QList<QPair<QString, QContact> > &addressbookContacts(q->m_serverAddModsByUid.values(uidstr));
            for (int j = 0; j < addressbookContacts.size(); ++j) {
                QContact downsyncedContact = addressbookContacts[j].second;
                if (q->significantDifferences(&c, &downsyncedContact)) {
                    spurious = false;
                    break;
                }
1172
            }
1173 1174 1175 1176
            if (spurious) {
                LOG_DEBUG(Q_FUNC_INFO << "not upsyncing spurious change to contact:" << guidstr);
                spuriousModifications += 1;
                continue;
1177
            }
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
        }
        // otherwise, convert to vcard and upsync to remote server.
        QString vcard = m_converter->convertContactToVCard(c, q->m_contactUnsupportedProperties[guidstr]);
        // upload
        QNetworkReply *reply = m_request->upsyncAddMod(m_serverUrl,
                q->m_contactUris[guidstr],
                q->m_contactEtags[guidstr],
                vcard);
        if (!reply) {
            emit error();
            return;
1189 1190
        }

1191 1192 1193 1194 1195 1196 1197
        m_upsyncRequests += 1;
        hadNonSpuriousChanges = true;
        reply->setProperty("addressbookUrl", addressbookUrl);
        reply->setProperty("contactGuid", guidstr);
        connect(reply, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(sslErrorsOccurred(QList<QSslError>)));
        connect(reply, SIGNAL(finished()), this, SLOT(upsyncResponse()));
    }
1198

1199 1200 1201 1202
    // delete local removals
    for (int i = 0; i < removed.size(); ++i) {
        QContact c = removed[i];
        QString guidstr = c.detail<QContactGuid>().guid();
1203
        QString oldguidstr = guidstr;
1204
        guidstr = transformIntoAddressbookSpecificGuid(guidstr, q->m_accountId, addressbookUrl);
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
        if (q->m_contactUris.value(guidstr).isEmpty()) {
            // check to see if the old guid was used previously.
            // this should only occur after the package upgrade, and not normally.
            if (!q->m_contactUris.value(oldguidstr).isEmpty()) {
                q->migrateGuidData(oldguidstr, guidstr, addressbookUrl);
            } else {
                LOG_WARNING(Q_FUNC_INFO << "deleted contact server uri unknown:" << c.id().toString() << guidstr);
                continue; // TODO: this is actually an error.
            }
        }
1215 1216 1217 1218 1219 1220
        QNetworkReply *reply = m_request->upsyncDeletion(m_serverUrl,
                q->m_contactUris[guidstr],
                q->m_contactEtags[guidstr]);
        if (!reply) {
            emit error();
            return;
1221
        }
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242

        // clear state data for this (deleted) contact
        q->m_contactEtags.remove(guidstr);
        q->m_contactUris.remove(guidstr);
        q->m_contactIds.remove(guidstr);
        q->m_contactUids.remove(guidstr);
        q->m_addressbookContactGuids[addressbookUrl].removeOne(guidstr);

        m_upsyncRequests += 1;
        hadNonSpuriousChanges = true;
        reply->setProperty("addressbookUrl", addressbookUrl);
        connect(reply, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(sslErrorsOccurred(QList<QSslError>)));
        connect(reply, SIGNAL(finished()), this, SLOT(upsyncResponse()));
    }

    if (!hadNonSpuriousChanges || (added.size() == 0 && modified.size() == 0 && removed.size() == 0)) {
        // nothing to upsync.  Use a singleshot to avoid synchronously
        // decrementing the m_upsyncRequests count to zero if there
        // happens to be nothing to upsync to the first addressbook.
        m_upsyncRequests += 1;
        QTimer::singleShot(0, this, SLOT(upsyncComplete()));
1243
    }
1244 1245

    LOG_DEBUG(Q_FUNC_INFO << "ignored" << spuriousModifications << "spurious updates to addressbook:" << addressbookUrl);
1246 1247 1248 1249 1250 1251 1252 1253
}

void CardDav::upsyncResponse()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
    QString guid = reply->property("contactGuid").toString();
    QByteArray data = reply->readAll();
    if (reply->error() != QNetworkReply::NoError) {
1254
        int httpError = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
1255
        LOG_WARNING(Q_FUNC_INFO << "error:" << reply->error()
1256
                   << "(" << httpError << ")");
1257
        debugDumpData(QString::fromUtf8(data));
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
        if (httpError == 405) {
            // MethodNotAllowed error.  Most likely the server has restricted
            // new writes to the collection (e.g., read-only or update-only).
            // We should not abort the sync if we receive this error.
            LOG_WARNING(Q_FUNC_INFO << "405 MethodNotAllowed - is the collection read-only?");
            LOG_WARNING(Q_FUNC_INFO << "continuing sync despite this error - upsync will have failed!");
        } else {
            errorOccurred(httpError);
            return;
        }
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
    }

    if (!guid.isEmpty()) {
        // this is an addition or modification.
        // get the new etag value reported by the server.
        QString etag;
        Q_FOREACH(const QByteArray &header, reply->rawHeaderList()) {
            if (QString::fromUtf8(header).contains(QLatin1String("etag"), Qt::CaseInsensitive)) {
                etag = reply->rawHeader(header);
                break;
            }
        }

        if (!etag.isEmpty()) {
1282
            LOG_DEBUG("Got updated etag for" << guid << ":" << etag);
1283
            q->m_contactEtags[guid] = etag;
1284 1285 1286 1287 1288
        } else {
            // If we don't perform an additional request, the etag server-side will be different to the etag
            // we have locally, and thus on next sync we would spuriously detect a server-side modification.
            // That's ok, we'll just detect that it's spurious via data inspection during the next sync.
            LOG_WARNING("No updated etag provided for" << guid << ": will be reported as spurious remote modification next sync");
1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
        }
    }

    // upsync is complete for this addressbook.
    upsyncComplete();
}

void CardDav::upsyncComplete()
{
    m_upsyncRequests -= 1;
    if (m_upsyncRequests == 0) {
        // finished upsyncing all data for all addressbooks.
1301
        LOG_DEBUG(Q_FUNC_INFO << "upsync complete");
1302 1303 1304
        emit upsyncCompleted();
    }
}