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
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 );
54 SdbdCommandlineArgs sdbd_commandline_args;
57 int is_emulator(void) {
61 return sdbd_commandline_args.emulator.host != NULL;
65 void handle_sig_term(int sig) {
67 if (access(SDB_PIDPATH, F_OK) == 0)
68 sdb_unlink(SDB_PIDPATH);
70 //kill(getpgid(getpid()),SIGTERM);
71 //killpg(getpgid(getpid()),SIGTERM);
75 // do nothing on a emulator
79 static const char *sdb_device_banner = "device";
81 void fatal(const char *fmt, ...)
85 fprintf(stderr, "error: ");
86 vfprintf(stderr, fmt, ap);
87 fprintf(stderr, "\n");
92 void fatal_errno(const char *fmt, ...)
96 fprintf(stderr, "error: %s: ", strerror(errno));
97 vfprintf(stderr, fmt, ap);
98 fprintf(stderr, "\n");
105 /* read a comma/space/colum/semi-column separated list of tags
106 * from the SDB_TRACE environment variable and build the trace
107 * mask from it. note that '1' and 'all' are special cases to
110 void sdb_trace_init(void)
112 const char* p = getenv("SDB_TRACE");
115 static const struct {
121 { "sdb", TRACE_SDB },
122 { "sockets", TRACE_SOCKETS },
123 { "packets", TRACE_PACKETS },
124 { "rwx", TRACE_RWX },
125 { "usb", TRACE_USB },
126 { "sync", TRACE_SYNC },
127 { "sysdeps", TRACE_SYSDEPS },
128 { "transport", TRACE_TRANSPORT },
129 { "jdwp", TRACE_JDWP },
130 { "services", TRACE_SERVICES },
131 { "properties", TRACE_PROPERTIES },
132 { "sdktools", TRACE_SDKTOOLS },
139 /* use a comma/column/semi-colum/space separated list */
143 q = strpbrk(p, " ,:;");
149 for (tagn = 0; tags[tagn].tag != NULL; tagn++)
151 int taglen = strlen(tags[tagn].tag);
153 if (len == taglen && !memcmp(tags[tagn].tag, p, len) )
155 int flag = tags[tagn].flag;
160 sdb_trace_mask |= (1 << flag);
172 * Implements SDB tracing inside the emulator.
178 * Redefine open and write for qemu_pipe.h that contains inlined references
179 * to those routines. We will redifine them back after qemu_pipe.h inclusion.
184 #define open sdb_open
185 #define write sdb_write
186 #include "qemu_pipe.h"
189 #define open ___xxx_open
190 #define write ___xxx_write
192 /* A handle to sdb-debug qemud service in the emulator. */
193 int sdb_debug_qemu = -1;
195 /* Initializes connection with the sdb-debug qemud service in the emulator. */
196 #if 0 /* doen't support in Tizen */
197 static int sdb_qemu_trace_init(void)
201 if (sdb_debug_qemu >= 0) {
205 /* sdb debugging QEMUD service connection request. */
206 snprintf(con_name, sizeof(con_name), "qemud:sdb-debug");
207 sdb_debug_qemu = qemu_pipe_open(con_name);
208 return (sdb_debug_qemu >= 0) ? 0 : -1;
211 void sdb_qemu_trace(const char* fmt, ...)
217 if (sdb_debug_qemu >= 0) {
218 vsnprintf(msg, sizeof(msg), fmt, args);
219 sdb_write(sdb_debug_qemu, msg, strlen(msg));
223 #endif /* !SDB_HOST */
225 apacket *get_apacket(void)
227 apacket *p = malloc(sizeof(apacket));
228 if(p == 0) fatal("failed to allocate an apacket");
229 memset(p, 0, sizeof(apacket) - MAX_PAYLOAD);
233 void put_apacket(apacket *p)
241 void handle_online(void)
246 void handle_offline(atransport *t)
249 //Close the associated usb
250 run_transport_disconnects(t);
255 void print_packet(const char *label, apacket *p)
261 switch(p->msg.command){
262 case A_SYNC: tag = "SYNC"; break;
263 case A_CNXN: tag = "CNXN" ; break;
264 case A_OPEN: tag = "OPEN"; break;
265 case A_OKAY: tag = "OKAY"; break;
266 case A_CLSE: tag = "CLSE"; break;
267 case A_WRTE: tag = "WRTE"; break;
268 default: tag = "????"; break;
271 fprintf(stderr, "%s: %s %08x %08x %04x \"",
272 label, tag, p->msg.arg0, p->msg.arg1, p->msg.data_length);
273 count = p->msg.data_length;
275 if(count > DUMPMAX) {
282 if((*x >= ' ') && (*x < 127)) {
289 fprintf(stderr, tag);
293 static void send_ready(unsigned local, unsigned remote, atransport *t)
295 D("Calling send_ready \n");
296 apacket *p = get_apacket();
297 p->msg.command = A_OKAY;
299 p->msg.arg1 = remote;
303 static void send_close(unsigned local, unsigned remote, atransport *t)
305 D("Calling send_close \n");
306 apacket *p = get_apacket();
307 p->msg.command = A_CLSE;
309 p->msg.arg1 = remote;
312 static int device_status = 0; // 0:online, 1: password locked later
313 static void send_connect(atransport *t)
315 D("Calling send_connect \n");
316 apacket *cp = get_apacket();
317 cp->msg.command = A_CNXN;
318 cp->msg.arg0 = A_VERSION;
319 cp->msg.arg1 = MAX_PAYLOAD;
321 char device_name[256]={0,};
325 r = get_emulator_name(device_name, sizeof device_name);
327 r = get_device_name(device_name, sizeof device_name);
330 snprintf((char*) cp->data, sizeof cp->data, "%s::%s::%d", sdb_device_banner, DEFAULT_DEVICENAME, device_status);
332 snprintf((char*) cp->data, sizeof cp->data, "%s::%s::%d", sdb_device_banner, device_name, device_status);
335 D("CNXN data:%s\n", (char*)cp->data);
336 cp->msg.data_length = strlen((char*) cp->data) + 1;
340 /* XXX why sleep here? */
341 // allow the device some time to respond to the connect message
346 static char *connection_state_name(atransport *t)
352 switch(t->connection_state) {
364 static int get_str_cmdline(char *src, char *dest, char str[], int str_size) {
365 char *s = strstr(src, dest);
369 char *e = strstr(s, " ");
374 int len = e-s-strlen(dest);
376 if (len >= str_size) {
377 D("buffer size(%d) should be bigger than %d\n", str_size, len+1);
381 s_strncpy(str, s + strlen(dest), len);
385 int get_emulator_forward_port() {
386 SdbdCommandlineArgs *sdbd_args = &sdbd_commandline_args; /* alias */
388 if (sdbd_args->emulator.host == NULL) {
392 return sdbd_args->emulator.port;
395 int get_emulator_name(char str[], int str_size) {
396 SdbdCommandlineArgs *sdbd_args = &sdbd_commandline_args; /* alias */
398 if (sdbd_args->emulator.host == NULL) {
402 s_strncpy(str, sdbd_args->emulator.host, str_size);
406 int get_device_name(char str[], int str_size) {
408 int r = system_info_get_value_string(SYSTEM_INFO_KEY_MODEL, &value);
409 if (r != SYSTEM_INFO_ERROR_NONE) {
410 D("fail to get system model:%d\n", errno);
413 s_strncpy(str, value, str_size);
414 D("returns model_name:%s\n", value);
421 int fd = unix_open(USB_SERIAL_PATH, O_RDONLY);
423 D("fail to read:%s (%d)\n", USB_SERIAL_PATH, errno);
427 if(read_line(fd, str, str_size)) {
428 D("device serial name: %s\n", str);
437 void parse_banner(char *banner, atransport *t)
439 char *type, *product, *end;
441 D("parse_banner: %s\n", banner);
443 product = strchr(type, ':');
450 /* remove trailing ':' */
451 end = strchr(product, ':');
454 /* save product name in device structure */
455 if (t->product == NULL) {
456 t->product = strdup(product);
457 } else if (strcmp(product, t->product) != 0) {
459 t->product = strdup(product);
462 if(!strcmp(type, "bootloader")){
463 D("setting connection_state to CS_BOOTLOADER\n");
464 t->connection_state = CS_BOOTLOADER;
469 if(!strcmp(type, "device")) {
470 D("setting connection_state to CS_DEVICE\n");
471 t->connection_state = CS_DEVICE;
476 if(!strcmp(type, "recovery")) {
477 D("setting connection_state to CS_RECOVERY\n");
478 t->connection_state = CS_RECOVERY;
483 if(!strcmp(type, "sideload")) {
484 D("setting connection_state to CS_SIDELOAD\n");
485 t->connection_state = CS_SIDELOAD;
490 t->connection_state = CS_HOST;
493 void handle_packet(apacket *p, atransport *t)
497 D("handle_packet() %c%c%c%c\n", ((char*) (&(p->msg.command)))[0],
498 ((char*) (&(p->msg.command)))[1],
499 ((char*) (&(p->msg.command)))[2],
500 ((char*) (&(p->msg.command)))[3]);
502 print_packet("recv", p);
504 switch(p->msg.command){
508 if(HOST) send_connect(t);
510 t->connection_state = CS_OFFLINE;
516 case A_CNXN: /* CONNECT(version, maxdata, "system-id-string") */
517 /* XXX verify version, etc */
518 if(t->connection_state != CS_OFFLINE) {
519 t->connection_state = CS_OFFLINE;
522 parse_banner((char*) p->data, t);
524 if(!HOST) send_connect(t);
527 case A_OPEN: /* OPEN(local-id, 0, "destination") */
528 if(t->connection_state != CS_OFFLINE) {
529 char *name = (char*) p->data;
530 name[p->msg.data_length > 0 ? p->msg.data_length - 1 : 0] = 0;
531 s = create_local_service_socket(name);
533 send_close(0, p->msg.arg0, t);
535 s->peer = create_remote_socket(p->msg.arg0, t);
537 send_ready(s->id, s->peer->id, t);
543 case A_OKAY: /* READY(local-id, remote-id, "") */
544 if(t->connection_state != CS_OFFLINE) {
545 if((s = find_local_socket(p->msg.arg1))) {
547 s->peer = create_remote_socket(p->msg.arg0, t);
555 case A_CLSE: /* CLOSE(local-id, remote-id, "") */
556 if(t->connection_state != CS_OFFLINE) {
557 if((s = find_local_socket(p->msg.arg1))) {
564 if(t->connection_state != CS_OFFLINE) {
565 if((s = find_local_socket(p->msg.arg1))) {
566 unsigned rid = p->msg.arg0;
567 p->len = p->msg.data_length;
569 if(s->enqueue(s, p) == 0) {
570 D("Enqueue the socket\n");
571 send_ready(s->id, rid, t);
579 printf("handle_packet: what is %08x?!\n", p->msg.command);
585 alistener listener_list = {
586 .next = &listener_list,
587 .prev = &listener_list,
590 static void ss_listener_event_func(int _fd, unsigned ev, void *_l)
595 struct sockaddr addr;
600 fd = sdb_socket_accept(_fd, &addr, &alen);
603 sdb_socket_setbufsize(fd, CHUNK_SIZE);
605 s = create_local_socket(fd);
607 connect_to_smartsocket(s);
615 static void listener_event_func(int _fd, unsigned ev, void *_l)
621 struct sockaddr addr;
626 fd = sdb_socket_accept(_fd, &addr, &alen);
629 s = create_local_socket(fd);
631 s->transport = l->transport;
632 connect_to_remote(s, l->connect_to);
640 static void free_listener(alistener* l)
643 l->next->prev = l->prev;
644 l->prev->next = l->next;
645 l->next = l->prev = l;
648 // closes the corresponding fd
649 fdevent_remove(&l->fde);
652 free((char*)l->local_name);
655 free((char*)l->connect_to);
658 remove_transport_disconnect(l->transport, &l->disconnect);
663 static void listener_disconnect(void* _l, atransport* t)
670 int local_name_to_fd(const char *name)
674 if(!strncmp("tcp:", name, 4)){
676 port = atoi(name + 4);
677 ret = socket_loopback_server(port, SOCK_STREAM);
680 #ifndef HAVE_WIN32_IPC /* no Unix-domain sockets on Win32 */
681 // It's non-sensical to support the "reserved" space on the sdb host side
682 if(!strncmp(name, "local:", 6)) {
683 return socket_local_server(name + 6,
684 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
685 } else if(!strncmp(name, "localabstract:", 14)) {
686 return socket_local_server(name + 14,
687 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
688 } else if(!strncmp(name, "localfilesystem:", 16)) {
689 return socket_local_server(name + 16,
690 ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
694 printf("unknown local portname '%s'\n", name);
698 static int remove_listener(const char *local_name, const char *connect_to, atransport* transport)
702 for (l = listener_list.next; l != &listener_list; l = l->next) {
703 if (!strcmp(local_name, l->local_name) &&
704 !strcmp(connect_to, l->connect_to) &&
705 l->transport && l->transport == transport) {
707 listener_disconnect(l, transport);
715 static int install_listener(const char *local_name, const char *connect_to, atransport* transport)
719 //printf("install_listener('%s','%s')\n", local_name, connect_to);
721 for(l = listener_list.next; l != &listener_list; l = l->next){
722 if(strcmp(local_name, l->local_name) == 0) {
725 /* can't repurpose a smartsocket */
726 if(l->connect_to[0] == '*') {
730 cto = strdup(connect_to);
735 //printf("rebinding '%s' to '%s'\n", local_name, connect_to);
736 free((void*) l->connect_to);
738 if (l->transport != transport) {
739 remove_transport_disconnect(l->transport, &l->disconnect);
740 l->transport = transport;
741 add_transport_disconnect(l->transport, &l->disconnect);
747 if((l = calloc(1, sizeof(alistener))) == 0) goto nomem;
748 if((l->local_name = strdup(local_name)) == 0) goto nomem;
749 if((l->connect_to = strdup(connect_to)) == 0) goto nomem;
752 l->fd = local_name_to_fd(local_name);
754 free((void*) l->local_name);
755 free((void*) l->connect_to);
757 printf("cannot bind '%s'\n", local_name);
761 if (close_on_exec(l->fd) < 0) {
762 D("fail to close fd exec:%d\n",l->fd);
764 if(!strcmp(l->connect_to, "*smartsocket*")) {
765 fdevent_install(&l->fde, l->fd, ss_listener_event_func, l);
767 fdevent_install(&l->fde, l->fd, listener_event_func, l);
769 fdevent_set(&l->fde, FDE_READ);
771 l->next = &listener_list;
772 l->prev = listener_list.prev;
775 l->transport = transport;
778 l->disconnect.opaque = l;
779 l->disconnect.func = listener_disconnect;
780 add_transport_disconnect(transport, &l->disconnect);
785 fatal("cannot allocate listener");
789 #ifdef HAVE_WIN32_PROC
790 static BOOL WINAPI ctrlc_handler(DWORD type)
792 exit(STATUS_CONTROL_C_EXIT);
797 static void sdb_cleanup(void)
799 clear_sdbd_commandline_args(&sdbd_commandline_args);
801 // if(required_pid > 0) {
802 // kill(required_pid, SIGKILL);
806 void start_logging(void)
808 #ifdef HAVE_WIN32_PROC
809 char temp[ MAX_PATH ];
813 GetTempPath( sizeof(temp) - 8, temp );
814 strcat( temp, "sdb.log" );
816 /* Win32 specific redirections */
817 fnul = fopen( "NUL", "rt" );
821 flog = fopen( temp, "at" );
825 setvbuf( flog, NULL, _IONBF, 0 );
829 fprintf(stderr,"--- sdb starting (pid %d) ---\n", getpid());
833 fd = unix_open("/dev/null", O_RDONLY);
835 // hopefully not gonna happen
841 fd = unix_open("/tmp/sdb.log", O_WRONLY | O_CREAT | O_APPEND, 0640);
843 fd = unix_open("/dev/null", O_WRONLY);
845 // hopefully not gonna happen
852 fprintf(stderr,"--- sdb starting (pid %d) ---\n", getpid());
857 void start_device_log(void)
863 // char value[PROPERTY_VALUE_MAX];
864 const char* p = getenv("SDB_TRACE");
865 // read the trace mask from persistent property persist.sdb.trace_mask
866 // give up if the property is not set or cannot be parsed
867 #if 0 /* tizen specific */
868 property_get("persist.sdb.trace_mask", value, "");
869 if (sscanf(value, "%x", &sdb_trace_mask) != 1)
878 localtime_r(&t, &now);
879 strftime(path, sizeof(path),
880 "/tmp/sdbd-%Y-%m-%d-%H-%M-%S.txt",
882 fd = unix_open(path, O_WRONLY | O_CREAT | O_TRUNC, 0640);
887 // redirect stdout and stderr to the log file
890 fprintf(stderr,"--- sdbd starting (pid %d) ---\n", getpid());
893 fd = unix_open("/dev/null", O_RDONLY);
895 // hopefully not gonna happen
902 int daemonize(void) {
904 // set file creation mask to 0
916 FILE *f = fopen(SDB_PIDPATH, "w");
919 fprintf(f, "%d\n", getpid());
927 D("sdbd: unable to change working directory to /\n");
934 int launch_server(int server_port)
936 #ifdef HAVE_WIN32_PROC
937 /* we need to start the server in the background */
938 /* we create a PIPE that will be used to wait for the server's "OK" */
939 /* message since the pipe handles must be inheritable, we use a */
940 /* security attribute */
941 HANDLE pipe_read, pipe_write;
942 SECURITY_ATTRIBUTES sa;
944 PROCESS_INFORMATION pinfo;
945 char program_path[ MAX_PATH ];
948 sa.nLength = sizeof(sa);
949 sa.lpSecurityDescriptor = NULL;
950 sa.bInheritHandle = TRUE;
952 /* create pipe, and ensure its read handle isn't inheritable */
953 ret = CreatePipe( &pipe_read, &pipe_write, &sa, 0 );
955 fprintf(stderr, "CreatePipe() failure, error %ld\n", GetLastError() );
959 SetHandleInformation( pipe_read, HANDLE_FLAG_INHERIT, 0 );
961 ZeroMemory( &startup, sizeof(startup) );
962 startup.cb = sizeof(startup);
963 startup.hStdInput = GetStdHandle( STD_INPUT_HANDLE );
964 startup.hStdOutput = pipe_write;
965 startup.hStdError = GetStdHandle( STD_ERROR_HANDLE );
966 startup.dwFlags = STARTF_USESTDHANDLES;
968 ZeroMemory( &pinfo, sizeof(pinfo) );
970 /* get path of current program */
971 GetModuleFileName( NULL, program_path, sizeof(program_path) );
974 program_path, /* program path */
975 "sdb fork-server server",
976 /* the fork-server argument will set the
977 debug = 2 in the child */
978 NULL, /* process handle is not inheritable */
979 NULL, /* thread handle is not inheritable */
980 TRUE, /* yes, inherit some handles */
981 DETACHED_PROCESS, /* the new process doesn't have a console */
982 NULL, /* use parent's environment block */
983 NULL, /* use parent's starting directory */
984 &startup, /* startup info, i.e. std handles */
987 CloseHandle( pipe_write );
990 fprintf(stderr, "CreateProcess failure, error %ld\n", GetLastError() );
991 CloseHandle( pipe_read );
995 CloseHandle( pinfo.hProcess );
996 CloseHandle( pinfo.hThread );
998 /* wait for the "OK\n" message */
1003 ret = ReadFile( pipe_read, temp, 3, &count, NULL );
1004 CloseHandle( pipe_read );
1006 fprintf(stderr, "could not read ok from SDB Server, error = %ld\n", GetLastError() );
1009 if (count != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
1010 fprintf(stderr, "SDB server didn't ACK\n" );
1014 #elif defined(HAVE_FORKEXEC)
1015 char path[PATH_MAX];
1018 // set up a pipe so the child can tell us when it is ready.
1019 // fd[0] will be parent's end, and fd[1] will get mapped to stderr in the child.
1021 fprintf(stderr, "pipe failed in launch_server, errno: %d\n", errno);
1024 get_my_path(path, PATH_MAX);
1026 if(pid < 0) return -1;
1029 // child side of the fork
1031 // redirect stderr to the pipe
1032 // we use stderr instead of stdout due to stdout's buffering behavior.
1034 dup2(fd[1], STDERR_FILENO);
1038 int result = execl(path, "sdb", "fork-server", "server", NULL);
1039 // this should not return
1040 fprintf(stderr, "OOPS! execl returned %d, errno: %d\n", result, errno);
1042 // parent side of the fork
1046 temp[0] = 'A'; temp[1] = 'B'; temp[2] = 'C';
1047 // wait for the "OK\n" message
1049 int ret = sdb_read(fd[0], temp, 3);
1050 int saved_errno = errno;
1053 fprintf(stderr, "could not read ok from SDB Server, errno = %d\n", saved_errno);
1056 if (ret != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
1057 fprintf(stderr, "SDB server didn't ACK\n" );
1064 #error "cannot implement background server start on this platform"
1070 /* Constructs a local name of form tcp:port.
1071 * target_str points to the target string, it's content will be overwritten.
1072 * target_size is the capacity of the target string.
1073 * server_port is the port number to use for the local name.
1075 void build_local_name(char* target_str, size_t target_size, int server_port)
1077 snprintf(target_str, target_size, "tcp:%d", server_port);
1081 static void init_drop_privileges() {
1082 #ifdef _DROP_PRIVILEGE
1089 int should_drop_privileges() {
1090 if (rootshell_mode == 1) { // if root, then don't drop
1096 int set_developer_privileges() {
1097 gid_t groups[] = { SID_DEVELOPER, SID_APP_LOGGING, SID_SYS_LOGGING, SID_INPUT };
1098 if (setgroups(sizeof(groups) / sizeof(groups[0]), groups) != 0) {
1099 D("set groups failed (errno: %d, %s)\n", errno, strerror(errno));
1102 // then switch user and group to developer
1103 if (setgid(SID_DEVELOPER) != 0) {
1104 D("set group id failed (errno: %d, %s)\n", errno, strerror(errno));
1108 if (setuid(SID_DEVELOPER) != 0) {
1109 D("set user id failed (errno: %d, %s)\n", errno, strerror(errno));
1113 if (chdir("/home/developer") < 0) {
1114 D("sdbd: unable to change working directory to /home/developer\n");
1116 if (chdir("/") < 0) {
1117 D("sdbd: unable to change working directory to /\n");
1120 // TODO: use pam later
1121 putenv("HOME=/home/developer");
1125 #define ONDEMAND_ROOT_PATH "/home/developer"
1127 static void execute_required_process() {
1129 FILE *pre_proc_file = popen("pidof debug_launchpad_preloading_preinitializing_daemon", "r");
1131 if(pre_proc_file == NULL) {
1132 D("fail to get the pidof debug_launchpad_preloading_preinitializing_daemon");
1137 while(!feof(pre_proc_file)) {
1139 result += fscanf(pre_proc_file, "%d", &pid);
1144 D("Kill %d debug launchpad daemon", result);
1146 pclose(pre_proc_file);
1148 system("/usr/bin/debug_launchpad_preloading_preinitializing_daemon &");
1151 static void init_sdk_requirements() {
1154 // set env variable for temporary
1155 // TODO: should use pam instead later!!
1156 if (!getenv("TERM")) {
1157 putenv("TERM=linux");
1160 if (!getenv("HOME")) {
1161 putenv("HOME=/root");
1164 if (stat(ONDEMAND_ROOT_PATH, &st) == -1) {
1167 if (st.st_uid != SID_DEVELOPER || st.st_gid != SID_DEVELOPER) {
1169 snprintf(cmd, sizeof(cmd), "chown developer:developer %s -R", ONDEMAND_ROOT_PATH);
1170 if (system(cmd) < 0) {
1171 D("failed to change ownership to developer to %s\n", ONDEMAND_ROOT_PATH);
1175 execute_required_process();
1177 #endif /* !SDB_HOST */
1179 int sdb_main(int is_daemon, int server_port)
1182 init_drop_privileges();
1183 init_sdk_requirements();
1187 atexit(sdb_cleanup);
1188 #ifdef HAVE_WIN32_PROC
1189 SetConsoleCtrlHandler( ctrlc_handler, TRUE );
1190 #elif defined(HAVE_FORKEXEC)
1191 // No SIGCHLD. Let the service subproc handle its children.
1192 signal(SIGPIPE, SIG_IGN);
1195 init_transport_registration();
1202 local_init(DEFAULT_SDB_LOCAL_TRANSPORT_PORT);
1204 char local_name[30];
1205 build_local_name(local_name, sizeof(local_name), server_port);
1206 if(install_listener(local_name, "*smartsocket*", NULL)) {
1210 /* don't listen on a port (default 5037) if running in secure mode */
1211 /* don't run as root if we are running in secure mode */
1213 if (should_drop_privileges()) {
1215 struct __user_cap_header_struct header;
1216 struct __user_cap_data_struct cap;
1218 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
1221 /* add extra groups:
1222 ** SID_TTY to access /dev/ptmx
1224 gid_t groups[] = { SID_TTY, SID_APP_LOGGING, SID_SYS_LOGGING };
1225 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
1228 /* then switch user and group to "developer" */
1229 if (setgid(SID_DEVELOPER) != 0) {
1230 fprintf(stderr, "set group id failed errno: %d\n", errno);
1233 if (setuid(SID_DEVELOPER) != 0) {
1234 fprintf(stderr, "set user id failed errno: %d\n", errno);
1238 /* set CAP_SYS_BOOT capability, so "sdb reboot" will succeed */
1239 header.version = _LINUX_CAPABILITY_VERSION;
1241 cap.effective = cap.permitted = (1 << CAP_SYS_BOOT);
1242 cap.inheritable = 0;
1243 capset(&header, &cap);
1245 D("Local port disabled\n");
1247 char local_name[30];
1248 build_local_name(local_name, sizeof(local_name), server_port);
1249 if(install_listener(local_name, "*smartsocket*", NULL)) {
1254 if (!is_emulator()) {
1258 //local_init(DEFAULT_SDB_LOCAL_TRANSPORT_PORT);
1260 // listen on default port
1261 local_init(DEFAULT_SDB_LOCAL_TRANSPORT_PORT);
1264 #if 0 /* tizen specific */
1265 D("sdb_main(): pre init_jdwp()\n");
1267 D("sdb_main(): post init_jdwp()\n");
1273 // inform our parent that we are up and running.
1274 #ifdef HAVE_WIN32_PROC
1276 WriteFile( GetStdHandle( STD_OUTPUT_HANDLE ), "OK\n", 3, &count, NULL );
1277 #elif defined(HAVE_FORKEXEC)
1278 fprintf(stderr, "OK\n");
1283 D("Event loop starting\n");
1293 void connect_device(char* host, char* buffer, int buffer_size)
1296 char* portstr = strchr(host, ':');
1300 strncpy(hostbuf, host, sizeof(hostbuf) - 1);
1302 if (portstr - host >= sizeof(hostbuf)) {
1303 snprintf(buffer, buffer_size, "bad host name %s", host);
1306 // zero terminate the host at the point we found the colon
1307 hostbuf[portstr - host] = 0;
1308 if (sscanf(portstr + 1, "%d", &port) == 0) {
1309 snprintf(buffer, buffer_size, "bad port number %s", portstr);
1313 port = DEFAULT_SDB_LOCAL_TRANSPORT_PORT;
1316 snprintf(serial, sizeof(serial), "%s:%d", hostbuf, port);
1317 if (find_transport(serial)) {
1318 snprintf(buffer, buffer_size, "already connected to %s", serial);
1322 fd = socket_network_client(hostbuf, port, SOCK_STREAM);
1324 snprintf(buffer, buffer_size, "unable to connect to %s", host);
1328 D("client: connected on remote on fd %d\n", fd);
1330 disable_tcp_nagle(fd);
1331 register_socket_transport(fd, serial, port, 0, NULL);
1332 snprintf(buffer, buffer_size, "connected to %s", serial);
1335 void connect_emulator(char* port_spec, char* buffer, int buffer_size)
1337 char* port_separator = strchr(port_spec, ',');
1338 if (!port_separator) {
1339 snprintf(buffer, buffer_size,
1340 "unable to parse '%s' as <console port>,<sdb port>",
1345 // Zero-terminate console port and make port_separator point to 2nd port.
1346 *port_separator++ = 0;
1347 int console_port = strtol(port_spec, NULL, 0);
1348 int sdb_port = strtol(port_separator, NULL, 0);
1349 if (!(console_port > 0 && sdb_port > 0)) {
1350 *(port_separator - 1) = ',';
1351 snprintf(buffer, buffer_size,
1352 "Invalid port numbers: Expected positive numbers, got '%s'",
1357 /* Check if the emulator is already known.
1358 * Note: There's a small but harmless race condition here: An emulator not
1359 * present just yet could be registered by another invocation right
1360 * after doing this check here. However, local_connect protects
1361 * against double-registration too. From here, a better error message
1362 * can be produced. In the case of the race condition, the very specific
1363 * error message won't be shown, but the data doesn't get corrupted. */
1364 atransport* known_emulator = find_emulator_transport_by_sdb_port(sdb_port);
1365 if (known_emulator != NULL) {
1366 snprintf(buffer, buffer_size,
1367 "Emulator on port %d already registered.", sdb_port);
1371 /* Check if more emulators can be registered. Similar unproblematic
1372 * race condition as above. */
1373 int candidate_slot = get_available_local_transport_index();
1374 if (candidate_slot < 0) {
1375 snprintf(buffer, buffer_size, "Cannot accept more emulators.");
1379 /* Preconditions met, try to connect to the emulator. */
1380 if (!local_connect_arbitrary_ports(console_port, sdb_port, NULL)) {
1381 snprintf(buffer, buffer_size,
1382 "Connected to emulator on ports %d,%d", console_port, sdb_port);
1384 snprintf(buffer, buffer_size,
1385 "Could not connect to emulator on ports %d,%d",
1386 console_port, sdb_port);
1391 int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s)
1393 atransport *transport = NULL;
1396 if(!strcmp(service, "kill")) {
1397 fprintf(stderr,"sdb server killed by remote request\n");
1399 sdb_write(reply_fd, "OKAY", 4);
1405 // "transport:" is used for switching transport with a specified serial number
1406 // "transport-usb:" is used for switching transport to the only USB transport
1407 // "transport-local:" is used for switching transport to the only local transport
1408 // "transport-any:" is used for switching transport to the only transport
1409 if (!strncmp(service, "transport", strlen("transport"))) {
1410 char* error_string = "unknown failure";
1411 transport_type type = kTransportAny;
1413 if (!strncmp(service, "transport-usb", strlen("transport-usb"))) {
1414 type = kTransportUsb;
1415 } else if (!strncmp(service, "transport-local", strlen("transport-local"))) {
1416 type = kTransportLocal;
1417 } else if (!strncmp(service, "transport-any", strlen("transport-any"))) {
1418 type = kTransportAny;
1419 } else if (!strncmp(service, "transport:", strlen("transport:"))) {
1420 service += strlen("transport:");
1424 transport = acquire_one_transport(CS_ANY, type, serial, &error_string);
1427 s->transport = transport;
1428 sdb_write(reply_fd, "OKAY", 4);
1430 sendfailmsg(reply_fd, error_string);
1435 // return a list of all connected devices
1436 if (!strcmp(service, "devices")) {
1438 memset(buf, 0, sizeof(buf));
1439 memset(buffer, 0, sizeof(buffer));
1440 D("Getting device list \n");
1441 list_transports(buffer, sizeof(buffer));
1442 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer),buffer);
1443 D("Wrote device list \n");
1444 writex(reply_fd, buf, strlen(buf));
1448 // add a new TCP transport, device or emulator
1449 if (!strncmp(service, "connect:", 8)) {
1451 char* host = service + 8;
1452 if (!strncmp(host, "emu:", 4)) {
1453 connect_emulator(host + 4, buffer, sizeof(buffer));
1455 connect_device(host, buffer, sizeof(buffer));
1457 // Send response for emulator and device
1458 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
1459 writex(reply_fd, buf, strlen(buf));
1463 // remove TCP transport
1464 if (!strncmp(service, "disconnect:", 11)) {
1466 memset(buffer, 0, sizeof(buffer));
1467 char* serial = service + 11;
1468 if (serial[0] == 0) {
1469 // disconnect from all TCP devices
1470 unregister_all_tcp_transports();
1473 // assume port 26101 if no port is specified
1474 if (!strchr(serial, ':')) {
1475 snprintf(hostbuf, sizeof(hostbuf) - 1, "%s:26101", serial);
1478 atransport *t = find_transport(serial);
1481 unregister_transport(t);
1483 snprintf(buffer, sizeof(buffer), "No such device %s", serial);
1487 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
1488 writex(reply_fd, buf, strlen(buf));
1492 // returns our value for SDB_SERVER_VERSION
1493 if (!strcmp(service, "version")) {
1495 snprintf(version, sizeof version, "%04x", SDB_SERVER_VERSION);
1496 snprintf(buf, sizeof buf, "OKAY%04x%s", (unsigned)strlen(version), version);
1497 writex(reply_fd, buf, strlen(buf));
1501 if(!strncmp(service,"get-serialno",strlen("get-serialno"))) {
1502 char *out = "unknown";
1503 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1504 if (transport && transport->serial) {
1505 out = transport->serial;
1507 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(out),out);
1508 writex(reply_fd, buf, strlen(buf));
1511 // indicates a new emulator instance has started
1512 if (!strncmp(service,"emulator:",9)) { /* tizen specific */
1513 char *tmp = strtok(service+9, DEVICEMAP_SEPARATOR);
1517 port = atoi(service+9);
1520 tmp = strtok(NULL, DEVICEMAP_SEPARATOR);
1522 local_connect(port, tmp);
1525 local_connect(port, NULL);
1530 if(!strncmp(service,"forward:",8) || !strncmp(service,"killforward:",12)) {
1531 char *local, *remote, *err;
1533 atransport *transport;
1535 int createForward = strncmp(service,"kill",4);
1537 local = service + (createForward ? 8 : 12);
1538 remote = strchr(local,';');
1540 sendfailmsg(reply_fd, "malformed forward spec");
1545 if((local[0] == 0) || (remote[0] == 0) || (remote[0] == '*')){
1546 sendfailmsg(reply_fd, "malformed forward spec");
1550 transport = acquire_one_transport(CS_ANY, ttype, serial, &err);
1552 sendfailmsg(reply_fd, err);
1556 if (createForward) {
1557 r = install_listener(local, remote, transport);
1559 r = remove_listener(local, remote, transport);
1562 /* 1st OKAY is connect, 2nd OKAY is status */
1563 writex(reply_fd, "OKAYOKAY", 8);
1567 if (createForward) {
1568 sendfailmsg(reply_fd, (r == -1) ? "cannot rebind smartsocket" : "cannot bind socket");
1570 sendfailmsg(reply_fd, "cannot remove listener");
1575 if(!strncmp(service,"get-state",strlen("get-state"))) {
1576 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1577 char *state = connection_state_name(transport);
1578 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(state),state);
1579 writex(reply_fd, buf, strlen(buf));
1586 int recovery_mode = 0;
1589 int main(int argc, char **argv)
1591 sdb_trace_init(); /* tizen specific */
1595 return sdb_commandline(argc - 1, argv + 1);
1597 /* If sdbd runs inside the emulator this will enable sdb tracing via
1598 * sdb-debug qemud service in the emulator. */
1599 #if 0 /* tizen specific */
1600 sdb_qemu_trace_init();
1601 if((argc > 1) && (!strcmp(argv[1],"recovery"))) {
1602 sdb_device_banner = "recovery";
1607 if (daemonize() < 0)
1608 fatal("daemonize() failed: %.200s", strerror(errno));
1612 D("Handling main()\n");
1614 //sdbd will never die on emulator!
1615 signal(SIGTERM, handle_sig_term); /* tizen specific */
1616 apply_sdbd_commandline_defaults(&sdbd_commandline_args);
1617 parse_sdbd_commandline(&sdbd_commandline_args, argc, argv);
1618 return sdb_main(0, DEFAULT_SDB_PORT);