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 static pid_t required_pid = 0;
50 void handle_sig_term(int sig) {
52 if (access(SDB_PIDPATH, F_OK) == 0)
53 sdb_unlink(SDB_PIDPATH);
55 //kill(getpgid(getpid()),SIGTERM);
56 //killpg(getpgid(getpid()),SIGTERM);
57 if (access("/dev/samsung_sdb", F_OK) == 0) {
60 // do nothing on a emulator
64 static const char *sdb_device_banner = "device";
66 void fatal(const char *fmt, ...)
70 fprintf(stderr, "error: ");
71 vfprintf(stderr, fmt, ap);
72 fprintf(stderr, "\n");
77 void fatal_errno(const char *fmt, ...)
81 fprintf(stderr, "error: %s: ", strerror(errno));
82 vfprintf(stderr, fmt, ap);
83 fprintf(stderr, "\n");
90 /* read a comma/space/colum/semi-column separated list of tags
91 * from the SDB_TRACE environment variable and build the trace
92 * mask from it. note that '1' and 'all' are special cases to
95 void sdb_trace_init(void)
97 const char* p = getenv("SDB_TRACE");
100 static const struct {
106 { "sdb", TRACE_SDB },
107 { "sockets", TRACE_SOCKETS },
108 { "packets", TRACE_PACKETS },
109 { "rwx", TRACE_RWX },
110 { "usb", TRACE_USB },
111 { "sync", TRACE_SYNC },
112 { "sysdeps", TRACE_SYSDEPS },
113 { "transport", TRACE_TRANSPORT },
114 { "jdwp", TRACE_JDWP },
115 { "services", TRACE_SERVICES },
116 { "properties", TRACE_PROPERTIES },
117 { "sdktools", TRACE_SDKTOOLS },
124 /* use a comma/column/semi-colum/space separated list */
128 q = strpbrk(p, " ,:;");
134 for (tagn = 0; tags[tagn].tag != NULL; tagn++)
136 int taglen = strlen(tags[tagn].tag);
138 if (len == taglen && !memcmp(tags[tagn].tag, p, len) )
140 int flag = tags[tagn].flag;
145 sdb_trace_mask |= (1 << flag);
157 * Implements SDB tracing inside the emulator.
163 * Redefine open and write for qemu_pipe.h that contains inlined references
164 * to those routines. We will redifine them back after qemu_pipe.h inclusion.
169 #define open sdb_open
170 #define write sdb_write
171 #include "qemu_pipe.h"
174 #define open ___xxx_open
175 #define write ___xxx_write
177 /* A handle to sdb-debug qemud service in the emulator. */
178 int sdb_debug_qemu = -1;
180 /* Initializes connection with the sdb-debug qemud service in the emulator. */
181 #if 0 /* doen't support in Tizen */
182 static int sdb_qemu_trace_init(void)
186 if (sdb_debug_qemu >= 0) {
190 /* sdb debugging QEMUD service connection request. */
191 snprintf(con_name, sizeof(con_name), "qemud:sdb-debug");
192 sdb_debug_qemu = qemu_pipe_open(con_name);
193 return (sdb_debug_qemu >= 0) ? 0 : -1;
196 void sdb_qemu_trace(const char* fmt, ...)
202 if (sdb_debug_qemu >= 0) {
203 vsnprintf(msg, sizeof(msg), fmt, args);
204 sdb_write(sdb_debug_qemu, msg, strlen(msg));
208 #endif /* !SDB_HOST */
210 apacket *get_apacket(void)
212 apacket *p = malloc(sizeof(apacket));
213 if(p == 0) fatal("failed to allocate an apacket");
214 memset(p, 0, sizeof(apacket) - MAX_PAYLOAD);
218 void put_apacket(apacket *p)
226 void handle_online(void)
231 void handle_offline(atransport *t)
234 //Close the associated usb
235 run_transport_disconnects(t);
240 void print_packet(const char *label, apacket *p)
246 switch(p->msg.command){
247 case A_SYNC: tag = "SYNC"; break;
248 case A_CNXN: tag = "CNXN" ; break;
249 case A_OPEN: tag = "OPEN"; break;
250 case A_OKAY: tag = "OKAY"; break;
251 case A_CLSE: tag = "CLSE"; break;
252 case A_WRTE: tag = "WRTE"; break;
253 default: tag = "????"; break;
256 fprintf(stderr, "%s: %s %08x %08x %04x \"",
257 label, tag, p->msg.arg0, p->msg.arg1, p->msg.data_length);
258 count = p->msg.data_length;
260 if(count > DUMPMAX) {
267 if((*x >= ' ') && (*x < 127)) {
274 fprintf(stderr, tag);
278 static void send_ready(unsigned local, unsigned remote, atransport *t)
280 D("Calling send_ready \n");
281 apacket *p = get_apacket();
282 p->msg.command = A_OKAY;
284 p->msg.arg1 = remote;
288 static void send_close(unsigned local, unsigned remote, atransport *t)
290 D("Calling send_close \n");
291 apacket *p = get_apacket();
292 p->msg.command = A_CLSE;
294 p->msg.arg1 = remote;
298 static void send_connect(atransport *t)
300 D("Calling send_connect \n");
301 apacket *cp = get_apacket();
302 cp->msg.command = A_CNXN;
303 cp->msg.arg0 = A_VERSION;
304 cp->msg.arg1 = MAX_PAYLOAD;
305 snprintf((char*) cp->data, sizeof cp->data, "%s::",
306 HOST ? "host" : sdb_device_banner);
307 cp->msg.data_length = strlen((char*) cp->data) + 1;
310 /* XXX why sleep here? */
311 // allow the device some time to respond to the connect message
316 static char *connection_state_name(atransport *t)
322 switch(t->connection_state) {
334 void parse_banner(char *banner, atransport *t)
336 char *type, *product, *end;
338 D("parse_banner: %s\n", banner);
340 product = strchr(type, ':');
347 /* remove trailing ':' */
348 end = strchr(product, ':');
351 /* save product name in device structure */
352 if (t->product == NULL) {
353 t->product = strdup(product);
354 } else if (strcmp(product, t->product) != 0) {
356 t->product = strdup(product);
359 if(!strcmp(type, "bootloader")){
360 D("setting connection_state to CS_BOOTLOADER\n");
361 t->connection_state = CS_BOOTLOADER;
366 if(!strcmp(type, "device")) {
367 D("setting connection_state to CS_DEVICE\n");
368 t->connection_state = CS_DEVICE;
373 if(!strcmp(type, "recovery")) {
374 D("setting connection_state to CS_RECOVERY\n");
375 t->connection_state = CS_RECOVERY;
380 if(!strcmp(type, "sideload")) {
381 D("setting connection_state to CS_SIDELOAD\n");
382 t->connection_state = CS_SIDELOAD;
387 t->connection_state = CS_HOST;
390 void handle_packet(apacket *p, atransport *t)
394 D("handle_packet() %c%c%c%c\n", ((char*) (&(p->msg.command)))[0],
395 ((char*) (&(p->msg.command)))[1],
396 ((char*) (&(p->msg.command)))[2],
397 ((char*) (&(p->msg.command)))[3]);
399 print_packet("recv", p);
401 switch(p->msg.command){
405 if(HOST) send_connect(t);
407 t->connection_state = CS_OFFLINE;
413 case A_CNXN: /* CONNECT(version, maxdata, "system-id-string") */
414 /* XXX verify version, etc */
415 if(t->connection_state != CS_OFFLINE) {
416 t->connection_state = CS_OFFLINE;
419 parse_banner((char*) p->data, t);
421 if(!HOST) send_connect(t);
424 case A_OPEN: /* OPEN(local-id, 0, "destination") */
425 if(t->connection_state != CS_OFFLINE) {
426 char *name = (char*) p->data;
427 name[p->msg.data_length > 0 ? p->msg.data_length - 1 : 0] = 0;
428 s = create_local_service_socket(name);
430 send_close(0, p->msg.arg0, t);
432 s->peer = create_remote_socket(p->msg.arg0, t);
434 send_ready(s->id, s->peer->id, t);
440 case A_OKAY: /* READY(local-id, remote-id, "") */
441 if(t->connection_state != CS_OFFLINE) {
442 if((s = find_local_socket(p->msg.arg1))) {
444 s->peer = create_remote_socket(p->msg.arg0, t);
452 case A_CLSE: /* CLOSE(local-id, remote-id, "") */
453 if(t->connection_state != CS_OFFLINE) {
454 if((s = find_local_socket(p->msg.arg1))) {
461 if(t->connection_state != CS_OFFLINE) {
462 if((s = find_local_socket(p->msg.arg1))) {
463 unsigned rid = p->msg.arg0;
464 p->len = p->msg.data_length;
466 if(s->enqueue(s, p) == 0) {
467 D("Enqueue the socket\n");
468 send_ready(s->id, rid, t);
476 printf("handle_packet: what is %08x?!\n", p->msg.command);
482 alistener listener_list = {
483 .next = &listener_list,
484 .prev = &listener_list,
487 static void ss_listener_event_func(int _fd, unsigned ev, void *_l)
492 struct sockaddr addr;
497 fd = sdb_socket_accept(_fd, &addr, &alen);
500 sdb_socket_setbufsize(fd, CHUNK_SIZE);
502 s = create_local_socket(fd);
504 connect_to_smartsocket(s);
512 static void listener_event_func(int _fd, unsigned ev, void *_l)
518 struct sockaddr addr;
523 fd = sdb_socket_accept(_fd, &addr, &alen);
526 s = create_local_socket(fd);
528 s->transport = l->transport;
529 connect_to_remote(s, l->connect_to);
537 static void free_listener(alistener* l)
540 l->next->prev = l->prev;
541 l->prev->next = l->next;
542 l->next = l->prev = l;
545 // closes the corresponding fd
546 fdevent_remove(&l->fde);
549 free((char*)l->local_name);
552 free((char*)l->connect_to);
555 remove_transport_disconnect(l->transport, &l->disconnect);
560 static void listener_disconnect(void* _l, atransport* t)
567 int local_name_to_fd(const char *name)
571 if(!strncmp("tcp:", name, 4)){
573 port = atoi(name + 4);
574 ret = socket_loopback_server(port, SOCK_STREAM);
577 #ifndef HAVE_WIN32_IPC /* no Unix-domain sockets on Win32 */
578 // It's non-sensical to support the "reserved" space on the sdb host side
579 if(!strncmp(name, "local:", 6)) {
580 return socket_local_server(name + 6,
581 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
582 } else if(!strncmp(name, "localabstract:", 14)) {
583 return socket_local_server(name + 14,
584 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
585 } else if(!strncmp(name, "localfilesystem:", 16)) {
586 return socket_local_server(name + 16,
587 ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
591 printf("unknown local portname '%s'\n", name);
595 static int remove_listener(const char *local_name, const char *connect_to, atransport* transport)
599 for (l = listener_list.next; l != &listener_list; l = l->next) {
600 if (!strcmp(local_name, l->local_name) &&
601 !strcmp(connect_to, l->connect_to) &&
602 l->transport && l->transport == transport) {
604 listener_disconnect(l, transport);
612 static int install_listener(const char *local_name, const char *connect_to, atransport* transport)
616 //printf("install_listener('%s','%s')\n", local_name, connect_to);
618 for(l = listener_list.next; l != &listener_list; l = l->next){
619 if(strcmp(local_name, l->local_name) == 0) {
622 /* can't repurpose a smartsocket */
623 if(l->connect_to[0] == '*') {
627 cto = strdup(connect_to);
632 //printf("rebinding '%s' to '%s'\n", local_name, connect_to);
633 free((void*) l->connect_to);
635 if (l->transport != transport) {
636 remove_transport_disconnect(l->transport, &l->disconnect);
637 l->transport = transport;
638 add_transport_disconnect(l->transport, &l->disconnect);
644 if((l = calloc(1, sizeof(alistener))) == 0) goto nomem;
645 if((l->local_name = strdup(local_name)) == 0) goto nomem;
646 if((l->connect_to = strdup(connect_to)) == 0) goto nomem;
649 l->fd = local_name_to_fd(local_name);
651 free((void*) l->local_name);
652 free((void*) l->connect_to);
654 printf("cannot bind '%s'\n", local_name);
658 if (close_on_exec(l->fd) < 0) {
659 D("fail to close fd exec:%d\n",l->fd);
661 if(!strcmp(l->connect_to, "*smartsocket*")) {
662 fdevent_install(&l->fde, l->fd, ss_listener_event_func, l);
664 fdevent_install(&l->fde, l->fd, listener_event_func, l);
666 fdevent_set(&l->fde, FDE_READ);
668 l->next = &listener_list;
669 l->prev = listener_list.prev;
672 l->transport = transport;
675 l->disconnect.opaque = l;
676 l->disconnect.func = listener_disconnect;
677 add_transport_disconnect(transport, &l->disconnect);
682 fatal("cannot allocate listener");
686 #ifdef HAVE_WIN32_PROC
687 static BOOL WINAPI ctrlc_handler(DWORD type)
689 exit(STATUS_CONTROL_C_EXIT);
694 static void sdb_cleanup(void)
697 // if(required_pid > 0) {
698 // kill(required_pid, SIGKILL);
702 void start_logging(void)
704 #ifdef HAVE_WIN32_PROC
705 char temp[ MAX_PATH ];
709 GetTempPath( sizeof(temp) - 8, temp );
710 strcat( temp, "sdb.log" );
712 /* Win32 specific redirections */
713 fnul = fopen( "NUL", "rt" );
717 flog = fopen( temp, "at" );
721 setvbuf( flog, NULL, _IONBF, 0 );
725 fprintf(stderr,"--- sdb starting (pid %d) ---\n", getpid());
729 fd = unix_open("/dev/null", O_RDONLY);
731 // hopefully not gonna happen
737 fd = unix_open("/tmp/sdb.log", O_WRONLY | O_CREAT | O_APPEND, 0640);
739 fd = unix_open("/dev/null", O_WRONLY);
741 // hopefully not gonna happen
748 fprintf(stderr,"--- sdb starting (pid %d) ---\n", getpid());
753 void start_device_log(void)
759 // char value[PROPERTY_VALUE_MAX];
760 const char* p = getenv("SDB_TRACE");
761 // read the trace mask from persistent property persist.sdb.trace_mask
762 // give up if the property is not set or cannot be parsed
763 #if 0 /* tizen specific */
764 property_get("persist.sdb.trace_mask", value, "");
765 if (sscanf(value, "%x", &sdb_trace_mask) != 1)
774 localtime_r(&t, &now);
775 strftime(path, sizeof(path),
776 "/tmp/sdbd-%Y-%m-%d-%H-%M-%S.txt",
778 fd = unix_open(path, O_WRONLY | O_CREAT | O_TRUNC, 0640);
783 // redirect stdout and stderr to the log file
786 fprintf(stderr,"--- sdbd starting (pid %d) ---\n", getpid());
789 fd = unix_open("/dev/null", O_RDONLY);
791 // hopefully not gonna happen
798 int daemonize(void) {
800 // set file creation mask to 0
812 FILE *f = fopen(SDB_PIDPATH, "w");
815 fprintf(f, "%d\n", getpid());
823 D("sdbd: unable to change working directory to /\n");
830 int launch_server(int server_port)
832 #ifdef HAVE_WIN32_PROC
833 /* we need to start the server in the background */
834 /* we create a PIPE that will be used to wait for the server's "OK" */
835 /* message since the pipe handles must be inheritable, we use a */
836 /* security attribute */
837 HANDLE pipe_read, pipe_write;
838 SECURITY_ATTRIBUTES sa;
840 PROCESS_INFORMATION pinfo;
841 char program_path[ MAX_PATH ];
844 sa.nLength = sizeof(sa);
845 sa.lpSecurityDescriptor = NULL;
846 sa.bInheritHandle = TRUE;
848 /* create pipe, and ensure its read handle isn't inheritable */
849 ret = CreatePipe( &pipe_read, &pipe_write, &sa, 0 );
851 fprintf(stderr, "CreatePipe() failure, error %ld\n", GetLastError() );
855 SetHandleInformation( pipe_read, HANDLE_FLAG_INHERIT, 0 );
857 ZeroMemory( &startup, sizeof(startup) );
858 startup.cb = sizeof(startup);
859 startup.hStdInput = GetStdHandle( STD_INPUT_HANDLE );
860 startup.hStdOutput = pipe_write;
861 startup.hStdError = GetStdHandle( STD_ERROR_HANDLE );
862 startup.dwFlags = STARTF_USESTDHANDLES;
864 ZeroMemory( &pinfo, sizeof(pinfo) );
866 /* get path of current program */
867 GetModuleFileName( NULL, program_path, sizeof(program_path) );
870 program_path, /* program path */
871 "sdb fork-server server",
872 /* the fork-server argument will set the
873 debug = 2 in the child */
874 NULL, /* process handle is not inheritable */
875 NULL, /* thread handle is not inheritable */
876 TRUE, /* yes, inherit some handles */
877 DETACHED_PROCESS, /* the new process doesn't have a console */
878 NULL, /* use parent's environment block */
879 NULL, /* use parent's starting directory */
880 &startup, /* startup info, i.e. std handles */
883 CloseHandle( pipe_write );
886 fprintf(stderr, "CreateProcess failure, error %ld\n", GetLastError() );
887 CloseHandle( pipe_read );
891 CloseHandle( pinfo.hProcess );
892 CloseHandle( pinfo.hThread );
894 /* wait for the "OK\n" message */
899 ret = ReadFile( pipe_read, temp, 3, &count, NULL );
900 CloseHandle( pipe_read );
902 fprintf(stderr, "could not read ok from SDB Server, error = %ld\n", GetLastError() );
905 if (count != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
906 fprintf(stderr, "SDB server didn't ACK\n" );
910 #elif defined(HAVE_FORKEXEC)
914 // set up a pipe so the child can tell us when it is ready.
915 // fd[0] will be parent's end, and fd[1] will get mapped to stderr in the child.
917 fprintf(stderr, "pipe failed in launch_server, errno: %d\n", errno);
920 get_my_path(path, PATH_MAX);
922 if(pid < 0) return -1;
925 // child side of the fork
927 // redirect stderr to the pipe
928 // we use stderr instead of stdout due to stdout's buffering behavior.
930 dup2(fd[1], STDERR_FILENO);
934 int result = execl(path, "sdb", "fork-server", "server", NULL);
935 // this should not return
936 fprintf(stderr, "OOPS! execl returned %d, errno: %d\n", result, errno);
938 // parent side of the fork
942 temp[0] = 'A'; temp[1] = 'B'; temp[2] = 'C';
943 // wait for the "OK\n" message
945 int ret = sdb_read(fd[0], temp, 3);
946 int saved_errno = errno;
949 fprintf(stderr, "could not read ok from SDB Server, errno = %d\n", saved_errno);
952 if (ret != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
953 fprintf(stderr, "SDB server didn't ACK\n" );
960 #error "cannot implement background server start on this platform"
966 /* Constructs a local name of form tcp:port.
967 * target_str points to the target string, it's content will be overwritten.
968 * target_size is the capacity of the target string.
969 * server_port is the port number to use for the local name.
971 void build_local_name(char* target_str, size_t target_size, int server_port)
973 snprintf(target_str, target_size, "tcp:%d", server_port);
977 static void init_drop_privileges() {
978 #ifdef _DROP_PRIVILEGE
985 int should_drop_privileges() {
986 if (rootshell_mode == 1) { // if root, then don't drop
992 int set_developer_privileges() {
993 gid_t groups[] = { SID_DEVELOPER, SID_APP_LOGGING, SID_SYS_LOGGING, SID_INPUT };
994 if (setgroups(sizeof(groups) / sizeof(groups[0]), groups) != 0) {
995 fprintf(stderr, "set groups failed (errno: %d, %s)\n", errno, strerror(errno));
999 // then switch user and group to developer
1000 if (setgid(SID_DEVELOPER) != 0) {
1001 fprintf(stderr, "set group id failed (errno: %d, %s)\n", errno, strerror(errno));
1006 if (setuid(SID_DEVELOPER) != 0) {
1007 fprintf(stderr, "set user id failed (errno: %d, %s)\n", errno, strerror(errno));
1012 if (chdir("/home/developer") < 0) {
1013 D("sdbd: unable to change working directory to /home/developer\n");
1015 if (chdir("/") < 0) {
1016 D("sdbd: unable to change working directory to /\n");
1021 #define ONDEMAND_ROOT_PATH "/home/developer"
1023 static void execute_required_process() {
1025 FILE *pre_proc_file = popen("pidof debug_launchpad_preloading_preinitializing_daemon", "r");
1028 while(!feof(pre_proc_file)) {
1030 result += fscanf(pre_proc_file, "%d", &pid);
1035 D("Kill %d debug launchpad daemon", result);
1037 pclose(pre_proc_file);
1039 system("/usr/bin/debug_launchpad_preloading_preinitializing_daemon &");
1042 static void init_sdk_requirements() {
1045 if (!getenv("TERM")) {
1046 putenv("TERM=linux");
1049 if (stat(ONDEMAND_ROOT_PATH, &st) == -1) {
1052 if (st.st_uid != SID_DEVELOPER || st.st_gid != SID_DEVELOPER) {
1054 snprintf(cmd, sizeof(cmd), "chown developer:developer %s -R", ONDEMAND_ROOT_PATH);
1055 if (system(cmd) < 0) {
1056 D("failed to change ownership to developer to %s\n", ONDEMAND_ROOT_PATH);
1060 execute_required_process();
1062 #endif /* !SDB_HOST */
1064 int sdb_main(int is_daemon, int server_port)
1067 init_drop_privileges();
1068 init_sdk_requirements();
1072 atexit(sdb_cleanup);
1073 #ifdef HAVE_WIN32_PROC
1074 SetConsoleCtrlHandler( ctrlc_handler, TRUE );
1075 #elif defined(HAVE_FORKEXEC)
1076 // No SIGCHLD. Let the service subproc handle its children.
1077 signal(SIGPIPE, SIG_IGN);
1080 init_transport_registration();
1087 local_init(DEFAULT_SDB_LOCAL_TRANSPORT_PORT);
1089 char local_name[30];
1090 build_local_name(local_name, sizeof(local_name), server_port);
1091 if(install_listener(local_name, "*smartsocket*", NULL)) {
1095 /* don't listen on a port (default 5037) if running in secure mode */
1096 /* don't run as root if we are running in secure mode */
1098 if (should_drop_privileges()) {
1100 struct __user_cap_header_struct header;
1101 struct __user_cap_data_struct cap;
1103 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
1106 /* add extra groups:
1107 ** SID_TTY to access /dev/ptmx
1109 gid_t groups[] = { SID_TTY, SID_APP_LOGGING, SID_SYS_LOGGING };
1110 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
1113 /* then switch user and group to "developer" */
1114 if (setgid(SID_DEVELOPER) != 0) {
1115 fprintf(stderr, "set group id failed errno: %d\n", errno);
1118 if (setuid(SID_DEVELOPER) != 0) {
1119 fprintf(stderr, "set user id failed errno: %d\n", errno);
1123 /* set CAP_SYS_BOOT capability, so "sdb reboot" will succeed */
1124 header.version = _LINUX_CAPABILITY_VERSION;
1126 cap.effective = cap.permitted = (1 << CAP_SYS_BOOT);
1127 cap.inheritable = 0;
1128 capset(&header, &cap);
1130 D("Local port disabled\n");
1132 char local_name[30];
1133 build_local_name(local_name, sizeof(local_name), server_port);
1134 if(install_listener(local_name, "*smartsocket*", NULL)) {
1139 if (access("/dev/samsung_sdb", F_OK) == 0) {
1143 //local_init(DEFAULT_SDB_LOCAL_TRANSPORT_PORT);
1145 // listen on default port
1146 local_init(DEFAULT_SDB_LOCAL_TRANSPORT_PORT);
1149 #if 0 /* tizen specific */
1150 D("sdb_main(): pre init_jdwp()\n");
1152 D("sdb_main(): post init_jdwp()\n");
1158 // inform our parent that we are up and running.
1159 #ifdef HAVE_WIN32_PROC
1161 WriteFile( GetStdHandle( STD_OUTPUT_HANDLE ), "OK\n", 3, &count, NULL );
1162 #elif defined(HAVE_FORKEXEC)
1163 fprintf(stderr, "OK\n");
1167 D("Event loop starting\n");
1177 void connect_device(char* host, char* buffer, int buffer_size)
1180 char* portstr = strchr(host, ':');
1184 strncpy(hostbuf, host, sizeof(hostbuf) - 1);
1186 if (portstr - host >= sizeof(hostbuf)) {
1187 snprintf(buffer, buffer_size, "bad host name %s", host);
1190 // zero terminate the host at the point we found the colon
1191 hostbuf[portstr - host] = 0;
1192 if (sscanf(portstr + 1, "%d", &port) == 0) {
1193 snprintf(buffer, buffer_size, "bad port number %s", portstr);
1197 port = DEFAULT_SDB_LOCAL_TRANSPORT_PORT;
1200 snprintf(serial, sizeof(serial), "%s:%d", hostbuf, port);
1201 if (find_transport(serial)) {
1202 snprintf(buffer, buffer_size, "already connected to %s", serial);
1206 fd = socket_network_client(hostbuf, port, SOCK_STREAM);
1208 snprintf(buffer, buffer_size, "unable to connect to %s", host);
1212 D("client: connected on remote on fd %d\n", fd);
1214 disable_tcp_nagle(fd);
1215 register_socket_transport(fd, serial, port, 0, NULL);
1216 snprintf(buffer, buffer_size, "connected to %s", serial);
1219 void connect_emulator(char* port_spec, char* buffer, int buffer_size)
1221 char* port_separator = strchr(port_spec, ',');
1222 if (!port_separator) {
1223 snprintf(buffer, buffer_size,
1224 "unable to parse '%s' as <console port>,<sdb port>",
1229 // Zero-terminate console port and make port_separator point to 2nd port.
1230 *port_separator++ = 0;
1231 int console_port = strtol(port_spec, NULL, 0);
1232 int sdb_port = strtol(port_separator, NULL, 0);
1233 if (!(console_port > 0 && sdb_port > 0)) {
1234 *(port_separator - 1) = ',';
1235 snprintf(buffer, buffer_size,
1236 "Invalid port numbers: Expected positive numbers, got '%s'",
1241 /* Check if the emulator is already known.
1242 * Note: There's a small but harmless race condition here: An emulator not
1243 * present just yet could be registered by another invocation right
1244 * after doing this check here. However, local_connect protects
1245 * against double-registration too. From here, a better error message
1246 * can be produced. In the case of the race condition, the very specific
1247 * error message won't be shown, but the data doesn't get corrupted. */
1248 atransport* known_emulator = find_emulator_transport_by_sdb_port(sdb_port);
1249 if (known_emulator != NULL) {
1250 snprintf(buffer, buffer_size,
1251 "Emulator on port %d already registered.", sdb_port);
1255 /* Check if more emulators can be registered. Similar unproblematic
1256 * race condition as above. */
1257 int candidate_slot = get_available_local_transport_index();
1258 if (candidate_slot < 0) {
1259 snprintf(buffer, buffer_size, "Cannot accept more emulators.");
1263 /* Preconditions met, try to connect to the emulator. */
1264 if (!local_connect_arbitrary_ports(console_port, sdb_port, NULL)) {
1265 snprintf(buffer, buffer_size,
1266 "Connected to emulator on ports %d,%d", console_port, sdb_port);
1268 snprintf(buffer, buffer_size,
1269 "Could not connect to emulator on ports %d,%d",
1270 console_port, sdb_port);
1275 int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s)
1277 atransport *transport = NULL;
1280 if(!strcmp(service, "kill")) {
1281 fprintf(stderr,"sdb server killed by remote request\n");
1283 sdb_write(reply_fd, "OKAY", 4);
1289 // "transport:" is used for switching transport with a specified serial number
1290 // "transport-usb:" is used for switching transport to the only USB transport
1291 // "transport-local:" is used for switching transport to the only local transport
1292 // "transport-any:" is used for switching transport to the only transport
1293 if (!strncmp(service, "transport", strlen("transport"))) {
1294 char* error_string = "unknown failure";
1295 transport_type type = kTransportAny;
1297 if (!strncmp(service, "transport-usb", strlen("transport-usb"))) {
1298 type = kTransportUsb;
1299 } else if (!strncmp(service, "transport-local", strlen("transport-local"))) {
1300 type = kTransportLocal;
1301 } else if (!strncmp(service, "transport-any", strlen("transport-any"))) {
1302 type = kTransportAny;
1303 } else if (!strncmp(service, "transport:", strlen("transport:"))) {
1304 service += strlen("transport:");
1308 transport = acquire_one_transport(CS_ANY, type, serial, &error_string);
1311 s->transport = transport;
1312 sdb_write(reply_fd, "OKAY", 4);
1314 sendfailmsg(reply_fd, error_string);
1319 // return a list of all connected devices
1320 if (!strcmp(service, "devices")) {
1322 memset(buf, 0, sizeof(buf));
1323 memset(buffer, 0, sizeof(buffer));
1324 D("Getting device list \n");
1325 list_transports(buffer, sizeof(buffer));
1326 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer),buffer);
1327 D("Wrote device list \n");
1328 writex(reply_fd, buf, strlen(buf));
1332 // add a new TCP transport, device or emulator
1333 if (!strncmp(service, "connect:", 8)) {
1335 char* host = service + 8;
1336 if (!strncmp(host, "emu:", 4)) {
1337 connect_emulator(host + 4, buffer, sizeof(buffer));
1339 connect_device(host, buffer, sizeof(buffer));
1341 // Send response for emulator and device
1342 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
1343 writex(reply_fd, buf, strlen(buf));
1347 // remove TCP transport
1348 if (!strncmp(service, "disconnect:", 11)) {
1350 memset(buffer, 0, sizeof(buffer));
1351 char* serial = service + 11;
1352 if (serial[0] == 0) {
1353 // disconnect from all TCP devices
1354 unregister_all_tcp_transports();
1357 // assume port 26101 if no port is specified
1358 if (!strchr(serial, ':')) {
1359 snprintf(hostbuf, sizeof(hostbuf) - 1, "%s:26101", serial);
1362 atransport *t = find_transport(serial);
1365 unregister_transport(t);
1367 snprintf(buffer, sizeof(buffer), "No such device %s", serial);
1371 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
1372 writex(reply_fd, buf, strlen(buf));
1376 // returns our value for SDB_SERVER_VERSION
1377 if (!strcmp(service, "version")) {
1379 snprintf(version, sizeof version, "%04x", SDB_SERVER_VERSION);
1380 snprintf(buf, sizeof buf, "OKAY%04x%s", (unsigned)strlen(version), version);
1381 writex(reply_fd, buf, strlen(buf));
1385 if(!strncmp(service,"get-serialno",strlen("get-serialno"))) {
1386 char *out = "unknown";
1387 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1388 if (transport && transport->serial) {
1389 out = transport->serial;
1391 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(out),out);
1392 writex(reply_fd, buf, strlen(buf));
1395 // indicates a new emulator instance has started
1396 if (!strncmp(service,"emulator:",9)) { /* tizen specific */
1397 char *tmp = strtok(service+9, DEVICEMAP_SEPARATOR);
1401 port = atoi(service+9);
1404 tmp = strtok(NULL, DEVICEMAP_SEPARATOR);
1406 local_connect(port, tmp);
1409 local_connect(port, NULL);
1414 if(!strncmp(service,"forward:",8) || !strncmp(service,"killforward:",12)) {
1415 char *local, *remote, *err;
1417 atransport *transport;
1419 int createForward = strncmp(service,"kill",4);
1421 local = service + (createForward ? 8 : 12);
1422 remote = strchr(local,';');
1424 sendfailmsg(reply_fd, "malformed forward spec");
1429 if((local[0] == 0) || (remote[0] == 0) || (remote[0] == '*')){
1430 sendfailmsg(reply_fd, "malformed forward spec");
1434 transport = acquire_one_transport(CS_ANY, ttype, serial, &err);
1436 sendfailmsg(reply_fd, err);
1440 if (createForward) {
1441 r = install_listener(local, remote, transport);
1443 r = remove_listener(local, remote, transport);
1446 /* 1st OKAY is connect, 2nd OKAY is status */
1447 writex(reply_fd, "OKAYOKAY", 8);
1451 if (createForward) {
1452 sendfailmsg(reply_fd, (r == -1) ? "cannot rebind smartsocket" : "cannot bind socket");
1454 sendfailmsg(reply_fd, "cannot remove listener");
1459 if(!strncmp(service,"get-state",strlen("get-state"))) {
1460 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1461 char *state = connection_state_name(transport);
1462 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(state),state);
1463 writex(reply_fd, buf, strlen(buf));
1470 int recovery_mode = 0;
1473 int main(int argc, char **argv)
1475 sdb_trace_init(); /* tizen specific */
1479 return sdb_commandline(argc - 1, argv + 1);
1481 /* If sdbd runs inside the emulator this will enable sdb tracing via
1482 * sdb-debug qemud service in the emulator. */
1483 #if 0 /* tizen specific */
1484 sdb_qemu_trace_init();
1485 if((argc > 1) && (!strcmp(argv[1],"recovery"))) {
1486 sdb_device_banner = "recovery";
1491 if (daemonize() < 0)
1492 fatal("daemonize() failed: %.200s", strerror(errno));
1496 D("Handling main()\n");
1498 //sdbd will never die on emulator!
1499 signal(SIGTERM, handle_sig_term); /* tizen specific */
1500 return sdb_main(0, DEFAULT_SDB_PORT);