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     // Return true if the transport successfully started.
119     virtual bool Start() = 0;
120     virtual void Stop() = 0;
121 
122     virtual bool DoTlsHandshake(RSA* key, std::string* auth_key = nullptr) = 0;
123 
124     // Stop, and reset the device if it's a USB connection.
125     virtual void Reset();
126 
AttachConnection127     virtual bool Attach(std::string* error) {
128         *error = "transport type doesn't support attach";
129         return false;
130     }
131 
DetachConnection132     virtual bool Detach(std::string* error) {
133         *error = "transport type doesn't support detach";
134         return false;
135     }
136 
137     std::string Serial() const;
138 
139     atransport* transport_ = nullptr;
140 
141     static std::unique_ptr<Connection> FromFd(unique_fd fd);
142 
NegotiatedSpeedMbpsConnection143     virtual uint64_t NegotiatedSpeedMbps() { return 0; }
MaxSpeedMbpsConnection144     virtual uint64_t MaxSpeedMbps() { return 0; }
145 };
146 
147 // Abstraction for a blocking packet transport.
148 struct BlockingConnection {
149     BlockingConnection() = default;
150     BlockingConnection(const BlockingConnection& copy) = delete;
151     BlockingConnection(BlockingConnection&& move) = delete;
152 
153     // Destroy a BlockingConnection. Formerly known as 'Close' in atransport.
154     virtual ~BlockingConnection() = default;
155 
156     // Read/Write a packet. These functions are concurrently called from a transport's reader/writer
157     // threads.
158     virtual bool Read(apacket* packet) = 0;
159     virtual bool Write(apacket* packet) = 0;
160 
161     virtual bool DoTlsHandshake(RSA* key, std::string* auth_key = nullptr) = 0;
162 
163     // Terminate a connection.
164     // This method must be thread-safe, and must cause concurrent Reads/Writes to terminate.
165     // Formerly known as 'Kick' in atransport.
166     virtual void Close() = 0;
167 
168     // Terminate a connection, and reset it.
169     virtual void Reset() = 0;
170 };
171 
172 struct BlockingConnectionAdapter : public Connection {
173     explicit BlockingConnectionAdapter(std::unique_ptr<BlockingConnection> connection);
174 
175     virtual ~BlockingConnectionAdapter();
176 
177     virtual bool Write(std::unique_ptr<apacket> packet) override final;
178 
179     virtual bool Start() override final;
180     virtual void Stop() override final;
181     virtual bool DoTlsHandshake(RSA* key, std::string* auth_key) override final;
182 
183     virtual void Reset() override final;
184 
185   private:
186     void StartReadThread() REQUIRES(mutex_);
187     bool started_ GUARDED_BY(mutex_) = false;
188     bool stopped_ GUARDED_BY(mutex_) = false;
189 
190     std::unique_ptr<BlockingConnection> underlying_;
191     std::thread read_thread_ GUARDED_BY(mutex_);
192     std::thread write_thread_ GUARDED_BY(mutex_);
193 
194     std::deque<std::unique_ptr<apacket>> write_queue_ GUARDED_BY(mutex_);
195     std::mutex mutex_;
196     std::condition_variable cv_;
197 
198     std::once_flag error_flag_;
199 };
200 
201 struct FdConnection : public BlockingConnection {
202     explicit FdConnection(unique_fd fd);
203     ~FdConnection();
204 
205     bool Read(apacket* packet) override final;
206     bool Write(apacket* packet) override final;
207     bool DoTlsHandshake(RSA* key, std::string* auth_key) override final;
208 
209     void Close() override;
ResetFdConnection210     virtual void Reset() override final { Close(); }
211 
212   private:
213     bool DispatchRead(void* buf, size_t len);
214     bool DispatchWrite(void* buf, size_t len);
215 
216     unique_fd fd_;
217     std::unique_ptr<adb::tls::TlsConnection> tls_;
218 };
219 
220 // Waits for a transport's connection to be not pending. This is a separate
221 // object so that the transport can be destroyed and another thread can be
222 // notified of it in a race-free way.
223 class ConnectionWaitable {
224   public:
225     ConnectionWaitable() = default;
226     ~ConnectionWaitable() = default;
227 
228     // Waits until the first CNXN packet has been received by the owning
229     // atransport, or the specified timeout has elapsed. Can be called from any
230     // thread.
231     //
232     // Returns true if the CNXN packet was received in a timely fashion, false
233     // otherwise.
234     bool WaitForConnection(std::chrono::milliseconds timeout);
235 
236     // Can be called from any thread when the connection stops being pending.
237     // Only the first invocation will be acknowledged, the rest will be no-ops.
238     void SetConnectionEstablished(bool success);
239 
240   private:
241     bool connection_established_ GUARDED_BY(mutex_) = false;
242     bool connection_established_ready_ GUARDED_BY(mutex_) = false;
243     std::mutex mutex_;
244     std::condition_variable cv_;
245 
246     DISALLOW_COPY_AND_ASSIGN(ConnectionWaitable);
247 };
248 
249 enum class ReconnectResult {
250     Retry,
251     Success,
252     Abort,
253 };
254 
255 #if ADB_HOST
256 struct usb_handle;
257 #endif
258 
259 class atransport : public enable_weak_from_this<atransport> {
260   public:
261     // TODO(danalbert): We expose waaaaaaay too much stuff because this was
262     // historically just a struct, but making the whole thing a more idiomatic
263     // class in one go is a very large change. Given how bad our testing is,
264     // it's better to do this piece by piece.
265 
266     using ReconnectCallback = std::function<ReconnectResult(atransport*)>;
267 
atransport(TransportType t,ReconnectCallback reconnect,ConnectionState state)268     atransport(TransportType t, ReconnectCallback reconnect, ConnectionState state)
269         : id(NextTransportId()),
270           type(t),
271           kicked_(false),
272           connection_state_(state),
273           connection_(nullptr),
274           reconnect_(std::move(reconnect)) {
275 #if ADB_HOST
276         connection_waitable_ = std::make_shared<ConnectionWaitable>();
277 #endif
278 
279         // Initialize protocol to min version for compatibility with older versions.
280         // Version will be updated post-connect.
281         protocol_version = A_VERSION_MIN;
282         max_payload = MAX_PAYLOAD;
283     }
284     atransport(TransportType t, ConnectionState state = kCsOffline)
285         : atransport(t, [](atransport*) { return ReconnectResult::Abort; }, state) {}
286     ~atransport();
287 
288     int Write(apacket* p);
289     void Reset();
290     void Kick();
kicked()291     bool kicked() const { return kicked_; }
292 
293     // ConnectionState can be read by all threads, but can only be written in the main thread.
294     ConnectionState GetConnectionState() const;
295     void SetConnectionState(ConnectionState state);
296 
297     void SetConnection(std::shared_ptr<Connection> connection);
connection()298     std::shared_ptr<Connection> connection() {
299         std::lock_guard<std::mutex> lock(mutex_);
300         return connection_;
301     }
302 
303     bool HandleRead(std::unique_ptr<apacket> p);
304     void HandleError(const std::string& error);
305 
306 #if ADB_HOST
SetUsbHandle(usb_handle * h)307     void SetUsbHandle(usb_handle* h) { usb_handle_ = h; }
GetUsbHandle()308     usb_handle* GetUsbHandle() { return usb_handle_; }
309 
310     // Interface for management/filter on forward:reverse: configuration.
311     void UpdateReverseConfig(std::string_view service_addr);
312     bool IsReverseConfigured(const std::string& local_addr);
313 #endif
314 
315     const TransportId id;
316 
317     bool online = false;
318     TransportType type = kTransportAny;
319 
320     // Used to identify transports for clients.
321     std::string serial;
322     std::string product;
323     std::string model;
324     std::string device;
325     std::string devpath;
326 
327     // If this is set, the transport will initiate the connection with a
328     // START_TLS command, instead of AUTH.
329     bool use_tls = false;
330     int tls_version = A_STLS_VERSION;
331     int get_tls_version() const;
332 
333 #if !ADB_HOST
334     // Used to provide the key to the framework.
335     std::string auth_key;
336     std::optional<uint64_t> auth_id;
337 #endif
338 
IsTcpDevice()339     bool IsTcpDevice() const { return type == kTransportLocal; }
340 
341 #if ADB_HOST
342     // The current key being authorized.
343     std::shared_ptr<RSA> Key();
344     std::shared_ptr<RSA> NextKey();
345     void ResetKeys();
346 #endif
347 
348     char token[TOKEN_SIZE] = {};
349     size_t failed_auth_attempts = 0;
350 
serial_name()351     std::string serial_name() const { return !serial.empty() ? serial : "<unknown>"; }
352 
353     void update_version(int version, size_t payload);
354     int get_protocol_version() const;
355     size_t get_max_payload() const;
356 
features()357     const FeatureSet& features() const { return features_; }
358 
359     bool has_feature(const std::string& feature) const;
360 
SupportsDelayedAck()361     bool SupportsDelayedAck() const {
362         return delayed_ack_;
363     }
364 
365     // Loads the transport's feature set from the given string.
366     void SetFeatures(const std::string& features_string);
367 
368     void AddDisconnect(adisconnect* disconnect);
369     void RemoveDisconnect(adisconnect* disconnect);
370     void RunDisconnects();
371 
372 #if ADB_HOST
373     bool Attach(std::string* error);
374     bool Detach(std::string* error);
375 #endif
376 
377 #if ADB_HOST
378     // Returns true if |target| matches this transport. A matching |target| can be any of:
379     //   * <serial>
380     //   * <devpath>
381     //   * product:<product>
382     //   * model:<model>
383     //   * device:<device>
384     //
385     // If this is a local transport, serial will also match [tcp:|udp:]<hostname>[:port] targets.
386     // For example, serial "100.100.100.100:5555" would match any of:
387     //   * 100.100.100.100
388     //   * tcp:100.100.100.100
389     //   * udp:100.100.100.100:5555
390     // This is to make it easier to use the same network target for both fastboot and adb.
391     bool MatchesTarget(const std::string& target) const;
392 
393     // Notifies that the atransport is no longer waiting for the connection
394     // being established.
395     void SetConnectionEstablished(bool success);
396 
397     // Gets a shared reference to the ConnectionWaitable.
connection_waitable()398     std::shared_ptr<ConnectionWaitable> connection_waitable() { return connection_waitable_; }
399 
400     // Attempts to reconnect with the underlying Connection.
401     ReconnectResult Reconnect();
402 #endif
403 
404   private:
405     std::atomic<bool> kicked_;
406 
407     // A set of features transmitted in the banner with the initial connection.
408     // This is stored in the banner as 'features=feature0,feature1,etc'.
409     FeatureSet features_;
410     int protocol_version;
411     size_t max_payload;
412 
413     // A list of adisconnect callbacks called when the transport is kicked.
414     std::list<adisconnect*> disconnects_;
415 
416     std::atomic<ConnectionState> connection_state_;
417 #if ADB_HOST
418     std::deque<std::shared_ptr<RSA>> keys_;
419 #endif
420 
421 #if ADB_HOST
422     // A sharable object that can be used to wait for the atransport's
423     // connection to be established.
424     std::shared_ptr<ConnectionWaitable> connection_waitable_;
425 #endif
426 
427     // The underlying connection object.
428     std::shared_ptr<Connection> connection_ GUARDED_BY(mutex_);
429 
430 #if ADB_HOST
431     // USB handle for the connection, if available.
432     usb_handle* usb_handle_ = nullptr;
433 #endif
434 
435     // A callback that will be invoked when the atransport needs to reconnect.
436     ReconnectCallback reconnect_;
437 
438     std::mutex mutex_;
439 
440     bool delayed_ack_ = false;
441 
442 #if ADB_HOST
443     // Track remote addresses against local addresses (configured)
444     // through `adb reverse` commands.
445     // Access constrained to primary thread by virtue of check_main_thread().
446     std::unordered_map<std::string, std::string> reverse_forwards_;
447 #endif
448 
449     DISALLOW_COPY_AND_ASSIGN(atransport);
450 };
451 
452 // --one-device command line parameter is eventually put here.
453 void transport_set_one_device(const char* adb_one_device);
454 
455 // Returns one device owned by this server of nullptr if all devices belong to server.
456 const char* transport_get_one_device();
457 
458 // Returns true if the adb server owns all devices, or `serial`.
459 bool transport_server_owns_device(std::string_view serial);
460 
461 // Returns true if the adb server owns all devices, `serial`, or `dev_path`.
462 bool transport_server_owns_device(std::string_view dev_path, std::string_view serial);
463 
464 /*
465  * Obtain a transport from the available transports.
466  * If serial is non-null then only the device with that serial will be chosen.
467  * If transport_id is non-zero then only the device with that transport ID will be chosen.
468  * If multiple devices/emulators would match, *is_ambiguous (if non-null)
469  * is set to true and nullptr returned.
470  * If no suitable transport is found, error is set and nullptr returned.
471  */
472 atransport* acquire_one_transport(TransportType type, const char* serial, TransportId transport_id,
473                                   bool* is_ambiguous, std::string* error_out,
474                                   bool accept_any_state = false);
475 void kick_transport(atransport* t, bool reset = false);
476 void update_transports();
477 
478 // Iterates across all of the current and pending transports.
479 // Stops iteration and returns false if fn returns false, otherwise returns true.
480 bool iterate_transports(std::function<bool(const atransport*)> fn);
481 
482 void init_reconnect_handler();
483 void init_mdns_transport_discovery();
484 
485 #if ADB_HOST
486 atransport* find_transport(const char* serial);
487 
488 void kick_all_tcp_devices();
489 
490 bool using_bonjour(void);
491 #endif
492 
493 void kick_all_transports();
494 
495 void kick_all_tcp_tls_transports();
496 
497 #if !ADB_HOST
498 void kick_all_transports_by_auth_key(std::string_view auth_key);
499 #endif
500 
501 void register_transport(atransport* transport);
502 
503 #if ADB_HOST
504 void init_usb_transport(atransport* t, usb_handle* usb);
505 
506 void register_libusb_transport(std::shared_ptr<Connection> connection, const char* serial,
507                                const char* devpath, unsigned writable);
508 
509 void register_usb_transport(usb_handle* h, const char* serial, const char* devpath,
510                             unsigned writeable);
511 
512 // This should only be used for transports with connection_state == kCsNoPerm.
513 void unregister_usb_transport(usb_handle* usb);
514 #endif
515 
516 /* Connect to a network address and register it as a device */
517 void connect_device(const std::string& address, std::string* response);
518 
519 /* initialize a transport object's func pointers and state */
520 int init_socket_transport(atransport* t, unique_fd s, int port, bool is_emulator);
521 
522 /* cause new transports to be init'd and added to the list */
523 bool register_socket_transport(unique_fd s, std::string serial, int port, bool is_emulator,
524                                atransport::ReconnectCallback reconnect, bool use_tls,
525                                int* error = nullptr);
526 
527 bool check_header(apacket* p, atransport* t);
528 
529 void close_usb_devices(bool reset = false);
530 void close_usb_devices(std::function<bool(const atransport*)> predicate, bool reset = false);
531 
532 void send_packet(apacket* p, atransport* t);
533 
534 #if ADB_HOST
535 enum TrackerOutputType { SHORT_TEXT, LONG_TEXT, PROTOBUF, TEXT_PROTOBUF };
536 asocket* create_device_tracker(TrackerOutputType type);
537 std::string list_transports(TrackerOutputType type);
538 #endif
539 
540 #endif /* __TRANSPORT_H */
541