servicebrowser.cpp 56.3 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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** 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
** Nokia at info@qt.nokia.com.
**
**************************************************************************/

#include "mdnsderived.h"
#include "servicebrowser_p.h"

#include <algorithm>
#include <errno.h>

#include <QtCore/QAtomicPointer>
#include <QtCore/QCoreApplication>
#include <QtCore/QGlobalStatic>
#include <QtCore/QMetaType>
#include <QtCore/QMutexLocker>
#include <QtCore/QString>
#include <QtCore/QStringList>
#include <QtCore/QtEndian>
#include <QtNetwork/QHostInfo>

/*!
  \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();
117
118
    ZConfLib::Ptr defaultLib();
    void setDefaultLib(LibUsage usage, const QString &avahiLibName, const QString &dnsSdLibName, const QString &dnsSdDaemonPath);
119
120
121

private:
    QMutex m_lock;
122
    ZConfLib::Ptr m_defaultLib;
123
124
125
126
};

Q_GLOBAL_STATIC(ZeroConfLib, zeroConfLibInstance)

127
128
ZeroConfLib::ZeroConfLib(): m_lock(QMutex::Recursive),
    m_defaultLib(ZConfLib::createAvahiLib(QLatin1String("avahi-client"),
129
130
                 ZConfLib::createDnsSdLib(QLatin1String("dns_sd"),
                 ZConfLib::createEmbeddedLib(QLatin1String("mdnssd")))))
131
{
132
    qRegisterMetaType<Service::ConstPtr>("ZeroConf::Service::ConstPtr");
133
134
}

135
ZConfLib::Ptr ZeroConfLib::defaultLib(){
136
137
138
139
    QMutexLocker l(&m_lock);
    return m_defaultLib;
}

140
void ZeroConfLib::setDefaultLib(LibUsage usage, const QString &avahiLibName, const QString &dnsSdLibName, const QString &dnsSdDaemonPath){
141
142
    QMutexLocker l(&m_lock);
    switch (usage){
143
144
    case (UseDnsSdOnly):
        m_defaultLib = ZConfLib::createDnsSdLib(dnsSdLibName);
145
146
        break;
    case (UseEmbeddedOnly):
147
        m_defaultLib = ZConfLib::createEmbeddedLib(dnsSdDaemonPath);
148
        break;
149
150
151
152
153
154
155
156
    case (UseAvahiOnly):
        m_defaultLib = ZConfLib::createAvahiLib(avahiLibName);
        break;
    case (UseAvahiOrDnsSd):
        m_defaultLib = ZConfLib::createAvahiLib(avahiLibName, ZConfLib::createDnsSdLib(dnsSdLibName));
        break;
    case (UseAvahiOrDnsSdOrEmbedded):
        m_defaultLib = ZConfLib::createAvahiLib(avahiLibName,ZConfLib::createDnsSdLib(dnsSdLibName, ZConfLib::createEmbeddedLib(dnsSdDaemonPath)));
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
        break;
    default:
        qDebug() << "invalid usage " << usage;
    }
}

} // end anonymous namespace

namespace ZeroConf {

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

  \brief class representing a zeroconf service

  Instances of this class are basically constant, but can be outdated. They are normally accessed through a Shared pointer.
  This design avoids race conditions when used though multiple threads.

  \threadsafe
 */

179
180
181
182
183
184
185
186
187
188
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)
189
190
191
{
}

192
Service::Service() : m_host(0), m_interfaceNr(0), m_outdated(false)
193
194
195
196
{ }

Service::~Service()
{
197
    delete m_host;
198
199
200
201
202
203
204
205
206
}

QDebug operator<<(QDebug dbg, const Service &service)
{
    dbg.maybeSpace() << "Service{ name:" << service.name() << ", "
                     << "type:" << service.type() << ", domain:" << service.domain() << ", "
                     << " fullName:" << service.fullName() << ", port:" << service.port()
                     << ", txtRecord:{";
    bool first=true;
207
208
209
    QHashIterator<QString, QString> i(service.txtRecord());
    while (i.hasNext()){
        i.next();
210
211
212
213
        if (first)
            first = false;
        else
            dbg << ", ";
214
        dbg << i.key() << ":" << i.value();
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
    }
    dbg << "}, ";
    if (const QHostInfo *host = service.host()){
        dbg << "host:{" << host->hostName() << ", addresses[";
        first=true;
        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();
}
// 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
302
void ServiceBrowser::startBrowsing(qint32 interfaceIndex)
303
{
Fawzi Mohamed's avatar
Fawzi Mohamed committed
304
    d->startBrowsing(interfaceIndex);
305
306
307
}

/// create a new brower for the given service type
308
309
310
311
312
ServiceBrowser::ServiceBrowser(const QString &serviceType, const QString &domain,
        AddressesSetting addressesSetting, QObject *parent)
    : QObject(parent),
      d(new ServiceBrowserPrivate(serviceType, domain, addressesSetting == RequireAddresses,
          MainConnectionPtr()))
313
314
315
316
{
    d->q = this;
}

317
318
319
320
321
ServiceBrowser::ServiceBrowser(const MainConnectionPtr &mainConnection, const QString &serviceType,
        const QString &domain, AddressesSetting addressesSetting, QObject *parent)
    : QObject(parent),
      d(new ServiceBrowserPrivate(serviceType, domain, addressesSetting == RequireAddresses,
          mainConnection))
322
323
324
325
326
327
328
329
330
331
{
    d->q = this;
}

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

/// returns the main connection used by this ServiceBrowser
332
MainConnectionPtr ServiceBrowser::mainConnection() const
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
{
    return d->mainConnection;
}

/// stops browsing, but does not delete all services found
void ServiceBrowser::stopBrowsing()
{
    d->stopBrowsing();
}

/// 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
368
bool ServiceBrowser::addressesRequired() const
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
{
    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);
}

// signals
/*!
  \fn void ServiceBrowser::serviceChanged(Service::ConstPtr oldService, Service::ConstPtr newService, ServiceBrowser *browser)

   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.
  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.
*/

