1 /*
2  * Copyright (C) 2007 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 #pragma once
18 
19 #include <limits.h>
20 #include <stdint.h>
21 #include <sys/types.h>
22 
23 #include <functional>
24 #include <string>
25 
26 #include <android-base/macros.h>
27 
28 #include "adb_trace.h"
29 #include "fdevent/fdevent.h"
30 #include "socket.h"
31 #include "types.h"
32 
33 constexpr size_t MAX_PAYLOAD_V1 = 4 * 1024;
34 constexpr size_t MAX_PAYLOAD = 1024 * 1024;
35 
36 // When delayed acks are supported, the initial number of unacknowledged bytes we're willing to
37 // receive on a socket before the other side should block.
38 constexpr size_t INITIAL_DELAYED_ACK_BYTES = 32 * 1024 * 1024;
39 
40 constexpr size_t LINUX_MAX_SOCKET_SIZE = 4194304;
41 
42 #define A_SYNC 0x434e5953
43 #define A_CNXN 0x4e584e43
44 #define A_OPEN 0x4e45504f
45 #define A_OKAY 0x59414b4f
46 #define A_CLSE 0x45534c43
47 #define A_WRTE 0x45545257
48 #define A_AUTH 0x48545541
49 #define A_STLS 0x534C5453
50 std::string command_to_string(uint32_t cmd);
51 
52 // ADB protocol version.
53 // Version revision:
54 // 0x01000000: original
55 // 0x01000001: skip checksum (Dec 2017)
56 #define A_VERSION_MIN 0x01000000
57 #define A_VERSION_SKIP_CHECKSUM 0x01000001
58 #define A_VERSION 0x01000001
59 
60 // Stream-based TLS protocol version
61 #define A_STLS_VERSION_MIN 0x01000000
62 #define A_STLS_VERSION 0x01000000
63 
64 // Used for help/version information.
65 #define ADB_VERSION_MAJOR 1
66 #define ADB_VERSION_MINOR 0
67 
68 std::string adb_version();
69 
70 // Increment this when we want to force users to start a new adb server.
71 #define ADB_SERVER_VERSION 41
72 
73 using TransportId = uint64_t;
74 class atransport;
75 
76 uint32_t calculate_apacket_checksum(const apacket* packet);
77 
78 /* the adisconnect structure is used to record a callback that
79 ** will be called whenever a transport is disconnected (e.g. by the user)
80 ** this should be used to cleanup objects that depend on the
81 ** transport (e.g. remote sockets, listeners, etc...)
82 */
83 struct adisconnect {
84     void (*func)(void* opaque, atransport* t);
85     void* opaque;
86 };
87 
88 // A transport object models the connection to a remote device or emulator there
89 // is one transport per connected device/emulator. A "local transport" connects
90 // through TCP (for the emulator), while a "usb transport" through USB (for real
91 // devices).
92 //
93 // Note that kTransportHost doesn't really correspond to a real transport
94 // object, it's a special value used to indicate that a client wants to connect
95 // to a service implemented within the ADB server itself.
96 enum TransportType {
97     kTransportUsb,
98     kTransportLocal,
99     kTransportAny,
100     kTransportHost,
101 };
102 
103 #define TOKEN_SIZE 20
104 
105 enum ConnectionState {
106     kCsAny = -1,
107 
108     kCsConnecting = 0,  // Haven't received a response from the device yet.
109     kCsAuthorizing,     // Authorizing with keys from ADB_VENDOR_KEYS.
110     kCsUnauthorized,    // ADB_VENDOR_KEYS exhausted, fell back to user prompt.
111     kCsNoPerm,          // Insufficient permissions to communicate with the device.
112     kCsDetached,        // USB device detached from the adb server (known but not opened/claimed).
113     kCsOffline,         // A peer has been detected (device/host) but no comm has started yet.
114 
115     // After CNXN packet, the ConnectionState describes not a state but the type of service
116     // on the other end of the transport.
117     kCsBootloader,  // Device running fastboot OS (fastboot) or userspace fastboot (fastbootd).
118     kCsDevice,      // Device running Android OS (adbd).
119     kCsHost,        // What a device sees from its end of a Transport (adb host).
120     kCsRecovery,    // Device with bootloader loaded but no ROM OS loaded (adbd).
121     kCsSideload,    // Device running Android OS Sideload mode (minadbd sideload mode).
122     kCsRescue,      // Device running Android OS Rescue mode (minadbd rescue mode).
123 };
124 
125 std::string to_string(ConnectionState state);
126 
ConnectionStateIsOnline(ConnectionState state)127 inline bool ConnectionStateIsOnline(ConnectionState state) {
128     switch (state) {
129         case kCsBootloader:
130         case kCsDevice:
131         case kCsHost:
132         case kCsRecovery:
133         case kCsSideload:
134         case kCsRescue:
135             return true;
136         default:
137             return false;
138     }
139 }
140 
141 void print_packet(const char* label, apacket* p);
142 
143 void handle_packet(apacket* p, atransport* t);
144 
145 bool is_one_device_mandatory();
146 int launch_server(const std::string& socket_spec, const char* one_device);
147 int adb_server_main(int is_daemon, const std::string& socket_spec, const char* one_device,
148                     int ack_reply_fd);
149 
150 std::string getEmulatorSerialString(int console_port);
151 #if ADB_HOST
152 atransport* find_emulator_transport_by_adb_port(int adb_port);
153 atransport* find_emulator_transport_by_console_port(int console_port);
154 #endif
155 
156 unique_fd service_to_fd(std::string_view name, atransport* transport);
157 #if !ADB_HOST
158 unique_fd daemon_service_to_fd(std::string_view name, atransport* transport);
159 #endif
160 
161 #if ADB_HOST
162 asocket* host_service_to_socket(std::string_view name, std::string_view serial,
163                                 TransportId transport_id);
164 #endif
165 
166 #if !ADB_HOST
167 asocket* daemon_service_to_socket(std::string_view name, atransport* transport);
168 #endif
169 
170 #if !ADB_HOST
171 unique_fd execute_abb_command(std::string_view command);
172 #endif
173 
174 bool handle_forward_request(const char* service, atransport* transport, int reply_fd);
175 bool handle_forward_request(const char* service,
176                             std::function<atransport*(std::string* error)> transport_acquirer,
177                             int reply_fd);
178 
179 /* packet allocator */
180 apacket* get_apacket();
181 void put_apacket(apacket* p);
182 
183 // Define it if you want to dump packets.
184 #define DEBUG_PACKETS 0
185 
186 #if !DEBUG_PACKETS
187 #define print_packet(tag, p) \
188     do {                     \
189     } while (0)
190 #endif
191 
192 #define DEFAULT_ADB_LOCAL_TRANSPORT_PORT 5555
193 
194 #define ADB_CLASS 0xff
195 #define ADB_SUBCLASS 0x42
196 #define ADB_PROTOCOL 0x1
197 
198 #define ADB_DBC_CLASS 0xDC
199 #define ADB_DBC_SUBCLASS 0x2
200 
201 bool connect_emulator(int port);
202 int connect_emulator_arbitrary_ports(int console_port, int adb_port, std::string* error);
203 
204 extern const char* adb_device_banner;
205 
206 #define CHUNK_SIZE (64 * 1024)
207 
208 // Argument delimeter for adb abb command.
209 #define ABB_ARG_DELIMETER ('\0')
210 
211 #if !ADB_HOST
212 #define USB_FFS_ADB_PATH "/dev/usb-ffs/adb/"
213 #define USB_FFS_ADB_EP(x) USB_FFS_ADB_PATH #x
214 
215 #define USB_FFS_ADB_EP0 USB_FFS_ADB_EP(ep0)
216 #define USB_FFS_ADB_OUT USB_FFS_ADB_EP(ep1)
217 #define USB_FFS_ADB_IN USB_FFS_ADB_EP(ep2)
218 #endif
219 
220 enum class HostRequestResult {
221     Handled,
222     SwitchedTransport,
223     Unhandled,
224 };
225 
226 HostRequestResult handle_host_request(std::string_view service, TransportType type,
227                                       const char* serial, TransportId transport_id, int reply_fd,
228                                       asocket* s);
229 
230 void handle_online(atransport* t);
231 void handle_offline(atransport* t);
232 
233 void send_connect(atransport* t);
234 void send_tls_request(atransport* t);
235 void send_ready(unsigned local, unsigned remote, atransport* t, uint32_t ack_bytes);
236 
237 void parse_banner(const std::string&, atransport* t);
238 
239 #if ADB_HOST
240 // On startup, the adb server needs to wait until all of the connected devices are ready.
241 // To do this, we need to know when the scan has identified all of the potential new transports, and
242 // when each transport becomes ready.
243 // TODO: Do this for mDNS as well, instead of just USB?
244 
245 // We've found all of the transports we potentially care about.
246 void adb_notify_device_scan_complete();
247 
248 // One or more transports have changed status, check to see if we're ready.
249 void update_transport_status();
250 
251 // Wait until device scan has completed and every transport is ready, or a timeout elapses.
252 void adb_wait_for_device_initialization();
253 
254 // When ssh-forwarding to a remote adb server, kill-server is almost never what you actually want,
255 // and unfortunately, many other tools issue it. This adds a knob to reject kill-servers.
256 void adb_set_reject_kill_server(bool reject);
257 #endif
258 
259 void usb_init();
260