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);
1046 if(setsid() == -1) {
1047 D("Fail to set session id of debug launchpad daemon\n");
1050 if(chdir("/") < 0) {
1051 D("Fail debug launchpad daemon to chdir\n");
1054 execl("/usr/bin/debug_launchpad_preloading_preinitializing_daemon", "debug_launchpad_preloading_preinitializing_daemon", NULL);
1065 static void init_sdk_requirements() {
1068 if (!getenv("TERM")) {
1069 putenv("TERM=linux");
1072 if (stat(ONDEMAND_ROOT_PATH, &st) == -1) {
1075 if (st.st_uid != SID_DEVELOPER || st.st_gid != SID_DEVELOPER) {
1077 snprintf(cmd, sizeof(cmd), "chown developer:developer %s -R", ONDEMAND_ROOT_PATH);
1078 if (system(cmd) < 0) {
1079 D("failed to change ownership to developer to %s\n", ONDEMAND_ROOT_PATH);
1083 execute_required_process();
1085 #endif /* !SDB_HOST */
1087 int sdb_main(int is_daemon, int server_port)
1090 init_drop_privileges();
1091 init_sdk_requirements();
1095 atexit(sdb_cleanup);
1096 #ifdef HAVE_WIN32_PROC
1097 SetConsoleCtrlHandler( ctrlc_handler, TRUE );
1098 #elif defined(HAVE_FORKEXEC)
1099 // No SIGCHLD. Let the service subproc handle its children.
1100 signal(SIGPIPE, SIG_IGN);
1103 init_transport_registration();
1110 local_init(DEFAULT_SDB_LOCAL_TRANSPORT_PORT);
1112 char local_name[30];
1113 build_local_name(local_name, sizeof(local_name), server_port);
1114 if(install_listener(local_name, "*smartsocket*", NULL)) {
1118 /* don't listen on a port (default 5037) if running in secure mode */
1119 /* don't run as root if we are running in secure mode */
1121 if (should_drop_privileges()) {
1123 struct __user_cap_header_struct header;
1124 struct __user_cap_data_struct cap;
1126 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
1129 /* add extra groups:
1130 ** SID_TTY to access /dev/ptmx
1132 gid_t groups[] = { SID_TTY, SID_APP_LOGGING, SID_SYS_LOGGING };
1133 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
1136 /* then switch user and group to "developer" */
1137 if (setgid(SID_DEVELOPER) != 0) {
1138 fprintf(stderr, "set group id failed errno: %d\n", errno);
1141 if (setuid(SID_DEVELOPER) != 0) {
1142 fprintf(stderr, "set user id failed errno: %d\n", errno);
1146 /* set CAP_SYS_BOOT capability, so "sdb reboot" will succeed */
1147 header.version = _LINUX_CAPABILITY_VERSION;
1149 cap.effective = cap.permitted = (1 << CAP_SYS_BOOT);
1150 cap.inheritable = 0;
1151 capset(&header, &cap);
1153 D("Local port disabled\n");
1155 char local_name[30];
1156 build_local_name(local_name, sizeof(local_name), server_port);
1157 if(install_listener(local_name, "*smartsocket*", NULL)) {
1162 if (access("/dev/samsung_sdb", F_OK) == 0) {
1166 //local_init(DEFAULT_SDB_LOCAL_TRANSPORT_PORT);
1168 // listen on default port
1169 local_init(DEFAULT_SDB_LOCAL_TRANSPORT_PORT);
1172 #if 0 /* tizen specific */
1173 D("sdb_main(): pre init_jdwp()\n");
1175 D("sdb_main(): post init_jdwp()\n");
1181 // inform our parent that we are up and running.
1182 #ifdef HAVE_WIN32_PROC
1184 WriteFile( GetStdHandle( STD_OUTPUT_HANDLE ), "OK\n", 3, &count, NULL );
1185 #elif defined(HAVE_FORKEXEC)
1186 fprintf(stderr, "OK\n");
1190 D("Event loop starting\n");
1200 void connect_device(char* host, char* buffer, int buffer_size)
1203 char* portstr = strchr(host, ':');
1207 strncpy(hostbuf, host, sizeof(hostbuf) - 1);
1209 if (portstr - host >= sizeof(hostbuf)) {
1210 snprintf(buffer, buffer_size, "bad host name %s", host);
1213 // zero terminate the host at the point we found the colon
1214 hostbuf[portstr - host] = 0;
1215 if (sscanf(portstr + 1, "%d", &port) == 0) {
1216 snprintf(buffer, buffer_size, "bad port number %s", portstr);
1220 port = DEFAULT_SDB_LOCAL_TRANSPORT_PORT;
1223 snprintf(serial, sizeof(serial), "%s:%d", hostbuf, port);
1224 if (find_transport(serial)) {
1225 snprintf(buffer, buffer_size, "already connected to %s", serial);
1229 fd = socket_network_client(hostbuf, port, SOCK_STREAM);
1231 snprintf(buffer, buffer_size, "unable to connect to %s", host);
1235 D("client: connected on remote on fd %d\n", fd);
1237 disable_tcp_nagle(fd);
1238 register_socket_transport(fd, serial, port, 0, NULL);
1239 snprintf(buffer, buffer_size, "connected to %s", serial);
1242 void connect_emulator(char* port_spec, char* buffer, int buffer_size)
1244 char* port_separator = strchr(port_spec, ',');
1245 if (!port_separator) {
1246 snprintf(buffer, buffer_size,
1247 "unable to parse '%s' as <console port>,<sdb port>",
1252 // Zero-terminate console port and make port_separator point to 2nd port.
1253 *port_separator++ = 0;
1254 int console_port = strtol(port_spec, NULL, 0);
1255 int sdb_port = strtol(port_separator, NULL, 0);
1256 if (!(console_port > 0 && sdb_port > 0)) {
1257 *(port_separator - 1) = ',';
1258 snprintf(buffer, buffer_size,
1259 "Invalid port numbers: Expected positive numbers, got '%s'",
1264 /* Check if the emulator is already known.
1265 * Note: There's a small but harmless race condition here: An emulator not
1266 * present just yet could be registered by another invocation right
1267 * after doing this check here. However, local_connect protects
1268 * against double-registration too. From here, a better error message
1269 * can be produced. In the case of the race condition, the very specific
1270 * error message won't be shown, but the data doesn't get corrupted. */
1271 atransport* known_emulator = find_emulator_transport_by_sdb_port(sdb_port);
1272 if (known_emulator != NULL) {
1273 snprintf(buffer, buffer_size,
1274 "Emulator on port %d already registered.", sdb_port);
1278 /* Check if more emulators can be registered. Similar unproblematic
1279 * race condition as above. */
1280 int candidate_slot = get_available_local_transport_index();
1281 if (candidate_slot < 0) {
1282 snprintf(buffer, buffer_size, "Cannot accept more emulators.");
1286 /* Preconditions met, try to connect to the emulator. */
1287 if (!local_connect_arbitrary_ports(console_port, sdb_port, NULL)) {
1288 snprintf(buffer, buffer_size,
1289 "Connected to emulator on ports %d,%d", console_port, sdb_port);
1291 snprintf(buffer, buffer_size,
1292 "Could not connect to emulator on ports %d,%d",
1293 console_port, sdb_port);
1298 int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s)
1300 atransport *transport = NULL;
1303 if(!strcmp(service, "kill")) {
1304 fprintf(stderr,"sdb server killed by remote request\n");
1306 sdb_write(reply_fd, "OKAY", 4);
1312 // "transport:" is used for switching transport with a specified serial number
1313 // "transport-usb:" is used for switching transport to the only USB transport
1314 // "transport-local:" is used for switching transport to the only local transport
1315 // "transport-any:" is used for switching transport to the only transport
1316 if (!strncmp(service, "transport", strlen("transport"))) {
1317 char* error_string = "unknown failure";
1318 transport_type type = kTransportAny;
1320 if (!strncmp(service, "transport-usb", strlen("transport-usb"))) {
1321 type = kTransportUsb;
1322 } else if (!strncmp(service, "transport-local", strlen("transport-local"))) {
1323 type = kTransportLocal;
1324 } else if (!strncmp(service, "transport-any", strlen("transport-any"))) {
1325 type = kTransportAny;
1326 } else if (!strncmp(service, "transport:", strlen("transport:"))) {
1327 service += strlen("transport:");
1331 transport = acquire_one_transport(CS_ANY, type, serial, &error_string);
1334 s->transport = transport;
1335 sdb_write(reply_fd, "OKAY", 4);
1337 sendfailmsg(reply_fd, error_string);
1342 // return a list of all connected devices
1343 if (!strcmp(service, "devices")) {
1345 memset(buf, 0, sizeof(buf));
1346 memset(buffer, 0, sizeof(buffer));
1347 D("Getting device list \n");
1348 list_transports(buffer, sizeof(buffer));
1349 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer),buffer);
1350 D("Wrote device list \n");
1351 writex(reply_fd, buf, strlen(buf));
1355 // add a new TCP transport, device or emulator
1356 if (!strncmp(service, "connect:", 8)) {
1358 char* host = service + 8;
1359 if (!strncmp(host, "emu:", 4)) {
1360 connect_emulator(host + 4, buffer, sizeof(buffer));
1362 connect_device(host, buffer, sizeof(buffer));
1364 // Send response for emulator and device
1365 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
1366 writex(reply_fd, buf, strlen(buf));
1370 // remove TCP transport
1371 if (!strncmp(service, "disconnect:", 11)) {
1373 memset(buffer, 0, sizeof(buffer));
1374 char* serial = service + 11;
1375 if (serial[0] == 0) {
1376 // disconnect from all TCP devices
1377 unregister_all_tcp_transports();
1380 // assume port 26101 if no port is specified
1381 if (!strchr(serial, ':')) {
1382 snprintf(hostbuf, sizeof(hostbuf) - 1, "%s:26101", serial);
1385 atransport *t = find_transport(serial);
1388 unregister_transport(t);
1390 snprintf(buffer, sizeof(buffer), "No such device %s", serial);
1394 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
1395 writex(reply_fd, buf, strlen(buf));
1399 // returns our value for SDB_SERVER_VERSION
1400 if (!strcmp(service, "version")) {
1402 snprintf(version, sizeof version, "%04x", SDB_SERVER_VERSION);
1403 snprintf(buf, sizeof buf, "OKAY%04x%s", (unsigned)strlen(version), version);
1404 writex(reply_fd, buf, strlen(buf));
1408 if(!strncmp(service,"get-serialno",strlen("get-serialno"))) {
1409 char *out = "unknown";
1410 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1411 if (transport && transport->serial) {
1412 out = transport->serial;
1414 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(out),out);
1415 writex(reply_fd, buf, strlen(buf));
1418 // indicates a new emulator instance has started
1419 if (!strncmp(service,"emulator:",9)) { /* tizen specific */
1420 char *tmp = strtok(service+9, DEVICEMAP_SEPARATOR);
1424 port = atoi(service+9);
1427 tmp = strtok(NULL, DEVICEMAP_SEPARATOR);
1429 local_connect(port, tmp);
1432 local_connect(port, NULL);
1437 if(!strncmp(service,"forward:",8) || !strncmp(service,"killforward:",12)) {
1438 char *local, *remote, *err;
1440 atransport *transport;
1442 int createForward = strncmp(service,"kill",4);
1444 local = service + (createForward ? 8 : 12);
1445 remote = strchr(local,';');
1447 sendfailmsg(reply_fd, "malformed forward spec");
1452 if((local[0] == 0) || (remote[0] == 0) || (remote[0] == '*')){
1453 sendfailmsg(reply_fd, "malformed forward spec");
1457 transport = acquire_one_transport(CS_ANY, ttype, serial, &err);
1459 sendfailmsg(reply_fd, err);
1463 if (createForward) {
1464 r = install_listener(local, remote, transport);
1466 r = remove_listener(local, remote, transport);
1469 /* 1st OKAY is connect, 2nd OKAY is status */
1470 writex(reply_fd, "OKAYOKAY", 8);
1474 if (createForward) {
1475 sendfailmsg(reply_fd, (r == -1) ? "cannot rebind smartsocket" : "cannot bind socket");
1477 sendfailmsg(reply_fd, "cannot remove listener");
1482 if(!strncmp(service,"get-state",strlen("get-state"))) {
1483 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1484 char *state = connection_state_name(transport);
1485 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(state),state);
1486 writex(reply_fd, buf, strlen(buf));
1493 int recovery_mode = 0;
1496 int main(int argc, char **argv)
1498 sdb_trace_init(); /* tizen specific */
1502 return sdb_commandline(argc - 1, argv + 1);
1504 /* If sdbd runs inside the emulator this will enable sdb tracing via
1505 * sdb-debug qemud service in the emulator. */
1506 #if 0 /* tizen specific */
1507 sdb_qemu_trace_init();
1508 if((argc > 1) && (!strcmp(argv[1],"recovery"))) {
1509 sdb_device_banner = "recovery";
1514 if (daemonize() < 0)
1515 fatal("daemonize() failed: %.200s", strerror(errno));
1519 D("Handling main()\n");
1521 //sdbd will never die on emulator!
1522 signal(SIGTERM, handle_sig_term); /* tizen specific */
1523 return sdb_main(0, DEFAULT_SDB_PORT);