Debian Codegraph @

interfaces/zeroconf/servicebrowser.cpp

raw symbols SCIP
1 /**************************************************************************
2 **
3 ** This file is part of Qt Creator
4 **
5 ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
6 **
7 ** Contact: Nokia Corporation ([email protected])
8 **
9 **
10 ** GNU Lesser General Public License Usage
11 **
12 ** This file may be used under the terms of the GNU Lesser General Public
13 ** License version 2.1 as published by the Free Software Foundation and
14 ** appearing in the file LICENSE.LGPL included in the packaging of this file.
15 ** Please review the following information to ensure the GNU Lesser General
16 ** Public License version 2.1 requirements will be met:
17 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
18 **
19 ** In addition, as a special exception, Nokia gives you certain additional
20 ** rights. These rights are described in the Nokia Qt LGPL Exception
21 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
22 **
23 ** Other Usage
24 **
25 ** Alternatively, this file may be used in accordance with the terms and
26 ** conditions contained in a signed written agreement between you and Nokia.
27 **
28 ** If you have questions regarding the use of this file, please contact
29 ** Nokia at [email protected].
30 **
31 **************************************************************************/
32
33 #ifdef Q_OS_WIN32
34 # include <Winsock2.h>
35 # ifndef SHUT_RDWR
36 # ifdef SD_BOTH
37 # define SHUT_RDWR SD_BOTH
38 # else
39 # define SHUT_RDWR 2
40 # endif
41 # endif
42 #else
43 # include <sys/socket.h>
44 #endif
45
46 #include "mdnsderived.h"
47 #include "servicebrowser_p.h"
48
49 #include <algorithm>
50 #include <errno.h>
51
52 #include <QtCore/QAtomicPointer>
53 #include <QtCore/QCoreApplication>
54 #include <QtCore/QGlobalStatic>
55 #include <QtCore/QMetaType>
56 #include <QtCore/QMutexLocker>
57 #include <QtCore/QString>
58 #include <QtCore/QStringList>
59 #include <QtCore/QtEndian>
60 #include <QtNetwork/QHostInfo>
61
62 /*!
63 \namespace ZeroConf
64
65 \brief namespace for zeroconf (Bonjour/DNS-SD) functionality, currently mostly for browsing services.
66 */
67
68 namespace { // anonymous namespace for free functions
69 // ----------------- free functions -----------------
70
71 using namespace ZeroConf;
72 using namespace ZeroConf::Internal;
73
74 QString toFullNameC(const char * const service, const char * const regtype, const char * const domain)
75 {
76 char fullName[kDNSServiceMaxDomainName];
77 myDNSServiceConstructFullName(fullName, service, regtype, domain);
78 fullName[kDNSServiceMaxDomainName - 1] = 0; // just to be sure
79 return QString::fromUtf8(fullName);
80 }
81
82 int fromFullNameC(const char * const fullName, QString &service, QString &regtype, QString &domain)
83 {
84 char fullNameDecoded[kDNSServiceMaxDomainName];
85 int encodedI = 0;
86 int decodedI = 0;
87 int oldPos[4];
88 int iPos = 0;
89 while (fullName[encodedI] != 0 && encodedI <kDNSServiceMaxDomainName){
90 char c = fullName[encodedI++];
91 if (c == '\\'){
92 c = fullName[++encodedI];
93 if (c == 0 || encodedI == kDNSServiceMaxDomainName)
94 return 1;
95 if (c >= '0' && c <= '9'){
96 int val = (c - '0') * 100;
97 c = fullName[++encodedI];
98 if (c < '0' || c > '9' || encodedI == kDNSServiceMaxDomainName)
99 return 2;
100 val += (c - '0') * 10;
101 c = fullName[++encodedI];
102 if (c < '0' || c > '9')
103 return 3;
104 val += (c - '0');
105 fullNameDecoded[decodedI++] = static_cast<char>(static_cast<unsigned char>(val));
106 } else {
107 fullNameDecoded[decodedI++] = c;
108 }
109 } else if (c == '.') {
110 if (iPos < 4) {
111 oldPos[iPos++] = decodedI;
112 }
113 fullNameDecoded[decodedI++] = c;
114 } else {
115 fullNameDecoded[decodedI++] = c;
116 }
117 }
118 if (iPos != 4) return 5;
119 service = QString::fromUtf8(&fullNameDecoded[0], oldPos[0]);
120 regtype = QString::fromUtf8(&fullNameDecoded[oldPos[0] + 1], oldPos[3] - oldPos[0] - 1);
121 domain = QString::fromUtf8(&fullNameDecoded[oldPos[3] + 1], decodedI - oldPos[3] - 1);
122 return 0;
123 }
124
125 /// singleton for lib setup
126 class ZeroConfLib
127 {
128 public:
129 ZeroConfLib();
130 ZConfLib *defaultLib();
131 void setDefaultLib(LibUsage usage, const QString &libName, const QString &daemonPath);
132
133 private:
134 QMutex m_lock;
135 ZConfLib *m_defaultLib;
136 };
137
138 Q_GLOBAL_STATIC(ZeroConfLib, zeroConfLibInstance)
139
140 ZeroConfLib::ZeroConfLib(): m_lock(QMutex::Recursive),
141 m_defaultLib(ZConfLib::createAvahiLib(QLatin1String("avahi-client"),
142 ZConfLib::createNativeLib(QLatin1String("dns_sd"),
143 ZConfLib::createEmbeddedLib(QString("mdnssd"), 0))))
144 {
145 qRegisterMetaType<Service::ConstPtr>("ZeroConf::Service::ConstPtr");
146 }
147
148 ZConfLib *ZeroConfLib::defaultLib(){
149 QMutexLocker l(&m_lock);
150 return m_defaultLib;
151 }
152
153 void ZeroConfLib::setDefaultLib(LibUsage usage, const QString &libName, const QString &daemonPath){ // leaks... should be ok, switch to shared pointers???
154 QMutexLocker l(&m_lock);
155 switch (usage){
156 case (UseNativeOnly):
157 m_defaultLib = ZConfLib::createNativeLib(libName, 0);
158 break;
159 case (UseEmbeddedOnly):
160 m_defaultLib = ZConfLib::createEmbeddedLib(daemonPath, 0);
161 break;
162 case (UseNativeOrEmbedded):
163 m_defaultLib = ZConfLib::createNativeLib(libName, ZConfLib::createEmbeddedLib(daemonPath, 0));
164 break;
165 default:
166 qDebug() << "invalid usage " << usage;
167 }
168 }
169
170 } // end anonymous namespace
171
172 namespace ZeroConf {
173
174 // ----------------- Service impl -----------------
175 /*!
176 \class ZeroConf::Service
177
178 \brief class representing a zeroconf service
179
180 Instances of this class are basically constant, but can be outdated. They are normally accessed through a Shared pointer.
181 This design avoids race conditions when used though multiple threads.
182
183 \threadsafe
184 */
185
186 Service::Service(const Service &o) :
187 m_name(o.m_name),
188 m_type(o.m_type),
189 m_domain(o.m_domain),
190 m_fullName(o.m_fullName),
191 m_port(o.m_port),
192 m_txtRecord(o.m_txtRecord),
193 m_host(o.m_host ? new QHostInfo(*o.m_host) : 0),
194 m_interfaceNr(o.m_interfaceNr),
195 m_outdated(o.m_outdated)
196 {
197 }
198
199 Service::Service() : m_host(0), m_interfaceNr(0), m_outdated(false)
200 { }
201
202 Service::~Service()
203 {
204 delete m_host;
205 }
206
207 QDebug operator<<(QDebug dbg, const Service &service)
208 {
209 dbg.maybeSpace() << "Service{ name:" << service.name() << ", "
210 << "type:" << service.type() << ", domain:" << service.domain() << ", "
211 << " fullName:" << service.fullName() << ", port:" << service.port()
212 << ", txtRecord:{";
213 bool first=true;
214 const ServiceTxtRecord &txtRecord = service.txtRecord();
215 foreach (const QString &k, txtRecord){
216 if (first)
217 first = false;
218 else
219 dbg << ", ";
220 dbg << k << ":" << txtRecord.value(k);
221 }
222 dbg << "}, ";
223 if (const QHostInfo *host = service.host()){
224 dbg << "host:{" << host->hostName() << ", addresses[";
225 first=true;
226 foreach (const QHostAddress &addr, host->addresses()){
227 if (first)
228 first = false;
229 else
230 dbg << ", ";
231 dbg << addr.toString();
232 }
233 dbg << "], },";
234 } else {
235 dbg << " host:*null*,";
236 }
237 dbg << " interfaceNr:" << service.interfaceNr() << ", outdated:" << service.outdated() << " }";
238 return dbg.space();
239 }
240 // inline methods
241 /*!
242 \fn bool Service::outdated() const
243
244 Returns if the service data is outdated, its value might change even on
245 the (otherwise constant) objects returned by a ServiceBrowser.
246 */
247 /*!
248 \fn QString Service::name() const
249
250 Returns the name of the service (non escaped).
251 */
252 /*!
253 \fn QString Service::type() const
254
255 Returns the name of the service type (non escaped).
256 */
257 /*!
258 \fn QString Service::domain() const
259
260 Returns the name of the domain (non escaped).
261 */
262 /*!
263 \fn QString Service::fullName() const
264
265 Returns the full name (service.type.domain) with each component correctly escaped.
266 */
267 /*!
268 \fn QString Service::port() const
269
270 Return the port of the service (as a string, not as number).
271 */
272 /*!
273 \fn const Service::ServiceTxtRecord &txtRecord() const
274
275 Returns the extra information on this service.
276 */
277 /*!
278 \fn const Service::QHostInfo *host() const
279
280 Returns the host through which this service is reachable.
281 */
282 /*!
283 \fn int Service::interfaceNr() const
284
285 returns the interface on which the service is reachable, 1 based, 0 means to try all interfaces
286 */
287 /*!
288 \fn bool Service::invalidate()
289
290 Marks this service as outdated.
291 */
292
293 // ----------------- ServiceBrowser impl -----------------
294 /*!
295 \class ZeroConf::ServiceBrowser
296
297 \brief class that browses (searches) for a given zeronconf service
298
299 The actual browsing starts only when startBrowsing() is called. If you want to receive all service
300 changes connect before starting browsing.
301
302 The current list of services can be gathered with the services() method.
303
304 \threadsafe
305 */
306
307 /// starts the browsing, return true if successfull
308 bool ServiceBrowser::startBrowsing(qint32 interfaceIndex)
309 {
310 return d->startBrowsing(interfaceIndex);
311 }
312
313 /// create a new brower for the given service type
314 ServiceBrowser::ServiceBrowser(const QString &serviceType, const QString &domain,
315 AddressesSetting addressesSetting, QObject *parent)
316 : QObject(parent),
317 d(new ServiceBrowserPrivate(serviceType, domain, addressesSetting == RequireAddresses,
318 MainConnectionPtr()))
319 {
320 d->q = this;
321 }
322
323 ServiceBrowser::ServiceBrowser(const MainConnectionPtr &mainConnection, const QString &serviceType,
324 const QString &domain, AddressesSetting addressesSetting, QObject *parent)
325 : QObject(parent),
326 d(new ServiceBrowserPrivate(serviceType, domain, addressesSetting == RequireAddresses,
327 mainConnection))
328 {
329 d->q = this;
330 }
331
332 ServiceBrowser::~ServiceBrowser()
333 {
334 delete d;
335 }
336
337 /// returns the main connection used by this ServiceBrowser
338 MainConnectionPtr ServiceBrowser::mainConnection() const
339 {
340 return d->mainConnection;
341 }
342
343 /// stops browsing, but does not delete all services found
344 void ServiceBrowser::stopBrowsing()
345 {
346 d->stopBrowsing();
347 }
348
349 /// if the service is currently active
350 bool ServiceBrowser::isBrowsing() const
351 {
352 return d->browsing;
353 }
354
355 /// type of the service browsed (non escaped)
356 const QString& ServiceBrowser::serviceType() const
357 {
358 return d->serviceType;
359 }
360
361 /// domain that is browser (non escaped)
362 const QString& ServiceBrowser::domain() const
363 {
364 return d->domain;
365 }
366
367 /// if addresses should be resolved automatically for each service found
368 bool ServiceBrowser::adressesAutoResolved() const
369 {
370 return d->autoResolveAddresses;
371 }
372
373 /// if addresses are required to add the service to the list of available services
374 bool ServiceBrowser::addressesRequired() const
375 {
376 return d->requireAddresses;
377 }
378
379 /// list of current services (by copy on purpose)
380 QList<Service::ConstPtr> ServiceBrowser::services() const
381 {
382 QMutexLocker l(d->mainConnection->lock());
383 return d->activeServices;
384 }
385
386 /// forces a full update of a service (call this after a failure to connect to the service)
387 /// this is an expensive call, use only when needed
388 void ServiceBrowser::reconfirmService(Service::ConstPtr service)
389 {
390 d->reconfirmService(service);
391 }
392
393 // signals
394 /*!
395 \fn void ServiceBrowser::serviceChanged(Service::ConstPtr oldService, Service::ConstPtr newService, ServiceBrowser *browser)
396
397 This signal is called when a service is added removed or changes.
398 Both oldService or newService might be null (covers both add and remove).
399 The services list might not be synchronized with respect to this signal.
400 */
401 /*!
402 \fn void ServiceBrowser::serviceAdded(Service::ConstPtr service, ServiceBrowser *browser)
403
404 This signal is called when a service is added (convenience method)
405 the services list might not be synchronized with respect to this signal
406
407 \sa serviceChanged()
408 */
409 /*!
410 \fn void ServiceBrowser::serviceRemoved(Service::ConstPtr service, ServiceBrowser *browser)
411
412 This signal is called when a service is removed (convenience method)
413 the services list might not be synchronized with respect to this signal
414
415 \sa serviceChanged()
416 */
417 /*!
418 \fn void ServiceBrowser::servicesUpdated(ServiceBrowser *browser)
419
420 This signal is called when the list is updated.
421 It might collect several serviceChanged signals together, if you use the list returned by services(),
422 use this signal, not serviceChanged(), serviceAdded() or serviceRemoved() to know about changes to the list.
423 */
424
425 // ----------------- library initialization impl -----------------
426 /*!
427 Intializes the library used for the mdns queries.
428 This changes the default library used by the next MainConnection, it does not change the already instantiated
429 connections.
430 \a usage can decide which libraries are tried,
431 \a libName should be the name (or path) to the libdns library,
432 \a daemonPath is the path to the daemon executable which should be started by the embedded library if no daemon
433 is found.
434
435 \threadsafe
436 */
437 void initLib(LibUsage usage, const QString &libName, const QString &daemonPath)
438 {
439 zeroConfLibInstance()->setDefaultLib(usage, libName, daemonPath);
440 }
441
442 namespace Internal {
443 // ----------------- dns-sd C callbacks -----------------
444
445 extern "C" void cServiceResolveReply(DNSServiceRef sdRef,
446 DNSServiceFlags flags,
447 uint32_t interfaceIndex,
448 DNSServiceErrorType errorCode,
449 const char *fullname,
450 const char *hosttarget,
451 uint16_t port, /* In network byte order */
452 uint16_t txtLen,
453 const unsigned char *txtRecord,
454 void *context)
455 {
456 if (DEBUG_ZEROCONF)
457 qDebug() << "cServiceResolveReply(" << ((size_t)sdRef) << ", " << ((quint32)flags) << ", " << interfaceIndex
458 << ", " << ((int)errorCode) << ", " << fullname << ", " << hosttarget << ", " << qFromBigEndian(port) << ", "
459 << txtLen << ", '" << QString::fromUtf8((const char *)txtRecord, txtLen) << "', " << ((size_t)context);
460 ServiceGatherer *ctxGatherer = reinterpret_cast<ServiceGatherer *>(context);
461 if (ctxGatherer){
462 if (ctxGatherer->currentService->fullName() != fullname){
463 qDebug() << "ServiceBrowser " << ctxGatherer->serviceBrowser->serviceType << " for service "
464 << ctxGatherer->currentService->name() << " ignoring resolve reply for " << fullname << " vs. " << ctxGatherer->currentService->fullName();
465 return;
466 }
467 ctxGatherer->serviceResolveReply(flags, interfaceIndex, errorCode, hosttarget, QString::number(qFromBigEndian(port)),
468 txtLen, txtRecord);
469 }
470 }
471
472 extern "C" void cTxtRecordReply(DNSServiceRef sdRef,
473 DNSServiceFlags flags,
474 uint32_t interfaceIndex,
475 DNSServiceErrorType errorCode,
476 const char *fullname,
477 uint16_t rrtype,
478 uint16_t rrclass,
479 uint16_t rdlen,
480 const void *rdata,
481 uint32_t ttl,
482 void *context)
483 {
484 if (DEBUG_ZEROCONF)
485 qDebug() << "cTxtRecordReply(" << ((size_t)sdRef) << ", " << ((int)flags) << ", " << interfaceIndex
486 << ", " << ((int)errorCode) << ", " << fullname << ", " << rrtype << ", " << rrclass << ", "
487 << ", " << rdlen << QString::fromUtf8((const char *)rdata, rdlen) << "', " << ttl << ", " << ((size_t)context);
488 ServiceGatherer *ctxGatherer = reinterpret_cast<ServiceGatherer *>(context);
489 if (ctxGatherer){
490 if (rrtype != kDNSServiceType_TXT || rrclass != kDNSServiceClass_IN) {
491 qDebug() << "ServiceBrowser " << ctxGatherer->serviceBrowser->serviceType << " for service "
492 << ctxGatherer->currentService->fullName() << " received an unexpected rrtype/class:" << rrtype << "/" << rrclass;
493 }
494 ctxGatherer->txtRecordReply(flags, errorCode, rdlen, rdata, ttl);
495 }
496 }
497
498 extern "C" void cAddrReply(DNSServiceRef sdRef,
499 DNSServiceFlags flags,
500 uint32_t interfaceIndex,
501 DNSServiceErrorType errorCode,
502 const char *hostname,
503 const struct sockaddr *address,
504 uint32_t ttl,
505 void *context)
506 {
507 if (DEBUG_ZEROCONF)
508 qDebug() << "cAddrReply(" << ((size_t)sdRef) << ", " << ((int)flags) << ", " << interfaceIndex
509 << ", " << ((int)errorCode) << ", " << hostname << ", " << QHostAddress(address).toString() << ", " << ttl << ", "
510 << ((size_t)context);
511 ServiceGatherer *ctxGatherer = reinterpret_cast<ServiceGatherer *>(context);
512 if (ctxGatherer){
513 ctxGatherer->addrReply(flags, errorCode, hostname, address, ttl);
514 }
515 }
516
517 /// callback for service browsing
518 extern "C" void cBrowseReply(DNSServiceRef sdRef,
519 DNSServiceFlags flags,
520 uint32_t interfaceIndex,
521 DNSServiceErrorType errorCode,
522 const char *serviceName,
523 const char *regtype,
524 const char *replyDomain,
525 void *context)
526 {
527 if (DEBUG_ZEROCONF)
528 qDebug() << "cBrowseReply(" << ((size_t)sdRef) << ", " << flags << ", " << interfaceIndex
529 << ", " << ((int)errorCode) << ", " << serviceName << ", " << regtype << ", " << replyDomain << ", "
530 << ((size_t)context);
531 ServiceBrowserPrivate *sb = (ServiceBrowserPrivate *)(context);
532 if (sb == 0){
533 qDebug() << "ServiceBrowser ignoring reply because context was null ";
534 return;
535 }
536 sb->browseReply(flags, interfaceIndex, errorCode, serviceName, regtype, replyDomain);
537 }
538
539 // ----------------- ConnectionThread impl -----------------
540
541 void ConnectionThread::run()
542 {
543 connection.handleEvents();
544 }
545
546 ConnectionThread::ConnectionThread(MainConnection &mc, QObject *parent):
547 QThread(parent), connection(mc)
548 { }
549
550 // ----------------- ServiceGatherer impl -----------------
551
552 ZConfLib *ServiceGatherer::lib()
553 {
554 return serviceBrowser->mainConnection->lib;
555 }
556
557 QString ServiceGatherer::fullName(){
558 return currentService->fullName();
559 }
560
561 void ServiceGatherer::enactServiceChange()
562 {
563 if (DEBUG_ZEROCONF)
564 qDebug() << "ServiceGatherer::enactServiceChange() for service " << currentService->fullName();
565 if (currentServiceCanBePublished()) {
566 Service::Ptr nService = Service::Ptr(currentService);
567 serviceBrowser->serviceChanged(publishedService, nService, serviceBrowser->q);
568 if (publishedService) {
569 serviceBrowser->nextActiveServices.removeOne(publishedService);
570 serviceBrowser->serviceRemoved(publishedService, serviceBrowser->q);
571 }
572 publishedService = nService;
573 if (nService) {
574 serviceBrowser->nextActiveServices.append(nService);
575 serviceBrowser->serviceAdded(nService, serviceBrowser->q);
576 currentService = new Service(*currentService);
577 }
578 }
579 }
580
581 void ServiceGatherer::retireService()
582 {
583 if (publishedService) {
584 Service::Ptr nService;
585 serviceBrowser->nextActiveServices.removeOne(publishedService);
586 serviceBrowser->serviceChanged(publishedService, nService, serviceBrowser->q);
587 serviceBrowser->serviceRemoved(publishedService, serviceBrowser->q);
588 publishedService = nService;
589 }
590 }
591
592 void ServiceGatherer::stopResolve()
593 {
594 if ((status & ResolveConnectionActive) == 0) return;
595 lib()->refDeallocate(resolveConnection);
596 status &= ~ResolveConnectionActive;
597 serviceBrowser->updateFlowStatusForCancel();
598 }
599
600 void ServiceGatherer::restartResolve()
601 {
602 stopResolve();
603 DNSServiceErrorType err = lib()->resolve(
604 serviceBrowser->mainRef(),
605 &resolveConnection,
606 currentService->interfaceNr(), currentService->name().toUtf8().constData(),
607 currentService->type().toUtf8().constData(), currentService->domain().toUtf8().constData(), this);
608 if (err != kDNSServiceErr_NoError) {
609 qDebug() << "ServiceBrowser " << serviceBrowser->serviceType << " failed discovery of service " << currentService->fullName()
610 << " due to error " << err;
611 status = status | ResolveConnectionFailed;
612 } else {
613 status = ((status & ~ResolveConnectionFailed) | ResolveConnectionActive);
614 }
615 }
616
617 void ServiceGatherer::stopTxt()
618 {
619 if ((status & TxtConnectionActive) == 0) return;
620 lib()->refDeallocate(txtConnection);
621 status &= ~TxtConnectionActive;
622 serviceBrowser->updateFlowStatusForCancel();
623 }
624
625 void ServiceGatherer::restartTxt()
626 {
627 stopTxt();
628 DNSServiceErrorType err = lib()->queryRecord(serviceBrowser->mainRef(), &txtConnection,
629 currentService->interfaceNr(), currentService->fullName().toUtf8().constData(), this);
630
631 if (err != kDNSServiceErr_NoError) {
632 qDebug() << "ServiceBrowser " << serviceBrowser->serviceType << " failed query of TXT record of service " << currentService->fullName()
633 << " due to error " << err;
634 status = status | TxtConnectionFailed;
635 } else {
636 status = ((status & ~TxtConnectionFailed) | TxtConnectionActive);
637 }
638 }
639
640 void ServiceGatherer::stopHostResolution()
641 {
642 if ((status & AddrConnectionActive) == 0) return;
643 lib()->refDeallocate(addrConnection);
644 status &= ~AddrConnectionActive;
645 serviceBrowser->updateFlowStatusForCancel();
646 }
647
648 void ServiceGatherer::restartHostResolution()
649 {
650 stopHostResolution();
651 if (DEBUG_ZEROCONF)
652 qDebug() << "ServiceGatherer::restartHostResolution for host " << hostName << " service " << currentService->fullName();
653 if (hostName.isEmpty()){
654 qDebug() << "ServiceBrowser " << serviceBrowser->serviceType << " cannot start host resolution without hostname for service "
655 << currentService->fullName();
656 }
657 DNSServiceErrorType err = lib()->getAddrInfo(serviceBrowser->mainRef(), &addrConnection,
658 currentService->interfaceNr(), 0 /* kDNSServiceProtocol_IPv4 | kDNSServiceProtocol_IPv6 */,
659 hostName.toUtf8().constData(), this);
660
661 if (err != kDNSServiceErr_NoError) {
662 qDebug() << "ServiceBrowser " << serviceBrowser->serviceType << " failed starting resolution of host "
663 << hostName << " for service " << currentService->fullName() << " due to error " << err;
664 status = status | AddrConnectionFailed;
665 } else {
666 status = ((status & ~AddrConnectionFailed) | AddrConnectionActive);
667 }
668 }
669
670 /// if the current service can be added
671 bool ServiceGatherer::currentServiceCanBePublished()
672 {
673 return (currentService->host() && !currentService->host()->addresses().isEmpty()) || !serviceBrowser->requireAddresses;
674 }
675
676 ServiceGatherer::ServiceGatherer(const QString &newServiceName, const QString &newType, const QString &newDomain,
677 const QString &fullName, uint32_t interfaceIndex, ServiceBrowserPrivate *serviceBrowser):
678 serviceBrowser(serviceBrowser), publishedService(0), currentService(new Service()), status(0)
679 {
680 if (DEBUG_ZEROCONF)
681 qDebug() << " creating ServiceGatherer(" << newServiceName << ", " << newType << ", " << newDomain << ", "
682 << fullName << ", " << interfaceIndex << ", " << ((size_t) serviceBrowser);
683 currentService->m_name = newServiceName;
684 currentService->m_type = newType;
685 currentService->m_domain = newDomain;
686 currentService->m_fullName = fullName;
687 currentService->m_interfaceNr = interfaceIndex;
688 if (fullName.isEmpty())
689 currentService->m_fullName = toFullNameC(currentService->name().toUtf8().data(), currentService->type().toUtf8().data(), currentService->domain().toUtf8().data());
690 restartResolve();
691 restartTxt();
692 }
693
694 ServiceGatherer::~ServiceGatherer()
695 {
696 stopHostResolution();
697 stopResolve();
698 stopTxt();
699 delete currentService;
700 }
701
702 ServiceGatherer::Ptr ServiceGatherer::createGatherer(const QString &newServiceName, const QString &newType,
703 const QString &newDomain, const QString &fullName,
704 uint32_t interfaceIndex, ServiceBrowserPrivate *serviceBrowser)
705 {
706 Ptr res(new ServiceGatherer(newServiceName, newType, newDomain, fullName, interfaceIndex, serviceBrowser));
707 res->self = res.toWeakRef();
708 return res;
709 }
710
711 ServiceGatherer::Ptr ServiceGatherer::gatherer() {
712 return self.toStrongRef();
713 }
714
715 void ServiceGatherer::serviceResolveReply(DNSServiceFlags flags,
716 uint32_t interfaceIndex,
717 DNSServiceErrorType errorCode,
718 const char *hosttarget,
719 const QString &port,
720 uint16_t txtLen,
721 const unsigned char *rawTxtRecord)
722 {
723 if (errorCode != kDNSServiceErr_NoError){
724 if (errorCode == kDNSServiceErr_Timeout){
725 if ((status & ResolveConnectionSuccess) == 0){
726 qDebug() << "ServiceBrowser " << serviceBrowser->serviceType << " failed service resolution for service "
727 << currentService->fullName() << " as it did timeout";
728 status |= ResolveConnectionFailed;
729 }
730 } else {
731 qDebug() << "ServiceBrowser " << serviceBrowser->serviceType << " failed service resolution for service "
732 << currentService->fullName() << " with error " << errorCode;
733 status |= ResolveConnectionFailed;
734 }
735 if (status & ResolveConnectionActive) {
736 status &= ~ResolveConnectionActive;
737 lib()->refDeallocate(resolveConnection);
738 serviceBrowser->updateFlowStatusForCancel();
739 }
740 return;
741 }
742 if (publishedService) publishedService->invalidate(); // delay this to enactServiceChange?
743 serviceBrowser->updateFlowStatusForFlags(flags);
744
745 uint16_t nKeys = txtRecordGetCount(txtLen, rawTxtRecord);
746 for (uint16_t i = 0; i < nKeys; ++i){
747 enum { maxTxtLen= 256 };
748 char keyBuf[maxTxtLen];
749 uint8_t valLen;
750 const char *valueCStr;
751 DNSServiceErrorType txtErr = txtRecordGetItemAtIndex(txtLen, rawTxtRecord, i, maxTxtLen,
752 keyBuf, &valLen, (const void **)&valueCStr);
753 if (txtErr != kDNSServiceErr_NoError){
754 qDebug() << "ServiceBrowser " << serviceBrowser->serviceType << " error " << txtErr
755 << " decoding txt record of service " << currentService->fullName();
756 break;
757 }
758 keyBuf[maxTxtLen-1] = 0; // just to be sure
759 if (flags & kDNSServiceFlagsAdd) {
760 txtRecord[QString::fromUtf8(keyBuf)] = QString::fromUtf8(valueCStr, valLen);
761 } else {
762 txtRecord.remove(QString::fromUtf8(keyBuf)); // check value???
763 }
764 }
765 currentService->m_interfaceNr = interfaceIndex;
766 currentService->m_port = port;
767 if (hostName != hosttarget) {
768 hostName = QString::fromUtf8(hosttarget);
769 if (!currentService->host())
770 currentService->m_host = new QHostInfo();
771 else
772 currentService->m_host->setAddresses(QList<QHostAddress>());
773 currentService->m_host->setHostName(hostName);
774 if (serviceBrowser->autoResolveAddresses){
775 restartHostResolution();
776 }
777 }
778 if (currentServiceCanBePublished())
779 serviceBrowser->pendingGathererAdd(gatherer());
780 }
781
782 void ServiceGatherer::txtRecordReply(DNSServiceFlags flags,
783 DNSServiceErrorType errorCode,
784 uint16_t txtLen,
785 const void *rawTxtRecord,
786 uint32_t /*ttl*/)
787 {
788 if (errorCode != kDNSServiceErr_NoError){
789 if (errorCode == kDNSServiceErr_Timeout){
790 if ((status & TxtConnectionSuccess) == 0){
791 qDebug() << "ServiceBrowser " << serviceBrowser->serviceType << " failed txt gathering for service "
792 << currentService->fullName() << " as it did timeout";
793 status |= TxtConnectionFailed;
794 }
795 } else {
796 qDebug() << "ServiceBrowser " << serviceBrowser->serviceType << " failed txt gathering for service "
797 << currentService->fullName() << " with error " << errorCode;
798 status |= TxtConnectionFailed;
799 }
800 if (status & TxtConnectionActive) {
801 status &= ~TxtConnectionActive;
802 lib()->refDeallocate(txtConnection);
803 serviceBrowser->updateFlowStatusForCancel();
804 }
805 return;
806 }
807 serviceBrowser->updateFlowStatusForFlags(flags);
808
809 uint16_t nKeys = txtRecordGetCount(txtLen, rawTxtRecord);
810 for (uint16_t i = 0; i < nKeys; ++i){
811 char keyBuf[256];
812 uint8_t valLen;
813 const char *valueCStr;
814 DNSServiceErrorType txtErr = txtRecordGetItemAtIndex(txtLen, rawTxtRecord, i, 256, keyBuf, &valLen, (const void **)&valueCStr);
815 if (txtErr != kDNSServiceErr_NoError){
816 qDebug() << "ServiceBrowser " << serviceBrowser->serviceType << " error " << txtErr
817 << " decoding txt record of service " << currentService->fullName();
818 if ((flags & kDNSServiceFlagsAdd) == 0)
819 txtRecord.clear();
820 break;
821 }
822 keyBuf[255] = 0; // just to be sure
823 if (flags & kDNSServiceFlagsAdd) {
824 txtRecord[QString::fromUtf8(keyBuf)] = QString::fromUtf8(valueCStr, valLen);
825 } else {
826 txtRecord.remove(QString::fromUtf8(keyBuf)); // check value???
827 }
828 }
829 if ((flags & kDNSServiceFlagsAdd) != 0) {
830 status |= TxtConnectionSuccess;
831 }
832 if (txtRecord.count() != 0 && currentServiceCanBePublished())
833 serviceBrowser->pendingGathererAdd(gatherer());
834 }
835
836 void ServiceGatherer::addrReply(DNSServiceFlags flags,
837 DNSServiceErrorType errorCode,
838 const char *hostname,
839 const struct sockaddr *address,
840 uint32_t /*ttl*/) // should we use this???
841 {
842 if (errorCode != kDNSServiceErr_NoError){
843 if (errorCode == kDNSServiceErr_Timeout){
844 if ((status & AddrConnectionSuccess) == 0){
845 qDebug() << "ServiceBrowser " << serviceBrowser->serviceType << " failed address resolve for service "
846 << currentService->fullName() << " as it did timeout";
847 status |= AddrConnectionFailed;
848 }
849 qDebug() << "ServiceBrowser " << serviceBrowser->serviceType << " failed addr resolve for service "
850 << currentService->fullName() << " with error " << errorCode;
851 status |= AddrConnectionFailed;
852 }
853 if (status & AddrConnectionActive){
854 status &= ~AddrConnectionActive;
855 lib()->refDeallocate(addrConnection);
856 serviceBrowser->updateFlowStatusForCancel();
857 }
858 return;
859 }
860 serviceBrowser->updateFlowStatusForFlags(flags);
861 if (!currentService->host())
862 currentService->m_host=new QHostInfo();
863 if (currentService->host()->hostName() != hostname) {
864 if ((flags & kDNSServiceFlagsAdd) == 1)
865 currentService->m_host->setHostName(QString::fromUtf8(hostname));
866 if (currentService->host()->addresses().isEmpty()) {
867 qDebug() << "ServiceBrowser " << serviceBrowser->serviceType << " for service "
868 << currentService->fullName() << " add with name " << hostname << " while old name "
869 << currentService->host()->hostName() << " has still adresses, removing them";
870 currentService->m_host->setAddresses(QList<QHostAddress>());
871 }
872 else{
873 qDebug() << "ServiceBrowser " << serviceBrowser->serviceType << " for service "
874 << currentService->fullName() << " ignoring remove for " << hostname << " as current hostname is "
875 << currentService->host()->hostName();
876 return;
877 }
878 }
879 QHostAddress newAddr(address);
880 QList<QHostAddress> addrNow = currentService->host()->addresses();
881 if ((flags & kDNSServiceFlagsAdd) == 0) {
882 if (addrNow.removeOne(newAddr))
883 currentService->m_host->setAddresses(addrNow);
884 } else {
885 if (!addrNow.contains(newAddr)){
886 addrNow.append(newAddr);
887 currentService->m_host->setAddresses(addrNow);
888 }
889 }
890 serviceBrowser->pendingGathererAdd(gatherer());
891 }
892
893 void ServiceGatherer::maybeRemove()
894 {
895 // could trigger an update, but for now we just ignore it (less chatty)
896 }
897
898 void ServiceGatherer::stop()
899 {
900 if (status & ResolveConnectionActive){
901 status &= ~ResolveConnectionActive;
902 lib()->refDeallocate(resolveConnection);
903 serviceBrowser->updateFlowStatusForCancel();
904 }
905 if (status & TxtConnectionActive){
906 status &= ~TxtConnectionActive;
907 lib()->refDeallocate(txtConnection);
908 serviceBrowser->updateFlowStatusForCancel();
909 }
910 if (status & AddrConnectionActive) {
911 status &= ~AddrConnectionActive;
912 lib()->refDeallocate(addrConnection);
913 serviceBrowser->updateFlowStatusForCancel();
914 }
915 }
916
917 void ServiceGatherer::reload(qint32 interfaceIndex)
918 {
919 this->interfaceIndex = interfaceIndex;
920 stop();
921 restartResolve();
922 restartTxt();
923 if (currentServiceCanBePublished()) // avoid???
924 restartHostResolution();
925 }
926
927 void ServiceGatherer::remove()
928 {
929 stop();
930 if (serviceBrowser->gatherers.contains(currentService->fullName()) && serviceBrowser->gatherers[currentService->fullName()] == this)
931 serviceBrowser->gatherers.remove(currentService->fullName());
932 }
933 /// forces a full reload of the record
934 void ServiceGatherer::reconfirm()
935 {
936 stop();
937 /* DNSServiceErrorType err = DNSServiceReconfirmRecord(kDNSServiceFlagsShareConnection,
938 interfaceIndex, fullName.toUtf8().constData(),
939 kDNSServiceType_PTR, // kDNSServiceType_SRV could be another possibility
940 kDNSServiceClass_IN //,
941 // uint16_t rdlen, // not cached... what is the best solution???
942 // const void *rdata
943 ); */
944 }
945
946 // ----------------- ServiceBrowserPrivate impl -----------------
947
948 ZConfLib::ConnectionRef ServiceBrowserPrivate::mainRef()
949 {
950 return mainConnection->mainRef();
951 }
952
953 void ServiceBrowserPrivate::updateFlowStatusForCancel()
954 {
955 mainConnection->updateFlowStatusForCancel();
956 }
957
958 void ServiceBrowserPrivate::updateFlowStatusForFlags(DNSServiceFlags flags)
959 {
960 mainConnection->updateFlowStatusForFlags(flags);
961 }
962
963 void ServiceBrowserPrivate::pendingGathererAdd(ServiceGatherer::Ptr gatherer)
964 {
965 int ng = pendingGatherers.count();
966 for (int i = 0; i < ng; ++i){
967 const ServiceGatherer::Ptr &g=pendingGatherers.at(i);
968 if (g->fullName() == gatherer->fullName()){
969 if (g != gatherer){
970 gatherer->publishedService = g->publishedService;
971 pendingGatherers[i] = gatherer;
972 }
973 return;
974 }
975 }
976 pendingGatherers.append(gatherer);
977 }
978
979 ServiceBrowserPrivate::ServiceBrowserPrivate(const QString &serviceType, const QString &domain, bool requireAddresses, MainConnectionPtr mconn):
980 q(0), serviceType(serviceType), domain(domain), mainConnection(mconn), serviceConnection(0), flags(0), interfaceIndex(0),
981 failed(false), browsing(false), autoResolveAddresses(requireAddresses), requireAddresses(requireAddresses)
982 {
983 }
984
985 ServiceBrowserPrivate::~ServiceBrowserPrivate()
986 {
987 qDebug() << "destroying ServiceBrowserPrivate " << serviceType;
988 if (browsing){
989 stopBrowsing();
990 }
991 if (mainConnection){
992 mainConnection->removeBrowser(this);
993 }
994 }
995
996 void ServiceBrowserPrivate::insertGatherer(const QString &fullName)
997 {
998 if (!gatherers.contains(fullName)){
999 QString newServiceName, newType, newDomain;
1000 if (fromFullNameC(fullName.toUtf8().data(), *&newServiceName, *&newType, *&newDomain)){
1001 qDebug() << "Error unescaping fullname " << fullName;
1002 } else {
1003 ServiceGatherer::Ptr serviceGatherer = ServiceGatherer::createGatherer(newServiceName, newType, newDomain, fullName, 0, this);
1004 gatherers[fullName] = serviceGatherer;
1005 }
1006 }
1007 }
1008
1009 void ServiceBrowserPrivate::maybeUpdateLists()
1010 {
1011 if (mainConnection->flowStatus != MainConnection::MoreComingRFS || pendingGatherers.count() > 50) {
1012 QList<QString>::iterator i = knownServices.begin(), endi = knownServices.end();
1013 QMap<QString, ServiceGatherer::Ptr>::iterator j = gatherers.begin();
1014 while (i != endi && j != gatherers.end()) {
1015 const QString vi = *i;
1016 QString vj = (*j)->fullName();
1017 if (vi == vj){
1018 ++i;
1019 ++j;
1020 } else if (vi < vj) {
1021 qDebug() << "ServiceBrowser " << serviceType << ", missing gatherer for " << vi;
1022 insertGatherer(vi);
1023 ++i;
1024 } else {
1025 (*j)->retireService();
1026 j = gatherers.erase(j);
1027 }
1028 }
1029 while (i != endi) {
1030 qDebug() << "ServiceBrowser " << serviceType << ", missing gatherer for " << *i;
1031 insertGatherer(*i);
1032 }
1033 while (j != gatherers.end()) {
1034 (*j)->retireService();
1035 j = gatherers.erase(j);
1036 }
1037 foreach (const ServiceGatherer::Ptr &g, pendingGatherers)
1038 g->enactServiceChange();
1039 {
1040 QMutexLocker l(mainConnection->lock());
1041 activeServices=nextActiveServices;
1042 }
1043 emit q->servicesUpdated(q);
1044 }
1045 }
1046
1047 /// callback announcing
1048 void ServiceBrowserPrivate::browseReply(DNSServiceFlags flags,
1049 uint32_t interfaceIndex,
1050 DNSServiceErrorType errorCode,
1051 const char *serviceName,
1052 const char *regtype,
1053 const char *replyDomain)
1054 {
1055 if (DEBUG_ZEROCONF)
1056 qDebug() << "browseReply(" << ((int)flags) << ", " << interfaceIndex << ", " << ((int)errorCode) << ", " << serviceName << ", "
1057 << regtype << ", " << replyDomain << ")";
1058 if (errorCode != kDNSServiceErr_NoError){
1059 qDebug() << "ServiceBrowser " << serviceType << " ignoring reply due to error " << errorCode;
1060 return;
1061 }
1062 QString newServiceName = QString::fromUtf8(serviceName);
1063 QString newType = serviceType;
1064 QString newDomain = domain;
1065 if (serviceType != regtype) // discard? should not happen...
1066 newType = QString::fromUtf8(regtype);
1067 if (domain != replyDomain)
1068 domain = QString::fromUtf8(replyDomain);
1069 QString fullName = toFullNameC(serviceName, regtype, replyDomain);
1070 updateFlowStatusForFlags(flags);
1071 if (flags & kDNSServiceFlagsAdd){
1072 ServiceGatherer::Ptr serviceGatherer;
1073 if (!gatherers.contains(fullName)){
1074 serviceGatherer = ServiceGatherer::createGatherer(newServiceName, newType, newDomain, fullName, interfaceIndex, this);
1075 gatherers[fullName] = serviceGatherer;
1076 } else {
1077 serviceGatherer = gatherers[fullName];
1078 serviceGatherer->reload(interfaceIndex);
1079 }
1080 QList<QString>::iterator pos = std::lower_bound(knownServices.begin(), knownServices.end(), fullName);
1081 // could order later (more efficient, but then we have to handle eventual duplicates)
1082 if (pos == knownServices.end() || *pos != fullName)
1083 knownServices.insert(pos, fullName);
1084 } else {
1085 if (gatherers.contains(fullName)){
1086 gatherers[fullName]->maybeRemove();
1087 }
1088 knownServices.removeOne(fullName);
1089 }
1090 maybeUpdateLists();
1091 }
1092
1093 bool ServiceBrowserPrivate::startBrowsing(quint32 interfaceIndex)
1094 {
1095 if (failed || browsing) return false;
1096 if (mainConnection.isNull())
1097 mainConnection = MainConnectionPtr(new MainConnection());
1098 mainConnection->addBrowser(this);
1099 DNSServiceErrorType err;
1100 err = mainConnection->lib->browse(mainRef(), &serviceConnection, interfaceIndex,
1101 serviceType.toUtf8().constData(), ((domain.isEmpty()) ? 0 : (domain.toUtf8().constData())), this);
1102 if (err != kDNSServiceErr_NoError){
1103 qDebug() << "ServiceBrowser " << serviceType << " failed initializing serviceConnection";
1104 return false;
1105 }
1106 browsing = true;
1107 if (DEBUG_ZEROCONF)
1108 qDebug() << "startBrowsing(" << interfaceIndex << ") for serviceType:" << serviceType << " domain:" << domain;
1109 return true;
1110 }
1111
1112 void ServiceBrowserPrivate::stopBrowsing()
1113 {
1114 QMutexLocker l(mainConnection->lock());
1115 if (browsing){
1116 if (serviceConnection) {
1117 mainConnection->lib->browserDeallocate(&serviceConnection);
1118 updateFlowStatusForCancel();
1119 serviceConnection=0;
1120 }
1121 }
1122 }
1123
1124 void ServiceBrowserPrivate::reconfirmService(Service::ConstPtr s)
1125 {
1126 if (!s->outdated())
1127 mainConnection->lib->reconfirmRecord(mainRef(), s->interfaceNr(), s->name().toUtf8().data(), s->type().toUtf8().data(),
1128 s->domain().toUtf8().data(), s->fullName().toUtf8().data());
1129 }
1130
1131 /// called when a service is added removed or changes. oldService or newService might be null (covers both add and remove)
1132 void ServiceBrowserPrivate::serviceChanged(const Service::ConstPtr &oldService, const Service::ConstPtr &newService, ServiceBrowser *browser)
1133 {
1134 emit q->serviceChanged(oldService, newService, browser);
1135 }
1136
1137 /// called when a service is added (utility method)
1138 void ServiceBrowserPrivate::serviceAdded(const Service::ConstPtr &service, ServiceBrowser *browser)
1139 {
1140 emit q->serviceAdded(service, browser);
1141 }
1142
1143 /// called when a service is removed (utility method)
1144 void ServiceBrowserPrivate::serviceRemoved(const Service::ConstPtr &service, ServiceBrowser *browser)
1145 {
1146 emit q->serviceRemoved(service, browser);
1147 }
1148
1149 /// called when the list is updated (this might collect several serviceChanged signals together)
1150 void ServiceBrowserPrivate::servicesUpdated(ServiceBrowser *browser)
1151 {
1152 emit q->servicesUpdated(browser);
1153 }
1154
1155 /// called when there is an error
1156 void ServiceBrowserPrivate::hadError(QStringList errorMsgs, bool completeFailure)
1157 {
1158 if (completeFailure)
1159 this->failed=true;
1160 emit q->hadError(errorMsgs,completeFailure);
1161 }
1162
1163 // ----------------- MainConnection impl -----------------
1164
1165 void MainConnection::stop(bool wait)
1166 {
1167 if (m_status < Stopping)
1168 increaseStatusTo(Stopping);
1169 if (m_mainRef)
1170 lib->stopConnection(m_mainRef);
1171 if (!m_thread)
1172 increaseStatusTo(Stopped);
1173 else if (wait && QThread::currentThread() != m_thread)
1174 m_thread->wait();
1175 }
1176
1177 MainConnection::MainConnection():
1178 lib(zeroConfLibInstance()->defaultLib()), m_lock(QMutex::Recursive), m_mainRef(0), m_failed(false), m_status(Starting), m_nErrs(0)
1179 {
1180 if (lib == 0){
1181 qDebug() << "could not load a valid library for ZeroConf::MainConnection, failing";
1182 } else {
1183 m_thread = new ConnectionThread(*this);
1184 m_thread->start(); // delay startup??
1185 }
1186 }
1187
1188 MainConnection::~MainConnection()
1189 {
1190 stop();
1191 delete m_thread;
1192 // to do
1193 }
1194
1195 bool MainConnection::increaseStatusTo(int s)
1196 {
1197 int sAtt = m_status;
1198 while (sAtt < s){
1199 if (m_status.testAndSetRelaxed(sAtt, s))
1200 return true;
1201 sAtt = m_status;
1202 }
1203 return false;
1204 }
1205
1206 QMutex *MainConnection::lock()
1207 {
1208 return &m_lock;
1209 }
1210
1211 void MainConnection::waitStartup()
1212 {
1213 int sAtt;
1214 while (true){
1215 {
1216 QMutexLocker l(lock());
1217 sAtt = m_status;
1218 if (sAtt >= Running)
1219 return;
1220 }
1221 QThread::yieldCurrentThread();
1222 }
1223 }
1224
1225 void MainConnection::addBrowser(ServiceBrowserPrivate *browser)
1226 {
1227 waitStartup();
1228 QStringList errs;
1229 bool didFail;
1230 {
1231 QMutexLocker l(lock());
1232 m_browsers.append(browser);
1233 errs=m_errors;
1234 didFail=m_failed;
1235 }
1236 if (didFail || !errs.isEmpty())
1237 browser->hadError(errs, didFail);
1238 }
1239
1240 void MainConnection::removeBrowser(ServiceBrowserPrivate *browser)
1241 {
1242 QMutexLocker l(lock());
1243 m_browsers.removeOne(browser);
1244 }
1245
1246 void MainConnection::updateFlowStatusForCancel(){
1247 flowStatus = ForceUpdateRFS;
1248 }
1249 void MainConnection::updateFlowStatusForFlags(DNSServiceFlags flags)
1250 {
1251 if (flags & kDNSServiceFlagsMoreComing) {
1252 if (flowStatus == NormalRFS)
1253 flowStatus = MoreComingRFS;
1254 } else {
1255 flowStatus = NormalRFS;
1256 }
1257 }
1258 void MainConnection::maybeUpdateLists()
1259 {
1260 foreach (ServiceBrowserPrivate *sb, m_browsers) {
1261 sb->maybeUpdateLists();
1262 }
1263 }
1264
1265 void MainConnection::gotoValidLib(){
1266 while (lib){
1267 if (lib->isOk()) break;
1268 appendError(QStringList(tr("MainConnection giving up on non Ok lib %1 (%2)")
1269 .arg(lib->name()).arg(lib->errorMsg())), false);
1270 lib = lib->fallbackLib;
1271 }
1272 if (!lib) {
1273 appendError(QStringList(tr("MainConnection has no valid library, aborting connection")
1274 .arg(lib->name())), true);
1275 increaseStatusTo(Stopping);
1276 }
1277 }
1278
1279 void MainConnection::abortLib(){
1280 if (!lib){
1281 appendError(QStringList(tr("MainConnection has no valid library, aborting connection")
1282 .arg(lib->name())), true);
1283 increaseStatusTo(Stopping);
1284 } else if (lib->fallbackLib){
1285 appendError(QStringList(tr("MainConnection giving up on lib %1, switching to lib %2")
1286 .arg(lib->name()).arg(lib->fallbackLib->name())), false);
1287 lib=lib->fallbackLib;
1288 m_nErrs=0;
1289 gotoValidLib();
1290 } else {
1291 appendError(QStringList(tr("MainConnection giving up on lib %1, no fallback provided, aborting connection")
1292 .arg(lib->name())), true);
1293 increaseStatusTo(Stopping);
1294 }
1295 }
1296
1297 void MainConnection::createConnection()
1298 {
1299 gotoValidLib();
1300 while (m_status <= Running) {
1301 if (!lib) {
1302 increaseStatusTo(Stopped);
1303 break;
1304 }
1305 uint32_t version;
1306 uint32_t size=(uint32_t)sizeof(uint32_t);
1307 DNSServiceErrorType err=lib->getProperty(kDNSServiceProperty_DaemonVersion, &version, &size);
1308 if (err == kDNSServiceErr_NoError){
1309 DNSServiceErrorType error = lib->createConnection(&m_mainRef);
1310 if (error != kDNSServiceErr_NoError){
1311 appendError(QStringList(tr("MainConnection using lib %1 failed the initialization of mainRef with error %2")
1312 .arg(lib->name()).arg(error)),false);
1313 ++m_nErrs;
1314 if (m_nErrs > 10 || !lib->isOk())
1315 abortLib();
1316 } else {
1317 increaseStatusTo(Running);
1318 // multithreading issues if we support multiple cycles of createConnection/destroyConnection
1319 for (int i = m_browsers.count(); i-- != 0; ){
1320 ServiceBrowserPrivate *bAtt=m_browsers[i];
1321 if (bAtt && !bAtt->browsing)
1322 bAtt->startBrowsing(bAtt->interfaceIndex);
1323 }
1324 break;
1325 }
1326 } else if (err == kDNSServiceErr_ServiceNotRunning) {
1327 appendError(QStringList(tr("MainConnection using lib %1 failed because no daemon is running")
1328 .arg(lib->name())),false);
1329 if (lib->tryStartDaemon()) {
1330 appendError(QStringList(tr("MainConnection using lib %1 daemon starting seem successful, continuing")
1331 .arg(lib->name())),false);
1332 } else {
1333 appendError(QStringList(tr("MainConnection using lib %1 failed because no daemon is running")
1334 .arg(lib->name())),false);
1335 abortLib();
1336 }
1337 } else {
1338 appendError(QStringList(tr("MainConnection using lib %1 failed getProperty call with error %2")
1339 .arg(lib->name()).arg(err)),false);
1340 abortLib();
1341 }
1342 }
1343 }
1344
1345 ZConfLib::ProcessStatus MainConnection::handleEvent()
1346 {
1347 ZConfLib::ProcessStatus err = lib->processResult(m_mainRef);
1348 if (err != ZConfLib::ProcessedOk) {
1349 qDebug() << "processResult returned " << err;
1350 ++m_nErrs;
1351 } else {
1352 m_nErrs=0;
1353 maybeUpdateLists();
1354 }
1355 return err;
1356 }
1357
1358 void MainConnection::destroyConnection()
1359 {
1360 // multithreading issues if we support multiple cycles of createConnection/destroyConnection
1361 for (int i = m_browsers.count(); i-- != 0;){
1362 ServiceBrowserPrivate *bAtt=m_browsers[i];
1363 if (bAtt->browsing)
1364 bAtt->stopBrowsing();
1365 }
1366 if (m_mainRef != 0)
1367 lib->destroyConnection(&m_mainRef);
1368 m_mainRef=0;
1369 }
1370
1371 void MainConnection::handleEvents()
1372 {
1373 if (!m_status.testAndSetAcquire(Starting, Started)){
1374 appendError(QStringList(tr("MainConnection::handleEvents called with m_status != Starting, aborting")),true);
1375 increaseStatusTo(Stopped);
1376 return;
1377 }
1378 m_nErrs = 0;
1379 createConnection();
1380 increaseStatusTo(Running);
1381 while (m_status < Stopping) {
1382 if (m_nErrs > 10)
1383 increaseStatusTo(Stopping);
1384 switch (handleEvent()) {
1385 case ZConfLib::ProcessedOk :
1386 break;
1387 case ZConfLib::ProcessedError :
1388 ++m_nErrs;
1389 break;
1390 case ZConfLib::ProcessedFailure :
1391 increaseStatusTo(Stopping);
1392 ++m_nErrs;
1393 break;
1394 case ZConfLib::ProcessedQuit :
1395 increaseStatusTo(Stopping);
1396 break;
1397 default:
1398 appendError(QStringList(tr("MainConnection::handleEvents unexpected return status of handleEvent")),true);
1399 increaseStatusTo(Stopping);
1400 break;
1401 }
1402 }
1403 destroyConnection();
1404 if (m_nErrs > 0){
1405 QString browsersNames=(m_browsers.isEmpty()?QString():m_browsers.at(0)->serviceType)+((m_browsers.count()>1)?QString::fromLatin1(",..."):QString());
1406 appendError(QStringList(tr("MainConnection for [%1] accumulated %2 consecutive errors, aborting").arg(browsersNames).arg(m_nErrs)),true);
1407 }
1408 increaseStatusTo(Stopped);
1409 }
1410
1411 ZConfLib::ConnectionRef MainConnection::mainRef()
1412 {
1413 while (m_status < Running){
1414 QThread::yieldCurrentThread();
1415 }
1416 return m_mainRef;
1417 }
1418
1419 QStringList MainConnection::errors()
1420 {
1421 QMutexLocker l(lock());
1422 return m_errors;
1423 }
1424
1425 void MainConnection::clearErrors()
1426 {
1427 QMutexLocker l(lock());
1428 m_errors.clear();
1429 }
1430
1431 void MainConnection::appendError(const QStringList &s,bool failure)
1432 {
1433 QList<ServiceBrowserPrivate *> browsersAtt;
1434 bool didFail;
1435 {
1436 QMutexLocker l(lock());
1437 m_errors.append(s);
1438 browsersAtt=m_browsers;
1439 m_failed= failure || m_failed;
1440 didFail=m_failed;
1441 }
1442 foreach (ServiceBrowserPrivate *b,browsersAtt)
1443 b->hadError(s,didFail);
1444 }
1445
1446 bool MainConnection::isOk()
1447 {
1448 return !m_failed;
1449 }
1450
1451 // ----------------- ZConfLib impl -----------------
1452
1453 bool ZConfLib::tryStartDaemon()
1454 {
1455 return false;
1456 }
1457
1458 QString ZConfLib::name(){
1459 return QString::fromUtf8("ZeroConfLib@%1").arg(size_t(this),0,16);
1460 }
1461
1462 ZConfLib::ZConfLib(ZConfLib * f) : fallbackLib(f), m_isOk(true)
1463 { }
1464
1465 ZConfLib::~ZConfLib()
1466 { }
1467
1468 bool ZConfLib::isOk()
1469 {
1470 return m_isOk;
1471 }
1472
1473 QString ZConfLib::errorMsg()
1474 {
1475 return m_errorMsg;
1476 }
1477
1478 void ZConfLib::setError(bool failure, const QString &eMsg)
1479 {
1480 m_errorMsg = eMsg;
1481 m_isOk = !failure;
1482 }
1483
1484 } // namespace Internal
1485 } // namespace ZeroConf