blob: ea97270b9bb23808737875aaf087d8b2dc9bf612 [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;
Dario Freni29814de2018-10-04 16:26:40 +010062// The server supports installing .apex packages.
63extern const char* const kFeatureApex;
David Pursell0955c662015-08-31 10:42:13 -070064
Josh Gaob122b172017-08-16 16:57:01 -070065TransportId NextTransportId();
66
Josh Gao0bbf69c2018-02-16 13:24:58 -080067// Abstraction for a non-blocking packet transport.
Josh Gaob800d882018-01-28 20:32:46 -080068struct Connection {
69 Connection() = default;
Josh Gaob800d882018-01-28 20:32:46 -080070 virtual ~Connection() = default;
71
Josh Gao0bbf69c2018-02-16 13:24:58 -080072 void SetTransportName(std::string transport_name) {
73 transport_name_ = std::move(transport_name);
74 }
75
76 using ReadCallback = std::function<bool(Connection*, std::unique_ptr<apacket>)>;
77 void SetReadCallback(ReadCallback callback) {
78 CHECK(!read_callback_);
79 read_callback_ = callback;
80 }
81
82 // Called after the Connection has terminated, either by an error or because Stop was called.
83 using ErrorCallback = std::function<void(Connection*, const std::string&)>;
84 void SetErrorCallback(ErrorCallback callback) {
85 CHECK(!error_callback_);
86 error_callback_ = callback;
87 }
88
89 virtual bool Write(std::unique_ptr<apacket> packet) = 0;
90
91 virtual void Start() = 0;
92 virtual void Stop() = 0;
93
94 std::string transport_name_;
95 ReadCallback read_callback_;
96 ErrorCallback error_callback_;
Josh Gao6082e7d2018-04-05 16:16:04 -070097
98 static std::unique_ptr<Connection> FromFd(unique_fd fd);
Josh Gao0bbf69c2018-02-16 13:24:58 -080099};
100
101// Abstraction for a blocking packet transport.
102struct BlockingConnection {
103 BlockingConnection() = default;
104 BlockingConnection(const BlockingConnection& copy) = delete;
105 BlockingConnection(BlockingConnection&& move) = delete;
106
107 // Destroy a BlockingConnection. Formerly known as 'Close' in atransport.
108 virtual ~BlockingConnection() = default;
109
Josh Gaob800d882018-01-28 20:32:46 -0800110 // Read/Write a packet. These functions are concurrently called from a transport's reader/writer
111 // threads.
112 virtual bool Read(apacket* packet) = 0;
113 virtual bool Write(apacket* packet) = 0;
114
115 // Terminate a connection.
116 // This method must be thread-safe, and must cause concurrent Reads/Writes to terminate.
117 // Formerly known as 'Kick' in atransport.
118 virtual void Close() = 0;
119};
120
Josh Gao0bbf69c2018-02-16 13:24:58 -0800121struct BlockingConnectionAdapter : public Connection {
122 explicit BlockingConnectionAdapter(std::unique_ptr<BlockingConnection> connection);
123
124 virtual ~BlockingConnectionAdapter();
125
126 virtual bool Write(std::unique_ptr<apacket> packet) override final;
127
128 virtual void Start() override final;
129 virtual void Stop() override final;
130
Josh Gaoc251ec52018-04-03 12:55:18 -0700131 bool started_ GUARDED_BY(mutex_) = false;
132 bool stopped_ GUARDED_BY(mutex_) = false;
Josh Gao0bbf69c2018-02-16 13:24:58 -0800133
134 std::unique_ptr<BlockingConnection> underlying_;
Josh Gaoc251ec52018-04-03 12:55:18 -0700135 std::thread read_thread_ GUARDED_BY(mutex_);
136 std::thread write_thread_ GUARDED_BY(mutex_);
Josh Gao0bbf69c2018-02-16 13:24:58 -0800137
Josh Gaoc251ec52018-04-03 12:55:18 -0700138 std::deque<std::unique_ptr<apacket>> write_queue_ GUARDED_BY(mutex_);
Josh Gao0bbf69c2018-02-16 13:24:58 -0800139 std::mutex mutex_;
140 std::condition_variable cv_;
141
142 std::once_flag error_flag_;
143};
144
145struct FdConnection : public BlockingConnection {
Josh Gaob800d882018-01-28 20:32:46 -0800146 explicit FdConnection(unique_fd fd) : fd_(std::move(fd)) {}
147
148 bool Read(apacket* packet) override final;
149 bool Write(apacket* packet) override final;
150
151 void Close() override;
152
153 private:
154 unique_fd fd_;
155};
156
Josh Gao0bbf69c2018-02-16 13:24:58 -0800157struct UsbConnection : public BlockingConnection {
Josh Gaob800d882018-01-28 20:32:46 -0800158 explicit UsbConnection(usb_handle* handle) : handle_(handle) {}
159 ~UsbConnection();
160
161 bool Read(apacket* packet) override final;
162 bool Write(apacket* packet) override final;
163
164 void Close() override final;
165
166 usb_handle* handle_;
167};
168
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700169// Waits for a transport's connection to be not pending. This is a separate
170// object so that the transport can be destroyed and another thread can be
171// notified of it in a race-free way.
172class ConnectionWaitable {
173 public:
174 ConnectionWaitable() = default;
175 ~ConnectionWaitable() = default;
176
177 // Waits until the first CNXN packet has been received by the owning
178 // atransport, or the specified timeout has elapsed. Can be called from any
179 // thread.
180 //
181 // Returns true if the CNXN packet was received in a timely fashion, false
182 // otherwise.
183 bool WaitForConnection(std::chrono::milliseconds timeout);
184
185 // Can be called from any thread when the connection stops being pending.
186 // Only the first invocation will be acknowledged, the rest will be no-ops.
187 void SetConnectionEstablished(bool success);
188
189 private:
190 bool connection_established_ GUARDED_BY(mutex_) = false;
191 bool connection_established_ready_ GUARDED_BY(mutex_) = false;
192 std::mutex mutex_;
193 std::condition_variable cv_;
194
195 DISALLOW_COPY_AND_ASSIGN(ConnectionWaitable);
196};
197
Josh Gaofc2e56f2018-08-30 11:37:00 -0700198enum class ReconnectResult {
199 Retry,
200 Success,
201 Abort,
202};
203
Dan Albert1792c232015-05-18 13:06:53 -0700204class atransport {
Josh Gaob122b172017-08-16 16:57:01 -0700205 public:
Dan Albert1792c232015-05-18 13:06:53 -0700206 // TODO(danalbert): We expose waaaaaaay too much stuff because this was
207 // historically just a struct, but making the whole thing a more idiomatic
208 // class in one go is a very large change. Given how bad our testing is,
209 // it's better to do this piece by piece.
210
Josh Gaofc2e56f2018-08-30 11:37:00 -0700211 using ReconnectCallback = std::function<ReconnectResult(atransport*)>;
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700212
213 atransport(ReconnectCallback reconnect, ConnectionState state)
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700214 : id(NextTransportId()),
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700215 kicked_(false),
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700216 connection_state_(state),
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700217 connection_waitable_(std::make_shared<ConnectionWaitable>()),
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700218 connection_(nullptr),
219 reconnect_(std::move(reconnect)) {
Tim Murrayde471942017-12-07 11:40:00 -0800220 // Initialize protocol to min version for compatibility with older versions.
221 // Version will be updated post-connect.
222 protocol_version = A_VERSION_MIN;
Dan Albert1792c232015-05-18 13:06:53 -0700223 max_payload = MAX_PAYLOAD;
224 }
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700225 atransport(ConnectionState state = kCsOffline)
Josh Gaofc2e56f2018-08-30 11:37:00 -0700226 : atransport([](atransport*) { return ReconnectResult::Abort; }, state) {}
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700227 virtual ~atransport();
Dan Albert1792c232015-05-18 13:06:53 -0700228
Yabin Cuib5e11412017-03-10 16:01:01 -0800229 int Write(apacket* p);
Yabin Cui7f274902016-04-18 11:22:34 -0700230 void Kick();
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700231 bool kicked() const { return kicked_; }
Dan Albert1792c232015-05-18 13:06:53 -0700232
Yabin Cuib5e11412017-03-10 16:01:01 -0800233 // ConnectionState can be read by all threads, but can only be written in the main thread.
234 ConnectionState GetConnectionState() const;
235 void SetConnectionState(ConnectionState state);
236
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700237 void SetConnection(std::unique_ptr<Connection> connection);
238 std::shared_ptr<Connection> connection() {
239 std::lock_guard<std::mutex> lock(mutex_);
240 return connection_;
241 }
242
Josh Gaob122b172017-08-16 16:57:01 -0700243 const TransportId id;
Josh Gaoe48ecce2017-09-13 13:40:57 -0700244 size_t ref_count = 0;
Dan Albert1792c232015-05-18 13:06:53 -0700245 bool online = false;
246 TransportType type = kTransportAny;
247
Dan Albert1792c232015-05-18 13:06:53 -0700248 // Used to identify transports for clients.
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700249 std::string serial;
250 std::string product;
251 std::string model;
252 std::string device;
253 std::string devpath;
Yabin Cuib74c6492016-04-29 16:53:52 -0700254
Josh Gaob800d882018-01-28 20:32:46 -0800255 bool IsTcpDevice() const { return type == kTransportLocal; }
Dan Albert1792c232015-05-18 13:06:53 -0700256
Josh Gao3bd28792016-10-05 19:02:29 -0700257#if ADB_HOST
Josh Gao2e671202016-08-18 22:00:12 -0700258 std::shared_ptr<RSA> NextKey();
Josh Gao3bd28792016-10-05 19:02:29 -0700259#endif
Elliott Hughes0aeb5052016-06-29 17:42:01 -0700260
Josh Gao06d61d42016-10-06 13:31:44 -0700261 char token[TOKEN_SIZE] = {};
Dan Albert1792c232015-05-18 13:06:53 -0700262 size_t failed_auth_attempts = 0;
263
Luis Hector Chavez6150a372018-07-18 21:18:27 -0700264 std::string serial_name() const { return !serial.empty() ? serial : "<unknown>"; }
Josh Gaoffbd3362018-02-28 14:44:23 -0800265 std::string connection_state_name() const;
Dan Albert1792c232015-05-18 13:06:53 -0700266
267 void update_version(int version, size_t payload);
268 int get_protocol_version() const;
269 size_t get_max_payload() const;
270
David Pursell4e2fd362015-09-22 10:43:08 -0700271 const FeatureSet& features() const {
Dan Albert1792c232015-05-18 13:06:53 -0700272 return features_;
273 }
274
275 bool has_feature(const std::string& feature) const;
David Pursell4e2fd362015-09-22 10:43:08 -0700276
277 // Loads the transport's feature set from the given string.
278 void SetFeatures(const std::string& features_string);
Dan Albert1792c232015-05-18 13:06:53 -0700279
Yabin Cuib3298242015-08-28 15:09:44 -0700280 void AddDisconnect(adisconnect* disconnect);
281 void RemoveDisconnect(adisconnect* disconnect);
282 void RunDisconnects();
283
David Pursell3f902aa2016-03-01 08:58:26 -0800284 // Returns true if |target| matches this transport. A matching |target| can be any of:
285 // * <serial>
286 // * <devpath>
287 // * product:<product>
288 // * model:<model>
289 // * device:<device>
290 //
291 // If this is a local transport, serial will also match [tcp:|udp:]<hostname>[:port] targets.
292 // For example, serial "100.100.100.100:5555" would match any of:
293 // * 100.100.100.100
294 // * tcp:100.100.100.100
295 // * udp:100.100.100.100:5555
296 // This is to make it easier to use the same network target for both fastboot and adb.
297 bool MatchesTarget(const std::string& target) const;
298
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700299 // Notifies that the atransport is no longer waiting for the connection
300 // being established.
301 void SetConnectionEstablished(bool success);
302
303 // Gets a shared reference to the ConnectionWaitable.
304 std::shared_ptr<ConnectionWaitable> connection_waitable() { return connection_waitable_; }
305
Josh Gaofc2e56f2018-08-30 11:37:00 -0700306 // Attempts to reconnect with the underlying Connection.
307 ReconnectResult Reconnect();
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700308
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700309 private:
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700310 std::atomic<bool> kicked_;
Yabin Cui7f274902016-04-18 11:22:34 -0700311
Dan Albert1792c232015-05-18 13:06:53 -0700312 // A set of features transmitted in the banner with the initial connection.
313 // This is stored in the banner as 'features=feature0,feature1,etc'.
314 FeatureSet features_;
315 int protocol_version;
316 size_t max_payload;
317
Yabin Cuib3298242015-08-28 15:09:44 -0700318 // A list of adisconnect callbacks called when the transport is kicked.
319 std::list<adisconnect*> disconnects_;
320
Yabin Cuib5e11412017-03-10 16:01:01 -0800321 std::atomic<ConnectionState> connection_state_;
Josh Gao3bd28792016-10-05 19:02:29 -0700322#if ADB_HOST
Josh Gao2e671202016-08-18 22:00:12 -0700323 std::deque<std::shared_ptr<RSA>> keys_;
Josh Gao3bd28792016-10-05 19:02:29 -0700324#endif
Elliott Hughes0aeb5052016-06-29 17:42:01 -0700325
Luis Hector Chavez56fe7532018-04-17 14:25:04 -0700326 // A sharable object that can be used to wait for the atransport's
327 // connection to be established.
328 std::shared_ptr<ConnectionWaitable> connection_waitable_;
329
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700330 // The underlying connection object.
331 std::shared_ptr<Connection> connection_ GUARDED_BY(mutex_);
332
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700333 // A callback that will be invoked when the atransport needs to reconnect.
334 ReconnectCallback reconnect_;
335
Luis Hector Chavez9a388d52018-04-25 08:56:41 -0700336 std::mutex mutex_;
337
Dan Albert1792c232015-05-18 13:06:53 -0700338 DISALLOW_COPY_AND_ASSIGN(atransport);
339};
340
Dan Albert76649012015-02-24 15:51:19 -0800341/*
342 * Obtain a transport from the available transports.
Elliott Hughes8d28e192015-10-07 14:55:10 -0700343 * If serial is non-null then only the device with that serial will be chosen.
Josh Gaob122b172017-08-16 16:57:01 -0700344 * If transport_id is non-zero then only the device with that transport ID will be chosen.
Elliott Hughes8d28e192015-10-07 14:55:10 -0700345 * If multiple devices/emulators would match, *is_ambiguous (if non-null)
346 * is set to true and nullptr returned.
347 * If no suitable transport is found, error is set and nullptr returned.
Dan Albert76649012015-02-24 15:51:19 -0800348 */
Josh Gaob122b172017-08-16 16:57:01 -0700349atransport* acquire_one_transport(TransportType type, const char* serial, TransportId transport_id,
350 bool* is_ambiguous, std::string* error_out,
351 bool accept_any_state = false);
Dan Albert76649012015-02-24 15:51:19 -0800352void kick_transport(atransport* t);
Dan Albert76649012015-02-24 15:51:19 -0800353void update_transports(void);
354
Josh Gaofd713e52017-05-03 22:37:10 -0700355// Iterates across all of the current and pending transports.
356// Stops iteration and returns false if fn returns false, otherwise returns true.
357bool iterate_transports(std::function<bool(const atransport*)> fn);
358
Luis Hector Chavez454bc7c2018-04-20 10:31:29 -0700359void init_reconnect_handler(void);
Dan Albert76649012015-02-24 15:51:19 -0800360void init_transport_registration(void);
Casey Dahlin13a269e2016-06-23 14:19:37 -0700361void init_mdns_transport_discovery(void);
Elliott Hughese67f1f82015-04-30 17:32:03 -0700362std::string list_transports(bool long_listing);
Dan Albert76649012015-02-24 15:51:19 -0800363atransport* find_transport(const char* serial);
Yabin Cuif4b99282015-08-27 12:03:11 -0700364void kick_all_tcp_devices();
Josh Gao01b7bc42017-05-09 13:43:35 -0700365void kick_all_transports();
Dan Albert76649012015-02-24 15:51:19 -0800366
Josh Gaoc51726c2018-10-11 16:33:05 -0700367void register_transport(atransport* transport);
Dan Albert76649012015-02-24 15:51:19 -0800368void register_usb_transport(usb_handle* h, const char* serial,
369 const char* devpath, unsigned writeable);
370
Casey Dahlin13a269e2016-06-23 14:19:37 -0700371/* Connect to a network address and register it as a device */
372void connect_device(const std::string& address, std::string* response);
373
Dan Albert76649012015-02-24 15:51:19 -0800374/* cause new transports to be init'd and added to the list */
Josh Gao362e6962018-08-08 16:20:14 -0700375bool register_socket_transport(unique_fd s, std::string serial, int port, int local,
376 atransport::ReconnectCallback reconnect, int* error = nullptr);
Dan Albert76649012015-02-24 15:51:19 -0800377
Dan Albertdcd78a12015-05-18 16:43:57 -0700378// This should only be used for transports with connection_state == kCsNoPerm.
Dan Albert76649012015-02-24 15:51:19 -0800379void unregister_usb_transport(usb_handle* usb);
380
Josh Gao36dadca2017-05-16 15:02:45 -0700381bool check_header(apacket* p, atransport* t);
Dan Albert76649012015-02-24 15:51:19 -0800382
Dan Albert76649012015-02-24 15:51:19 -0800383void close_usb_devices();
Josh Gao22d2b3e2016-10-27 14:01:08 -0700384void close_usb_devices(std::function<bool(const atransport*)> predicate);
Dan Albert76649012015-02-24 15:51:19 -0800385
386void send_packet(apacket* p, atransport* t);
387
Josh Gaob0c18022017-08-14 18:57:54 -0700388asocket* create_device_tracker(bool long_output);
Dan Albert76649012015-02-24 15:51:19 -0800389
JP Abgrall408fa572011-03-16 15:57:42 -0700390#endif /* __TRANSPORT_H */