servicebrowser.cpp 76.3 KB
Newer Older
1 2 3 4
/**************************************************************************
**
** This file is part of Qt Creator
**
hjk's avatar
hjk committed
5
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
6
**
7
** Contact: Nokia Corporation (qt-info@nokia.com)
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
29
** Nokia at qt-info@nokia.com.
30 31
**
**************************************************************************/
32
#include "zeroconf_global.h"
33 34 35 36 37 38
#ifdef Q_OS_WIN
// Disable min max macros from windows headers,
// because we want to use the template methods from std.
#  ifndef NOMINMAX
#    define NOMINMAX
#  endif
39
#  include <winsock2.h>
40
#endif // Q_OS_WIN
tjenssen's avatar
tjenssen committed
41

42 43 44 45 46
#include "mdnsderived.h"
#include "servicebrowser_p.h"

#include <algorithm>
#include <errno.h>
47
#include <limits>
48
#include <signal.h>
49 50 51 52
#ifdef Q_OS_UNIX
// for select()
#  include <unistd.h>
#endif
53

54 55 56 57 58 59
#include <QAtomicPointer>
#include <QCoreApplication>
#include <QDateTime>
#include <QGlobalStatic>
#include <QMetaType>
#include <QMutexLocker>
60
#include <QNetworkInterface>
61 62 63 64
#include <QString>
#include <QStringList>
#include <QtEndian>
#include <QHostInfo>
65

tjenssen's avatar
tjenssen committed
66 67 68 69 70
//the timeval struct under windows uses long instead of suseconds_t
#ifdef Q_OS_WIN
typedef long suseconds_t;
#endif

71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
/*!
  \namespace ZeroConf

  \brief namespace for zeroconf (Bonjour/DNS-SD) functionality, currently mostly for browsing services.
*/

namespace { // anonymous namespace for free functions
// ----------------- free functions -----------------

using namespace ZeroConf;
using namespace ZeroConf::Internal;

QString toFullNameC(const char * const service, const char * const regtype, const char * const domain)
{
    char fullName[kDNSServiceMaxDomainName];
    myDNSServiceConstructFullName(fullName, service, regtype, domain);
    fullName[kDNSServiceMaxDomainName - 1] = 0; // just to be sure
    return QString::fromUtf8(fullName);
}

int fromFullNameC(const char * const fullName, QString &service, QString &regtype, QString &domain)
{
    char fullNameDecoded[kDNSServiceMaxDomainName];
    int encodedI = 0;
    int decodedI = 0;
    int oldPos[4];
    int iPos = 0;
    while (fullName[encodedI] != 0 && encodedI <kDNSServiceMaxDomainName){
        char c = fullName[encodedI++];
        if (c == '\\'){
            c = fullName[++encodedI];
            if (c == 0 || encodedI == kDNSServiceMaxDomainName)
                return 1;
            if (c >= '0' && c <= '9'){
                int val = (c - '0') * 100;
                c = fullName[++encodedI];
                if (c < '0' || c > '9' || encodedI == kDNSServiceMaxDomainName)
                    return 2;
                val += (c - '0') * 10;
                c = fullName[++encodedI];
                if (c < '0' || c > '9')
                    return 3;
                val += (c - '0');
                fullNameDecoded[decodedI++] = static_cast<char>(static_cast<unsigned char>(val));
            } else {
                fullNameDecoded[decodedI++] = c;
            }
        } else if (c == '.') {
            if (iPos < 4) {
                oldPos[iPos++] = decodedI;
            }
            fullNameDecoded[decodedI++] = c;
        } else {
            fullNameDecoded[decodedI++] = c;
        }
    }
    if (iPos != 4) return 5;
    service = QString::fromUtf8(&fullNameDecoded[0], oldPos[0]);
    regtype = QString::fromUtf8(&fullNameDecoded[oldPos[0] + 1], oldPos[3] - oldPos[0] - 1);
    domain = QString::fromUtf8(&fullNameDecoded[oldPos[3] + 1], decodedI - oldPos[3] - 1);
    return 0;
}

/// singleton for lib setup
class ZeroConfLib
{
public:
    ZeroConfLib();
139
    ZConfLib::Ptr defaultLib();
140 141
    void setDefaultLib(LibUsage usage, const QString &avahiLibName, const QString &avahiVersion,
                       const QString &dnsSdLibName, const QString &dnsSdDaemonPath);
142
    int nFallbacksTot() const;
143 144

private:
145 146
    static const char *defaultmDnsSdLibName;
    static const char *defaultmDNSDaemonName;
147
    int m_nFallbacksTot;
148
    QMutex m_lock;
149
    ZConfLib::Ptr m_defaultLib;
150 151 152 153
};

Q_GLOBAL_STATIC(ZeroConfLib, zeroConfLibInstance)

154 155 156 157 158 159 160 161
#ifdef Q_OS_WIN
    const char *ZeroConfLib::defaultmDnsSdLibName  = "dnssd";
    const char *ZeroConfLib::defaultmDNSDaemonName = "mdnssd.exe";
#else
    const char *ZeroConfLib::defaultmDnsSdLibName  = "dns_sd";
    const char *ZeroConfLib::defaultmDNSDaemonName = "mdnssd";
#endif

162
ZeroConfLib::ZeroConfLib(): m_lock(QMutex::Recursive),
163 164 165 166
    m_defaultLib(ZConfLib::createDnsSdLib(QLatin1String(defaultmDnsSdLibName),
                 ZConfLib::createEmbeddedLib(QString(),
                 ZConfLib::createAvahiLib(QLatin1String("avahi-client"),QLatin1String("3"),
                 ZConfLib::createEmbeddedLib(QLatin1String(defaultmDNSDaemonName))))))
167
{
168 169 170 171
    qRegisterMetaType<ZeroConf::Service::ConstPtr>("ZeroConf::Service::ConstPtr");
    qRegisterMetaType<ZeroConf::ErrorMessage::SeverityLevel>("ZeroConf::ErrorMessage::SeverityLevel");
    qRegisterMetaType<ZeroConf::ErrorMessage>("ZeroConf::ErrorMessage");
    qRegisterMetaType<QList<ZeroConf::ErrorMessage> >("QList<ZeroConf::ErrorMessage>");
172 173
    m_nFallbacksTot = (m_defaultLib ? m_defaultLib->nFallbacks() : 0);

174 175
}

176
ZConfLib::Ptr ZeroConfLib::defaultLib(){
177 178 179 180
    QMutexLocker l(&m_lock);
    return m_defaultLib;
}

Fawzi Mohamed's avatar
Fawzi Mohamed committed
181
void ZeroConfLib::setDefaultLib(LibUsage usage, const QString &avahiLibName,
182 183
                                const QString &avahiVersion, const QString &dnsSdLibName,
                                const QString &dnsSdDaemonPath){
184 185
    QMutexLocker l(&m_lock);
    switch (usage){
186 187
    case (UseDnsSdOnly):
        m_defaultLib = ZConfLib::createDnsSdLib(dnsSdLibName);
188 189
        break;
    case (UseEmbeddedOnly):
190
        m_defaultLib = ZConfLib::createEmbeddedLib(dnsSdDaemonPath);
191
        break;
192
    case (UseAvahiOnly):
193
        m_defaultLib = ZConfLib::createAvahiLib(avahiLibName, avahiVersion);
194 195
        break;
    case (UseAvahiOrDnsSd):
196 197
        m_defaultLib = ZConfLib::createAvahiLib(avahiLibName, avahiVersion,
                       ZConfLib::createDnsSdLib(dnsSdLibName));
198 199
        break;
    case (UseAvahiOrDnsSdOrEmbedded):
200 201 202
        m_defaultLib = ZConfLib::createAvahiLib(avahiLibName, avahiVersion,
                       ZConfLib::createDnsSdLib(dnsSdLibName,
                       ZConfLib::createEmbeddedLib(dnsSdDaemonPath)));
203 204 205 206
        break;
    default:
        qDebug() << "invalid usage " << usage;
    }
207 208 209 210 211 212 213 214
    int newNFallbacks = m_defaultLib->nFallbacks();
    if (m_nFallbacksTot < newNFallbacks)
        m_nFallbacksTot = newNFallbacks;
}

int ZeroConfLib::nFallbacksTot() const
{
    return m_nFallbacksTot;
215 216 217 218 219 220
}

} // end anonymous namespace

