1 /*
2  * Copyright (C) 2011 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 #ifndef __TRANSPORT_H
18 #define __TRANSPORT_H
19 
20 #include <sys/types.h>
21 
22 #include <atomic>
23 #include <chrono>
24 #include <condition_variable>
25 #include <deque>
26 #include <functional>
27 #include <list>
28 #include <memory>
29 #include <mutex>
30 #include <optional>
31 #include <string>
32 #include <string_view>
33 #include <thread>
34 #include <unordered_map>
35 #include <vector>
36 
37 #include <android-base/macros.h>
38 #include <android-base/thread_annotations.h>
39 #include <openssl/rsa.h>
40 
41 #include "adb.h"
42 #include "adb_unique_fd.h"
43 #include "types.h"
44 
45 // Even though the feature set is used as a set, we only have a dozen or two
46 // of available features at any moment. Vector works much better in terms of
47 // both memory usage and performance for these sizes.
48 using FeatureSet = std::vector<std::string>;
49 
50 namespace adb {
51 namespace tls {
52 
53 class TlsConnection;
54 
55 }  // namespace tls
56 }  // namespace adb
57 
58 const FeatureSet& supported_features();
59 
60 // Encodes and decodes FeatureSet objects into human-readable strings.
61 std::string FeatureSetToString(const FeatureSet& features);
62 FeatureSet StringToFeatureSet(const std::string& features_string);
63 
64 // Returns true if both local features and |feature_set| support |feature|.
65 bool CanUseFeature(const FeatureSet& feature_set, const std::string& feature);
66 
67 // Do not use any of [:;=,] in feature strings, they have special meaning
68 // in the connection banner.
69 extern const char* const kFeatureShell2;
70 // The 'cmd' command is available
71 extern const char* const kFeatureCmd;
72 extern const char* const kFeatureStat2;
73 extern const char* const kFeatureLs2;
74 // The server is running with libusb enabled.
75 extern const char* const kFeatureLibusb;
76 // adbd supports `push --sync`.
77 extern const char* const kFeaturePushSync;
78 // adbd supports installing .apex packages.
79 extern const char* const kFeatureApex;
80 // adbd has b/110953234 fixed.
81 extern const char* const kFeatureFixedPushMkdir;
82 // adbd supports android binder bridge (abb) in interactive mode using shell protocol.
83 extern const char* const kFeatureAbb;
84 // adbd supports abb using raw pipe.
85 extern const char* const kFeatureAbbExec;
86 // adbd properly updates symlink timestamps on push.
87 extern const char* const kFeatureFixedPushSymlinkTimestamp;
88 // Implement `adb remount` via shelling out to /system/bin/remount.
89 extern const char* const kFeatureRemountShell;
90 // adbd supports `track-app` service reporting debuggable/profileable apps.
91 extern const char* const kFeatureTrackApp;
92 // adbd supports version 2 of send/recv.
93 extern const char* const kFeatureSendRecv2;
94 // adbd supports brotli for send/recv v2.
95 extern const char* const kFeatureSendRecv2Brotli;
96 // adbd supports LZ4 for send/recv v2.
97 extern const char* const kFeatureSendRecv2LZ4;
98 // adbd supports Zstd for send/recv v2.
99 extern const char* const kFeatureSendRecv2Zstd;
100 // adbd supports dry-run send for send/recv v2.
101 extern const char* const kFeatureSendRecv2DryRunSend;
102 // adbd supports delayed acks.
103 extern const char* const kFeatureDelayedAck;
104 // adbd supports `dev-raw` service
105 extern const char* const kFeatureDevRaw;
106 
107 TransportId NextTransportId();
108 
109 // Abstraction for a non-blocking packet transport.
110 struct Connection {
111     Connection() = default;
112     virtual ~Connection() = default;
113 
SetTransportConnection114     void SetTransport(atransport* transport) { transport_ = transport; }
115 
116     virtual bool Write(std::unique_ptr<apacket> packet) = 0;
117 
118     virtual void Start() = 0;
119     virtual void Stop() = 0;
120 
121     virtual bool DoTlsHandshake(RSA* key, std::string* auth_key = nullptr) = 0;
122 
123     // Stop, and reset the device if it's a USB connection.
124     virtual void Reset();
125 
AttachConnection126     virtual bool Attach(std::string* error) {
127         *error = "transport type doesn't support attach";
128         return false;
129     }
130 
DetachConnection131     virtual bool Detach(std::string* error) {
132         *error = "transport type doesn't support detach";
133         return false;
134     }
135 
136     std::string Serial() const;
137 
138     atransport* transport_ = nullptr;
139 
140     static std::unique_ptr<Connection> FromFd(unique_fd fd);
141 
NegotiatedSpeedMbpsConnection142     virtual uint64_t NegotiatedSpeedMbps() { return 0; }
MaxSpeedMbpsConnection143     virtual uint64_t MaxSpeedMbps() { return 0; }
144 };
145 
146 // Abstraction for a blocking packet transport.
147 struct BlockingConnection {
148     BlockingConnection() = default;
149     BlockingConnection(const BlockingConnection& copy) = delete;
150     BlockingConnection(BlockingConnection&& move) = delete;
151 
152     // Destroy a BlockingConnection. Formerly known as 'Close' in atransport.
153     virtual ~BlockingConnection() = default;
154 
155     // Read/Write a packet. These functions are concurrently called from a transport's reader/writer
156     // threads.
157     virtual bool Read(apacket* packet) = 0;
158     virtual bool Write(apacket* packet) = 0;
159 
160     virtual bool DoTlsHandshake(RSA* key, std::string* auth_key = nullptr) = 0;
161 
162     // Terminate a connection.
163     // This method must be thread-safe, and must cause concurrent Reads/Writes to terminate.
164     // Formerly known as 'Kick' in atransport.
165     virtual void Close() = 0;
166 
167     // Terminate a connection, and reset it.
168     virtual void Reset() = 0;
169 };
170 
171 struct BlockingConnectionAdapter : public Connection {
172     explicit BlockingConnectionAdapter(std::unique_ptr<BlockingConnection> connection);
173 
174     virtual ~BlockingConnectionAdapter();
175 
176     virtual bool Write(std::unique_ptr<apacket> packet) override final;
177 
178     virtual void Start() override final;
179     virtual void Stop() override final;
180     virtual bool DoTlsHandshake(RSA* key, std::string* auth_key) override final;
181 
182     virtual void Reset() override final;
183 
184   private:
185     void StartReadThread() REQUIRES(mutex_);
186     bool started_ GUARDED_BY(mutex_) = false;
187     bool stopped_ GUARDED_BY(mutex_) = false;
188 
189     std::unique_ptr<BlockingConnection> underlying_;
190     std::thread read_thread_ GUARDED_BY(mutex_);
191     std::thread write_thread_ GUARDED_BY(mutex_);
192 
193     std::deque<std::unique_ptr<apacket>> write_queue_ GUARDED_BY(mutex_);
194     std::mutex mutex_;
195     std::condition_variable cv_;
196 
197     std::once_flag error_flag_;
198 };
199 
200 struct FdConnection : public BlockingConnection {
201     explicit FdConnection(unique_fd fd);
202     ~FdConnection();
203 
204     bool Read(apacket* packet) override final;
205     bool Write(apacket* packet) override final;
206     bool DoTlsHandshake(RSA* key, std::string* auth_key) override final;
207 
208     void Close() override;
ResetFdConnection209     virtual void Reset() override final { Close(); }
210 
211   private:
212     bool DispatchRead(void* buf, size_t len);
213     bool DispatchWrite(void* buf, size_t len);
214 
215     unique_fd fd_;
216     std::unique_ptr<adb::tls::TlsConnection> tls_;
217 };
218 
219 // Waits for a transport's connection to be not pending. This is a separate
220 // object so that the transport can be destroyed and another thread can be
221 // notified of it in a race-free way.
222 class ConnectionWaitable {
223   public:
224     ConnectionWaitable() = default;
225     ~ConnectionWaitable() = default;
226 
227     // Waits until the first CNXN packet has been received by the owning
228     // atransport, or the specified timeout has elapsed. Can be called from any
229     // thread.
230     //
231     // Returns true if the CNXN packet was received in a timely fashion, false
232     // otherwise.
233     bool WaitForConnection(std::chrono::milliseconds timeout);
234 
235     // Can be called from any thread when the connection stops being pending.
236     // Only the first invocation will be acknowledged, the rest will be no-ops.
237     void SetConnectionEstablished(bool success);
238 
239   private:
240     bool connection_established_ GUARDED_BY(mutex_) = false;
241     bool connection_established_ready_ GUARDED_BY(mutex_) = false;
242     std::mutex mutex_;
243     std::condition_variable cv_;
244 
245     DISALLOW_COPY_AND_ASSIGN(ConnectionWaitable);
246 };
247 
248 enum class ReconnectResult {
249     Retry,
250     Success,
251     Abort,
252 };
253 
254 #if ADB_HOST
255 struct usb_handle;
256 #endif
257 
258 class atransport : public enable_weak_from_this<atransport> {
259   public:
260     // TODO(danalbert): We expose waaaaaaay too much stuff because this was
261     // historically just a struct, but making the whole thing a more idiomatic
262     // class in one go is a very large change. Given how bad our testing is,
263     // it's better to do this piece by piece.
264 
265     using ReconnectCallback = std::function<ReconnectResult(atransport*)>;
266 
atransport(ReconnectCallback reconnect,ConnectionState state)267     atransport(ReconnectCallback reconnect, ConnectionState state)
268         : id(NextTransportId()),
269           kicked_(false),
270           connection_state_(state),
271           connection_(nullptr),
272           reconnect_(std::move(reconnect)) {
273 #if ADB_HOST
274         connection_waitable_ = std::make_shared<ConnectionWaitable>();
275 #endif
276 
277         // Initialize protocol to min version for compatibility with older versions.
278         // Version will be updated post-connect.
279         protocol_version = A_VERSION_MIN;
280         max_payload = MAX_PAYLOAD;
281     }
282     atransport(ConnectionState state = kCsOffline)
283         : atransport([](atransport*) { return ReconnectResult::Abort; }, state) {}
284     ~atransport();
285 
286     int Write(apacket* p);
287     void Reset();
288     void Kick();
kicked()289     bool kicked() const { return kicked_; }
290 
291     // ConnectionState can be read by all threads, but can only be written in the main thread.
292     ConnectionState GetConnectionState() const;
293     void SetConnectionState(ConnectionState state);
294 
295     void SetConnection(std::shared_ptr<Connection> connection);
connection()296     std::shared_ptr<Connection> connection() {
297         std::lock_guard<std::mutex> lock(mutex_);
298         return connection_;
299     }
300 
301     bool HandleRead(std::unique_ptr<apacket> p);
302     void HandleError(const std::string& error);
303 
304 #if ADB_HOST
SetUsbHandle(usb_handle * h)305     void SetUsbHandle(usb_handle* h) { usb_handle_ = h; }
GetUsbHandle()306     usb_handle* GetUsbHandle() { return usb_handle_; }
307 
308     // Interface for management/filter on forward:reverse: configuration.
309     void UpdateReverseConfig(std::string_view service_addr);
310     bool IsReverseConfigured(const std::string& local_addr);
311 #endif
312 
313     const TransportId id;
314 
315     bool online = false;
316     TransportType type = kTransportAny;
317 
318     // Used to identify transports for clients.
319     std::string serial;
320     std::string product;
321     std::string model;
322     std::string device;
323     std::string devpath;
324 
325     // If this is set, the transport will initiate the connection with a
326     // START_TLS command, instead of AUTH.
327     bool use_tls = false;
328     int tls_version = A_STLS_VERSION;
329     int get_tls_version() const;
330 
331 #if !ADB_HOST
332     // Used to provide the key to the framework.
333     std::string auth_key;
334     std::optional<uint64_t> auth_id;
335 #endif
336 
IsTcpDevice()337     bool IsTcpDevice() const { return type == kTransportLocal; }
338 
339 #if ADB_HOST
340     // The current key being authorized.
341     std::shared_ptr<RSA> Key();
342     std::shared_ptr<RSA> NextKey();
343     void ResetKeys();
344 #endif
345 
346     char token[TOKEN_SIZE] = {};
347     size_t failed_auth_attempts = 0;
348 
serial_name()349     std::string serial_name() const { return !serial.empty() ? serial : "<unknown>"; }
350 
351     void update_version(int version, size_t payload);
352     int get_protocol_version() const;
353     size_t get_max_payload() const;
354 
features()355     const FeatureSet& features() const { return features_; }
356 
357     bool has_feature(const std::string& feature) const;
358 
SupportsDelayedAck()359     bool SupportsDelayedAck() const {
360         return delayed_ack_;
361     }
362 
363     // Loads the transport's feature set from the given string.
364     void SetFeatures(const std::string& features_string);
365 
366     void AddDisconnect(adisconnect* disconnect);
367     void RemoveDisconnect(adisconnect* disconnect);
368     void RunDisconnects();
369 
370 #if ADB_HOST
371     bool Attach(std::string* error);
372     bool Detach(std::string* error);
373 #endif
374 
375 #if ADB_HOST
376     // Returns true if |target| matches this transport. A matching |target| can be any of:
377     //   * <serial>
378     //   * <devpath>
379     //   * product:<product>
380     //   * model:<model>
381     //   * device:<device>
382     //
383     // If this is a local transport, serial will also match [tcp:|udp:]<hostname>[:port] targets.
384     // For example, serial "100.100.100.100:5555" would match any of:
385     //   * 100.100.100.100
386     //   * tcp:100.100.100.100
387     //   * udp:100.100.100.100:5555
388     // This is to make it easier to use the same network target for both fastboot and adb.
389     bool MatchesTarget(const std::string& target) const;
390 
391     // Notifies that the atransport is no longer waiting for the connection
392     // being established.
393     void SetConnectionEstablished(bool success);
394 
395     // Gets a shared reference to the ConnectionWaitable.
connection_waitable()396     std::shared_ptr<ConnectionWaitable> connection_waitable() { return connection_waitable_; }
397 
398     // Attempts to reconnect with the underlying Connection.
399     ReconnectResult Reconnect();
400 #endif
401 
402   private:
403     std::atomic<bool> kicked_;
404 
405     // A set of features transmitted in the banner with the initial connection.
406     // This is stored in the banner as 'features=feature0,feature1,etc'.
407     FeatureSet features_;
408     int protocol_version;
409     size_t max_payload;
410 
411     // A list of adisconnect callbacks called when the transport is kicked.
412     std::list<adisconnect*> disconnects_;
413 
414     std::atomic<ConnectionState> connection_state_;
415 #if ADB_HOST
416     std::deque<std::shared_ptr<RSA>> keys_;
417 #endif
418 
419 #if ADB_HOST
420     // A sharable object that can be used to wait for the atransport's
421     // connection to be established.
422     std::shared_ptr<ConnectionWaitable> connection_waitable_;
423 #endif
424 
425     // The underlying connection object.
426     std::shared_ptr<Connection> connection_ GUARDED_BY(mutex_);
427 
428 #if ADB_HOST
429     // USB handle for the connection, if available.
430     usb_handle* usb_handle_ = nullptr;
431 #endif
432 
433     // A callback that will be invoked when the atransport needs to reconnect.
434     ReconnectCallback reconnect_;
435 
436     std::mutex mutex_;
437 
438     bool delayed_ack_ = false;
439 
440 #if ADB_HOST
441     // Track remote addresses against local addresses (configured)
442     // through `adb reverse` commands.
443     // Access constrained to primary thread by virtue of check_main_thread().
444     std::unordered_map<std::string, std::string> reverse_forwards_;
445 #endif
446 
447     DISALLOW_COPY_AND_ASSIGN(atransport);
448 };
449 
450 // --one-device command line parameter is eventually put here.
451 void transport_set_one_device(const char* adb_one_device);
452 
453 // Returns one device owned by this server of nullptr if all devices belong to server.
454 const char* transport_get_one_device();
455 
456 // Returns true if the adb server owns all devices, or `serial`.
457 bool transport_server_owns_device(std::string_view serial);
458 
459 // Returns true if the adb server owns all devices, `serial`, or `dev_path`.
460 bool transport_server_owns_device(std::string_view dev_path, std::string_view serial);
461 
462 /*
463  * Obtain a transport from the available transports.
464  * If serial is non-null then only the device with that serial will be chosen.
465  * If transport_id is non-zero then only the device with that transport ID will be chosen.
466  * If multiple devices/emulators would match, *is_ambiguous (if non-null)
467  * is set to true and nullptr returned.
468  * If no suitable transport is found, error is set and nullptr returned.
469  */
470 atransport* acquire_one_transport(TransportType type, const char* serial, TransportId transport_id,
471                                   bool* is_ambiguous, std::string* error_out,
472                                   bool accept_any_state = false);
473 void kick_transport(atransport* t, bool reset = false);
474 void update_transports(void);
475 
476 // Iterates across all of the current and pending transports.
477 // Stops iteration and returns false if fn returns false, otherwise returns true.
478 bool iterate_transports(std::function<bool(const atransport*)> fn);
479 
480 void init_reconnect_handler(void);
481 void init_mdns_transport_discovery(void);
482 
483 #if ADB_HOST
484 atransport* find_transport(const char* serial);
485 
486 void kick_all_tcp_devices();
487 #endif
488 
489 void kick_all_transports();
490 
491 void kick_all_tcp_tls_transports();
492 
493 #if !ADB_HOST
494 void kick_all_transports_by_auth_key(std::string_view auth_key);
495 #endif
496 
497 void register_transport(atransport* transport);
498 
499 #if ADB_HOST
500 void init_usb_transport(atransport* t, usb_handle* usb);
501 
502 void register_usb_transport(std::shared_ptr<Connection> connection, const char* serial,
503                             const char* devpath, unsigned writeable);
504 void register_usb_transport(usb_handle* h, const char* serial, const char* devpath,
505                             unsigned writeable);
506 
507 // This should only be used for transports with connection_state == kCsNoPerm.
508 void unregister_usb_transport(usb_handle* usb);
509 #endif
510 
511 /* Connect to a network address and register it as a device */
512 void connect_device(const std::string& address, std::string* response);
513 
514 /* cause new transports to be init'd and added to the list */
515 bool register_socket_transport(unique_fd s, std::string serial, int port, int local,
516                                atransport::ReconnectCallback reconnect, bool use_tls,
517                                int* error = nullptr);
518 
519 bool check_header(apacket* p, atransport* t);
520 
521 void close_usb_devices(bool reset = false);
522 void close_usb_devices(std::function<bool(const atransport*)> predicate, bool reset = false);
523 
524 void send_packet(apacket* p, atransport* t);
525 
526 #if ADB_HOST
527 enum TrackerOutputType { SHORT_TEXT, LONG_TEXT, PROTOBUF, TEXT_PROTOBUF };
528 asocket* create_device_tracker(TrackerOutputType type);
529 std::string list_transports(TrackerOutputType type);
530 #endif
531 
532 #if !ADB_HOST
533 unique_fd adb_listen(std::string_view addr, std::string* error);
534 void server_socket_thread(std::function<unique_fd(std::string_view, std::string*)> listen_func,
535                           std::string_view addr);
536 #endif
537 
538 #endif /* __TRANSPORT_H */
539