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