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