// ----------------- library initialization impl -----------------
/*!
421
  Sets the library used by future Service Browsers to preform the mdns queries.
422
423
424
425
426
427
428
429
430
  This changes the default library used by the next MainConnection, it does not change the already instantiated
  connections.
  \a usage can decide which libraries are tried,
  \a libName should be the name (or path) to the libdns library,
  \a daemonPath is the path to the daemon executable which should be started by the embedded library if no daemon
  is found.

  \threadsafe
*/
431
void setDefaultZConfLib(LibUsage usage, const QString &avahiLibName, const QString &dnsSdLibName, const QString &dnsSdDaemonPath)
432
{
433
    zeroConfLibInstance()->setDefaultLib(usage, avahiLibName, dnsSdLibName, dnsSdDaemonPath);
434
435
436
}

namespace Internal {
437
438
// ----------------- dns-sd C callbacks -----------------

Fawzi Mohamed's avatar
Fawzi Mohamed committed
439
440
441
442
443
444
445
446
447
448
extern "C" void DNSSD_API cServiceResolveReply(DNSServiceRef                       sdRef,
                                               DNSServiceFlags                     flags,
                                               uint32_t                            interfaceIndex,
                                               DNSServiceErrorType                 errorCode,
                                               const char                          *fullname,
                                               const char                          *hosttarget,
                                               uint16_t                            port,        /* In network byte order */
                                               uint16_t                            txtLen,
                                               const unsigned char                 *txtRecord,
                                               void                                *context)
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
{
    if (DEBUG_ZEROCONF)
        qDebug() << "cServiceResolveReply(" << ((size_t)sdRef) << ", " << ((quint32)flags) << ", " << interfaceIndex
                 << ", " << ((int)errorCode) << ", " << fullname << ", " << hosttarget << ", " << qFromBigEndian(port) << ", "
                 << txtLen << ", '" << QString::fromUtf8((const char *)txtRecord, txtLen) << "', " << ((size_t)context);
    ServiceGatherer *ctxGatherer = reinterpret_cast<ServiceGatherer *>(context);
    if (ctxGatherer){
        if (ctxGatherer->currentService->fullName() != fullname){
            qDebug() << "ServiceBrowser " << ctxGatherer->serviceBrowser->serviceType << " for service "
                     << ctxGatherer->currentService->name() << " ignoring resolve reply for " << fullname << " vs. " << ctxGatherer->currentService->fullName();
            return;
        }
        ctxGatherer->serviceResolveReply(flags, interfaceIndex, errorCode, hosttarget, QString::number(qFromBigEndian(port)),
                                         txtLen, txtRecord);
    }
}

Fawzi Mohamed's avatar
Fawzi Mohamed committed
466
467
468
469
470
471
472
473
474
475
476
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)
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
{
    if (DEBUG_ZEROCONF)
        qDebug() << "cTxtRecordReply(" << ((size_t)sdRef) << ", " << ((int)flags) << ", " << interfaceIndex
                 << ", " << ((int)errorCode) << ", " << fullname << ", " << rrtype << ", " << rrclass << ", "
                 << ", " << rdlen << QString::fromUtf8((const char *)rdata, rdlen) << "', " << ttl << ", " << ((size_t)context);
    ServiceGatherer *ctxGatherer = reinterpret_cast<ServiceGatherer *>(context);
    if (ctxGatherer){
        if (rrtype != kDNSServiceType_TXT || rrclass != kDNSServiceClass_IN) {
            qDebug() << "ServiceBrowser " << ctxGatherer->serviceBrowser->serviceType << " for service "
                     << ctxGatherer->currentService->fullName() << " received an unexpected rrtype/class:" << rrtype << "/" << rrclass;
        }
        ctxGatherer->txtRecordReply(flags, errorCode, rdlen, rdata, ttl);
    }
}

Fawzi Mohamed's avatar
Fawzi Mohamed committed
492
493
494
495
496
497
498
499
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)
500
501
502
503
504
505
506
507
508
509
510
511
{
    if (DEBUG_ZEROCONF)
        qDebug() << "cAddrReply(" << ((size_t)sdRef) << ", " << ((int)flags) << ", " << interfaceIndex
                 << ", " << ((int)errorCode) << ", " << hostname << ", " << QHostAddress(address).toString() << ", " << ttl << ", "
                 << ((size_t)context);
    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
512
513
514
515
516
517
518
519
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)
520
521
522
523
524
525
526
527
528
529
530
531
532
{
    if (DEBUG_ZEROCONF)
        qDebug() << "cBrowseReply(" << ((size_t)sdRef) << ", " << flags << ", " << interfaceIndex
                 << ", " << ((int)errorCode) << ", " << serviceName << ", " << regtype << ", " << replyDomain << ", "
                 << ((size_t)context);
    ServiceBrowserPrivate *sb = (ServiceBrowserPrivate *)(context);
    if (sb == 0){
        qDebug() << "ServiceBrowser ignoring reply because context was null ";
        return;
    }
    sb->browseReply(flags, interfaceIndex, errorCode, serviceName, regtype, replyDomain);
}

533
534
535
536
537
538
539
540
541
542
543
544
545
// ----------------- ConnectionThread impl -----------------

void ConnectionThread::run()
{
    connection.handleEvents();
}

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

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

546
ZConfLib::Ptr ServiceGatherer::lib()
547
548
549
550
{
    return serviceBrowser->mainConnection->lib;
}

551
552
553
554
QString ServiceGatherer::fullName(){
    return currentService->fullName();
}

555
556
void ServiceGatherer::enactServiceChange()
{
557
558
    if (DEBUG_ZEROCONF)
        qDebug() << "ServiceGatherer::enactServiceChange() for service " << currentService->fullName();
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
    if (currentServiceCanBePublished()) {
        Service::Ptr nService = Service::Ptr(currentService);
        serviceBrowser->serviceChanged(publishedService, nService, serviceBrowser->q);
        if (publishedService) {
            serviceBrowser->nextActiveServices.removeOne(publishedService);
            serviceBrowser->serviceRemoved(publishedService, serviceBrowser->q);
        }
        publishedService = nService;
        if (nService) {
            serviceBrowser->nextActiveServices.append(nService);
            serviceBrowser->serviceAdded(nService, serviceBrowser->q);
            currentService = new Service(*currentService);
        }
    }
}

