2 * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #define TRACE_TAG TRACE_SDB
34 //#include <private/android_filesystem_config.h> eric
35 #include <linux/capability.h>
36 #include <linux/prctl.h>
37 #define SDB_PIDPATH "/tmp/.sdbd.pid"
39 #include "usb_vendors.h"
43 SDB_MUTEX_DEFINE( D_lock );
48 void handle_sig_term(int sig) {
50 if (access(SDB_PIDPATH, F_OK) == 0)
51 sdb_unlink(SDB_PIDPATH);
53 //kill(getpgid(getpid()),SIGTERM);
54 //killpg(getpgid(getpid()),SIGTERM);
55 if (access("/dev/samsung_sdb", F_OK) == 0) {
58 // do nothing on a emulator
62 static const char *sdb_device_banner = "device";
64 void fatal(const char *fmt, ...)
68 fprintf(stderr, "error: ");
69 vfprintf(stderr, fmt, ap);
70 fprintf(stderr, "\n");
75 void fatal_errno(const char *fmt, ...)
79 fprintf(stderr, "error: %s: ", strerror(errno));
80 vfprintf(stderr, fmt, ap);
81 fprintf(stderr, "\n");
88 /* read a comma/space/colum/semi-column separated list of tags
89 * from the SDB_TRACE environment variable and build the trace
90 * mask from it. note that '1' and 'all' are special cases to
93 void sdb_trace_init(void)
95 const char* p = getenv("SDB_TRACE");
104 { "sdb", TRACE_SDB },
105 { "sockets", TRACE_SOCKETS },
106 { "packets", TRACE_PACKETS },
107 { "rwx", TRACE_RWX },
108 { "usb", TRACE_USB },
109 { "sync", TRACE_SYNC },
110 { "sysdeps", TRACE_SYSDEPS },
111 { "transport", TRACE_TRANSPORT },
112 { "jdwp", TRACE_JDWP },
113 { "services", TRACE_SERVICES },
114 { "properties", TRACE_PROPERTIES },
115 { "sdktools", TRACE_SDKTOOLS },
122 /* use a comma/column/semi-colum/space separated list */
126 q = strpbrk(p, " ,:;");
132 for (tagn = 0; tags[tagn].tag != NULL; tagn++)
134 int taglen = strlen(tags[tagn].tag);
136 if (len == taglen && !memcmp(tags[tagn].tag, p, len) )
138 int flag = tags[tagn].flag;
143 sdb_trace_mask |= (1 << flag);
155 * Implements SDB tracing inside the emulator.
161 * Redefine open and write for qemu_pipe.h that contains inlined references
162 * to those routines. We will redifine them back after qemu_pipe.h inclusion.
167 #define open sdb_open
168 #define write sdb_write
169 #include "qemu_pipe.h"
172 #define open ___xxx_open
173 #define write ___xxx_write
175 /* A handle to sdb-debug qemud service in the emulator. */
176 int sdb_debug_qemu = -1;
178 /* Initializes connection with the sdb-debug qemud service in the emulator. */
179 #if 0 /* doen't support in Tizen */
180 static int sdb_qemu_trace_init(void)
184 if (sdb_debug_qemu >= 0) {
188 /* sdb debugging QEMUD service connection request. */
189 snprintf(con_name, sizeof(con_name), "qemud:sdb-debug");
190 sdb_debug_qemu = qemu_pipe_open(con_name);
191 return (sdb_debug_qemu >= 0) ? 0 : -1;
194 void sdb_qemu_trace(const char* fmt, ...)
200 if (sdb_debug_qemu >= 0) {
201 vsnprintf(msg, sizeof(msg), fmt, args);
202 sdb_write(sdb_debug_qemu, msg, strlen(msg));
206 #endif /* !SDB_HOST */
208 apacket *get_apacket(void)
210 apacket *p = malloc(sizeof(apacket));
211 if(p == 0) fatal("failed to allocate an apacket");
212 memset(p, 0, sizeof(apacket) - MAX_PAYLOAD);
216 void put_apacket(apacket *p)
224 void handle_online(void)
229 void handle_offline(atransport *t)
232 //Close the associated usb
233 run_transport_disconnects(t);
238 void print_packet(const char *label, apacket *p)
244 switch(p->msg.command){
245 case A_SYNC: tag = "SYNC"; break;
246 case A_CNXN: tag = "CNXN" ; break;
247 case A_OPEN: tag = "OPEN"; break;
248 case A_OKAY: tag = "OKAY"; break;
249 case A_CLSE: tag = "CLSE"; break;
250 case A_WRTE: tag = "WRTE"; break;
251 default: tag = "????"; break;
254 fprintf(stderr, "%s: %s %08x %08x %04x \"",
255 label, tag, p->msg.arg0, p->msg.arg1, p->msg.data_length);
256 count = p->msg.data_length;
258 if(count > DUMPMAX) {
265 if((*x >= ' ') && (*x < 127)) {
272 fprintf(stderr, tag);
276 static void send_ready(unsigned local, unsigned remote, atransport *t)
278 D("Calling send_ready \n");
279 apacket *p = get_apacket();
280 p->msg.command = A_OKAY;
282 p->msg.arg1 = remote;
286 static void send_close(unsigned local, unsigned remote, atransport *t)
288 D("Calling send_close \n");
289 apacket *p = get_apacket();
290 p->msg.command = A_CLSE;
292 p->msg.arg1 = remote;
296 static void send_connect(atransport *t)
298 D("Calling send_connect \n");
299 apacket *cp = get_apacket();
300 cp->msg.command = A_CNXN;
301 cp->msg.arg0 = A_VERSION;
302 cp->msg.arg1 = MAX_PAYLOAD;
303 snprintf((char*) cp->data, sizeof cp->data, "%s::",
304 HOST ? "host" : sdb_device_banner);
305 cp->msg.data_length = strlen((char*) cp->data) + 1;
308 /* XXX why sleep here? */
309 // allow the device some time to respond to the connect message
314 static char *connection_state_name(atransport *t)
320 switch(t->connection_state) {
332 void parse_banner(char *banner, atransport *t)
334 char *type, *product, *end;
336 D("parse_banner: %s\n", banner);
338 product = strchr(type, ':');
345 /* remove trailing ':' */
346 end = strchr(product, ':');
349 /* save product name in device structure */
350 if (t->product == NULL) {
351 t->product = strdup(product);
352 } else if (strcmp(product, t->product) != 0) {
354 t->product = strdup(product);
357 if(!strcmp(type, "bootloader")){
358 D("setting connection_state to CS_BOOTLOADER\n");
359 t->connection_state = CS_BOOTLOADER;
364 if(!strcmp(type, "device")) {
365 D("setting connection_state to CS_DEVICE\n");
366 t->connection_state = CS_DEVICE;
371 if(!strcmp(type, "recovery")) {
372 D("setting connection_state to CS_RECOVERY\n");
373 t->connection_state = CS_RECOVERY;
378 if(!strcmp(type, "sideload")) {
379 D("setting connection_state to CS_SIDELOAD\n");
380 t->connection_state = CS_SIDELOAD;
385 t->connection_state = CS_HOST;
388 void handle_packet(apacket *p, atransport *t)
392 D("handle_packet() %c%c%c%c\n", ((char*) (&(p->msg.command)))[0],
393 ((char*) (&(p->msg.command)))[1],
394 ((char*) (&(p->msg.command)))[2],
395 ((char*) (&(p->msg.command)))[3]);
397 print_packet("recv", p);
399 switch(p->msg.command){
403 if(HOST) send_connect(t);
405 t->connection_state = CS_OFFLINE;
411 case A_CNXN: /* CONNECT(version, maxdata, "system-id-string") */
412 /* XXX verify version, etc */
413 if(t->connection_state != CS_OFFLINE) {
414 t->connection_state = CS_OFFLINE;
417 parse_banner((char*) p->data, t);
419 if(!HOST) send_connect(t);
422 case A_OPEN: /* OPEN(local-id, 0, "destination") */
423 if(t->connection_state != CS_OFFLINE) {
424 char *name = (char*) p->data;
425 name[p->msg.data_length > 0 ? p->msg.data_length - 1 : 0] = 0;
426 s = create_local_service_socket(name);
428 send_close(0, p->msg.arg0, t);
430 s->peer = create_remote_socket(p->msg.arg0, t);
432 send_ready(s->id, s->peer->id, t);
438 case A_OKAY: /* READY(local-id, remote-id, "") */
439 if(t->connection_state != CS_OFFLINE) {
440 if((s = find_local_socket(p->msg.arg1))) {
442 s->peer = create_remote_socket(p->msg.arg0, t);
450 case A_CLSE: /* CLOSE(local-id, remote-id, "") */
451 if(t->connection_state != CS_OFFLINE) {
452 if((s = find_local_socket(p->msg.arg1))) {
459 if(t->connection_state != CS_OFFLINE) {
460 if((s = find_local_socket(p->msg.arg1))) {
461 unsigned rid = p->msg.arg0;
462 p->len = p->msg.data_length;
464 if(s->enqueue(s, p) == 0) {
465 D("Enqueue the socket\n");
466 send_ready(s->id, rid, t);
474 printf("handle_packet: what is %08x?!\n", p->msg.command);
480 alistener listener_list = {
481 .next = &listener_list,
482 .prev = &listener_list,
485 static void ss_listener_event_func(int _fd, unsigned ev, void *_l)
490 struct sockaddr addr;
495 fd = sdb_socket_accept(_fd, &addr, &alen);
498 sdb_socket_setbufsize(fd, CHUNK_SIZE);
500 s = create_local_socket(fd);
502 connect_to_smartsocket(s);
510 static void listener_event_func(int _fd, unsigned ev, void *_l)
516 struct sockaddr addr;
521 fd = sdb_socket_accept(_fd, &addr, &alen);
524 s = create_local_socket(fd);
526 s->transport = l->transport;
527 connect_to_remote(s, l->connect_to);
535 static void free_listener(alistener* l)
538 l->next->prev = l->prev;
539 l->prev->next = l->next;
540 l->next = l->prev = l;
543 // closes the corresponding fd
544 fdevent_remove(&l->fde);
547 free((char*)l->local_name);
550 free((char*)l->connect_to);
553 remove_transport_disconnect(l->transport, &l->disconnect);
558 static void listener_disconnect(void* _l, atransport* t)
565 int local_name_to_fd(const char *name)
569 if(!strncmp("tcp:", name, 4)){
571 port = atoi(name + 4);
572 ret = socket_loopback_server(port, SOCK_STREAM);
575 #ifndef HAVE_WIN32_IPC /* no Unix-domain sockets on Win32 */
576 // It's non-sensical to support the "reserved" space on the sdb host side
577 if(!strncmp(name, "local:", 6)) {
578 return socket_local_server(name + 6,
579 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
580 } else if(!strncmp(name, "localabstract:", 14)) {
581 return socket_local_server(name + 14,
582 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
583 } else if(!strncmp(name, "localfilesystem:", 16)) {
584 return socket_local_server(name + 16,
585 ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
589 printf("unknown local portname '%s'\n", name);
593 static int remove_listener(const char *local_name, const char *connect_to, atransport* transport)
597 for (l = listener_list.next; l != &listener_list; l = l->next) {
598 if (!strcmp(local_name, l->local_name) &&
599 !strcmp(connect_to, l->connect_to) &&
600 l->transport && l->transport == transport) {
602 listener_disconnect(l, transport);
610 static int install_listener(const char *local_name, const char *connect_to, atransport* transport)
614 //printf("install_listener('%s','%s')\n", local_name, connect_to);
616 for(l = listener_list.next; l != &listener_list; l = l->next){
617 if(strcmp(local_name, l->local_name) == 0) {
620 /* can't repurpose a smartsocket */
621 if(l->connect_to[0] == '*') {
625 cto = strdup(connect_to);
630 //printf("rebinding '%s' to '%s'\n", local_name, connect_to);
631 free((void*) l->connect_to);
633 if (l->transport != transport) {
634 remove_transport_disconnect(l->transport, &l->disconnect);
635 l->transport = transport;
636 add_transport_disconnect(l->transport, &l->disconnect);
642 if((l = calloc(1, sizeof(alistener))) == 0) goto nomem;
643 if((l->local_name = strdup(local_name)) == 0) goto nomem;
644 if((l->connect_to = strdup(connect_to)) == 0) goto nomem;
647 l->fd = local_name_to_fd(local_name);
649 free((void*) l->local_name);
650 free((void*) l->connect_to);
652 printf("cannot bind '%s'\n", local_name);
656 if (close_on_exec(l->fd) < 0) {
657 D("fail to close fd exec:%d\n",l->fd);
659 if(!strcmp(l->connect_to, "*smartsocket*")) {
660 fdevent_install(&l->fde, l->fd, ss_listener_event_func, l);
662 fdevent_install(&l->fde, l->fd, listener_event_func, l);
664 fdevent_set(&l->fde, FDE_READ);
666 l->next = &listener_list;
667 l->prev = listener_list.prev;
670 l->transport = transport;
673 l->disconnect.opaque = l;
674 l->disconnect.func = listener_disconnect;
675 add_transport_disconnect(transport, &l->disconnect);
680 fatal("cannot allocate listener");
684 #ifdef HAVE_WIN32_PROC
685 static BOOL WINAPI ctrlc_handler(DWORD type)
687 exit(STATUS_CONTROL_C_EXIT);
692 static void sdb_cleanup(void)
697 void start_logging(void)
699 #ifdef HAVE_WIN32_PROC
700 char temp[ MAX_PATH ];
704 GetTempPath( sizeof(temp) - 8, temp );
705 strcat( temp, "sdb.log" );
707 /* Win32 specific redirections */
708 fnul = fopen( "NUL", "rt" );
712 flog = fopen( temp, "at" );
716 setvbuf( flog, NULL, _IONBF, 0 );
720 fprintf(stderr,"--- sdb starting (pid %d) ---\n", getpid());
724 fd = unix_open("/dev/null", O_RDONLY);
726 // hopefully not gonna happen
732 fd = unix_open("/tmp/sdb.log", O_WRONLY | O_CREAT | O_APPEND, 0640);
734 fd = unix_open("/dev/null", O_WRONLY);
736 // hopefully not gonna happen
743 fprintf(stderr,"--- sdb starting (pid %d) ---\n", getpid());
748 void start_device_log(void)
754 // char value[PROPERTY_VALUE_MAX];
755 const char* p = getenv("SDB_TRACE");
756 // read the trace mask from persistent property persist.sdb.trace_mask
757 // give up if the property is not set or cannot be parsed
758 #if 0 /* tizen specific */
759 property_get("persist.sdb.trace_mask", value, "");
760 if (sscanf(value, "%x", &sdb_trace_mask) != 1)
769 localtime_r(&t, &now);
770 strftime(path, sizeof(path),
771 "/tmp/sdbd-%Y-%m-%d-%H-%M-%S.txt",
773 fd = unix_open(path, O_WRONLY | O_CREAT | O_TRUNC, 0640);
778 // redirect stdout and stderr to the log file
781 fprintf(stderr,"--- sdbd starting (pid %d) ---\n", getpid());
784 fd = unix_open("/dev/null", O_RDONLY);
786 // hopefully not gonna happen
793 int daemonize(void) {
795 // set file creation mask to 0
807 FILE *f = fopen(SDB_PIDPATH, "w");
810 fprintf(f, "%d\n", getpid());
818 D("sdbd: unable to change working directory to /\n");
825 int launch_server(int server_port)
827 #ifdef HAVE_WIN32_PROC
828 /* we need to start the server in the background */
829 /* we create a PIPE that will be used to wait for the server's "OK" */
830 /* message since the pipe handles must be inheritable, we use a */
831 /* security attribute */
832 HANDLE pipe_read, pipe_write;
833 SECURITY_ATTRIBUTES sa;
835 PROCESS_INFORMATION pinfo;
836 char program_path[ MAX_PATH ];
839 sa.nLength = sizeof(sa);
840 sa.lpSecurityDescriptor = NULL;
841 sa.bInheritHandle = TRUE;
843 /* create pipe, and ensure its read handle isn't inheritable */
844 ret = CreatePipe( &pipe_read, &pipe_write, &sa, 0 );
846 fprintf(stderr, "CreatePipe() failure, error %ld\n", GetLastError() );
850 SetHandleInformation( pipe_read, HANDLE_FLAG_INHERIT, 0 );
852 ZeroMemory( &startup, sizeof(startup) );
853 startup.cb = sizeof(startup);
854 startup.hStdInput = GetStdHandle( STD_INPUT_HANDLE );
855 startup.hStdOutput = pipe_write;
856 startup.hStdError = GetStdHandle( STD_ERROR_HANDLE );
857 startup.dwFlags = STARTF_USESTDHANDLES;
859 ZeroMemory( &pinfo, sizeof(pinfo) );
861 /* get path of current program */
862 GetModuleFileName( NULL, program_path, sizeof(program_path) );
865 program_path, /* program path */
866 "sdb fork-server server",
867 /* the fork-server argument will set the
868 debug = 2 in the child */
869 NULL, /* process handle is not inheritable */
870 NULL, /* thread handle is not inheritable */
871 TRUE, /* yes, inherit some handles */
872 DETACHED_PROCESS, /* the new process doesn't have a console */
873 NULL, /* use parent's environment block */
874 NULL, /* use parent's starting directory */
875 &startup, /* startup info, i.e. std handles */
878 CloseHandle( pipe_write );
881 fprintf(stderr, "CreateProcess failure, error %ld\n", GetLastError() );
882 CloseHandle( pipe_read );
886 CloseHandle( pinfo.hProcess );
887 CloseHandle( pinfo.hThread );
889 /* wait for the "OK\n" message */
894 ret = ReadFile( pipe_read, temp, 3, &count, NULL );
895 CloseHandle( pipe_read );
897 fprintf(stderr, "could not read ok from SDB Server, error = %ld\n", GetLastError() );
900 if (count != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
901 fprintf(stderr, "SDB server didn't ACK\n" );
905 #elif defined(HAVE_FORKEXEC)
909 // set up a pipe so the child can tell us when it is ready.
910 // fd[0] will be parent's end, and fd[1] will get mapped to stderr in the child.
912 fprintf(stderr, "pipe failed in launch_server, errno: %d\n", errno);
915 get_my_path(path, PATH_MAX);
917 if(pid < 0) return -1;
920 // child side of the fork
922 // redirect stderr to the pipe
923 // we use stderr instead of stdout due to stdout's buffering behavior.
925 dup2(fd[1], STDERR_FILENO);
929 int result = execl(path, "sdb", "fork-server", "server", NULL);
930 // this should not return
931 fprintf(stderr, "OOPS! execl returned %d, errno: %d\n", result, errno);
933 // parent side of the fork
937 temp[0] = 'A'; temp[1] = 'B'; temp[2] = 'C';
938 // wait for the "OK\n" message
940 int ret = sdb_read(fd[0], temp, 3);
941 int saved_errno = errno;
944 fprintf(stderr, "could not read ok from SDB Server, errno = %d\n", saved_errno);
947 if (ret != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
948 fprintf(stderr, "SDB server didn't ACK\n" );
955 #error "cannot implement background server start on this platform"
961 /* Constructs a local name of form tcp:port.
962 * target_str points to the target string, it's content will be overwritten.
963 * target_size is the capacity of the target string.
964 * server_port is the port number to use for the local name.
966 void build_local_name(char* target_str, size_t target_size, int server_port)
968 snprintf(target_str, target_size, "tcp:%d", server_port);
972 static void init_drop_privileges() {
973 #ifdef _DROP_PRIVILEGE
980 int should_drop_privileges() {
981 if (rootshell_mode == 1) { // if root, then don't drop
987 int set_developer_privileges() {
988 gid_t groups[] = { SID_DEVELOPER, SID_APP_LOGGING, SID_SYS_LOGGING, SID_INPUT };
989 if (setgroups(sizeof(groups) / sizeof(groups[0]), groups) != 0) {
990 fprintf(stderr, "set groups failed (errno: %d, %s)\n", errno, strerror(errno));
994 // then switch user and group to developer
995 if (setgid(SID_DEVELOPER) != 0) {
996 fprintf(stderr, "set group id failed (errno: %d, %s)\n", errno, strerror(errno));
1001 if (setuid(SID_DEVELOPER) != 0) {
1002 fprintf(stderr, "set user id failed (errno: %d, %s)\n", errno, strerror(errno));
1007 if (chdir("/home/developer") < 0) {
1008 D("sdbd: unable to change working directory to /home/developer\n");
1010 if (chdir("/") < 0) {
1011 D("sdbd: unable to change working directory to /\n");
1016 #define ONDEMAND_ROOT_PATH "/home/developer"
1018 static void init_sdk_requirements() {
1021 if (!getenv("TERM")) {
1022 putenv("TERM=linux");
1025 if (stat(ONDEMAND_ROOT_PATH, &st) == -1) {
1028 if (st.st_uid != SID_DEVELOPER || st.st_gid != SID_DEVELOPER) {
1030 snprintf(cmd, sizeof(cmd), "chown developer:developer %s -R", ONDEMAND_ROOT_PATH);
1031 if (system(cmd) < 0) {
1032 D("failed to change ownership to developer to %s\n", ONDEMAND_ROOT_PATH);
1036 #endif /* !SDB_HOST */
1038 int sdb_main(int is_daemon, int server_port)
1042 init_drop_privileges();
1043 init_sdk_requirements();
1047 atexit(sdb_cleanup);
1048 #ifdef HAVE_WIN32_PROC
1049 SetConsoleCtrlHandler( ctrlc_handler, TRUE );
1050 #elif defined(HAVE_FORKEXEC)
1051 // No SIGCHLD. Let the service subproc handle its children.
1052 signal(SIGPIPE, SIG_IGN);
1055 init_transport_registration();
1062 local_init(DEFAULT_SDB_LOCAL_TRANSPORT_PORT);
1064 char local_name[30];
1065 build_local_name(local_name, sizeof(local_name), server_port);
1066 if(install_listener(local_name, "*smartsocket*", NULL)) {
1070 /* don't listen on a port (default 5037) if running in secure mode */
1071 /* don't run as root if we are running in secure mode */
1073 if (should_drop_privileges()) {
1075 struct __user_cap_header_struct header;
1076 struct __user_cap_data_struct cap;
1078 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
1081 /* add extra groups:
1082 ** SID_TTY to access /dev/ptmx
1084 gid_t groups[] = { SID_TTY, SID_APP_LOGGING, SID_SYS_LOGGING };
1085 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
1088 /* then switch user and group to "developer" */
1089 if (setgid(SID_DEVELOPER) != 0) {
1090 fprintf(stderr, "set group id failed errno: %d\n", errno);
1093 if (setuid(SID_DEVELOPER) != 0) {
1094 fprintf(stderr, "set user id failed errno: %d\n", errno);
1098 /* set CAP_SYS_BOOT capability, so "sdb reboot" will succeed */
1099 header.version = _LINUX_CAPABILITY_VERSION;
1101 cap.effective = cap.permitted = (1 << CAP_SYS_BOOT);
1102 cap.inheritable = 0;
1103 capset(&header, &cap);
1105 D("Local port disabled\n");
1107 char local_name[30];
1108 build_local_name(local_name, sizeof(local_name), server_port);
1109 if(install_listener(local_name, "*smartsocket*", NULL)) {
1114 if (access("/dev/samsung_sdb", F_OK) == 0) {
1118 //local_init(DEFAULT_SDB_LOCAL_TRANSPORT_PORT);
1120 // listen on default port
1121 local_init(DEFAULT_SDB_LOCAL_TRANSPORT_PORT);
1124 #if 0 /* tizen specific */
1125 D("sdb_main(): pre init_jdwp()\n");
1127 D("sdb_main(): post init_jdwp()\n");
1133 // inform our parent that we are up and running.
1134 #ifdef HAVE_WIN32_PROC
1136 WriteFile( GetStdHandle( STD_OUTPUT_HANDLE ), "OK\n", 3, &count, NULL );
1137 #elif defined(HAVE_FORKEXEC)
1138 fprintf(stderr, "OK\n");
1142 D("Event loop starting\n");
1152 void connect_device(char* host, char* buffer, int buffer_size)
1155 char* portstr = strchr(host, ':');
1159 strncpy(hostbuf, host, sizeof(hostbuf) - 1);
1161 if (portstr - host >= sizeof(hostbuf)) {
1162 snprintf(buffer, buffer_size, "bad host name %s", host);
1165 // zero terminate the host at the point we found the colon
1166 hostbuf[portstr - host] = 0;
1167 if (sscanf(portstr + 1, "%d", &port) == 0) {
1168 snprintf(buffer, buffer_size, "bad port number %s", portstr);
1172 port = DEFAULT_SDB_LOCAL_TRANSPORT_PORT;
1175 snprintf(serial, sizeof(serial), "%s:%d", hostbuf, port);
1176 if (find_transport(serial)) {
1177 snprintf(buffer, buffer_size, "already connected to %s", serial);
1181 fd = socket_network_client(hostbuf, port, SOCK_STREAM);
1183 snprintf(buffer, buffer_size, "unable to connect to %s", host);
1187 D("client: connected on remote on fd %d\n", fd);
1189 disable_tcp_nagle(fd);
1190 register_socket_transport(fd, serial, port, 0, NULL);
1191 snprintf(buffer, buffer_size, "connected to %s", serial);
1194 void connect_emulator(char* port_spec, char* buffer, int buffer_size)
1196 char* port_separator = strchr(port_spec, ',');
1197 if (!port_separator) {
1198 snprintf(buffer, buffer_size,
1199 "unable to parse '%s' as <console port>,<sdb port>",
1204 // Zero-terminate console port and make port_separator point to 2nd port.
1205 *port_separator++ = 0;
1206 int console_port = strtol(port_spec, NULL, 0);
1207 int sdb_port = strtol(port_separator, NULL, 0);
1208 if (!(console_port > 0 && sdb_port > 0)) {
1209 *(port_separator - 1) = ',';
1210 snprintf(buffer, buffer_size,
1211 "Invalid port numbers: Expected positive numbers, got '%s'",
1216 /* Check if the emulator is already known.
1217 * Note: There's a small but harmless race condition here: An emulator not
1218 * present just yet could be registered by another invocation right
1219 * after doing this check here. However, local_connect protects
1220 * against double-registration too. From here, a better error message
1221 * can be produced. In the case of the race condition, the very specific
1222 * error message won't be shown, but the data doesn't get corrupted. */
1223 atransport* known_emulator = find_emulator_transport_by_sdb_port(sdb_port);
1224 if (known_emulator != NULL) {
1225 snprintf(buffer, buffer_size,
1226 "Emulator on port %d already registered.", sdb_port);
1230 /* Check if more emulators can be registered. Similar unproblematic
1231 * race condition as above. */
1232 int candidate_slot = get_available_local_transport_index();
1233 if (candidate_slot < 0) {
1234 snprintf(buffer, buffer_size, "Cannot accept more emulators.");
1238 /* Preconditions met, try to connect to the emulator. */
1239 if (!local_connect_arbitrary_ports(console_port, sdb_port, NULL)) {
1240 snprintf(buffer, buffer_size,
1241 "Connected to emulator on ports %d,%d", console_port, sdb_port);
1243 snprintf(buffer, buffer_size,
1244 "Could not connect to emulator on ports %d,%d",
1245 console_port, sdb_port);
1250 int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s)
1252 atransport *transport = NULL;
1255 if(!strcmp(service, "kill")) {
1256 fprintf(stderr,"sdb server killed by remote request\n");
1258 sdb_write(reply_fd, "OKAY", 4);
1264 // "transport:" is used for switching transport with a specified serial number
1265 // "transport-usb:" is used for switching transport to the only USB transport
1266 // "transport-local:" is used for switching transport to the only local transport
1267 // "transport-any:" is used for switching transport to the only transport
1268 if (!strncmp(service, "transport", strlen("transport"))) {
1269 char* error_string = "unknown failure";
1270 transport_type type = kTransportAny;
1272 if (!strncmp(service, "transport-usb", strlen("transport-usb"))) {
1273 type = kTransportUsb;
1274 } else if (!strncmp(service, "transport-local", strlen("transport-local"))) {
1275 type = kTransportLocal;
1276 } else if (!strncmp(service, "transport-any", strlen("transport-any"))) {
1277 type = kTransportAny;
1278 } else if (!strncmp(service, "transport:", strlen("transport:"))) {
1279 service += strlen("transport:");
1283 transport = acquire_one_transport(CS_ANY, type, serial, &error_string);
1286 s->transport = transport;
1287 sdb_write(reply_fd, "OKAY", 4);
1289 sendfailmsg(reply_fd, error_string);
1294 // return a list of all connected devices
1295 if (!strcmp(service, "devices")) {
1297 memset(buf, 0, sizeof(buf));
1298 memset(buffer, 0, sizeof(buffer));
1299 D("Getting device list \n");
1300 list_transports(buffer, sizeof(buffer));
1301 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer),buffer);
1302 D("Wrote device list \n");
1303 writex(reply_fd, buf, strlen(buf));
1307 // add a new TCP transport, device or emulator
1308 if (!strncmp(service, "connect:", 8)) {
1310 char* host = service + 8;
1311 if (!strncmp(host, "emu:", 4)) {
1312 connect_emulator(host + 4, buffer, sizeof(buffer));
1314 connect_device(host, buffer, sizeof(buffer));
1316 // Send response for emulator and device
1317 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
1318 writex(reply_fd, buf, strlen(buf));
1322 // remove TCP transport
1323 if (!strncmp(service, "disconnect:", 11)) {
1325 memset(buffer, 0, sizeof(buffer));
1326 char* serial = service + 11;
1327 if (serial[0] == 0) {
1328 // disconnect from all TCP devices
1329 unregister_all_tcp_transports();
1332 // assume port 26101 if no port is specified
1333 if (!strchr(serial, ':')) {
1334 snprintf(hostbuf, sizeof(hostbuf) - 1, "%s:26101", serial);
1337 atransport *t = find_transport(serial);
1340 unregister_transport(t);
1342 snprintf(buffer, sizeof(buffer), "No such device %s", serial);
1346 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
1347 writex(reply_fd, buf, strlen(buf));
1351 // returns our value for SDB_SERVER_VERSION
1352 if (!strcmp(service, "version")) {
1354 snprintf(version, sizeof version, "%04x", SDB_SERVER_VERSION);
1355 snprintf(buf, sizeof buf, "OKAY%04x%s", (unsigned)strlen(version), version);
1356 writex(reply_fd, buf, strlen(buf));
1360 if(!strncmp(service,"get-serialno",strlen("get-serialno"))) {
1361 char *out = "unknown";
1362 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1363 if (transport && transport->serial) {
1364 out = transport->serial;
1366 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(out),out);
1367 writex(reply_fd, buf, strlen(buf));
1370 // indicates a new emulator instance has started
1371 if (!strncmp(service,"emulator:",9)) { /* tizen specific */
1372 char *tmp = strtok(service+9, DEVICEMAP_SEPARATOR);
1376 port = atoi(service+9);
1379 tmp = strtok(NULL, DEVICEMAP_SEPARATOR);
1381 local_connect(port, tmp);
1384 local_connect(port, NULL);
1389 if(!strncmp(service,"forward:",8) || !strncmp(service,"killforward:",12)) {
1390 char *local, *remote, *err;
1392 atransport *transport;
1394 int createForward = strncmp(service,"kill",4);
1396 local = service + (createForward ? 8 : 12);
1397 remote = strchr(local,';');
1399 sendfailmsg(reply_fd, "malformed forward spec");
1404 if((local[0] == 0) || (remote[0] == 0) || (remote[0] == '*')){
1405 sendfailmsg(reply_fd, "malformed forward spec");
1409 transport = acquire_one_transport(CS_ANY, ttype, serial, &err);
1411 sendfailmsg(reply_fd, err);
1415 if (createForward) {
1416 r = install_listener(local, remote, transport);
1418 r = remove_listener(local, remote, transport);
1421 /* 1st OKAY is connect, 2nd OKAY is status */
1422 writex(reply_fd, "OKAYOKAY", 8);
1426 if (createForward) {
1427 sendfailmsg(reply_fd, (r == -1) ? "cannot rebind smartsocket" : "cannot bind socket");
1429 sendfailmsg(reply_fd, "cannot remove listener");
1434 if(!strncmp(service,"get-state",strlen("get-state"))) {
1435 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1436 char *state = connection_state_name(transport);
1437 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(state),state);
1438 writex(reply_fd, buf, strlen(buf));
1445 int recovery_mode = 0;
1448 int main(int argc, char **argv)
1450 sdb_trace_init(); /* tizen specific */
1454 return sdb_commandline(argc - 1, argv + 1);
1456 /* If sdbd runs inside the emulator this will enable sdb tracing via
1457 * sdb-debug qemud service in the emulator. */
1458 #if 0 /* tizen specific */
1459 sdb_qemu_trace_init();
1460 if((argc > 1) && (!strcmp(argv[1],"recovery"))) {
1461 sdb_device_banner = "recovery";
1466 if (daemonize() < 0)
1467 fatal("daemonize() failed: %.200s", strerror(errno));
1471 D("Handling main()\n");
1473 //sdbd will never die on emulator!
1474 signal(SIGTERM, handle_sig_term); /* tizen specific */
1475 return sdb_main(0, DEFAULT_SDB_PORT);