namespace ZeroConf {

221 222
int gQuickStop = 0;

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
// ----------------- ErrorMessage impl -----------------
/*!
  \class ZeroConf::ErrorMessage

  \brief class representing an error message

  very simple class representing an error message
 */

/// empty constructor (required by qRegisterMetaType)
ErrorMessage::ErrorMessage(): severity(FailureLevel) {}
/// constructor
ErrorMessage::ErrorMessage(SeverityLevel s, const QString &m): severity(s), msg(m) {}

/// returns a human readable string for each severity level
QString ErrorMessage::severityLevelToString(ErrorMessage::SeverityLevel severity)
{
    const char *ctx = "Zeroconf::SeverityLevel";
    switch (severity) {
    case NoteLevel:
        return QCoreApplication::translate(ctx, "NOTE");
    case WarningLevel:
        return QCoreApplication::translate(ctx, "WARNING");
    case ErrorLevel:
        return QCoreApplication::translate(ctx, "ERROR");
    case FailureLevel:
        return QCoreApplication::translate(ctx, "FATAL_ERROR");
    default:
        return QCoreApplication::translate(ctx, "UNKNOWN_LEVEL_%1").arg(severity);
    }
}

QDebug operator<<(QDebug dbg, const ErrorMessage &eMsg)
{
    dbg << ErrorMessage::severityLevelToString(eMsg.severity) << eMsg.msg;
    return dbg;
}

261 262 263 264 265 266
// ----------------- Service impl -----------------
/*!
  \class ZeroConf::Service

  \brief class representing a zeroconf service

Fawzi Mohamed's avatar
Fawzi Mohamed committed
267 268
  Instances of this class are basically constant, but can be outdated. They are normally accessed
  through a Shared pointer.
269 270 271 272 273
  This design avoids race conditions when used though multiple threads.

  \threadsafe
 */

274 275 276 277 278 279 280 281 282 283
Service::Service(const Service &o) :
    m_name(o.m_name),
    m_type(o.m_type),
    m_domain(o.m_domain),
    m_fullName(o.m_fullName),
    m_port(o.m_port),
    m_txtRecord(o.m_txtRecord),
    m_host(o.m_host ? new QHostInfo(*o.m_host) : 0),
    m_interfaceNr(o.m_interfaceNr),
    m_outdated(o.m_outdated)
284 285 286
{
}

287
Service::Service() : m_host(0), m_interfaceNr(0), m_outdated(false)
288 289 290 291
{ }

Service::~Service()
{
292
    delete m_host;
293 294
}

295
/*!
296
  \fn QString Service::networkInterface()
297 298 299

  Returns the interface on which the service is reachable.
 */
300
QNetworkInterface Service::networkInterface() const
301 302 303 304
{
    return QNetworkInterface::interfaceFromIndex(m_interfaceNr);
}

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
QStringList Service::addresses(Service::AddressStyle style) const
{
    QStringList res;
    if (host() == 0)
        return res;
    foreach (const QHostAddress &addr, host()->addresses()){
        QString addrStr;
        if (addr.protocol() == QAbstractSocket::IPv6Protocol) {
            // Add the interface to use to the address <address>%<interface>
            //
            // This is required only for link local addresses (like fe80:*)
            // but as we have it we do it (and most likely addresses here are
            // link local).
            //
            // on windows only addresses like fe80::42%22 work
            // on OSX 10.5 only things like fe80::42%en4 work
            // on later OSX versions and linux both <address>%<interface number>
            // and <address>%<interface name> work, we use the interface name as
            // it looks better
#ifdef Q_OS_WIN
            QString interfaceStr = QString::number(networkInterface().index());
#else
            QString interfaceStr = networkInterface().name();
#endif
            addrStr = QString::fromLatin1("%1%%2").arg(addr.toString()).arg(interfaceStr);
            if (style == QuoteIPv6Adresses)
                addrStr = QString::fromLatin1("[%1]").arg(addrStr);
        } else {
            addrStr = addr.toString();
        }
        res.append(addrStr);
    }
    return res;
}

340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
bool Service::operator==(const Service &o) const {
    bool eq = m_fullName == o.m_fullName
            && m_name == o.m_name && m_type == o.m_type
            && m_domain == o.m_domain && m_port == o.m_port
            && m_txtRecord == o.m_txtRecord && m_interfaceNr == o.m_interfaceNr
            && m_outdated == m_outdated;
    if (eq) {
        if (m_host != o.m_host) {
            if (m_host == 0 || o.m_host == 0)
                return false;
            return m_host->hostName() == o.m_host->hostName()
                    && m_host->addresses() == o.m_host->addresses();
        }
    }
    return eq;
}

QDebug operator<<(QDebug dbg, const Service &service)
358 359 360 361 362
{
    dbg.maybeSpace() << "Service{ name:" << service.name() << ", "
                     << "type:" << service.type() << ", domain:" << service.domain() << ", "
                     << " fullName:" << service.fullName() << ", port:" << service.port()
                     << ", txtRecord:{";
Fawzi Mohamed's avatar
Fawzi Mohamed committed
363
    bool first = true;
364 365 366
    QHashIterator<QString, QString> i(service.txtRecord());
    while (i.hasNext()){
        i.next();
367 368 369 370
        if (first)
            first = false;
        else
            dbg << ", ";
371
        dbg << i.key() << ":" << i.value();
372 373 374 375
    }
    dbg << "}, ";
    if (const QHostInfo *host = service.host()){
        dbg << "host:{" << host->hostName() << ", addresses[";
Fawzi Mohamed's avatar
Fawzi Mohamed committed
376
        first = true;
377 378 379 380 381 382 383 384 385 386 387 388 389 390
        foreach (const QHostAddress &addr, host->addresses()){
            if (first)
                first = false;
            else
                dbg << ", ";
            dbg << addr.toString();
        }
        dbg << "], },";
    } else {
        dbg << " host:*null*,";
    }
    dbg << " interfaceNr:" << service.interfaceNr() << ", outdated:" << service.outdated() << " }";
    return dbg.space();
}
391 392 393 394 395 396 397 398 399 400

QDebug operator<<(QDebug dbg, const Service::ConstPtr &service){
    if (service.data() == 0){
        dbg << "Service{*NULL*}";
    } else {
        dbg << *service.data();
    }
    return dbg;
}

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
// inline methods
/*!
  \fn bool Service::outdated() const

  Returns if the service data is outdated, its value might change even on
  the (otherwise constant) objects returned by a ServiceBrowser.
*/
/*!
  \fn QString Service::name() const

  Returns the name of the service (non escaped).
*/
/*!
  \fn QString Service::type() const

  Returns the name of the service type (non escaped).
*/
/*!
  \fn QString Service::domain() const

  Returns the name of the domain (non escaped).
*/
/*!
  \fn QString Service::fullName() const

  Returns the full name (service.type.domain) with each component correctly escaped.
*/
/*!
  \fn QString Service::port() const

  Return the port of the service (as a string, not as number).
*/
/*!
  \fn const Service::ServiceTxtRecord &txtRecord() const

  Returns the extra information on this service.
*/
/*!
  \fn const Service::QHostInfo *host() const

  Returns the host through which this service is reachable.
*/
/*!
  \fn int Service::interfaceNr() const

  returns the interface on which the service is reachable, 1 based, 0 means to try all interfaces
*/
/*!
  \fn bool Service::invalidate()

  Marks this service as outdated.
*/

// ----------------- ServiceBrowser impl -----------------
/*!
  \class ZeroConf::ServiceBrowser

  \brief class that browses (searches) for a given zeronconf service

  The actual browsing starts only when startBrowsing() is called. If you want to receive all service
  changes connect before starting browsing.

  The current list of services can be gathered with the services() method.

  \threadsafe
 */

/// starts the browsing, return true if successfull
Fawzi Mohamed's avatar
Fawzi Mohamed committed
469
void ServiceBrowser::startBrowsing(qint32 interfaceIndex)
470
{
Fawzi Mohamed's avatar
Fawzi Mohamed committed
471
    d->startBrowsing(interfaceIndex);
472 473 474
}

/// create a new brower for the given service type
475 476
ServiceBrowser::ServiceBrowser(const QString &serviceType, const QString &domain,
        AddressesSetting addressesSetting, QObject *parent)
477
    : QObject(parent), timer(0),
478 479
      d(new ServiceBrowserPrivate(serviceType, domain, addressesSetting == RequireAddresses,
          MainConnectionPtr()))
480
{
481
    connect(this,SIGNAL(activateAutoRefresh()),this,SLOT(autoRefresh()));
482 483 484
    d->q = this;
}

485 486
ServiceBrowser::ServiceBrowser(const MainConnectionPtr &mainConnection, const QString &serviceType,
        const QString &domain, AddressesSetting addressesSetting, QObject *parent)
487
    : QObject(parent), timer(0),
488 489
      d(new ServiceBrowserPrivate(serviceType, domain, addressesSetting == RequireAddresses,
          mainConnection))
490 491 492 493 494 495 496 497 498 499
{
    d->q = this;
}

ServiceBrowser::~ServiceBrowser()
{
    delete d;
}

/// returns the main connection used by this ServiceBrowser
500
MainConnectionPtr ServiceBrowser::mainConnection() const
501 502 503 504 505 506 507
{
    return d->mainConnection;
}

/// stops browsing, but does not delete all services found
void ServiceBrowser::stopBrowsing()
{
508 509 510 511 512
    if (timer) {
        timer->stop();
        delete timer;
        timer = 0;
    }
513 514 515
    d->stopBrowsing();
}

516 517 518 519 520 521
/// starts an explicit browse (important especially with avahi)
void ServiceBrowser::triggerRefresh()
{
    d->triggerRefresh();
}

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
/// if the service is currently active
bool ServiceBrowser::isBrowsing() const
{
    return d->browsing;
}

/// type of the service browsed (non escaped)
const QString& ServiceBrowser::serviceType() const
{
    return d->serviceType;
}

/// domain that is browser (non escaped)
const QString& ServiceBrowser::domain() const
{
    return d->domain;
}

/// if addresses should be resolved automatically for each service found
bool ServiceBrowser::adressesAutoResolved() const
{
    return d->autoResolveAddresses;
}

/// if addresses are required to add the service to the list of available services
547
bool ServiceBrowser::addressesRequired() const
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
{
    return d->requireAddresses;
}

/// list of current services (by copy on purpose)
QList<Service::ConstPtr> ServiceBrowser::services() const
{
    QMutexLocker l(d->mainConnection->lock());
    return d->activeServices;
}

/// forces a full update of a service (call this after a failure to connect to the service)
/// this is an expensive call, use only when needed
void ServiceBrowser::reconfirmService(Service::ConstPtr service)
{
    d->reconfirmService(service);
}

566 567 568 569 570 571
void ServiceBrowser::autoRefresh()
{
    QMutexLocker l(d->mainConnection->lock());
    if (!timer) {
        timer = new QTimer(this);
        connect(timer,SIGNAL(timeout()),this,SLOT(triggerRefresh()));
572
        timer->setSingleShot(true);
573
    }
574
    timer->start(5000);
575 576
}

577 578
// signals
/*!
Fawzi Mohamed's avatar
Fawzi Mohamed committed
579 580
  \fn void ServiceBrowser::serviceChanged(
       Service::ConstPtr oldService, Service::ConstPtr newService, ServiceBrowser *browser)
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

   This signal is called when a service is added removed or changes.
   Both oldService or newService might be null (covers both add and remove).
   The services list might not be synchronized with respect to this signal.
*/
/*!
  \fn void ServiceBrowser::serviceAdded(Service::ConstPtr service, ServiceBrowser *browser)

   This signal is called when a service is added (convenience method)
   the services list might not be synchronized with respect to this signal

   \sa serviceChanged()
*/
/*!
  \fn void ServiceBrowser::serviceRemoved(Service::ConstPtr service, ServiceBrowser *browser)

  This signal is called when a service is removed (convenience method)
  the services list might not be synchronized with respect to this signal

   \sa serviceChanged()
*/
/*!
  \fn void ServiceBrowser::servicesUpdated(ServiceBrowser *browser)

  This signal is called when the list is updated.
Fawzi Mohamed's avatar
Fawzi Mohamed committed
606 607 608
  It might collect several serviceChanged signals together, if you use the list returned by
  services(), use this signal, not serviceChanged(), serviceAdded() or serviceRemoved() to know
  about changes to the list.
609
*/
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
/*!
  \fn void errorMessage(ZeroConf::ErrorMessage::SeverityLevel severity, const QString &msg, ZeroConf::ServiceBrowser *browser)

  This signal is called every time a warning or error is emitted (for example when a library 
  cannot be used and another one has to be used). Zeroconf will still work if severity < FailureLevel.
*/
/*!
  \fn void hadFailure(const QList<ZeroConf::ErrorMessage> &messages, ZeroConf::ServiceBrowser *browser)

  This signal is emitted only when a full failure has happened, and all the previous errors/attempts to set up zeroconf
  are passed in messages.
*/
/*!
  \fn void startedBrowsing(ZeroConf::ServiceBrowser *browser)

  This signal is emitted when browsing has actually started.
  One can rely on either startedBrowsing or hadFailure to be emitted.
*/
628 629 630

// ----------------- library initialization impl -----------------
/*!
631
  Sets the library used by future Service Browsers to preform the mdns queries.
Fawzi Mohamed's avatar
Fawzi Mohamed committed
632 633
  This changes the default library used by the next MainConnection, it does not change the already
  instantiated connections.
634 635
  \a usage can decide which libraries are tried,
  \a libName should be the name (or path) to the libdns library,
Fawzi Mohamed's avatar
Fawzi Mohamed committed
636 637
  \a daemonPath is the path to the daemon executable which should be started by the embedded library
                if no daemon is found.
638 639 640

  \threadsafe
*/
641 642
void setDefaultZConfLib(LibUsage usage, const QString &avahiLibName, const QString &version,
                        const QString &dnsSdLibName,const QString &dnsSdDaemonPath)
643
{
644
    zeroConfLibInstance()->setDefaultLib(usage, avahiLibName, version, dnsSdLibName, dnsSdDaemonPath);
645 646 647
}

namespace Internal {
648 649
// ----------------- dns-sd C callbacks -----------------

Fawzi Mohamed's avatar
Fawzi Mohamed committed
650 651 652 653 654 655
extern "C" void DNSSD_API cServiceResolveReply(DNSServiceRef                       sdRef,
                                               DNSServiceFlags                     flags,
                                               uint32_t                            interfaceIndex,
                                               DNSServiceErrorType                 errorCode,
                                               const char                          *fullname,
                                               const char                          *hosttarget,
Fawzi Mohamed's avatar
Fawzi Mohamed committed
656
                                               uint16_t                            port, /* In network byte order */
Fawzi Mohamed's avatar
Fawzi Mohamed committed
657 658 659
                                               uint16_t                            txtLen,
                                               const unsigned char                 *txtRecord,
                                               void                                *context)
660 661
{
    if (DEBUG_ZEROCONF)
Fawzi Mohamed's avatar
Fawzi Mohamed committed
662 663 664 665 666
        qDebug() << "cServiceResolveReply(" << ((size_t)sdRef) << ", " << ((quint32)flags)
                 << ", " << interfaceIndex << ", " << ((int)errorCode) << ", " << fullname
                 << ", " << hosttarget << ", " << qFromBigEndian(port) << ", " << txtLen << ", '"
                 << QString::fromUtf8((const char *)txtRecord, txtLen) << "', "
                 << ((size_t)context);
667 668 669
    ServiceGatherer *ctxGatherer = reinterpret_cast<ServiceGatherer *>(context);
    if (ctxGatherer){
        if (ctxGatherer->currentService->fullName() != fullname){
Fawzi Mohamed's avatar
Fawzi Mohamed committed
670 671 672 673
            qDebug() << "ServiceBrowser " << ctxGatherer->serviceBrowser->serviceType
                     << " for service " << ctxGatherer->currentService->name()
                     << " ignoring resolve reply for " << fullname << " vs. "
                     << ctxGatherer->currentService->fullName();
674 675
            return;
        }
Fawzi Mohamed's avatar
Fawzi Mohamed committed
676 677
        ctxGatherer->serviceResolveReply(flags, interfaceIndex, errorCode, hosttarget,
                                         QString::number(qFromBigEndian(port)), txtLen, txtRecord);
678 679 680
    }
}

Fawzi Mohamed's avatar
Fawzi Mohamed committed
681 682 683 684 685 686 687 688 689 690 691
extern "C" void DNSSD_API cTxtRecordReply(DNSServiceRef                       sdRef,
                                          DNSServiceFlags                     flags,
                                          uint32_t                            interfaceIndex,
                                          DNSServiceErrorType                 errorCode,
                                          const char                          *fullname,
                                          uint16_t                            rrtype,
                                          uint16_t                            rrclass,
                                          uint16_t                            rdlen,
                                          const void                          *rdata,
                                          uint32_t                            ttl,
                                          void                                *context)
692 693
{
    if (DEBUG_ZEROCONF)
Fawzi Mohamed's avatar
Fawzi Mohamed committed
694 695 696 697 698
        qDebug() << "cTxtRecordReply(" << ((size_t)sdRef) << ", " << ((int)flags) << ", "
                 << interfaceIndex << ", " << ((int)errorCode) << ", " << fullname << ", "
                 << rrtype << ", " << rrclass << ", " << ", " << rdlen
                 << QString::fromUtf8((const char *)rdata, rdlen) << "', " << ttl << ", "
                 << ((size_t)context);
699 700 701
    ServiceGatherer *ctxGatherer = reinterpret_cast<ServiceGatherer *>(context);
    if (ctxGatherer){
        if (rrtype != kDNSServiceType_TXT || rrclass != kDNSServiceClass_IN) {
Fawzi Mohamed's avatar
Fawzi Mohamed committed
702 703 704
            qDebug() << "ServiceBrowser " << ctxGatherer->serviceBrowser->serviceType
                     << " for service " << ctxGatherer->currentService->fullName()
                     << " received an unexpected rrtype/class:" << rrtype << "/" << rrclass;
705 706 707 708 709
        }
        ctxGatherer->txtRecordReply(flags, errorCode, rdlen, rdata, ttl);
    }
}

Fawzi Mohamed's avatar
Fawzi Mohamed committed
710 711 712 713 714 715 716 717
extern "C" void DNSSD_API cAddrReply(DNSServiceRef                    sdRef,
                                     DNSServiceFlags                  flags,
                                     uint32_t                         interfaceIndex,
                                     DNSServiceErrorType              errorCode,
                                     const char                       *hostname,
                                     const struct sockaddr            *address,
                                     uint32_t                         ttl,
                                     void                             *context)
718 719
{
    if (DEBUG_ZEROCONF)
Fawzi Mohamed's avatar
Fawzi Mohamed committed
720 721 722
        qDebug() << "cAddrReply(" << ((size_t)sdRef) << ", " << ((int)flags) << ", "
                 << interfaceIndex << ", " << ((int)errorCode) << ", " << hostname << ", "
                 << QHostAddress(address).toString() << ", " << ttl << ", " << ((size_t)context);
723 724 725 726 727 728 729
    ServiceGatherer *ctxGatherer = reinterpret_cast<ServiceGatherer *>(context);
    if (ctxGatherer){
        ctxGatherer->addrReply(flags, errorCode, hostname, address, ttl);
    }
}

/// callback for service browsing
Fawzi Mohamed's avatar
Fawzi Mohamed committed
730 731 732 733 734 735 736 737
extern "C" void DNSSD_API cBrowseReply(DNSServiceRef       sdRef,
                                       DNSServiceFlags     flags,
                                       uint32_t            interfaceIndex,
                                       DNSServiceErrorType errorCode,
                                       const char          *serviceName,
                                       const char          *regtype,
                                       const char          *replyDomain,
                                       void                *context)
738 739 740
{
    if (DEBUG_ZEROCONF)
        qDebug() << "cBrowseReply(" << ((size_t)sdRef) << ", " << flags << ", " << interfaceIndex
Fawzi Mohamed's avatar
Fawzi Mohamed committed
741 742
                 << ", " << ((int)errorCode) << ", " << serviceName << ", " << regtype << ", "
                 << replyDomain << ", " << ((size_t)context);
743 744 745 746 747
    ServiceBrowserPrivate *sb = (ServiceBrowserPrivate *)(context);
    if (sb == 0){
        qDebug() << "ServiceBrowser ignoring reply because context was null ";
        return;
    }
748 749
    sb->browseReply(flags, interfaceIndex, ZK_PROTO_IPv4_OR_IPv6,
                    errorCode, serviceName, regtype, replyDomain);
750 751
}

752 753 754 755
// ----------------- ConnectionThread impl -----------------

void ConnectionThread::run()
{
756 757 758 759 760 761 762 763
#if defined(Q_OS_UNIX) && !defined(Q_OS_DARWIN)
    struct sigaction act;
    // ignore SIGPIPE
    act.sa_handler=SIG_IGN;
    sigemptyset(&act.sa_mask);
    act.sa_flags=0;
    sigaction(SIGPIPE, &act, NULL);
#endif
764 765 766 767 768 769 770 771 772
    connection.handleEvents();
}

ConnectionThread::ConnectionThread(MainConnection &mc, QObject *parent):
    QThread(parent), connection(mc)
{ }

// ----------------- ServiceGatherer impl -----------------

773
ZConfLib::Ptr ServiceGatherer::lib()
774 775 776 777
{
    return serviceBrowser->mainConnection->lib;
}

778 779 780 781
QString ServiceGatherer::fullName(){
    return currentService->fullName();
}

782
bool ServiceGatherer::enactServiceChange()
783
{
784
    if (DEBUG_ZEROCONF)
Fawzi Mohamed's avatar
Fawzi Mohamed committed
785 786
        qDebug() << "ServiceGatherer::enactServiceChange() for service "
                 << currentService->fullName();
787
    if (currentServiceCanBePublished()) {
788 789 790 791
        if ((publishedService.data() == 0 && currentService == 0)
                || (publishedService.data() != 0 && currentService != 0
                    && *publishedService == *currentService))
            return false;
792 793
        Service::Ptr nService = Service::Ptr(currentService);
        if (publishedService) {
794
            publishedService->invalidate();
795 796 797
            serviceBrowser->nextActiveServices.removeOne(publishedService);
            serviceBrowser->serviceRemoved(publishedService, serviceBrowser->q);
        }
798
        serviceBrowser->serviceChanged(publishedService, nService, serviceBrowser->q);
799 800 801 802 803 804
        publishedService = nService;
        if (nService) {
            serviceBrowser->nextActiveServices.append(nService);
            serviceBrowser->serviceAdded(nService, serviceBrowser->q);
            currentService = new Service(*currentService);
        }
805
        return true;
806
    }
807
    return false;
808 809 810 811 812
}

void ServiceGatherer::retireService()
{
    if (publishedService) {
813 814 815
        if (DEBUG_ZEROCONF)
            qDebug() << "ServiceGatherer::retireService() for service "
                     << currentService->fullName();
816 817
        Service::Ptr nService;
        serviceBrowser->nextActiveServices.removeOne(publishedService);
818
        publishedService->invalidate();
819
        serviceBrowser->serviceRemoved(publishedService, serviceBrowser->q);
820
        serviceBrowser->serviceChanged(publishedService, nService, serviceBrowser->q);
821
        publishedService = nService;
822 823 824
    } else if (DEBUG_ZEROCONF){
        qDebug() << "ServiceGatherer::retireService() for non published service "
                 << currentService->fullName();
825 826 827
    }
}

828
void ServiceGatherer::stopResolve(ZK_IP_Protocol protocol)
829
{
830 831
    if ((protocol == ZK_PROTO_IPv4_OR_IPv6 || protocol == ZK_PROTO_IPv4)
            && (status & ResolveConnectionActive) != 0) {
832 833 834
        QMutexLocker l(serviceBrowser->mainConnection->lock());
        if (serviceBrowser->mainConnection->status() < MainConnection::Stopping)
            lib()->refDeallocate(resolveConnection);
835 836 837 838 839
        status &= ~ResolveConnectionActive;
        serviceBrowser->updateFlowStatusForCancel();
    }
    if ((protocol == ZK_PROTO_IPv4_OR_IPv6 || protocol == ZK_PROTO_IPv6)
            && (status & ResolveConnectionV6Active) != 0) {
840 841 842
        QMutexLocker l(serviceBrowser->mainConnection->lock());
        if (serviceBrowser->mainConnection->status() < MainConnection::Stopping)
            lib()->refDeallocate(resolveConnectionV6);
843 844 845
        status &= ~ResolveConnectionV6Active;
        serviceBrowser->updateFlowStatusForCancel();
    }
846 847
}

848
void ServiceGatherer::restartResolve(ZK_IP_Protocol protocol)
849
{
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
    stopResolve(protocol);
    if (protocol == ZK_PROTO_IPv6) {
        if (currentService->host()) {
            QList<QHostAddress> addrNow = currentService->host()->addresses();
            QMutableListIterator<QHostAddress> addr(addrNow);
            bool changed = false;
            while (addr.hasNext()) {
                if (addr.next().protocol() == QAbstractSocket::IPv6Protocol) {
                    addr.remove();
                    changed = true;
                }
            }
            if (changed) {
                currentService->m_host->setAddresses(addrNow);
            }
        }
        DNSServiceErrorType err = lib()->resolve(
                    serviceBrowser->mainRef(),
                    &resolveConnectionV6,
                    currentService->interfaceNr(), protocol,
                    currentService->name().toUtf8().constData(),
                    currentService->type().toUtf8().constData(),
                    currentService->domain().toUtf8().constData(), this);
        if (err != kDNSServiceErr_NoError) {
            qDebug() << "ServiceBrowser " << serviceBrowser->serviceType
                     << " failed IPv6 discovery of service " << currentService->fullName()
                     << " due to error " << err;
            status = status | ResolveConnectionV6Failed;
        } else {
            status = ((status & ~ResolveConnectionV6Failed) | ResolveConnectionV6Active);
        }
881
    } else {
882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
        if (currentService->host()) {
            if (protocol == ZK_PROTO_IPv4_OR_IPv6) {
                currentService->m_host->setAddresses(QList<QHostAddress>());
            } else {
                QList<QHostAddress> addrNow = currentService->host()->addresses();
                QMutableListIterator<QHostAddress> addr(addrNow);
                bool changed = false;
                while (addr.hasNext()) {
                    if (addr.next().protocol() == QAbstractSocket::IPv4Protocol) {
                        addr.remove();
                        changed = true;
                    }
                }
                if (changed) {
                    currentService->m_host->setAddresses(addrNow);
                }
            }
        }
        DNSServiceErrorType err = lib()->resolve(
                    serviceBrowser->mainRef(),
                    &resolveConnection,
                    currentService->interfaceNr(), protocol,
                    currentService->name().toUtf8().constData(),
                    currentService->type().toUtf8().constData(),
                    currentService->domain().toUtf8().constData(), this);
        if (err != kDNSServiceErr_NoError) {
            qDebug() << "ServiceBrowser " << serviceBrowser->serviceType
                     << " failed discovery of service " << currentService->fullName()
                     << " due to error " << err;
            status = status | ResolveConnectionFailed;
        } else {
            status = ((status & ~ResolveConnectionFailed) | ResolveConnectionActive);
        }
915 916 917 918 919 920
    }
}

void ServiceGatherer::stopTxt()
{
    if ((status & TxtConnectionActive) == 0) return;
921 922 923
    QMutexLocker l(serviceBrowser->mainConnection->lock());
    if (serviceBrowser->mainConnection->status() < MainConnection::Stopping)
        lib()->refDeallocate(txtConnection);
924 925 926 927 928 929 930
    status &= ~TxtConnectionActive;
    serviceBrowser->updateFlowStatusForCancel();
}

void ServiceGatherer::restartTxt()
{
    stopTxt();
931
    DNSServiceErrorType err = lib()->queryRecord(serviceBrowser->mainRef(), &txtConnection,
Fawzi Mohamed's avatar
Fawzi Mohamed committed
932 933 934
                                                 currentService->interfaceNr(),
                                                 currentService->fullName().toUtf8().constData(),
                                                 this);
935 936

    if (err != kDNSServiceErr_NoError) {
Fawzi Mohamed's avatar
Fawzi Mohamed committed
937 938
        qDebug() << "ServiceBrowser " << serviceBrowser->serviceType
                 << " failed query of TXT record of service " << currentService->fullName()
939 940 941 942 943 944 945 946 947 948
                 << " due to error " << err;
        status = status | TxtConnectionFailed;
    } else {
        status = ((status & ~TxtConnectionFailed) | TxtConnectionActive);
    }
}

void ServiceGatherer::stopHostResolution()
{
    if ((status & AddrConnectionActive) == 0) return;
949 950 951
    QMutexLocker l(serviceBrowser->mainConnection->lock());
    if (serviceBrowser->mainConnection->status() < MainConnection::Stopping)
        lib()->refDeallocate(addrConnection);
952 953 954 955 956 957 958
    status &= ~AddrConnectionActive;
    serviceBrowser->updateFlowStatusForCancel();
}

void ServiceGatherer::restartHostResolution()
{
    stopHostResolution();
959
    if (DEBUG_ZEROCONF)
Fawzi Mohamed's avatar
Fawzi Mohamed committed
960 961
        qDebug() << "ServiceGatherer::restartHostResolution for host " << hostName << " service "
                 << currentService->fullName();
962
    if (hostName.isEmpty()){
Fawzi Mohamed's avatar
Fawzi Mohamed committed
963 964
        qDebug() << "ServiceBrowser " << serviceBrowser->serviceType
                 << " cannot start host resolution without hostname for service "
965
                 << currentService->fullName();
966
    }
967
    DNSServiceErrorType err = lib()->getAddrInfo(serviceBrowser->mainRef(), &addrConnection,
Fawzi Mohamed's avatar
Fawzi Mohamed committed
968 969
                                                 currentService->interfaceNr(),
                                                 0 /* kDNSServiceProtocol_IPv4 | kDNSServiceProtocol_IPv6 */,
970
                                                 hostName.toUtf8().constData(), this);
971 972

    if (err != kDNSServiceErr_NoError) {
Fawzi Mohamed's avatar
Fawzi Mohamed committed
973 974 975
        qDebug() << "ServiceBrowser " << serviceBrowser->serviceType
                 << " failed starting resolution of host " << hostName << " for service "
                 << currentService->fullName() << " due to error " << err;
976 977 978 979 980 981 982 983 984
        status = status | AddrConnectionFailed;
    } else {
        status = ((status & ~AddrConnectionFailed) | AddrConnectionActive);
    }
}

/// if the current service can be added
bool ServiceGatherer::currentServiceCanBePublished()
{
Fawzi Mohamed's avatar
Fawzi Mohamed committed
985 986
    return (currentService->host() && !currentService->host()->addresses().isEmpty())
            || !serviceBrowser->requireAddresses;
987 988
}

Fawzi Mohamed's avatar
Fawzi Mohamed committed
989 990
ServiceGatherer::ServiceGatherer(const QString &newServiceName, const QString &newType,
                                 const QString &newDomain, const QString &fullName,
991 992
                                 uint32_t interfaceIndex, ZK_IP_Protocol protocol,
                                 ServiceBrowserPrivate *serviceBrowser):
993
    serviceBrowser(serviceBrowser), publishedService(0), currentService(new Service()), status(0)
994
{
995
    if (DEBUG_ZEROCONF)
Fawzi Mohamed's avatar
Fawzi Mohamed committed
996 997 998
        qDebug() << " creating ServiceGatherer(" << newServiceName << ", " << newType << ", "
                 << newDomain << ", " << fullName << ", " << interfaceIndex << ", "
                 << ((size_t) serviceBrowser);
999 1000 1001 1002 1003
    currentService->m_name = newServiceName;
    currentService->m_type = newType;
    currentService->m_domain = newDomain;
    currentService->m_fullName = fullName;
    currentService->m_interfaceNr = interfaceIndex;
1004
    if (fullName.isEmpty())
Fawzi Mohamed's avatar
Fawzi Mohamed committed
1005 1006 1007
        currentService->m_fullName = toFullNameC(currentService->name().toUtf8().data(),
                                                 currentService->type().toUtf8().data(),
                                                 currentService->domain().toUtf8().data());
1008
    restartResolve(protocol);
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
    restartTxt();
}

ServiceGatherer::~ServiceGatherer()
{
    stopHostResolution();
    stopResolve();
    stopTxt();
    delete currentService;
}

Fawzi Mohamed's avatar
Fawzi Mohamed committed
1020 1021
ServiceGatherer::Ptr ServiceGatherer::createGatherer(
        const QString &newServiceName, const QString &newType, const QString &newDomain,
1022 1023
        const QString &fullName, uint32_t interfaceIndex, ZK_IP_Protocol protocol,
        ServiceBrowserPrivate *serviceBrowser)
1024
{
Fawzi Mohamed's avatar
Fawzi Mohamed committed
1025
    Ptr res(new ServiceGatherer(newServiceName, newType, newDomain, fullName, interfaceIndex,
1026
                                protocol, serviceBrowser));
1027 1028 1029 1030 1031 1032 1033 1034
    res->self = res.toWeakRef();
    return res;
}

ServiceGatherer::Ptr ServiceGatherer::gatherer() {
    return self.toStrongRef();
}

1035
void ServiceGatherer::serviceResolveReply(DNSServiceFlags                     flags,
1036 1037 1038
                                          uint32_t                            interfaceIndex,
                                          DNSServiceErrorType                 errorCode,
                                          const char                          *hosttarget,
1039
                                          const QString                       &port,
1040 1041 1042 1043 1044 1045
                                          uint16_t                            txtLen,
                                          const unsigned char                 *rawTxtRecord)
{
    if (errorCode != kDNSServiceErr_NoError){
        if (errorCode == kDNSServiceErr_Timeout){
            if ((status & ResolveConnectionSuccess) == 0){
Fawzi Mohamed's avatar
Fawzi Mohamed committed
1046 1047
                qDebug() << "ServiceBrowser " << serviceBrowser->serviceType
                         << " failed service resolution for service "
1048
                         << currentService->fullName() << " as it did timeout";
1049 1050 1051
                status |= ResolveConnectionFailed;
            }
        } else {
Fawzi Mohamed's avatar
Fawzi Mohamed committed
1052 1053 1054
            qDebug() << "ServiceBrowser " << serviceBrowser->serviceType
                     << " failed service resolution for service " << currentService->fullName()
                     << " with error " << errorCode;
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
            status |= ResolveConnectionFailed;
        }
        if (status & ResolveConnectionActive) {
            status &= ~ResolveConnectionActive;
            lib()->refDeallocate(resolveConnection);
            serviceBrowser->updateFlowStatusForCancel();
        }
        return;
    }
    serviceBrowser->updateFlowStatusForFlags(flags);
1065
    uint16_t nKeys = txtRecordGetCount(txtLen, rawTxtRecord);
1066
    for (uint16_t i = 0; i < nKeys; ++i){
1067
        enum { maxTxtLen = 256 };
1068 1069 1070
        char keyBuf[maxTxtLen];
        uint8_t valLen;
        const char *valueCStr;
Fawzi Mohamed's avatar
Fawzi Mohamed committed
1071 1072
        DNSServiceErrorType txtErr = txtRecordGetItemAtIndex(
                    txtLen, rawTxtRecord, i, maxTxtLen, keyBuf, &valLen, (const void **)&valueCStr);
1073 1074
        if (txtErr != kDNSServiceErr_NoError){
            qDebug() << "ServiceBrowser " << serviceBrowser->serviceType << " error " << txtErr
1075
                     << " decoding txt record of service " << currentService->fullName();
1076 1077 1078
            break;
        }
        keyBuf[maxTxtLen-1] = 0; // just to be sure
Fawzi Mohamed's avatar
Fawzi Mohamed committed
1079 1080
        currentService->m_txtRecord.insert(QString::fromUtf8(keyBuf),
                                           QString::fromUtf8(valueCStr, valLen));
1081 1082
    }
    currentService->m_interfaceNr = interfaceIndex;
1083
    currentService->m_port = port;
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
    if (hostName != hosttarget) {
        hostName = QString::fromUtf8(hosttarget);
        if (!currentService->host())
            currentService->m_host = new QHostInfo();
        else
            currentService->m_host->setAddresses(QList<QHostAddress>());
        currentService->m_host->setHostName(hostName);
        if (serviceBrowser->autoResolveAddresses){
            restartHostResolution();
        }
    }
    if (currentServiceCanBePublished())
        serviceBrowser->pendingGathererAdd(gatherer());
}

1099
void ServiceGatherer::txtRecordReply(DNSServiceFlags                     flags,
1100 1101 1102 1103 1104 1105 1106 1107
                                     DNSServiceErrorType                 errorCode,
                                     uint16_t                            txtLen,
                                     const void                          *rawTxtRecord,
                                     uint32_t                            /*ttl*/)
{
    if (errorCode != kDNSServiceErr_NoError){
        if (errorCode == kDNSServiceErr_Timeout){
            if ((status & TxtConnectionSuccess) == 0){
Fawzi Mohamed's avatar
Fawzi Mohamed committed
1108 1109 1110
                qDebug() << "ServiceBrowser " << serviceBrowser->serviceType
                         << " failed txt gathering for service " << currentService->fullName()
                         << " as it did timeout";
1111 1112 1113
                status |= TxtConnectionFailed;
            }
        } else {
Fawzi Mohamed's avatar
Fawzi Mohamed committed
1114 1115 1116
            qDebug() << "ServiceBrowser " << serviceBrowser->serviceType
                     << " failed txt gathering for service " << currentService->fullName()
                     << " with error " << errorCode;
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
            status |= TxtConnectionFailed;
        }
        if (status & TxtConnectionActive) {
            status &= ~TxtConnectionActive;
            lib()->refDeallocate(txtConnection);
            serviceBrowser->updateFlowStatusForCancel();
        }
        return;
    }
    serviceBrowser->updateFlowStatusForFlags(flags);

1128
    uint16_t nKeys = txtRecordGetCount(txtLen, rawTxtRecord);
1129 1130 1131 1132
    for (uint16_t i = 0; i < nKeys; ++i){
        char keyBuf[256];
        uint8_t valLen;
        const char *valueCStr;
Fawzi Mohamed's avatar
Fawzi Mohamed committed
1133 1134
        DNSServiceErrorType txtErr = txtRecordGetItemAtIndex(txtLen, rawTxtRecord, i, 256, keyBuf,
                                                             &valLen, (const void **)&valueCStr);
1135 1136
        if (txtErr != kDNSServiceErr_NoError){
            qDebug() << "ServiceBrowser " << serviceBrowser->serviceType << " error " << txtErr
1137
                     << " decoding txt record of service " << currentService->fullName();
1138
            if ((flags & kDNSServiceFlagsAdd) == 0)
1139
                currentService->m_txtRecord.clear();
1140 1141 1142 1143
            break;
        }
        keyBuf[255] = 0; // just to be sure
        if (flags & kDNSServiceFlagsAdd) {
Fawzi Mohamed's avatar
Fawzi Mohamed committed
1144 1145
            currentService->m_txtRecord.insert(QString::fromUtf8(keyBuf),
                                               QString::fromUtf8(valueCStr, valLen));
1146
        } else {
1147
            currentService->m_txtRecord.remove(QString::fromUtf8(keyBuf)); // check value???
1148 1149 1150 1151 1152
        }
    }
    if ((flags & kDNSServiceFlagsAdd) != 0) {
        status |= TxtConnectionSuccess;
    }
1153
    if (currentService->m_txtRecord.count() != 0 && currentServiceCanBePublished())
1154 1155 1156
        serviceBrowser->pendingGathererAdd(gatherer());
}

1157 1158 1159