1 /*
2  * Copyright (C) 2020 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 <memory>
28 #include <thread>
29 #include <unordered_set>
30 #include <vector>
31 
32 #include <android-base/stringprintf.h>
33 #include <android-base/strings.h>
34 
35 #include <discovery/common/config.h>
36 #include <discovery/common/reporting_client.h>
37 #include <discovery/public/dns_sd_service_factory.h>
38 #include <platform/api/network_interface.h>
39 #include <platform/api/serial_delete_ptr.h>
40 #include <platform/base/error.h>
41 #include <platform/base/interface_info.h>
42 
43 #include "adb_client.h"
44 #include "adb_mdns.h"
45 #include "adb_trace.h"
46 #include "adb_utils.h"
47 #include "adb_wifi.h"
48 #include "client/mdns_utils.h"
49 #include "client/openscreen/mdns_service_watcher.h"
50 #include "client/openscreen/platform/task_runner.h"
51 #include "fdevent/fdevent.h"
52 #include "sysdeps.h"
53 
54 namespace {
55 
56 using namespace mdns;
57 using namespace openscreen;
58 using ServicesUpdatedState = mdns::ServiceReceiver::ServicesUpdatedState;
59 
60 struct DiscoveryState;
61 DiscoveryState* g_state = nullptr;
62 // TODO: remove once openscreen has bonjour client APIs.
63 bool g_using_bonjour = false;
64 AdbMdnsResponderFuncs g_adb_mdnsresponder_funcs;
65 
66 class DiscoveryReportingClient : public discovery::ReportingClient {
67   public:
OnFatalError(Error error)68     void OnFatalError(Error error) override {
69         // The multicast port 5353 may fail to bind because of another process already binding
70         // to it (bonjour). So let's fallback to bonjour client APIs.
71         // TODO: Remove this once openscreen implements the bonjour client APIs.
72         LOG(ERROR) << "Encountered fatal discovery error: " << error;
73         got_fatal_ = true;
74     }
75 
OnRecoverableError(Error error)76     void OnRecoverableError(Error error) override {
77         LOG(ERROR) << "Encountered recoverable discovery error: " << error;
78     }
79 
GotFatalError() const80     bool GotFatalError() const { return got_fatal_; }
81 
82   private:
83     std::atomic<bool> got_fatal_{false};
84 };
85 
86 struct DiscoveryState {
87     SerialDeletePtr<discovery::DnsSdService> service;
88     std::unique_ptr<DiscoveryReportingClient> reporting_client;
89     std::unique_ptr<AdbOspTaskRunner> task_runner;
90     std::vector<std::unique_ptr<ServiceReceiver>> receivers;
91     InterfaceInfo interface_info;
92 };
93 
94 // Callback provided to service receiver for updates.
OnServiceReceiverResult(std::vector<std::reference_wrapper<const ServiceInfo>> infos,std::reference_wrapper<const ServiceInfo> info,ServicesUpdatedState state)95 void OnServiceReceiverResult(std::vector<std::reference_wrapper<const ServiceInfo>> infos,
96                              std::reference_wrapper<const ServiceInfo> info,
97                              ServicesUpdatedState state) {
98     LOG(INFO) << "Endpoint state=" << static_cast<int>(state)
99               << " instance_name=" << info.get().instance_name
100               << " service_name=" << info.get().service_name << " addr=" << info.get().v4_address
101               << " addrv6=" << info.get().v6_address << " total_serv=" << infos.size();
102 
103     switch (state) {
104         case ServicesUpdatedState::EndpointCreated:
105         case ServicesUpdatedState::EndpointUpdated:
106             if (adb_DNSServiceShouldAutoConnect(info.get().service_name,
107                                                 info.get().instance_name) &&
108                 info.get().v4_address) {
109                 auto index = adb_DNSServiceIndexByName(info.get().service_name);
110                 if (!index) {
111                     return;
112                 }
113 
114                 // Don't try to auto-connect if not in the keystore.
115                 if (*index == kADBSecureConnectServiceRefIndex &&
116                     !adb_wifi_is_known_host(info.get().instance_name)) {
117                     LOG(INFO) << "instance_name=" << info.get().instance_name << " not in keystore";
118                     return;
119                 }
120                 std::string response;
121                 LOG(INFO) << "Attempting to auto-connect to instance=" << info.get().instance_name
122                           << " service=" << info.get().service_name << " addr4=%s"
123                           << info.get().v4_address << ":" << info.get().port;
124                 connect_device(
125                         android::base::StringPrintf("%s.%s", info.get().instance_name.c_str(),
126                                                     info.get().service_name.c_str()),
127                         &response);
128             }
129             break;
130         default:
131             break;
132     }
133 }
134 
GetConfigForAllInterfaces()135 std::optional<discovery::Config> GetConfigForAllInterfaces() {
136     auto interface_infos = GetNetworkInterfaces();
137 
138     discovery::Config config;
139     for (const auto interface : interface_infos) {
140         if (interface.GetIpAddressV4() || interface.GetIpAddressV6()) {
141             config.network_info.push_back({interface});
142             LOG(VERBOSE) << "Listening on interface [" << interface << "]";
143         }
144     }
145 
146     if (config.network_info.empty()) {
147         LOG(INFO) << "No available network interfaces for mDNS discovery";
148         return std::nullopt;
149     }
150 
151     return config;
152 }
153 
StartDiscovery()154 void StartDiscovery() {
155     CHECK(!g_state);
156     g_state = new DiscoveryState();
157     g_state->task_runner = std::make_unique<AdbOspTaskRunner>();
158     g_state->reporting_client = std::make_unique<DiscoveryReportingClient>();
159 
160     g_state->task_runner->PostTask([]() {
161         auto config = GetConfigForAllInterfaces();
162         if (!config) {
163             return;
164         }
165 
166         g_state->service = discovery::CreateDnsSdService(g_state->task_runner.get(),
167                                                          g_state->reporting_client.get(), *config);
168         // Register a receiver for each service type
169         for (int i = 0; i < kNumADBDNSServices; ++i) {
170             auto receiver = std::make_unique<ServiceReceiver>(
171                     g_state->service.get(), kADBDNSServices[i], OnServiceReceiverResult);
172             receiver->StartDiscovery();
173             g_state->receivers.push_back(std::move(receiver));
174 
175             if (g_state->reporting_client->GotFatalError()) {
176                 for (auto& r : g_state->receivers) {
177                     if (r->is_running()) {
178                         r->StopDiscovery();
179                     }
180                 }
181                 g_using_bonjour = true;
182                 break;
183             }
184         }
185 
186         if (g_using_bonjour) {
187             LOG(INFO) << "Fallback to MdnsResponder client for discovery";
188             g_adb_mdnsresponder_funcs = StartMdnsResponderDiscovery();
189         }
190     });
191 }
192 
ForEachService(const std::unique_ptr<ServiceReceiver> & receiver,std::string_view wanted_instance_name,adb_secure_foreach_service_callback cb)193 void ForEachService(const std::unique_ptr<ServiceReceiver>& receiver,
194                     std::string_view wanted_instance_name, adb_secure_foreach_service_callback cb) {
195     if (!receiver->is_running()) {
196         return;
197     }
198     auto services = receiver->GetServices();
199     for (const auto& s : services) {
200         if (wanted_instance_name.empty() || s.get().instance_name == wanted_instance_name) {
201             std::stringstream ss;
202             ss << s.get().v4_address;
203             cb(s.get().instance_name.c_str(), s.get().service_name.c_str(), ss.str().c_str(),
204                s.get().port);
205         }
206     }
207 }
208 
ConnectAdbSecureDevice(const MdnsInfo & info)209 bool ConnectAdbSecureDevice(const MdnsInfo& info) {
210     if (!adb_wifi_is_known_host(info.service_name)) {
211         LOG(INFO) << "serviceName=" << info.service_name << " not in keystore";
212         return false;
213     }
214 
215     std::string response;
216     connect_device(android::base::StringPrintf("%s.%s", info.service_name.c_str(),
217                                                info.service_type.c_str()),
218                    &response);
219     D("Secure connect to %s regtype %s (%s:%hu) : %s", info.service_name.c_str(),
220       info.service_type.c_str(), info.addr.c_str(), info.port, response.c_str());
221     return true;
222 }
223 
224 }  // namespace
225 
226 /////////////////////////////////////////////////////////////////////////////////
mdns_cleanup()227 void mdns_cleanup() {
228     if (g_using_bonjour) {
229         return g_adb_mdnsresponder_funcs.mdns_cleanup();
230     }
231 }
232 
init_mdns_transport_discovery(void)233 void init_mdns_transport_discovery(void) {
234     // TODO(joshuaduong): Use openscreen discovery by default for all platforms.
235     const char* mdns_osp = getenv("ADB_MDNS_OPENSCREEN");
236     if (mdns_osp && strcmp(mdns_osp, "1") == 0) {
237         LOG(INFO) << "Openscreen mdns discovery enabled";
238         StartDiscovery();
239     } else {
240         // Original behavior is to use Bonjour client.
241         g_using_bonjour = true;
242         g_adb_mdnsresponder_funcs = StartMdnsResponderDiscovery();
243     }
244 }
245 
adb_secure_connect_by_service_name(const std::string & instance_name)246 bool adb_secure_connect_by_service_name(const std::string& instance_name) {
247     if (g_using_bonjour) {
248         return g_adb_mdnsresponder_funcs.adb_secure_connect_by_service_name(instance_name);
249     }
250 
251     if (!g_state || g_state->receivers.empty()) {
252         LOG(INFO) << "Mdns not enabled";
253         return false;
254     }
255 
256     std::optional<MdnsInfo> info;
257     auto cb = [&](const std::string& instance_name, const std::string& service_name,
258                   const std::string& ip_addr,
259                   uint16_t port) { info.emplace(instance_name, service_name, ip_addr, port); };
260     ForEachService(g_state->receivers[kADBSecureConnectServiceRefIndex], instance_name, cb);
261     if (info.has_value()) {
262         return ConnectAdbSecureDevice(*info);
263     }
264     return false;
265 }
266 
mdns_check()267 std::string mdns_check() {
268     if (!g_state && !g_using_bonjour) {
269         return "ERROR: mdns discovery disabled";
270     }
271 
272     if (g_using_bonjour) {
273         return g_adb_mdnsresponder_funcs.mdns_check();
274     }
275 
276     return "mdns daemon version [Openscreen discovery 0.0.0]";
277 }
278 
mdns_list_discovered_services()279 std::string mdns_list_discovered_services() {
280     if (g_using_bonjour) {
281         return g_adb_mdnsresponder_funcs.mdns_list_discovered_services();
282     }
283 
284     if (!g_state || g_state->receivers.empty()) {
285         return "";
286     }
287 
288     std::string result;
289     auto cb = [&](const std::string& instance_name, const std::string& service_name,
290                   const std::string& ip_addr, uint16_t port) {
291         result += android::base::StringPrintf("%s\t%s\t%s:%u\n", instance_name.data(),
292                                               service_name.data(), ip_addr.data(), port);
293     };
294 
295     for (const auto& receiver : g_state->receivers) {
296         ForEachService(receiver, "", cb);
297     }
298     return result;
299 }
300 
mdns_get_connect_service_info(const std::string & name)301 std::optional<MdnsInfo> mdns_get_connect_service_info(const std::string& name) {
302     CHECK(!name.empty());
303 
304     if (g_using_bonjour) {
305         return g_adb_mdnsresponder_funcs.mdns_get_connect_service_info(name);
306     }
307 
308     if (!g_state || g_state->receivers.empty()) {
309         return std::nullopt;
310     }
311 
312     auto mdns_instance = mdns::mdns_parse_instance_name(name);
313     if (!mdns_instance.has_value()) {
314         D("Failed to parse mDNS name [%s]", name.data());
315         return std::nullopt;
316     }
317 
318     std::optional<MdnsInfo> info;
319     auto cb = [&](const std::string& instance_name, const std::string& service_name,
320                   const std::string& ip_addr,
321                   uint16_t port) { info.emplace(instance_name, service_name, ip_addr, port); };
322 
323     std::string reg_type;
324     // Service name was provided.
325     if (!mdns_instance->service_name.empty()) {
326         reg_type = android::base::StringPrintf("%s.%s", mdns_instance->service_name.data(),
327                                                mdns_instance->transport_type.data());
328         const auto index = adb_DNSServiceIndexByName(reg_type);
329         if (!index) {
330             return std::nullopt;
331         }
332         switch (*index) {
333             case kADBTransportServiceRefIndex:
334             case kADBSecureConnectServiceRefIndex:
335                 ForEachService(g_state->receivers[*index], mdns_instance->instance_name, cb);
336                 break;
337             default:
338                 D("Not a connectable service name [%s]", reg_type.data());
339                 return std::nullopt;
340         }
341         return info;
342     }
343 
344     // No mdns service name provided. Just search for the instance name in all adb connect services.
345     // Prefer the secured connect service over the other.
346     ForEachService(g_state->receivers[kADBSecureConnectServiceRefIndex], name, cb);
347     if (!info.has_value()) {
348         ForEachService(g_state->receivers[kADBTransportServiceRefIndex], name, cb);
349     }
350 
351     return info;
352 }
353 
mdns_get_pairing_service_info(const std::string & name)354 std::optional<MdnsInfo> mdns_get_pairing_service_info(const std::string& name) {
355     CHECK(!name.empty());
356 
357     if (g_using_bonjour) {
358         return g_adb_mdnsresponder_funcs.mdns_get_pairing_service_info(name);
359     }
360 
361     if (!g_state || g_state->receivers.empty()) {
362         return std::nullopt;
363     }
364 
365     auto mdns_instance = mdns::mdns_parse_instance_name(name);
366     if (!mdns_instance.has_value()) {
367         D("Failed to parse mDNS name [%s]", name.data());
368         return std::nullopt;
369     }
370 
371     std::optional<MdnsInfo> info;
372     auto cb = [&](const std::string& instance_name, const std::string& service_name,
373                   const std::string& ip_addr,
374                   uint16_t port) { info.emplace(instance_name, service_name, ip_addr, port); };
375 
376     std::string reg_type;
377     // Verify it's a pairing service if user explicitly inputs it.
378     if (!mdns_instance->service_name.empty()) {
379         reg_type = android::base::StringPrintf("%s.%s", mdns_instance->service_name.data(),
380                                                mdns_instance->transport_type.data());
381         const auto index = adb_DNSServiceIndexByName(reg_type);
382         if (!index) {
383             return std::nullopt;
384         }
385         switch (*index) {
386             case kADBSecurePairingServiceRefIndex:
387                 break;
388             default:
389                 D("Not an adb pairing reg_type [%s]", reg_type.data());
390                 return std::nullopt;
391         }
392         return info;
393     }
394 
395     ForEachService(g_state->receivers[kADBSecurePairingServiceRefIndex], name, cb);
396 
397     return info;
398 }
399