blob: cb20615102e5610f2dcbd4f0dad9ad637c62fcf5 [file] [log] [blame]
JP Abgrall408fa572011-03-16 15:57:42 -07001/*
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
Dan Alberte9fca142015-02-18 18:03:26 -080020#include <sys/types.h>
21
Yabin Cuib5e11412017-03-10 16:01:01 -080022#include <atomic>
Luis Hector Chavez56fe7532018-04-17 14:25:04 -070023#include <chrono>
Josh Gao0bbf69c2018-02-16 13:24:58 -080024#include <condition_variable>
Elliott Hughes0aeb5052016-06-29 17:42:01 -070025#include <deque>
Josh Gao22d2b3e2016-10-27 14:01:08 -070026#include <functional>
Yabin Cuib3298242015-08-28 15:09:44 -070027#include <list>
Josh Gao2e671202016-08-18 22:00:12 -070028#include <memory>
Yabin Cuib5e11412017-03-10 16:01:01 -080029#include <mutex>
Elliott Hughes7be29c82015-04-16 22:54:44 -070030#include <string>
Josh Gao0bbf69c2018-02-16 13:24:58 -080031#include <thread>
Dan Albert1792c232015-05-18 13:06:53 -070032#include <unordered_set>
Dan Albert76649012015-02-24 15:51:19 -080033
Luis Hector Chavez56fe7532018-04-17 14:25:04 -070034#include <android-base/macros.h>
Josh Gaoc251ec52018-04-03 12:55:18 -070035#include <android-base/thread_annotations.h>
Elliott Hughes0aeb5052016-06-29 17:42:01 -070036#include <openssl/rsa.h>
37
Josh Gaob800d882018-01-28 20:32:46 -080038#include "adb.h"
39#include "adb_unique_fd.h"
40
Dan Albert1792c232015-05-18 13:06:53 -070041typedef std::unordered_set<std::string> FeatureSet;
42
43const FeatureSet& supported_features();
44
David Pursell4e2fd362015-09-22 10:43:08 -070045// Encodes and decodes FeatureSet objects into human-readable strings.
46std::string FeatureSetToString(const FeatureSet& features);
47FeatureSet StringToFeatureSet(const std::string& features_string);
48
David Pursell70ef7b42015-09-30 13:35:42 -070049// Returns true if both local features and |feature_set| support |feature|.
50bool CanUseFeature(const FeatureSet& feature_set, const std::string& feature);
51
David Pursell4e2fd362015-09-22 10:43:08 -070052// Do not use any of [:;=,] in feature strings, they have special meaning
53// in the connection banner.
Todd Kennedy6fa848a2015-11-03 16:53:08 -080054extern const char* const kFeatureShell2;
55// The 'cmd' command is available
56extern const char* const kFeatureCmd;
Josh Gao5a1e3fd2016-12-05 17:11:34 -080057extern const char* const kFeatureStat2;
Josh Gao5d1756c2017-02-22 17:07:01 -080058// The server is running with libusb enabled.
59extern const char* const kFeatureLibusb;
Dan Albert5176df82017-05-23 14:30:00 -070060// The server supports `push --sync`.
61extern const char* const kFeaturePushSync;
David Pursell0955c662015-08-31 10:42:13 -070062
Josh Gaob122b172017-08-16 16:57:01 -070063TransportId NextTransportId();
64
Josh Gao0bbf69c2018-02-16 13:24:58 -080065// Abstraction for a non-blocking packet transport.
Josh Gaob800d882018-01-28 20:32:46 -080066struct Connection {
67 Connection() = default;
Josh Gaob800d882018-01-28 20:32:46 -080068 virtual ~Connection() = default;
69
Josh Gao0bbf69c2018-02-16 13:24:58 -080070 void SetTransportName(std::string transport_name) {
71 transport_name_ = std::move(transport_name);
72 }
73
74 using ReadCallback = std::function<bool(Connection*, std::unique_ptr<apacket>)>;
75 void SetReadCallback(ReadCallback callback) {
76 CHECK(!read_callback_);
77 read_callback_ = callback;
78 }
79
80 // Called after the Connection has terminated, either by an error or because Stop was called.
81 using ErrorCallback = std::function<void(Connection*, const std::string&)>;
82 void SetErrorCallback(ErrorCallback callback) {
83 CHECK(!error_callback_);
84 error_callback_ = callback;
85 }
86
87 virtual bool Write(std::unique_ptr<apacket> packet) = 0;
88
89 virtual void Start() = 0;
90 virtual void Stop() = 0;
91
92 std::string transport_name_;
93 ReadCallback read_callback_;
94 ErrorCallback error_callback_;
Josh Gao6082e7d2018-04-05 16:16:04 -070095
96 static std::unique_ptr<Connection> FromFd(unique_fd fd);
Josh Gao0bbf69c2018-02-16 13:24:58 -080097};
98
99// Abstraction for a blocking packet transport.
100struct BlockingConnection {
101 BlockingConnection() = default;
102 BlockingConnection(const BlockingConnection& copy) = delete;
103 BlockingConnection(BlockingConnection&& move) = delete;
104
105 // Destroy a BlockingConnection. Formerly known as 'Close' in atransport.
106 virtual ~BlockingConnection() = default;
107
Josh Gaob800d882018-01-28 20:32:46 -0800108 // Read/Write a packet. These functions are concurrently called from a transport's reader/writer
109 // threads.
110 virtual bool Read(apacket* packet) = 0;
111 virtual bool Write(apacket* packet) = 0;
112
113 // Terminate a connection.
114 // This method must be thread-safe, and must cause concurrent Reads/Writes to terminate.
115 // Formerly known as 'Kick' in atransport.
116 virtual void Close() = 0;
117};
118
Josh Gao0bbf69c2018-02-16 13:24:58 -0800119struct BlockingConnectionAdapter : public Connection {
120 explicit BlockingConnectionAdapter(std::unique_ptr<BlockingConnection> connection);
121
122 virtual ~BlockingConnectionAdapter();
123
124 virtual bool Write(std::unique_ptr<apacket> packet) override final;
125
126 virtual void Start() override final;
127 virtual void Stop() override final;
128
Josh Gaoc251ec52018-04-03 12:55:18 -0700129 bool started_ GUARDED_BY(mutex_) = false;
130 bool stopped_ GUARDED_BY(mutex_) = false;
Josh Gao0bbf69c2018-02-16 13:24:58 -0800131
132 std::unique_ptr<BlockingConnection> underlying_;
Josh Gaoc251ec52018-04-03 12:55:18 -0700133 std::thread read_thread_ GUARDED_BY(mutex_);
134 std::thread write_thread_ GUARDED_BY(mutex_);
Josh Gao0bbf69c2018-02-16 13:24:58 -0800135
Josh Gaoc251ec52018-04-03 12:55:18 -0700136 std::deque<std::unique_ptr<apacket>> write_queue_ GUARDED_BY(mutex_);
Josh Gao0bbf69c2018-02-16 13:24:58 -0800137 std::mutex mutex_;
138 std::condition_variable cv_;
139
140 std::once_flag error_flag_;
141};
142
143struct FdConnection : public BlockingConnection {
Josh Gaob800d882018-01-28 20:32:46 -0800144 explicit FdConnection(unique_fd fd) : fd_(std::move(fd)) {}
145
146 bool Read(apacket* packet) override final;
147 bool Write(apacket* packet) override final;
148
149 void Close() override;
150
151 private:
152 unique_fd fd_;
153};
154
Josh Gao0bbf69c2018-02-16 13:24:58 -0800155struct UsbConnection : public BlockingConnection {
Josh Gaob800d882018-01-28 20:32:46 -0800156 explicit UsbConnection(usb_handle* handle) : handle_(handle) {}
157 ~UsbConnection();
158
159 bool Read(apacket* packet) override final;
160 bool Write(apacket* packet) override final;
161
162 void Close() override final;
163
164 usb_handle* handle_;
165};
166
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700167// Waits for a transport's connection to be not pending. This is a separate
168// object so that the transport can be destroyed and another thread can be
169// notified of it in a race-free way.
170class ConnectionWaitable {
171 public:
172 ConnectionWaitable() = default;
173 ~ConnectionWaitable() = default;
174
175 // Waits until the first CNXN packet has been received by the owning
176 // atransport, or the specified timeout has elapsed. Can be called from any
177 // thread.
178 //
179 // Returns true if the CNXN packet was received in a timely fashion, false
180 // otherwise.
181 bool WaitForConnection(std::chrono::milliseconds timeout);
182
183 // Can be called from any thread when the connection stops being pending.
184 // Only the first invocation will be acknowledged, the rest will be no-ops.
185 void SetConnectionEstablished(bool success);
186
187 private:
188 bool connection_established_ GUARDED_BY(mutex_) = false;
189 bool connection_established_ready_ GUARDED_BY(mutex_) = false;
190 std::mutex mutex_;
191 std::condition_variable cv_;
192
193 DISALLOW_COPY_AND_ASSIGN(ConnectionWaitable);
194};
195
Dan Albert1792c232015-05-18 13:06:53 -0700196class atransport {
Josh Gaob122b172017-08-16 16:57:01 -0700197 public:
Dan Albert1792c232015-05-18 13:06:53 -0700198 // TODO(danalbert): We expose waaaaaaay too much stuff because this was
199 // historically just a struct, but making the whole thing a more idiomatic
200 // class in one go is a very large change. Given how bad our testing is,
201 // it's better to do this piece by piece.
202
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700203 using ReconnectCallback = std::function<bool(atransport*)>;
204
205 atransport(ReconnectCallback reconnect, ConnectionState state)
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700206 : id(NextTransportId()),
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700207 kicked_(false),
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700208 connection_state_(state),
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700209 connection_waitable_(std::make_shared<ConnectionWaitable>()),
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700210 connection_(nullptr),
211 reconnect_(std::move(reconnect)) {
Tim Murrayde471942017-12-07 11:40:00 -0800212 // Initialize protocol to min version for compatibility with older versions.
213 // Version will be updated post-connect.
214 protocol_version = A_VERSION_MIN;
Dan Albert1792c232015-05-18 13:06:53 -0700215 max_payload = MAX_PAYLOAD;
216 }
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700217 atransport(ConnectionState state = kCsOffline)
218 : atransport([](atransport*) { return false; }, state) {}
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700219 virtual ~atransport();
Dan Albert1792c232015-05-18 13:06:53 -0700220
Yabin Cuib5e11412017-03-10 16:01:01 -0800221 int Write(apacket* p);
Yabin Cui7f274902016-04-18 11:22:34 -0700222 void Kick();
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700223 bool kicked() const { return kicked_; }
Dan Albert1792c232015-05-18 13:06:53 -0700224
Yabin Cuib5e11412017-03-10 16:01:01 -0800225 // ConnectionState can be read by all threads, but can only be written in the main thread.
226 ConnectionState GetConnectionState() const;
227 void SetConnectionState(ConnectionState state);
228
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700229 void SetConnection(std::unique_ptr<Connection> connection);
230 std::shared_ptr<Connection> connection() {
231 std::lock_guard<std::mutex> lock(mutex_);
232 return connection_;
233 }
234
Josh Gaob122b172017-08-16 16:57:01 -0700235 const TransportId id;
Josh Gaoe48ecce2017-09-13 13:40:57 -0700236 size_t ref_count = 0;
Dan Albert1792c232015-05-18 13:06:53 -0700237 bool online = false;
238 TransportType type = kTransportAny;
239
Dan Albert1792c232015-05-18 13:06:53 -0700240 // Used to identify transports for clients.
241 char* serial = nullptr;
242 char* product = nullptr;
243 char* model = nullptr;
244 char* device = nullptr;
245 char* devpath = nullptr;
Yabin Cuib74c6492016-04-29 16:53:52 -0700246
Josh Gaob800d882018-01-28 20:32:46 -0800247 bool IsTcpDevice() const { return type == kTransportLocal; }
Dan Albert1792c232015-05-18 13:06:53 -0700248
Josh Gao3bd28792016-10-05 19:02:29 -0700249#if ADB_HOST
Josh Gao2e671202016-08-18 22:00:12 -0700250 std::shared_ptr<RSA> NextKey();
Josh Gao3bd28792016-10-05 19:02:29 -0700251#endif
Elliott Hughes0aeb5052016-06-29 17:42:01 -0700252
Josh Gao06d61d42016-10-06 13:31:44 -0700253 char token[TOKEN_SIZE] = {};
Dan Albert1792c232015-05-18 13:06:53 -0700254 size_t failed_auth_attempts = 0;
255
Josh Gaoffbd3362018-02-28 14:44:23 -0800256 std::string serial_name() const { return serial ? serial : "<unknown>"; }
257 std::string connection_state_name() const;
Dan Albert1792c232015-05-18 13:06:53 -0700258
259 void update_version(int version, size_t payload);
260 int get_protocol_version() const;
261 size_t get_max_payload() const;
262
David Pursell4e2fd362015-09-22 10:43:08 -0700263 const FeatureSet& features() const {
Dan Albert1792c232015-05-18 13:06:53 -0700264 return features_;
265 }
266
267 bool has_feature(const std::string& feature) const;
David Pursell4e2fd362015-09-22 10:43:08 -0700268
269 // Loads the transport's feature set from the given string.
270 void SetFeatures(const std::string& features_string);
Dan Albert1792c232015-05-18 13:06:53 -0700271
Yabin Cuib3298242015-08-28 15:09:44 -0700272 void AddDisconnect(adisconnect* disconnect);
273 void RemoveDisconnect(adisconnect* disconnect);
274 void RunDisconnects();
275
David Pursell3f902aa2016-03-01 08:58:26 -0800276 // Returns true if |target| matches this transport. A matching |target| can be any of:
277 // * <serial>
278 // * <devpath>
279 // * product:<product>
280 // * model:<model>
281 // * device:<device>
282 //
283 // If this is a local transport, serial will also match [tcp:|udp:]<hostname>[:port] targets.
284 // For example, serial "100.100.100.100:5555" would match any of:
285 // * 100.100.100.100
286 // * tcp:100.100.100.100
287 // * udp:100.100.100.100:5555
288 // This is to make it easier to use the same network target for both fastboot and adb.
289 bool MatchesTarget(const std::string& target) const;
290
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700291 // Notifies that the atransport is no longer waiting for the connection
292 // being established.
293 void SetConnectionEstablished(bool success);
294
295 // Gets a shared reference to the ConnectionWaitable.
296 std::shared_ptr<ConnectionWaitable> connection_waitable() { return connection_waitable_; }
297
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700298 // Attempts to reconnect with the underlying Connection. Returns true if the
299 // reconnection attempt succeeded.
300 bool Reconnect();
301
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700302 private:
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700303 std::atomic<bool> kicked_;
Yabin Cui7f274902016-04-18 11:22:34 -0700304
Dan Albert1792c232015-05-18 13:06:53 -0700305 // A set of features transmitted in the banner with the initial connection.
306 // This is stored in the banner as 'features=feature0,feature1,etc'.
307 FeatureSet features_;
308 int protocol_version;
309 size_t max_payload;
310
Yabin Cuib3298242015-08-28 15:09:44 -0700311 // A list of adisconnect callbacks called when the transport is kicked.
312 std::list<adisconnect*> disconnects_;
313
Yabin Cuib5e11412017-03-10 16:01:01 -0800314 std::atomic<ConnectionState> connection_state_;
Josh Gao3bd28792016-10-05 19:02:29 -0700315#if ADB_HOST
Josh Gao2e671202016-08-18 22:00:12 -0700316 std::deque<std::shared_ptr<RSA>> keys_;
Josh Gao3bd28792016-10-05 19:02:29 -0700317#endif
Elliott Hughes0aeb5052016-06-29 17:42:01 -0700318
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700319 // A sharable object that can be used to wait for the atransport's
320 // connection to be established.
321 std::shared_ptr<ConnectionWaitable> connection_waitable_;
322
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700323 // The underlying connection object.
324 std::shared_ptr<Connection> connection_ GUARDED_BY(mutex_);
325
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700326 // A callback that will be invoked when the atransport needs to reconnect.
327 ReconnectCallback reconnect_;
328
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700329 std::mutex mutex_;
330
Dan Albert1792c232015-05-18 13:06:53 -0700331 DISALLOW_COPY_AND_ASSIGN(atransport);
332};
333
Dan Albert76649012015-02-24 15:51:19 -0800334/*
335 * Obtain a transport from the available transports.
Elliott Hughes8d28e192015-10-07 14:55:10 -0700336 * If serial is non-null then only the device with that serial will be chosen.
Josh Gaob122b172017-08-16 16:57:01 -0700337 * If transport_id is non-zero then only the device with that transport ID will be chosen.
Elliott Hughes8d28e192015-10-07 14:55:10 -0700338 * If multiple devices/emulators would match, *is_ambiguous (if non-null)
339 * is set to true and nullptr returned.
340 * If no suitable transport is found, error is set and nullptr returned.
Dan Albert76649012015-02-24 15:51:19 -0800341 */
Josh Gaob122b172017-08-16 16:57:01 -0700342atransport* acquire_one_transport(TransportType type, const char* serial, TransportId transport_id,
343 bool* is_ambiguous, std::string* error_out,
344 bool accept_any_state = false);
Dan Albert76649012015-02-24 15:51:19 -0800345void kick_transport(atransport* t);
Dan Albert76649012015-02-24 15:51:19 -0800346void update_transports(void);
347
Josh Gaofd713e52017-05-03 22:37:10 -0700348// Iterates across all of the current and pending transports.
349// Stops iteration and returns false if fn returns false, otherwise returns true.
350bool iterate_transports(std::function<bool(const atransport*)> fn);
351
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700352void init_reconnect_handler(void);
Dan Albert76649012015-02-24 15:51:19 -0800353void init_transport_registration(void);
Casey Dahlin13a269e2016-06-23 14:19:37 -0700354void init_mdns_transport_discovery(void);
Elliott Hughese67f1f82015-04-30 17:32:03 -0700355std::string list_transports(bool long_listing);
Dan Albert76649012015-02-24 15:51:19 -0800356atransport* find_transport(const char* serial);
Yabin Cuif4b99282015-08-27 12:03:11 -0700357void kick_all_tcp_devices();
Josh Gao01b7bc42017-05-09 13:43:35 -0700358void kick_all_transports();
Dan Albert76649012015-02-24 15:51:19 -0800359
360void register_usb_transport(usb_handle* h, const char* serial,
361 const char* devpath, unsigned writeable);
362
Casey Dahlin13a269e2016-06-23 14:19:37 -0700363/* Connect to a network address and register it as a device */
364void connect_device(const std::string& address, std::string* response);
365
Dan Albert76649012015-02-24 15:51:19 -0800366/* cause new transports to be init'd and added to the list */
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700367int register_socket_transport(int s, const char* serial, int port, int local,
368 atransport::ReconnectCallback reconnect);
Dan Albert76649012015-02-24 15:51:19 -0800369
Dan Albertdcd78a12015-05-18 16:43:57 -0700370// This should only be used for transports with connection_state == kCsNoPerm.
Dan Albert76649012015-02-24 15:51:19 -0800371void unregister_usb_transport(usb_handle* usb);
372
Josh Gao36dadca2017-05-16 15:02:45 -0700373bool check_header(apacket* p, atransport* t);
Dan Albert76649012015-02-24 15:51:19 -0800374
Dan Albert76649012015-02-24 15:51:19 -0800375void close_usb_devices();
Josh Gao22d2b3e2016-10-27 14:01:08 -0700376void close_usb_devices(std::function<bool(const atransport*)> predicate);
Dan Albert76649012015-02-24 15:51:19 -0800377
378void send_packet(apacket* p, atransport* t);
379
Josh Gaob0c18022017-08-14 18:57:54 -0700380asocket* create_device_tracker(bool long_output);
Dan Albert76649012015-02-24 15:51:19 -0800381
JP Abgrall408fa572011-03-16 15:57:42 -0700382#endif /* __TRANSPORT_H */