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>
34 #include <sys/smack.h>
41 #include "commandline_sdbd.h"
46 #include "sdbd_plugin.h"
48 #ifdef SUPPORT_ENCRYPT
49 #include "plugin_encrypt.h"
53 #include <linux/prctl.h>
54 #define SDB_PIDPATH "/tmp/.sdbd.pid"
56 #include <system_info.h>
60 #define PROC_CMDLINE_PATH "/proc/cmdline"
61 #define USB_SERIAL_PATH "/sys/class/usb_mode/usb0/iSerial"
62 #define APPID2PID_PATH "/usr/bin/appid2pid"
64 #include <sys/ioctl.h>
66 #include <netinet/in.h>
67 #include <arpa/inet.h>
68 #define GUEST_IP_INTERFACE "eth0"
70 SDB_MUTEX_DEFINE(zone_check_lock);
72 SDB_MUTEX_DEFINE( D_lock );
78 char* g_sdk_home_dir = NULL;
79 char* g_sdk_home_dir_env = NULL;
81 int rootshell_mode; // 0: sdk user, 1: root
82 int booting_done; // 0: platform booting is in progess 1: platform booting is done
89 struct group_info g_default_groups[] = {
90 {"priv_externalstorage", -1},
91 {"priv_externalstorage_appdata", -1},
92 {"priv_mediastorage", -1},
96 #define SDB_DEFAULT_GROUPS_CNT ((sizeof(g_default_groups)/sizeof(g_default_groups[0]))-1)
98 int is_init_sdk_userinfo = 0;
99 int is_pwlocked = 0; // 0 if unlocked, 1 otherwise
102 SdbdCommandlineArgs sdbd_commandline_args;
105 static int is_support_usbproto();
106 static int is_support_sockproto();
108 void (*usb_init)() = NULL;
109 void (*usb_cleanup)() = NULL;
110 int (*usb_write)(usb_handle *h, const void *data, int len) = NULL;
111 int (*usb_read)(usb_handle *h, void *data, size_t len) = NULL;
112 int (*usb_close)(usb_handle *h) = NULL;
113 void (*usb_kick)(usb_handle *h) = NULL;
115 int g_is_emulator = -1;
116 int is_emulator(void) {
120 if (g_is_emulator >= 0) {
121 return g_is_emulator;
123 D("failed to initialize check emulator\n");
126 return sdbd_commandline_args.emulator.host != NULL;
130 int is_appid2pid_supported(void) {
132 if (access(APPID2PID_PATH, F_OK) == 0) {
133 /* It is necessary to confirm that it is possible
134 * to run "appid2pid" in the sdk user/group privileges. */
136 if (stat(APPID2PID_PATH, &st) == 0) {
137 D("appid2pid uid=%d, gid=%d, mode=0x%x.\n", st.st_uid, st.st_gid, st.st_mode);
138 if ( (st.st_uid == STATIC_SDK_USER_ID && st.st_mode & S_IXUSR)
139 || (st.st_gid == STATIC_SDK_GROUP_ID && st.st_mode & S_IXGRP)
140 || (st.st_mode & S_IXOTH) ) {
141 D("appid2pid is supported.\n");
146 D("failed to access appid2pid file: %d\n", errno);
149 D("appid2pid is NOT supported.\n");
153 int is_container_enabled(void) {
156 ret = system_info_get_platform_bool("tizen.org/feature/container", &value);
157 if (ret != SYSTEM_INFO_ERROR_NONE) {
158 D("failed to get container information: %d\n", errno);
161 D("tizen container: %d\n", value);
169 void handle_sig_term(int sig) {
171 if (access(SDB_PIDPATH, F_OK) == 0)
172 sdb_unlink(SDB_PIDPATH);
176 static const char *sdb_device_banner = "device";
178 void fatal(const char *fmt, ...)
182 fprintf(stderr, "error: ");
183 vfprintf(stderr, fmt, ap);
184 fprintf(stderr, "\n");
189 void fatal_errno(const char *fmt, ...)
193 fprintf(stderr, "errno: %d: ", errno);
194 vfprintf(stderr, fmt, ap);
195 fprintf(stderr, "\n");
200 static int is_enable_sdbd_log()
202 return (!strncmp(g_capabilities.log_enable, PLUGIN_RET_ENABLED, strlen(PLUGIN_RET_ENABLED)));
207 /* read a comma/space/colum/semi-column separated list of tags
208 * from the SDB_TRACE environment variable and build the trace
209 * mask from it. note that '1' and 'all' are special cases to
212 void sdb_trace_init(void)
214 const char* p = getenv("SDB_TRACE");
217 static const struct {
223 { "sdb", TRACE_SDB },
224 { "sockets", TRACE_SOCKETS },
225 { "packets", TRACE_PACKETS },
226 { "rwx", TRACE_RWX },
227 { "usb", TRACE_USB },
228 { "sync", TRACE_SYNC },
229 { "sysdeps", TRACE_SYSDEPS },
230 { "transport", TRACE_TRANSPORT },
231 { "jdwp", TRACE_JDWP },
232 { "services", TRACE_SERVICES },
233 { "properties", TRACE_PROPERTIES },
234 { "sdktools", TRACE_SDKTOOLS },
235 { "appcmd", TRACE_APPCMD },
240 if (is_enable_sdbd_log())
246 /* use a comma/column/semi-colum/space separated list */
250 q = strpbrk(p, " ,:;");
256 for (tagn = 0; tags[tagn].tag != NULL; tagn++)
258 int taglen = strlen(tags[tagn].tag);
260 if (len == taglen && !memcmp(tags[tagn].tag, p, len) )
262 int flag = tags[tagn].flag;
267 sdb_trace_mask |= (1 << flag);
279 * Implements SDB tracing inside the emulator.
285 * Redefine open and write for qemu_pipe.h that contains inlined references
286 * to those routines. We will redifine them back after qemu_pipe.h inclusion.
291 #define open sdb_open
292 #define write sdb_write
293 #include "qemu_pipe.h"
296 #define open ___xxx_open
297 #define write ___xxx_write
299 /* A handle to sdb-debug qemud service in the emulator. */
300 int sdb_debug_qemu = -1;
302 /* Initializes connection with the sdb-debug qemud service in the emulator. */
303 #if 0 /* doen't support in Tizen */
304 static int sdb_qemu_trace_init(void)
308 if (sdb_debug_qemu >= 0) {
312 /* sdb debugging QEMUD service connection request. */
313 snprintf(con_name, sizeof(con_name), "qemud:sdb-debug");
314 sdb_debug_qemu = qemu_pipe_open(con_name);
315 return (sdb_debug_qemu >= 0) ? 0 : -1;
318 void sdb_qemu_trace(const char* fmt, ...)
324 if (sdb_debug_qemu >= 0) {
325 vsnprintf(msg, sizeof(msg), fmt, args);
326 sdb_write(sdb_debug_qemu, msg, strlen(msg));
330 #endif /* !SDB_HOST */
332 apacket *get_apacket(void)
334 apacket *p = malloc(sizeof(apacket));
335 if(p == 0) fatal("failed to allocate an apacket");
336 memset(p, 0, sizeof(apacket) - MAX_PAYLOAD);
340 void put_apacket(apacket *p)
348 void handle_online(void)
353 void handle_offline(atransport *t)
356 //Close the associated usb
357 run_transport_disconnects(t);
362 void print_packet(const char *label, apacket *p)
368 switch(p->msg.command){
369 case A_SYNC: tag = "SYNC"; break;
370 case A_CNXN: tag = "CNXN" ; break;
371 case A_OPEN: tag = "OPEN"; break;
372 case A_OKAY: tag = "OKAY"; break;
373 case A_CLSE: tag = "CLSE"; break;
374 case A_WRTE: tag = "WRTE"; break;
375 default: tag = "????"; break;
378 fprintf(stderr, "%s: %s %08x %08x %04x \"",
379 label, tag, p->msg.arg0, p->msg.arg1, p->msg.data_length);
380 count = p->msg.data_length;
382 if(count > DUMPMAX) {
389 if((*x >= ' ') && (*x < 127)) {
396 fprintf(stderr, tag);
400 #ifdef SUPPORT_ENCRYPT
402 desc. : 암호화 실패 메시지 전송
403 parameter : [in] apacket* p : sdbd로 들어온 메시지
404 [in] atransport *t : 현재 연결에 대한 atransport
405 [in] unsigned failed_value : 실패 값
407 void send_encr_fail(apacket* p, atransport *t, unsigned failed_value){
409 enc_p = get_apacket();
410 enc_p->msg.command = A_ENCR; // 암호화 메시지
411 enc_p->msg.arg0 = failed_value; // 실패값
412 enc_p->msg.arg1 = p->msg.arg1;
413 send_packet(enc_p, t);
414 //put_apacket(enc_p);
419 parameter : [in] apacket* p : sdbd로 들어온 메시지
420 [in/out] atransport *t : 현재 연결에 대한 atransport
421 ret : 0 : 정상적으로 메시지 전송
424 int handle_encr_packet(apacket* p, atransport *t){
425 static int sessionID = 0;
427 apacket* enc_p = NULL;
429 if(p->msg.arg0 == ENCR_SET_ON_REQ){ // hello 메시지인 경우
430 t->sessionID = sessionID;
431 if((retVal = security_init(t->sessionID, NULL)) == 1){ // 암호화 handshaking을 위한 init
432 if(security_parse_server_hello(t->sessionID, p) == 1){ // hello 메시지 파싱
433 D("security_parse_server_hello success\n");
434 enc_p = get_apacket();
435 if(security_gen_client_hello(t->sessionID, enc_p) == 1){ // hello 메시지 생성
436 D("security_gen_client_hello success\n");
437 enc_p->msg.command = A_ENCR;
438 enc_p->msg.arg0 = ENCR_SET_ON_REQ;
439 enc_p->msg.arg1 = p->msg.arg1;
441 send_packet(enc_p, t);
443 else { // hello 메시지 생성 실패
444 D("security_gen_client_hello error\n");
445 send_encr_fail(p, t, ENCR_ON_FAIL); // 암호화 on 실패 메시지 전송
446 t->encryption = ENCR_OFF; // 암호화 모드는 off
447 security_deinit(t->sessionID);
451 else{ // hello 메시지 파싱 실패
452 D("security_parse_server_hello error\n");
453 send_encr_fail(p, t, ENCR_ON_FAIL);
454 t->encryption = ENCR_OFF;
455 security_deinit(t->sessionID);
460 D("security_init error\n");
461 send_encr_fail(p, t, ENCR_ON_FAIL);
462 t->encryption = ENCR_OFF;
465 security_deinit(t->sessionID);
467 //here!! do security_deinit(), but when plugin pointer is null -> not deinit
471 else if(p->msg.arg0 == ENCR_SET_ON_OK){ // ack 메시지인 경우
472 if(security_parse_server_ack(t->sessionID, p) == 1){ // ack 메시지 파싱
473 enc_p = get_apacket();
474 if(security_gen_client_ack(t->sessionID, enc_p) == 1){ // ack 메시지 생성
475 D("security_gen_client_ack success\n");
476 enc_p->msg.command = A_ENCR;
477 enc_p->msg.arg0 = ENCR_SET_ON_OK;
478 enc_p->msg.arg1 = p->msg.arg1;
479 t->encryption = ENCR_ON;
480 send_packet(enc_p, t);
482 else { // ack 메시지 생성에 실패한 경우
483 D("security_gen_client_ack error\n");
484 send_encr_fail(p, t, ENCR_ON_FAIL);
485 t->encryption = ENCR_OFF;
486 security_deinit(t->sessionID);
490 else { // ack 메시지 파싱에 실패한 경우
491 D("security_parse_server_ack error\n");
492 send_encr_fail(p, t, ENCR_ON_FAIL);
493 t->encryption = ENCR_OFF;
494 security_deinit(t->sessionID);
498 else if(p->msg.arg0 == ENCR_SET_OFF){ // 암호화 모드 off 요청 메시지
499 if(t->encryption == ENCR_ON && security_deinit(t->sessionID) == 1){ // 현재 암호화 모드가 on 상태인 경우
500 enc_p = get_apacket();
501 t->encryption = ENCR_OFF; // 현재 연결에 대한 암호화 모드 off
502 enc_p->msg.command = A_ENCR;
503 enc_p->msg.arg0 = ENCR_SET_OFF;
504 enc_p->msg.arg1 = p->msg.arg1;
505 send_packet(enc_p, t);
507 else { // 암호화 모드 off에 실패한 경우
508 D("security_deinit error\n");
509 send_encr_fail(p, t, ENCR_OFF_FAIL); // 암호화 모드 off 실패 메시지 전송
513 else if(p->msg.arg0 == ENCR_GET){ // 암호화 모드의 상태 요청 메시지인 경우
514 enc_p = get_apacket();
515 enc_p->msg.command = A_ENCR;
516 enc_p->msg.arg0 = ENCR_GET; // 암호화 모드 status get메시지
517 enc_p->msg.arg1 = p->msg.arg1;
518 if(t->encryption == ENCR_ON){ // 암호화 모드가 on인 경우
519 enc_p->msg.data_length = 13;
520 strncpy((char*)enc_p->data, "encryption:on", enc_p->msg.data_length); // encryption:on 메시지 전송
521 } else if(t->encryption == ENCR_OFF){ // 암호화 모드가 off인 경우
522 enc_p->msg.data_length = 14;
523 strncpy((char*)enc_p->data, "encryption:off", enc_p->msg.data_length); // encryption:off 메시지 전송
525 send_packet(enc_p, t);
527 else if (p->msg.arg0 == ENCR_ON_FAIL) // 암호화 모드를 on 하는 도중 실패한 경우 받는 메시지
529 t->encryption = ENCR_OFF; // 암호화 모드를 다시 off
530 D("encryption on failed\n");
532 else if (p->msg.arg0 == ENCR_OFF_FAIL) // 암호화 모드를 off하는 도중 실패한 경우 받는 메시지
534 //t->encryption = ENCR_ON;
535 D("encryption off failed\n");
537 //put_apacket(enc_p);
544 static void send_ready(unsigned local, unsigned remote, atransport *t)
546 D("Calling send_ready \n");
547 apacket *p = get_apacket();
548 p->msg.command = A_OKAY;
550 p->msg.arg1 = remote;
554 static void send_close(unsigned local, unsigned remote, atransport *t)
556 D("Calling send_close \n");
557 apacket *p = get_apacket();
558 p->msg.command = A_CLSE;
560 p->msg.arg1 = remote;
564 static void send_connect(atransport *t)
566 D("Calling send_connect \n");
567 apacket *cp = get_apacket();
568 cp->msg.command = A_CNXN;
569 cp->msg.arg0 = A_VERSION;
570 #ifdef SUPPORT_ENCRYPT
571 cp->msg.arg1 = MAX_PAYLOAD - 100; // connection 시, sdb server의 패킷 크기를 암호화 오버로드 만큼 줄임
573 cp->msg.arg1 = MAX_PAYLOAD;
575 char device_name[256]={0,};
578 if (request_lock_state_to_plugin(LOCKTYPE_PASSWORD) == 1) {
580 t->connection_state = CS_PWLOCK;
584 r = get_emulator_name(device_name, sizeof device_name);
586 r = get_device_name(device_name, sizeof device_name);
589 snprintf((char*) cp->data, sizeof cp->data, "%s::%s::%d", sdb_device_banner, DEFAULT_DEVICENAME, status);
591 snprintf((char*) cp->data, sizeof cp->data, "%s::%s::%d", sdb_device_banner, device_name, status);
594 D("CNXN data:%s\n", (char*)cp->data);
595 cp->msg.data_length = strlen((char*) cp->data) + 1;
599 /* XXX why sleep here? */
600 // allow the device some time to respond to the connect message
605 void send_device_status()
607 D("broadcast device status\n");
608 apacket* cp = get_apacket();
609 cp->msg.command = A_STAT;
610 cp->msg.arg0 = is_pwlocked;
613 broadcast_transport(cp);
615 //all broadcasted packets are memory copied
616 //so, we should call put_apacket
620 static char *connection_state_name(atransport *t)
626 switch(t->connection_state) {
638 static int get_str_cmdline(char *src, char *dest, char str[], int str_size) {
639 char *s = strstr(src, dest);
643 char *e = strstr(s, " ");
648 int len = e-s-strlen(dest);
650 if (len >= str_size) {
651 D("buffer size(%d) should be bigger than %d\n", str_size, len+1);
655 strncpy(str, s + strlen(dest), len);
660 int get_emulator_forward_port() {
661 SdbdCommandlineArgs *sdbd_args = &sdbd_commandline_args; /* alias */
663 if (sdbd_args->emulator.host == NULL) {
667 return sdbd_args->emulator.port;
670 int get_emulator_name(char str[], int str_size) {
671 SdbdCommandlineArgs *sdbd_args = &sdbd_commandline_args; /* alias */
673 if (sdbd_args->emulator.host == NULL) {
677 s_strncpy(str, sdbd_args->emulator.host, str_size);
681 int get_device_name(char str[], int str_size) {
683 int r = system_info_get_platform_string("http://tizen.org/system/model_name", &value);
684 if (r != SYSTEM_INFO_ERROR_NONE) {
685 D("fail to get system model:%d\n", errno);
688 s_strncpy(str, value, str_size);
689 D("returns model_name:%s\n", value);
696 int fd = unix_open(USB_SERIAL_PATH, O_RDONLY);
698 D("fail to read:%s (%d)\n", USB_SERIAL_PATH, errno);
702 if(read_line(fd, str, str_size)) {
703 D("device serial name: %s\n", str);
712 static int get_cmdline_value(char *split, char str[], int str_size) {
714 int fd = unix_open(PROC_CMDLINE_PATH, O_RDONLY);
717 D("fail to read /proc/cmdline\n");
720 if(read_line(fd, cmdline, sizeof(cmdline))) {
721 D("qemu cmd: %s\n", cmdline);
722 if (get_str_cmdline(cmdline, split, str, str_size) < 1) {
723 D("could not get the (%s) value from cmdline\n", split);
732 int get_emulator_hostip(char str[], int str_size) {
733 return get_cmdline_value("host_ip=", str, str_size);
736 int get_emulator_guestip(char str[], int str_size) {
739 struct sockaddr_in *sin;
741 s = socket(AF_INET, SOCK_DGRAM, 0);
747 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s", GUEST_IP_INTERFACE);
748 if(ioctl(s, SIOCGIFHWADDR, &ifr) < 0) {
749 D("ioctl hwaddr error\n");
754 if(ioctl(s, SIOCGIFADDR, &ifr) < 0) {
755 D("ioctl addr error\n");
759 sin = (struct sockaddr_in *)&ifr.ifr_addr;
760 snprintf(str, str_size, "%s", inet_ntoa(sin->sin_addr));
766 void parse_banner(char *banner, atransport *t)
768 char *type, *product, *end;
770 D("parse_banner: %s\n", banner);
772 product = strchr(type, ':');
779 /* remove trailing ':' */
780 end = strchr(product, ':');
783 /* save product name in device structure */
784 if (t->product == NULL) {
785 t->product = strdup(product);
786 } else if (strcmp(product, t->product) != 0) {
788 t->product = strdup(product);
791 if(!strcmp(type, "bootloader")){
792 D("setting connection_state to CS_BOOTLOADER\n");
793 t->connection_state = CS_BOOTLOADER;
798 if(!strcmp(type, "device")) {
799 D("setting connection_state to CS_DEVICE\n");
800 t->connection_state = CS_DEVICE;
805 if(!strcmp(type, "recovery")) {
806 D("setting connection_state to CS_RECOVERY\n");
807 t->connection_state = CS_RECOVERY;
812 if(!strcmp(type, "sideload")) {
813 D("setting connection_state to CS_SIDELOAD\n");
814 t->connection_state = CS_SIDELOAD;
819 t->connection_state = CS_HOST;
822 static void update_version(atransport *t, int version, size_t payload)
824 #ifdef SUPPORT_ENCRYPT
825 size_t max_payload = MAX_PAYLOAD - 100;
827 size_t max_payload = MAX_PAYLOAD;
829 t->protocol_version = min(version, A_VERSION);
830 t->max_payload = min(payload, max_payload);
831 D("update transport version. version=%x, max_payload=%d\n", t->protocol_version, t->max_payload);
834 void handle_packet(apacket *p, atransport *t)
837 int result = access((const char *) p, F_OK);
838 if ((result == -1) && (errno == EFAULT)) {
839 fatal("Invalid apacket = [0x%p]", p);
844 D("handle_packet() %c%c%c%c\n", ((char*) (&(p->msg.command)))[0],
845 ((char*) (&(p->msg.command)))[1],
846 ((char*) (&(p->msg.command)))[2],
847 ((char*) (&(p->msg.command)))[3]);
849 print_packet("recv", p);
851 switch(p->msg.command){
855 if(HOST) send_connect(t);
857 t->connection_state = CS_OFFLINE;
863 case A_CNXN: /* CONNECT(version, maxdata, "system-id-string") */
864 /* XXX verify version, etc */
865 if(t->connection_state != CS_OFFLINE) {
866 t->connection_state = CS_OFFLINE;
869 update_version(t, p->msg.arg0, p->msg.arg1);
870 parse_banner((char*) p->data, t);
872 if(!HOST) send_connect(t);
875 case A_OPEN: /* OPEN(local-id, 0, "destination") */
876 if (request_lock_state_to_plugin(LOCKTYPE_PASSWORD) == 1 && t->connection_state == CS_PWLOCK) {
877 // in case of already locked before get A_CNXN
878 D("open failed due to password locked before get A_CNXN:%d\n", t->connection_state);
879 send_close(0, p->msg.arg0, t);
881 if(t->connection_state != CS_OFFLINE) {
882 char *name = (char*) p->data;
883 name[p->msg.data_length > 0 ? p->msg.data_length - 1 : 0] = 0;
884 s = create_local_service_socket(name);
886 send_close(0, p->msg.arg0, t);
888 s->peer = create_remote_socket(p->msg.arg0, t);
890 send_ready(s->id, s->peer->id, t);
897 case A_OKAY: /* READY(local-id, remote-id, "") */
898 if(t->connection_state != CS_OFFLINE) {
899 if((s = find_local_socket(p->msg.arg1))) {
901 s->peer = create_remote_socket(p->msg.arg0, t);
909 case A_CLSE: /* CLOSE(local-id, remote-id, "") */
910 if(t->connection_state != CS_OFFLINE) {
911 if((s = find_local_socket(p->msg.arg1))) {
918 if(t->connection_state != CS_OFFLINE) {
919 if((s = find_local_socket(p->msg.arg1))) {
920 unsigned rid = p->msg.arg0;
921 p->len = p->msg.data_length;
923 if(s->enqueue(s, p) == 0) {
924 D("Enqueue the socket\n");
925 send_ready(s->id, rid, t);
931 #ifdef SUPPORT_ENCRYPT
932 case A_ENCR: // 암호화 메시지인 경우
933 if(t->connection_state != CS_OFFLINE) {
934 handle_encr_packet(p, t);
940 printf("handle_packet: what is %08x?!\n", p->msg.command);
946 alistener listener_list = {
947 .next = &listener_list,
948 .prev = &listener_list,
951 static void ss_listener_event_func(int _fd, unsigned ev, void *_l)
956 struct sockaddr addr;
961 fd = sdb_socket_accept(_fd, &addr, &alen);
964 sdb_socket_setbufsize(fd, CHUNK_SIZE);
966 s = create_local_socket(fd);
968 connect_to_smartsocket(s);
976 static void listener_event_func(int _fd, unsigned ev, void *_l)
982 struct sockaddr addr;
987 fd = sdb_socket_accept(_fd, &addr, &alen);
990 s = create_local_socket(fd);
992 s->transport = l->transport;
993 connect_to_remote(s, l->connect_to);
1001 static void free_listener(alistener* l)
1004 l->next->prev = l->prev;
1005 l->prev->next = l->next;
1006 l->next = l->prev = l;
1009 // closes the corresponding fd
1010 fdevent_remove(&l->fde);
1013 free((char*)l->local_name);
1016 free((char*)l->connect_to);
1019 remove_transport_disconnect(l->transport, &l->disconnect);
1024 static void listener_disconnect(void* _l, atransport* t)
1031 int local_name_to_fd(const char *name)
1035 if(!strncmp("tcp:", name, 4)){
1037 port = atoi(name + 4);
1038 ret = socket_loopback_server(port, SOCK_STREAM);
1041 #ifndef HAVE_WIN32_IPC /* no Unix-domain sockets on Win32 */
1042 // It's non-sensical to support the "reserved" space on the sdb host side
1043 if(!strncmp(name, "local:", 6)) {
1044 return socket_local_server(name + 6,
1045 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
1046 } else if(!strncmp(name, "localabstract:", 14)) {
1047 return socket_local_server(name + 14,
1048 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
1049 } else if(!strncmp(name, "localfilesystem:", 16)) {
1050 return socket_local_server(name + 16,
1051 ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
1055 printf("unknown local portname '%s'\n", name);
1059 static int remove_listener(const char *local_name, const char *connect_to, atransport* transport)
1063 for (l = listener_list.next; l != &listener_list; l = l->next) {
1064 if (!strcmp(local_name, l->local_name) &&
1065 !strcmp(connect_to, l->connect_to) &&
1066 l->transport && l->transport == transport) {
1068 listener_disconnect(l, transport);
1076 static int install_listener(const char *local_name, const char *connect_to, atransport* transport)
1080 //printf("install_listener('%s','%s')\n", local_name, connect_to);
1082 for(l = listener_list.next; l != &listener_list; l = l->next){
1083 if(strcmp(local_name, l->local_name) == 0) {
1086 /* can't repurpose a smartsocket */
1087 if(l->connect_to[0] == '*') {
1091 cto = strdup(connect_to);
1096 //printf("rebinding '%s' to '%s'\n", local_name, connect_to);
1097 free((void*) l->connect_to);
1098 l->connect_to = cto;
1099 if (l->transport != transport) {
1100 remove_transport_disconnect(l->transport, &l->disconnect);
1101 l->transport = transport;
1102 add_transport_disconnect(l->transport, &l->disconnect);
1108 if((l = calloc(1, sizeof(alistener))) == 0) goto nomem;
1109 if((l->local_name = strdup(local_name)) == 0) goto nomem;
1110 if((l->connect_to = strdup(connect_to)) == 0) goto nomem;
1113 l->fd = local_name_to_fd(local_name);
1115 free((void*) l->local_name);
1116 free((void*) l->connect_to);
1118 printf("cannot bind '%s'\n", local_name);
1122 if (close_on_exec(l->fd) < 0) {
1123 D("fail to close fd exec:%d\n",l->fd);
1125 if(!strcmp(l->connect_to, "*smartsocket*")) {
1126 fdevent_install(&l->fde, l->fd, ss_listener_event_func, l);
1128 fdevent_install(&l->fde, l->fd, listener_event_func, l);
1130 fdevent_set(&l->fde, FDE_READ);
1132 l->next = &listener_list;
1133 l->prev = listener_list.prev;
1136 l->transport = transport;
1139 l->disconnect.opaque = l;
1140 l->disconnect.func = listener_disconnect;
1141 add_transport_disconnect(transport, &l->disconnect);
1146 fatal("cannot allocate listener");
1150 #ifdef HAVE_WIN32_PROC
1151 static BOOL WINAPI ctrlc_handler(DWORD type)
1153 exit(STATUS_CONTROL_C_EXIT);
1158 static void sdb_cleanup(void)
1160 clear_sdbd_commandline_args(&sdbd_commandline_args);
1162 if (is_support_usbproto()) {
1165 // if(required_pid > 0) {
1166 // kill(required_pid, SIGKILL);
1169 unload_sdbd_plugin();
1172 void start_logging(void)
1174 #ifdef HAVE_WIN32_PROC
1175 char temp[ MAX_PATH ];
1179 GetTempPath( sizeof(temp) - 8, temp );
1180 strcat( temp, "sdb.log" );
1182 /* Win32 specific redirections */
1183 fnul = fopen( "NUL", "rt" );
1187 flog = fopen( temp, "at" );
1191 setvbuf( flog, NULL, _IONBF, 0 );
1193 stdout[0] = flog[0];
1194 stderr[0] = flog[0];
1195 fprintf(stderr,"--- sdb starting (pid %d) ---\n", getpid());
1199 fd = unix_open("/dev/null", O_RDONLY);
1201 // hopefully not gonna happen
1207 fd = unix_open("/tmp/sdb.log", O_WRONLY | O_CREAT | O_APPEND, 0640);
1209 fd = unix_open("/dev/null", O_WRONLY);
1211 // hopefully not gonna happen
1218 fprintf(stderr,"--- sdb starting (pid %d) ---\n", getpid());
1224 void start_device_log(void)
1227 char path[PATH_MAX] = {0, };
1228 char path_folder[PATH_MAX] = {0, };
1229 char path_file[PATH_MAX] = {0, };
1232 // char value[PROPERTY_VALUE_MAX];
1233 const char* p_trace = getenv("SDB_TRACE");
1234 const char* p_path = getenv("SDBD_LOG_PATH");
1235 // read the trace mask from persistent property persist.sdb.trace_mask
1236 // give up if the property is not set or cannot be parsed
1238 if ((p_trace == NULL ) && !is_enable_sdbd_log()) {
1243 snprintf(path_folder, sizeof(path_folder), "%s", p_path);
1244 else if (g_capabilities.log_path[0] != '\0')
1245 snprintf(path_folder, sizeof(path_folder), "%s", g_capabilities.log_path);
1251 localtime_r(&t, &now);
1253 strftime(path_file, sizeof(path_file),
1254 "sdbd-%Y-%m-%d-%H-%M-%S.txt",
1257 snprintf(path, sizeof(path), "%s/%s", path_folder, path_file);
1259 fd = unix_open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1264 if (smack_setlabel(path, SDK_SHELL_LABEL_NAME, SMACK_LABEL_ACCESS) == -1) {
1265 D("unable to set sdk shell smack label %s due to (errno:%d)\n", SDK_SHELL_LABEL_NAME, errno);
1268 // redirect stdout and stderr to the log file
1271 fprintf(stderr,"--- sdbd starting (pid %d) ---\n", getpid());
1274 fd = unix_open("/dev/null", O_RDONLY);
1276 // hopefully not gonna happen
1283 int daemonize(void) {
1285 // set file creation mask to 0
1297 FILE *f = fopen(SDB_PIDPATH, "w");
1300 fprintf(f, "%d\n", getpid());
1308 D("sdbd: unable to change working directory to /\n");
1315 int launch_server(int server_port)
1317 #ifdef HAVE_WIN32_PROC
1318 /* we need to start the server in the background */
1319 /* we create a PIPE that will be used to wait for the server's "OK" */
1320 /* message since the pipe handles must be inheritable, we use a */
1321 /* security attribute */
1322 HANDLE pipe_read, pipe_write;
1323 SECURITY_ATTRIBUTES sa;
1324 STARTUPINFO startup;
1325 PROCESS_INFORMATION pinfo;
1326 char program_path[ MAX_PATH ];
1329 sa.nLength = sizeof(sa);
1330 sa.lpSecurityDescriptor = NULL;
1331 sa.bInheritHandle = TRUE;
1333 /* create pipe, and ensure its read handle isn't inheritable */
1334 ret = CreatePipe( &pipe_read, &pipe_write, &sa, 0 );
1336 fprintf(stderr, "CreatePipe() failure, error %ld\n", GetLastError() );
1340 SetHandleInformation( pipe_read, HANDLE_FLAG_INHERIT, 0 );
1342 ZeroMemory( &startup, sizeof(startup) );
1343 startup.cb = sizeof(startup);
1344 startup.hStdInput = GetStdHandle( STD_INPUT_HANDLE );
1345 startup.hStdOutput = pipe_write;
1346 startup.hStdError = GetStdHandle( STD_ERROR_HANDLE );
1347 startup.dwFlags = STARTF_USESTDHANDLES;
1349 ZeroMemory( &pinfo, sizeof(pinfo) );
1351 /* get path of current program */
1352 GetModuleFileName( NULL, program_path, sizeof(program_path) );
1354 ret = CreateProcess(
1355 program_path, /* program path */
1356 "sdb fork-server server",
1357 /* the fork-server argument will set the
1358 debug = 2 in the child */
1359 NULL, /* process handle is not inheritable */
1360 NULL, /* thread handle is not inheritable */
1361 TRUE, /* yes, inherit some handles */
1362 DETACHED_PROCESS, /* the new process doesn't have a console */
1363 NULL, /* use parent's environment block */
1364 NULL, /* use parent's starting directory */
1365 &startup, /* startup info, i.e. std handles */
1368 CloseHandle( pipe_write );
1371 fprintf(stderr, "CreateProcess failure, error %ld\n", GetLastError() );
1372 CloseHandle( pipe_read );
1376 CloseHandle( pinfo.hProcess );
1377 CloseHandle( pinfo.hThread );
1379 /* wait for the "OK\n" message */
1384 ret = ReadFile( pipe_read, temp, 3, &count, NULL );
1385 CloseHandle( pipe_read );
1387 fprintf(stderr, "could not read ok from SDB Server, error = %ld\n", GetLastError() );
1390 if (count != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
1391 fprintf(stderr, "SDB server didn't ACK\n" );
1395 #elif defined(HAVE_FORKEXEC)
1396 char path[PATH_MAX];
1399 // set up a pipe so the child can tell us when it is ready.
1400 // fd[0] will be parent's end, and fd[1] will get mapped to stderr in the child.
1402 fprintf(stderr, "pipe failed in launch_server, errno: %d\n", errno);
1405 get_my_path(path, PATH_MAX);
1407 if(pid < 0) return -1;
1410 // child side of the fork
1412 // redirect stderr to the pipe
1413 // we use stderr instead of stdout due to stdout's buffering behavior.
1415 dup2(fd[1], STDERR_FILENO);
1419 int result = execl(path, "sdb", "fork-server", "server", NULL);
1420 // this should not return
1421 fprintf(stderr, "OOPS! execl returned %d, errno: %d\n", result, errno);
1423 // parent side of the fork
1427 temp[0] = 'A'; temp[1] = 'B'; temp[2] = 'C';
1428 // wait for the "OK\n" message
1430 int ret = sdb_read(fd[0], temp, 3);
1431 int saved_errno = errno;
1434 fprintf(stderr, "could not read ok from SDB Server, errno = %d\n", saved_errno);
1437 if (ret != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
1438 fprintf(stderr, "SDB server didn't ACK\n" );
1445 #error "cannot implement background server start on this platform"
1451 /* Constructs a local name of form tcp:port.
1452 * target_str points to the target string, it's content will be overwritten.
1453 * target_size is the capacity of the target string.
1454 * server_port is the port number to use for the local name.
1456 void build_local_name(char* target_str, size_t target_size, int server_port)
1458 snprintf(target_str, target_size, "tcp:%d", server_port);
1462 static void init_drop_privileges() {
1463 #ifdef _DROP_PRIVILEGE
1470 int should_drop_privileges() {
1471 if (rootshell_mode == 1) { // if root, then don't drop
1477 #include <dbus/dbus.h>
1478 #include <dbus/dbus-glib.h>
1479 #include <dbus/dbus-glib-lowlevel.h>
1481 #define BOOTING_DONE_SIGNAL "BootingDone"
1482 #define DEVICED_CORE_INTERFACE "org.tizen.system.deviced.core"
1483 #define SDBD_BOOT_INFO_FILE "/tmp/sdbd_boot_info"
1485 static DBusHandlerResult __sdbd_dbus_signal_filter(DBusConnection *conn,
1486 DBusMessage *message, void *user_data) {
1487 D("got dbus message\n");
1488 const char *interface;
1491 dbus_error_init(&error);
1493 interface = dbus_message_get_interface(message);
1494 if (interface == NULL) {
1495 D("reject by security issue - no interface\n");
1496 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1499 if (dbus_message_is_signal(message, DEVICED_CORE_INTERFACE,
1500 BOOTING_DONE_SIGNAL)) {
1502 if (access(SDBD_BOOT_INFO_FILE, F_OK) == 0) {
1503 D("booting is done before\n");
1505 FILE *f = fopen(SDBD_BOOT_INFO_FILE, "w");
1507 fprintf(f, "%d", 1);
1511 D("booting is done\n");
1514 D("handled dbus message\n");
1515 return DBUS_HANDLER_RESULT_HANDLED;
1518 static void *bootdone_cb(void *x) {
1519 int MAX_LOCAL_BUFSZ = 128;
1521 DBusConnection *bus;
1522 char rule[MAX_LOCAL_BUFSZ];
1523 GMainLoop *mainloop;
1525 /* g_type_init() is deprecated for glib version 2.35.0 or greater, */
1526 #if !GLIB_CHECK_VERSION(2,35,0)
1530 dbus_error_init(&error);
1531 bus = dbus_bus_get(DBUS_BUS_SYSTEM, &error);
1533 D("Failed to connect to the D-BUS daemon: %s", error.message);
1534 dbus_error_free(&error);
1537 dbus_connection_setup_with_g_main(bus, NULL);
1539 snprintf(rule, MAX_LOCAL_BUFSZ, "type='signal',interface='%s'",
1540 DEVICED_CORE_INTERFACE);
1541 /* listening to messages */
1542 dbus_bus_add_match(bus, rule, &error);
1543 if (dbus_error_is_set(&error)) {
1544 D("Fail to rule set: %s", error.message);
1545 dbus_error_free(&error);
1549 if (dbus_connection_add_filter(bus, __sdbd_dbus_signal_filter, NULL, NULL)
1553 D("booting signal initialized\n");
1554 mainloop = g_main_loop_new(NULL, FALSE);
1555 g_main_loop_run(mainloop);
1557 D("dbus loop exited");
1562 void register_bootdone_cb() {
1563 D("registerd bootdone callback\n");
1566 if (sdb_thread_create(&t, bootdone_cb, NULL)) {
1567 D("cannot create service thread\n");
1572 static int sdbd_set_groups() {
1573 gid_t *group_ids = NULL;
1576 int group_match = 0;
1577 int added_group_cnt = 0;
1579 getgrouplist(SDK_USER_NAME, g_sdk_group_id, NULL, &ngroups);
1580 D("group list : ngroups = %d\n", ngroups);
1581 group_ids = malloc((ngroups + SDB_DEFAULT_GROUPS_CNT) * sizeof(gid_t));
1582 if (group_ids == NULL) {
1583 D("failed to allocate group_ids(%d)\n", (ngroups + SDB_DEFAULT_GROUPS_CNT) * sizeof(gid_t));
1586 if (getgrouplist(SDK_USER_NAME, g_sdk_group_id, group_ids, &ngroups) == -1) {
1587 D("failed to getgrouplist(), ngroups = %d\n", ngroups);
1592 for (i = 0; g_default_groups[i].name != NULL; i++) {
1593 for (j = 0; j < ngroups; j++) {
1594 if (group_ids[j] == g_default_groups[i].gid) {
1599 if (group_match == 0 && g_default_groups[i].gid != -1) {
1600 group_ids[ngroups + added_group_cnt] = g_default_groups[i].gid;
1606 if (setgroups(ngroups+added_group_cnt, group_ids) != 0) {
1607 D("failed to setgroups().\n");
1616 static int sdbd_get_user_pwd(const char* user_name, struct passwd* pwd, char* buf, size_t bufsize) {
1617 struct passwd *result = NULL;
1620 ret = getpwnam_r(user_name, pwd, buf, bufsize, &result);
1621 if (result == NULL) {
1623 D("Not found passwd : username(%s)\n", user_name);
1626 D("failed to getpwnam_r\n");
1634 static int sdbd_get_group(const char* group_name, struct group* grp, char* buf, size_t bufsize) {
1635 struct group *result = NULL;
1638 ret = getgrnam_r(group_name, grp, buf, bufsize, &result);
1639 if (result == NULL) {
1641 D("Not found group : groupname(%s)\n", group_name);
1644 D("failed to getgrnam_r\n");
1652 int set_sdk_user_privileges() {
1653 if (!is_init_sdk_userinfo) {
1654 D("failed to init sdk user information.\n");
1658 if (sdbd_set_groups() < 0) {
1659 D("set groups failed (errno: %d)\n", errno);
1663 if (setgid(g_sdk_group_id) != 0) {
1664 D("set group id failed (errno: %d)\n", errno);
1668 if (setuid(g_sdk_user_id) != 0) {
1669 D("set user id failed (errno: %d)\n", errno);
1673 if (chdir(g_sdk_home_dir) < 0) {
1674 D("unable to change working directory to %s\n", g_sdk_home_dir);
1677 // TODO: use pam later
1678 if (g_sdk_home_dir_env) {
1679 putenv(g_sdk_home_dir_env);
1685 #define SDB_PW_GR_DEFAULT_SIZE (16*1024)
1686 static long get_passwd_bufsize() {
1689 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
1691 bufsize = SDB_PW_GR_DEFAULT_SIZE;
1697 static long get_group_bufsize() {
1700 bufsize = sysconf(_SC_GETGR_R_SIZE_MAX);
1702 bufsize = SDB_PW_GR_DEFAULT_SIZE;
1708 static int init_sdb_default_groups() {
1714 bufsize = get_group_bufsize();
1715 buf = malloc(bufsize);
1717 D("failed to allocate gruop buf(%ld)\n", bufsize);
1721 for (i = 0; g_default_groups[i].name != NULL; i++) {
1722 memset(buf, 0, bufsize);
1723 if (sdbd_get_group(g_default_groups[i].name, &grp, buf, bufsize) == 0) {
1724 g_default_groups[i].gid = grp.gr_gid;
1726 D("failed get group info.(errno: %d)\n", errno);
1734 static void set_static_userinfo() {
1735 g_sdk_user_id = STATIC_SDK_USER_ID;
1736 g_sdk_group_id = STATIC_SDK_GROUP_ID;
1737 g_sdk_home_dir = STATIC_SDK_HOME_DIR;
1740 static int init_sdk_userinfo() {
1745 if (is_init_sdk_userinfo) {
1749 if (init_sdb_default_groups() < 0) {
1750 D("failed to initialize default groups.\n");
1753 bufsize = get_passwd_bufsize();
1754 buf = malloc(bufsize);
1756 D("failed to allocate passwd buf(%ld)\n", bufsize);
1757 set_static_userinfo();
1759 if (sdbd_get_user_pwd(SDK_USER_NAME, &pwd, buf, bufsize) < 0) {
1760 D("get user passwd info.(errno: %d)\n", errno);
1761 set_static_userinfo();
1763 D("username=%s, uid=%d, gid=%d, dir=%s\n", pwd.pw_name, pwd.pw_uid, pwd.pw_gid, pwd.pw_dir);
1765 g_sdk_user_id = pwd.pw_uid;
1766 g_sdk_group_id = pwd.pw_gid;
1767 g_sdk_home_dir = strdup(pwd.pw_dir);
1772 int env_size = strlen("HOME=") + strlen(g_sdk_home_dir) + 1;
1773 g_sdk_home_dir_env = malloc(env_size);
1774 if(g_sdk_home_dir_env == NULL) {
1775 D("failed to allocate for home dir env string\n");
1777 snprintf(g_sdk_home_dir_env, env_size, "HOME=%s", g_sdk_home_dir);
1780 is_init_sdk_userinfo = 1;
1784 static void init_sdk_requirements() {
1787 // set env variable for temporary
1788 // TODO: should use pam instead later!!
1789 if (!getenv("TERM")) {
1790 putenv("TERM=linux");
1793 if (!getenv("HOME")) {
1794 putenv("HOME=/root");
1797 init_sdk_userinfo();
1799 if (g_sdk_home_dir != NULL && stat(g_sdk_home_dir, &st) == 0) {
1800 if (st.st_uid != g_sdk_user_id || st.st_gid != g_sdk_group_id) {
1802 snprintf(cmd, sizeof(cmd), "chown %s:%s %s -R", SDK_USER_NAME, SDK_USER_NAME, g_sdk_home_dir);
1803 if (system(cmd) < 0) {
1804 D("failed to change ownership to sdk user to %s\n", g_sdk_home_dir);
1809 if (is_emulator()) {
1810 register_bootdone_cb();
1813 #endif /* !SDB_HOST */
1815 static void init_capabilities(void) {
1819 memset(&g_capabilities, 0, sizeof(g_capabilities));
1821 // CPU Architecture of model
1822 ret = system_info_get_platform_string("http://tizen.org/feature/platform.core.cpu.arch", &value);
1823 if (ret != SYSTEM_INFO_ERROR_NONE) {
1824 snprintf(g_capabilities.cpu_arch, sizeof(g_capabilities.cpu_arch),
1826 D("fail to get the CPU architecture of model:%d\n", errno);
1828 snprintf(g_capabilities.cpu_arch, sizeof(g_capabilities.cpu_arch),
1830 if (value != NULL) {
1836 // Secure protocol support
1837 if(!request_capability_to_plugin(CAPABILITY_SECURE, g_capabilities.secure_protocol,
1838 sizeof(g_capabilities.secure_protocol))) {
1839 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_SECURE);
1840 snprintf(g_capabilities.secure_protocol, sizeof(g_capabilities.secure_protocol),
1845 // Interactive shell support
1846 if(!request_capability_to_plugin(CAPABILITY_INTER_SHELL, g_capabilities.intershell_support,
1847 sizeof(g_capabilities.intershell_support))) {
1848 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_INTER_SHELL);
1849 snprintf(g_capabilities.intershell_support, sizeof(g_capabilities.intershell_support),
1854 // File push/pull support
1855 if(!request_capability_to_plugin(CAPABILITY_FILESYNC, g_capabilities.filesync_support,
1856 sizeof(g_capabilities.filesync_support))) {
1857 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_FILESYNC);
1858 snprintf(g_capabilities.filesync_support, sizeof(g_capabilities.filesync_support),
1863 // USB protocol support
1864 if(!request_capability_to_plugin(CAPABILITY_USB_PROTOCOL, g_capabilities.usbproto_support,
1865 sizeof(g_capabilities.usbproto_support))) {
1866 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_USB_PROTOCOL);
1867 snprintf(g_capabilities.usbproto_support, sizeof(g_capabilities.usbproto_support),
1872 // Socket protocol support
1873 if(!request_capability_to_plugin(CAPABILITY_SOCK_PROTOCOL, g_capabilities.sockproto_support,
1874 sizeof(g_capabilities.sockproto_support))) {
1875 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_SOCK_PROTOCOL);
1876 snprintf(g_capabilities.sockproto_support, sizeof(g_capabilities.sockproto_support),
1881 // Root command support
1882 if(!request_capability_to_plugin(CAPABILITY_ROOT_ONOFF, g_capabilities.rootonoff_support,
1883 sizeof(g_capabilities.rootonoff_support))) {
1884 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_ROOT_ONOFF);
1885 snprintf(g_capabilities.rootonoff_support, sizeof(g_capabilities.rootonoff_support),
1890 // Encryption support
1891 if(!request_capability_to_plugin(CAPABILITY_ENCRYPTION, g_capabilities.encryption_support,
1892 sizeof(g_capabilities.encryption_support))) {
1893 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_ENCRYPTION);
1894 snprintf(g_capabilities.encryption_support, sizeof(g_capabilities.encryption_support),
1900 ret = is_container_enabled();
1901 snprintf(g_capabilities.zone_support, sizeof(g_capabilities.zone_support),
1902 "%s", ret == 1 ? ENABLED : DISABLED);
1904 // Multi-User support
1905 // XXX: There is no clear way to determine whether multi-user support.
1906 // Since TZ_SYS_DEFAULT_USER is set to "owner" for multi-user support,
1907 // guess whether multiuser support through that information.
1908 const char* sys_default_user = tzplatform_getenv(TZ_SYS_DEFAULT_USER);
1909 if (sys_default_user != NULL && !strcmp(sys_default_user, "owner")) {
1910 snprintf(g_capabilities.multiuser_support, sizeof(g_capabilities.multiuser_support),
1913 snprintf(g_capabilities.multiuser_support, sizeof(g_capabilities.multiuser_support),
1917 // Window size synchronization support
1918 snprintf(g_capabilities.syncwinsz_support, sizeof(g_capabilities.syncwinsz_support),
1922 if (SDK_TOOL_PATH == NULL) {
1923 D("fail to get SDK tool path.\n");
1924 snprintf(g_capabilities.sdk_toolpath, sizeof(g_capabilities.sdk_toolpath),
1927 snprintf(g_capabilities.sdk_toolpath, sizeof(g_capabilities.sdk_toolpath),
1928 "%s", SDK_TOOL_PATH);
1932 ret = system_info_get_platform_string("http://tizen.org/feature/profile", &value);
1933 if (ret != SYSTEM_INFO_ERROR_NONE) {
1934 snprintf(g_capabilities.profile_name, sizeof(g_capabilities.profile_name),
1936 D("fail to get profile name:%d\n", errno);
1938 snprintf(g_capabilities.profile_name, sizeof(g_capabilities.profile_name),
1940 if (value != NULL) {
1947 ret = system_info_get_platform_string("http://tizen.org/system/manufacturer", &value);
1948 if (ret != SYSTEM_INFO_ERROR_NONE) {
1949 snprintf(g_capabilities.vendor_name, sizeof(g_capabilities.vendor_name),
1951 D("fail to get the Vendor name:%d\n", errno);
1953 snprintf(g_capabilities.vendor_name, sizeof(g_capabilities.vendor_name),
1955 if (value != NULL) {
1961 // Target name of the launch possible
1962 if(!request_capability_to_plugin(CAPABILITY_CAN_LAUNCH, g_capabilities.can_launch,
1963 sizeof(g_capabilities.can_launch))) {
1964 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_CAN_LAUNCH);
1965 snprintf(g_capabilities.can_launch, sizeof(g_capabilities.can_launch),
1971 ret = system_info_get_platform_string("http://tizen.org/feature/platform.version", &value);
1972 if (ret != SYSTEM_INFO_ERROR_NONE) {
1973 snprintf(g_capabilities.platform_version, sizeof(g_capabilities.platform_version),
1975 D("fail to get platform version:%d\n", errno);
1977 snprintf(g_capabilities.platform_version, sizeof(g_capabilities.platform_version),
1979 if (value != NULL) {
1986 if(!request_capability_to_plugin(CAPABILITY_PRODUCT_VER, g_capabilities.product_version,
1987 sizeof(g_capabilities.product_version))) {
1988 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_PRODUCT_VER);
1989 snprintf(g_capabilities.product_version, sizeof(g_capabilities.product_version),
1995 snprintf(g_capabilities.sdbd_version, sizeof(g_capabilities.sdbd_version),
1996 "%d.%d.%d", SDB_VERSION_MAJOR, SDB_VERSION_MINOR, SDB_VERSION_PATCH);
1999 // Sdbd plugin version
2000 if(!request_capability_to_plugin(CAPABILITY_PLUGIN_VER, g_capabilities.sdbd_plugin_version,
2001 sizeof(g_capabilities.sdbd_plugin_version))) {
2002 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_PLUGIN_VER);
2003 snprintf(g_capabilities.sdbd_plugin_version, sizeof(g_capabilities.sdbd_plugin_version),
2009 if(!request_capability_to_plugin(CAPABILITY_LOG_ENABLE, g_capabilities.log_enable,
2010 sizeof(g_capabilities.log_enable))) {
2011 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_LOG_ENABLE);
2012 snprintf(g_capabilities.log_enable, sizeof(g_capabilities.log_enable),
2017 if(!request_capability_to_plugin(CAPABILITY_LOG_PATH, g_capabilities.log_path,
2018 sizeof(g_capabilities.log_path))) {
2019 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_LOG_PATH);
2020 snprintf(g_capabilities.log_path, sizeof(g_capabilities.log_path),
2024 // Application command support
2025 if(!request_capability_to_plugin(CAPABILITY_APPCMD, g_capabilities.appcmd_support,
2026 sizeof(g_capabilities.appcmd_support))) {
2027 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_APPCMD);
2028 snprintf(g_capabilities.appcmd_support, sizeof(g_capabilities.appcmd_support),
2032 // appid2pid support
2033 ret = is_appid2pid_supported();
2034 snprintf(g_capabilities.appid2pid_support, sizeof(g_capabilities.appid2pid_support),
2035 "%s", ret == 1 ? ENABLED : DISABLED);
2038 // pkgcmd debug mode support
2039 snprintf(g_capabilities.pkgcmd_debugmode, sizeof(g_capabilities.pkgcmd_debugmode),
2043 // Capability version
2044 snprintf(g_capabilities.sdbd_cap_version, sizeof(g_capabilities.sdbd_cap_version),
2045 "%d.%d", SDBD_CAP_VERSION_MAJOR, SDBD_CAP_VERSION_MINOR);
2048 static int is_support_usbproto()
2050 return (!strncmp(g_capabilities.usbproto_support, PLUGIN_RET_ENABLED, strlen(PLUGIN_RET_ENABLED)));
2053 static int is_support_sockproto()
2055 return (!strncmp(g_capabilities.sockproto_support, PLUGIN_RET_ENABLED, strlen(PLUGIN_RET_ENABLED)));
2058 #define EMULATOR_MODEL_NAME "Emulator"
2059 static void check_emulator_or_device()
2061 char model_name[256]={0,};
2064 // Get the model name from model_config.xml
2065 ret = get_device_name(model_name, sizeof model_name);
2067 if(!strncmp(model_name, EMULATOR_MODEL_NAME, sizeof(EMULATOR_MODEL_NAME))){
2069 D("This target type is Emulator\n");
2072 D("This target type is Device\n");
2076 D("failed to get the model name.\n");
2080 static void fork_prepare_handler(void)
2082 sdb_mutex_lock(&D_lock);
2085 static void fork_parent_handler(void)
2087 sdb_mutex_unlock(&D_lock);
2090 static void fork_child_handler(void)
2092 sdb_mutex_unlock(&D_lock);
2095 int sdb_main(int is_daemon, int server_port)
2098 check_emulator_or_device();
2102 init_capabilities();
2107 init_drop_privileges();
2108 init_sdk_requirements();
2109 if (!request_validity_to_plugin(PLUGIN_SYNC_CMD_VERIFY_LAUNCH, NULL)) {
2110 D("sdbd should be launched in develop mode.\n");
2116 pthread_atfork(fork_prepare_handler, fork_parent_handler, fork_child_handler);
2119 atexit(sdb_cleanup);
2120 #ifdef HAVE_WIN32_PROC
2121 SetConsoleCtrlHandler( ctrlc_handler, TRUE );
2122 #elif defined(HAVE_FORKEXEC)
2123 // No SIGCHLD. Let the service subproc handle its children.
2124 signal(SIGPIPE, SIG_IGN);
2127 init_transport_registration();
2133 local_init(DEFAULT_SDB_LOCAL_TRANSPORT_PORT);
2135 char local_name[30];
2136 build_local_name(local_name, sizeof(local_name), server_port);
2137 if(install_listener(local_name, "*smartsocket*", NULL)) {
2141 /* don't listen on a port (default 5037) if running in secure mode */
2142 /* don't run as root if we are running in secure mode */
2144 if (should_drop_privileges()) {
2146 struct __user_cap_header_struct header;
2147 struct __user_cap_data_struct cap;
2149 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
2152 /* add extra groups:
2153 ** SID_TTY to access /dev/ptmx
2155 gid_t groups[] = { SID_TTY, SID_APP_LOGGING, SID_SYS_LOGGING };
2156 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
2159 /* then switch user and group to "developer" */
2160 if (setgid(GID_DEVELOPER) != 0) {
2161 fprintf(stderr, "set group id failed errno: %d\n", errno);
2164 if (setuid(SID_DEVELOPER) != 0) {
2165 fprintf(stderr, "set user id failed errno: %d\n", errno);
2169 /* set CAP_SYS_BOOT capability, so "sdb reboot" will succeed */
2170 header.version = _LINUX_CAPABILITY_VERSION;
2172 cap.effective = cap.permitted = (1 << CAP_SYS_BOOT);
2173 cap.inheritable = 0;
2174 capset(&header, &cap);
2176 D("Local port disabled\n");
2178 char local_name[30];
2179 build_local_name(local_name, sizeof(local_name), server_port);
2180 if(install_listener(local_name, "*smartsocket*", NULL)) {
2185 /* choose the usb gadget backend */
2186 if (access(USB_NODE_FILE, F_OK) == 0) {
2187 /* legacy kernel-based sdb gadget */
2188 usb_init = &linux_usb_init;
2189 usb_cleanup = &linux_usb_cleanup;
2190 usb_write = &linux_usb_write;
2191 usb_read = &linux_usb_read;
2192 usb_close = &linux_usb_close;
2193 usb_kick = &linux_usb_kick;
2195 /* functionfs based gadget */
2196 usb_init = &ffs_usb_init;
2197 usb_cleanup = &ffs_usb_cleanup;
2198 usb_write = &ffs_usb_write;
2199 usb_read = &ffs_usb_read;
2200 usb_close = &ffs_usb_close;
2201 usb_kick = &ffs_usb_kick;
2204 if (is_support_usbproto()) {
2208 if (is_support_sockproto()) {
2209 /* by default don't listen on local transport but
2210 * listen if suitable command line argument has been provided */
2211 if (sdbd_commandline_args.sdbd_port >= 0) {
2212 local_init(sdbd_commandline_args.sdbd_port);
2214 local_init(DEFAULT_SDB_LOCAL_TRANSPORT_PORT);
2218 #if 0 /* tizen specific */
2219 D("sdb_main(): pre init_jdwp()\n");
2221 D("sdb_main(): post init_jdwp()\n");
2227 // inform our parent that we are up and running.
2228 #ifdef HAVE_WIN32_PROC
2230 WriteFile( GetStdHandle( STD_OUTPUT_HANDLE ), "OK\n", 3, &count, NULL );
2231 #elif defined(HAVE_FORKEXEC)
2232 fprintf(stderr, "OK\n");
2237 D("Event loop starting\n");
2241 if (is_support_usbproto()) {
2249 void connect_device(char* host, char* buffer, int buffer_size)
2252 char* portstr = strchr(host, ':');
2256 s_strncpy(hostbuf, host, sizeof(hostbuf) - 1);
2258 if (portstr - host >= sizeof(hostbuf)) {
2259 snprintf(buffer, buffer_size, "bad host name %s", host);
2262 // zero terminate the host at the point we found the colon
2263 hostbuf[portstr - host] = 0;
2264 if (sscanf(portstr + 1, "%d", &port) == 0) {
2265 snprintf(buffer, buffer_size, "bad port number %s", portstr);
2269 port = DEFAULT_SDB_LOCAL_TRANSPORT_PORT;
2272 snprintf(serial, sizeof(serial), "%s:%d", hostbuf, port);
2273 if (find_transport(serial)) {
2274 snprintf(buffer, buffer_size, "already connected to %s", serial);
2278 fd = socket_network_client(hostbuf, port, SOCK_STREAM);
2280 snprintf(buffer, buffer_size, "unable to connect to %s", host);
2284 D("client: connected on remote on fd %d\n", fd);
2286 disable_tcp_nagle(fd);
2287 register_socket_transport(fd, serial, port, 0, NULL);
2288 snprintf(buffer, buffer_size, "connected to %s", serial);
2291 void connect_emulator(char* port_spec, char* buffer, int buffer_size)
2293 char* port_separator = strchr(port_spec, ',');
2294 if (!port_separator) {
2295 snprintf(buffer, buffer_size,
2296 "unable to parse '%s' as <console port>,<sdb port>",
2301 // Zero-terminate console port and make port_separator point to 2nd port.
2302 *port_separator++ = 0;
2303 int console_port = strtol(port_spec, NULL, 0);
2304 int sdb_port = strtol(port_separator, NULL, 0);
2305 if (!(console_port > 0 && sdb_port > 0)) {
2306 *(port_separator - 1) = ',';
2307 snprintf(buffer, buffer_size,
2308 "Invalid port numbers: Expected positive numbers, got '%s'",
2313 /* Check if the emulator is already known.
2314 * Note: There's a small but harmless race condition here: An emulator not
2315 * present just yet could be registered by another invocation right
2316 * after doing this check here. However, local_connect protects
2317 * against double-registration too. From here, a better error message
2318 * can be produced. In the case of the race condition, the very specific
2319 * error message won't be shown, but the data doesn't get corrupted. */
2320 atransport* known_emulator = find_emulator_transport_by_sdb_port(sdb_port);
2321 if (known_emulator != NULL) {
2322 snprintf(buffer, buffer_size,
2323 "Emulator on port %d already registered.", sdb_port);
2327 /* Check if more emulators can be registered. Similar unproblematic
2328 * race condition as above. */
2329 int candidate_slot = get_available_local_transport_index();
2330 if (candidate_slot < 0) {
2331 snprintf(buffer, buffer_size, "Cannot accept more emulators.");
2335 /* Preconditions met, try to connect to the emulator. */
2336 if (!local_connect_arbitrary_ports(console_port, sdb_port, NULL)) {
2337 snprintf(buffer, buffer_size,
2338 "Connected to emulator on ports %d,%d", console_port, sdb_port);
2340 snprintf(buffer, buffer_size,
2341 "Could not connect to emulator on ports %d,%d",
2342 console_port, sdb_port);
2347 int copy_packet(apacket* dest, apacket* src) {
2350 D("dest packet is NULL\n");
2355 D("src packet is NULL\n");
2359 dest->next = src->next;
2360 dest->ptr = src->ptr;
2361 dest->len = src->len;
2363 int data_length = src->msg.data_length;
2364 if(data_length > MAX_PAYLOAD) {
2365 data_length = MAX_PAYLOAD;
2367 memcpy(&(dest->msg), &(src->msg), sizeof(amessage) + data_length);
2372 int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s)
2374 atransport *transport = NULL;
2377 if(!strcmp(service, "kill")) {
2378 fprintf(stderr,"sdb server killed by remote request\n");
2380 sdb_write(reply_fd, "OKAY", 4);
2381 if (is_support_usbproto()) {
2388 // "transport:" is used for switching transport with a specified serial number
2389 // "transport-usb:" is used for switching transport to the only USB transport
2390 // "transport-local:" is used for switching transport to the only local transport
2391 // "transport-any:" is used for switching transport to the only transport
2392 if (!strncmp(service, "transport", strlen("transport"))) {
2393 char* error_string = "unknown failure";
2394 transport_type type = kTransportAny;
2396 if (!strncmp(service, "transport-usb", strlen("transport-usb"))) {
2397 type = kTransportUsb;
2398 } else if (!strncmp(service, "transport-local", strlen("transport-local"))) {
2399 type = kTransportLocal;
2400 } else if (!strncmp(service, "transport-any", strlen("transport-any"))) {
2401 type = kTransportAny;
2402 } else if (!strncmp(service, "transport:", strlen("transport:"))) {
2403 service += strlen("transport:");
2407 transport = acquire_one_transport(CS_ANY, type, serial, &error_string);
2410 s->transport = transport;
2411 sdb_write(reply_fd, "OKAY", 4);
2413 sendfailmsg(reply_fd, error_string);
2418 // return a list of all connected devices
2419 if (!strcmp(service, "devices")) {
2421 memset(buf, 0, sizeof(buf));
2422 memset(buffer, 0, sizeof(buffer));
2423 D("Getting device list \n");
2424 list_transports(buffer, sizeof(buffer));
2425 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer),buffer);
2426 D("Wrote device list \n");
2427 writex(reply_fd, buf, strlen(buf));
2431 // add a new TCP transport, device or emulator
2432 if (!strncmp(service, "connect:", 8)) {
2434 char* host = service + 8;
2435 if (!strncmp(host, "emu:", 4)) {
2436 connect_emulator(host + 4, buffer, sizeof(buffer));
2438 connect_device(host, buffer, sizeof(buffer));
2440 // Send response for emulator and device
2441 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
2442 writex(reply_fd, buf, strlen(buf));
2446 // remove TCP transport
2447 if (!strncmp(service, "disconnect:", 11)) {
2449 memset(buffer, 0, sizeof(buffer));
2450 char* serial = service + 11;
2451 if (serial[0] == 0) {
2452 // disconnect from all TCP devices
2453 unregister_all_tcp_transports();
2456 // assume port 26101 if no port is specified
2457 if (!strchr(serial, ':')) {
2458 snprintf(hostbuf, sizeof(hostbuf) - 1, "%s:26101", serial);
2461 atransport *t = find_transport(serial);
2464 unregister_transport(t);
2466 snprintf(buffer, sizeof(buffer), "No such device %s", serial);
2470 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
2471 writex(reply_fd, buf, strlen(buf));
2475 // returns our value for SDB_SERVER_VERSION
2476 if (!strcmp(service, "version")) {
2478 snprintf(version, sizeof version, "%04x", SDB_SERVER_VERSION);
2479 snprintf(buf, sizeof buf, "OKAY%04x%s", (unsigned)strlen(version), version);
2480 writex(reply_fd, buf, strlen(buf));
2484 if(!strncmp(service,"get-serialno",strlen("get-serialno"))) {
2485 char *out = "unknown";
2486 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
2487 if (transport && transport->serial) {
2488 out = transport->serial;
2490 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(out),out);
2491 writex(reply_fd, buf, strlen(buf));
2494 // indicates a new emulator instance has started
2495 if (!strncmp(service,"emulator:",9)) { /* tizen specific */
2496 char *tmp = strtok(service+9, DEVICEMAP_SEPARATOR);
2500 port = atoi(service+9);
2503 tmp = strtok(NULL, DEVICEMAP_SEPARATOR);
2505 local_connect(port, tmp);
2508 local_connect(port, NULL);
2513 if(!strncmp(service,"forward:",8) || !strncmp(service,"killforward:",12)) {
2514 char *local, *remote, *err;
2516 atransport *transport;
2518 int createForward = strncmp(service,"kill",4);
2520 local = service + (createForward ? 8 : 12);
2521 remote = strchr(local,';');
2523 sendfailmsg(reply_fd, "malformed forward spec");
2528 if((local[0] == 0) || (remote[0] == 0) || (remote[0] == '*')){
2529 sendfailmsg(reply_fd, "malformed forward spec");
2533 transport = acquire_one_transport(CS_ANY, ttype, serial, &err);
2535 sendfailmsg(reply_fd, err);
2539 if (createForward) {
2540 r = install_listener(local, remote, transport);
2542 r = remove_listener(local, remote, transport);
2545 /* 1st OKAY is connect, 2nd OKAY is status */
2546 writex(reply_fd, "OKAYOKAY", 8);
2550 if (createForward) {
2551 sendfailmsg(reply_fd, (r == -1) ? "cannot rebind smartsocket" : "cannot bind socket");
2553 sendfailmsg(reply_fd, "cannot remove listener");
2558 if(!strncmp(service,"get-state",strlen("get-state"))) {
2559 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
2560 char *state = connection_state_name(transport);
2561 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(state),state);
2562 writex(reply_fd, buf, strlen(buf));
2569 int recovery_mode = 0;
2572 int main(int argc, char **argv)
2577 return sdb_commandline(argc - 1, argv + 1);
2579 /* If sdbd runs inside the emulator this will enable sdb tracing via
2580 * sdb-debug qemud service in the emulator. */
2581 #if 0 /* tizen specific */
2582 sdb_qemu_trace_init();
2583 if((argc > 1) && (!strcmp(argv[1],"recovery"))) {
2584 sdb_device_banner = "recovery";
2589 apply_sdbd_commandline_defaults(&sdbd_commandline_args);
2590 int parse_ret = parse_sdbd_commandline(&sdbd_commandline_args, argc, argv);
2592 // TODO: Add detailed error messages
2593 // TODO: Add individual messages for help and usage
2594 if(parse_ret != SDBD_COMMANDLINE_SUCCESS) {
2595 if (parse_ret == SDBD_COMMANDLINE_HELP
2596 || parse_ret == SDBD_COMMANDLINE_USAGE) {
2597 // User requested help or usage
2598 print_sdbd_usage_message(stdout);
2599 return EXIT_SUCCESS;
2602 // Print usage message because of invalid options
2603 print_sdbd_usage_message(stderr);
2604 return EXIT_FAILURE;
2608 if (daemonize() < 0)
2609 fatal("daemonize() failed: errno:%d", errno);
2612 D("Handling main()\n");
2614 //sdbd will never die on emulator!
2615 signal(SIGTERM, handle_sig_term); /* tizen specific */
2616 return sdb_main(0, DEFAULT_SDB_PORT);