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