adb.c 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594
  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 TRACE_ADB
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. #include <ctype.h>
  20. #include <stdarg.h>
  21. #include <errno.h>
  22. #include <stddef.h>
  23. #include <string.h>
  24. #include <time.h>
  25. #include <sys/time.h>
  26. #include "cutils/properties.h"
  27. #include "sysdeps.h"
  28. #include "adb.h"
  29. #include "adb_auth.h"
  30. #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
  31. #if !ADB_HOST
  32. #include <private/android_filesystem_config.h>
  33. #include <linux/capability.h>
  34. #include <linux/prctl.h>
  35. #include <sys/mount.h>
  36. #else
  37. #include "usb_vendors.h"
  38. #endif
  39. #if ADB_TRACE
  40. ADB_MUTEX_DEFINE( D_lock );
  41. #endif
  42. int HOST = 0;
  43. static int auth_enabled = 0;
  44. #if !ADB_HOST
  45. static const char *adb_device_banner = "device";
  46. #endif
  47. void fatal(const char *fmt, ...)
  48. {
  49. va_list ap;
  50. va_start(ap, fmt);
  51. fprintf(stderr, "error: ");
  52. vfprintf(stderr, fmt, ap);
  53. fprintf(stderr, "\n");
  54. va_end(ap);
  55. exit(-1);
  56. }
  57. void fatal_errno(const char *fmt, ...)
  58. {
  59. va_list ap;
  60. va_start(ap, fmt);
  61. fprintf(stderr, "error: %s: ", strerror(errno));
  62. vfprintf(stderr, fmt, ap);
  63. fprintf(stderr, "\n");
  64. va_end(ap);
  65. exit(-1);
  66. }
  67. int adb_trace_mask;
  68. /* read a comma/space/colum/semi-column separated list of tags
  69. * from the ADB_TRACE environment variable and build the trace
  70. * mask from it. note that '1' and 'all' are special cases to
  71. * enable all tracing
  72. */
  73. void adb_trace_init(void)
  74. {
  75. const char* p = getenv("ADB_TRACE");
  76. const char* q;
  77. static const struct {
  78. const char* tag;
  79. int flag;
  80. } tags[] = {
  81. { "1", 0 },
  82. { "all", 0 },
  83. { "adb", TRACE_ADB },
  84. { "sockets", TRACE_SOCKETS },
  85. { "packets", TRACE_PACKETS },
  86. { "rwx", TRACE_RWX },
  87. { "usb", TRACE_USB },
  88. { "sync", TRACE_SYNC },
  89. { "sysdeps", TRACE_SYSDEPS },
  90. { "transport", TRACE_TRANSPORT },
  91. { "jdwp", TRACE_JDWP },
  92. { "services", TRACE_SERVICES },
  93. { "auth", TRACE_AUTH },
  94. { NULL, 0 }
  95. };
  96. if (p == NULL)
  97. return;
  98. /* use a comma/column/semi-colum/space separated list */
  99. while (*p) {
  100. int len, tagn;
  101. q = strpbrk(p, " ,:;");
  102. if (q == NULL) {
  103. q = p + strlen(p);
  104. }
  105. len = q - p;
  106. for (tagn = 0; tags[tagn].tag != NULL; tagn++)
  107. {
  108. int taglen = strlen(tags[tagn].tag);
  109. if (len == taglen && !memcmp(tags[tagn].tag, p, len) )
  110. {
  111. int flag = tags[tagn].flag;
  112. if (flag == 0) {
  113. adb_trace_mask = ~0;
  114. return;
  115. }
  116. adb_trace_mask |= (1 << flag);
  117. break;
  118. }
  119. }
  120. p = q;
  121. if (*p)
  122. p++;
  123. }
  124. adb_trace_mask = ~0;
  125. }
  126. #if !ADB_HOST
  127. /*
  128. * Implements ADB tracing inside the emulator.
  129. */
  130. #include <stdarg.h>
  131. /*
  132. * Redefine open and write for qemu_pipe.h that contains inlined references
  133. * to those routines. We will redifine them back after qemu_pipe.h inclusion.
  134. */
  135. #undef open
  136. #undef write
  137. #define open adb_open
  138. #define write adb_write
  139. #include <qemu/qemu_pipe.h>
  140. #undef open
  141. #undef write
  142. #define open ___xxx_open
  143. #define write ___xxx_write
  144. /* A handle to adb-debug qemud service in the emulator. */
  145. int adb_debug_qemu = -1;
  146. /* Initializes connection with the adb-debug qemud service in the emulator. */
  147. static int adb_qemu_trace_init(void)
  148. {
  149. char con_name[32];
  150. if (adb_debug_qemu >= 0) {
  151. return 0;
  152. }
  153. /* adb debugging QEMUD service connection request. */
  154. snprintf(con_name, sizeof(con_name), "qemud:adb-debug");
  155. adb_debug_qemu = qemu_pipe_open(con_name);
  156. return (adb_debug_qemu >= 0) ? 0 : -1;
  157. }
  158. void adb_qemu_trace(const char* fmt, ...)
  159. {
  160. va_list args;
  161. va_start(args, fmt);
  162. char msg[1024];
  163. if (adb_debug_qemu >= 0) {
  164. vsnprintf(msg, sizeof(msg), fmt, args);
  165. adb_write(adb_debug_qemu, msg, strlen(msg));
  166. }
  167. va_end(args);
  168. }
  169. #endif /* !ADB_HOST */
  170. apacket *get_apacket(void)
  171. {
  172. apacket *p = malloc(sizeof(apacket));
  173. if(p == 0) fatal("failed to allocate an apacket");
  174. memset(p, 0, sizeof(apacket) - MAX_PAYLOAD);
  175. return p;
  176. }
  177. void put_apacket(apacket *p)
  178. {
  179. free(p);
  180. }
  181. void handle_online(atransport *t)
  182. {
  183. D("adb: online\n");
  184. t->online = 1;
  185. }
  186. void handle_offline(atransport *t)
  187. {
  188. D("adb: offline\n");
  189. //Close the associated usb
  190. t->online = 0;
  191. run_transport_disconnects(t);
  192. }
  193. #if DEBUG_PACKETS
  194. #define DUMPMAX 32
  195. void print_packet(const char *label, apacket *p)
  196. {
  197. char *tag;
  198. char *x;
  199. unsigned count;
  200. switch(p->msg.command){
  201. case A_SYNC: tag = "SYNC"; break;
  202. case A_CNXN: tag = "CNXN" ; break;
  203. case A_OPEN: tag = "OPEN"; break;
  204. case A_OKAY: tag = "OKAY"; break;
  205. case A_CLSE: tag = "CLSE"; break;
  206. case A_WRTE: tag = "WRTE"; break;
  207. case A_AUTH: tag = "AUTH"; break;
  208. default: tag = "????"; break;
  209. }
  210. fprintf(stderr, "%s: %s %08x %08x %04x \"",
  211. label, tag, p->msg.arg0, p->msg.arg1, p->msg.data_length);
  212. count = p->msg.data_length;
  213. x = (char*) p->data;
  214. if(count > DUMPMAX) {
  215. count = DUMPMAX;
  216. tag = "\n";
  217. } else {
  218. tag = "\"\n";
  219. }
  220. while(count-- > 0){
  221. if((*x >= ' ') && (*x < 127)) {
  222. fputc(*x, stderr);
  223. } else {
  224. fputc('.', stderr);
  225. }
  226. x++;
  227. }
  228. fputs(tag, stderr);
  229. }
  230. #endif
  231. static void send_ready(unsigned local, unsigned remote, atransport *t)
  232. {
  233. D("Calling send_ready \n");
  234. apacket *p = get_apacket();
  235. p->msg.command = A_OKAY;
  236. p->msg.arg0 = local;
  237. p->msg.arg1 = remote;
  238. send_packet(p, t);
  239. }
  240. static void send_close(unsigned local, unsigned remote, atransport *t)
  241. {
  242. D("Calling send_close \n");
  243. apacket *p = get_apacket();
  244. p->msg.command = A_CLSE;
  245. p->msg.arg0 = local;
  246. p->msg.arg1 = remote;
  247. send_packet(p, t);
  248. }
  249. static size_t fill_connect_data(char *buf, size_t bufsize)
  250. {
  251. #if ADB_HOST
  252. return snprintf(buf, bufsize, "host::") + 1;
  253. #else
  254. static const char *cnxn_props[] = {
  255. "ro.product.name",
  256. "ro.product.model",
  257. "ro.product.device",
  258. };
  259. static const int num_cnxn_props = ARRAY_SIZE(cnxn_props);
  260. int i;
  261. size_t remaining = bufsize;
  262. size_t len;
  263. len = snprintf(buf, remaining, "%s::", adb_device_banner);
  264. remaining -= len;
  265. buf += len;
  266. for (i = 0; i < num_cnxn_props; i++) {
  267. char value[PROPERTY_VALUE_MAX];
  268. property_get(cnxn_props[i], value, "");
  269. len = snprintf(buf, remaining, "%s=%s;", cnxn_props[i], value);
  270. remaining -= len;
  271. buf += len;
  272. }
  273. return bufsize - remaining + 1;
  274. #endif
  275. }
  276. static void send_connect(atransport *t)
  277. {
  278. D("Calling send_connect \n");
  279. apacket *cp = get_apacket();
  280. cp->msg.command = A_CNXN;
  281. cp->msg.arg0 = A_VERSION;
  282. cp->msg.arg1 = MAX_PAYLOAD;
  283. cp->msg.data_length = fill_connect_data((char *)cp->data,
  284. sizeof(cp->data));
  285. send_packet(cp, t);
  286. }
  287. static void send_auth_request(atransport *t)
  288. {
  289. D("Calling send_auth_request\n");
  290. apacket *p;
  291. int ret;
  292. ret = adb_auth_generate_token(t->token, sizeof(t->token));
  293. if (ret != sizeof(t->token)) {
  294. D("Error generating token ret=%d\n", ret);
  295. return;
  296. }
  297. p = get_apacket();
  298. memcpy(p->data, t->token, ret);
  299. p->msg.command = A_AUTH;
  300. p->msg.arg0 = ADB_AUTH_TOKEN;
  301. p->msg.data_length = ret;
  302. send_packet(p, t);
  303. }
  304. static void send_auth_response(uint8_t *token, size_t token_size, atransport *t)
  305. {
  306. D("Calling send_auth_response\n");
  307. apacket *p = get_apacket();
  308. int ret;
  309. ret = adb_auth_sign(t->key, token, token_size, p->data);
  310. if (!ret) {
  311. D("Error signing the token\n");
  312. put_apacket(p);
  313. return;
  314. }
  315. p->msg.command = A_AUTH;
  316. p->msg.arg0 = ADB_AUTH_SIGNATURE;
  317. p->msg.data_length = ret;
  318. send_packet(p, t);
  319. }
  320. static void send_auth_publickey(atransport *t)
  321. {
  322. D("Calling send_auth_publickey\n");
  323. apacket *p = get_apacket();
  324. int ret;
  325. ret = adb_auth_get_userkey(p->data, sizeof(p->data));
  326. if (!ret) {
  327. D("Failed to get user public key\n");
  328. put_apacket(p);
  329. return;
  330. }
  331. p->msg.command = A_AUTH;
  332. p->msg.arg0 = ADB_AUTH_RSAPUBLICKEY;
  333. p->msg.data_length = ret;
  334. send_packet(p, t);
  335. }
  336. void adb_auth_verified(atransport *t)
  337. {
  338. handle_online(t);
  339. send_connect(t);
  340. }
  341. static char *connection_state_name(atransport *t)
  342. {
  343. if (t == NULL) {
  344. return "unknown";
  345. }
  346. switch(t->connection_state) {
  347. case CS_BOOTLOADER:
  348. return "bootloader";
  349. case CS_DEVICE:
  350. return "device";
  351. case CS_OFFLINE:
  352. return "offline";
  353. default:
  354. return "unknown";
  355. }
  356. }
  357. /* qual_overwrite is used to overwrite a qualifier string. dst is a
  358. * pointer to a char pointer. It is assumed that if *dst is non-NULL, it
  359. * was malloc'ed and needs to freed. *dst will be set to a dup of src.
  360. */
  361. static void qual_overwrite(char **dst, const char *src)
  362. {
  363. if (!dst)
  364. return;
  365. free(*dst);
  366. *dst = NULL;
  367. if (!src || !*src)
  368. return;
  369. *dst = strdup(src);
  370. }
  371. void parse_banner(char *banner, atransport *t)
  372. {
  373. static const char *prop_seps = ";";
  374. static const char key_val_sep = '=';
  375. char *cp;
  376. char *type;
  377. D("parse_banner: %s\n", banner);
  378. type = banner;
  379. cp = strchr(type, ':');
  380. if (cp) {
  381. *cp++ = 0;
  382. /* Nothing is done with second field. */
  383. cp = strchr(cp, ':');
  384. if (cp) {
  385. char *save;
  386. char *key;
  387. key = adb_strtok_r(cp + 1, prop_seps, &save);
  388. while (key) {
  389. cp = strchr(key, key_val_sep);
  390. if (cp) {
  391. *cp++ = '\0';
  392. if (!strcmp(key, "ro.product.name"))
  393. qual_overwrite(&t->product, cp);
  394. else if (!strcmp(key, "ro.product.model"))
  395. qual_overwrite(&t->model, cp);
  396. else if (!strcmp(key, "ro.product.device"))
  397. qual_overwrite(&t->device, cp);
  398. }
  399. key = adb_strtok_r(NULL, prop_seps, &save);
  400. }
  401. }
  402. }
  403. if(!strcmp(type, "bootloader")){
  404. D("setting connection_state to CS_BOOTLOADER\n");
  405. t->connection_state = CS_BOOTLOADER;
  406. update_transports();
  407. return;
  408. }
  409. if(!strcmp(type, "device")) {
  410. D("setting connection_state to CS_DEVICE\n");
  411. t->connection_state = CS_DEVICE;
  412. update_transports();
  413. return;
  414. }
  415. if(!strcmp(type, "recovery")) {
  416. D("setting connection_state to CS_RECOVERY\n");
  417. t->connection_state = CS_RECOVERY;
  418. update_transports();
  419. return;
  420. }
  421. if(!strcmp(type, "sideload")) {
  422. D("setting connection_state to CS_SIDELOAD\n");
  423. t->connection_state = CS_SIDELOAD;
  424. update_transports();
  425. return;
  426. }
  427. t->connection_state = CS_HOST;
  428. }
  429. void handle_packet(apacket *p, atransport *t)
  430. {
  431. asocket *s;
  432. D("handle_packet() %c%c%c%c\n", ((char*) (&(p->msg.command)))[0],
  433. ((char*) (&(p->msg.command)))[1],
  434. ((char*) (&(p->msg.command)))[2],
  435. ((char*) (&(p->msg.command)))[3]);
  436. print_packet("recv", p);
  437. switch(p->msg.command){
  438. case A_SYNC:
  439. if(p->msg.arg0){
  440. send_packet(p, t);
  441. if(HOST) send_connect(t);
  442. } else {
  443. t->connection_state = CS_OFFLINE;
  444. handle_offline(t);
  445. send_packet(p, t);
  446. }
  447. return;
  448. case A_CNXN: /* CONNECT(version, maxdata, "system-id-string") */
  449. /* XXX verify version, etc */
  450. if(t->connection_state != CS_OFFLINE) {
  451. t->connection_state = CS_OFFLINE;
  452. handle_offline(t);
  453. }
  454. parse_banner((char*) p->data, t);
  455. if (HOST || !auth_enabled) {
  456. handle_online(t);
  457. if(!HOST) send_connect(t);
  458. } else {
  459. send_auth_request(t);
  460. }
  461. break;
  462. case A_AUTH:
  463. D("handle_packet() AUTH with arg:%u\n", p->msg.arg0);
  464. if (p->msg.arg0 == ADB_AUTH_TOKEN) {
  465. t->key = adb_auth_nextkey(t->key);
  466. if (t->key) {
  467. send_auth_response(p->data, p->msg.data_length, t);
  468. } else {
  469. /* No more private keys to try, send the public key */
  470. send_auth_publickey(t);
  471. }
  472. } else if (p->msg.arg0 == ADB_AUTH_SIGNATURE) {
  473. if (adb_auth_verify(t->token, p->data, p->msg.data_length)) {
  474. adb_auth_verified(t);
  475. t->failed_auth_attempts = 0;
  476. } else {
  477. if (t->failed_auth_attempts++ > 10)
  478. adb_sleep_ms(1000);
  479. send_auth_request(t);
  480. }
  481. } else if (p->msg.arg0 == ADB_AUTH_RSAPUBLICKEY) {
  482. adb_auth_confirm_key(p->data, p->msg.data_length, t);
  483. }
  484. break;
  485. case A_OPEN: /* OPEN(local-id, 0, "destination") */
  486. if (t->online) {
  487. char *name = (char*) p->data;
  488. name[p->msg.data_length > 0 ? p->msg.data_length - 1 : 0] = 0;
  489. s = create_local_service_socket(name);
  490. if(s == 0) {
  491. send_close(0, p->msg.arg0, t);
  492. } else {
  493. s->peer = create_remote_socket(p->msg.arg0, t);
  494. s->peer->peer = s;
  495. send_ready(s->id, s->peer->id, t);
  496. s->ready(s);
  497. }
  498. }
  499. break;
  500. case A_OKAY: /* READY(local-id, remote-id, "") */
  501. if (t->online) {
  502. if((s = find_local_socket(p->msg.arg1))) {
  503. if(s->peer == 0) {
  504. s->peer = create_remote_socket(p->msg.arg0, t);
  505. s->peer->peer = s;
  506. }
  507. s->ready(s);
  508. }
  509. }
  510. break;
  511. case A_CLSE: /* CLOSE(local-id, remote-id, "") */
  512. if (t->online) {
  513. if((s = find_local_socket(p->msg.arg1))) {
  514. s->close(s);
  515. }
  516. }
  517. break;
  518. case A_WRTE:
  519. if (t->online) {
  520. if((s = find_local_socket(p->msg.arg1))) {
  521. unsigned rid = p->msg.arg0;
  522. p->len = p->msg.data_length;
  523. if(s->enqueue(s, p) == 0) {
  524. D("Enqueue the socket\n");
  525. send_ready(s->id, rid, t);
  526. }
  527. return;
  528. }
  529. }
  530. break;
  531. default:
  532. printf("handle_packet: what is %08x?!\n", p->msg.command);
  533. }
  534. put_apacket(p);
  535. }
  536. alistener listener_list = {
  537. .next = &listener_list,
  538. .prev = &listener_list,
  539. };
  540. static void ss_listener_event_func(int _fd, unsigned ev, void *_l)
  541. {
  542. asocket *s;
  543. if(ev & FDE_READ) {
  544. struct sockaddr addr;
  545. socklen_t alen;
  546. int fd;
  547. alen = sizeof(addr);
  548. fd = adb_socket_accept(_fd, &addr, &alen);
  549. if(fd < 0) return;
  550. adb_socket_setbufsize(fd, CHUNK_SIZE);
  551. s = create_local_socket(fd);
  552. if(s) {
  553. connect_to_smartsocket(s);
  554. return;
  555. }
  556. adb_close(fd);
  557. }
  558. }
  559. static void listener_event_func(int _fd, unsigned ev, void *_l)
  560. {
  561. alistener *l = _l;
  562. asocket *s;
  563. if(ev & FDE_READ) {
  564. struct sockaddr addr;
  565. socklen_t alen;
  566. int fd;
  567. alen = sizeof(addr);
  568. fd = adb_socket_accept(_fd, &addr, &alen);
  569. if(fd < 0) return;
  570. s = create_local_socket(fd);
  571. if(s) {
  572. s->transport = l->transport;
  573. connect_to_remote(s, l->connect_to);
  574. return;
  575. }
  576. adb_close(fd);
  577. }
  578. }
  579. static void free_listener(alistener* l)
  580. {
  581. if (l->next) {
  582. l->next->prev = l->prev;
  583. l->prev->next = l->next;
  584. l->next = l->prev = l;
  585. }
  586. // closes the corresponding fd
  587. fdevent_remove(&l->fde);
  588. if (l->local_name)
  589. free((char*)l->local_name);
  590. if (l->connect_to)
  591. free((char*)l->connect_to);
  592. if (l->transport) {
  593. remove_transport_disconnect(l->transport, &l->disconnect);
  594. }
  595. free(l);
  596. }
  597. static void listener_disconnect(void* _l, atransport* t)
  598. {
  599. alistener* l = _l;
  600. free_listener(l);
  601. }
  602. int local_name_to_fd(const char *name)
  603. {
  604. int port;
  605. if(!strncmp("tcp:", name, 4)){
  606. int ret;
  607. port = atoi(name + 4);
  608. ret = socket_loopback_server(port, SOCK_STREAM);
  609. return ret;
  610. }
  611. #ifndef HAVE_WIN32_IPC /* no Unix-domain sockets on Win32 */
  612. // It's non-sensical to support the "reserved" space on the adb host side
  613. if(!strncmp(name, "local:", 6)) {
  614. return socket_local_server(name + 6,
  615. ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
  616. } else if(!strncmp(name, "localabstract:", 14)) {
  617. return socket_local_server(name + 14,
  618. ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
  619. } else if(!strncmp(name, "localfilesystem:", 16)) {
  620. return socket_local_server(name + 16,
  621. ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
  622. }
  623. #endif
  624. printf("unknown local portname '%s'\n", name);
  625. return -1;
  626. }
  627. static int remove_listener(const char *local_name, const char *connect_to, atransport* transport)
  628. {
  629. alistener *l;
  630. for (l = listener_list.next; l != &listener_list; l = l->next) {
  631. if (!strcmp(local_name, l->local_name) &&
  632. !strcmp(connect_to, l->connect_to) &&
  633. l->transport && l->transport == transport) {
  634. listener_disconnect(l, transport);
  635. return 0;
  636. }
  637. }
  638. return -1;
  639. }
  640. static int install_listener(const char *local_name, const char *connect_to, atransport* transport)
  641. {
  642. alistener *l;
  643. //printf("install_listener('%s','%s')\n", local_name, connect_to);
  644. for(l = listener_list.next; l != &listener_list; l = l->next){
  645. if(strcmp(local_name, l->local_name) == 0) {
  646. char *cto;
  647. /* can't repurpose a smartsocket */
  648. if(l->connect_to[0] == '*') {
  649. return -1;
  650. }
  651. cto = strdup(connect_to);
  652. if(cto == 0) {
  653. return -1;
  654. }
  655. //printf("rebinding '%s' to '%s'\n", local_name, connect_to);
  656. free((void*) l->connect_to);
  657. l->connect_to = cto;
  658. if (l->transport != transport) {
  659. remove_transport_disconnect(l->transport, &l->disconnect);
  660. l->transport = transport;
  661. add_transport_disconnect(l->transport, &l->disconnect);
  662. }
  663. return 0;
  664. }
  665. }
  666. if((l = calloc(1, sizeof(alistener))) == 0) goto nomem;
  667. if((l->local_name = strdup(local_name)) == 0) goto nomem;
  668. if((l->connect_to = strdup(connect_to)) == 0) goto nomem;
  669. l->fd = local_name_to_fd(local_name);
  670. if(l->fd < 0) {
  671. free((void*) l->local_name);
  672. free((void*) l->connect_to);
  673. free(l);
  674. printf("cannot bind '%s'\n", local_name);
  675. return -2;
  676. }
  677. close_on_exec(l->fd);
  678. if(!strcmp(l->connect_to, "*smartsocket*")) {
  679. fdevent_install(&l->fde, l->fd, ss_listener_event_func, l);
  680. } else {
  681. fdevent_install(&l->fde, l->fd, listener_event_func, l);
  682. }
  683. fdevent_set(&l->fde, FDE_READ);
  684. l->next = &listener_list;
  685. l->prev = listener_list.prev;
  686. l->next->prev = l;
  687. l->prev->next = l;
  688. l->transport = transport;
  689. if (transport) {
  690. l->disconnect.opaque = l;
  691. l->disconnect.func = listener_disconnect;
  692. add_transport_disconnect(transport, &l->disconnect);
  693. }
  694. return 0;
  695. nomem:
  696. fatal("cannot allocate listener");
  697. return 0;
  698. }
  699. #ifdef HAVE_WIN32_PROC
  700. static BOOL WINAPI ctrlc_handler(DWORD type)
  701. {
  702. exit(STATUS_CONTROL_C_EXIT);
  703. return TRUE;
  704. }
  705. #endif
  706. static void adb_cleanup(void)
  707. {
  708. usb_cleanup();
  709. }
  710. void start_logging(void)
  711. {
  712. #ifdef HAVE_WIN32_PROC
  713. char temp[ MAX_PATH ];
  714. FILE* fnul;
  715. FILE* flog;
  716. GetTempPath( sizeof(temp) - 8, temp );
  717. strcat( temp, "adb.log" );
  718. /* Win32 specific redirections */
  719. fnul = fopen( "NUL", "rt" );
  720. if (fnul != NULL)
  721. stdin[0] = fnul[0];
  722. flog = fopen( temp, "at" );
  723. if (flog == NULL)
  724. flog = fnul;
  725. setvbuf( flog, NULL, _IONBF, 0 );
  726. stdout[0] = flog[0];
  727. stderr[0] = flog[0];
  728. fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
  729. #else
  730. int fd;
  731. fd = unix_open("/dev/null", O_RDONLY);
  732. dup2(fd, 0);
  733. adb_close(fd);
  734. fd = unix_open("/tmp/adb.log", O_WRONLY | O_CREAT | O_APPEND, 0640);
  735. if(fd < 0) {
  736. fd = unix_open("/dev/null", O_WRONLY);
  737. }
  738. dup2(fd, 1);
  739. dup2(fd, 2);
  740. adb_close(fd);
  741. fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
  742. #endif
  743. }
  744. #if !ADB_HOST
  745. void start_device_log(void)
  746. {
  747. int fd;
  748. char path[PATH_MAX];
  749. struct tm now;
  750. time_t t;
  751. char value[PROPERTY_VALUE_MAX];
  752. // read the trace mask from persistent property persist.adb.trace_mask
  753. // give up if the property is not set or cannot be parsed
  754. property_get("persist.adb.trace_mask", value, "");
  755. if (sscanf(value, "%x", &adb_trace_mask) != 1)
  756. return;
  757. adb_mkdir("/data/adb", 0775);
  758. tzset();
  759. time(&t);
  760. localtime_r(&t, &now);
  761. strftime(path, sizeof(path),
  762. "/data/adb/adb-%Y-%m-%d-%H-%M-%S.txt",
  763. &now);
  764. fd = unix_open(path, O_WRONLY | O_CREAT | O_TRUNC, 0640);
  765. if (fd < 0)
  766. return;
  767. // redirect stdout and stderr to the log file
  768. dup2(fd, 1);
  769. dup2(fd, 2);
  770. fprintf(stderr,"--- adb starting (pid %d) ---\n", getpid());
  771. adb_close(fd);
  772. fd = unix_open("/dev/null", O_RDONLY);
  773. dup2(fd, 0);
  774. adb_close(fd);
  775. }
  776. #endif
  777. #if ADB_HOST
  778. int launch_server(int server_port)
  779. {
  780. #ifdef HAVE_WIN32_PROC
  781. /* we need to start the server in the background */
  782. /* we create a PIPE that will be used to wait for the server's "OK" */
  783. /* message since the pipe handles must be inheritable, we use a */
  784. /* security attribute */
  785. HANDLE pipe_read, pipe_write;
  786. SECURITY_ATTRIBUTES sa;
  787. STARTUPINFO startup;
  788. PROCESS_INFORMATION pinfo;
  789. char program_path[ MAX_PATH ];
  790. int ret;
  791. sa.nLength = sizeof(sa);
  792. sa.lpSecurityDescriptor = NULL;
  793. sa.bInheritHandle = TRUE;
  794. /* create pipe, and ensure its read handle isn't inheritable */
  795. ret = CreatePipe( &pipe_read, &pipe_write, &sa, 0 );
  796. if (!ret) {
  797. fprintf(stderr, "CreatePipe() failure, error %ld\n", GetLastError() );
  798. return -1;
  799. }
  800. SetHandleInformation( pipe_read, HANDLE_FLAG_INHERIT, 0 );
  801. ZeroMemory( &startup, sizeof(startup) );
  802. startup.cb = sizeof(startup);
  803. startup.hStdInput = GetStdHandle( STD_INPUT_HANDLE );
  804. startup.hStdOutput = pipe_write;
  805. startup.hStdError = GetStdHandle( STD_ERROR_HANDLE );
  806. startup.dwFlags = STARTF_USESTDHANDLES;
  807. ZeroMemory( &pinfo, sizeof(pinfo) );
  808. /* get path of current program */
  809. GetModuleFileName( NULL, program_path, sizeof(program_path) );
  810. ret = CreateProcess(
  811. program_path, /* program path */
  812. "adb fork-server server",
  813. /* the fork-server argument will set the
  814. debug = 2 in the child */
  815. NULL, /* process handle is not inheritable */
  816. NULL, /* thread handle is not inheritable */
  817. TRUE, /* yes, inherit some handles */
  818. DETACHED_PROCESS, /* the new process doesn't have a console */
  819. NULL, /* use parent's environment block */
  820. NULL, /* use parent's starting directory */
  821. &startup, /* startup info, i.e. std handles */
  822. &pinfo );
  823. CloseHandle( pipe_write );
  824. if (!ret) {
  825. fprintf(stderr, "CreateProcess failure, error %ld\n", GetLastError() );
  826. CloseHandle( pipe_read );
  827. return -1;
  828. }
  829. CloseHandle( pinfo.hProcess );
  830. CloseHandle( pinfo.hThread );
  831. /* wait for the "OK\n" message */
  832. {
  833. char temp[3];
  834. DWORD count;
  835. ret = ReadFile( pipe_read, temp, 3, &count, NULL );
  836. CloseHandle( pipe_read );
  837. if ( !ret ) {
  838. fprintf(stderr, "could not read ok from ADB Server, error = %ld\n", GetLastError() );
  839. return -1;
  840. }
  841. if (count != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
  842. fprintf(stderr, "ADB server didn't ACK\n" );
  843. return -1;
  844. }
  845. }
  846. #elif defined(HAVE_FORKEXEC)
  847. char path[PATH_MAX];
  848. int fd[2];
  849. // set up a pipe so the child can tell us when it is ready.
  850. // fd[0] will be parent's end, and fd[1] will get mapped to stderr in the child.
  851. if (pipe(fd)) {
  852. fprintf(stderr, "pipe failed in launch_server, errno: %d\n", errno);
  853. return -1;
  854. }
  855. get_my_path(path, PATH_MAX);
  856. pid_t pid = fork();
  857. if(pid < 0) return -1;
  858. if (pid == 0) {
  859. // child side of the fork
  860. // redirect stderr to the pipe
  861. // we use stderr instead of stdout due to stdout's buffering behavior.
  862. adb_close(fd[0]);
  863. dup2(fd[1], STDERR_FILENO);
  864. adb_close(fd[1]);
  865. // child process
  866. int result = execl(path, "adb", "fork-server", "server", NULL);
  867. // this should not return
  868. fprintf(stderr, "OOPS! execl returned %d, errno: %d\n", result, errno);
  869. } else {
  870. // parent side of the fork
  871. char temp[3];
  872. temp[0] = 'A'; temp[1] = 'B'; temp[2] = 'C';
  873. // wait for the "OK\n" message
  874. adb_close(fd[1]);
  875. int ret = adb_read(fd[0], temp, 3);
  876. int saved_errno = errno;
  877. adb_close(fd[0]);
  878. if (ret < 0) {
  879. fprintf(stderr, "could not read ok from ADB Server, errno = %d\n", saved_errno);
  880. return -1;
  881. }
  882. if (ret != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
  883. fprintf(stderr, "ADB server didn't ACK\n" );
  884. return -1;
  885. }
  886. setsid();
  887. }
  888. #else
  889. #error "cannot implement background server start on this platform"
  890. #endif
  891. return 0;
  892. }
  893. #endif
  894. /* Constructs a local name of form tcp:port.
  895. * target_str points to the target string, it's content will be overwritten.
  896. * target_size is the capacity of the target string.
  897. * server_port is the port number to use for the local name.
  898. */
  899. void build_local_name(char* target_str, size_t target_size, int server_port)
  900. {
  901. snprintf(target_str, target_size, "tcp:%d", server_port);
  902. }
  903. #if !ADB_HOST
  904. static int should_drop_privileges() {
  905. #ifndef ALLOW_ADBD_ROOT
  906. return 1;
  907. #else /* ALLOW_ADBD_ROOT */
  908. int secure = 0;
  909. char value[PROPERTY_VALUE_MAX];
  910. /* run adbd in secure mode if ro.secure is set and
  911. ** we are not in the emulator
  912. */
  913. property_get("ro.kernel.qemu", value, "");
  914. if (strcmp(value, "1") != 0) {
  915. property_get("ro.secure", value, "1");
  916. if (strcmp(value, "1") == 0) {
  917. // don't run as root if ro.secure is set...
  918. secure = 1;
  919. // ... except we allow running as root in userdebug builds if the
  920. // service.adb.root property has been set by the "adb root" command
  921. property_get("ro.debuggable", value, "");
  922. if (strcmp(value, "1") == 0) {
  923. property_get("service.adb.root", value, "");
  924. if (strcmp(value, "1") == 0) {
  925. secure = 0;
  926. }
  927. }
  928. }
  929. }
  930. return secure;
  931. #endif /* ALLOW_ADBD_ROOT */
  932. }
  933. #endif /* !ADB_HOST */
  934. extern char *external_key_path;
  935. int adb_main(int is_daemon, int server_port)
  936. {
  937. #if !ADB_HOST
  938. int port;
  939. char value[PROPERTY_VALUE_MAX];
  940. umask(000);
  941. #endif
  942. atexit(adb_cleanup);
  943. #ifdef HAVE_WIN32_PROC
  944. SetConsoleCtrlHandler( ctrlc_handler, TRUE );
  945. #elif defined(HAVE_FORKEXEC)
  946. // No SIGCHLD. Let the service subproc handle its children.
  947. signal(SIGPIPE, SIG_IGN);
  948. #endif
  949. init_transport_registration();
  950. #if ADB_HOST
  951. HOST = 1;
  952. usb_vendors_init();
  953. usb_init();
  954. local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
  955. adb_auth_init();
  956. char local_name[30];
  957. build_local_name(local_name, sizeof(local_name), server_port);
  958. if(install_listener(local_name, "*smartsocket*", NULL)) {
  959. exit(1);
  960. }
  961. #else
  962. #if 0
  963. property_get("ro.adb.secure", value, "0");
  964. auth_enabled = !strcmp(value, "1");
  965. #else
  966. char *auth_value = NULL;
  967. auth_value = getenv("ADB_AUTH_ENABLE");
  968. if (auth_value != NULL) {
  969. auth_enabled = !strcmp(auth_value, "1");
  970. }
  971. #endif
  972. if (auth_enabled) {
  973. char *key_path = NULL;
  974. if (external_key_path != NULL) {
  975. free(external_key_path);
  976. external_key_path = NULL;
  977. }
  978. key_path = getenv("ADB_AUTH_EXTERNAL_KEY_PATH");
  979. if (key_path != NULL) {
  980. external_key_path = strdup(key_path);
  981. D("ADB_AUTH_EXTERNAL_KEY_PATH=%s\n", external_key_path);
  982. }
  983. adb_auth_init();
  984. }
  985. // Our external storage path may be different than apps, since
  986. // we aren't able to bind mount after dropping root.
  987. const char* adb_external_storage = getenv("ADB_EXTERNAL_STORAGE");
  988. if (NULL != adb_external_storage) {
  989. setenv("EXTERNAL_STORAGE", adb_external_storage, 1);
  990. } else {
  991. D("Warning: ADB_EXTERNAL_STORAGE is not set. Leaving EXTERNAL_STORAGE"
  992. " unchanged.\n");
  993. }
  994. /* don't listen on a port (default 5037) if running in secure mode */
  995. /* don't run as root if we are running in secure mode */
  996. if (should_drop_privileges()) {
  997. struct __user_cap_header_struct header;
  998. struct __user_cap_data_struct cap;
  999. if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
  1000. exit(1);
  1001. }
  1002. /* add extra groups:
  1003. ** AID_ADB to access the USB driver
  1004. ** AID_LOG to read system logs (adb logcat)
  1005. ** AID_INPUT to diagnose input issues (getevent)
  1006. ** AID_INET to diagnose network issues (netcfg, ping)
  1007. ** AID_GRAPHICS to access the frame buffer
  1008. ** AID_NET_BT and AID_NET_BT_ADMIN to diagnose bluetooth (hcidump)
  1009. ** AID_SDCARD_R to allow reading from the SD card
  1010. ** AID_SDCARD_RW to allow writing to the SD card
  1011. ** AID_MOUNT to allow unmounting the SD card before rebooting
  1012. ** AID_NET_BW_STATS to read out qtaguid statistics
  1013. */
  1014. gid_t groups[] = { AID_ADB, AID_LOG, AID_INPUT, AID_INET, AID_GRAPHICS,
  1015. AID_NET_BT, AID_NET_BT_ADMIN, AID_SDCARD_R, AID_SDCARD_RW,
  1016. AID_MOUNT, AID_NET_BW_STATS };
  1017. if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
  1018. exit(1);
  1019. }
  1020. /* then switch user and group to "shell" */
  1021. if (setgid(AID_SHELL) != 0) {
  1022. exit(1);
  1023. }
  1024. if (setuid(AID_SHELL) != 0) {
  1025. exit(1);
  1026. }
  1027. /* set CAP_SYS_BOOT capability, so "adb reboot" will succeed */
  1028. header.version = _LINUX_CAPABILITY_VERSION;
  1029. header.pid = 0;
  1030. cap.effective = cap.permitted = (1 << CAP_SYS_BOOT);
  1031. cap.inheritable = 0;
  1032. capset(&header, &cap);
  1033. D("Local port disabled\n");
  1034. } else {
  1035. char local_name[30];
  1036. build_local_name(local_name, sizeof(local_name), server_port);
  1037. if(install_listener(local_name, "*smartsocket*", NULL)) {
  1038. exit(1);
  1039. }
  1040. }
  1041. int usb = 0;
  1042. if (access(USB_ADB_PATH, F_OK) == 0 || access(USB_FFS_ADB_EP0, F_OK) == 0) {
  1043. // listen on USB
  1044. usb_init();
  1045. usb = 1;
  1046. }
  1047. // If one of these properties is set, also listen on that port
  1048. // If one of the properties isn't set and we couldn't listen on usb,
  1049. // listen on the default port.
  1050. #if 0
  1051. property_get("service.adb.tcp.port", value, "");
  1052. if (!value[0]) {
  1053. property_get("persist.adb.tcp.port", value, "");
  1054. }
  1055. #else
  1056. char *port_value = NULL;
  1057. port_value = getenv("ADB_TRANSPORT_PORT");
  1058. if (port_value != NULL) {
  1059. strncpy(value, port_value, strlen(port_value)+1);
  1060. }
  1061. #endif
  1062. if (sscanf(value, "%d", &port) == 1 && port > 0) {
  1063. printf("using port=%d\n", port);
  1064. // listen on TCP port specified by service.adb.tcp.port property
  1065. local_init(port);
  1066. } else if (!usb) {
  1067. // listen on default port
  1068. local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT);
  1069. }
  1070. D("adb_main(): pre init_jdwp()\n");
  1071. init_jdwp();
  1072. D("adb_main(): post init_jdwp()\n");
  1073. #endif
  1074. if (is_daemon)
  1075. {
  1076. // inform our parent that we are up and running.
  1077. #ifdef HAVE_WIN32_PROC
  1078. DWORD count;
  1079. WriteFile( GetStdHandle( STD_OUTPUT_HANDLE ), "OK\n", 3, &count, NULL );
  1080. #elif defined(HAVE_FORKEXEC)
  1081. fprintf(stderr, "OK\n");
  1082. #endif
  1083. start_logging();
  1084. }
  1085. D("Event loop starting\n");
  1086. fdevent_loop();
  1087. usb_cleanup();
  1088. return 0;
  1089. }
  1090. #if ADB_HOST
  1091. void connect_device(char* host, char* buffer, int buffer_size)
  1092. {
  1093. int port, fd;
  1094. char* portstr = strchr(host, ':');
  1095. char hostbuf[100];
  1096. char serial[100];
  1097. memset(hostbuf, 0, sizeof(hostbuf));
  1098. strncpy(hostbuf, host, sizeof(hostbuf) - 1);
  1099. if (portstr) {
  1100. if (portstr - host >= (ptrdiff_t)sizeof(hostbuf)) {
  1101. snprintf(buffer, buffer_size, "bad host name %s", host);
  1102. return;
  1103. }
  1104. // zero terminate the host at the point we found the colon
  1105. hostbuf[portstr - host] = 0;
  1106. if (sscanf(portstr + 1, "%d", &port) == 0) {
  1107. snprintf(buffer, buffer_size, "bad port number %s", portstr);
  1108. return;
  1109. }
  1110. } else {
  1111. port = DEFAULT_ADB_LOCAL_TRANSPORT_PORT;
  1112. }
  1113. snprintf(serial, sizeof(serial), "%s:%d", hostbuf, port);
  1114. if (find_transport(serial)) {
  1115. snprintf(buffer, buffer_size, "already connected to %s", serial);
  1116. return;
  1117. }
  1118. fd = socket_network_client(hostbuf, port, SOCK_STREAM);
  1119. if (fd < 0) {
  1120. snprintf(buffer, buffer_size, "unable to connect to %s:%d", host, port);
  1121. return;
  1122. }
  1123. D("client: connected on remote on fd %d\n", fd);
  1124. close_on_exec(fd);
  1125. disable_tcp_nagle(fd);
  1126. register_socket_transport(fd, serial, port, 0);
  1127. snprintf(buffer, buffer_size, "connected to %s", serial);
  1128. }
  1129. void connect_emulator(char* port_spec, char* buffer, int buffer_size)
  1130. {
  1131. char* port_separator = strchr(port_spec, ',');
  1132. if (!port_separator) {
  1133. snprintf(buffer, buffer_size,
  1134. "unable to parse '%s' as <console port>,<adb port>",
  1135. port_spec);
  1136. return;
  1137. }
  1138. // Zero-terminate console port and make port_separator point to 2nd port.
  1139. *port_separator++ = 0;
  1140. int console_port = strtol(port_spec, NULL, 0);
  1141. int adb_port = strtol(port_separator, NULL, 0);
  1142. if (!(console_port > 0 && adb_port > 0)) {
  1143. *(port_separator - 1) = ',';
  1144. snprintf(buffer, buffer_size,
  1145. "Invalid port numbers: Expected positive numbers, got '%s'",
  1146. port_spec);
  1147. return;
  1148. }
  1149. /* Check if the emulator is already known.
  1150. * Note: There's a small but harmless race condition here: An emulator not
  1151. * present just yet could be registered by another invocation right
  1152. * after doing this check here. However, local_connect protects
  1153. * against double-registration too. From here, a better error message
  1154. * can be produced. In the case of the race condition, the very specific
  1155. * error message won't be shown, but the data doesn't get corrupted. */
  1156. atransport* known_emulator = find_emulator_transport_by_adb_port(adb_port);
  1157. if (known_emulator != NULL) {
  1158. snprintf(buffer, buffer_size,
  1159. "Emulator on port %d already registered.", adb_port);
  1160. return;
  1161. }
  1162. /* Check if more emulators can be registered. Similar unproblematic
  1163. * race condition as above. */
  1164. int candidate_slot = get_available_local_transport_index();
  1165. if (candidate_slot < 0) {
  1166. snprintf(buffer, buffer_size, "Cannot accept more emulators.");
  1167. return;
  1168. }
  1169. /* Preconditions met, try to connect to the emulator. */
  1170. if (!local_connect_arbitrary_ports(console_port, adb_port)) {
  1171. snprintf(buffer, buffer_size,
  1172. "Connected to emulator on ports %d,%d", console_port, adb_port);
  1173. } else {
  1174. snprintf(buffer, buffer_size,
  1175. "Could not connect to emulator on ports %d,%d",
  1176. console_port, adb_port);
  1177. }
  1178. }
  1179. #endif
  1180. int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s)
  1181. {
  1182. atransport *transport = NULL;
  1183. char buf[4096];
  1184. if(!strcmp(service, "kill")) {
  1185. fprintf(stderr,"adb server killed by remote request\n");
  1186. fflush(stdout);
  1187. adb_write(reply_fd, "OKAY", 4);
  1188. usb_cleanup();
  1189. exit(0);
  1190. }
  1191. #if ADB_HOST
  1192. // "transport:" is used for switching transport with a specified serial number
  1193. // "transport-usb:" is used for switching transport to the only USB transport
  1194. // "transport-local:" is used for switching transport to the only local transport
  1195. // "transport-any:" is used for switching transport to the only transport
  1196. if (!strncmp(service, "transport", strlen("transport"))) {
  1197. char* error_string = "unknown failure";
  1198. transport_type type = kTransportAny;
  1199. if (!strncmp(service, "transport-usb", strlen("transport-usb"))) {
  1200. type = kTransportUsb;
  1201. } else if (!strncmp(service, "transport-local", strlen("transport-local"))) {
  1202. type = kTransportLocal;
  1203. } else if (!strncmp(service, "transport-any", strlen("transport-any"))) {
  1204. type = kTransportAny;
  1205. } else if (!strncmp(service, "transport:", strlen("transport:"))) {
  1206. service += strlen("transport:");
  1207. serial = service;
  1208. }
  1209. transport = acquire_one_transport(CS_ANY, type, serial, &error_string);
  1210. if (transport) {
  1211. s->transport = transport;
  1212. adb_write(reply_fd, "OKAY", 4);
  1213. } else {
  1214. sendfailmsg(reply_fd, error_string);
  1215. }
  1216. return 1;
  1217. }
  1218. // return a list of all connected devices
  1219. if (!strncmp(service, "devices", 7)) {
  1220. char buffer[4096];
  1221. int use_long = !strcmp(service+7, "-l");
  1222. if (use_long || service[7] == 0) {
  1223. memset(buf, 0, sizeof(buf));
  1224. memset(buffer, 0, sizeof(buffer));
  1225. D("Getting device list \n");
  1226. list_transports(buffer, sizeof(buffer), use_long);
  1227. snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer),buffer);
  1228. D("Wrote device list \n");
  1229. writex(reply_fd, buf, strlen(buf));
  1230. return 0;
  1231. }
  1232. }
  1233. // add a new TCP transport, device or emulator
  1234. if (!strncmp(service, "connect:", 8)) {
  1235. char buffer[4096];
  1236. char* host = service + 8;
  1237. if (!strncmp(host, "emu:", 4)) {
  1238. connect_emulator(host + 4, buffer, sizeof(buffer));
  1239. } else {
  1240. connect_device(host, buffer, sizeof(buffer));
  1241. }
  1242. // Send response for emulator and device
  1243. snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
  1244. writex(reply_fd, buf, strlen(buf));
  1245. return 0;
  1246. }
  1247. // remove TCP transport
  1248. if (!strncmp(service, "disconnect:", 11)) {
  1249. char buffer[4096];
  1250. memset(buffer, 0, sizeof(buffer));
  1251. char* serial = service + 11;
  1252. if (serial[0] == 0) {
  1253. // disconnect from all TCP devices
  1254. unregister_all_tcp_transports();
  1255. } else {
  1256. char hostbuf[100];
  1257. // assume port 5555 if no port is specified
  1258. if (!strchr(serial, ':')) {
  1259. snprintf(hostbuf, sizeof(hostbuf) - 1, "%s:5555", serial);
  1260. serial = hostbuf;
  1261. }
  1262. atransport *t = find_transport(serial);
  1263. if (t) {
  1264. unregister_transport(t);
  1265. } else {
  1266. snprintf(buffer, sizeof(buffer), "No such device %s", serial);
  1267. }
  1268. }
  1269. snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
  1270. writex(reply_fd, buf, strlen(buf));
  1271. return 0;
  1272. }
  1273. // returns our value for ADB_SERVER_VERSION
  1274. if (!strcmp(service, "version")) {
  1275. char version[12];
  1276. snprintf(version, sizeof version, "%04x", ADB_SERVER_VERSION);
  1277. snprintf(buf, sizeof buf, "OKAY%04x%s", (unsigned)strlen(version), version);
  1278. writex(reply_fd, buf, strlen(buf));
  1279. return 0;
  1280. }
  1281. if(!strncmp(service,"get-serialno",strlen("get-serialno"))) {
  1282. char *out = "unknown";
  1283. transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
  1284. if (transport && transport->serial) {
  1285. out = transport->serial;
  1286. }
  1287. snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(out),out);
  1288. writex(reply_fd, buf, strlen(buf));
  1289. return 0;
  1290. }
  1291. if(!strncmp(service,"get-devpath",strlen("get-devpath"))) {
  1292. char *out = "unknown";
  1293. transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
  1294. if (transport && transport->devpath) {
  1295. out = transport->devpath;
  1296. }
  1297. snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(out),out);
  1298. writex(reply_fd, buf, strlen(buf));
  1299. return 0;
  1300. }
  1301. // indicates a new emulator instance has started
  1302. if (!strncmp(service,"emulator:",9)) {
  1303. int port = atoi(service+9);
  1304. local_connect(port);
  1305. /* we don't even need to send a reply */
  1306. return 0;
  1307. }
  1308. #endif // ADB_HOST
  1309. if(!strncmp(service,"forward:",8) || !strncmp(service,"killforward:",12)) {
  1310. char *local, *remote, *err;
  1311. int r;
  1312. atransport *transport;
  1313. int createForward = strncmp(service,"kill",4);
  1314. local = service + (createForward ? 8 : 12);
  1315. remote = strchr(local,';');
  1316. if(remote == 0) {
  1317. sendfailmsg(reply_fd, "malformed forward spec");
  1318. return 0;
  1319. }
  1320. *remote++ = 0;
  1321. if((local[0] == 0) || (remote[0] == 0) || (remote[0] == '*')){
  1322. sendfailmsg(reply_fd, "malformed forward spec");
  1323. return 0;
  1324. }
  1325. transport = acquire_one_transport(CS_ANY, ttype, serial, &err);
  1326. if (!transport) {
  1327. sendfailmsg(reply_fd, err);
  1328. return 0;
  1329. }
  1330. if (createForward) {
  1331. r = install_listener(local, remote, transport);
  1332. } else {
  1333. r = remove_listener(local, remote, transport);
  1334. }
  1335. if(r == 0) {
  1336. /* 1st OKAY is connect, 2nd OKAY is status */
  1337. writex(reply_fd, "OKAYOKAY", 8);
  1338. return 0;
  1339. }
  1340. if (createForward) {
  1341. sendfailmsg(reply_fd, (r == -1) ? "cannot rebind smartsocket" : "cannot bind socket");
  1342. } else {
  1343. sendfailmsg(reply_fd, "cannot remove listener");
  1344. }
  1345. return 0;
  1346. }
  1347. if(!strncmp(service,"get-state",strlen("get-state"))) {
  1348. transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
  1349. char *state = connection_state_name(transport);
  1350. snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(state),state);
  1351. writex(reply_fd, buf, strlen(buf));
  1352. return 0;
  1353. }
  1354. return -1;
  1355. }
  1356. #if !ADB_HOST
  1357. int recovery_mode = 0;
  1358. #endif
  1359. int main(int argc, char **argv)
  1360. {
  1361. //check_chip();
  1362. #if ADB_HOST
  1363. adb_sysdeps_init();
  1364. adb_trace_init();
  1365. D("Handling commandline()\n");
  1366. return adb_commandline(argc - 1, argv + 1);
  1367. #else
  1368. /* If adbd runs inside the emulator this will enable adb tracing via
  1369. * adb-debug qemud service in the emulator. */
  1370. printf("init adb main\n");
  1371. adb_qemu_trace_init();
  1372. if((argc > 1) && (!strcmp(argv[1],"recovery"))) {
  1373. adb_device_banner = "recovery";
  1374. recovery_mode = 1;
  1375. }
  1376. start_device_log();
  1377. D("Handling main()\n");
  1378. printf("Handling main()\n");
  1379. return adb_main(0, DEFAULT_ADB_PORT);
  1380. #endif
  1381. }