sockets.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931
  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. #define TRACE_TAG SOCKETS
  17. #include "sysdeps.h"
  18. #include <ctype.h>
  19. #include <errno.h>
  20. #include <stdio.h>
  21. #include <stdlib.h>
  22. #include <string.h>
  23. #include <unistd.h>
  24. #include <algorithm>
  25. #include <chrono>
  26. #include <mutex>
  27. #include <string>
  28. #include <vector>
  29. #if !ADB_HOST
  30. #include <android-base/properties.h>
  31. #include <log/log_properties.h>
  32. #endif
  33. #include "adb.h"
  34. #include "adb_io.h"
  35. #include "adb_utils.h"
  36. #include "transport.h"
  37. #include "types.h"
  38. using namespace std::chrono_literals;
  39. static std::recursive_mutex& local_socket_list_lock = *new std::recursive_mutex();
  40. static unsigned local_socket_next_id = 1;
  41. static auto& local_socket_list = *new std::vector<asocket*>();
  42. /* the the list of currently closing local sockets.
  43. ** these have no peer anymore, but still packets to
  44. ** write to their fd.
  45. */
  46. static auto& local_socket_closing_list = *new std::vector<asocket*>();
  47. // Parse the global list of sockets to find one with id |local_id|.
  48. // If |peer_id| is not 0, also check that it is connected to a peer
  49. // with id |peer_id|. Returns an asocket handle on success, NULL on failure.
  50. asocket* find_local_socket(unsigned local_id, unsigned peer_id) {
  51. asocket* result = nullptr;
  52. std::lock_guard<std::recursive_mutex> lock(local_socket_list_lock);
  53. for (asocket* s : local_socket_list) {
  54. if (s->id != local_id) {
  55. continue;
  56. }
  57. if (peer_id == 0 || (s->peer && s->peer->id == peer_id)) {
  58. result = s;
  59. }
  60. break;
  61. }
  62. return result;
  63. }
  64. void install_local_socket(asocket* s) {
  65. std::lock_guard<std::recursive_mutex> lock(local_socket_list_lock);
  66. s->id = local_socket_next_id++;
  67. // Socket ids should never be 0.
  68. if (local_socket_next_id == 0) {
  69. LOG(FATAL) << "local socket id overflow";
  70. }
  71. local_socket_list.push_back(s);
  72. }
  73. void remove_socket(asocket* s) {
  74. std::lock_guard<std::recursive_mutex> lock(local_socket_list_lock);
  75. for (auto list : { &local_socket_list, &local_socket_closing_list }) {
  76. list->erase(std::remove_if(list->begin(), list->end(), [s](asocket* x) { return x == s; }),
  77. list->end());
  78. }
  79. }
  80. void close_all_sockets(atransport* t) {
  81. /* this is a little gross, but since s->close() *will* modify
  82. ** the list out from under you, your options are limited.
  83. */
  84. std::lock_guard<std::recursive_mutex> lock(local_socket_list_lock);
  85. restart:
  86. for (asocket* s : local_socket_list) {
  87. if (s->transport == t || (s->peer && s->peer->transport == t)) {
  88. s->close(s);
  89. goto restart;
  90. }
  91. }
  92. }
  93. enum class SocketFlushResult {
  94. Destroyed,
  95. TryAgain,
  96. Completed,
  97. };
  98. static SocketFlushResult local_socket_flush_incoming(asocket* s) {
  99. if (!s->packet_queue.empty()) {
  100. std::vector<adb_iovec> iov = s->packet_queue.iovecs();
  101. ssize_t rc = adb_writev(s->fd, iov.data(), iov.size());
  102. if (rc > 0 && static_cast<size_t>(rc) == s->packet_queue.size()) {
  103. s->packet_queue.clear();
  104. } else if (rc > 0) {
  105. // TODO: Implement a faster drop_front?
  106. s->packet_queue.take_front(rc);
  107. fdevent_add(s->fde, FDE_WRITE);
  108. return SocketFlushResult::TryAgain;
  109. } else if (rc == -1 && errno == EAGAIN) {
  110. fdevent_add(s->fde, FDE_WRITE);
  111. return SocketFlushResult::TryAgain;
  112. } else {
  113. // We failed to write, but it's possible that we can still read from the socket.
  114. // Give that a try before giving up.
  115. s->has_write_error = true;
  116. }
  117. }
  118. // If we sent the last packet of a closing socket, we can now destroy it.
  119. if (s->closing) {
  120. s->close(s);
  121. return SocketFlushResult::Destroyed;
  122. }
  123. fdevent_del(s->fde, FDE_WRITE);
  124. return SocketFlushResult::Completed;
  125. }
  126. // Returns false if the socket has been closed and destroyed as a side-effect of this function.
  127. static bool local_socket_flush_outgoing(asocket* s) {
  128. const size_t max_payload = s->get_max_payload();
  129. apacket::payload_type data;
  130. data.resize(max_payload);
  131. char* x = &data[0];
  132. size_t avail = max_payload;
  133. int r = 0;
  134. int is_eof = 0;
  135. while (avail > 0) {
  136. r = adb_read(s->fd, x, avail);
  137. D("LS(%d): post adb_read(fd=%d,...) r=%d (errno=%d) avail=%zu", s->id, s->fd, r,
  138. r < 0 ? errno : 0, avail);
  139. if (r == -1) {
  140. if (errno == EAGAIN) {
  141. break;
  142. }
  143. } else if (r > 0) {
  144. avail -= r;
  145. x += r;
  146. continue;
  147. }
  148. /* r = 0 or unhandled error */
  149. is_eof = 1;
  150. break;
  151. }
  152. D("LS(%d): fd=%d post avail loop. r=%d is_eof=%d forced_eof=%d", s->id, s->fd, r, is_eof,
  153. s->fde->force_eof);
  154. if (avail != max_payload && s->peer) {
  155. data.resize(max_payload - avail);
  156. // s->peer->enqueue() may call s->close() and free s,
  157. // so save variables for debug printing below.
  158. unsigned saved_id = s->id;
  159. int saved_fd = s->fd;
  160. r = s->peer->enqueue(s->peer, std::move(data));
  161. D("LS(%u): fd=%d post peer->enqueue(). r=%d", saved_id, saved_fd, r);
  162. if (r < 0) {
  163. // Error return means they closed us as a side-effect and we must
  164. // return immediately.
  165. //
  166. // Note that if we still have buffered packets, the socket will be
  167. // placed on the closing socket list. This handler function will be
  168. // called again to process FDE_WRITE events.
  169. return false;
  170. }
  171. if (r > 0) {
  172. /* if the remote cannot accept further events,
  173. ** we disable notification of READs. They'll
  174. ** be enabled again when we get a call to ready()
  175. */
  176. fdevent_del(s->fde, FDE_READ);
  177. }
  178. }
  179. // Don't allow a forced eof if data is still there.
  180. if ((s->fde->force_eof && !r) || is_eof) {
  181. D(" closing because is_eof=%d r=%d s->fde.force_eof=%d", is_eof, r, s->fde->force_eof);
  182. s->close(s);
  183. return false;
  184. }
  185. return true;
  186. }
  187. static int local_socket_enqueue(asocket* s, apacket::payload_type data) {
  188. D("LS(%d): enqueue %zu", s->id, data.size());
  189. s->packet_queue.append(std::move(data));
  190. switch (local_socket_flush_incoming(s)) {
  191. case SocketFlushResult::Destroyed:
  192. return -1;
  193. case SocketFlushResult::TryAgain:
  194. return 1;
  195. case SocketFlushResult::Completed:
  196. return 0;
  197. }
  198. return !s->packet_queue.empty();
  199. }
  200. static void local_socket_ready(asocket* s) {
  201. /* far side is ready for data, pay attention to
  202. readable events */
  203. fdevent_add(s->fde, FDE_READ);
  204. }
  205. struct ClosingSocket {
  206. std::chrono::steady_clock::time_point begin;
  207. };
  208. // The standard (RFC 1122 - 4.2.2.13) says that if we call close on a
  209. // socket while we have pending data, a TCP RST should be sent to the
  210. // other end to notify it that we didn't read all of its data. However,
  211. // this can result in data that we've successfully written out to be dropped
  212. // on the other end. To avoid this, instead of immediately closing a
  213. // socket, call shutdown on it instead, and then read from the file
  214. // descriptor until we hit EOF or an error before closing.
  215. static void deferred_close(unique_fd fd) {
  216. // Shutdown the socket in the outgoing direction only, so that
  217. // we don't have the same problem on the opposite end.
  218. adb_shutdown(fd.get(), SHUT_WR);
  219. auto callback = [](fdevent* fde, unsigned event, void* arg) {
  220. auto socket_info = static_cast<ClosingSocket*>(arg);
  221. if (event & FDE_READ) {
  222. ssize_t rc;
  223. char buf[BUFSIZ];
  224. while ((rc = adb_read(fde->fd.get(), buf, sizeof(buf))) > 0) {
  225. continue;
  226. }
  227. if (rc == -1 && errno == EAGAIN) {
  228. // There's potentially more data to read.
  229. auto duration = std::chrono::steady_clock::now() - socket_info->begin;
  230. if (duration > 1s) {
  231. LOG(WARNING) << "timeout expired while flushing socket, closing";
  232. } else {
  233. return;
  234. }
  235. }
  236. } else if (event & FDE_TIMEOUT) {
  237. LOG(WARNING) << "timeout expired while flushing socket, closing";
  238. }
  239. // Either there was an error, we hit the end of the socket, or our timeout expired.
  240. fdevent_destroy(fde);
  241. delete socket_info;
  242. };
  243. ClosingSocket* socket_info = new ClosingSocket{
  244. .begin = std::chrono::steady_clock::now(),
  245. };
  246. fdevent* fde = fdevent_create(fd.release(), callback, socket_info);
  247. fdevent_add(fde, FDE_READ);
  248. fdevent_set_timeout(fde, 1s);
  249. }
  250. // be sure to hold the socket list lock when calling this
  251. static void local_socket_destroy(asocket* s) {
  252. int exit_on_close = s->exit_on_close;
  253. D("LS(%d): destroying fde.fd=%d", s->id, s->fd);
  254. deferred_close(fdevent_release(s->fde));
  255. remove_socket(s);
  256. delete s;
  257. if (exit_on_close) {
  258. D("local_socket_destroy: exiting");
  259. exit(1);
  260. }
  261. }
  262. static void local_socket_close(asocket* s) {
  263. D("entered local_socket_close. LS(%d) fd=%d", s->id, s->fd);
  264. std::lock_guard<std::recursive_mutex> lock(local_socket_list_lock);
  265. if (s->peer) {
  266. D("LS(%d): closing peer. peer->id=%d peer->fd=%d", s->id, s->peer->id, s->peer->fd);
  267. /* Note: it's important to call shutdown before disconnecting from
  268. * the peer, this ensures that remote sockets can still get the id
  269. * of the local socket they're connected to, to send a CLOSE()
  270. * protocol event. */
  271. if (s->peer->shutdown) {
  272. s->peer->shutdown(s->peer);
  273. }
  274. s->peer->peer = nullptr;
  275. s->peer->close(s->peer);
  276. s->peer = nullptr;
  277. }
  278. /* If we are already closing, or if there are no
  279. ** pending packets, destroy immediately
  280. */
  281. if (s->closing || s->has_write_error || s->packet_queue.empty()) {
  282. int id = s->id;
  283. local_socket_destroy(s);
  284. D("LS(%d): closed", id);
  285. return;
  286. }
  287. /* otherwise, put on the closing list
  288. */
  289. D("LS(%d): closing", s->id);
  290. s->closing = 1;
  291. fdevent_del(s->fde, FDE_READ);
  292. remove_socket(s);
  293. D("LS(%d): put on socket_closing_list fd=%d", s->id, s->fd);
  294. local_socket_closing_list.push_back(s);
  295. CHECK_EQ(FDE_WRITE, s->fde->state & FDE_WRITE);
  296. }
  297. static void local_socket_event_func(int fd, unsigned ev, void* _s) {
  298. asocket* s = reinterpret_cast<asocket*>(_s);
  299. D("LS(%d): event_func(fd=%d(==%d), ev=%04x)", s->id, s->fd, fd, ev);
  300. /* put the FDE_WRITE processing before the FDE_READ
  301. ** in order to simplify the code.
  302. */
  303. if (ev & FDE_WRITE) {
  304. switch (local_socket_flush_incoming(s)) {
  305. case SocketFlushResult::Destroyed:
  306. return;
  307. case SocketFlushResult::TryAgain:
  308. break;
  309. case SocketFlushResult::Completed:
  310. s->peer->ready(s->peer);
  311. break;
  312. }
  313. }
  314. if (ev & FDE_READ) {
  315. if (!local_socket_flush_outgoing(s)) {
  316. return;
  317. }
  318. }
  319. if (ev & FDE_ERROR) {
  320. /* this should be caught be the next read or write
  321. ** catching it here means we may skip the last few
  322. ** bytes of readable data.
  323. */
  324. D("LS(%d): FDE_ERROR (fd=%d)", s->id, s->fd);
  325. return;
  326. }
  327. }
  328. asocket* create_local_socket(unique_fd ufd) {
  329. int fd = ufd.release();
  330. asocket* s = new asocket();
  331. s->fd = fd;
  332. s->enqueue = local_socket_enqueue;
  333. s->ready = local_socket_ready;
  334. s->shutdown = nullptr;
  335. s->close = local_socket_close;
  336. install_local_socket(s);
  337. s->fde = fdevent_create(fd, local_socket_event_func, s);
  338. D("LS(%d): created (fd=%d)", s->id, s->fd);
  339. return s;
  340. }
  341. asocket* create_local_service_socket(std::string_view name, atransport* transport) {
  342. #if !ADB_HOST
  343. if (asocket* s = daemon_service_to_socket(name); s) {
  344. return s;
  345. }
  346. #endif
  347. unique_fd fd = service_to_fd(name, transport);
  348. if (fd < 0) {
  349. return nullptr;
  350. }
  351. int fd_value = fd.get();
  352. asocket* s = create_local_socket(std::move(fd));
  353. LOG(VERBOSE) << "LS(" << s->id << "): bound to '" << name << "' via " << fd_value;
  354. #if !ADB_HOST
  355. if ((name.starts_with("root:") && getuid() != 0 && __android_log_is_debuggable()) ||
  356. (name.starts_with("unroot:") && getuid() == 0) || name.starts_with("usb:") ||
  357. name.starts_with("tcpip:")) {
  358. D("LS(%d): enabling exit_on_close", s->id);
  359. s->exit_on_close = 1;
  360. }
  361. #endif
  362. return s;
  363. }
  364. static int remote_socket_enqueue(asocket* s, apacket::payload_type data) {
  365. D("entered remote_socket_enqueue RS(%d) WRITE fd=%d peer.fd=%d", s->id, s->fd, s->peer->fd);
  366. apacket* p = get_apacket();
  367. p->msg.command = A_WRTE;
  368. p->msg.arg0 = s->peer->id;
  369. p->msg.arg1 = s->id;
  370. if (data.size() > MAX_PAYLOAD) {
  371. put_apacket(p);
  372. return -1;
  373. }
  374. p->payload = std::move(data);
  375. p->msg.data_length = p->payload.size();
  376. send_packet(p, s->transport);
  377. return 1;
  378. }
  379. static void remote_socket_ready(asocket* s) {
  380. D("entered remote_socket_ready RS(%d) OKAY fd=%d peer.fd=%d", s->id, s->fd, s->peer->fd);
  381. apacket* p = get_apacket();
  382. p->msg.command = A_OKAY;
  383. p->msg.arg0 = s->peer->id;
  384. p->msg.arg1 = s->id;
  385. send_packet(p, s->transport);
  386. }
  387. static void remote_socket_shutdown(asocket* s) {
  388. D("entered remote_socket_shutdown RS(%d) CLOSE fd=%d peer->fd=%d", s->id, s->fd,
  389. s->peer ? s->peer->fd : -1);
  390. apacket* p = get_apacket();
  391. p->msg.command = A_CLSE;
  392. if (s->peer) {
  393. p->msg.arg0 = s->peer->id;
  394. }
  395. p->msg.arg1 = s->id;
  396. send_packet(p, s->transport);
  397. }
  398. static void remote_socket_close(asocket* s) {
  399. if (s->peer) {
  400. s->peer->peer = nullptr;
  401. D("RS(%d) peer->close()ing peer->id=%d peer->fd=%d", s->id, s->peer->id, s->peer->fd);
  402. s->peer->close(s->peer);
  403. }
  404. D("entered remote_socket_close RS(%d) CLOSE fd=%d peer->fd=%d", s->id, s->fd,
  405. s->peer ? s->peer->fd : -1);
  406. D("RS(%d): closed", s->id);
  407. delete s;
  408. }
  409. // Create a remote socket to exchange packets with a remote service through transport
  410. // |t|. Where |id| is the socket id of the corresponding service on the other
  411. // side of the transport (it is allocated by the remote side and _cannot_ be 0).
  412. // Returns a new non-NULL asocket handle.
  413. asocket* create_remote_socket(unsigned id, atransport* t) {
  414. if (id == 0) {
  415. LOG(FATAL) << "invalid remote socket id (0)";
  416. }
  417. asocket* s = new asocket();
  418. s->id = id;
  419. s->enqueue = remote_socket_enqueue;
  420. s->ready = remote_socket_ready;
  421. s->shutdown = remote_socket_shutdown;
  422. s->close = remote_socket_close;
  423. s->transport = t;
  424. D("RS(%d): created", s->id);
  425. return s;
  426. }
  427. void connect_to_remote(asocket* s, std::string_view destination) {
  428. D("Connect_to_remote call RS(%d) fd=%d", s->id, s->fd);
  429. apacket* p = get_apacket();
  430. LOG(VERBOSE) << "LS(" << s->id << ": connect(" << destination << ")";
  431. p->msg.command = A_OPEN;
  432. p->msg.arg0 = s->id;
  433. // adbd used to expect a null-terminated string.
  434. // Keep doing so to maintain backward compatibility.
  435. p->payload.resize(destination.size() + 1);
  436. memcpy(p->payload.data(), destination.data(), destination.size());
  437. p->payload[destination.size()] = '\0';
  438. p->msg.data_length = p->payload.size();
  439. CHECK_LE(p->msg.data_length, s->get_max_payload());
  440. send_packet(p, s->transport);
  441. }
  442. /* this is used by magic sockets to rig local sockets to
  443. send the go-ahead message when they connect */
  444. static void local_socket_ready_notify(asocket* s) {
  445. s->ready = local_socket_ready;
  446. s->shutdown = nullptr;
  447. s->close = local_socket_close;
  448. SendOkay(s->fd);
  449. s->ready(s);
  450. }
  451. /* this is used by magic sockets to rig local sockets to
  452. send the failure message if they are closed before
  453. connected (to avoid closing them without a status message) */
  454. static void local_socket_close_notify(asocket* s) {
  455. s->ready = local_socket_ready;
  456. s->shutdown = nullptr;
  457. s->close = local_socket_close;
  458. SendFail(s->fd, "closed");
  459. s->close(s);
  460. }
  461. static unsigned unhex(const char* s, int len) {
  462. unsigned n = 0, c;
  463. while (len-- > 0) {
  464. switch ((c = *s++)) {
  465. case '0':
  466. case '1':
  467. case '2':
  468. case '3':
  469. case '4':
  470. case '5':
  471. case '6':
  472. case '7':
  473. case '8':
  474. case '9':
  475. c -= '0';
  476. break;
  477. case 'a':
  478. case 'b':
  479. case 'c':
  480. case 'd':
  481. case 'e':
  482. case 'f':
  483. c = c - 'a' + 10;
  484. break;
  485. case 'A':
  486. case 'B':
  487. case 'C':
  488. case 'D':
  489. case 'E':
  490. case 'F':
  491. c = c - 'A' + 10;
  492. break;
  493. default:
  494. return 0xffffffff;
  495. }
  496. n = (n << 4) | c;
  497. }
  498. return n;
  499. }
  500. #if ADB_HOST
  501. namespace internal {
  502. // Parses a host service string of the following format:
  503. // * [tcp:|udp:]<serial>[:<port>]:<command>
  504. // * <prefix>:<serial>:<command>
  505. // Where <port> must be a base-10 number and <prefix> may be any of {usb,product,model,device}.
  506. bool parse_host_service(std::string_view* out_serial, std::string_view* out_command,
  507. std::string_view full_service) {
  508. if (full_service.empty()) {
  509. return false;
  510. }
  511. std::string_view serial;
  512. std::string_view command = full_service;
  513. // Remove |count| bytes from the beginning of command and add them to |serial|.
  514. auto consume = [&full_service, &serial, &command](size_t count) {
  515. CHECK_LE(count, command.size());
  516. if (!serial.empty()) {
  517. CHECK_EQ(serial.data() + serial.size(), command.data());
  518. }
  519. serial = full_service.substr(0, serial.size() + count);
  520. command.remove_prefix(count);
  521. };
  522. // Remove the trailing : from serial, and assign the values to the output parameters.
  523. auto finish = [out_serial, out_command, &serial, &command] {
  524. if (serial.empty() || command.empty()) {
  525. return false;
  526. }
  527. CHECK_EQ(':', serial.back());
  528. serial.remove_suffix(1);
  529. *out_serial = serial;
  530. *out_command = command;
  531. return true;
  532. };
  533. static constexpr std::string_view prefixes[] = {"usb:", "product:", "model:", "device:"};
  534. for (std::string_view prefix : prefixes) {
  535. if (command.starts_with(prefix)) {
  536. consume(prefix.size());
  537. size_t offset = command.find_first_of(':');
  538. if (offset == std::string::npos) {
  539. return false;
  540. }
  541. consume(offset + 1);
  542. return finish();
  543. }
  544. }
  545. // For fastboot compatibility, ignore protocol prefixes.
  546. if (command.starts_with("tcp:") || command.starts_with("udp:")) {
  547. consume(4);
  548. if (command.empty()) {
  549. return false;
  550. }
  551. }
  552. if (command.starts_with("vsock:")) {
  553. // vsock serials are vsock:cid:port, which have an extra colon compared to tcp.
  554. size_t next_colon = command.find(':');
  555. if (next_colon == std::string::npos) {
  556. return false;
  557. }
  558. consume(next_colon + 1);
  559. }
  560. bool found_address = false;
  561. if (command[0] == '[') {
  562. // Read an IPv6 address. `adb connect` creates the serial number from the canonical
  563. // network address so it will always have the [] delimiters.
  564. size_t ipv6_end = command.find_first_of(']');
  565. if (ipv6_end != std::string::npos) {
  566. consume(ipv6_end + 1);
  567. if (command.empty()) {
  568. // Nothing after the IPv6 address.
  569. return false;
  570. } else if (command[0] != ':') {
  571. // Garbage after the IPv6 address.
  572. return false;
  573. }
  574. consume(1);
  575. found_address = true;
  576. }
  577. }
  578. if (!found_address) {
  579. // Scan ahead to the next colon.
  580. size_t offset = command.find_first_of(':');
  581. if (offset == std::string::npos) {
  582. return false;
  583. }
  584. consume(offset + 1);
  585. }
  586. // We're either at the beginning of a port, or the command itself.
  587. // Look for a port in between colons.
  588. size_t next_colon = command.find_first_of(':');
  589. if (next_colon == std::string::npos) {
  590. // No colon, we must be at the command.
  591. return finish();
  592. }
  593. bool port_valid = true;
  594. if (command.size() <= next_colon) {
  595. return false;
  596. }
  597. std::string_view port = command.substr(0, next_colon);
  598. for (auto digit : port) {
  599. if (!isdigit(digit)) {
  600. // Port isn't a number.
  601. port_valid = false;
  602. break;
  603. }
  604. }
  605. if (port_valid) {
  606. consume(next_colon + 1);
  607. }
  608. return finish();
  609. }
  610. } // namespace internal
  611. #endif // ADB_HOST
  612. static int smart_socket_enqueue(asocket* s, apacket::payload_type data) {
  613. #if ADB_HOST
  614. std::string_view service;
  615. std::string_view serial;
  616. TransportId transport_id = 0;
  617. TransportType type = kTransportAny;
  618. #endif
  619. D("SS(%d): enqueue %zu", s->id, data.size());
  620. if (s->smart_socket_data.empty()) {
  621. // TODO: Make this an IOVector?
  622. s->smart_socket_data.assign(data.begin(), data.end());
  623. } else {
  624. std::copy(data.begin(), data.end(), std::back_inserter(s->smart_socket_data));
  625. }
  626. /* don't bother if we can't decode the length */
  627. if (s->smart_socket_data.size() < 4) {
  628. return 0;
  629. }
  630. uint32_t len = unhex(s->smart_socket_data.data(), 4);
  631. if (len == 0 || len > MAX_PAYLOAD) {
  632. D("SS(%d): bad size (%u)", s->id, len);
  633. goto fail;
  634. }
  635. D("SS(%d): len is %u", s->id, len);
  636. /* can't do anything until we have the full header */
  637. if ((len + 4) > s->smart_socket_data.size()) {
  638. D("SS(%d): waiting for %zu more bytes", s->id, len + 4 - s->smart_socket_data.size());
  639. return 0;
  640. }
  641. s->smart_socket_data[len + 4] = 0;
  642. D("SS(%d): '%s'", s->id, (char*)(s->smart_socket_data.data() + 4));
  643. #if ADB_HOST
  644. service = std::string_view(s->smart_socket_data).substr(4);
  645. if (ConsumePrefix(&service, "host-serial:")) {
  646. // serial number should follow "host:" and could be a host:port string.
  647. if (!internal::parse_host_service(&serial, &service, service)) {
  648. LOG(ERROR) << "SS(" << s->id << "): failed to parse host service: " << service;
  649. goto fail;
  650. }
  651. } else if (ConsumePrefix(&service, "host-transport-id:")) {
  652. if (!ParseUint(&transport_id, service, &service)) {
  653. LOG(ERROR) << "SS(" << s->id << "): failed to parse host transport id: " << service;
  654. return -1;
  655. }
  656. if (!ConsumePrefix(&service, ":")) {
  657. LOG(ERROR) << "SS(" << s->id << "): host-transport-id without command";
  658. return -1;
  659. }
  660. } else if (ConsumePrefix(&service, "host-usb:")) {
  661. type = kTransportUsb;
  662. } else if (ConsumePrefix(&service, "host-local:")) {
  663. type = kTransportLocal;
  664. } else if (ConsumePrefix(&service, "host:")) {
  665. type = kTransportAny;
  666. } else {
  667. service = std::string_view{};
  668. }
  669. if (!service.empty()) {
  670. asocket* s2;
  671. // Some requests are handled immediately -- in that case the handle_host_request() routine
  672. // has sent the OKAY or FAIL message and all we have to do is clean up.
  673. auto host_request_result = handle_host_request(
  674. service, type, serial.empty() ? nullptr : std::string(serial).c_str(), transport_id,
  675. s->peer->fd, s);
  676. switch (host_request_result) {
  677. case HostRequestResult::Handled:
  678. LOG(VERBOSE) << "SS(" << s->id << "): handled host service '" << service << "'";
  679. goto fail;
  680. case HostRequestResult::SwitchedTransport:
  681. D("SS(%d): okay transport", s->id);
  682. s->smart_socket_data.clear();
  683. return 0;
  684. case HostRequestResult::Unhandled:
  685. break;
  686. }
  687. /* try to find a local service with this name.
  688. ** if no such service exists, we'll fail out
  689. ** and tear down here.
  690. */
  691. // TODO: Convert to string_view.
  692. s2 = host_service_to_socket(service, serial, transport_id);
  693. if (s2 == nullptr) {
  694. LOG(VERBOSE) << "SS(" << s->id << "): couldn't create host service '" << service << "'";
  695. SendFail(s->peer->fd, "unknown host service");
  696. goto fail;
  697. }
  698. /* we've connected to a local host service,
  699. ** so we make our peer back into a regular
  700. ** local socket and bind it to the new local
  701. ** service socket, acknowledge the successful
  702. ** connection, and close this smart socket now
  703. ** that its work is done.
  704. */
  705. SendOkay(s->peer->fd);
  706. s->peer->ready = local_socket_ready;
  707. s->peer->shutdown = nullptr;
  708. s->peer->close = local_socket_close;
  709. s->peer->peer = s2;
  710. s2->peer = s->peer;
  711. s->peer = nullptr;
  712. D("SS(%d): okay", s->id);
  713. s->close(s);
  714. /* initial state is "ready" */
  715. s2->ready(s2);
  716. return 0;
  717. }
  718. #else /* !ADB_HOST */
  719. if (s->transport == nullptr) {
  720. std::string error_msg = "unknown failure";
  721. s->transport = acquire_one_transport(kTransportAny, nullptr, 0, nullptr, &error_msg);
  722. if (s->transport == nullptr) {
  723. SendFail(s->peer->fd, error_msg);
  724. goto fail;
  725. }
  726. }
  727. #endif
  728. if (!s->transport) {
  729. SendFail(s->peer->fd, "device offline (no transport)");
  730. goto fail;
  731. } else if (!ConnectionStateIsOnline(s->transport->GetConnectionState())) {
  732. /* if there's no remote we fail the connection
  733. ** right here and terminate it
  734. */
  735. SendFail(s->peer->fd, "device offline (transport offline)");
  736. goto fail;
  737. }
  738. /* instrument our peer to pass the success or fail
  739. ** message back once it connects or closes, then
  740. ** detach from it, request the connection, and
  741. ** tear down
  742. */
  743. s->peer->ready = local_socket_ready_notify;
  744. s->peer->shutdown = nullptr;
  745. s->peer->close = local_socket_close_notify;
  746. s->peer->peer = nullptr;
  747. /* give him our transport and upref it */
  748. s->peer->transport = s->transport;
  749. connect_to_remote(s->peer, std::string_view(s->smart_socket_data).substr(4));
  750. s->peer = nullptr;
  751. s->close(s);
  752. return 1;
  753. fail:
  754. /* we're going to close our peer as a side-effect, so
  755. ** return -1 to signal that state to the local socket
  756. ** who is enqueueing against us
  757. */
  758. s->close(s);
  759. return -1;
  760. }
  761. static void smart_socket_ready(asocket* s) {
  762. D("SS(%d): ready", s->id);
  763. }
  764. static void smart_socket_close(asocket* s) {
  765. D("SS(%d): closed", s->id);
  766. if (s->peer) {
  767. s->peer->peer = nullptr;
  768. s->peer->close(s->peer);
  769. s->peer = nullptr;
  770. }
  771. delete s;
  772. }
  773. static asocket* create_smart_socket(void) {
  774. D("Creating smart socket");
  775. asocket* s = new asocket();
  776. s->enqueue = smart_socket_enqueue;
  777. s->ready = smart_socket_ready;
  778. s->shutdown = nullptr;
  779. s->close = smart_socket_close;
  780. D("SS(%d)", s->id);
  781. return s;
  782. }
  783. void connect_to_smartsocket(asocket* s) {
  784. D("Connecting to smart socket");
  785. asocket* ss = create_smart_socket();
  786. s->peer = ss;
  787. ss->peer = s;
  788. s->ready(s);
  789. }
  790. size_t asocket::get_max_payload() const {
  791. size_t max_payload = MAX_PAYLOAD;
  792. if (transport) {
  793. max_payload = std::min(max_payload, transport->get_max_payload());
  794. }
  795. if (peer && peer->transport) {
  796. max_payload = std::min(max_payload, peer->transport->get_max_payload());
  797. }
  798. return max_payload;
  799. }