1 /*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #define TRACE_TAG TRANSPORT
18
19 #include "transport.h"
20
21 #ifdef _WIN32
22 #include <winsock2.h>
23 #else
24 #include <arpa/inet.h>
25 #endif
26
27 #include <thread>
28
29 #include <android-base/stringprintf.h>
30 #include <dns_sd.h>
31
32 #include "adb_mdns.h"
33 #include "adb_trace.h"
34 #include "fdevent.h"
35 #include "sysdeps.h"
36
37 static DNSServiceRef service_ref;
38 static fdevent* service_ref_fde;
39
40 // Use adb_DNSServiceRefSockFD() instead of calling DNSServiceRefSockFD()
41 // directly so that the socket is put through the appropriate compatibility
42 // layers to work with the rest of ADB's internal APIs.
adb_DNSServiceRefSockFD(DNSServiceRef ref)43 static inline int adb_DNSServiceRefSockFD(DNSServiceRef ref) {
44 return adb_register_socket(DNSServiceRefSockFD(ref));
45 }
46 #define DNSServiceRefSockFD ___xxx_DNSServiceRefSockFD
47
48 static void DNSSD_API register_service_ip(DNSServiceRef sdRef,
49 DNSServiceFlags flags,
50 uint32_t interfaceIndex,
51 DNSServiceErrorType errorCode,
52 const char* hostname,
53 const sockaddr* address,
54 uint32_t ttl,
55 void* context);
56
pump_service_ref(int,unsigned ev,void * data)57 static void pump_service_ref(int /*fd*/, unsigned ev, void* data) {
58 DNSServiceRef* ref = reinterpret_cast<DNSServiceRef*>(data);
59
60 if (ev & FDE_READ)
61 DNSServiceProcessResult(*ref);
62 }
63
64 class AsyncServiceRef {
65 public:
Initialized()66 bool Initialized() {
67 return initialized_;
68 }
69
~AsyncServiceRef()70 virtual ~AsyncServiceRef() {
71 if (!initialized_) {
72 return;
73 }
74
75 DNSServiceRefDeallocate(sdRef_);
76 fdevent_destroy(fde_);
77 }
78
79 protected:
80 DNSServiceRef sdRef_;
81
Initialize()82 void Initialize() {
83 fde_ = fdevent_create(adb_DNSServiceRefSockFD(sdRef_), pump_service_ref, &sdRef_);
84 fdevent_set(fde_, FDE_READ);
85 initialized_ = true;
86 }
87
88 private:
89 bool initialized_ = false;
90 fdevent* fde_;
91 };
92
93 class ResolvedService : public AsyncServiceRef {
94 public:
95 virtual ~ResolvedService() = default;
96
ResolvedService(std::string name,uint32_t interfaceIndex,const char * hosttarget,uint16_t port)97 ResolvedService(std::string name, uint32_t interfaceIndex,
98 const char* hosttarget, uint16_t port) :
99 name_(name),
100 port_(port) {
101
102 /* TODO: We should be able to get IPv6 support by adding
103 * kDNSServiceProtocol_IPv6 to the flags below. However, when we do
104 * this, we get served link-local addresses that are usually useless to
105 * connect to. What's more, we seem to /only/ get those and nothing else.
106 * If we want IPv6 in the future we'll have to figure out why.
107 */
108 DNSServiceErrorType ret =
109 DNSServiceGetAddrInfo(
110 &sdRef_, 0, interfaceIndex,
111 kDNSServiceProtocol_IPv4, hosttarget,
112 register_service_ip, reinterpret_cast<void*>(this));
113
114 if (ret != kDNSServiceErr_NoError) {
115 D("Got %d from DNSServiceGetAddrInfo.", ret);
116 } else {
117 Initialize();
118 }
119 }
120
Connect(const sockaddr * address)121 void Connect(const sockaddr* address) {
122 char ip_addr[INET6_ADDRSTRLEN];
123 const void* ip_addr_data;
124 const char* addr_format;
125
126 if (address->sa_family == AF_INET) {
127 ip_addr_data =
128 &reinterpret_cast<const sockaddr_in*>(address)->sin_addr;
129 addr_format = "%s:%hu";
130 } else if (address->sa_family == AF_INET6) {
131 ip_addr_data =
132 &reinterpret_cast<const sockaddr_in6*>(address)->sin6_addr;
133 addr_format = "[%s]:%hu";
134 } else { // Should be impossible
135 D("mDNS resolved non-IP address.");
136 return;
137 }
138
139 // Winsock version requires the const cast Because Microsoft.
140 if (!inet_ntop(address->sa_family, const_cast<void*>(ip_addr_data),
141 ip_addr, INET6_ADDRSTRLEN)) {
142 D("Could not convert IP address to string.");
143 return;
144 }
145
146 std::string response;
147 connect_device(android::base::StringPrintf(addr_format, ip_addr, port_),
148 &response);
149 D("Connect to %s (%s:%hu) : %s", name_.c_str(), ip_addr, port_,
150 response.c_str());
151 }
152
153 private:
154 std::string name_;
155 const uint16_t port_;
156 };
157
register_service_ip(DNSServiceRef,DNSServiceFlags,uint32_t,DNSServiceErrorType,const char *,const sockaddr * address,uint32_t,void * context)158 static void DNSSD_API register_service_ip(DNSServiceRef /*sdRef*/,
159 DNSServiceFlags /*flags*/,
160 uint32_t /*interfaceIndex*/,
161 DNSServiceErrorType /*errorCode*/,
162 const char* /*hostname*/,
163 const sockaddr* address,
164 uint32_t /*ttl*/,
165 void* context) {
166 D("Got IP for service.");
167 std::unique_ptr<ResolvedService> data(
168 reinterpret_cast<ResolvedService*>(context));
169 data->Connect(address);
170 }
171
172 static void DNSSD_API register_resolved_mdns_service(DNSServiceRef sdRef,
173 DNSServiceFlags flags,
174 uint32_t interfaceIndex,
175 DNSServiceErrorType errorCode,
176 const char* fullname,
177 const char* hosttarget,
178 uint16_t port,
179 uint16_t txtLen,
180 const unsigned char* txtRecord,
181 void* context);
182
183 class DiscoveredService : public AsyncServiceRef {
184 public:
DiscoveredService(uint32_t interfaceIndex,const char * serviceName,const char * regtype,const char * domain)185 DiscoveredService(uint32_t interfaceIndex, const char* serviceName,
186 const char* regtype, const char* domain)
187 : serviceName_(serviceName) {
188
189 DNSServiceErrorType ret =
190 DNSServiceResolve(&sdRef_, 0, interfaceIndex, serviceName, regtype,
191 domain, register_resolved_mdns_service,
192 reinterpret_cast<void*>(this));
193
194 if (ret != kDNSServiceErr_NoError) {
195 D("Got %d from DNSServiceResolve.", ret);
196 } else {
197 Initialize();
198 }
199 }
200
ServiceName()201 const char* ServiceName() {
202 return serviceName_.c_str();
203 }
204
205 private:
206 std::string serviceName_;
207 };
208
register_resolved_mdns_service(DNSServiceRef sdRef,DNSServiceFlags flags,uint32_t interfaceIndex,DNSServiceErrorType errorCode,const char * fullname,const char * hosttarget,uint16_t port,uint16_t,const unsigned char *,void * context)209 static void DNSSD_API register_resolved_mdns_service(DNSServiceRef sdRef,
210 DNSServiceFlags flags,
211 uint32_t interfaceIndex,
212 DNSServiceErrorType errorCode,
213 const char* fullname,
214 const char* hosttarget,
215 uint16_t port,
216 uint16_t /*txtLen*/,
217 const unsigned char* /*txtRecord*/,
218 void* context) {
219 D("Resolved a service.");
220 std::unique_ptr<DiscoveredService> discovered(
221 reinterpret_cast<DiscoveredService*>(context));
222
223 if (errorCode != kDNSServiceErr_NoError) {
224 D("Got error %d resolving service.", errorCode);
225 return;
226 }
227
228
229 auto resolved =
230 new ResolvedService(discovered->ServiceName(),
231 interfaceIndex, hosttarget, ntohs(port));
232
233 if (! resolved->Initialized()) {
234 delete resolved;
235 }
236
237 if (flags) { /* Only ever equals MoreComing or 0 */
238 discovered.release();
239 }
240 }
241
register_mdns_transport(DNSServiceRef sdRef,DNSServiceFlags flags,uint32_t interfaceIndex,DNSServiceErrorType errorCode,const char * serviceName,const char * regtype,const char * domain,void *)242 static void DNSSD_API register_mdns_transport(DNSServiceRef sdRef,
243 DNSServiceFlags flags,
244 uint32_t interfaceIndex,
245 DNSServiceErrorType errorCode,
246 const char* serviceName,
247 const char* regtype,
248 const char* domain,
249 void* /*context*/) {
250 D("Registering a transport.");
251 if (errorCode != kDNSServiceErr_NoError) {
252 D("Got error %d during mDNS browse.", errorCode);
253 DNSServiceRefDeallocate(sdRef);
254 fdevent_destroy(service_ref_fde);
255 return;
256 }
257
258 auto discovered = new DiscoveredService(interfaceIndex, serviceName, regtype, domain);
259 if (!discovered->Initialized()) {
260 delete discovered;
261 }
262 }
263
init_mdns_transport_discovery_thread(void)264 void init_mdns_transport_discovery_thread(void) {
265 DNSServiceErrorType errorCode = DNSServiceBrowse(&service_ref, 0, 0, kADBServiceType, nullptr,
266 register_mdns_transport, nullptr);
267
268 if (errorCode != kDNSServiceErr_NoError) {
269 D("Got %d initiating mDNS browse.", errorCode);
270 return;
271 }
272
273 fdevent_run_on_main_thread([]() {
274 service_ref_fde =
275 fdevent_create(adb_DNSServiceRefSockFD(service_ref), pump_service_ref, &service_ref);
276 fdevent_set(service_ref_fde, FDE_READ);
277 });
278 }
279
init_mdns_transport_discovery(void)280 void init_mdns_transport_discovery(void) {
281 std::thread(init_mdns_transport_discovery_thread).detach();
282 }
283