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