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