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"
47 #ifdef SUPPORT_ENCRYPT
48 #include "plugin_encrypt.h"
52 #include <linux/prctl.h>
53 #define SDB_PIDPATH "/tmp/.sdbd.pid"
55 #include <system_info.h>
59 #define PROC_CMDLINE_PATH "/proc/cmdline"
60 #define USB_SERIAL_PATH "/sys/class/usb_mode/usb0/iSerial"
62 #include <sys/ioctl.h>
64 #include <netinet/in.h>
65 #include <arpa/inet.h>
66 #define GUEST_IP_INTERFACE "eth0"
68 SDB_MUTEX_DEFINE(zone_check_lock);
70 SDB_MUTEX_DEFINE( D_lock );
76 char* g_sdk_home_dir = NULL;
77 char* g_sdk_home_dir_env = NULL;
79 int rootshell_mode; // 0: sdk user, 1: root
80 int booting_done; // 0: platform booting is in progess 1: platform booting is done
87 struct group_info g_default_groups[] = {
88 {"priv_externalstorage", -1},
89 {"priv_externalstorage_appdata", -1},
90 {"priv_mediastorage", -1},
94 #define SDB_DEFAULT_GROUPS_CNT ((sizeof(g_default_groups)/sizeof(g_default_groups[0]))-1)
96 int is_init_sdk_userinfo = 0;
97 int is_pwlocked = 0; // 0 if unlocked, 1 otherwise
100 SdbdCommandlineArgs sdbd_commandline_args;
103 static int is_support_usbproto();
104 static int is_support_sockproto();
106 void (*usb_init)() = NULL;
107 void (*usb_cleanup)() = NULL;
108 int (*usb_write)(usb_handle *h, const void *data, int len) = NULL;
109 int (*usb_read)(usb_handle *h, void *data, size_t len) = NULL;
110 int (*usb_close)(usb_handle *h) = NULL;
111 void (*usb_kick)(usb_handle *h) = NULL;
113 int g_is_emulator = -1;
114 int is_emulator(void) {
118 if (g_is_emulator >= 0) {
119 return g_is_emulator;
121 D("failed to initialize check emulator\n");
124 return sdbd_commandline_args.emulator.host != NULL;
128 int is_container_enabled(void) {
131 ret = system_info_get_platform_bool("tizen.org/feature/container", &value);
132 if (ret != SYSTEM_INFO_ERROR_NONE) {
133 D("failed to get container information: %d\n", errno);
136 D("tizen container: %d\n", value);
144 void handle_sig_term(int sig) {
146 if (access(SDB_PIDPATH, F_OK) == 0)
147 sdb_unlink(SDB_PIDPATH);
151 static const char *sdb_device_banner = "device";
153 void fatal(const char *fmt, ...)
157 fprintf(stderr, "error: ");
158 vfprintf(stderr, fmt, ap);
159 fprintf(stderr, "\n");
164 void fatal_errno(const char *fmt, ...)
168 fprintf(stderr, "errno: %d: ", errno);
169 vfprintf(stderr, fmt, ap);
170 fprintf(stderr, "\n");
175 static int is_enable_sdbd_log()
177 return (!strncmp(g_capabilities.log_enable, PLUGIN_RET_ENABLED, strlen(PLUGIN_RET_ENABLED)));
182 /* read a comma/space/colum/semi-column separated list of tags
183 * from the SDB_TRACE environment variable and build the trace
184 * mask from it. note that '1' and 'all' are special cases to
187 void sdb_trace_init(void)
189 const char* p = getenv("SDB_TRACE");
192 static const struct {
198 { "sdb", TRACE_SDB },
199 { "sockets", TRACE_SOCKETS },
200 { "packets", TRACE_PACKETS },
201 { "rwx", TRACE_RWX },
202 { "usb", TRACE_USB },
203 { "sync", TRACE_SYNC },
204 { "sysdeps", TRACE_SYSDEPS },
205 { "transport", TRACE_TRANSPORT },
206 { "jdwp", TRACE_JDWP },
207 { "services", TRACE_SERVICES },
208 { "properties", TRACE_PROPERTIES },
209 { "sdktools", TRACE_SDKTOOLS },
210 { "appcmd", TRACE_APPCMD },
215 if (is_enable_sdbd_log())
221 /* use a comma/column/semi-colum/space separated list */
225 q = strpbrk(p, " ,:;");
231 for (tagn = 0; tags[tagn].tag != NULL; tagn++)
233 int taglen = strlen(tags[tagn].tag);
235 if (len == taglen && !memcmp(tags[tagn].tag, p, len) )
237 int flag = tags[tagn].flag;
242 sdb_trace_mask |= (1 << flag);
254 * Implements SDB tracing inside the emulator.
260 * Redefine open and write for qemu_pipe.h that contains inlined references
261 * to those routines. We will redifine them back after qemu_pipe.h inclusion.
266 #define open sdb_open
267 #define write sdb_write
268 #include "qemu_pipe.h"
271 #define open ___xxx_open
272 #define write ___xxx_write
274 /* A handle to sdb-debug qemud service in the emulator. */
275 int sdb_debug_qemu = -1;
277 /* Initializes connection with the sdb-debug qemud service in the emulator. */
278 #if 0 /* doen't support in Tizen */
279 static int sdb_qemu_trace_init(void)
283 if (sdb_debug_qemu >= 0) {
287 /* sdb debugging QEMUD service connection request. */
288 snprintf(con_name, sizeof(con_name), "qemud:sdb-debug");
289 sdb_debug_qemu = qemu_pipe_open(con_name);
290 return (sdb_debug_qemu >= 0) ? 0 : -1;
293 void sdb_qemu_trace(const char* fmt, ...)
299 if (sdb_debug_qemu >= 0) {
300 vsnprintf(msg, sizeof(msg), fmt, args);
301 sdb_write(sdb_debug_qemu, msg, strlen(msg));
305 #endif /* !SDB_HOST */
307 apacket *get_apacket(void)
309 apacket *p = malloc(sizeof(apacket));
310 if(p == 0) fatal("failed to allocate an apacket");
311 memset(p, 0, sizeof(apacket) - MAX_PAYLOAD);
315 void put_apacket(apacket *p)
323 void handle_online(void)
328 void handle_offline(atransport *t)
331 //Close the associated usb
332 run_transport_disconnects(t);
337 void print_packet(const char *label, apacket *p)
343 switch(p->msg.command){
344 case A_SYNC: tag = "SYNC"; break;
345 case A_CNXN: tag = "CNXN" ; break;
346 case A_OPEN: tag = "OPEN"; break;
347 case A_OKAY: tag = "OKAY"; break;
348 case A_CLSE: tag = "CLSE"; break;
349 case A_WRTE: tag = "WRTE"; break;
350 default: tag = "????"; break;
353 fprintf(stderr, "%s: %s %08x %08x %04x \"",
354 label, tag, p->msg.arg0, p->msg.arg1, p->msg.data_length);
355 count = p->msg.data_length;
357 if(count > DUMPMAX) {
364 if((*x >= ' ') && (*x < 127)) {
371 fprintf(stderr, tag);
375 #ifdef SUPPORT_ENCRYPT
377 desc. : 암호화 실패 메시지 전송
378 parameter : [in] apacket* p : sdbd로 들어온 메시지
379 [in] atransport *t : 현재 연결에 대한 atransport
380 [in] unsigned failed_value : 실패 값
382 void send_encr_fail(apacket* p, atransport *t, unsigned failed_value){
384 enc_p = get_apacket();
385 enc_p->msg.command = A_ENCR; // 암호화 메시지
386 enc_p->msg.arg0 = failed_value; // 실패값
387 enc_p->msg.arg1 = p->msg.arg1;
388 send_packet(enc_p, t);
389 //put_apacket(enc_p);
394 parameter : [in] apacket* p : sdbd로 들어온 메시지
395 [in/out] atransport *t : 현재 연결에 대한 atransport
396 ret : 0 : 정상적으로 메시지 전송
399 int handle_encr_packet(apacket* p, atransport *t){
400 static int sessionID = 0;
402 apacket* enc_p = NULL;
404 if(p->msg.arg0 == ENCR_SET_ON_REQ){ // hello 메시지인 경우
405 t->sessionID = sessionID;
406 if((retVal = security_init(t->sessionID, NULL)) == 1){ // 암호화 handshaking을 위한 init
407 if(security_parse_server_hello(t->sessionID, p) == 1){ // hello 메시지 파싱
408 D("security_parse_server_hello success\n");
409 enc_p = get_apacket();
410 if(security_gen_client_hello(t->sessionID, enc_p) == 1){ // hello 메시지 생성
411 D("security_gen_client_hello success\n");
412 enc_p->msg.command = A_ENCR;
413 enc_p->msg.arg0 = ENCR_SET_ON_REQ;
414 enc_p->msg.arg1 = p->msg.arg1;
416 send_packet(enc_p, t);
418 else { // hello 메시지 생성 실패
419 D("security_gen_client_hello error\n");
420 send_encr_fail(p, t, ENCR_ON_FAIL); // 암호화 on 실패 메시지 전송
421 t->encryption = ENCR_OFF; // 암호화 모드는 off
422 security_deinit(t->sessionID);
426 else{ // hello 메시지 파싱 실패
427 D("security_parse_server_hello error\n");
428 send_encr_fail(p, t, ENCR_ON_FAIL);
429 t->encryption = ENCR_OFF;
430 security_deinit(t->sessionID);
435 D("security_init error\n");
436 send_encr_fail(p, t, ENCR_ON_FAIL);
437 t->encryption = ENCR_OFF;
440 security_deinit(t->sessionID);
442 //here!! do security_deinit(), but when plugin pointer is null -> not deinit
446 else if(p->msg.arg0 == ENCR_SET_ON_OK){ // ack 메시지인 경우
447 if(security_parse_server_ack(t->sessionID, p) == 1){ // ack 메시지 파싱
448 enc_p = get_apacket();
449 if(security_gen_client_ack(t->sessionID, enc_p) == 1){ // ack 메시지 생성
450 D("security_gen_client_ack success\n");
451 enc_p->msg.command = A_ENCR;
452 enc_p->msg.arg0 = ENCR_SET_ON_OK;
453 enc_p->msg.arg1 = p->msg.arg1;
454 t->encryption = ENCR_ON;
455 send_packet(enc_p, t);
457 else { // ack 메시지 생성에 실패한 경우
458 D("security_gen_client_ack error\n");
459 send_encr_fail(p, t, ENCR_ON_FAIL);
460 t->encryption = ENCR_OFF;
461 security_deinit(t->sessionID);
465 else { // ack 메시지 파싱에 실패한 경우
466 D("security_parse_server_ack error\n");
467 send_encr_fail(p, t, ENCR_ON_FAIL);
468 t->encryption = ENCR_OFF;
469 security_deinit(t->sessionID);
473 else if(p->msg.arg0 == ENCR_SET_OFF){ // 암호화 모드 off 요청 메시지
474 if(t->encryption == ENCR_ON && security_deinit(t->sessionID) == 1){ // 현재 암호화 모드가 on 상태인 경우
475 enc_p = get_apacket();
476 t->encryption = ENCR_OFF; // 현재 연결에 대한 암호화 모드 off
477 enc_p->msg.command = A_ENCR;
478 enc_p->msg.arg0 = ENCR_SET_OFF;
479 enc_p->msg.arg1 = p->msg.arg1;
480 send_packet(enc_p, t);
482 else { // 암호화 모드 off에 실패한 경우
483 D("security_deinit error\n");
484 send_encr_fail(p, t, ENCR_OFF_FAIL); // 암호화 모드 off 실패 메시지 전송
488 else if(p->msg.arg0 == ENCR_GET){ // 암호화 모드의 상태 요청 메시지인 경우
489 enc_p = get_apacket();
490 enc_p->msg.command = A_ENCR;
491 enc_p->msg.arg0 = ENCR_GET; // 암호화 모드 status get메시지
492 enc_p->msg.arg1 = p->msg.arg1;
493 if(t->encryption == ENCR_ON){ // 암호화 모드가 on인 경우
494 enc_p->msg.data_length = 13;
495 strncpy((char*)enc_p->data, "encryption:on", enc_p->msg.data_length); // encryption:on 메시지 전송
496 } else if(t->encryption == ENCR_OFF){ // 암호화 모드가 off인 경우
497 enc_p->msg.data_length = 14;
498 strncpy((char*)enc_p->data, "encryption:off", enc_p->msg.data_length); // encryption:off 메시지 전송
500 send_packet(enc_p, t);
502 else if (p->msg.arg0 == ENCR_ON_FAIL) // 암호화 모드를 on 하는 도중 실패한 경우 받는 메시지
504 t->encryption = ENCR_OFF; // 암호화 모드를 다시 off
505 D("encryption on failed\n");
507 else if (p->msg.arg0 == ENCR_OFF_FAIL) // 암호화 모드를 off하는 도중 실패한 경우 받는 메시지
509 //t->encryption = ENCR_ON;
510 D("encryption off failed\n");
512 //put_apacket(enc_p);
519 static void send_ready(unsigned local, unsigned remote, atransport *t)
521 D("Calling send_ready \n");
522 apacket *p = get_apacket();
523 p->msg.command = A_OKAY;
525 p->msg.arg1 = remote;
529 static void send_close(unsigned local, unsigned remote, atransport *t)
531 D("Calling send_close \n");
532 apacket *p = get_apacket();
533 p->msg.command = A_CLSE;
535 p->msg.arg1 = remote;
539 static void send_connect(atransport *t)
541 D("Calling send_connect \n");
542 apacket *cp = get_apacket();
543 cp->msg.command = A_CNXN;
544 cp->msg.arg0 = A_VERSION;
545 #ifdef SUPPORT_ENCRYPT
546 cp->msg.arg1 = MAX_PAYLOAD - 100; // connection 시, sdb server의 패킷 크기를 암호화 오버로드 만큼 줄임
548 cp->msg.arg1 = MAX_PAYLOAD;
550 char device_name[256]={0,};
553 if (request_lock_state_to_plugin(LOCKTYPE_PASSWORD) == 1) {
555 t->connection_state = CS_PWLOCK;
559 r = get_emulator_name(device_name, sizeof device_name);
561 r = get_device_name(device_name, sizeof device_name);
564 snprintf((char*) cp->data, sizeof cp->data, "%s::%s::%d", sdb_device_banner, DEFAULT_DEVICENAME, status);
566 snprintf((char*) cp->data, sizeof cp->data, "%s::%s::%d", sdb_device_banner, device_name, status);
569 D("CNXN data:%s\n", (char*)cp->data);
570 cp->msg.data_length = strlen((char*) cp->data) + 1;
574 /* XXX why sleep here? */
575 // allow the device some time to respond to the connect message
580 void send_device_status()
582 D("broadcast device status\n");
583 apacket* cp = get_apacket();
584 cp->msg.command = A_STAT;
585 cp->msg.arg0 = is_pwlocked;
588 broadcast_transport(cp);
590 //all broadcasted packets are memory copied
591 //so, we should call put_apacket
595 static char *connection_state_name(atransport *t)
601 switch(t->connection_state) {
613 static int get_str_cmdline(char *src, char *dest, char str[], int str_size) {
614 char *s = strstr(src, dest);
618 char *e = strstr(s, " ");
623 int len = e-s-strlen(dest);
625 if (len >= str_size) {
626 D("buffer size(%d) should be bigger than %d\n", str_size, len+1);
630 strncpy(str, s + strlen(dest), len);
635 int get_emulator_forward_port() {
636 SdbdCommandlineArgs *sdbd_args = &sdbd_commandline_args; /* alias */
638 if (sdbd_args->emulator.host == NULL) {
642 return sdbd_args->emulator.port;
645 int get_emulator_name(char str[], int str_size) {
646 SdbdCommandlineArgs *sdbd_args = &sdbd_commandline_args; /* alias */
648 if (sdbd_args->emulator.host == NULL) {
652 s_strncpy(str, sdbd_args->emulator.host, str_size);
656 int get_device_name(char str[], int str_size) {
658 int r = system_info_get_platform_string("http://tizen.org/system/model_name", &value);
659 if (r != SYSTEM_INFO_ERROR_NONE) {
660 D("fail to get system model:%d\n", errno);
663 s_strncpy(str, value, str_size);
664 D("returns model_name:%s\n", value);
671 int fd = unix_open(USB_SERIAL_PATH, O_RDONLY);
673 D("fail to read:%s (%d)\n", USB_SERIAL_PATH, errno);
677 if(read_line(fd, str, str_size)) {
678 D("device serial name: %s\n", str);
687 static int get_cmdline_value(char *split, char str[], int str_size) {
689 int fd = unix_open(PROC_CMDLINE_PATH, O_RDONLY);
692 D("fail to read /proc/cmdline\n");
695 if(read_line(fd, cmdline, sizeof(cmdline))) {
696 D("qemu cmd: %s\n", cmdline);
697 if (get_str_cmdline(cmdline, split, str, str_size) < 1) {
698 D("could not get the (%s) value from cmdline\n", split);
707 int get_emulator_hostip(char str[], int str_size) {
708 return get_cmdline_value("host_ip=", str, str_size);
711 int get_emulator_guestip(char str[], int str_size) {
714 struct sockaddr_in *sin;
716 s = socket(AF_INET, SOCK_DGRAM, 0);
722 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s", GUEST_IP_INTERFACE);
723 if(ioctl(s, SIOCGIFHWADDR, &ifr) < 0) {
724 D("ioctl hwaddr error\n");
729 if(ioctl(s, SIOCGIFADDR, &ifr) < 0) {
730 D("ioctl addr error\n");
734 sin = (struct sockaddr_in *)&ifr.ifr_addr;
735 snprintf(str, str_size, "%s", inet_ntoa(sin->sin_addr));
741 void parse_banner(char *banner, atransport *t)
743 char *type, *product, *end;
745 D("parse_banner: %s\n", banner);
747 product = strchr(type, ':');
754 /* remove trailing ':' */
755 end = strchr(product, ':');
758 /* save product name in device structure */
759 if (t->product == NULL) {
760 t->product = strdup(product);
761 } else if (strcmp(product, t->product) != 0) {
763 t->product = strdup(product);
766 if(!strcmp(type, "bootloader")){
767 D("setting connection_state to CS_BOOTLOADER\n");
768 t->connection_state = CS_BOOTLOADER;
773 if(!strcmp(type, "device")) {
774 D("setting connection_state to CS_DEVICE\n");
775 t->connection_state = CS_DEVICE;
780 if(!strcmp(type, "recovery")) {
781 D("setting connection_state to CS_RECOVERY\n");
782 t->connection_state = CS_RECOVERY;
787 if(!strcmp(type, "sideload")) {
788 D("setting connection_state to CS_SIDELOAD\n");
789 t->connection_state = CS_SIDELOAD;
794 t->connection_state = CS_HOST;
797 void handle_packet(apacket *p, atransport *t)
800 int result = access((const char *) p, F_OK);
801 if ((result == -1) && (errno == EFAULT)) {
802 fatal("Invalid apacket = [0x%p]", p);
807 D("handle_packet() %c%c%c%c\n", ((char*) (&(p->msg.command)))[0],
808 ((char*) (&(p->msg.command)))[1],
809 ((char*) (&(p->msg.command)))[2],
810 ((char*) (&(p->msg.command)))[3]);
812 print_packet("recv", p);
814 switch(p->msg.command){
818 if(HOST) send_connect(t);
820 t->connection_state = CS_OFFLINE;
826 case A_CNXN: /* CONNECT(version, maxdata, "system-id-string") */
827 /* XXX verify version, etc */
828 if(t->connection_state != CS_OFFLINE) {
829 t->connection_state = CS_OFFLINE;
832 parse_banner((char*) p->data, t);
834 if(!HOST) send_connect(t);
837 case A_OPEN: /* OPEN(local-id, 0, "destination") */
838 if (request_lock_state_to_plugin(LOCKTYPE_PASSWORD) == 1 && t->connection_state == CS_PWLOCK) {
839 // in case of already locked before get A_CNXN
840 D("open failed due to password locked before get A_CNXN:%d\n", t->connection_state);
841 send_close(0, p->msg.arg0, t);
843 if(t->connection_state != CS_OFFLINE) {
844 char *name = (char*) p->data;
845 name[p->msg.data_length > 0 ? p->msg.data_length - 1 : 0] = 0;
846 s = create_local_service_socket(name);
848 send_close(0, p->msg.arg0, t);
850 s->peer = create_remote_socket(p->msg.arg0, t);
852 send_ready(s->id, s->peer->id, t);
859 case A_OKAY: /* READY(local-id, remote-id, "") */
860 if(t->connection_state != CS_OFFLINE) {
861 if((s = find_local_socket(p->msg.arg1))) {
863 s->peer = create_remote_socket(p->msg.arg0, t);
871 case A_CLSE: /* CLOSE(local-id, remote-id, "") */
872 if(t->connection_state != CS_OFFLINE) {
873 if((s = find_local_socket(p->msg.arg1))) {
880 if(t->connection_state != CS_OFFLINE) {
881 if((s = find_local_socket(p->msg.arg1))) {
882 unsigned rid = p->msg.arg0;
883 p->len = p->msg.data_length;
885 if(s->enqueue(s, p) == 0) {
886 D("Enqueue the socket\n");
887 send_ready(s->id, rid, t);
893 #ifdef SUPPORT_ENCRYPT
894 case A_ENCR: // 암호화 메시지인 경우
895 if(t->connection_state != CS_OFFLINE) {
896 handle_encr_packet(p, t);
902 printf("handle_packet: what is %08x?!\n", p->msg.command);
908 alistener listener_list = {
909 .next = &listener_list,
910 .prev = &listener_list,
913 static void ss_listener_event_func(int _fd, unsigned ev, void *_l)
918 struct sockaddr addr;
923 fd = sdb_socket_accept(_fd, &addr, &alen);
926 sdb_socket_setbufsize(fd, CHUNK_SIZE);
928 s = create_local_socket(fd);
930 connect_to_smartsocket(s);
938 static void listener_event_func(int _fd, unsigned ev, void *_l)
944 struct sockaddr addr;
949 fd = sdb_socket_accept(_fd, &addr, &alen);
952 s = create_local_socket(fd);
954 s->transport = l->transport;
955 connect_to_remote(s, l->connect_to);
963 static void free_listener(alistener* l)
966 l->next->prev = l->prev;
967 l->prev->next = l->next;
968 l->next = l->prev = l;
971 // closes the corresponding fd
972 fdevent_remove(&l->fde);
975 free((char*)l->local_name);
978 free((char*)l->connect_to);
981 remove_transport_disconnect(l->transport, &l->disconnect);
986 static void listener_disconnect(void* _l, atransport* t)
993 int local_name_to_fd(const char *name)
997 if(!strncmp("tcp:", name, 4)){
999 port = atoi(name + 4);
1000 ret = socket_loopback_server(port, SOCK_STREAM);
1003 #ifndef HAVE_WIN32_IPC /* no Unix-domain sockets on Win32 */
1004 // It's non-sensical to support the "reserved" space on the sdb host side
1005 if(!strncmp(name, "local:", 6)) {
1006 return socket_local_server(name + 6,
1007 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
1008 } else if(!strncmp(name, "localabstract:", 14)) {
1009 return socket_local_server(name + 14,
1010 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
1011 } else if(!strncmp(name, "localfilesystem:", 16)) {
1012 return socket_local_server(name + 16,
1013 ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
1017 printf("unknown local portname '%s'\n", name);
1021 static int remove_listener(const char *local_name, const char *connect_to, atransport* transport)
1025 for (l = listener_list.next; l != &listener_list; l = l->next) {
1026 if (!strcmp(local_name, l->local_name) &&
1027 !strcmp(connect_to, l->connect_to) &&
1028 l->transport && l->transport == transport) {
1030 listener_disconnect(l, transport);
1038 static int install_listener(const char *local_name, const char *connect_to, atransport* transport)
1042 //printf("install_listener('%s','%s')\n", local_name, connect_to);
1044 for(l = listener_list.next; l != &listener_list; l = l->next){
1045 if(strcmp(local_name, l->local_name) == 0) {
1048 /* can't repurpose a smartsocket */
1049 if(l->connect_to[0] == '*') {
1053 cto = strdup(connect_to);
1058 //printf("rebinding '%s' to '%s'\n", local_name, connect_to);
1059 free((void*) l->connect_to);
1060 l->connect_to = cto;
1061 if (l->transport != transport) {
1062 remove_transport_disconnect(l->transport, &l->disconnect);
1063 l->transport = transport;
1064 add_transport_disconnect(l->transport, &l->disconnect);
1070 if((l = calloc(1, sizeof(alistener))) == 0) goto nomem;
1071 if((l->local_name = strdup(local_name)) == 0) goto nomem;
1072 if((l->connect_to = strdup(connect_to)) == 0) goto nomem;
1075 l->fd = local_name_to_fd(local_name);
1077 free((void*) l->local_name);
1078 free((void*) l->connect_to);
1080 printf("cannot bind '%s'\n", local_name);
1084 if (close_on_exec(l->fd) < 0) {
1085 D("fail to close fd exec:%d\n",l->fd);
1087 if(!strcmp(l->connect_to, "*smartsocket*")) {
1088 fdevent_install(&l->fde, l->fd, ss_listener_event_func, l);
1090 fdevent_install(&l->fde, l->fd, listener_event_func, l);
1092 fdevent_set(&l->fde, FDE_READ);
1094 l->next = &listener_list;
1095 l->prev = listener_list.prev;
1098 l->transport = transport;
1101 l->disconnect.opaque = l;
1102 l->disconnect.func = listener_disconnect;
1103 add_transport_disconnect(transport, &l->disconnect);
1108 fatal("cannot allocate listener");
1112 #ifdef HAVE_WIN32_PROC
1113 static BOOL WINAPI ctrlc_handler(DWORD type)
1115 exit(STATUS_CONTROL_C_EXIT);
1120 static void sdb_cleanup(void)
1122 clear_sdbd_commandline_args(&sdbd_commandline_args);
1124 if (is_support_usbproto()) {
1127 // if(required_pid > 0) {
1128 // kill(required_pid, SIGKILL);
1131 unload_sdbd_plugin();
1134 void start_logging(void)
1136 #ifdef HAVE_WIN32_PROC
1137 char temp[ MAX_PATH ];
1141 GetTempPath( sizeof(temp) - 8, temp );
1142 strcat( temp, "sdb.log" );
1144 /* Win32 specific redirections */
1145 fnul = fopen( "NUL", "rt" );
1149 flog = fopen( temp, "at" );
1153 setvbuf( flog, NULL, _IONBF, 0 );
1155 stdout[0] = flog[0];
1156 stderr[0] = flog[0];
1157 fprintf(stderr,"--- sdb starting (pid %d) ---\n", getpid());
1161 fd = unix_open("/dev/null", O_RDONLY);
1163 // hopefully not gonna happen
1169 fd = unix_open("/tmp/sdb.log", O_WRONLY | O_CREAT | O_APPEND, 0640);
1171 fd = unix_open("/dev/null", O_WRONLY);
1173 // hopefully not gonna happen
1180 fprintf(stderr,"--- sdb starting (pid %d) ---\n", getpid());
1186 void start_device_log(void)
1189 char path[PATH_MAX] = {0, };
1190 char path_folder[PATH_MAX] = {0, };
1191 char path_file[PATH_MAX] = {0, };
1194 // char value[PROPERTY_VALUE_MAX];
1195 const char* p_trace = getenv("SDB_TRACE");
1196 const char* p_path = getenv("SDBD_LOG_PATH");
1197 // read the trace mask from persistent property persist.sdb.trace_mask
1198 // give up if the property is not set or cannot be parsed
1199 #if 0 /* tizen specific */
1200 property_get("persist.sdb.trace_mask", value, "");
1201 if (sscanf(value, "%x", &sdb_trace_mask) != 1)
1205 if ((p_trace == NULL ) && !is_enable_sdbd_log()) {
1210 snprintf(path_folder, sizeof(path_folder), "%s", p_path);
1211 else if (g_capabilities.log_path[0] != '\0')
1212 snprintf(path_folder, sizeof(path_folder), "%s", g_capabilities.log_path);
1218 localtime_r(&t, &now);
1220 strftime(path_file, sizeof(path_file),
1221 "sdbd-%Y-%m-%d-%H-%M-%S.txt",
1224 snprintf(path, sizeof(path), "%s/%s", path_folder, path_file);
1226 fd = unix_open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1231 // redirect stdout and stderr to the log file
1234 fprintf(stderr,"--- sdbd starting (pid %d) ---\n", getpid());
1237 fd = unix_open("/dev/null", O_RDONLY);
1239 // hopefully not gonna happen
1246 int daemonize(void) {
1248 // set file creation mask to 0
1260 FILE *f = fopen(SDB_PIDPATH, "w");
1263 fprintf(f, "%d\n", getpid());
1271 D("sdbd: unable to change working directory to /\n");
1278 int launch_server(int server_port)
1280 #ifdef HAVE_WIN32_PROC
1281 /* we need to start the server in the background */
1282 /* we create a PIPE that will be used to wait for the server's "OK" */
1283 /* message since the pipe handles must be inheritable, we use a */
1284 /* security attribute */
1285 HANDLE pipe_read, pipe_write;
1286 SECURITY_ATTRIBUTES sa;
1287 STARTUPINFO startup;
1288 PROCESS_INFORMATION pinfo;
1289 char program_path[ MAX_PATH ];
1292 sa.nLength = sizeof(sa);
1293 sa.lpSecurityDescriptor = NULL;
1294 sa.bInheritHandle = TRUE;
1296 /* create pipe, and ensure its read handle isn't inheritable */
1297 ret = CreatePipe( &pipe_read, &pipe_write, &sa, 0 );
1299 fprintf(stderr, "CreatePipe() failure, error %ld\n", GetLastError() );
1303 SetHandleInformation( pipe_read, HANDLE_FLAG_INHERIT, 0 );
1305 ZeroMemory( &startup, sizeof(startup) );
1306 startup.cb = sizeof(startup);
1307 startup.hStdInput = GetStdHandle( STD_INPUT_HANDLE );
1308 startup.hStdOutput = pipe_write;
1309 startup.hStdError = GetStdHandle( STD_ERROR_HANDLE );
1310 startup.dwFlags = STARTF_USESTDHANDLES;
1312 ZeroMemory( &pinfo, sizeof(pinfo) );
1314 /* get path of current program */
1315 GetModuleFileName( NULL, program_path, sizeof(program_path) );
1317 ret = CreateProcess(
1318 program_path, /* program path */
1319 "sdb fork-server server",
1320 /* the fork-server argument will set the
1321 debug = 2 in the child */
1322 NULL, /* process handle is not inheritable */
1323 NULL, /* thread handle is not inheritable */
1324 TRUE, /* yes, inherit some handles */
1325 DETACHED_PROCESS, /* the new process doesn't have a console */
1326 NULL, /* use parent's environment block */
1327 NULL, /* use parent's starting directory */
1328 &startup, /* startup info, i.e. std handles */
1331 CloseHandle( pipe_write );
1334 fprintf(stderr, "CreateProcess failure, error %ld\n", GetLastError() );
1335 CloseHandle( pipe_read );
1339 CloseHandle( pinfo.hProcess );
1340 CloseHandle( pinfo.hThread );
1342 /* wait for the "OK\n" message */
1347 ret = ReadFile( pipe_read, temp, 3, &count, NULL );
1348 CloseHandle( pipe_read );
1350 fprintf(stderr, "could not read ok from SDB Server, error = %ld\n", GetLastError() );
1353 if (count != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
1354 fprintf(stderr, "SDB server didn't ACK\n" );
1358 #elif defined(HAVE_FORKEXEC)
1359 char path[PATH_MAX];
1362 // set up a pipe so the child can tell us when it is ready.
1363 // fd[0] will be parent's end, and fd[1] will get mapped to stderr in the child.
1365 fprintf(stderr, "pipe failed in launch_server, errno: %d\n", errno);
1368 get_my_path(path, PATH_MAX);
1370 if(pid < 0) return -1;
1373 // child side of the fork
1375 // redirect stderr to the pipe
1376 // we use stderr instead of stdout due to stdout's buffering behavior.
1378 dup2(fd[1], STDERR_FILENO);
1382 int result = execl(path, "sdb", "fork-server", "server", NULL);
1383 // this should not return
1384 fprintf(stderr, "OOPS! execl returned %d, errno: %d\n", result, errno);
1386 // parent side of the fork
1390 temp[0] = 'A'; temp[1] = 'B'; temp[2] = 'C';
1391 // wait for the "OK\n" message
1393 int ret = sdb_read(fd[0], temp, 3);
1394 int saved_errno = errno;
1397 fprintf(stderr, "could not read ok from SDB Server, errno = %d\n", saved_errno);
1400 if (ret != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
1401 fprintf(stderr, "SDB server didn't ACK\n" );
1408 #error "cannot implement background server start on this platform"
1414 /* Constructs a local name of form tcp:port.
1415 * target_str points to the target string, it's content will be overwritten.
1416 * target_size is the capacity of the target string.
1417 * server_port is the port number to use for the local name.
1419 void build_local_name(char* target_str, size_t target_size, int server_port)
1421 snprintf(target_str, target_size, "tcp:%d", server_port);
1425 static void init_drop_privileges() {
1426 #ifdef _DROP_PRIVILEGE
1433 int should_drop_privileges() {
1434 if (rootshell_mode == 1) { // if root, then don't drop
1440 #include <dbus/dbus.h>
1441 #include <dbus/dbus-glib.h>
1442 #include <dbus/dbus-glib-lowlevel.h>
1444 #define BOOTING_DONE_SIGNAL "BootingDone"
1445 #define DEVICED_CORE_INTERFACE "org.tizen.system.deviced.core"
1446 #define SDBD_BOOT_INFO_FILE "/tmp/sdbd_boot_info"
1448 static DBusHandlerResult __sdbd_dbus_signal_filter(DBusConnection *conn,
1449 DBusMessage *message, void *user_data) {
1450 D("got dbus message\n");
1451 const char *interface;
1454 dbus_error_init(&error);
1456 interface = dbus_message_get_interface(message);
1457 if (interface == NULL) {
1458 D("reject by security issue - no interface\n");
1459 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1462 if (dbus_message_is_signal(message, DEVICED_CORE_INTERFACE,
1463 BOOTING_DONE_SIGNAL)) {
1465 if (access(SDBD_BOOT_INFO_FILE, F_OK) == 0) {
1466 D("booting is done before\n");
1468 FILE *f = fopen(SDBD_BOOT_INFO_FILE, "w");
1470 fprintf(f, "%d", 1);
1474 D("booting is done\n");
1477 D("handled dbus message\n");
1478 return DBUS_HANDLER_RESULT_HANDLED;
1481 static void *bootdone_cb(void *x) {
1482 int MAX_LOCAL_BUFSZ = 128;
1484 DBusConnection *bus;
1485 char rule[MAX_LOCAL_BUFSZ];
1486 GMainLoop *mainloop;
1488 /* g_type_init() is deprecated for glib version 2.35.0 or greater, */
1489 #if !GLIB_CHECK_VERSION(2,35,0)
1493 dbus_error_init(&error);
1494 bus = dbus_bus_get(DBUS_BUS_SYSTEM, &error);
1496 D("Failed to connect to the D-BUS daemon: %s", error.message);
1497 dbus_error_free(&error);
1500 dbus_connection_setup_with_g_main(bus, NULL);
1502 snprintf(rule, MAX_LOCAL_BUFSZ, "type='signal',interface='%s'",
1503 DEVICED_CORE_INTERFACE);
1504 /* listening to messages */
1505 dbus_bus_add_match(bus, rule, &error);
1506 if (dbus_error_is_set(&error)) {
1507 D("Fail to rule set: %s", error.message);
1508 dbus_error_free(&error);
1512 if (dbus_connection_add_filter(bus, __sdbd_dbus_signal_filter, NULL, NULL)
1516 D("booting signal initialized\n");
1517 mainloop = g_main_loop_new(NULL, FALSE);
1518 g_main_loop_run(mainloop);
1520 D("dbus loop exited");
1525 void register_bootdone_cb() {
1526 D("registerd bootdone callback\n");
1529 if (sdb_thread_create(&t, bootdone_cb, NULL)) {
1530 D("cannot create service thread\n");
1535 static int sdbd_set_groups() {
1536 gid_t *group_ids = NULL;
1539 int group_match = 0;
1540 int added_group_cnt = 0;
1542 getgrouplist(SDK_USER_NAME, g_sdk_group_id, NULL, &ngroups);
1543 D("group list : ngroups = %d\n", ngroups);
1544 group_ids = malloc((ngroups + SDB_DEFAULT_GROUPS_CNT) * sizeof(gid_t));
1545 if (group_ids == NULL) {
1546 D("failed to allocate group_ids(%d)\n", (ngroups + SDB_DEFAULT_GROUPS_CNT) * sizeof(gid_t));
1549 if (getgrouplist(SDK_USER_NAME, g_sdk_group_id, group_ids, &ngroups) == -1) {
1550 D("failed to getgrouplist(), ngroups = %d\n", ngroups);
1555 for (i = 0; g_default_groups[i].name != NULL; i++) {
1556 for (j = 0; j < ngroups; j++) {
1557 if (group_ids[j] == g_default_groups[i].gid) {
1562 if (group_match == 0 && g_default_groups[i].gid != -1) {
1563 group_ids[ngroups + added_group_cnt] = g_default_groups[i].gid;
1569 if (setgroups(ngroups+added_group_cnt, group_ids) != 0) {
1570 D("failed to setgroups().\n");
1579 static int sdbd_get_user_pwd(const char* user_name, struct passwd* pwd, char* buf, size_t bufsize) {
1580 struct passwd *result = NULL;
1583 ret = getpwnam_r(user_name, pwd, buf, bufsize, &result);
1584 if (result == NULL) {
1586 D("Not found passwd : username(%s)\n", user_name);
1589 D("failed to getpwnam_r\n");
1597 static int sdbd_get_group(const char* group_name, struct group* grp, char* buf, size_t bufsize) {
1598 struct group *result = NULL;
1601 ret = getgrnam_r(group_name, grp, buf, bufsize, &result);
1602 if (result == NULL) {
1604 D("Not found group : groupname(%s)\n", group_name);
1607 D("failed to getgrnam_r\n");
1615 int set_sdk_user_privileges() {
1616 if (!is_init_sdk_userinfo) {
1617 D("failed to init sdk user information.\n");
1621 if (sdbd_set_groups() < 0) {
1622 D("set groups failed (errno: %d)\n", errno);
1626 if (setgid(g_sdk_group_id) != 0) {
1627 D("set group id failed (errno: %d)\n", errno);
1631 if (setuid(g_sdk_user_id) != 0) {
1632 D("set user id failed (errno: %d)\n", errno);
1636 if (chdir(g_sdk_home_dir) < 0) {
1637 D("unable to change working directory to %s\n", g_sdk_home_dir);
1640 // TODO: use pam later
1641 if (g_sdk_home_dir_env) {
1642 putenv(g_sdk_home_dir_env);
1648 #define SDB_PW_GR_DEFAULT_SIZE (16*1024)
1649 static long get_passwd_bufsize() {
1652 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
1654 bufsize = SDB_PW_GR_DEFAULT_SIZE;
1660 static long get_group_bufsize() {
1663 bufsize = sysconf(_SC_GETGR_R_SIZE_MAX);
1665 bufsize = SDB_PW_GR_DEFAULT_SIZE;
1671 static int init_sdb_default_groups() {
1677 bufsize = get_group_bufsize();
1678 buf = malloc(bufsize);
1680 D("failed to allocate gruop buf(%ld)\n", bufsize);
1684 for (i = 0; g_default_groups[i].name != NULL; i++) {
1685 memset(buf, 0, bufsize);
1686 if (sdbd_get_group(g_default_groups[i].name, &grp, buf, bufsize) == 0) {
1687 g_default_groups[i].gid = grp.gr_gid;
1689 D("failed get group info.(errno: %d)\n", errno);
1697 static void set_static_userinfo() {
1698 g_sdk_user_id = STATIC_SDK_USER_ID;
1699 g_sdk_group_id = STATIC_SDK_GROUP_ID;
1700 g_sdk_home_dir = STATIC_SDK_HOME_DIR;
1703 static int init_sdk_userinfo() {
1708 if (is_init_sdk_userinfo) {
1712 if (init_sdb_default_groups() < 0) {
1713 D("failed to initialize default groups.\n");
1716 bufsize = get_passwd_bufsize();
1717 buf = malloc(bufsize);
1719 D("failed to allocate passwd buf(%ld)\n", bufsize);
1720 set_static_userinfo();
1722 if (sdbd_get_user_pwd(SDK_USER_NAME, &pwd, buf, bufsize) < 0) {
1723 D("get user passwd info.(errno: %d)\n", errno);
1724 set_static_userinfo();
1726 D("username=%s, uid=%d, gid=%d, dir=%s\n", pwd.pw_name, pwd.pw_uid, pwd.pw_gid, pwd.pw_dir);
1728 g_sdk_user_id = pwd.pw_uid;
1729 g_sdk_group_id = pwd.pw_gid;
1730 g_sdk_home_dir = strdup(pwd.pw_dir);
1735 int env_size = strlen("HOME=") + strlen(g_sdk_home_dir) + 1;
1736 g_sdk_home_dir_env = malloc(env_size);
1737 if(g_sdk_home_dir_env == NULL) {
1738 D("failed to allocate for home dir env string\n");
1740 snprintf(g_sdk_home_dir_env, env_size, "HOME=%s", g_sdk_home_dir);
1743 is_init_sdk_userinfo = 1;
1747 static void init_sdk_requirements() {
1750 // set env variable for temporary
1751 // TODO: should use pam instead later!!
1752 if (!getenv("TERM")) {
1753 putenv("TERM=linux");
1756 if (!getenv("HOME")) {
1757 putenv("HOME=/root");
1760 init_sdk_userinfo();
1762 if (g_sdk_home_dir != NULL && stat(g_sdk_home_dir, &st) == 0) {
1763 if (st.st_uid != g_sdk_user_id || st.st_gid != g_sdk_group_id) {
1765 snprintf(cmd, sizeof(cmd), "chown %s:%s %s -R", SDK_USER_NAME, SDK_USER_NAME, g_sdk_home_dir);
1766 if (system(cmd) < 0) {
1767 D("failed to change ownership to sdk user to %s\n", g_sdk_home_dir);
1772 if (is_emulator()) {
1773 register_bootdone_cb();
1776 #endif /* !SDB_HOST */
1778 static void init_capabilities(void) {
1782 memset(&g_capabilities, 0, sizeof(g_capabilities));
1784 // CPU Architecture of model
1785 ret = system_info_get_platform_string("http://tizen.org/feature/platform.core.cpu.arch", &value);
1786 if (ret != SYSTEM_INFO_ERROR_NONE) {
1787 snprintf(g_capabilities.cpu_arch, sizeof(g_capabilities.cpu_arch),
1789 D("fail to get the CPU architecture of model:%d\n", errno);
1791 snprintf(g_capabilities.cpu_arch, sizeof(g_capabilities.cpu_arch),
1793 if (value != NULL) {
1799 // Secure protocol support
1800 if(!request_capability_to_plugin(CAPABILITY_SECURE, g_capabilities.secure_protocol,
1801 sizeof(g_capabilities.secure_protocol))) {
1802 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_SECURE);
1803 snprintf(g_capabilities.secure_protocol, sizeof(g_capabilities.secure_protocol),
1808 // Interactive shell support
1809 if(!request_capability_to_plugin(CAPABILITY_INTER_SHELL, g_capabilities.intershell_support,
1810 sizeof(g_capabilities.intershell_support))) {
1811 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_INTER_SHELL);
1812 snprintf(g_capabilities.intershell_support, sizeof(g_capabilities.intershell_support),
1817 // File push/pull support
1818 if(!request_capability_to_plugin(CAPABILITY_FILESYNC, g_capabilities.filesync_support,
1819 sizeof(g_capabilities.filesync_support))) {
1820 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_FILESYNC);
1821 snprintf(g_capabilities.filesync_support, sizeof(g_capabilities.filesync_support),
1826 // USB protocol support
1827 if(!request_capability_to_plugin(CAPABILITY_USB_PROTOCOL, g_capabilities.usbproto_support,
1828 sizeof(g_capabilities.usbproto_support))) {
1829 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_USB_PROTOCOL);
1830 snprintf(g_capabilities.usbproto_support, sizeof(g_capabilities.usbproto_support),
1835 // Socket protocol support
1836 if(!request_capability_to_plugin(CAPABILITY_SOCK_PROTOCOL, g_capabilities.sockproto_support,
1837 sizeof(g_capabilities.sockproto_support))) {
1838 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_SOCK_PROTOCOL);
1839 snprintf(g_capabilities.sockproto_support, sizeof(g_capabilities.sockproto_support),
1844 // Root command support
1845 if(!request_capability_to_plugin(CAPABILITY_ROOT_ONOFF, g_capabilities.rootonoff_support,
1846 sizeof(g_capabilities.rootonoff_support))) {
1847 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_ROOT_ONOFF);
1848 snprintf(g_capabilities.rootonoff_support, sizeof(g_capabilities.rootonoff_support),
1853 // Encryption support
1854 if(!request_capability_to_plugin(CAPABILITY_ENCRYPTION, g_capabilities.encryption_support,
1855 sizeof(g_capabilities.encryption_support))) {
1856 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_ENCRYPTION);
1857 snprintf(g_capabilities.encryption_support, sizeof(g_capabilities.encryption_support),
1863 ret = is_container_enabled();
1864 snprintf(g_capabilities.zone_support, sizeof(g_capabilities.zone_support),
1865 "%s", ret == 1 ? ENABLED : DISABLED);
1867 // Multi-User support
1868 // XXX: There is no clear way to determine whether multi-user support.
1869 // Since TZ_SYS_DEFAULT_USER is set to "owner" for multi-user support,
1870 // guess whether multiuser support through that information.
1871 const char* sys_default_user = tzplatform_getenv(TZ_SYS_DEFAULT_USER);
1872 if (sys_default_user != NULL && !strcmp(sys_default_user, "owner")) {
1873 snprintf(g_capabilities.multiuser_support, sizeof(g_capabilities.multiuser_support),
1876 snprintf(g_capabilities.multiuser_support, sizeof(g_capabilities.multiuser_support),
1880 // Window size synchronization support
1881 snprintf(g_capabilities.syncwinsz_support, sizeof(g_capabilities.syncwinsz_support),
1885 if (SDK_TOOL_PATH == NULL) {
1886 D("fail to get SDK tool path.\n");
1887 snprintf(g_capabilities.sdk_toolpath, sizeof(g_capabilities.sdk_toolpath),
1890 snprintf(g_capabilities.sdk_toolpath, sizeof(g_capabilities.sdk_toolpath),
1891 "%s", SDK_TOOL_PATH);
1895 ret = system_info_get_platform_string("http://tizen.org/feature/profile", &value);
1896 if (ret != SYSTEM_INFO_ERROR_NONE) {
1897 snprintf(g_capabilities.profile_name, sizeof(g_capabilities.profile_name),
1899 D("fail to get profile name:%d\n", errno);
1901 snprintf(g_capabilities.profile_name, sizeof(g_capabilities.profile_name),
1903 if (value != NULL) {
1910 ret = system_info_get_platform_string("http://tizen.org/system/manufacturer", &value);
1911 if (ret != SYSTEM_INFO_ERROR_NONE) {
1912 snprintf(g_capabilities.vendor_name, sizeof(g_capabilities.vendor_name),
1914 D("fail to get the Vendor name:%d\n", errno);
1916 snprintf(g_capabilities.vendor_name, sizeof(g_capabilities.vendor_name),
1918 if (value != NULL) {
1924 // Target name of the launch possible
1925 if(!request_capability_to_plugin(CAPABILITY_CAN_LAUNCH, g_capabilities.can_launch,
1926 sizeof(g_capabilities.can_launch))) {
1927 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_CAN_LAUNCH);
1928 snprintf(g_capabilities.can_launch, sizeof(g_capabilities.can_launch),
1934 ret = system_info_get_platform_string("http://tizen.org/feature/platform.version", &value);
1935 if (ret != SYSTEM_INFO_ERROR_NONE) {
1936 snprintf(g_capabilities.platform_version, sizeof(g_capabilities.platform_version),
1938 D("fail to get platform version:%d\n", errno);
1940 snprintf(g_capabilities.platform_version, sizeof(g_capabilities.platform_version),
1942 if (value != NULL) {
1949 if(!request_capability_to_plugin(CAPABILITY_PRODUCT_VER, g_capabilities.product_version,
1950 sizeof(g_capabilities.product_version))) {
1951 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_PRODUCT_VER);
1952 snprintf(g_capabilities.product_version, sizeof(g_capabilities.product_version),
1958 snprintf(g_capabilities.sdbd_version, sizeof(g_capabilities.sdbd_version),
1959 "%d.%d.%d", SDB_VERSION_MAJOR, SDB_VERSION_MINOR, SDB_VERSION_PATCH);
1962 // Sdbd plugin version
1963 if(!request_capability_to_plugin(CAPABILITY_PLUGIN_VER, g_capabilities.sdbd_plugin_version,
1964 sizeof(g_capabilities.sdbd_plugin_version))) {
1965 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_PLUGIN_VER);
1966 snprintf(g_capabilities.sdbd_plugin_version, sizeof(g_capabilities.sdbd_plugin_version),
1972 if(!request_capability_to_plugin(CAPABILITY_LOG_ENABLE, g_capabilities.log_enable,
1973 sizeof(g_capabilities.log_enable))) {
1974 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_LOG_ENABLE);
1975 snprintf(g_capabilities.log_enable, sizeof(g_capabilities.log_enable),
1980 if(!request_capability_to_plugin(CAPABILITY_LOG_PATH, g_capabilities.log_path,
1981 sizeof(g_capabilities.log_path))) {
1982 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_LOG_PATH);
1983 snprintf(g_capabilities.log_path, sizeof(g_capabilities.log_path),
1987 // Application command support
1988 if(!request_capability_to_plugin(CAPABILITY_APPCMD, g_capabilities.appcmd_support,
1989 sizeof(g_capabilities.appcmd_support))) {
1990 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_APPCMD);
1991 snprintf(g_capabilities.appcmd_support, sizeof(g_capabilities.appcmd_support),
1995 // Capability version
1996 snprintf(g_capabilities.sdbd_cap_version, sizeof(g_capabilities.sdbd_cap_version),
1997 "%d.%d", SDBD_CAP_VERSION_MAJOR, SDBD_CAP_VERSION_MINOR);
2000 static int is_support_usbproto()
2002 return (!strncmp(g_capabilities.usbproto_support, PLUGIN_RET_ENABLED, strlen(PLUGIN_RET_ENABLED)));
2005 static int is_support_sockproto()
2007 return (!strncmp(g_capabilities.sockproto_support, PLUGIN_RET_ENABLED, strlen(PLUGIN_RET_ENABLED)));
2010 #define EMULATOR_MODEL_NAME "Emulator"
2011 static void check_emulator_or_device()
2013 char model_name[256]={0,};
2016 // Get the model name from model_config.xml
2017 ret = get_device_name(model_name, sizeof model_name);
2019 if(!strncmp(model_name, EMULATOR_MODEL_NAME, sizeof(EMULATOR_MODEL_NAME))){
2021 D("This target type is Emulator\n");
2024 D("This target type is Device\n");
2028 D("failed to get the model name.\n");
2032 static void fork_prepare_handler(void)
2034 sdb_mutex_lock(&D_lock);
2037 static void fork_parent_handler(void)
2039 sdb_mutex_unlock(&D_lock);
2042 static void fork_child_handler(void)
2044 sdb_mutex_unlock(&D_lock);
2047 int sdb_main(int is_daemon, int server_port)
2050 check_emulator_or_device();
2054 init_capabilities();
2059 init_drop_privileges();
2060 init_sdk_requirements();
2061 if (!request_validity_to_plugin(PLUGIN_SYNC_CMD_VERIFY_LAUNCH, NULL)) {
2062 D("sdbd should be launched in develop mode.\n");
2068 pthread_atfork(fork_prepare_handler, fork_parent_handler, fork_child_handler);
2071 atexit(sdb_cleanup);
2072 #ifdef HAVE_WIN32_PROC
2073 SetConsoleCtrlHandler( ctrlc_handler, TRUE );
2074 #elif defined(HAVE_FORKEXEC)
2075 // No SIGCHLD. Let the service subproc handle its children.
2076 signal(SIGPIPE, SIG_IGN);
2079 init_transport_registration();
2085 local_init(DEFAULT_SDB_LOCAL_TRANSPORT_PORT);
2087 char local_name[30];
2088 build_local_name(local_name, sizeof(local_name), server_port);
2089 if(install_listener(local_name, "*smartsocket*", NULL)) {
2093 /* don't listen on a port (default 5037) if running in secure mode */
2094 /* don't run as root if we are running in secure mode */
2096 if (should_drop_privileges()) {
2098 struct __user_cap_header_struct header;
2099 struct __user_cap_data_struct cap;
2101 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
2104 /* add extra groups:
2105 ** SID_TTY to access /dev/ptmx
2107 gid_t groups[] = { SID_TTY, SID_APP_LOGGING, SID_SYS_LOGGING };
2108 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
2111 /* then switch user and group to "developer" */
2112 if (setgid(GID_DEVELOPER) != 0) {
2113 fprintf(stderr, "set group id failed errno: %d\n", errno);
2116 if (setuid(SID_DEVELOPER) != 0) {
2117 fprintf(stderr, "set user id failed errno: %d\n", errno);
2121 /* set CAP_SYS_BOOT capability, so "sdb reboot" will succeed */
2122 header.version = _LINUX_CAPABILITY_VERSION;
2124 cap.effective = cap.permitted = (1 << CAP_SYS_BOOT);
2125 cap.inheritable = 0;
2126 capset(&header, &cap);
2128 D("Local port disabled\n");
2130 char local_name[30];
2131 build_local_name(local_name, sizeof(local_name), server_port);
2132 if(install_listener(local_name, "*smartsocket*", NULL)) {
2137 /* choose the usb gadget backend */
2138 if (access(USB_NODE_FILE, F_OK) == 0) {
2139 /* legacy kernel-based sdb gadget */
2140 usb_init = &linux_usb_init;
2141 usb_cleanup = &linux_usb_cleanup;
2142 usb_write = &linux_usb_write;
2143 usb_read = &linux_usb_read;
2144 usb_close = &linux_usb_close;
2145 usb_kick = &linux_usb_kick;
2147 /* functionfs based gadget */
2148 usb_init = &ffs_usb_init;
2149 usb_cleanup = &ffs_usb_cleanup;
2150 usb_write = &ffs_usb_write;
2151 usb_read = &ffs_usb_read;
2152 usb_close = &ffs_usb_close;
2153 usb_kick = &ffs_usb_kick;
2156 if (is_support_usbproto()) {
2160 if (is_support_sockproto()) {
2161 /* by default don't listen on local transport but
2162 * listen if suitable command line argument has been provided */
2163 if (sdbd_commandline_args.sdbd_port >= 0) {
2164 local_init(sdbd_commandline_args.sdbd_port);
2166 local_init(DEFAULT_SDB_LOCAL_TRANSPORT_PORT);
2170 #if 0 /* tizen specific */
2171 D("sdb_main(): pre init_jdwp()\n");
2173 D("sdb_main(): post init_jdwp()\n");
2179 // inform our parent that we are up and running.
2180 #ifdef HAVE_WIN32_PROC
2182 WriteFile( GetStdHandle( STD_OUTPUT_HANDLE ), "OK\n", 3, &count, NULL );
2183 #elif defined(HAVE_FORKEXEC)
2184 fprintf(stderr, "OK\n");
2189 D("Event loop starting\n");
2193 if (is_support_usbproto()) {
2201 void connect_device(char* host, char* buffer, int buffer_size)
2204 char* portstr = strchr(host, ':');
2208 s_strncpy(hostbuf, host, sizeof(hostbuf) - 1);
2210 if (portstr - host >= sizeof(hostbuf)) {
2211 snprintf(buffer, buffer_size, "bad host name %s", host);
2214 // zero terminate the host at the point we found the colon
2215 hostbuf[portstr - host] = 0;
2216 if (sscanf(portstr + 1, "%d", &port) == 0) {
2217 snprintf(buffer, buffer_size, "bad port number %s", portstr);
2221 port = DEFAULT_SDB_LOCAL_TRANSPORT_PORT;
2224 snprintf(serial, sizeof(serial), "%s:%d", hostbuf, port);
2225 if (find_transport(serial)) {
2226 snprintf(buffer, buffer_size, "already connected to %s", serial);
2230 fd = socket_network_client(hostbuf, port, SOCK_STREAM);
2232 snprintf(buffer, buffer_size, "unable to connect to %s", host);
2236 D("client: connected on remote on fd %d\n", fd);
2238 disable_tcp_nagle(fd);
2239 register_socket_transport(fd, serial, port, 0, NULL);
2240 snprintf(buffer, buffer_size, "connected to %s", serial);
2243 void connect_emulator(char* port_spec, char* buffer, int buffer_size)
2245 char* port_separator = strchr(port_spec, ',');
2246 if (!port_separator) {
2247 snprintf(buffer, buffer_size,
2248 "unable to parse '%s' as <console port>,<sdb port>",
2253 // Zero-terminate console port and make port_separator point to 2nd port.
2254 *port_separator++ = 0;
2255 int console_port = strtol(port_spec, NULL, 0);
2256 int sdb_port = strtol(port_separator, NULL, 0);
2257 if (!(console_port > 0 && sdb_port > 0)) {
2258 *(port_separator - 1) = ',';
2259 snprintf(buffer, buffer_size,
2260 "Invalid port numbers: Expected positive numbers, got '%s'",
2265 /* Check if the emulator is already known.
2266 * Note: There's a small but harmless race condition here: An emulator not
2267 * present just yet could be registered by another invocation right
2268 * after doing this check here. However, local_connect protects
2269 * against double-registration too. From here, a better error message
2270 * can be produced. In the case of the race condition, the very specific
2271 * error message won't be shown, but the data doesn't get corrupted. */
2272 atransport* known_emulator = find_emulator_transport_by_sdb_port(sdb_port);
2273 if (known_emulator != NULL) {
2274 snprintf(buffer, buffer_size,
2275 "Emulator on port %d already registered.", sdb_port);
2279 /* Check if more emulators can be registered. Similar unproblematic
2280 * race condition as above. */
2281 int candidate_slot = get_available_local_transport_index();
2282 if (candidate_slot < 0) {
2283 snprintf(buffer, buffer_size, "Cannot accept more emulators.");
2287 /* Preconditions met, try to connect to the emulator. */
2288 if (!local_connect_arbitrary_ports(console_port, sdb_port, NULL)) {
2289 snprintf(buffer, buffer_size,
2290 "Connected to emulator on ports %d,%d", console_port, sdb_port);
2292 snprintf(buffer, buffer_size,
2293 "Could not connect to emulator on ports %d,%d",
2294 console_port, sdb_port);
2299 int copy_packet(apacket* dest, apacket* src) {
2302 D("dest packet is NULL\n");
2307 D("src packet is NULL\n");
2311 dest->next = src->next;
2312 dest->ptr = src->ptr;
2313 dest->len = src->len;
2315 int data_length = src->msg.data_length;
2316 if(data_length > MAX_PAYLOAD) {
2317 data_length = MAX_PAYLOAD;
2319 memcpy(&(dest->msg), &(src->msg), sizeof(amessage) + data_length);
2324 int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s)
2326 atransport *transport = NULL;
2329 if(!strcmp(service, "kill")) {
2330 fprintf(stderr,"sdb server killed by remote request\n");
2332 sdb_write(reply_fd, "OKAY", 4);
2333 if (is_support_usbproto()) {
2340 // "transport:" is used for switching transport with a specified serial number
2341 // "transport-usb:" is used for switching transport to the only USB transport
2342 // "transport-local:" is used for switching transport to the only local transport
2343 // "transport-any:" is used for switching transport to the only transport
2344 if (!strncmp(service, "transport", strlen("transport"))) {
2345 char* error_string = "unknown failure";
2346 transport_type type = kTransportAny;
2348 if (!strncmp(service, "transport-usb", strlen("transport-usb"))) {
2349 type = kTransportUsb;
2350 } else if (!strncmp(service, "transport-local", strlen("transport-local"))) {
2351 type = kTransportLocal;
2352 } else if (!strncmp(service, "transport-any", strlen("transport-any"))) {
2353 type = kTransportAny;
2354 } else if (!strncmp(service, "transport:", strlen("transport:"))) {
2355 service += strlen("transport:");
2359 transport = acquire_one_transport(CS_ANY, type, serial, &error_string);
2362 s->transport = transport;
2363 sdb_write(reply_fd, "OKAY", 4);
2365 sendfailmsg(reply_fd, error_string);
2370 // return a list of all connected devices
2371 if (!strcmp(service, "devices")) {
2373 memset(buf, 0, sizeof(buf));
2374 memset(buffer, 0, sizeof(buffer));
2375 D("Getting device list \n");
2376 list_transports(buffer, sizeof(buffer));
2377 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer),buffer);
2378 D("Wrote device list \n");
2379 writex(reply_fd, buf, strlen(buf));
2383 // add a new TCP transport, device or emulator
2384 if (!strncmp(service, "connect:", 8)) {
2386 char* host = service + 8;
2387 if (!strncmp(host, "emu:", 4)) {
2388 connect_emulator(host + 4, buffer, sizeof(buffer));
2390 connect_device(host, buffer, sizeof(buffer));
2392 // Send response for emulator and device
2393 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
2394 writex(reply_fd, buf, strlen(buf));
2398 // remove TCP transport
2399 if (!strncmp(service, "disconnect:", 11)) {
2401 memset(buffer, 0, sizeof(buffer));
2402 char* serial = service + 11;
2403 if (serial[0] == 0) {
2404 // disconnect from all TCP devices
2405 unregister_all_tcp_transports();
2408 // assume port 26101 if no port is specified
2409 if (!strchr(serial, ':')) {
2410 snprintf(hostbuf, sizeof(hostbuf) - 1, "%s:26101", serial);
2413 atransport *t = find_transport(serial);
2416 unregister_transport(t);
2418 snprintf(buffer, sizeof(buffer), "No such device %s", serial);
2422 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
2423 writex(reply_fd, buf, strlen(buf));
2427 // returns our value for SDB_SERVER_VERSION
2428 if (!strcmp(service, "version")) {
2430 snprintf(version, sizeof version, "%04x", SDB_SERVER_VERSION);
2431 snprintf(buf, sizeof buf, "OKAY%04x%s", (unsigned)strlen(version), version);
2432 writex(reply_fd, buf, strlen(buf));
2436 if(!strncmp(service,"get-serialno",strlen("get-serialno"))) {
2437 char *out = "unknown";
2438 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
2439 if (transport && transport->serial) {
2440 out = transport->serial;
2442 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(out),out);
2443 writex(reply_fd, buf, strlen(buf));
2446 // indicates a new emulator instance has started
2447 if (!strncmp(service,"emulator:",9)) { /* tizen specific */
2448 char *tmp = strtok(service+9, DEVICEMAP_SEPARATOR);
2452 port = atoi(service+9);
2455 tmp = strtok(NULL, DEVICEMAP_SEPARATOR);
2457 local_connect(port, tmp);
2460 local_connect(port, NULL);
2465 if(!strncmp(service,"forward:",8) || !strncmp(service,"killforward:",12)) {
2466 char *local, *remote, *err;
2468 atransport *transport;
2470 int createForward = strncmp(service,"kill",4);
2472 local = service + (createForward ? 8 : 12);
2473 remote = strchr(local,';');
2475 sendfailmsg(reply_fd, "malformed forward spec");
2480 if((local[0] == 0) || (remote[0] == 0) || (remote[0] == '*')){
2481 sendfailmsg(reply_fd, "malformed forward spec");
2485 transport = acquire_one_transport(CS_ANY, ttype, serial, &err);
2487 sendfailmsg(reply_fd, err);
2491 if (createForward) {
2492 r = install_listener(local, remote, transport);
2494 r = remove_listener(local, remote, transport);
2497 /* 1st OKAY is connect, 2nd OKAY is status */
2498 writex(reply_fd, "OKAYOKAY", 8);
2502 if (createForward) {
2503 sendfailmsg(reply_fd, (r == -1) ? "cannot rebind smartsocket" : "cannot bind socket");
2505 sendfailmsg(reply_fd, "cannot remove listener");
2510 if(!strncmp(service,"get-state",strlen("get-state"))) {
2511 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
2512 char *state = connection_state_name(transport);
2513 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(state),state);
2514 writex(reply_fd, buf, strlen(buf));
2521 int recovery_mode = 0;
2524 int main(int argc, char **argv)
2529 return sdb_commandline(argc - 1, argv + 1);
2531 /* If sdbd runs inside the emulator this will enable sdb tracing via
2532 * sdb-debug qemud service in the emulator. */
2533 #if 0 /* tizen specific */
2534 sdb_qemu_trace_init();
2535 if((argc > 1) && (!strcmp(argv[1],"recovery"))) {
2536 sdb_device_banner = "recovery";
2541 apply_sdbd_commandline_defaults(&sdbd_commandline_args);
2542 int parse_ret = parse_sdbd_commandline(&sdbd_commandline_args, argc, argv);
2544 // TODO: Add detailed error messages
2545 // TODO: Add individual messages for help and usage
2546 if(parse_ret != SDBD_COMMANDLINE_SUCCESS) {
2547 if (parse_ret == SDBD_COMMANDLINE_HELP
2548 || parse_ret == SDBD_COMMANDLINE_USAGE) {
2549 // User requested help or usage
2550 print_sdbd_usage_message(stdout);
2551 return EXIT_SUCCESS;
2554 // Print usage message because of invalid options
2555 print_sdbd_usage_message(stderr);
2556 return EXIT_FAILURE;
2560 if (daemonize() < 0)
2561 fatal("daemonize() failed: errno:%d", errno);
2564 D("Handling main()\n");
2566 //sdbd will never die on emulator!
2567 signal(SIGTERM, handle_sig_term); /* tizen specific */
2568 return sdb_main(0, DEFAULT_SDB_PORT);