void ServiceGatherer::retireService()
{
    if (publishedService) {
        Service::Ptr nService;
        serviceBrowser->nextActiveServices.removeOne(publishedService);
        serviceBrowser->serviceChanged(publishedService, nService, serviceBrowser->q);
        serviceBrowser->serviceRemoved(publishedService, serviceBrowser->q);
        publishedService = nService;
    }
}

void ServiceGatherer::stopResolve()
{
    if ((status & ResolveConnectionActive) == 0) return;
    lib()->refDeallocate(resolveConnection);
    status &= ~ResolveConnectionActive;
    serviceBrowser->updateFlowStatusForCancel();
}

void ServiceGatherer::restartResolve()
{
    stopResolve();
    DNSServiceErrorType err = lib()->resolve(
598
                serviceBrowser->mainRef(),
599
                &resolveConnection,
600
601
                currentService->interfaceNr(), currentService->name().toUtf8().constData(),
                currentService->type().toUtf8().constData(), currentService->domain().toUtf8().constData(), this);
602
    if (err != kDNSServiceErr_NoError) {
603
        qDebug() << "ServiceBrowser " << serviceBrowser->serviceType << " failed discovery of service " << currentService->fullName()
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
                 << " due to error " << err;
        status = status | ResolveConnectionFailed;
    } else {
        status = ((status & ~ResolveConnectionFailed) | ResolveConnectionActive);
    }
}

void ServiceGatherer::stopTxt()
{
    if ((status & TxtConnectionActive) == 0) return;
    lib()->refDeallocate(txtConnection);
    status &= ~TxtConnectionActive;
    serviceBrowser->updateFlowStatusForCancel();
}

void ServiceGatherer::restartTxt()
{
    stopTxt();
622
623
    DNSServiceErrorType err = lib()->queryRecord(serviceBrowser->mainRef(), &txtConnection,
                                                 currentService->interfaceNr(), currentService->fullName().toUtf8().constData(), this);
624
625

    if (err != kDNSServiceErr_NoError) {
626
        qDebug() << "ServiceBrowser " << serviceBrowser->serviceType << " failed query of TXT record of service " << currentService->fullName()
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
                 << " due to error " << err;
        status = status | TxtConnectionFailed;
    } else {
        status = ((status & ~TxtConnectionFailed) | TxtConnectionActive);
    }
}

void ServiceGatherer::stopHostResolution()
{
    if ((status & AddrConnectionActive) == 0) return;
    lib()->refDeallocate(addrConnection);
    status &= ~AddrConnectionActive;
    serviceBrowser->updateFlowStatusForCancel();
}

void ServiceGatherer::restartHostResolution()
{
    stopHostResolution();
645
646
    if (DEBUG_ZEROCONF)
        qDebug() << "ServiceGatherer::restartHostResolution for host " << hostName << " service " << currentService->fullName();
647
648
    if (hostName.isEmpty()){
        qDebug() << "ServiceBrowser " << serviceBrowser->serviceType << " cannot start host resolution without hostname for service "
649
                 << currentService->fullName();
650
    }
651
652
653
    DNSServiceErrorType err = lib()->getAddrInfo(serviceBrowser->mainRef(), &addrConnection,
                                                 currentService->interfaceNr(), 0 /* kDNSServiceProtocol_IPv4 | kDNSServiceProtocol_IPv6 */,
                                                 hostName.toUtf8().constData(), this);
654
655
656

    if (err != kDNSServiceErr_NoError) {
        qDebug() << "ServiceBrowser " << serviceBrowser->serviceType << " failed starting resolution of host "
657
                 << hostName << " for service " << currentService->fullName() << " due to error " << err;
658
659
660
661
662
663
664
665
666
667
668
669
670
671
        status = status | AddrConnectionFailed;
    } else {
        status = ((status & ~AddrConnectionFailed) | AddrConnectionActive);
    }
}

/// if the current service can be added
bool ServiceGatherer::currentServiceCanBePublished()
{
    return (currentService->host() && !currentService->host()->addresses().isEmpty()) || !serviceBrowser->requireAddresses;
}

ServiceGatherer::ServiceGatherer(const QString &newServiceName, const QString &newType, const QString &newDomain,
                                 const QString &fullName, uint32_t interfaceIndex, ServiceBrowserPrivate *serviceBrowser):
672
    serviceBrowser(serviceBrowser), publishedService(0), currentService(new Service()), status(0)
673
{
674
    if (DEBUG_ZEROCONF)
675
676
        qDebug() << " creating ServiceGatherer(" << newServiceName << ", " << newType << ", " << newDomain << ", "
                 << fullName << ", " << interfaceIndex << ", " << ((size_t) serviceBrowser);
677
678
679
680
681
    currentService->m_name = newServiceName;
    currentService->m_type = newType;
    currentService->m_domain = newDomain;
    currentService->m_fullName = fullName;
    currentService->m_interfaceNr = interfaceIndex;
682
    if (fullName.isEmpty())
683
        currentService->m_fullName = toFullNameC(currentService->name().toUtf8().data(), currentService->type().toUtf8().data(), currentService->domain().toUtf8().data());
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
    restartResolve();
    restartTxt();
}

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

ServiceGatherer::Ptr ServiceGatherer::createGatherer(const QString &newServiceName, const QString &newType,
                                                     const QString &newDomain, const QString &fullName,
                                                     uint32_t interfaceIndex, ServiceBrowserPrivate *serviceBrowser)
{
    Ptr res(new ServiceGatherer(newServiceName, newType, newDomain, fullName, interfaceIndex, serviceBrowser));
    res->self = res.toWeakRef();
    return res;
}

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

