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
30 #include <tzplatform_config.h>
36 #include "commandline_sdbd.h"
40 #include <linux/prctl.h>
41 #define SDB_PIDPATH "/tmp/.sdbd.pid"
43 #include "usb_vendors.h"
45 #include <system_info.h>
46 #define PROC_CMDLINE_PATH "/proc/cmdline"
48 SDB_MUTEX_DEFINE( D_lock );
52 #define HOME_DEV_PATH tzplatform_getenv(TZ_SDK_HOME)
53 #define DEV_NAME tzplatform_getenv(TZ_SDK_USER_NAME)
55 SdbdCommandlineArgs sdbd_commandline_args;
58 int is_emulator(void) {
62 return sdbd_commandline_args.emulator.host != NULL;
66 void handle_sig_term(int sig) {
68 if (access(SDB_PIDPATH, F_OK) == 0)
69 sdb_unlink(SDB_PIDPATH);
71 //kill(getpgid(getpid()),SIGTERM);
72 //killpg(getpgid(getpid()),SIGTERM);
76 // do nothing on a emulator
80 static const char *sdb_device_banner = "device";
82 void fatal(const char *fmt, ...)
86 fprintf(stderr, "error: ");
87 vfprintf(stderr, fmt, ap);
88 fprintf(stderr, "\n");
93 void fatal_errno(const char *fmt, ...)
97 fprintf(stderr, "error: %s: ", strerror(errno));
98 vfprintf(stderr, fmt, ap);
99 fprintf(stderr, "\n");
106 /* read a comma/space/colum/semi-column separated list of tags
107 * from the SDB_TRACE environment variable and build the trace
108 * mask from it. note that '1' and 'all' are special cases to
111 void sdb_trace_init(void)
113 const char* p = getenv("SDB_TRACE");
116 static const struct {
122 { "sdb", TRACE_SDB },
123 { "sockets", TRACE_SOCKETS },
124 { "packets", TRACE_PACKETS },
125 { "rwx", TRACE_RWX },
126 { "usb", TRACE_USB },
127 { "sync", TRACE_SYNC },
128 { "sysdeps", TRACE_SYSDEPS },
129 { "transport", TRACE_TRANSPORT },
130 { "jdwp", TRACE_JDWP },
131 { "services", TRACE_SERVICES },
132 { "properties", TRACE_PROPERTIES },
133 { "sdktools", TRACE_SDKTOOLS },
140 /* use a comma/column/semi-colum/space separated list */
144 q = strpbrk(p, " ,:;");
150 for (tagn = 0; tags[tagn].tag != NULL; tagn++)
152 int taglen = strlen(tags[tagn].tag);
154 if (len == taglen && !memcmp(tags[tagn].tag, p, len) )
156 int flag = tags[tagn].flag;
161 sdb_trace_mask |= (1 << flag);
173 * Implements SDB tracing inside the emulator.
179 * Redefine open and write for qemu_pipe.h that contains inlined references
180 * to those routines. We will redifine them back after qemu_pipe.h inclusion.
185 #define open sdb_open
186 #define write sdb_write
187 #include "qemu_pipe.h"
190 #define open ___xxx_open
191 #define write ___xxx_write
193 /* A handle to sdb-debug qemud service in the emulator. */
194 int sdb_debug_qemu = -1;
196 /* Initializes connection with the sdb-debug qemud service in the emulator. */
197 #if 0 /* doen't support in Tizen */
198 static int sdb_qemu_trace_init(void)
202 if (sdb_debug_qemu >= 0) {
206 /* sdb debugging QEMUD service connection request. */
207 snprintf(con_name, sizeof(con_name), "qemud:sdb-debug");
208 sdb_debug_qemu = qemu_pipe_open(con_name);
209 return (sdb_debug_qemu >= 0) ? 0 : -1;
212 void sdb_qemu_trace(const char* fmt, ...)
218 if (sdb_debug_qemu >= 0) {
219 vsnprintf(msg, sizeof(msg), fmt, args);
220 sdb_write(sdb_debug_qemu, msg, strlen(msg));
224 #endif /* !SDB_HOST */
226 apacket *get_apacket(void)
228 apacket *p = malloc(sizeof(apacket));
229 if(p == 0) fatal("failed to allocate an apacket");
230 memset(p, 0, sizeof(apacket) - MAX_PAYLOAD);
234 void put_apacket(apacket *p)
242 void handle_online(void)
247 void handle_offline(atransport *t)
250 //Close the associated usb
251 run_transport_disconnects(t);
256 void print_packet(const char *label, apacket *p)
262 switch(p->msg.command){
263 case A_SYNC: tag = "SYNC"; break;
264 case A_CNXN: tag = "CNXN" ; break;
265 case A_OPEN: tag = "OPEN"; break;
266 case A_OKAY: tag = "OKAY"; break;
267 case A_CLSE: tag = "CLSE"; break;
268 case A_WRTE: tag = "WRTE"; break;
269 default: tag = "????"; break;
272 fprintf(stderr, "%s: %s %08x %08x %04x \"",
273 label, tag, p->msg.arg0, p->msg.arg1, p->msg.data_length);
274 count = p->msg.data_length;
276 if(count > DUMPMAX) {
283 if((*x >= ' ') && (*x < 127)) {
290 fprintf(stderr, tag);
294 static void send_ready(unsigned local, unsigned remote, atransport *t)
296 D("Calling send_ready \n");
297 apacket *p = get_apacket();
298 p->msg.command = A_OKAY;
300 p->msg.arg1 = remote;
304 static void send_close(unsigned local, unsigned remote, atransport *t)
306 D("Calling send_close \n");
307 apacket *p = get_apacket();
308 p->msg.command = A_CLSE;
310 p->msg.arg1 = remote;
313 static int device_status = 0; // 0:online, 1: password locked later
314 static void send_connect(atransport *t)
316 D("Calling send_connect \n");
317 apacket *cp = get_apacket();
318 cp->msg.command = A_CNXN;
319 cp->msg.arg0 = A_VERSION;
320 cp->msg.arg1 = MAX_PAYLOAD;
322 char device_name[256]={0,};
326 r = get_emulator_name(device_name, sizeof device_name);
328 r = get_device_name(device_name, sizeof device_name);
331 snprintf((char*) cp->data, sizeof cp->data, "%s::%s::%d", sdb_device_banner, DEFAULT_DEVICENAME, device_status);
333 snprintf((char*) cp->data, sizeof cp->data, "%s::%s::%d", sdb_device_banner, device_name, device_status);
336 D("CNXN data:%s\n", (char*)cp->data);
337 cp->msg.data_length = strlen((char*) cp->data) + 1;
341 /* XXX why sleep here? */
342 // allow the device some time to respond to the connect message
347 static char *connection_state_name(atransport *t)
353 switch(t->connection_state) {
365 static int get_str_cmdline(char *src, char *dest, char str[], int str_size) {
366 char *s = strstr(src, dest);
370 char *e = strstr(s, " ");
375 int len = e-s-strlen(dest);
377 if (len >= str_size) {
378 D("buffer size(%d) should be bigger than %d\n", str_size, len+1);
382 s_strncpy(str, s + strlen(dest), len);
386 int get_emulator_forward_port() {
387 SdbdCommandlineArgs *sdbd_args = &sdbd_commandline_args; /* alias */
389 if (sdbd_args->emulator.host == NULL) {
393 return sdbd_args->emulator.port;
396 int get_emulator_name(char str[], int str_size) {
397 SdbdCommandlineArgs *sdbd_args = &sdbd_commandline_args; /* alias */
399 if (sdbd_args->emulator.host == NULL) {
403 s_strncpy(str, sdbd_args->emulator.host, str_size);
407 int get_device_name(char str[], int str_size) {
409 int r = system_info_get_value_string(SYSTEM_INFO_KEY_MODEL, &value);
410 if (r != SYSTEM_INFO_ERROR_NONE) {
411 D("fail to get system model:%d\n", errno);
414 s_strncpy(str, value, str_size);
415 D("returns model_name:%s\n", value);
422 int fd = unix_open(USB_SERIAL_PATH, O_RDONLY);
424 D("fail to read:%s (%d)\n", USB_SERIAL_PATH, errno);
428 if(read_line(fd, str, str_size)) {
429 D("device serial name: %s\n", str);
438 void parse_banner(char *banner, atransport *t)
440 char *type, *product, *end;
442 D("parse_banner: %s\n", banner);
444 product = strchr(type, ':');
451 /* remove trailing ':' */
452 end = strchr(product, ':');
455 /* save product name in device structure */
456 if (t->product == NULL) {
457 t->product = strdup(product);
458 } else if (strcmp(product, t->product) != 0) {
460 t->product = strdup(product);
463 if(!strcmp(type, "bootloader")){
464 D("setting connection_state to CS_BOOTLOADER\n");
465 t->connection_state = CS_BOOTLOADER;
470 if(!strcmp(type, "device")) {
471 D("setting connection_state to CS_DEVICE\n");
472 t->connection_state = CS_DEVICE;
477 if(!strcmp(type, "recovery")) {
478 D("setting connection_state to CS_RECOVERY\n");
479 t->connection_state = CS_RECOVERY;
484 if(!strcmp(type, "sideload")) {
485 D("setting connection_state to CS_SIDELOAD\n");
486 t->connection_state = CS_SIDELOAD;
491 t->connection_state = CS_HOST;
494 void handle_packet(apacket *p, atransport *t)
498 D("handle_packet() %c%c%c%c\n", ((char*) (&(p->msg.command)))[0],
499 ((char*) (&(p->msg.command)))[1],
500 ((char*) (&(p->msg.command)))[2],
501 ((char*) (&(p->msg.command)))[3]);
503 print_packet("recv", p);
505 switch(p->msg.command){
509 if(HOST) send_connect(t);
511 t->connection_state = CS_OFFLINE;
517 case A_CNXN: /* CONNECT(version, maxdata, "system-id-string") */
518 /* XXX verify version, etc */
519 if(t->connection_state != CS_OFFLINE) {
520 t->connection_state = CS_OFFLINE;
523 parse_banner((char*) p->data, t);
525 if(!HOST) send_connect(t);
528 case A_OPEN: /* OPEN(local-id, 0, "destination") */
529 if(t->connection_state != CS_OFFLINE) {
530 char *name = (char*) p->data;
531 name[p->msg.data_length > 0 ? p->msg.data_length - 1 : 0] = 0;
532 s = create_local_service_socket(name);
534 send_close(0, p->msg.arg0, t);
536 s->peer = create_remote_socket(p->msg.arg0, t);
538 send_ready(s->id, s->peer->id, t);
544 case A_OKAY: /* READY(local-id, remote-id, "") */
545 if(t->connection_state != CS_OFFLINE) {
546 if((s = find_local_socket(p->msg.arg1))) {
548 s->peer = create_remote_socket(p->msg.arg0, t);
556 case A_CLSE: /* CLOSE(local-id, remote-id, "") */
557 if(t->connection_state != CS_OFFLINE) {
558 if((s = find_local_socket(p->msg.arg1))) {
565 if(t->connection_state != CS_OFFLINE) {
566 if((s = find_local_socket(p->msg.arg1))) {
567 unsigned rid = p->msg.arg0;
568 p->len = p->msg.data_length;
570 if(s->enqueue(s, p) == 0) {
571 D("Enqueue the socket\n");
572 send_ready(s->id, rid, t);
580 printf("handle_packet: what is %08x?!\n", p->msg.command);
586 alistener listener_list = {
587 .next = &listener_list,
588 .prev = &listener_list,
591 static void ss_listener_event_func(int _fd, unsigned ev, void *_l)
596 struct sockaddr addr;
601 fd = sdb_socket_accept(_fd, &addr, &alen);
604 sdb_socket_setbufsize(fd, CHUNK_SIZE);
606 s = create_local_socket(fd);
608 connect_to_smartsocket(s);
616 static void listener_event_func(int _fd, unsigned ev, void *_l)
622 struct sockaddr addr;
627 fd = sdb_socket_accept(_fd, &addr, &alen);
630 s = create_local_socket(fd);
632 s->transport = l->transport;
633 connect_to_remote(s, l->connect_to);
641 static void free_listener(alistener* l)
644 l->next->prev = l->prev;
645 l->prev->next = l->next;
646 l->next = l->prev = l;
649 // closes the corresponding fd
650 fdevent_remove(&l->fde);
653 free((char*)l->local_name);
656 free((char*)l->connect_to);
659 remove_transport_disconnect(l->transport, &l->disconnect);
664 static void listener_disconnect(void* _l, atransport* t)
671 int local_name_to_fd(const char *name)
675 if(!strncmp("tcp:", name, 4)){
677 port = atoi(name + 4);
678 ret = socket_loopback_server(port, SOCK_STREAM);
681 #ifndef HAVE_WIN32_IPC /* no Unix-domain sockets on Win32 */
682 // It's non-sensical to support the "reserved" space on the sdb host side
683 if(!strncmp(name, "local:", 6)) {
684 return socket_local_server(name + 6,
685 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
686 } else if(!strncmp(name, "localabstract:", 14)) {
687 return socket_local_server(name + 14,
688 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
689 } else if(!strncmp(name, "localfilesystem:", 16)) {
690 return socket_local_server(name + 16,
691 ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
695 printf("unknown local portname '%s'\n", name);
699 static int remove_listener(const char *local_name, const char *connect_to, atransport* transport)
703 for (l = listener_list.next; l != &listener_list; l = l->next) {
704 if (!strcmp(local_name, l->local_name) &&
705 !strcmp(connect_to, l->connect_to) &&
706 l->transport && l->transport == transport) {
708 listener_disconnect(l, transport);
716 static int install_listener(const char *local_name, const char *connect_to, atransport* transport)
720 //printf("install_listener('%s','%s')\n", local_name, connect_to);
722 for(l = listener_list.next; l != &listener_list; l = l->next){
723 if(strcmp(local_name, l->local_name) == 0) {
726 /* can't repurpose a smartsocket */
727 if(l->connect_to[0] == '*') {
731 cto = strdup(connect_to);
736 //printf("rebinding '%s' to '%s'\n", local_name, connect_to);
737 free((void*) l->connect_to);
739 if (l->transport != transport) {
740 remove_transport_disconnect(l->transport, &l->disconnect);
741 l->transport = transport;
742 add_transport_disconnect(l->transport, &l->disconnect);
748 if((l = calloc(1, sizeof(alistener))) == 0) goto nomem;
749 if((l->local_name = strdup(local_name)) == 0) goto nomem;
750 if((l->connect_to = strdup(connect_to)) == 0) goto nomem;
753 l->fd = local_name_to_fd(local_name);
755 free((void*) l->local_name);
756 free((void*) l->connect_to);
758 printf("cannot bind '%s'\n", local_name);
762 if (close_on_exec(l->fd) < 0) {
763 D("fail to close fd exec:%d\n",l->fd);
765 if(!strcmp(l->connect_to, "*smartsocket*")) {
766 fdevent_install(&l->fde, l->fd, ss_listener_event_func, l);
768 fdevent_install(&l->fde, l->fd, listener_event_func, l);
770 fdevent_set(&l->fde, FDE_READ);
772 l->next = &listener_list;
773 l->prev = listener_list.prev;
776 l->transport = transport;
779 l->disconnect.opaque = l;
780 l->disconnect.func = listener_disconnect;
781 add_transport_disconnect(transport, &l->disconnect);
786 fatal("cannot allocate listener");
790 #ifdef HAVE_WIN32_PROC
791 static BOOL WINAPI ctrlc_handler(DWORD type)
793 exit(STATUS_CONTROL_C_EXIT);
798 static void sdb_cleanup(void)
800 clear_sdbd_commandline_args(&sdbd_commandline_args);
802 // if(required_pid > 0) {
803 // kill(required_pid, SIGKILL);
807 void start_logging(void)
809 #ifdef HAVE_WIN32_PROC
810 char temp[ MAX_PATH ];
814 GetTempPath( sizeof(temp) - 8, temp );
815 strcat( temp, "sdb.log" );
817 /* Win32 specific redirections */
818 fnul = fopen( "NUL", "rt" );
822 flog = fopen( temp, "at" );
826 setvbuf( flog, NULL, _IONBF, 0 );
830 fprintf(stderr,"--- sdb starting (pid %d) ---\n", getpid());
834 fd = unix_open("/dev/null", O_RDONLY);
836 // hopefully not gonna happen
842 fd = unix_open("/tmp/sdb.log", O_WRONLY | O_CREAT | O_APPEND, 0640);
844 fd = unix_open("/dev/null", O_WRONLY);
846 // hopefully not gonna happen
853 fprintf(stderr,"--- sdb starting (pid %d) ---\n", getpid());
858 void start_device_log(void)
864 // char value[PROPERTY_VALUE_MAX];
865 const char* p = getenv("SDB_TRACE");
866 // read the trace mask from persistent property persist.sdb.trace_mask
867 // give up if the property is not set or cannot be parsed
868 #if 0 /* tizen specific */
869 property_get("persist.sdb.trace_mask", value, "");
870 if (sscanf(value, "%x", &sdb_trace_mask) != 1)
879 localtime_r(&t, &now);
880 strftime(path, sizeof(path),
881 "/tmp/sdbd-%Y-%m-%d-%H-%M-%S.txt",
883 fd = unix_open(path, O_WRONLY | O_CREAT | O_TRUNC, 0640);
888 // redirect stdout and stderr to the log file
891 fprintf(stderr,"--- sdbd starting (pid %d) ---\n", getpid());
894 fd = unix_open("/dev/null", O_RDONLY);
896 // hopefully not gonna happen
903 int daemonize(void) {
905 // set file creation mask to 0
917 FILE *f = fopen(SDB_PIDPATH, "w");
920 fprintf(f, "%d\n", getpid());
928 D("sdbd: unable to change working directory to /\n");
935 int launch_server(int server_port)
937 #ifdef HAVE_WIN32_PROC
938 /* we need to start the server in the background */
939 /* we create a PIPE that will be used to wait for the server's "OK" */
940 /* message since the pipe handles must be inheritable, we use a */
941 /* security attribute */
942 HANDLE pipe_read, pipe_write;
943 SECURITY_ATTRIBUTES sa;
945 PROCESS_INFORMATION pinfo;
946 char program_path[ MAX_PATH ];
949 sa.nLength = sizeof(sa);
950 sa.lpSecurityDescriptor = NULL;
951 sa.bInheritHandle = TRUE;
953 /* create pipe, and ensure its read handle isn't inheritable */
954 ret = CreatePipe( &pipe_read, &pipe_write, &sa, 0 );
956 fprintf(stderr, "CreatePipe() failure, error %ld\n", GetLastError() );
960 SetHandleInformation( pipe_read, HANDLE_FLAG_INHERIT, 0 );
962 ZeroMemory( &startup, sizeof(startup) );
963 startup.cb = sizeof(startup);
964 startup.hStdInput = GetStdHandle( STD_INPUT_HANDLE );
965 startup.hStdOutput = pipe_write;
966 startup.hStdError = GetStdHandle( STD_ERROR_HANDLE );
967 startup.dwFlags = STARTF_USESTDHANDLES;
969 ZeroMemory( &pinfo, sizeof(pinfo) );
971 /* get path of current program */
972 GetModuleFileName( NULL, program_path, sizeof(program_path) );
975 program_path, /* program path */
976 "sdb fork-server server",
977 /* the fork-server argument will set the
978 debug = 2 in the child */
979 NULL, /* process handle is not inheritable */
980 NULL, /* thread handle is not inheritable */
981 TRUE, /* yes, inherit some handles */
982 DETACHED_PROCESS, /* the new process doesn't have a console */
983 NULL, /* use parent's environment block */
984 NULL, /* use parent's starting directory */
985 &startup, /* startup info, i.e. std handles */
988 CloseHandle( pipe_write );
991 fprintf(stderr, "CreateProcess failure, error %ld\n", GetLastError() );
992 CloseHandle( pipe_read );
996 CloseHandle( pinfo.hProcess );
997 CloseHandle( pinfo.hThread );
999 /* wait for the "OK\n" message */
1004 ret = ReadFile( pipe_read, temp, 3, &count, NULL );
1005 CloseHandle( pipe_read );
1007 fprintf(stderr, "could not read ok from SDB Server, error = %ld\n", GetLastError() );
1010 if (count != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
1011 fprintf(stderr, "SDB server didn't ACK\n" );
1015 #elif defined(HAVE_FORKEXEC)
1016 char path[PATH_MAX];
1019 // set up a pipe so the child can tell us when it is ready.
1020 // fd[0] will be parent's end, and fd[1] will get mapped to stderr in the child.
1022 fprintf(stderr, "pipe failed in launch_server, errno: %d\n", errno);
1025 get_my_path(path, PATH_MAX);
1027 if(pid < 0) return -1;
1030 // child side of the fork
1032 // redirect stderr to the pipe
1033 // we use stderr instead of stdout due to stdout's buffering behavior.
1035 dup2(fd[1], STDERR_FILENO);
1039 int result = execl(path, "sdb", "fork-server", "server", NULL);
1040 // this should not return
1041 fprintf(stderr, "OOPS! execl returned %d, errno: %d\n", result, errno);
1043 // parent side of the fork
1047 temp[0] = 'A'; temp[1] = 'B'; temp[2] = 'C';
1048 // wait for the "OK\n" message
1050 int ret = sdb_read(fd[0], temp, 3);
1051 int saved_errno = errno;
1054 fprintf(stderr, "could not read ok from SDB Server, errno = %d\n", saved_errno);
1057 if (ret != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
1058 fprintf(stderr, "SDB server didn't ACK\n" );
1065 #error "cannot implement background server start on this platform"
1071 /* Constructs a local name of form tcp:port.
1072 * target_str points to the target string, it's content will be overwritten.
1073 * target_size is the capacity of the target string.
1074 * server_port is the port number to use for the local name.
1076 void build_local_name(char* target_str, size_t target_size, int server_port)
1078 snprintf(target_str, target_size, "tcp:%d", server_port);
1082 static void init_drop_privileges() {
1083 #ifdef _DROP_PRIVILEGE
1090 int should_drop_privileges() {
1091 if (rootshell_mode == 1) { // if root, then don't drop
1097 int set_developer_privileges() {
1098 gid_t groups[] = { SID_DEVELOPER, SID_APP_LOGGING, SID_SYS_LOGGING, SID_INPUT };
1099 if (setgroups(sizeof(groups) / sizeof(groups[0]), groups) != 0) {
1100 D("set groups failed (errno: %d, %s)\n", errno, strerror(errno));
1103 // then switch user and group to developer
1104 if (setgid(SID_DEVELOPER) != 0) {
1105 D("set group id failed (errno: %d, %s)\n", errno, strerror(errno));
1109 if (setuid(SID_DEVELOPER) != 0) {
1110 D("set user id failed (errno: %d, %s)\n", errno, strerror(errno));
1114 if (chdir(HOME_DEV_PATH) < 0) {
1115 D("sdbd: unable to change working directory to %s\n", HOME_DEV_PATH);
1117 if (chdir("/") < 0) {
1118 D("sdbd: unable to change working directory to /\n");
1121 // TODO: use pam later
1122 char * env = "HOME=";
1123 strcat(env, HOME_DEV_PATH);
1128 #define ONDEMAND_ROOT_PATH tzplatform_getenv(TZ_SDK_HOME)
1130 static void init_sdk_requirements() {
1133 // set env variable for temporary
1134 // TODO: should use pam instead later!!
1135 if (!getenv("TERM")) {
1136 putenv("TERM=linux");
1139 if (!getenv("HOME")) {
1140 putenv("HOME=/root");
1143 if (stat(ONDEMAND_ROOT_PATH, &st) == -1) {
1146 if (st.st_uid != SID_DEVELOPER || st.st_gid != SID_DEVELOPER) {
1148 snprintf(cmd, sizeof(cmd), "chown %s:%s %s -R", DEV_NAME, DEV_NAME, ONDEMAND_ROOT_PATH);
1149 if (system(cmd) < 0) {
1150 D("failed to change ownership to developer to %s\n", ONDEMAND_ROOT_PATH);
1155 #endif /* !SDB_HOST */
1157 int sdb_main(int is_daemon, int server_port)
1160 init_drop_privileges();
1161 init_sdk_requirements();
1165 atexit(sdb_cleanup);
1166 #ifdef HAVE_WIN32_PROC
1167 SetConsoleCtrlHandler( ctrlc_handler, TRUE );
1168 #elif defined(HAVE_FORKEXEC)
1169 // No SIGCHLD. Let the service subproc handle its children.
1170 signal(SIGPIPE, SIG_IGN);
1173 init_transport_registration();
1180 local_init(DEFAULT_SDB_LOCAL_TRANSPORT_PORT);
1182 char local_name[30];
1183 build_local_name(local_name, sizeof(local_name), server_port);
1184 if(install_listener(local_name, "*smartsocket*", NULL)) {
1188 /* don't listen on a port (default 5037) if running in secure mode */
1189 /* don't run as root if we are running in secure mode */
1191 if (should_drop_privileges()) {
1193 struct __user_cap_header_struct header;
1194 struct __user_cap_data_struct cap;
1196 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
1199 /* add extra groups:
1200 ** SID_TTY to access /dev/ptmx
1202 gid_t groups[] = { SID_TTY, SID_APP_LOGGING, SID_SYS_LOGGING };
1203 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
1206 /* then switch user and group to "developer" */
1207 if (setgid(SID_DEVELOPER) != 0) {
1208 fprintf(stderr, "set group id failed errno: %d\n", errno);
1211 if (setuid(SID_DEVELOPER) != 0) {
1212 fprintf(stderr, "set user id failed errno: %d\n", errno);
1216 /* set CAP_SYS_BOOT capability, so "sdb reboot" will succeed */
1217 header.version = _LINUX_CAPABILITY_VERSION;
1219 cap.effective = cap.permitted = (1 << CAP_SYS_BOOT);
1220 cap.inheritable = 0;
1221 capset(&header, &cap);
1223 D("Local port disabled\n");
1225 char local_name[30];
1226 build_local_name(local_name, sizeof(local_name), server_port);
1227 if(install_listener(local_name, "*smartsocket*", NULL)) {
1232 if (!is_emulator()) {
1237 /* by default don't listen on local transport but
1238 * listen if suitable command line argument has been provided */
1239 if (sdbd_commandline_args.sdbd_port >= 0) {
1240 local_init(sdbd_commandline_args.sdbd_port);
1243 #if 0 /* tizen specific */
1244 D("sdb_main(): pre init_jdwp()\n");
1246 D("sdb_main(): post init_jdwp()\n");
1252 // inform our parent that we are up and running.
1253 #ifdef HAVE_WIN32_PROC
1255 WriteFile( GetStdHandle( STD_OUTPUT_HANDLE ), "OK\n", 3, &count, NULL );
1256 #elif defined(HAVE_FORKEXEC)
1257 fprintf(stderr, "OK\n");
1262 D("Event loop starting\n");
1272 void connect_device(char* host, char* buffer, int buffer_size)
1275 char* portstr = strchr(host, ':');
1279 strncpy(hostbuf, host, sizeof(hostbuf) - 1);
1281 if (portstr - host >= sizeof(hostbuf)) {
1282 snprintf(buffer, buffer_size, "bad host name %s", host);
1285 // zero terminate the host at the point we found the colon
1286 hostbuf[portstr - host] = 0;
1287 if (sscanf(portstr + 1, "%d", &port) == 0) {
1288 snprintf(buffer, buffer_size, "bad port number %s", portstr);
1292 port = DEFAULT_SDB_LOCAL_TRANSPORT_PORT;
1295 snprintf(serial, sizeof(serial), "%s:%d", hostbuf, port);
1296 if (find_transport(serial)) {
1297 snprintf(buffer, buffer_size, "already connected to %s", serial);
1301 fd = socket_network_client(hostbuf, port, SOCK_STREAM);
1303 snprintf(buffer, buffer_size, "unable to connect to %s", host);
1307 D("client: connected on remote on fd %d\n", fd);
1309 disable_tcp_nagle(fd);
1310 register_socket_transport(fd, serial, port, 0, NULL);
1311 snprintf(buffer, buffer_size, "connected to %s", serial);
1314 void connect_emulator(char* port_spec, char* buffer, int buffer_size)
1316 char* port_separator = strchr(port_spec, ',');
1317 if (!port_separator) {
1318 snprintf(buffer, buffer_size,
1319 "unable to parse '%s' as <console port>,<sdb port>",
1324 // Zero-terminate console port and make port_separator point to 2nd port.
1325 *port_separator++ = 0;
1326 int console_port = strtol(port_spec, NULL, 0);
1327 int sdb_port = strtol(port_separator, NULL, 0);
1328 if (!(console_port > 0 && sdb_port > 0)) {
1329 *(port_separator - 1) = ',';
1330 snprintf(buffer, buffer_size,
1331 "Invalid port numbers: Expected positive numbers, got '%s'",
1336 /* Check if the emulator is already known.
1337 * Note: There's a small but harmless race condition here: An emulator not
1338 * present just yet could be registered by another invocation right
1339 * after doing this check here. However, local_connect protects
1340 * against double-registration too. From here, a better error message
1341 * can be produced. In the case of the race condition, the very specific
1342 * error message won't be shown, but the data doesn't get corrupted. */
1343 atransport* known_emulator = find_emulator_transport_by_sdb_port(sdb_port);
1344 if (known_emulator != NULL) {
1345 snprintf(buffer, buffer_size,
1346 "Emulator on port %d already registered.", sdb_port);
1350 /* Check if more emulators can be registered. Similar unproblematic
1351 * race condition as above. */
1352 int candidate_slot = get_available_local_transport_index();
1353 if (candidate_slot < 0) {
1354 snprintf(buffer, buffer_size, "Cannot accept more emulators.");
1358 /* Preconditions met, try to connect to the emulator. */
1359 if (!local_connect_arbitrary_ports(console_port, sdb_port, NULL)) {
1360 snprintf(buffer, buffer_size,
1361 "Connected to emulator on ports %d,%d", console_port, sdb_port);
1363 snprintf(buffer, buffer_size,
1364 "Could not connect to emulator on ports %d,%d",
1365 console_port, sdb_port);
1370 int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s)
1372 atransport *transport = NULL;
1375 if(!strcmp(service, "kill")) {
1376 fprintf(stderr,"sdb server killed by remote request\n");
1378 sdb_write(reply_fd, "OKAY", 4);
1384 // "transport:" is used for switching transport with a specified serial number
1385 // "transport-usb:" is used for switching transport to the only USB transport
1386 // "transport-local:" is used for switching transport to the only local transport
1387 // "transport-any:" is used for switching transport to the only transport
1388 if (!strncmp(service, "transport", strlen("transport"))) {
1389 char* error_string = "unknown failure";
1390 transport_type type = kTransportAny;
1392 if (!strncmp(service, "transport-usb", strlen("transport-usb"))) {
1393 type = kTransportUsb;
1394 } else if (!strncmp(service, "transport-local", strlen("transport-local"))) {
1395 type = kTransportLocal;
1396 } else if (!strncmp(service, "transport-any", strlen("transport-any"))) {
1397 type = kTransportAny;
1398 } else if (!strncmp(service, "transport:", strlen("transport:"))) {
1399 service += strlen("transport:");
1403 transport = acquire_one_transport(CS_ANY, type, serial, &error_string);
1406 s->transport = transport;
1407 sdb_write(reply_fd, "OKAY", 4);
1409 sendfailmsg(reply_fd, error_string);
1414 // return a list of all connected devices
1415 if (!strcmp(service, "devices")) {
1417 memset(buf, 0, sizeof(buf));
1418 memset(buffer, 0, sizeof(buffer));
1419 D("Getting device list \n");
1420 list_transports(buffer, sizeof(buffer));
1421 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer),buffer);
1422 D("Wrote device list \n");
1423 writex(reply_fd, buf, strlen(buf));
1427 // add a new TCP transport, device or emulator
1428 if (!strncmp(service, "connect:", 8)) {
1430 char* host = service + 8;
1431 if (!strncmp(host, "emu:", 4)) {
1432 connect_emulator(host + 4, buffer, sizeof(buffer));
1434 connect_device(host, buffer, sizeof(buffer));
1436 // Send response for emulator and device
1437 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
1438 writex(reply_fd, buf, strlen(buf));
1442 // remove TCP transport
1443 if (!strncmp(service, "disconnect:", 11)) {
1445 memset(buffer, 0, sizeof(buffer));
1446 char* serial = service + 11;
1447 if (serial[0] == 0) {
1448 // disconnect from all TCP devices
1449 unregister_all_tcp_transports();
1452 // assume port 26101 if no port is specified
1453 if (!strchr(serial, ':')) {
1454 snprintf(hostbuf, sizeof(hostbuf) - 1, "%s:26101", serial);
1457 atransport *t = find_transport(serial);
1460 unregister_transport(t);
1462 snprintf(buffer, sizeof(buffer), "No such device %s", serial);
1466 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
1467 writex(reply_fd, buf, strlen(buf));
1471 // returns our value for SDB_SERVER_VERSION
1472 if (!strcmp(service, "version")) {
1474 snprintf(version, sizeof version, "%04x", SDB_SERVER_VERSION);
1475 snprintf(buf, sizeof buf, "OKAY%04x%s", (unsigned)strlen(version), version);
1476 writex(reply_fd, buf, strlen(buf));
1480 if(!strncmp(service,"get-serialno",strlen("get-serialno"))) {
1481 char *out = "unknown";
1482 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1483 if (transport && transport->serial) {
1484 out = transport->serial;
1486 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(out),out);
1487 writex(reply_fd, buf, strlen(buf));
1490 // indicates a new emulator instance has started
1491 if (!strncmp(service,"emulator:",9)) { /* tizen specific */
1492 char *tmp = strtok(service+9, DEVICEMAP_SEPARATOR);
1496 port = atoi(service+9);
1499 tmp = strtok(NULL, DEVICEMAP_SEPARATOR);
1501 local_connect(port, tmp);
1504 local_connect(port, NULL);
1509 if(!strncmp(service,"forward:",8) || !strncmp(service,"killforward:",12)) {
1510 char *local, *remote, *err;
1512 atransport *transport;
1514 int createForward = strncmp(service,"kill",4);
1516 local = service + (createForward ? 8 : 12);
1517 remote = strchr(local,';');
1519 sendfailmsg(reply_fd, "malformed forward spec");
1524 if((local[0] == 0) || (remote[0] == 0) || (remote[0] == '*')){
1525 sendfailmsg(reply_fd, "malformed forward spec");
1529 transport = acquire_one_transport(CS_ANY, ttype, serial, &err);
1531 sendfailmsg(reply_fd, err);
1535 if (createForward) {
1536 r = install_listener(local, remote, transport);
1538 r = remove_listener(local, remote, transport);
1541 /* 1st OKAY is connect, 2nd OKAY is status */
1542 writex(reply_fd, "OKAYOKAY", 8);
1546 if (createForward) {
1547 sendfailmsg(reply_fd, (r == -1) ? "cannot rebind smartsocket" : "cannot bind socket");
1549 sendfailmsg(reply_fd, "cannot remove listener");
1554 if(!strncmp(service,"get-state",strlen("get-state"))) {
1555 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1556 char *state = connection_state_name(transport);
1557 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(state),state);
1558 writex(reply_fd, buf, strlen(buf));
1565 int recovery_mode = 0;
1568 int main(int argc, char **argv)
1570 sdb_trace_init(); /* tizen specific */
1574 return sdb_commandline(argc - 1, argv + 1);
1576 /* If sdbd runs inside the emulator this will enable sdb tracing via
1577 * sdb-debug qemud service in the emulator. */
1578 #if 0 /* tizen specific */
1579 sdb_qemu_trace_init();
1580 if((argc > 1) && (!strcmp(argv[1],"recovery"))) {
1581 sdb_device_banner = "recovery";
1586 apply_sdbd_commandline_defaults(&sdbd_commandline_args);
1587 int parse_ret = parse_sdbd_commandline(&sdbd_commandline_args, argc, argv);
1589 // TODO: Add detailed error messages
1590 // TODO: Add individual messages for help and usage
1591 if(parse_ret != SDBD_COMMANDLINE_SUCCESS) {
1592 if (parse_ret == SDBD_COMMANDLINE_HELP
1593 || parse_ret == SDBD_COMMANDLINE_USAGE) {
1594 // User requested help or usage
1595 print_sdbd_usage_message(stdout);
1596 return EXIT_SUCCESS;
1599 // Print usage message because of invalid options
1600 print_sdbd_usage_message(stderr);
1601 return EXIT_FAILURE;
1605 if (daemonize() < 0)
1606 fatal("daemonize() failed: %.200s", strerror(errno));
1610 D("Handling main()\n");
1612 //sdbd will never die on emulator!
1613 signal(SIGTERM, handle_sig_term); /* tizen specific */
1614 return sdb_main(0, DEFAULT_SDB_PORT);