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