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