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
31 #include <tzplatform_config.h>
40 #include "commandline_sdbd.h"
45 #include "sdbd_plugin.h"
48 #include <linux/prctl.h>
49 #define SDB_PIDPATH "/tmp/.sdbd.pid"
51 #include <system_info.h>
55 #define PROC_CMDLINE_PATH "/proc/cmdline"
56 #define USB_SERIAL_PATH "/sys/class/usb_mode/usb0/iSerial"
58 #include <sys/ioctl.h>
60 #include <netinet/in.h>
61 #include <arpa/inet.h>
62 #define GUEST_IP_INTERFACE "eth0"
64 SDB_MUTEX_DEFINE(zone_check_lock);
66 SDB_MUTEX_DEFINE( D_lock );
72 char* g_sdk_home_dir = NULL;
73 char* g_sdk_home_dir_env = NULL;
75 int rootshell_mode; // 0: sdk user, 1: root
76 int booting_done; // 0: platform booting is in progess 1: platform booting is done
83 struct group_info g_default_groups[] = {
84 {"priv_externalstorage", -1},
85 {"priv_externalstorage_appdata", -1},
86 {"priv_mediastorage", -1},
90 #define SDB_DEFAULT_GROUPS_CNT ((sizeof(g_default_groups)/sizeof(g_default_groups[0]))-1)
92 int is_init_sdk_userinfo = 0;
93 int is_pwlocked = 0; // 0 if unlocked, 1 otherwise
96 SdbdCommandlineArgs sdbd_commandline_args;
99 static int is_support_usbproto();
100 static int is_support_sockproto();
102 void (*usb_init)() = NULL;
103 void (*usb_cleanup)() = NULL;
104 int (*usb_write)(usb_handle *h, const void *data, int len) = NULL;
105 int (*usb_read)(usb_handle *h, void *data, size_t len) = NULL;
106 int (*usb_close)(usb_handle *h) = NULL;
107 void (*usb_kick)(usb_handle *h) = NULL;
109 int g_is_emulator = -1;
110 int is_emulator(void) {
114 if (g_is_emulator >= 0) {
115 return g_is_emulator;
117 D("failed to initialize check emulator\n");
120 return sdbd_commandline_args.emulator.host != NULL;
124 int is_container_enabled(void) {
127 ret = system_info_get_platform_bool("tizen.org/feature/container", &value);
128 if (ret != SYSTEM_INFO_ERROR_NONE) {
129 D("failed to get container information: %d\n", errno);
132 D("tizen container: %d\n", value);
140 void handle_sig_term(int sig) {
142 if (access(SDB_PIDPATH, F_OK) == 0)
143 sdb_unlink(SDB_PIDPATH);
147 static const char *sdb_device_banner = "device";
149 void fatal(const char *fmt, ...)
153 fprintf(stderr, "error: ");
154 vfprintf(stderr, fmt, ap);
155 fprintf(stderr, "\n");
160 void fatal_errno(const char *fmt, ...)
164 fprintf(stderr, "errno: %d: ", errno);
165 vfprintf(stderr, fmt, ap);
166 fprintf(stderr, "\n");
171 static int is_enable_sdbd_log()
173 return (!strncmp(g_capabilities.log_enable, PLUGIN_RET_ENABLED, strlen(PLUGIN_RET_ENABLED)));
178 /* read a comma/space/colum/semi-column separated list of tags
179 * from the SDB_TRACE environment variable and build the trace
180 * mask from it. note that '1' and 'all' are special cases to
183 void sdb_trace_init(void)
185 const char* p = getenv("SDB_TRACE");
188 static const struct {
194 { "sdb", TRACE_SDB },
195 { "sockets", TRACE_SOCKETS },
196 { "packets", TRACE_PACKETS },
197 { "rwx", TRACE_RWX },
198 { "usb", TRACE_USB },
199 { "sync", TRACE_SYNC },
200 { "sysdeps", TRACE_SYSDEPS },
201 { "transport", TRACE_TRANSPORT },
202 { "jdwp", TRACE_JDWP },
203 { "services", TRACE_SERVICES },
204 { "properties", TRACE_PROPERTIES },
205 { "sdktools", TRACE_SDKTOOLS },
210 if (is_enable_sdbd_log())
216 /* use a comma/column/semi-colum/space separated list */
220 q = strpbrk(p, " ,:;");
226 for (tagn = 0; tags[tagn].tag != NULL; tagn++)
228 int taglen = strlen(tags[tagn].tag);
230 if (len == taglen && !memcmp(tags[tagn].tag, p, len) )
232 int flag = tags[tagn].flag;
237 sdb_trace_mask |= (1 << flag);
249 * Implements SDB tracing inside the emulator.
255 * Redefine open and write for qemu_pipe.h that contains inlined references
256 * to those routines. We will redifine them back after qemu_pipe.h inclusion.
261 #define open sdb_open
262 #define write sdb_write
263 #include "qemu_pipe.h"
266 #define open ___xxx_open
267 #define write ___xxx_write
269 /* A handle to sdb-debug qemud service in the emulator. */
270 int sdb_debug_qemu = -1;
272 /* Initializes connection with the sdb-debug qemud service in the emulator. */
273 #if 0 /* doen't support in Tizen */
274 static int sdb_qemu_trace_init(void)
278 if (sdb_debug_qemu >= 0) {
282 /* sdb debugging QEMUD service connection request. */
283 snprintf(con_name, sizeof(con_name), "qemud:sdb-debug");
284 sdb_debug_qemu = qemu_pipe_open(con_name);
285 return (sdb_debug_qemu >= 0) ? 0 : -1;
288 void sdb_qemu_trace(const char* fmt, ...)
294 if (sdb_debug_qemu >= 0) {
295 vsnprintf(msg, sizeof(msg), fmt, args);
296 sdb_write(sdb_debug_qemu, msg, strlen(msg));
300 #endif /* !SDB_HOST */
302 apacket *get_apacket(void)
304 apacket *p = malloc(sizeof(apacket));
305 if(p == 0) fatal("failed to allocate an apacket");
306 memset(p, 0, sizeof(apacket) - MAX_PAYLOAD);
310 void put_apacket(apacket *p)
318 void handle_online(void)
323 void handle_offline(atransport *t)
326 //Close the associated usb
327 run_transport_disconnects(t);
332 void print_packet(const char *label, apacket *p)
338 switch(p->msg.command){
339 case A_SYNC: tag = "SYNC"; break;
340 case A_CNXN: tag = "CNXN" ; break;
341 case A_OPEN: tag = "OPEN"; break;
342 case A_OKAY: tag = "OKAY"; break;
343 case A_CLSE: tag = "CLSE"; break;
344 case A_WRTE: tag = "WRTE"; break;
345 default: tag = "????"; break;
348 fprintf(stderr, "%s: %s %08x %08x %04x \"",
349 label, tag, p->msg.arg0, p->msg.arg1, p->msg.data_length);
350 count = p->msg.data_length;
352 if(count > DUMPMAX) {
359 if((*x >= ' ') && (*x < 127)) {
366 fprintf(stderr, tag);
370 static void send_ready(unsigned local, unsigned remote, atransport *t)
372 D("Calling send_ready \n");
373 apacket *p = get_apacket();
374 p->msg.command = A_OKAY;
376 p->msg.arg1 = remote;
380 static void send_close(unsigned local, unsigned remote, atransport *t)
382 D("Calling send_close \n");
383 apacket *p = get_apacket();
384 p->msg.command = A_CLSE;
386 p->msg.arg1 = remote;
390 static void send_connect(atransport *t)
392 D("Calling send_connect \n");
393 apacket *cp = get_apacket();
394 cp->msg.command = A_CNXN;
395 cp->msg.arg0 = A_VERSION;
396 cp->msg.arg1 = MAX_PAYLOAD;
398 char device_name[256]={0,};
401 if (request_lock_state_to_plugin(LOCKTYPE_PASSWORD) == 1) {
403 t->connection_state = CS_PWLOCK;
407 r = get_emulator_name(device_name, sizeof device_name);
409 r = get_device_name(device_name, sizeof device_name);
412 snprintf((char*) cp->data, sizeof cp->data, "%s::%s::%d", sdb_device_banner, DEFAULT_DEVICENAME, status);
414 snprintf((char*) cp->data, sizeof cp->data, "%s::%s::%d", sdb_device_banner, device_name, status);
417 D("CNXN data:%s\n", (char*)cp->data);
418 cp->msg.data_length = strlen((char*) cp->data) + 1;
422 /* XXX why sleep here? */
423 // allow the device some time to respond to the connect message
428 void send_device_status()
430 D("broadcast device status\n");
431 apacket* cp = get_apacket();
432 cp->msg.command = A_STAT;
433 cp->msg.arg0 = is_pwlocked;
436 broadcast_transport(cp);
438 //all broadcasted packets are memory copied
439 //so, we should call put_apacket
443 static char *connection_state_name(atransport *t)
449 switch(t->connection_state) {
461 static int get_str_cmdline(char *src, char *dest, char str[], int str_size) {
462 char *s = strstr(src, dest);
466 char *e = strstr(s, " ");
471 int len = e-s-strlen(dest);
473 if (len >= str_size) {
474 D("buffer size(%d) should be bigger than %d\n", str_size, len+1);
478 strncpy(str, s + strlen(dest), len);
483 int get_emulator_forward_port() {
484 SdbdCommandlineArgs *sdbd_args = &sdbd_commandline_args; /* alias */
486 if (sdbd_args->emulator.host == NULL) {
490 return sdbd_args->emulator.port;
493 int get_emulator_name(char str[], int str_size) {
494 SdbdCommandlineArgs *sdbd_args = &sdbd_commandline_args; /* alias */
496 if (sdbd_args->emulator.host == NULL) {
500 s_strncpy(str, sdbd_args->emulator.host, str_size);
504 int get_device_name(char str[], int str_size) {
506 int r = system_info_get_platform_string("http://tizen.org/system/model_name", &value);
507 if (r != SYSTEM_INFO_ERROR_NONE) {
508 D("fail to get system model:%d\n", errno);
511 s_strncpy(str, value, str_size);
512 D("returns model_name:%s\n", value);
519 int fd = unix_open(USB_SERIAL_PATH, O_RDONLY);
521 D("fail to read:%s (%d)\n", USB_SERIAL_PATH, errno);
525 if(read_line(fd, str, str_size)) {
526 D("device serial name: %s\n", str);
535 static int get_cmdline_value(char *split, char str[], int str_size) {
537 int fd = unix_open(PROC_CMDLINE_PATH, O_RDONLY);
540 D("fail to read /proc/cmdline\n");
543 if(read_line(fd, cmdline, sizeof(cmdline))) {
544 D("qemu cmd: %s\n", cmdline);
545 if (get_str_cmdline(cmdline, split, str, str_size) < 1) {
546 D("could not get the (%s) value from cmdline\n", split);
555 int get_emulator_hostip(char str[], int str_size) {
556 return get_cmdline_value("host_ip=", str, str_size);
559 int get_emulator_guestip(char str[], int str_size) {
562 struct sockaddr_in *sin;
564 s = socket(AF_INET, SOCK_DGRAM, 0);
570 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s", GUEST_IP_INTERFACE);
571 if(ioctl(s, SIOCGIFHWADDR, &ifr) < 0) {
572 D("ioctl hwaddr error\n");
577 if(ioctl(s, SIOCGIFADDR, &ifr) < 0) {
578 D("ioctl addr error\n");
582 sin = (struct sockaddr_in *)&ifr.ifr_addr;
583 snprintf(str, str_size, "%s", inet_ntoa(sin->sin_addr));
589 void parse_banner(char *banner, atransport *t)
591 char *type, *product, *end;
593 D("parse_banner: %s\n", banner);
595 product = strchr(type, ':');
602 /* remove trailing ':' */
603 end = strchr(product, ':');
606 /* save product name in device structure */
607 if (t->product == NULL) {
608 t->product = strdup(product);
609 } else if (strcmp(product, t->product) != 0) {
611 t->product = strdup(product);
614 if(!strcmp(type, "bootloader")){
615 D("setting connection_state to CS_BOOTLOADER\n");
616 t->connection_state = CS_BOOTLOADER;
621 if(!strcmp(type, "device")) {
622 D("setting connection_state to CS_DEVICE\n");
623 t->connection_state = CS_DEVICE;
628 if(!strcmp(type, "recovery")) {
629 D("setting connection_state to CS_RECOVERY\n");
630 t->connection_state = CS_RECOVERY;
635 if(!strcmp(type, "sideload")) {
636 D("setting connection_state to CS_SIDELOAD\n");
637 t->connection_state = CS_SIDELOAD;
642 t->connection_state = CS_HOST;
645 void handle_packet(apacket *p, atransport *t)
648 int result = access((const char *) p, F_OK);
649 if ((result == -1) && (errno == EFAULT)) {
650 fatal("Invalid apacket = [0x%p]", p);
655 D("handle_packet() %c%c%c%c\n", ((char*) (&(p->msg.command)))[0],
656 ((char*) (&(p->msg.command)))[1],
657 ((char*) (&(p->msg.command)))[2],
658 ((char*) (&(p->msg.command)))[3]);
660 print_packet("recv", p);
662 switch(p->msg.command){
666 if(HOST) send_connect(t);
668 t->connection_state = CS_OFFLINE;
674 case A_CNXN: /* CONNECT(version, maxdata, "system-id-string") */
675 /* XXX verify version, etc */
676 if(t->connection_state != CS_OFFLINE) {
677 t->connection_state = CS_OFFLINE;
680 parse_banner((char*) p->data, t);
682 if(!HOST) send_connect(t);
685 case A_OPEN: /* OPEN(local-id, 0, "destination") */
686 if (request_lock_state_to_plugin(LOCKTYPE_PASSWORD) == 1 && t->connection_state == CS_PWLOCK) {
687 // in case of already locked before get A_CNXN
688 D("open failed due to password locked before get A_CNXN:%d\n", t->connection_state);
689 send_close(0, p->msg.arg0, t);
691 if(t->connection_state != CS_OFFLINE) {
692 char *name = (char*) p->data;
693 name[p->msg.data_length > 0 ? p->msg.data_length - 1 : 0] = 0;
694 s = create_local_service_socket(name);
696 send_close(0, p->msg.arg0, t);
698 s->peer = create_remote_socket(p->msg.arg0, t);
700 send_ready(s->id, s->peer->id, t);
707 case A_OKAY: /* READY(local-id, remote-id, "") */
708 if(t->connection_state != CS_OFFLINE) {
709 if((s = find_local_socket(p->msg.arg1))) {
711 s->peer = create_remote_socket(p->msg.arg0, t);
719 case A_CLSE: /* CLOSE(local-id, remote-id, "") */
720 if(t->connection_state != CS_OFFLINE) {
721 if((s = find_local_socket(p->msg.arg1))) {
728 if(t->connection_state != CS_OFFLINE) {
729 if((s = find_local_socket(p->msg.arg1))) {
730 unsigned rid = p->msg.arg0;
731 p->len = p->msg.data_length;
733 if(s->enqueue(s, p) == 0) {
734 D("Enqueue the socket\n");
735 send_ready(s->id, rid, t);
743 printf("handle_packet: what is %08x?!\n", p->msg.command);
749 alistener listener_list = {
750 .next = &listener_list,
751 .prev = &listener_list,
754 static void ss_listener_event_func(int _fd, unsigned ev, void *_l)
759 struct sockaddr addr;
764 fd = sdb_socket_accept(_fd, &addr, &alen);
767 sdb_socket_setbufsize(fd, CHUNK_SIZE);
769 s = create_local_socket(fd);
771 connect_to_smartsocket(s);
779 static void listener_event_func(int _fd, unsigned ev, void *_l)
785 struct sockaddr addr;
790 fd = sdb_socket_accept(_fd, &addr, &alen);
793 s = create_local_socket(fd);
795 s->transport = l->transport;
796 connect_to_remote(s, l->connect_to);
804 static void free_listener(alistener* l)
807 l->next->prev = l->prev;
808 l->prev->next = l->next;
809 l->next = l->prev = l;
812 // closes the corresponding fd
813 fdevent_remove(&l->fde);
816 free((char*)l->local_name);
819 free((char*)l->connect_to);
822 remove_transport_disconnect(l->transport, &l->disconnect);
827 static void listener_disconnect(void* _l, atransport* t)
834 int local_name_to_fd(const char *name)
838 if(!strncmp("tcp:", name, 4)){
840 port = atoi(name + 4);
841 ret = socket_loopback_server(port, SOCK_STREAM);
844 #ifndef HAVE_WIN32_IPC /* no Unix-domain sockets on Win32 */
845 // It's non-sensical to support the "reserved" space on the sdb host side
846 if(!strncmp(name, "local:", 6)) {
847 return socket_local_server(name + 6,
848 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
849 } else if(!strncmp(name, "localabstract:", 14)) {
850 return socket_local_server(name + 14,
851 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
852 } else if(!strncmp(name, "localfilesystem:", 16)) {
853 return socket_local_server(name + 16,
854 ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
858 printf("unknown local portname '%s'\n", name);
862 static int remove_listener(const char *local_name, const char *connect_to, atransport* transport)
866 for (l = listener_list.next; l != &listener_list; l = l->next) {
867 if (!strcmp(local_name, l->local_name) &&
868 !strcmp(connect_to, l->connect_to) &&
869 l->transport && l->transport == transport) {
871 listener_disconnect(l, transport);
879 static int install_listener(const char *local_name, const char *connect_to, atransport* transport)
883 //printf("install_listener('%s','%s')\n", local_name, connect_to);
885 for(l = listener_list.next; l != &listener_list; l = l->next){
886 if(strcmp(local_name, l->local_name) == 0) {
889 /* can't repurpose a smartsocket */
890 if(l->connect_to[0] == '*') {
894 cto = strdup(connect_to);
899 //printf("rebinding '%s' to '%s'\n", local_name, connect_to);
900 free((void*) l->connect_to);
902 if (l->transport != transport) {
903 remove_transport_disconnect(l->transport, &l->disconnect);
904 l->transport = transport;
905 add_transport_disconnect(l->transport, &l->disconnect);
911 if((l = calloc(1, sizeof(alistener))) == 0) goto nomem;
912 if((l->local_name = strdup(local_name)) == 0) goto nomem;
913 if((l->connect_to = strdup(connect_to)) == 0) goto nomem;
916 l->fd = local_name_to_fd(local_name);
918 free((void*) l->local_name);
919 free((void*) l->connect_to);
921 printf("cannot bind '%s'\n", local_name);
925 if (close_on_exec(l->fd) < 0) {
926 D("fail to close fd exec:%d\n",l->fd);
928 if(!strcmp(l->connect_to, "*smartsocket*")) {
929 fdevent_install(&l->fde, l->fd, ss_listener_event_func, l);
931 fdevent_install(&l->fde, l->fd, listener_event_func, l);
933 fdevent_set(&l->fde, FDE_READ);
935 l->next = &listener_list;
936 l->prev = listener_list.prev;
939 l->transport = transport;
942 l->disconnect.opaque = l;
943 l->disconnect.func = listener_disconnect;
944 add_transport_disconnect(transport, &l->disconnect);
949 fatal("cannot allocate listener");
953 #ifdef HAVE_WIN32_PROC
954 static BOOL WINAPI ctrlc_handler(DWORD type)
956 exit(STATUS_CONTROL_C_EXIT);
961 static void sdb_cleanup(void)
963 clear_sdbd_commandline_args(&sdbd_commandline_args);
965 if (is_support_usbproto()) {
968 // if(required_pid > 0) {
969 // kill(required_pid, SIGKILL);
972 unload_sdbd_plugin();
975 void start_logging(void)
977 #ifdef HAVE_WIN32_PROC
978 char temp[ MAX_PATH ];
982 GetTempPath( sizeof(temp) - 8, temp );
983 strcat( temp, "sdb.log" );
985 /* Win32 specific redirections */
986 fnul = fopen( "NUL", "rt" );
990 flog = fopen( temp, "at" );
994 setvbuf( flog, NULL, _IONBF, 0 );
998 fprintf(stderr,"--- sdb starting (pid %d) ---\n", getpid());
1002 fd = unix_open("/dev/null", O_RDONLY);
1004 // hopefully not gonna happen
1010 fd = unix_open("/tmp/sdb.log", O_WRONLY | O_CREAT | O_APPEND, 0640);
1012 fd = unix_open("/dev/null", O_WRONLY);
1014 // hopefully not gonna happen
1021 fprintf(stderr,"--- sdb starting (pid %d) ---\n", getpid());
1027 void start_device_log(void)
1030 char path[PATH_MAX] = {0, };
1031 char path_folder[PATH_MAX] = {0, };
1032 char path_file[PATH_MAX] = {0, };
1035 // char value[PROPERTY_VALUE_MAX];
1036 const char* p_trace = getenv("SDB_TRACE");
1037 const char* p_path = getenv("SDBD_LOG_PATH");
1038 // read the trace mask from persistent property persist.sdb.trace_mask
1039 // give up if the property is not set or cannot be parsed
1040 #if 0 /* tizen specific */
1041 property_get("persist.sdb.trace_mask", value, "");
1042 if (sscanf(value, "%x", &sdb_trace_mask) != 1)
1046 if ((p_trace == NULL ) && !is_enable_sdbd_log()) {
1051 snprintf(path_folder, sizeof(path_folder), "%s", p_path);
1052 else if (g_capabilities.log_path[0] != '\0')
1053 snprintf(path_folder, sizeof(path_folder), "%s", g_capabilities.log_path);
1059 localtime_r(&t, &now);
1061 strftime(path_file, sizeof(path_file),
1062 "sdbd-%Y-%m-%d-%H-%M-%S.txt",
1065 snprintf(path, sizeof(path), "%s/%s", path_folder, path_file);
1067 fd = unix_open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1072 // redirect stdout and stderr to the log file
1075 fprintf(stderr,"--- sdbd starting (pid %d) ---\n", getpid());
1078 fd = unix_open("/dev/null", O_RDONLY);
1080 // hopefully not gonna happen
1087 int daemonize(void) {
1089 // set file creation mask to 0
1101 FILE *f = fopen(SDB_PIDPATH, "w");
1104 fprintf(f, "%d\n", getpid());
1112 D("sdbd: unable to change working directory to /\n");
1119 int launch_server(int server_port)
1121 #ifdef HAVE_WIN32_PROC
1122 /* we need to start the server in the background */
1123 /* we create a PIPE that will be used to wait for the server's "OK" */
1124 /* message since the pipe handles must be inheritable, we use a */
1125 /* security attribute */
1126 HANDLE pipe_read, pipe_write;
1127 SECURITY_ATTRIBUTES sa;
1128 STARTUPINFO startup;
1129 PROCESS_INFORMATION pinfo;
1130 char program_path[ MAX_PATH ];
1133 sa.nLength = sizeof(sa);
1134 sa.lpSecurityDescriptor = NULL;
1135 sa.bInheritHandle = TRUE;
1137 /* create pipe, and ensure its read handle isn't inheritable */
1138 ret = CreatePipe( &pipe_read, &pipe_write, &sa, 0 );
1140 fprintf(stderr, "CreatePipe() failure, error %ld\n", GetLastError() );
1144 SetHandleInformation( pipe_read, HANDLE_FLAG_INHERIT, 0 );
1146 ZeroMemory( &startup, sizeof(startup) );
1147 startup.cb = sizeof(startup);
1148 startup.hStdInput = GetStdHandle( STD_INPUT_HANDLE );
1149 startup.hStdOutput = pipe_write;
1150 startup.hStdError = GetStdHandle( STD_ERROR_HANDLE );
1151 startup.dwFlags = STARTF_USESTDHANDLES;
1153 ZeroMemory( &pinfo, sizeof(pinfo) );
1155 /* get path of current program */
1156 GetModuleFileName( NULL, program_path, sizeof(program_path) );
1158 ret = CreateProcess(
1159 program_path, /* program path */
1160 "sdb fork-server server",
1161 /* the fork-server argument will set the
1162 debug = 2 in the child */
1163 NULL, /* process handle is not inheritable */
1164 NULL, /* thread handle is not inheritable */
1165 TRUE, /* yes, inherit some handles */
1166 DETACHED_PROCESS, /* the new process doesn't have a console */
1167 NULL, /* use parent's environment block */
1168 NULL, /* use parent's starting directory */
1169 &startup, /* startup info, i.e. std handles */
1172 CloseHandle( pipe_write );
1175 fprintf(stderr, "CreateProcess failure, error %ld\n", GetLastError() );
1176 CloseHandle( pipe_read );
1180 CloseHandle( pinfo.hProcess );
1181 CloseHandle( pinfo.hThread );
1183 /* wait for the "OK\n" message */
1188 ret = ReadFile( pipe_read, temp, 3, &count, NULL );
1189 CloseHandle( pipe_read );
1191 fprintf(stderr, "could not read ok from SDB Server, error = %ld\n", GetLastError() );
1194 if (count != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
1195 fprintf(stderr, "SDB server didn't ACK\n" );
1199 #elif defined(HAVE_FORKEXEC)
1200 char path[PATH_MAX];
1203 // set up a pipe so the child can tell us when it is ready.
1204 // fd[0] will be parent's end, and fd[1] will get mapped to stderr in the child.
1206 fprintf(stderr, "pipe failed in launch_server, errno: %d\n", errno);
1209 get_my_path(path, PATH_MAX);
1211 if(pid < 0) return -1;
1214 // child side of the fork
1216 // redirect stderr to the pipe
1217 // we use stderr instead of stdout due to stdout's buffering behavior.
1219 dup2(fd[1], STDERR_FILENO);
1223 int result = execl(path, "sdb", "fork-server", "server", NULL);
1224 // this should not return
1225 fprintf(stderr, "OOPS! execl returned %d, errno: %d\n", result, errno);
1227 // parent side of the fork
1231 temp[0] = 'A'; temp[1] = 'B'; temp[2] = 'C';
1232 // wait for the "OK\n" message
1234 int ret = sdb_read(fd[0], temp, 3);
1235 int saved_errno = errno;
1238 fprintf(stderr, "could not read ok from SDB Server, errno = %d\n", saved_errno);
1241 if (ret != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
1242 fprintf(stderr, "SDB server didn't ACK\n" );
1249 #error "cannot implement background server start on this platform"
1255 /* Constructs a local name of form tcp:port.
1256 * target_str points to the target string, it's content will be overwritten.
1257 * target_size is the capacity of the target string.
1258 * server_port is the port number to use for the local name.
1260 void build_local_name(char* target_str, size_t target_size, int server_port)
1262 snprintf(target_str, target_size, "tcp:%d", server_port);
1266 static void init_drop_privileges() {
1267 #ifdef _DROP_PRIVILEGE
1274 int should_drop_privileges() {
1275 if (rootshell_mode == 1) { // if root, then don't drop
1281 #include <dbus/dbus.h>
1282 #include <dbus/dbus-glib.h>
1283 #include <dbus/dbus-glib-lowlevel.h>
1285 #define BOOTING_DONE_SIGNAL "BootingDone"
1286 #define DEVICED_CORE_INTERFACE "org.tizen.system.deviced.core"
1287 #define SDBD_BOOT_INFO_FILE "/tmp/sdbd_boot_info"
1289 static DBusHandlerResult __sdbd_dbus_signal_filter(DBusConnection *conn,
1290 DBusMessage *message, void *user_data) {
1291 D("got dbus message\n");
1292 const char *interface;
1295 dbus_error_init(&error);
1297 interface = dbus_message_get_interface(message);
1298 if (interface == NULL) {
1299 D("reject by security issue - no interface\n");
1300 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1303 if (dbus_message_is_signal(message, DEVICED_CORE_INTERFACE,
1304 BOOTING_DONE_SIGNAL)) {
1306 if (access(SDBD_BOOT_INFO_FILE, F_OK) == 0) {
1307 D("booting is done before\n");
1309 FILE *f = fopen(SDBD_BOOT_INFO_FILE, "w");
1311 fprintf(f, "%d", 1);
1315 D("booting is done\n");
1318 D("handled dbus message\n");
1319 return DBUS_HANDLER_RESULT_HANDLED;
1322 static void *bootdone_cb(void *x) {
1323 int MAX_LOCAL_BUFSZ = 128;
1325 DBusConnection *bus;
1326 char rule[MAX_LOCAL_BUFSZ];
1327 GMainLoop *mainloop;
1329 /* g_type_init() is deprecated for glib version 2.35.0 or greater, */
1330 #if !GLIB_CHECK_VERSION(2,35,0)
1334 dbus_error_init(&error);
1335 bus = dbus_bus_get(DBUS_BUS_SYSTEM, &error);
1337 D("Failed to connect to the D-BUS daemon: %s", error.message);
1338 dbus_error_free(&error);
1341 dbus_connection_setup_with_g_main(bus, NULL);
1343 snprintf(rule, MAX_LOCAL_BUFSZ, "type='signal',interface='%s'",
1344 DEVICED_CORE_INTERFACE);
1345 /* listening to messages */
1346 dbus_bus_add_match(bus, rule, &error);
1347 if (dbus_error_is_set(&error)) {
1348 D("Fail to rule set: %s", error.message);
1349 dbus_error_free(&error);
1353 if (dbus_connection_add_filter(bus, __sdbd_dbus_signal_filter, NULL, NULL)
1357 D("booting signal initialized\n");
1358 mainloop = g_main_loop_new(NULL, FALSE);
1359 g_main_loop_run(mainloop);
1361 D("dbus loop exited");
1366 void register_bootdone_cb() {
1367 D("registerd bootdone callback\n");
1370 if (sdb_thread_create(&t, bootdone_cb, NULL)) {
1371 D("cannot create service thread\n");
1376 static int sdbd_set_groups() {
1377 gid_t *group_ids = NULL;
1380 int group_match = 0;
1381 int added_group_cnt = 0;
1383 getgrouplist(SDK_USER_NAME, g_sdk_group_id, NULL, &ngroups);
1384 D("group list : ngroups = %d\n", ngroups);
1385 group_ids = malloc((ngroups + SDB_DEFAULT_GROUPS_CNT) * sizeof(gid_t));
1386 if (group_ids == NULL) {
1387 D("failed to allocate group_ids(%d)\n", (ngroups + SDB_DEFAULT_GROUPS_CNT) * sizeof(gid_t));
1390 if (getgrouplist(SDK_USER_NAME, g_sdk_group_id, group_ids, &ngroups) == -1) {
1391 D("failed to getgrouplist(), ngroups = %d\n", ngroups);
1396 for (i = 0; g_default_groups[i].name != NULL; i++) {
1397 for (j = 0; j < ngroups; j++) {
1398 if (group_ids[j] == g_default_groups[i].gid) {
1403 if (group_match == 0 && g_default_groups[i].gid != -1) {
1404 group_ids[ngroups + added_group_cnt] = g_default_groups[i].gid;
1410 if (setgroups(ngroups+added_group_cnt, group_ids) != 0) {
1411 D("failed to setgroups().\n");
1420 static int sdbd_get_user_pwd(const char* user_name, struct passwd* pwd, char* buf, size_t bufsize) {
1421 struct passwd *result = NULL;
1424 ret = getpwnam_r(user_name, pwd, buf, bufsize, &result);
1425 if (result == NULL) {
1427 D("Not found passwd : username(%s)\n", user_name);
1430 D("failed to getpwnam_r\n");
1438 static int sdbd_get_group(const char* group_name, struct group* grp, char* buf, size_t bufsize) {
1439 struct group *result = NULL;
1442 ret = getgrnam_r(group_name, grp, buf, bufsize, &result);
1443 if (result == NULL) {
1445 D("Not found group : groupname(%s)\n", group_name);
1448 D("failed to getgrnam_r\n");
1456 int set_sdk_user_privileges() {
1457 if (!is_init_sdk_userinfo) {
1458 D("failed to init sdk user information.\n");
1462 if (sdbd_set_groups() < 0) {
1463 D("set groups failed (errno: %d)\n", errno);
1467 if (setgid(g_sdk_group_id) != 0) {
1468 D("set group id failed (errno: %d)\n", errno);
1472 if (setuid(g_sdk_user_id) != 0) {
1473 D("set user id failed (errno: %d)\n", errno);
1477 if (chdir(g_sdk_home_dir) < 0) {
1478 D("unable to change working directory to %s\n", g_sdk_home_dir);
1481 // TODO: use pam later
1482 if (g_sdk_home_dir_env) {
1483 putenv(g_sdk_home_dir_env);
1489 #define SDB_PW_GR_DEFAULT_SIZE (16*1024)
1490 static long get_passwd_bufsize() {
1493 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
1495 bufsize = SDB_PW_GR_DEFAULT_SIZE;
1501 static long get_group_bufsize() {
1504 bufsize = sysconf(_SC_GETGR_R_SIZE_MAX);
1506 bufsize = SDB_PW_GR_DEFAULT_SIZE;
1512 static int init_sdb_default_groups() {
1518 bufsize = get_group_bufsize();
1519 buf = malloc(bufsize);
1521 D("failed to allocate gruop buf(%ld)\n", bufsize);
1525 for (i = 0; g_default_groups[i].name != NULL; i++) {
1526 memset(buf, 0, bufsize);
1527 if (sdbd_get_group(g_default_groups[i].name, &grp, buf, bufsize) == 0) {
1528 g_default_groups[i].gid = grp.gr_gid;
1530 D("failed get group info.(errno: %d)\n", errno);
1538 static void set_static_userinfo() {
1539 g_sdk_user_id = STATIC_SDK_USER_ID;
1540 g_sdk_group_id = STATIC_SDK_GROUP_ID;
1541 g_sdk_home_dir = STATIC_SDK_HOME_DIR;
1544 static int init_sdk_userinfo() {
1549 if (is_init_sdk_userinfo) {
1553 if (init_sdb_default_groups() < 0) {
1554 D("failed to initialize default groups.\n");
1557 bufsize = get_passwd_bufsize();
1558 buf = malloc(bufsize);
1560 D("failed to allocate passwd buf(%ld)\n", bufsize);
1561 set_static_userinfo();
1563 if (sdbd_get_user_pwd(SDK_USER_NAME, &pwd, buf, bufsize) < 0) {
1564 D("get user passwd info.(errno: %d)\n", errno);
1565 set_static_userinfo();
1567 D("username=%s, uid=%d, gid=%d, dir=%s\n", pwd.pw_name, pwd.pw_uid, pwd.pw_gid, pwd.pw_dir);
1569 g_sdk_user_id = pwd.pw_uid;
1570 g_sdk_group_id = pwd.pw_gid;
1571 g_sdk_home_dir = strdup(pwd.pw_dir);
1576 int env_size = strlen("HOME=") + strlen(g_sdk_home_dir) + 1;
1577 g_sdk_home_dir_env = malloc(env_size);
1578 if(g_sdk_home_dir_env == NULL) {
1579 D("failed to allocate for home dir env string\n");
1581 snprintf(g_sdk_home_dir_env, env_size, "HOME=%s", g_sdk_home_dir);
1584 is_init_sdk_userinfo = 1;
1588 static void init_sdk_requirements() {
1591 // set env variable for temporary
1592 // TODO: should use pam instead later!!
1593 if (!getenv("TERM")) {
1594 putenv("TERM=linux");
1597 if (!getenv("HOME")) {
1598 putenv("HOME=/root");
1601 init_sdk_userinfo();
1603 if (g_sdk_home_dir != NULL && stat(g_sdk_home_dir, &st) == 0) {
1604 if (st.st_uid != g_sdk_user_id || st.st_gid != g_sdk_group_id) {
1606 snprintf(cmd, sizeof(cmd), "chown %s:%s %s -R", SDK_USER_NAME, SDK_USER_NAME, g_sdk_home_dir);
1607 if (system(cmd) < 0) {
1608 D("failed to change ownership to sdk user to %s\n", g_sdk_home_dir);
1613 if (is_emulator()) {
1614 register_bootdone_cb();
1617 #endif /* !SDB_HOST */
1619 static void init_capabilities(void) {
1623 memset(&g_capabilities, 0, sizeof(g_capabilities));
1625 // CPU Architecture of model
1626 ret = system_info_get_platform_string("http://tizen.org/feature/platform.core.cpu.arch", &value);
1627 if (ret != SYSTEM_INFO_ERROR_NONE) {
1628 snprintf(g_capabilities.cpu_arch, sizeof(g_capabilities.cpu_arch),
1630 D("fail to get the CPU architecture of model:%d\n", errno);
1632 snprintf(g_capabilities.cpu_arch, sizeof(g_capabilities.cpu_arch),
1634 if (value != NULL) {
1640 // Secure protocol support
1641 if(!request_capability_to_plugin(CAPABILITY_SECURE, g_capabilities.secure_protocol,
1642 sizeof(g_capabilities.secure_protocol))) {
1643 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_SECURE);
1644 snprintf(g_capabilities.secure_protocol, sizeof(g_capabilities.secure_protocol),
1649 // Interactive shell support
1650 if(!request_capability_to_plugin(CAPABILITY_INTER_SHELL, g_capabilities.intershell_support,
1651 sizeof(g_capabilities.intershell_support))) {
1652 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_INTER_SHELL);
1653 snprintf(g_capabilities.intershell_support, sizeof(g_capabilities.intershell_support),
1658 // File push/pull support
1659 if(!request_capability_to_plugin(CAPABILITY_FILESYNC, g_capabilities.filesync_support,
1660 sizeof(g_capabilities.filesync_support))) {
1661 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_FILESYNC);
1662 snprintf(g_capabilities.filesync_support, sizeof(g_capabilities.filesync_support),
1667 // USB protocol support
1668 if(!request_capability_to_plugin(CAPABILITY_USB_PROTOCOL, g_capabilities.usbproto_support,
1669 sizeof(g_capabilities.usbproto_support))) {
1670 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_USB_PROTOCOL);
1671 snprintf(g_capabilities.usbproto_support, sizeof(g_capabilities.usbproto_support),
1676 // Socket protocol support
1677 if(!request_capability_to_plugin(CAPABILITY_SOCK_PROTOCOL, g_capabilities.sockproto_support,
1678 sizeof(g_capabilities.sockproto_support))) {
1679 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_SOCK_PROTOCOL);
1680 snprintf(g_capabilities.sockproto_support, sizeof(g_capabilities.sockproto_support),
1685 // Root command support
1686 if(!request_capability_to_plugin(CAPABILITY_ROOT_ONOFF, g_capabilities.rootonoff_support,
1687 sizeof(g_capabilities.rootonoff_support))) {
1688 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_ROOT_ONOFF);
1689 snprintf(g_capabilities.rootonoff_support, sizeof(g_capabilities.rootonoff_support),
1695 ret = is_container_enabled();
1696 snprintf(g_capabilities.zone_support, sizeof(g_capabilities.zone_support),
1697 "%s", ret == 1 ? ENABLED : DISABLED);
1699 // Multi-User support
1700 // XXX: There is no clear way to determine whether multi-user support.
1701 // Since TZ_SYS_DEFAULT_USER is set to "owner" for multi-user support,
1702 // guess whether multiuser support through that information.
1703 const char* sys_default_user = tzplatform_getenv(TZ_SYS_DEFAULT_USER);
1704 if (sys_default_user != NULL && !strcmp(sys_default_user, "owner")) {
1705 snprintf(g_capabilities.multiuser_support, sizeof(g_capabilities.multiuser_support),
1708 snprintf(g_capabilities.multiuser_support, sizeof(g_capabilities.multiuser_support),
1712 // Window size synchronization support
1713 snprintf(g_capabilities.syncwinsz_support, sizeof(g_capabilities.syncwinsz_support),
1717 if (SDK_TOOL_PATH == NULL) {
1718 D("fail to get SDK tool path.\n");
1719 snprintf(g_capabilities.sdk_toolpath, sizeof(g_capabilities.sdk_toolpath),
1722 snprintf(g_capabilities.sdk_toolpath, sizeof(g_capabilities.sdk_toolpath),
1723 "%s", SDK_TOOL_PATH);
1727 ret = system_info_get_platform_string("http://tizen.org/feature/profile", &value);
1728 if (ret != SYSTEM_INFO_ERROR_NONE) {
1729 snprintf(g_capabilities.profile_name, sizeof(g_capabilities.profile_name),
1731 D("fail to get profile name:%d\n", errno);
1733 snprintf(g_capabilities.profile_name, sizeof(g_capabilities.profile_name),
1735 if (value != NULL) {
1742 ret = system_info_get_platform_string("http://tizen.org/system/manufacturer", &value);
1743 if (ret != SYSTEM_INFO_ERROR_NONE) {
1744 snprintf(g_capabilities.vendor_name, sizeof(g_capabilities.vendor_name),
1746 D("fail to get the Vendor name:%d\n", errno);
1748 snprintf(g_capabilities.vendor_name, sizeof(g_capabilities.vendor_name),
1750 if (value != NULL) {
1756 // Target name of the launch possible
1757 if(!request_plugin_cmd(SDBD_CMD_PLUGIN_CAP, SDBD_CAP_TYPE_CANLAUNCH,
1758 g_capabilities.can_launch,
1759 sizeof(g_capabilities.can_launch))) {
1760 D("failed to request. (%s:%s) \n", SDBD_CMD_PLUGIN_CAP, SDBD_CAP_TYPE_CANLAUNCH);
1761 snprintf(g_capabilities.can_launch, sizeof(g_capabilities.can_launch),
1767 ret = system_info_get_platform_string("http://tizen.org/feature/platform.version", &value);
1768 if (ret != SYSTEM_INFO_ERROR_NONE) {
1769 snprintf(g_capabilities.platform_version, sizeof(g_capabilities.platform_version),
1771 D("fail to get platform version:%d\n", errno);
1773 snprintf(g_capabilities.platform_version, sizeof(g_capabilities.platform_version),
1775 if (value != NULL) {
1782 if(!request_capability_to_plugin(CAPABILITY_PRODUCT_VER, g_capabilities.product_version,
1783 sizeof(g_capabilities.product_version))) {
1784 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_PRODUCT_VER);
1785 snprintf(g_capabilities.product_version, sizeof(g_capabilities.product_version),
1791 snprintf(g_capabilities.sdbd_version, sizeof(g_capabilities.sdbd_version),
1792 "%d.%d.%d", SDB_VERSION_MAJOR, SDB_VERSION_MINOR, SDB_VERSION_PATCH);
1795 // Sdbd plugin version
1796 if(!request_capability_to_plugin(CAPABILITY_PLUGIN_VER, g_capabilities.sdbd_plugin_version,
1797 sizeof(g_capabilities.sdbd_plugin_version))) {
1798 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_PLUGIN_VER);
1799 snprintf(g_capabilities.sdbd_plugin_version, sizeof(g_capabilities.sdbd_plugin_version),
1805 if(!request_capability_to_plugin(CAPABILITY_LOG_ENABLE, g_capabilities.log_enable,
1806 sizeof(g_capabilities.log_enable))) {
1807 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_LOG_ENABLE);
1808 snprintf(g_capabilities.log_enable, sizeof(g_capabilities.log_enable),
1813 if(!request_capability_to_plugin(CAPABILITY_LOG_PATH, g_capabilities.log_path,
1814 sizeof(g_capabilities.log_path))) {
1815 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_LOG_PATH);
1816 snprintf(g_capabilities.log_path, sizeof(g_capabilities.log_path),
1821 // Capability version
1822 snprintf(g_capabilities.sdbd_cap_version, sizeof(g_capabilities.sdbd_cap_version),
1823 "%d.%d", SDBD_CAP_VERSION_MAJOR, SDBD_CAP_VERSION_MINOR);
1826 static int is_support_usbproto()
1828 return (!strncmp(g_capabilities.usbproto_support, PLUGIN_RET_ENABLED, strlen(PLUGIN_RET_ENABLED)));
1831 static int is_support_sockproto()
1833 return (!strncmp(g_capabilities.sockproto_support, PLUGIN_RET_ENABLED, strlen(PLUGIN_RET_ENABLED)));
1836 #define EMULATOR_MODEL_NAME "Emulator"
1837 static void check_emulator_or_device()
1839 char model_name[256]={0,};
1842 // Get the model name from model_config.xml
1843 ret = get_device_name(model_name, sizeof model_name);
1845 if(!strncmp(model_name, EMULATOR_MODEL_NAME, sizeof(EMULATOR_MODEL_NAME))){
1847 D("This target type is Emulator\n");
1850 D("This target type is Device\n");
1854 D("failed to get the model name.\n");
1858 int sdb_main(int is_daemon, int server_port)
1861 check_emulator_or_device();
1865 init_capabilities();
1870 init_drop_privileges();
1871 init_sdk_requirements();
1872 if (!request_validity_to_plugin(PLUGIN_SYNC_CMD_VERIFY_LAUNCH, NULL)) {
1873 D("sdbd should be launched in develop mode.\n");
1880 atexit(sdb_cleanup);
1881 #ifdef HAVE_WIN32_PROC
1882 SetConsoleCtrlHandler( ctrlc_handler, TRUE );
1883 #elif defined(HAVE_FORKEXEC)
1884 // No SIGCHLD. Let the service subproc handle its children.
1885 signal(SIGPIPE, SIG_IGN);
1888 init_transport_registration();
1894 local_init(DEFAULT_SDB_LOCAL_TRANSPORT_PORT);
1896 char local_name[30];
1897 build_local_name(local_name, sizeof(local_name), server_port);
1898 if(install_listener(local_name, "*smartsocket*", NULL)) {
1902 /* don't listen on a port (default 5037) if running in secure mode */
1903 /* don't run as root if we are running in secure mode */
1905 if (should_drop_privileges()) {
1907 struct __user_cap_header_struct header;
1908 struct __user_cap_data_struct cap;
1910 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
1913 /* add extra groups:
1914 ** SID_TTY to access /dev/ptmx
1916 gid_t groups[] = { SID_TTY, SID_APP_LOGGING, SID_SYS_LOGGING };
1917 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
1920 /* then switch user and group to "developer" */
1921 if (setgid(GID_DEVELOPER) != 0) {
1922 fprintf(stderr, "set group id failed errno: %d\n", errno);
1925 if (setuid(SID_DEVELOPER) != 0) {
1926 fprintf(stderr, "set user id failed errno: %d\n", errno);
1930 /* set CAP_SYS_BOOT capability, so "sdb reboot" will succeed */
1931 header.version = _LINUX_CAPABILITY_VERSION;
1933 cap.effective = cap.permitted = (1 << CAP_SYS_BOOT);
1934 cap.inheritable = 0;
1935 capset(&header, &cap);
1937 D("Local port disabled\n");
1939 char local_name[30];
1940 build_local_name(local_name, sizeof(local_name), server_port);
1941 if(install_listener(local_name, "*smartsocket*", NULL)) {
1946 /* choose the usb gadget backend */
1947 if (access(USB_NODE_FILE, F_OK) == 0) {
1948 /* legacy kernel-based sdb gadget */
1949 usb_init = &linux_usb_init;
1950 usb_cleanup = &linux_usb_cleanup;
1951 usb_write = &linux_usb_write;
1952 usb_read = &linux_usb_read;
1953 usb_close = &linux_usb_close;
1954 usb_kick = &linux_usb_kick;
1956 /* functionfs based gadget */
1957 usb_init = &ffs_usb_init;
1958 usb_cleanup = &ffs_usb_cleanup;
1959 usb_write = &ffs_usb_write;
1960 usb_read = &ffs_usb_read;
1961 usb_close = &ffs_usb_close;
1962 usb_kick = &ffs_usb_kick;
1965 if (is_support_usbproto()) {
1969 if (is_support_sockproto()) {
1970 /* by default don't listen on local transport but
1971 * listen if suitable command line argument has been provided */
1972 if (sdbd_commandline_args.sdbd_port >= 0) {
1973 local_init(sdbd_commandline_args.sdbd_port);
1975 local_init(DEFAULT_SDB_LOCAL_TRANSPORT_PORT);
1979 #if 0 /* tizen specific */
1980 D("sdb_main(): pre init_jdwp()\n");
1982 D("sdb_main(): post init_jdwp()\n");
1988 // inform our parent that we are up and running.
1989 #ifdef HAVE_WIN32_PROC
1991 WriteFile( GetStdHandle( STD_OUTPUT_HANDLE ), "OK\n", 3, &count, NULL );
1992 #elif defined(HAVE_FORKEXEC)
1993 fprintf(stderr, "OK\n");
1998 D("Event loop starting\n");
2002 if (is_support_usbproto()) {
2010 void connect_device(char* host, char* buffer, int buffer_size)
2013 char* portstr = strchr(host, ':');
2017 s_strncpy(hostbuf, host, sizeof(hostbuf) - 1);
2019 if (portstr - host >= sizeof(hostbuf)) {
2020 snprintf(buffer, buffer_size, "bad host name %s", host);
2023 // zero terminate the host at the point we found the colon
2024 hostbuf[portstr - host] = 0;
2025 if (sscanf(portstr + 1, "%d", &port) == 0) {
2026 snprintf(buffer, buffer_size, "bad port number %s", portstr);
2030 port = DEFAULT_SDB_LOCAL_TRANSPORT_PORT;
2033 snprintf(serial, sizeof(serial), "%s:%d", hostbuf, port);
2034 if (find_transport(serial)) {
2035 snprintf(buffer, buffer_size, "already connected to %s", serial);
2039 fd = socket_network_client(hostbuf, port, SOCK_STREAM);
2041 snprintf(buffer, buffer_size, "unable to connect to %s", host);
2045 D("client: connected on remote on fd %d\n", fd);
2047 disable_tcp_nagle(fd);
2048 register_socket_transport(fd, serial, port, 0, NULL);
2049 snprintf(buffer, buffer_size, "connected to %s", serial);
2052 void connect_emulator(char* port_spec, char* buffer, int buffer_size)
2054 char* port_separator = strchr(port_spec, ',');
2055 if (!port_separator) {
2056 snprintf(buffer, buffer_size,
2057 "unable to parse '%s' as <console port>,<sdb port>",
2062 // Zero-terminate console port and make port_separator point to 2nd port.
2063 *port_separator++ = 0;
2064 int console_port = strtol(port_spec, NULL, 0);
2065 int sdb_port = strtol(port_separator, NULL, 0);
2066 if (!(console_port > 0 && sdb_port > 0)) {
2067 *(port_separator - 1) = ',';
2068 snprintf(buffer, buffer_size,
2069 "Invalid port numbers: Expected positive numbers, got '%s'",
2074 /* Check if the emulator is already known.
2075 * Note: There's a small but harmless race condition here: An emulator not
2076 * present just yet could be registered by another invocation right
2077 * after doing this check here. However, local_connect protects
2078 * against double-registration too. From here, a better error message
2079 * can be produced. In the case of the race condition, the very specific
2080 * error message won't be shown, but the data doesn't get corrupted. */
2081 atransport* known_emulator = find_emulator_transport_by_sdb_port(sdb_port);
2082 if (known_emulator != NULL) {
2083 snprintf(buffer, buffer_size,
2084 "Emulator on port %d already registered.", sdb_port);
2088 /* Check if more emulators can be registered. Similar unproblematic
2089 * race condition as above. */
2090 int candidate_slot = get_available_local_transport_index();
2091 if (candidate_slot < 0) {
2092 snprintf(buffer, buffer_size, "Cannot accept more emulators.");
2096 /* Preconditions met, try to connect to the emulator. */
2097 if (!local_connect_arbitrary_ports(console_port, sdb_port, NULL)) {
2098 snprintf(buffer, buffer_size,
2099 "Connected to emulator on ports %d,%d", console_port, sdb_port);
2101 snprintf(buffer, buffer_size,
2102 "Could not connect to emulator on ports %d,%d",
2103 console_port, sdb_port);
2108 int copy_packet(apacket* dest, apacket* src) {
2111 D("dest packet is NULL\n");
2116 D("src packet is NULL\n");
2120 dest->next = src->next;
2121 dest->ptr = src->ptr;
2122 dest->len = src->len;
2124 int data_length = src->msg.data_length;
2125 if(data_length > MAX_PAYLOAD) {
2126 data_length = MAX_PAYLOAD;
2128 memcpy(&(dest->msg), &(src->msg), sizeof(amessage) + data_length);
2133 int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s)
2135 atransport *transport = NULL;
2138 if(!strcmp(service, "kill")) {
2139 fprintf(stderr,"sdb server killed by remote request\n");
2141 sdb_write(reply_fd, "OKAY", 4);
2142 if (is_support_usbproto()) {
2149 // "transport:" is used for switching transport with a specified serial number
2150 // "transport-usb:" is used for switching transport to the only USB transport
2151 // "transport-local:" is used for switching transport to the only local transport
2152 // "transport-any:" is used for switching transport to the only transport
2153 if (!strncmp(service, "transport", strlen("transport"))) {
2154 char* error_string = "unknown failure";
2155 transport_type type = kTransportAny;
2157 if (!strncmp(service, "transport-usb", strlen("transport-usb"))) {
2158 type = kTransportUsb;
2159 } else if (!strncmp(service, "transport-local", strlen("transport-local"))) {
2160 type = kTransportLocal;
2161 } else if (!strncmp(service, "transport-any", strlen("transport-any"))) {
2162 type = kTransportAny;
2163 } else if (!strncmp(service, "transport:", strlen("transport:"))) {
2164 service += strlen("transport:");
2168 transport = acquire_one_transport(CS_ANY, type, serial, &error_string);
2171 s->transport = transport;
2172 sdb_write(reply_fd, "OKAY", 4);
2174 sendfailmsg(reply_fd, error_string);
2179 // return a list of all connected devices
2180 if (!strcmp(service, "devices")) {
2182 memset(buf, 0, sizeof(buf));
2183 memset(buffer, 0, sizeof(buffer));
2184 D("Getting device list \n");
2185 list_transports(buffer, sizeof(buffer));
2186 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer),buffer);
2187 D("Wrote device list \n");
2188 writex(reply_fd, buf, strlen(buf));
2192 // add a new TCP transport, device or emulator
2193 if (!strncmp(service, "connect:", 8)) {
2195 char* host = service + 8;
2196 if (!strncmp(host, "emu:", 4)) {
2197 connect_emulator(host + 4, buffer, sizeof(buffer));
2199 connect_device(host, buffer, sizeof(buffer));
2201 // Send response for emulator and device
2202 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
2203 writex(reply_fd, buf, strlen(buf));
2207 // remove TCP transport
2208 if (!strncmp(service, "disconnect:", 11)) {
2210 memset(buffer, 0, sizeof(buffer));
2211 char* serial = service + 11;
2212 if (serial[0] == 0) {
2213 // disconnect from all TCP devices
2214 unregister_all_tcp_transports();
2217 // assume port 26101 if no port is specified
2218 if (!strchr(serial, ':')) {
2219 snprintf(hostbuf, sizeof(hostbuf) - 1, "%s:26101", serial);
2222 atransport *t = find_transport(serial);
2225 unregister_transport(t);
2227 snprintf(buffer, sizeof(buffer), "No such device %s", serial);
2231 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
2232 writex(reply_fd, buf, strlen(buf));
2236 // returns our value for SDB_SERVER_VERSION
2237 if (!strcmp(service, "version")) {
2239 snprintf(version, sizeof version, "%04x", SDB_SERVER_VERSION);
2240 snprintf(buf, sizeof buf, "OKAY%04x%s", (unsigned)strlen(version), version);
2241 writex(reply_fd, buf, strlen(buf));
2245 if(!strncmp(service,"get-serialno",strlen("get-serialno"))) {
2246 char *out = "unknown";
2247 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
2248 if (transport && transport->serial) {
2249 out = transport->serial;
2251 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(out),out);
2252 writex(reply_fd, buf, strlen(buf));
2255 // indicates a new emulator instance has started
2256 if (!strncmp(service,"emulator:",9)) { /* tizen specific */
2257 char *tmp = strtok(service+9, DEVICEMAP_SEPARATOR);
2261 port = atoi(service+9);
2264 tmp = strtok(NULL, DEVICEMAP_SEPARATOR);
2266 local_connect(port, tmp);
2269 local_connect(port, NULL);
2274 if(!strncmp(service,"forward:",8) || !strncmp(service,"killforward:",12)) {
2275 char *local, *remote, *err;
2277 atransport *transport;
2279 int createForward = strncmp(service,"kill",4);
2281 local = service + (createForward ? 8 : 12);
2282 remote = strchr(local,';');
2284 sendfailmsg(reply_fd, "malformed forward spec");
2289 if((local[0] == 0) || (remote[0] == 0) || (remote[0] == '*')){
2290 sendfailmsg(reply_fd, "malformed forward spec");
2294 transport = acquire_one_transport(CS_ANY, ttype, serial, &err);
2296 sendfailmsg(reply_fd, err);
2300 if (createForward) {
2301 r = install_listener(local, remote, transport);
2303 r = remove_listener(local, remote, transport);
2306 /* 1st OKAY is connect, 2nd OKAY is status */
2307 writex(reply_fd, "OKAYOKAY", 8);
2311 if (createForward) {
2312 sendfailmsg(reply_fd, (r == -1) ? "cannot rebind smartsocket" : "cannot bind socket");
2314 sendfailmsg(reply_fd, "cannot remove listener");
2319 if(!strncmp(service,"get-state",strlen("get-state"))) {
2320 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
2321 char *state = connection_state_name(transport);
2322 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(state),state);
2323 writex(reply_fd, buf, strlen(buf));
2330 int recovery_mode = 0;
2333 int main(int argc, char **argv)
2338 return sdb_commandline(argc - 1, argv + 1);
2340 /* If sdbd runs inside the emulator this will enable sdb tracing via
2341 * sdb-debug qemud service in the emulator. */
2342 #if 0 /* tizen specific */
2343 sdb_qemu_trace_init();
2344 if((argc > 1) && (!strcmp(argv[1],"recovery"))) {
2345 sdb_device_banner = "recovery";
2350 apply_sdbd_commandline_defaults(&sdbd_commandline_args);
2351 int parse_ret = parse_sdbd_commandline(&sdbd_commandline_args, argc, argv);
2353 // TODO: Add detailed error messages
2354 // TODO: Add individual messages for help and usage
2355 if(parse_ret != SDBD_COMMANDLINE_SUCCESS) {
2356 if (parse_ret == SDBD_COMMANDLINE_HELP
2357 || parse_ret == SDBD_COMMANDLINE_USAGE) {
2358 // User requested help or usage
2359 print_sdbd_usage_message(stdout);
2360 return EXIT_SUCCESS;
2363 // Print usage message because of invalid options
2364 print_sdbd_usage_message(stderr);
2365 return EXIT_FAILURE;
2369 if (daemonize() < 0)
2370 fatal("daemonize() failed: errno:%d", errno);
2373 D("Handling main()\n");
2375 //sdbd will never die on emulator!
2376 signal(SIGTERM, handle_sig_term); /* tizen specific */
2377 return sdb_main(0, DEFAULT_SDB_PORT);