summaryrefslogtreecommitdiffstats
blob: d16ca5b02d591cc62e74e140cdb7bba4ac81d021 (plain)
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
#pragma once

#include "Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuery.h"
#include "Swiften/LinkLocal/DNSSD/DNSSDResolveServiceQuery.h"
#include "Swiften/LinkLocal/LinkLocalServiceInfo.h"
#include "Swiften/Base/ByteArray.h"
#include "Swiften/EventLoop/MainEventLoop.h"

namespace Swift {
	class BonjourQuerier;

	class BonjourResolveServiceQuery : public DNSSDResolveServiceQuery, public BonjourQuery {
		public:	
			BonjourResolveServiceQuery(const DNSSDServiceID& service, boost::shared_ptr<BonjourQuerier> querier) : BonjourQuery(querier) {
				DNSServiceErrorType result = DNSServiceResolve(
						&sdRef, 0, service.getNetworkInterfaceID(), 
						service.getName().getUTF8Data(), service.getType().getUTF8Data(), 
						service.getDomain().getUTF8Data(), 
						&BonjourResolveServiceQuery::handleServiceResolvedStatic, this);
				if (result != kDNSServiceErr_NoError) {
					sdRef = NULL;
				}
			}

			void start() {
				if (sdRef) {
					run();
				}
				else {
					MainEventLoop::postEvent(boost::bind(boost::ref(onServiceResolved), boost::optional<Result>()), shared_from_this());
				}
			}

			void stop() {
				finish();
			}

		private:
			static void handleServiceResolvedStatic(DNSServiceRef, DNSServiceFlags, uint32_t, DNSServiceErrorType errorCode, const char *fullname, const char *hosttarget, uint16_t port, uint16_t txtLen, const unsigned char *txtRecord, void *context) {
				static_cast<BonjourResolveServiceQuery*>(context)->handleServiceResolved(errorCode, fullname, hosttarget, port, txtLen, txtRecord);
			}

			void handleServiceResolved(DNSServiceErrorType errorCode, const char* fullName, const char* host, uint16_t port, uint16_t txtLen, const unsigned char *txtRecord) {
				if (errorCode != kDNSServiceErr_NoError) {
					MainEventLoop::postEvent(boost::bind(boost::ref(onServiceResolved), boost::optional<Result>()), shared_from_this());
				}
				else {
					MainEventLoop::postEvent(
							boost::bind(
								boost::ref(onServiceResolved), 
								Result(String(fullName), String(host), port, 
									ByteArray(reinterpret_cast<const char*>(txtRecord), txtLen))), 
							shared_from_this());
				}
			}
	};
}