709
void ServiceGatherer::serviceResolveReply(DNSServiceFlags                     flags,
710
711
712
                                          uint32_t                            interfaceIndex,
                                          DNSServiceErrorType                 errorCode,
                                          const char                          *hosttarget,
713
                                          const QString                       &port,
714
715
716
717
718
719
720
                                          uint16_t                            txtLen,
                                          const unsigned char                 *rawTxtRecord)
{
    if (errorCode != kDNSServiceErr_NoError){
        if (errorCode == kDNSServiceErr_Timeout){
            if ((status & ResolveConnectionSuccess) == 0){
                qDebug() << "ServiceBrowser " << serviceBrowser->serviceType << " failed service resolution for service "
721
                         << currentService->fullName() << " as it did timeout";
722
723
724
725
                status |= ResolveConnectionFailed;
            }
        } else {
            qDebug() << "ServiceBrowser " << serviceBrowser->serviceType << " failed service resolution for service "
726
                     << currentService->fullName() << " with error " << errorCode;
727
728
729
730
731
732
733
734
735
736
737
            status |= ResolveConnectionFailed;
        }
        if (status & ResolveConnectionActive) {
            status &= ~ResolveConnectionActive;
            lib()->refDeallocate(resolveConnection);
            serviceBrowser->updateFlowStatusForCancel();
        }
        return;
    }
    if (publishedService) publishedService->invalidate(); // delay this to enactServiceChange?
    serviceBrowser->updateFlowStatusForFlags(flags);
738
    uint16_t nKeys = txtRecordGetCount(txtLen, rawTxtRecord);
739
740
741
742
743
    for (uint16_t i = 0; i < nKeys; ++i){
        enum { maxTxtLen= 256 };
        char keyBuf[maxTxtLen];
        uint8_t valLen;
        const char *valueCStr;
744
        DNSServiceErrorType txtErr = txtRecordGetItemAtIndex(txtLen, rawTxtRecord, i, maxTxtLen,
745
746
747
                                                                    keyBuf, &valLen, (const void **)&valueCStr);
        if (txtErr != kDNSServiceErr_NoError){
            qDebug() << "ServiceBrowser " << serviceBrowser->serviceType << " error " << txtErr
748
                     << " decoding txt record of service " << currentService->fullName();
749
750
751
            break;
        }
        keyBuf[maxTxtLen-1] = 0; // just to be sure
752
        currentService->m_txtRecord.insert(QString::fromUtf8(keyBuf),QString::fromUtf8(valueCStr, valLen));
753
754
    }
    currentService->m_interfaceNr = interfaceIndex;
755
    currentService->m_port = port;
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
    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());
}

771
void ServiceGatherer::txtRecordReply(DNSServiceFlags                     flags,
772
773
774
775
776
777
778
779
780
                                     DNSServiceErrorType                 errorCode,
                                     uint16_t                            txtLen,
                                     const void                          *rawTxtRecord,
                                     uint32_t                            /*ttl*/)
{
    if (errorCode != kDNSServiceErr_NoError){
        if (errorCode == kDNSServiceErr_Timeout){
            if ((status & TxtConnectionSuccess) == 0){
                qDebug() << "ServiceBrowser " << serviceBrowser->serviceType << " failed txt gathering for service "
781
                         << currentService->fullName() << " as it did timeout";
782
783
784
785
                status |= TxtConnectionFailed;
            }
        } else {
            qDebug() << "ServiceBrowser " << serviceBrowser->serviceType << " failed txt gathering for service "
786
                     << currentService->fullName() << " with error " << errorCode;
787
788
789
790
791
792
793
794
795
796
797
            status |= TxtConnectionFailed;
        }
        if (status & TxtConnectionActive) {
            status &= ~TxtConnectionActive;
            lib()->refDeallocate(txtConnection);
            serviceBrowser->updateFlowStatusForCancel();
        }
        return;
    }
    serviceBrowser->updateFlowStatusForFlags(flags);

798
    uint16_t nKeys = txtRecordGetCount(txtLen, rawTxtRecord);
799
800
801
802
    for (uint16_t i = 0; i < nKeys; ++i){
        char keyBuf[256];
        uint8_t valLen;
        const char *valueCStr;
803
        DNSServiceErrorType txtErr = txtRecordGetItemAtIndex(txtLen, rawTxtRecord, i, 256, keyBuf, &valLen, (const void **)&valueCStr);
804
805
        if (txtErr != kDNSServiceErr_NoError){
            qDebug() << "ServiceBrowser " << serviceBrowser->serviceType << " error " << txtErr
806
                     << " decoding txt record of service " << currentService->fullName();
807
            if ((flags & kDNSServiceFlagsAdd) == 0)
808
                currentService->m_txtRecord.clear();
809
810
811
812
            break;
        }
        keyBuf[255] = 0; // just to be sure
        if (flags & kDNSServiceFlagsAdd) {
813
            currentService->m_txtRecord.insert(QString::fromUtf8(keyBuf), QString::fromUtf8(valueCStr, valLen));
814
        } else {
815
            currentService->m_txtRecord.remove(QString::fromUtf8(keyBuf)); // check value???
816
817
818
819
820
        }
    }
    if ((flags & kDNSServiceFlagsAdd) != 0) {
        status |= TxtConnectionSuccess;
    }
821
    if (currentService->m_txtRecord.count() != 0 && currentServiceCanBePublished())
822
823
824
        serviceBrowser->pendingGathererAdd(gatherer());
}

825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
void ServiceGatherer::txtFieldReply(DNSServiceFlags                     flags,
                                    DNSServiceErrorType                 errorCode,
                                    uint16_t                            txtLen,
                                    const void                          *rawTxtRecord,
                                    uint32_t                            /*ttl*/){
    if (errorCode != kDNSServiceErr_NoError){
        if (errorCode == kDNSServiceErr_Timeout){
            if ((status & TxtConnectionSuccess) == 0){
                qDebug() << "ServiceBrowser " << serviceBrowser->serviceType << " failed txt gathering for service "
                         << currentService->fullName() << " as it did timeout";
                status |= TxtConnectionFailed;
            }
        } else {
            qDebug() << "ServiceBrowser " << serviceBrowser->serviceType << " failed txt gathering for service "
                     << currentService->fullName() << " with error " << errorCode;
            status |= TxtConnectionFailed;
        }
        if (status & TxtConnectionActive) {
            status &= ~TxtConnectionActive;
            lib()->refDeallocate(txtConnection);
            serviceBrowser->updateFlowStatusForCancel();
        }
        return;
    }
    serviceBrowser->updateFlowStatusForFlags(flags);
    uint16_t keyLen=0;
    const char *txt=reinterpret_cast<const char *>(rawTxtRecord);
    while (keyLen < txtLen) {
        if (txt[keyLen]=='=')
            break;
        ++keyLen;
    }
    if (flags & kDNSServiceFlagsAdd) {
        currentService->m_txtRecord.insert(QString::fromUtf8(txt, keyLen),
                                           QString::fromUtf8(txt + keyLen + 1,
                                                             ((txtLen>keyLen)?txtLen - keyLen - 1:0)));
    } else {
        currentService->m_txtRecord.remove(QString::fromUtf8(txt, keyLen)); // check value???
    }

}

