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