867
void ServiceGatherer::addrReply(DNSServiceFlags                  flags,
868
869
870
871
872
873
874
875
876
                                DNSServiceErrorType              errorCode,
                                const char                       *hostname,
                                const struct sockaddr            *address,
                                uint32_t                         /*ttl*/) // should we use this???
{
    if (errorCode != kDNSServiceErr_NoError){
        if (errorCode == kDNSServiceErr_Timeout){
            if ((status & AddrConnectionSuccess) == 0){
                qDebug() << "ServiceBrowser " << serviceBrowser->serviceType << " failed address resolve for service "
877
                         << currentService->fullName() << " as it did timeout";
878
879
880
                status |= AddrConnectionFailed;
            }
            qDebug() << "ServiceBrowser " << serviceBrowser->serviceType << " failed addr resolve for service "
881
                     << currentService->fullName() << " with error " << errorCode;
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
            status |= AddrConnectionFailed;
        }
        if (status & AddrConnectionActive){
            status &= ~AddrConnectionActive;
            lib()->refDeallocate(addrConnection);
            serviceBrowser->updateFlowStatusForCancel();
        }
        return;
    }
    serviceBrowser->updateFlowStatusForFlags(flags);
    if (!currentService->host())
        currentService->m_host=new QHostInfo();
    if (currentService->host()->hostName() != hostname) {
        if ((flags & kDNSServiceFlagsAdd) == 1)
            currentService->m_host->setHostName(QString::fromUtf8(hostname));
        if (currentService->host()->addresses().isEmpty()) {
            qDebug() << "ServiceBrowser " << serviceBrowser->serviceType << " for service "
899
                     << currentService->fullName() << " add with name " << hostname << " while old name "
900
901
902
903
904
                     << currentService->host()->hostName() << " has still adresses, removing them";
            currentService->m_host->setAddresses(QList<QHostAddress>());
        }
        else{
            qDebug() << "ServiceBrowser " << serviceBrowser->serviceType << " for service "
905
                     << currentService->fullName() << " ignoring remove for " << hostname << " as current hostname is "
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
                     << currentService->host()->hostName();
            return;
        }
    }
    QHostAddress newAddr(address);
    QList<QHostAddress> addrNow = currentService->host()->addresses();
    if ((flags & kDNSServiceFlagsAdd) == 0) {
        if (addrNow.removeOne(newAddr))
            currentService->m_host->setAddresses(addrNow);
    } else {
        if (!addrNow.contains(newAddr)){
            addrNow.append(newAddr);
            currentService->m_host->setAddresses(addrNow);
        }
    }
    serviceBrowser->pendingGathererAdd(gatherer());
}

void ServiceGatherer::maybeRemove()
{
    // could trigger an update, but for now we just ignore it (less chatty)
}

void ServiceGatherer::stop()
{
    if (status & ResolveConnectionActive){
        status &= ~ResolveConnectionActive;
        lib()->refDeallocate(resolveConnection);
        serviceBrowser->updateFlowStatusForCancel();
    }
    if (status & TxtConnectionActive){
        status &= ~TxtConnectionActive;
        lib()->refDeallocate(txtConnection);
        serviceBrowser->updateFlowStatusForCancel();
    }
    if (status & AddrConnectionActive) {
        status &= ~AddrConnectionActive;
        lib()->refDeallocate(addrConnection);
        serviceBrowser->updateFlowStatusForCancel();
    }
}

void ServiceGatherer::reload(qint32 interfaceIndex)
{
    this->interfaceIndex = interfaceIndex;
    stop();
    restartResolve();
    restartTxt();
    if (currentServiceCanBePublished()) // avoid???
        restartHostResolution();
}

void ServiceGatherer::remove()
{
    stop();
961
962
    if (serviceBrowser->gatherers.contains(currentService->fullName()) && serviceBrowser->gatherers[currentService->fullName()] == this)
        serviceBrowser->gatherers.remove(currentService->fullName());
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
}
/// forces a full reload of the record
void ServiceGatherer::reconfirm()
{
    stop();
    /*        DNSServiceErrorType err = DNSServiceReconfirmRecord(kDNSServiceFlagsShareConnection,
                                                        interfaceIndex, fullName.toUtf8().constData(),
                                                        kDNSServiceType_PTR, // kDNSServiceType_SRV could be another possibility
                                                        kDNSServiceClass_IN //,
                                                        // uint16_t                           rdlen, // not cached... what is the best solution???
                                                        // const void                         *rdata
                                                        ); */
}

// ----------------- ServiceBrowserPrivate impl -----------------

979
ZConfLib::ConnectionRef ServiceBrowserPrivate::mainRef()
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
{
    return mainConnection->mainRef();
}

void ServiceBrowserPrivate::updateFlowStatusForCancel()
{
    mainConnection->updateFlowStatusForCancel();
}

void ServiceBrowserPrivate::updateFlowStatusForFlags(DNSServiceFlags flags)
{
    mainConnection->updateFlowStatusForFlags(flags);
}

void ServiceBrowserPrivate::pendingGathererAdd(ServiceGatherer::Ptr gatherer)
{
    int ng = pendingGatherers.count();
    for (int i = 0; i < ng; ++i){
        const ServiceGatherer::Ptr &g=pendingGatherers.at(i);
999
        if (g->fullName() == gatherer->fullName()){
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
            if (g != gatherer){
                gatherer->publishedService = g->publishedService;
                pendingGatherers[i] = gatherer;
            }
            return;
        }
    }
    pendingGatherers.append(gatherer);
}

ServiceBrowserPrivate::ServiceBrowserPrivate(const QString &serviceType, const QString &domain, bool requireAddresses, MainConnectionPtr mconn):
    q(0), serviceType(serviceType), domain(domain), mainConnection(mconn), serviceConnection(0), flags(0), interfaceIndex(0),
    failed(false), browsing(false), autoResolveAddresses(requireAddresses), requireAddresses(requireAddresses)
{
}

ServiceBrowserPrivate::~ServiceBrowserPrivate()
{
1018
1019
    if (DEBUG_ZEROCONF)
        qDebug() << "destroying ServiceBrowserPrivate " << serviceType;
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
1047
    if (browsing){
        stopBrowsing();
    }
    if (mainConnection){
        mainConnection->removeBrowser(this);
    }
}

void ServiceBrowserPrivate::insertGatherer(const QString &fullName)
{
    if (!gatherers.contains(fullName)){
        QString newServiceName, newType, newDomain;
        if (fromFullNameC(fullName.toUtf8().data(), *&newServiceName, *&newType, *&newDomain)){
            qDebug() << "Error unescaping fullname " << fullName;
        } else {
            ServiceGatherer::Ptr serviceGatherer = ServiceGatherer::createGatherer(newServiceName, newType, newDomain, fullName, 0, this);
            gatherers[fullName] = serviceGatherer;
        }
    }
}

void ServiceBrowserPrivate::maybeUpdateLists()
{
    if (mainConnection->flowStatus != MainConnection::MoreComingRFS || pendingGatherers.count() > 50) {
        QList<QString>::iterator i = knownServices.begin(), endi = knownServices.end();
        QMap<QString, ServiceGatherer::Ptr>::iterator j = gatherers.begin();
        while (i != endi && j != gatherers.end()) {
            const QString vi = *i;
1048
            QString vj = (*j)->fullName();
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
            if (vi == vj){
                ++i;
                ++j;
            } else if (vi < vj) {
                qDebug() << "ServiceBrowser " << serviceType << ", missing gatherer for " << vi;
                insertGatherer(vi);
                ++i;
            } else {
                (*j)->retireService();
                j = gatherers.erase(j);
            }
        }
        while (i != endi) {
            qDebug() << "ServiceBrowser " << serviceType << ", missing gatherer for " << *i;
            insertGatherer(*i);
        }
        while (j != gatherers.end()) {
            (*j)->retireService();
            j = gatherers.erase(j);
        }
        foreach (const ServiceGatherer::Ptr &g, pendingGatherers)
            g->enactServiceChange();
        {
            QMutexLocker l(mainConnection->lock());
            activeServices=nextActiveServices;
        }
        emit q->servicesUpdated(q);
    }
}

/// callback announcing
1080
void ServiceBrowserPrivate::browseReply(DNSServiceFlags                     flags,
1081
1082
1083
1084
1085
1086
                                        uint32_t                            interfaceIndex,
                                        DNSServiceErrorType                 errorCode,
                                        const char                          *serviceName,
                                        const char                          *regtype,
                                        const char                          *replyDomain)
{
1087
    if (DEBUG_ZEROCONF)
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
        qDebug() << "browseReply(" << ((int)flags) << ", " << interfaceIndex << ", " << ((int)errorCode) << ", " << serviceName << ", "
                 << regtype << ", " << replyDomain << ")";
    if (errorCode != kDNSServiceErr_NoError){
        qDebug() << "ServiceBrowser " << serviceType << " ignoring reply due to error " << errorCode;
        return;
    }
    QString newServiceName = QString::fromUtf8(serviceName);
    QString newType = serviceType;
    QString newDomain = domain;
    if (serviceType != regtype) // discard? should not happen...
        newType = QString::fromUtf8(regtype);
    if (domain != replyDomain)
        domain = QString::fromUtf8(replyDomain);
    QString fullName = toFullNameC(serviceName, regtype, replyDomain);
    updateFlowStatusForFlags(flags);
    if (flags & kDNSServiceFlagsAdd){
        ServiceGatherer::Ptr serviceGatherer;
        if (!gatherers.contains(fullName)){
            serviceGatherer = ServiceGatherer::createGatherer(newServiceName, newType, newDomain, fullName, interfaceIndex, this);
            gatherers[fullName] = serviceGatherer;
        } else {
            serviceGatherer = gatherers[fullName];
            serviceGatherer->reload(interfaceIndex);
        }
        QList<QString>::iterator pos = std::lower_bound(knownServices.begin(), knownServices.end(), fullName);
        // could order later (more efficient, but then we have to handle eventual duplicates)
        if (pos == knownServices.end() || *pos != fullName)
            knownServices.insert(pos, fullName);
    } else {
        if (gatherers.contains(fullName)){
            gatherers[fullName]->maybeRemove();
        }
        knownServices.removeOne(fullName);
    }
    maybeUpdateLists();
}

Fawzi Mohamed's avatar
Fawzi Mohamed committed
1125
void ServiceBrowserPrivate::startBrowsing(quint32 interfaceIndex)
1126
{
Fawzi Mohamed's avatar
Fawzi Mohamed committed
1127
1128
1129
    this->interfaceIndex = interfaceIndex;
    if (failed || browsing)
        return;
1130
1131
1132
    if (mainConnection.isNull())
        mainConnection = MainConnectionPtr(new MainConnection());
    mainConnection->addBrowser(this);
Fawzi Mohamed's avatar
Fawzi Mohamed committed
1133
1134
1135
1136
1137
1138
}

bool ServiceBrowserPrivate::internalStartBrowsing()
{
    if (failed || browsing)
        return false;
1139
    DNSServiceErrorType err;
1140
1141
    err = mainConnection->lib->browse(mainRef(), &serviceConnection, interfaceIndex,
                                      serviceType.toUtf8().constData(), ((domain.isEmpty()) ? 0 : (domain.toUtf8().constData())), this);
1142
1143
1144
1145
1146
    if (err != kDNSServiceErr_NoError){
        qDebug() << "ServiceBrowser " << serviceType << " failed initializing serviceConnection";
        return false;
    }
    browsing = true;
1147
    if (DEBUG_ZEROCONF)
1148
1149
1150
1151
1152
1153
1154
1155
1156
        qDebug() << "startBrowsing(" << interfaceIndex << ") for serviceType:" << serviceType << " domain:" << domain;
    return true;
}

void ServiceBrowserPrivate::stopBrowsing()
{
    QMutexLocker l(mainConnection->lock());
    if (browsing){
        if (serviceConnection) {
1157
            mainConnection->lib->browserDeallocate(&serviceConnection);
1158
1159
1160
1161
1162
1163
            updateFlowStatusForCancel();
            serviceConnection=0;
        }
    }
}

1164
void ServiceBrowserPrivate::reconfirmService(Service::ConstPtr s)
1165
{
1166
1167
1168
    if (!s->outdated())
        mainConnection->lib->reconfirmRecord(mainRef(), s->interfaceNr(), s->name().toUtf8().data(), s->type().toUtf8().data(),
                                             s->domain().toUtf8().data(), s->fullName().toUtf8().data());
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
}

/// called when a service is added removed or changes. oldService or newService might be null (covers both add and remove)
void ServiceBrowserPrivate::serviceChanged(const Service::ConstPtr &oldService, const Service::ConstPtr &newService, ServiceBrowser *browser)
{
    emit q->serviceChanged(oldService, newService, browser);
}

/// called when a service is added (utility method)
void ServiceBrowserPrivate::serviceAdded(const Service::ConstPtr &service, ServiceBrowser *browser)
{
    emit q->serviceAdded(service, browser);
}

/// called when a service is removed (utility method)
void ServiceBrowserPrivate::serviceRemoved(const Service::ConstPtr &service, ServiceBrowser *browser)
{
    emit q->serviceRemoved(service, browser);
}

/// called when the list is updated (this might collect several serviceChanged signals together)
void ServiceBrowserPrivate::servicesUpdated(ServiceBrowser *browser)
{
    emit q->servicesUpdated(browser);
}

/// called when there is an error
void ServiceBrowserPrivate::hadError(QStringList errorMsgs, bool completeFailure)
{
    if (completeFailure)
        this->failed=true;
    emit q->hadError(errorMsgs,completeFailure);
}

// ----------------- MainConnection impl -----------------

void MainConnection::stop(bool wait)
{
    if (m_status < Stopping)
        increaseStatusTo(Stopping);
1209
1210
    if (m_mainRef)
        lib->stopConnection(m_mainRef);
1211
1212
1213
1214
1215
1216
1217
    if (!m_thread)
        increaseStatusTo(Stopped);
    else if (wait && QThread::currentThread() != m_thread)
        m_thread->wait();
}

MainConnection::MainConnection():
1218
    lib(zeroConfLibInstance()->defaultLib()), m_lock(QMutex::Recursive), m_mainRef(0), m_failed(false), m_status(Starting), m_nErrs(0)
1219
{
1220
    if (lib.isNull()){
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
        qDebug() << "could not load a valid library for ZeroConf::MainConnection, failing";
    } else {
        m_thread = new ConnectionThread(*this);
        m_thread->start(); // delay startup??
    }
}

MainConnection::~MainConnection()
{
    stop();
    delete m_thread;
    // to do
}

bool MainConnection::increaseStatusTo(int s)
{
    int sAtt = m_status;
    while (sAtt < s){
        if (m_status.testAndSetRelaxed(sAtt, s))
            return true;
        sAtt = m_status;
    }
    return false;
}

QMutex *MainConnection::lock()
{
    return &m_lock;
}

void MainConnection::waitStartup()
{
    int sAtt;
    while (true){
1255
1256
1257
1258
1259
1260
1261
        {
            QMutexLocker l(lock());
            sAtt = m_status;
            if (sAtt >= Running)
                return;
        }
        QThread::yieldCurrentThread();
1262
1263
1264
1265
1266
    }
}

void MainConnection::addBrowser(ServiceBrowserPrivate *browser)
{
Fawzi Mohamed's avatar
Fawzi Mohamed committed
1267
    int actualStatus;
1268
1269
1270
1271
    QStringList errs;
    bool didFail;
    {
        QMutexLocker l(lock());
Fawzi Mohamed's avatar
Fawzi Mohamed committed
1272
        actualStatus = m_status;
1273
1274
1275
1276
        m_browsers.append(browser);
        errs=m_errors;
        didFail=m_failed;
    }
Fawzi Mohamed's avatar
Fawzi Mohamed committed
1277
1278
1279
    if (actualStatus == Running) {
        browser->internalStartBrowsing();
    }
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
    if (didFail || !errs.isEmpty())
        browser->hadError(errs, didFail);
}

void MainConnection::removeBrowser(ServiceBrowserPrivate *browser)
{
    QMutexLocker l(lock());
    m_browsers.removeOne(browser);
}

void MainConnection::updateFlowStatusForCancel(){
    flowStatus = ForceUpdateRFS;
}
void MainConnection::updateFlowStatusForFlags(DNSServiceFlags flags)
{
    if (flags & kDNSServiceFlagsMoreComing) {
        if (flowStatus == NormalRFS)
            flowStatus = MoreComingRFS;
    } else {
        flowStatus = NormalRFS;
    }
}
void MainConnection::maybeUpdateLists()
{
    foreach (ServiceBrowserPrivate *sb, m_browsers) {
        sb->maybeUpdateLists();
    }
}

void MainConnection::gotoValidLib(){
    while (lib){
        if (lib->isOk()) break;
1312
1313
1314
        appendError(QStringList(tr("MainConnection giving up on non Ok lib %1 (%2)")
                                .arg(lib->name()).arg(lib->errorMsg())), false);
        lib = lib->fallbackLib;
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
    }
    if (!lib) {
        appendError(QStringList(tr("MainConnection has no valid library, aborting connection")
                                .arg(lib->name())), true);
        increaseStatusTo(Stopping);
    }
}

void MainConnection::abortLib(){
    if (!lib){
        appendError(QStringList(tr("MainConnection has no valid library, aborting connection")
                                .arg(lib->name())), true);
        increaseStatusTo(Stopping);
    } else if (lib->fallbackLib){
        appendError(QStringList(tr("MainConnection giving up on lib %1, switching to lib %2")
                                .arg(lib->name()).arg(lib->fallbackLib->name())), false);
        lib=lib->fallbackLib;
        m_nErrs=0;
        gotoValidLib();
    } else {
        appendError(QStringList(tr("MainConnection giving up on lib %1, no fallback provided, aborting connection")
                                .arg(lib->name())), true);
        increaseStatusTo(Stopping);
    }
}

void MainConnection::createConnection()
{
    gotoValidLib();
    while (m_status <= Running) {
1345
1346
1347
1348
        if (!lib) {
            increaseStatusTo(Stopped);
            break;
        }
1349
1350
1351
1352
1353
1354
1355
1356
1357
        uint32_t version;
        uint32_t size=(uint32_t)sizeof(uint32_t);
        DNSServiceErrorType err=lib->getProperty(kDNSServiceProperty_DaemonVersion, &version, &size);
        if (err == kDNSServiceErr_NoError){
            DNSServiceErrorType error = lib->createConnection(&m_mainRef);
            if (error != kDNSServiceErr_NoError){
                appendError(QStringList(tr("MainConnection using lib %1 failed the initialization of mainRef with error %2")
                                        .arg(lib->name()).arg(error)),false);
                ++m_nErrs;
1358
                if (m_nErrs > 10 || !lib->isOk())
1359
1360
                    abortLib();
            } else {
Fawzi Mohamed's avatar
Fawzi Mohamed committed
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
                QList<ServiceBrowserPrivate *> waitingBrowsers;
                {
                    QMutexLocker(lock());
                    waitingBrowsers = m_browsers;
                    increaseStatusTo(Running);
                }
                for (int i = waitingBrowsers.count(); i-- != 0; ){
                    ServiceBrowserPrivate *actualBrowser = waitingBrowsers[i];
                    if (actualBrowser && !actualBrowser->browsing)
                        actualBrowser->internalStartBrowsing();
1371
1372
1373
1374
1375
1376
                }
                break;
            }
        } else if (err == kDNSServiceErr_ServiceNotRunning) {
            appendError(QStringList(tr("MainConnection using lib %1 failed because no daemon is running")
                                    .arg(lib->name())),false);
Fawzi Mohamed's avatar
Fawzi Mohamed committed
1377
1378
1379
1380
            if (m_nErrs > 5 || !lib->isOk()) {
                abortLib();
            } else if (lib->tryStartDaemon()) {
                ++m_nErrs;
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
                appendError(QStringList(tr("MainConnection using lib %1 daemon starting seem successful, continuing")
                                        .arg(lib->name())),false);
            } else {
                appendError(QStringList(tr("MainConnection using lib %1 failed because no daemon is running")
                                        .arg(lib->name())),false);
                abortLib();
            }
        } else {
            appendError(QStringList(tr("MainConnection using lib %1 failed getProperty call with error %2")
                                    .arg(lib->name()).arg(err)),false);
            abortLib();
        }
    }
}

1396
ZConfLib::ProcessStatus MainConnection::handleEvent()
1397
{
1398
1399
1400
    ZConfLib::ProcessStatus err = lib->processResult(m_mainRef);
    if (err != ZConfLib::ProcessedOk) {
        qDebug() << "processResult returned " << err;
1401
1402
1403
1404
1405
        ++m_nErrs;
    } else {
        m_nErrs=0;
        maybeUpdateLists();
    }
1406
    return err;
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
}

void MainConnection::destroyConnection()
{
    // multithreading issues if we support multiple cycles of createConnection/destroyConnection
    for (int i = m_browsers.count(); i-- != 0;){
        ServiceBrowserPrivate *bAtt=m_browsers[i];
        if (bAtt->browsing)
            bAtt->stopBrowsing();
    }
    if (m_mainRef != 0)
1418
        lib->destroyConnection(&m_mainRef);
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
    m_mainRef=0;
}

void  MainConnection::handleEvents()
{
    if (!m_status.testAndSetAcquire(Starting, Started)){
        appendError(QStringList(tr("MainConnection::handleEvents called with m_status != Starting, aborting")),true);
        increaseStatusTo(Stopped);
        return;
    }
    m_nErrs = 0;
    createConnection();
    increaseStatusTo(Running);
    while (m_status < Stopping) {
        if (m_nErrs > 10)
            increaseStatusTo(Stopping);
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
        switch (handleEvent()) {
        case ZConfLib::ProcessedOk :
            break;
        case ZConfLib::ProcessedError :
            ++m_nErrs;
            break;
        case ZConfLib::ProcessedFailure :
            increaseStatusTo(Stopping);
            ++m_nErrs;
            break;
        case ZConfLib::ProcessedQuit :
            increaseStatusTo(Stopping);
            break;
        default:
            appendError(QStringList(tr("MainConnection::handleEvents unexpected return status of handleEvent")),true);
            increaseStatusTo(Stopping);
            break;
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
        }
    }
    destroyConnection();
    if (m_nErrs > 0){
        QString browsersNames=(m_browsers.isEmpty()?QString():m_browsers.at(0)->serviceType)+((m_browsers.count()>1)?QString::fromLatin1(",..."):QString());
        appendError(QStringList(tr("MainConnection for [%1] accumulated %2 consecutive errors, aborting").arg(browsersNames).arg(m_nErrs)),true);
    }
    increaseStatusTo(Stopped);
}

1462
ZConfLib::ConnectionRef MainConnection::mainRef()
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
{
    while (m_status < Running){
        QThread::yieldCurrentThread();
    }
    return m_mainRef;
}

QStringList MainConnection::errors()
{
    QMutexLocker l(lock());
    return m_errors;
}

void MainConnection::clearErrors()
{
    QMutexLocker l(lock());
    m_errors.clear();
}

void MainConnection::appendError(const QStringList &s,bool failure)
{
    QList<ServiceBrowserPrivate *> browsersAtt;
    bool didFail;
    {
        QMutexLocker l(lock());
        m_errors.append(s);
        browsersAtt=m_browsers;
        m_failed= failure || m_failed;
        didFail=m_failed;
    }
    foreach (ServiceBrowserPrivate *b,browsersAtt)
        b->hadError(s,didFail);
}

bool MainConnection::isOk()
{
    return !m_failed;
}

// ----------------- ZConfLib impl -----------------

bool ZConfLib::tryStartDaemon()
{
    return false;
}

QString ZConfLib::name(){
    return QString::fromUtf8("ZeroConfLib@%1").arg(size_t(this),0,16);
}

1513
ZConfLib::ZConfLib(ZConfLib::Ptr f) : fallbackLib(f), m_isOk(true)
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
{ }

ZConfLib::~ZConfLib()
{ }

bool ZConfLib::isOk()
{
    return m_isOk;
}

1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
QString ZConfLib::errorMsg()
{
    return m_errorMsg;
}

void ZConfLib::setError(bool failure, const QString &eMsg)
{
    m_errorMsg = eMsg;
    m_isOk = !failure;
}

1535
1536
} // namespace Internal
} // namespace ZeroConf