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
18 #define LOG_TAG "SDBD_TRACE_SDB"
32 #include <tzplatform_config.h>
35 #include <sys/smack.h>
41 #include "commandline_sdbd.h"
45 #include "sdbd_plugin.h"
46 #include "sdb_systemd.h"
48 #ifdef SUPPORT_ENCRYPT
49 #include "plugin_encrypt.h"
52 #include <linux/prctl.h>
53 #define SDB_PIDPATH "/tmp/.sdbd.pid"
54 #include <system_info.h>
58 #define PROC_CMDLINE_PATH "/proc/cmdline"
59 #define USB_SERIAL_PATH "/sys/class/usb_mode/usb0/iSerial"
60 #define APPID2PID_PATH "/usr/bin/appid2pid"
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 );
73 #define SDB_LOGCONF_PATH "/tmp/.sdbdlog.conf"
80 char* g_sdk_home_dir = NULL;
81 char* g_sdk_home_dir_env = NULL;
83 int rootshell_mode; // 0: sdk user, 1: root
84 int booting_done; // 0: platform booting is in progess 1: platform booting is done
88 gid_t g_root_group_id;
89 char* g_root_home_dir = NULL;
90 char* g_root_home_dir_env = NULL;
97 struct group_info g_default_groups[] = {
98 {"priv_externalstorage", -1},
99 {"priv_externalstorage_appdata", -1},
100 {"priv_mediastorage", -1},
105 #define SDB_DEFAULT_GROUPS_CNT ((sizeof(g_default_groups)/sizeof(g_default_groups[0]))-1)
107 int is_init_sdk_userinfo = 0;
108 int is_pwlocked = 0; // 0 if unlocked, 1 otherwise
110 SdbdCommandlineArgs sdbd_commandline_args;
112 static int is_support_usbproto();
113 static int is_support_sockproto();
115 void (*usb_init)() = NULL;
116 void (*usb_cleanup)() = NULL;
117 int (*usb_write)(usb_handle *h, const void *data, int len) = NULL;
118 int (*usb_read)(usb_handle *h, void *data, size_t len) = NULL;
119 int (*usb_close)(usb_handle *h) = NULL;
120 void (*usb_kick)(usb_handle *h) = NULL;
122 int g_is_emulator = -1;
123 int is_emulator(void) {
124 if (g_is_emulator >= 0) {
125 return g_is_emulator;
127 D("failed to initialize check emulator\n");
130 return sdbd_commandline_args.emulator.host != NULL;
133 int is_appid2pid_supported(void) {
135 if (access(APPID2PID_PATH, F_OK) == 0) {
136 /* It is necessary to confirm that it is possible
137 * to run "appid2pid" in the sdk user/group privileges. */
139 if (stat(APPID2PID_PATH, &st) == 0) {
140 D("appid2pid uid=%d, gid=%d, mode=0x%x.\n", st.st_uid, st.st_gid, st.st_mode);
141 if ( (st.st_uid == STATIC_SDK_USER_ID && st.st_mode & S_IXUSR)
142 || (st.st_gid == STATIC_SDK_GROUP_ID && st.st_mode & S_IXGRP)
143 || (st.st_mode & S_IXOTH) ) {
144 D("appid2pid is supported.\n");
149 D("failed to access appid2pid file: %d\n", errno);
152 D("appid2pid is NOT supported.\n");
156 int is_container_enabled(void) {
159 ret = system_info_get_platform_bool("tizen.org/feature/container", &value);
160 if (ret != SYSTEM_INFO_ERROR_NONE) {
161 E("failed to get container information: %d\n", errno);
164 D("tizen container: %d\n", value);
172 void handle_sig_term(int sig) {
174 if (access(SDB_PIDPATH, F_OK) == 0)
175 sdb_unlink(SDB_PIDPATH);
179 static const char *sdb_device_banner = "device";
181 void fatal(const char *fmt, ...)
185 fprintf(stderr, "error: ");
186 vfprintf(stderr, fmt, ap);
187 fprintf(stderr, "\n");
192 void fatal_errno(const char *fmt, ...)
196 fprintf(stderr, "errno: %d: ", errno);
197 vfprintf(stderr, fmt, ap);
198 fprintf(stderr, "\n");
203 static char* get_sdb_log_conf(const char* key)
206 char line[256] = {0,};
207 char value[256] = {0,};
209 if (access(SDB_LOGCONF_PATH, F_OK)) {
213 fd = unix_open(SDB_LOGCONF_PATH, O_RDONLY);
215 E("failed to open '%s' file: %d\n", SDB_LOGCONF_PATH, errno);
219 if (read_line(fd, line, sizeof(line)) > 0) {
220 char* start = strstr(line, key);
222 // move one more character to remove '=',
223 // including the length of the key string
224 start = start + strlen(key) + 1;
225 char* end = strstr(start, " ");
227 strncpy(value, start, end - start);
229 strncpy(value, start, sizeof(value));
237 return strdup(value);
240 static int is_enable_sdbd_log()
242 return (!strncmp(g_capabilities.log_enable, PLUGIN_RET_ENABLED, strlen(PLUGIN_RET_ENABLED)));
247 /* read a comma/space/colum/semi-column separated list of tags
248 * from the SDB_TRACE environment variable and build the trace
249 * mask from it. note that '1' and 'all' are special cases to
252 void sdb_trace_init(void)
254 char* ptr = get_sdb_log_conf("SDB_TRACE");
258 static const struct {
264 { "sdb", TRACE_SDB },
265 { "sockets", TRACE_SOCKETS },
266 { "packets", TRACE_PACKETS },
267 { "rwx", TRACE_RWX },
268 { "usb", TRACE_USB },
269 { "sync", TRACE_SYNC },
270 { "sysdeps", TRACE_SYSDEPS },
271 { "transport", TRACE_TRANSPORT },
272 { "jdwp", TRACE_JDWP },
273 { "services", TRACE_SERVICES },
274 { "properties", TRACE_PROPERTIES },
275 { "sdktools", TRACE_SDKTOOLS },
276 { "appcmd", TRACE_APPCMD },
281 if (is_enable_sdbd_log())
289 /* use a comma/column/semi-colum/space separated list */
293 q = strpbrk(p, " ,:;");
299 for (tagn = 0; tags[tagn].tag != NULL; tagn++)
301 int taglen = strlen(tags[tagn].tag);
303 if (len == taglen && !memcmp(tags[tagn].tag, p, len) )
305 int flag = tags[tagn].flag;
311 sdb_trace_mask |= (1 << flag);
323 * Implements SDB tracing inside the emulator.
329 * Redefine open and write for qemu_pipe.h that contains inlined references
330 * to those routines. We will redifine them back after qemu_pipe.h inclusion.
335 #define open sdb_open
336 #define write sdb_write
337 #include "qemu_pipe.h"
340 #define open ___xxx_open
341 #define write ___xxx_write
343 /* A handle to sdb-debug qemud service in the emulator. */
344 int sdb_debug_qemu = -1;
346 apacket *get_apacket(void)
348 apacket *p = malloc(sizeof(apacket));
349 if(p == 0) fatal("failed to allocate an apacket");
350 memset(p, 0, sizeof(apacket) - MAX_PAYLOAD);
354 void put_apacket(apacket *p)
362 void handle_online(void)
367 void handle_offline(atransport *t)
370 //Close the associated usb
371 run_transport_disconnects(t);
376 void print_packet(const char *label, apacket *p)
382 switch(p->msg.command){
383 case A_SYNC: tag = "SYNC"; break;
384 case A_CNXN: tag = "CNXN" ; break;
385 case A_OPEN: tag = "OPEN"; break;
386 case A_OKAY: tag = "OKAY"; break;
387 case A_CLSE: tag = "CLSE"; break;
388 case A_WRTE: tag = "WRTE"; break;
389 default: tag = "????"; break;
392 fprintf(stderr, "%s: %s %08x %08x %04x \"",
393 label, tag, p->msg.arg0, p->msg.arg1, p->msg.data_length);
394 count = p->msg.data_length;
396 if(count > DUMPMAX) {
403 if((*x >= ' ') && (*x < 127)) {
410 fprintf(stderr, tag);
414 #ifdef SUPPORT_ENCRYPT
416 desc. : 암호화 실패 메시지 전송
417 parameter : [in] apacket* p : sdbd로 들어온 메시지
418 [in] atransport *t : 현재 연결에 대한 atransport
419 [in] unsigned failed_value : 실패 값
421 void send_encr_fail(apacket* p, atransport *t, unsigned failed_value){
423 enc_p = get_apacket();
424 enc_p->msg.command = A_ENCR; // 암호화 메시지
425 enc_p->msg.arg0 = failed_value; // 실패값
426 enc_p->msg.arg1 = p->msg.arg1;
427 send_packet(enc_p, t);
428 //put_apacket(enc_p);
433 parameter : [in] apacket* p : sdbd로 들어온 메시지
434 [in/out] atransport *t : 현재 연결에 대한 atransport
435 ret : 0 : 정상적으로 메시지 전송
438 int handle_encr_packet(apacket* p, atransport *t){
439 static int sessionID = 0;
441 apacket* enc_p = NULL;
443 if(p->msg.arg0 == ENCR_SET_ON_REQ){ // hello 메시지인 경우
444 t->sessionID = sessionID;
445 if((retVal = security_init(t->sessionID, NULL)) == 1){ // 암호화 handshaking을 위한 init
446 if(security_parse_server_hello(t->sessionID, p) == 1){ // hello 메시지 파싱
447 I("security_parse_server_hello success\n");
448 enc_p = get_apacket();
449 if(security_gen_client_hello(t->sessionID, enc_p) == 1){ // hello 메시지 생성
450 I("security_gen_client_hello success\n");
451 enc_p->msg.command = A_ENCR;
452 enc_p->msg.arg0 = ENCR_SET_ON_REQ;
453 enc_p->msg.arg1 = p->msg.arg1;
455 send_packet(enc_p, t);
457 else { // hello 메시지 생성 실패
458 E("security_gen_client_hello error\n");
459 send_encr_fail(p, t, ENCR_ON_FAIL); // 암호화 on 실패 메시지 전송
460 t->encryption = ENCR_OFF; // 암호화 모드는 off
461 security_deinit(t->sessionID);
465 else{ // hello 메시지 파싱 실패
466 E("security_parse_server_hello error\n");
467 send_encr_fail(p, t, ENCR_ON_FAIL);
468 t->encryption = ENCR_OFF;
469 security_deinit(t->sessionID);
474 E("security_init error\n");
475 send_encr_fail(p, t, ENCR_ON_FAIL);
476 t->encryption = ENCR_OFF;
479 security_deinit(t->sessionID);
481 //here!! do security_deinit(), but when plugin pointer is null -> not deinit
485 else if(p->msg.arg0 == ENCR_SET_ON_OK){ // ack 메시지인 경우
486 if(security_parse_server_ack(t->sessionID, p) == 1){ // ack 메시지 파싱
487 enc_p = get_apacket();
488 if(security_gen_client_ack(t->sessionID, enc_p) == 1){ // ack 메시지 생성
489 I("security_gen_client_ack success\n");
490 enc_p->msg.command = A_ENCR;
491 enc_p->msg.arg0 = ENCR_SET_ON_OK;
492 enc_p->msg.arg1 = p->msg.arg1;
493 t->encryption = ENCR_ON;
494 send_packet(enc_p, t);
496 else { // ack 메시지 생성에 실패한 경우
497 E("security_gen_client_ack error\n");
498 send_encr_fail(p, t, ENCR_ON_FAIL);
499 t->encryption = ENCR_OFF;
500 security_deinit(t->sessionID);
504 else { // ack 메시지 파싱에 실패한 경우
505 E("security_parse_server_ack error\n");
506 send_encr_fail(p, t, ENCR_ON_FAIL);
507 t->encryption = ENCR_OFF;
508 security_deinit(t->sessionID);
512 else if(p->msg.arg0 == ENCR_SET_OFF){ // 암호화 모드 off 요청 메시지
513 if(t->encryption == ENCR_ON && security_deinit(t->sessionID) == 1){ // 현재 암호화 모드가 on 상태인 경우
514 enc_p = get_apacket();
515 t->encryption = ENCR_OFF; // 현재 연결에 대한 암호화 모드 off
516 enc_p->msg.command = A_ENCR;
517 enc_p->msg.arg0 = ENCR_SET_OFF;
518 enc_p->msg.arg1 = p->msg.arg1;
519 send_packet(enc_p, t);
521 else { // 암호화 모드 off에 실패한 경우
522 E("security_deinit error\n");
523 send_encr_fail(p, t, ENCR_OFF_FAIL); // 암호화 모드 off 실패 메시지 전송
527 else if(p->msg.arg0 == ENCR_GET){ // 암호화 모드의 상태 요청 메시지인 경우
528 enc_p = get_apacket();
529 enc_p->msg.command = A_ENCR;
530 enc_p->msg.arg0 = ENCR_GET; // 암호화 모드 status get메시지
531 enc_p->msg.arg1 = p->msg.arg1;
532 if(t->encryption == ENCR_ON){ // 암호화 모드가 on인 경우
533 enc_p->msg.data_length = 13;
534 strncpy((char*)enc_p->data, "encryption:on", enc_p->msg.data_length); // encryption:on 메시지 전송
535 } else if(t->encryption == ENCR_OFF){ // 암호화 모드가 off인 경우
536 enc_p->msg.data_length = 14;
537 strncpy((char*)enc_p->data, "encryption:off", enc_p->msg.data_length); // encryption:off 메시지 전송
539 send_packet(enc_p, t);
541 else if (p->msg.arg0 == ENCR_ON_FAIL) // 암호화 모드를 on 하는 도중 실패한 경우 받는 메시지
543 t->encryption = ENCR_OFF; // 암호화 모드를 다시 off
544 E("encryption on failed\n");
546 else if (p->msg.arg0 == ENCR_OFF_FAIL) // 암호화 모드를 off하는 도중 실패한 경우 받는 메시지
548 //t->encryption = ENCR_ON;
549 E("encryption off failed\n");
551 //put_apacket(enc_p);
558 static void send_ready(unsigned local, unsigned remote, atransport *t)
560 I("Calling send_ready \n");
561 apacket *p = get_apacket();
562 p->msg.command = A_OKAY;
564 p->msg.arg1 = remote;
568 static void send_close(unsigned local, unsigned remote, atransport *t)
570 I("Calling send_close \n");
571 apacket *p = get_apacket();
572 p->msg.command = A_CLSE;
574 p->msg.arg1 = remote;
578 static void send_connect(atransport *t)
580 I("Calling send_connect \n");
581 apacket *cp = get_apacket();
582 cp->msg.command = A_CNXN;
583 cp->msg.arg0 = A_VERSION;
584 #ifdef SUPPORT_ENCRYPT
585 cp->msg.arg1 = MAX_PAYLOAD - 100; // connection 시, sdb server의 패킷 크기를 암호화 오버로드 만큼 줄임
587 cp->msg.arg1 = MAX_PAYLOAD;
589 char device_name[256]={0,};
592 if (request_lock_state_to_plugin(LOCKTYPE_PASSWORD) == 1) {
594 t->connection_state = CS_PWLOCK;
598 r = get_emulator_name(device_name, sizeof device_name);
600 r = get_device_name(device_name, sizeof device_name);
603 snprintf((char*) cp->data, sizeof cp->data, "%s::%s::%d", sdb_device_banner, DEFAULT_DEVICENAME, status);
605 snprintf((char*) cp->data, sizeof cp->data, "%s::%s::%d", sdb_device_banner, device_name, status);
608 D("CNXN data:%s\n", (char*)cp->data);
609 cp->msg.data_length = strlen((char*) cp->data) + 1;
614 void send_device_status()
616 I("broadcast device status\n");
617 apacket* cp = get_apacket();
618 cp->msg.command = A_STAT;
619 cp->msg.arg0 = is_pwlocked;
622 broadcast_transport(cp);
624 //all broadcasted packets are memory copied
625 //so, we should call put_apacket
629 static char *connection_state_name(atransport *t)
635 switch(t->connection_state) {
647 static int get_str_cmdline(char *src, char *dest, char str[], int str_size) {
648 char *s = strstr(src, dest);
652 char *e = strstr(s, " ");
657 int len = e-s-strlen(dest);
659 if (len >= str_size) {
660 E("buffer size(%d) should be bigger than %d\n", str_size, len+1);
664 strncpy(str, s + strlen(dest), len);
669 int get_emulator_forward_port() {
670 SdbdCommandlineArgs *sdbd_args = &sdbd_commandline_args; /* alias */
672 if (sdbd_args->emulator.host == NULL) {
676 return sdbd_args->emulator.port;
679 int get_emulator_name(char str[], int str_size) {
680 SdbdCommandlineArgs *sdbd_args = &sdbd_commandline_args; /* alias */
682 if (sdbd_args->emulator.host == NULL) {
686 s_strncpy(str, sdbd_args->emulator.host, str_size);
690 int get_device_name(char str[], int str_size) {
692 int r = system_info_get_platform_string("http://tizen.org/system/model_name", &value);
693 if (r != SYSTEM_INFO_ERROR_NONE) {
694 E("fail to get system model:%d\n", errno);
697 s_strncpy(str, value, str_size);
698 D("returns model_name:%s\n", value);
705 int fd = unix_open(USB_SERIAL_PATH, O_RDONLY);
707 D("fail to read:%s (%d)\n", USB_SERIAL_PATH, errno);
711 if(read_line(fd, str, str_size)) {
712 D("device serial name: %s\n", str);
721 static int get_cmdline_value(char *split, char str[], int str_size) {
723 int fd = unix_open(PROC_CMDLINE_PATH, O_RDONLY);
726 E("fail to read /proc/cmdline\n");
729 if(read_line(fd, cmdline, sizeof(cmdline))) {
730 D("qemu cmd: %s\n", cmdline);
731 if (get_str_cmdline(cmdline, split, str, str_size) < 1) {
732 E("could not get the (%s) value from cmdline\n", split);
741 int get_emulator_hostip(char str[], int str_size) {
742 return get_cmdline_value("host_ip=", str, str_size);
745 int get_emulator_guestip(char str[], int str_size) {
748 struct sockaddr_in *sin;
750 s = socket(AF_INET, SOCK_DGRAM, 0);
756 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s", GUEST_IP_INTERFACE);
757 if(ioctl(s, SIOCGIFHWADDR, &ifr) < 0) {
758 E("ioctl hwaddr error\n");
763 if(ioctl(s, SIOCGIFADDR, &ifr) < 0) {
764 E("ioctl addr error\n");
768 sin = (struct sockaddr_in *)&ifr.ifr_addr;
769 snprintf(str, str_size, "%s", inet_ntoa(sin->sin_addr));
775 void parse_banner(char *banner, atransport *t)
777 char *type, *product, *end;
779 D("parse_banner: %s\n", banner);
781 product = strchr(type, ':');
788 /* remove trailing ':' */
789 end = strchr(product, ':');
792 /* save product name in device structure */
793 if (t->product == NULL) {
794 t->product = strdup(product);
795 } else if (strcmp(product, t->product) != 0) {
797 t->product = strdup(product);
800 if(!strcmp(type, "bootloader")){
801 I("setting connection_state to CS_BOOTLOADER\n");
802 t->connection_state = CS_BOOTLOADER;
807 if(!strcmp(type, "device")) {
808 I("setting connection_state to CS_DEVICE\n");
809 t->connection_state = CS_DEVICE;
814 if(!strcmp(type, "recovery")) {
815 I("setting connection_state to CS_RECOVERY\n");
816 t->connection_state = CS_RECOVERY;
821 if(!strcmp(type, "sideload")) {
822 I("setting connection_state to CS_SIDELOAD\n");
823 t->connection_state = CS_SIDELOAD;
828 t->connection_state = CS_HOST;
831 static void update_version(atransport *t, int version, size_t payload)
833 #ifdef SUPPORT_ENCRYPT
834 size_t max_payload = MAX_PAYLOAD - 100;
836 size_t max_payload = MAX_PAYLOAD;
838 t->protocol_version = min(version, A_VERSION);
839 t->max_payload = min(payload, max_payload);
840 D("update transport version. version=%x, max_payload=%zu\n", t->protocol_version, t->max_payload);
843 void handle_packet(apacket *p, atransport *t)
846 int result = access((const char *) p, F_OK);
847 if ((result == -1) && (errno == EFAULT)) {
848 fatal("Invalid apacket = [0x%p]", p);
853 // D("handle_packet() %c%c%c%c\n", ((char*) (&(p->msg.command)))[0],
854 // ((char*) (&(p->msg.command)))[1],
855 // ((char*) (&(p->msg.command)))[2],
856 // ((char*) (&(p->msg.command)))[3]);
858 print_packet("recv", p);
860 switch(p->msg.command){
864 if(HOST) send_connect(t);
866 t->connection_state = CS_OFFLINE;
872 case A_CNXN: /* CONNECT(version, maxdata, "system-id-string") */
873 /* XXX verify version, etc */
874 if(t->connection_state != CS_OFFLINE) {
875 t->connection_state = CS_OFFLINE;
878 update_version(t, p->msg.arg0, p->msg.arg1);
879 parse_banner((char*) p->data, t);
881 if(!HOST) send_connect(t);
884 case A_OPEN: /* OPEN(local-id, 0, "destination") */
885 if (request_lock_state_to_plugin(LOCKTYPE_PASSWORD) == 1 && t->connection_state == CS_PWLOCK) {
886 // in case of already locked before get A_CNXN
887 E("open failed due to password locked before get A_CNXN:%d\n", t->connection_state);
888 send_close(0, p->msg.arg0, t);
890 if(t->connection_state != CS_OFFLINE) {
891 char *name = (char*) p->data;
892 name[p->msg.data_length > 0 ? p->msg.data_length - 1 : 0] = 0;
893 s = create_local_service_socket(name);
895 send_close(0, p->msg.arg0, t);
897 s->peer = create_remote_socket(p->msg.arg0, t);
899 send_ready(s->id, s->peer->id, t);
906 case A_OKAY: /* READY(local-id, remote-id, "") */
907 if(t->connection_state != CS_OFFLINE) {
908 if((s = find_local_socket(p->msg.arg1))) {
910 s->peer = create_remote_socket(p->msg.arg0, t);
918 case A_CLSE: /* CLOSE(local-id, remote-id, "") */
919 if(t->connection_state != CS_OFFLINE) {
920 if((s = find_local_socket(p->msg.arg1))) {
927 if(t->connection_state != CS_OFFLINE) {
928 if((s = find_local_socket(p->msg.arg1))) {
929 unsigned rid = p->msg.arg0;
930 p->len = p->msg.data_length;
932 if(s->enqueue(s, p) == 0) {
933 I("Enqueue the socket\n");
934 send_ready(s->id, rid, t);
940 #ifdef SUPPORT_ENCRYPT
941 case A_ENCR: // 암호화 메시지인 경우
942 if(t->connection_state != CS_OFFLINE) {
943 handle_encr_packet(p, t);
949 printf("handle_packet: what is %08x?!\n", p->msg.command);
955 alistener listener_list = {
956 .next = &listener_list,
957 .prev = &listener_list,
960 static void ss_listener_event_func(int _fd, unsigned ev, void *_l)
966 struct sockaddr addr;
971 fd = sdb_socket_accept(_fd, &addr, &alen);
974 ret = sdb_socket_setbufsize(fd, CHUNK_SIZE);
976 D("sdbd: sdb_socket_setbufsize failed \n", ret);
979 s = create_local_socket(fd);
981 connect_to_smartsocket(s);
989 static void listener_event_func(int _fd, unsigned ev, void *_l)
995 struct sockaddr addr;
1000 fd = sdb_socket_accept(_fd, &addr, &alen);
1003 s = create_local_socket(fd);
1005 s->transport = l->transport;
1006 connect_to_remote(s, l->connect_to);
1014 static void free_listener(alistener* l)
1017 l->next->prev = l->prev;
1018 l->prev->next = l->next;
1019 l->next = l->prev = l;
1022 // closes the corresponding fd
1023 fdevent_remove(&l->fde);
1026 free((char*)l->local_name);
1029 free((char*)l->connect_to);
1032 remove_transport_disconnect(l->transport, &l->disconnect);
1037 static void listener_disconnect(void* _l, atransport* t)
1044 int local_name_to_fd(const char *name)
1048 if(!strncmp("tcp:", name, 4)){
1050 port = atoi(name + 4);
1051 ret = socket_loopback_server(port, SOCK_STREAM);
1054 #ifndef HAVE_WIN32_IPC /* no Unix-domain sockets on Win32 */
1055 // It's non-sensical to support the "reserved" space on the sdb host side
1056 if(!strncmp(name, "local:", 6)) {
1057 return socket_local_server(name + 6,
1058 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
1059 } else if(!strncmp(name, "localabstract:", 14)) {
1060 return socket_local_server(name + 14,
1061 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
1062 } else if(!strncmp(name, "localfilesystem:", 16)) {
1063 return socket_local_server(name + 16,
1064 ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
1068 printf("unknown local portname '%s'\n", name);
1072 static int remove_listener(const char *local_name, const char *connect_to, atransport* transport)
1076 for (l = listener_list.next; l != &listener_list; l = l->next) {
1077 if (!strcmp(local_name, l->local_name) &&
1078 !strcmp(connect_to, l->connect_to) &&
1079 l->transport && l->transport == transport) {
1081 listener_disconnect(l, transport);
1089 static int install_listener(const char *local_name, const char *connect_to, atransport* transport)
1093 //printf("install_listener('%s','%s')\n", local_name, connect_to);
1095 for(l = listener_list.next; l != &listener_list; l = l->next){
1096 if(strcmp(local_name, l->local_name) == 0) {
1099 /* can't repurpose a smartsocket */
1100 if(l->connect_to[0] == '*') {
1104 cto = strdup(connect_to);
1109 //printf("rebinding '%s' to '%s'\n", local_name, connect_to);
1110 free((void*) l->connect_to);
1111 l->connect_to = cto;
1112 if (l->transport != transport) {
1113 remove_transport_disconnect(l->transport, &l->disconnect);
1114 l->transport = transport;
1115 add_transport_disconnect(l->transport, &l->disconnect);
1121 if((l = calloc(1, sizeof(alistener))) == 0) goto nomem;
1122 if((l->local_name = strdup(local_name)) == 0) goto nomem;
1123 if((l->connect_to = strdup(connect_to)) == 0) goto nomem;
1126 l->fd = local_name_to_fd(local_name);
1128 free((void*) l->local_name);
1129 free((void*) l->connect_to);
1131 printf("cannot bind '%s'\n", local_name);
1135 if (close_on_exec(l->fd) < 0) {
1136 E("fail to close fd exec:%d\n",l->fd);
1138 if(!strcmp(l->connect_to, "*smartsocket*")) {
1139 fdevent_install(&l->fde, l->fd, ss_listener_event_func, l);
1141 fdevent_install(&l->fde, l->fd, listener_event_func, l);
1143 fdevent_set(&l->fde, FDE_READ);
1145 l->next = &listener_list;
1146 l->prev = listener_list.prev;
1149 l->transport = transport;
1152 l->disconnect.opaque = l;
1153 l->disconnect.func = listener_disconnect;
1154 add_transport_disconnect(transport, &l->disconnect);
1159 fatal("cannot allocate listener");
1163 static void sdb_cleanup(void)
1165 clear_sdbd_commandline_args(&sdbd_commandline_args);
1167 if (is_support_usbproto()) {
1170 // if(required_pid > 0) {
1171 // kill(required_pid, SIGKILL);
1174 unload_sdbd_plugin();
1177 void start_device_log(void)
1180 char path[PATH_MAX] = {0, };
1181 char path_folder[PATH_MAX] = {0, };
1182 char path_file[PATH_MAX] = {0, };
1186 // read the trace mask from persistent property persist.sdb.trace_mask
1187 // give up if the property is not set or cannot be parsed
1188 char* p_trace = get_sdb_log_conf("SDB_TRACE");
1189 if ((p_trace == NULL ) && !is_enable_sdbd_log()) {
1194 char* p_path = get_sdb_log_conf("SDBD_LOG_PATH");
1196 snprintf(path_folder, sizeof(path_folder), "%s", p_path);
1198 } else if (g_capabilities.log_path[0] != '\0') {
1199 snprintf(path_folder, sizeof(path_folder), "%s", g_capabilities.log_path);
1206 localtime_r(&t, &now);
1208 strftime(path_file, sizeof(path_file),
1209 "sdbd-%Y-%m-%d-%H-%M-%S.txt",
1212 snprintf(path, sizeof(path), "%s/%s", path_folder, path_file);
1214 fd = unix_open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1219 // redirect stdout and stderr to the log file
1222 fprintf(stderr,"--- sdbd starting (pid %d) ---\n", getpid());
1225 fd = unix_open("/dev/null", O_RDONLY);
1227 // hopefully not gonna happen
1234 /* Constructs a local name of form tcp:port.
1235 * target_str points to the target string, it's content will be overwritten.
1236 * target_size is the capacity of the target string.
1237 * server_port is the port number to use for the local name.
1239 void build_local_name(char* target_str, size_t target_size, int server_port)
1241 snprintf(target_str, target_size, "tcp:%d", server_port);
1244 static void init_drop_privileges() {
1245 #ifdef _DROP_PRIVILEGE
1252 int should_drop_privileges() {
1253 if (rootshell_mode == 1) { // if root, then don't drop
1259 #include <gio/gio.h>
1261 #define DEVICED_BUS "org.tizen.system.deviced"
1262 #define DEVICED_CORE_PATH "/Org/Tizen/System/DeviceD/Core"
1263 #define BOOTING_DONE_SIGNAL "BootingDone"
1264 #define DEVICED_CORE_INTERFACE "org.tizen.system.deviced.core"
1265 #define SDBD_BOOT_INFO_FILE "/tmp/sdbd_boot_info"
1267 static GMainLoop *g_mainloop;
1269 static void booting_done_signal_subscriber(GDBusConnection *connection,
1270 const gchar *sender, const gchar *path, const gchar *interface,
1271 const gchar *signal, GVariant *parameters, gpointer user_data)
1273 if (g_strcmp0(signal, BOOTING_DONE_SIGNAL) != 0) {
1274 D("received signal(%s) does not match the desired signal(%s)\n",
1275 signal, BOOTING_DONE_SIGNAL);
1279 D("received the \"%s\" signal\n", signal);
1282 if (access(SDBD_BOOT_INFO_FILE, F_OK) == 0) {
1283 I("booting is already done\n");
1285 FILE *info_file = fopen(SDBD_BOOT_INFO_FILE, "w");
1286 if (info_file != NULL) {
1287 fprintf(info_file, "%d", 1);
1290 I("booting is done\n");
1293 I("handled the booting done signal\n");
1294 g_main_loop_quit(g_mainloop);
1297 static void *bootdone_cb(void *args)
1299 GError *error = NULL;
1300 GDBusConnection *connection = NULL;
1303 connection = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &error);
1304 if (connection == NULL) {
1305 if (error != NULL) {
1306 E("failed to connect to the system bus: %s\n", error->message);
1307 g_error_free(error);
1309 E("failed to connect to the system bus\n");
1314 g_mainloop = g_main_loop_new(NULL, false);
1315 if (g_mainloop == NULL) {
1316 E("failed to create a g_main_loop\n");
1320 id = g_dbus_connection_signal_subscribe(connection,
1321 DEVICED_BUS, DEVICED_CORE_INTERFACE, BOOTING_DONE_SIGNAL,
1322 DEVICED_CORE_PATH, NULL, G_DBUS_SIGNAL_FLAGS_NONE,
1323 booting_done_signal_subscriber, NULL, NULL);
1325 E("failed to subscribe to the booting done signal\n");
1329 I("wait for the booting done signal\n");
1330 g_main_loop_run(g_mainloop);
1332 g_dbus_connection_signal_unsubscribe(connection, id);
1335 if (g_mainloop != NULL) {
1336 g_main_loop_unref(g_mainloop);
1338 if (connection != NULL) {
1339 g_object_unref(connection);
1341 I("exit the bootdone_cb thread\n");
1346 void register_bootdone_cb()
1349 if (sdb_thread_create(&t, bootdone_cb, NULL)) {
1350 E("can not create a service thread to check the booting done\n");
1353 I("created the bootdone_cb thread\n");
1356 static int sdbd_set_groups(const char *name, int gid, struct group_info default_groups[], int default_groups_size) {
1357 gid_t *group_ids = NULL;
1360 int group_match = 0;
1361 int added_group_cnt = 0;
1363 if (getgrouplist(name, gid, NULL, &ngroups) == -1) {
1364 D("group list : ngroups = %d\n", ngroups);
1366 group_ids = malloc((ngroups + default_groups_size) * sizeof(gid_t));
1367 if (group_ids == NULL) {
1368 E("failed to allocate group_ids(%zu)\n", (ngroups + default_groups_size) * sizeof(gid_t));
1371 if (getgrouplist(name, gid, group_ids, &ngroups) == -1) {
1372 E("failed to getgrouplist(), ngroups = %d\n", ngroups);
1376 if(default_groups_size >= 1) {
1377 for (i = 0; default_groups[i].name != NULL; i++) {
1378 for (j = 0; j < ngroups; j++) {
1379 if (group_ids[j] == default_groups[i].gid) {
1384 if (group_match == 0 && default_groups[i].gid != -1) {
1385 group_ids[ngroups + added_group_cnt] = default_groups[i].gid;
1391 if (setgroups(ngroups+added_group_cnt, group_ids) != 0) {
1392 E("failed to setgroups().\n");
1401 static int sdbd_get_user_pwd(const char* user_name, struct passwd* pwd, char* buf, size_t bufsize) {
1402 struct passwd *result = NULL;
1405 ret = getpwnam_r(user_name, pwd, buf, bufsize, &result);
1406 if (result == NULL) {
1408 E("Not found passwd : username(%s)\n", user_name);
1411 E("failed to getpwnam_r\n");
1419 static int sdbd_get_group(const char* group_name, struct group* grp, char* buf, size_t bufsize) {
1420 struct group *result = NULL;
1423 ret = getgrnam_r(group_name, grp, buf, bufsize, &result);
1424 if (result == NULL) {
1426 E("Not found group : groupname(%s)\n", group_name);
1429 E("failed to getgrnam_r\n");
1437 int set_sdk_user_privileges(int is_drop_capability_after_fork) {
1438 if (!is_init_sdk_userinfo) {
1439 E("failed to init sdk user information.\n");
1444 * If a process switches its real, effective, or saved uids from at least one being 0 to all being non-zero,
1445 * then both the permitted and effective capabilities are cleared.
1447 if(is_drop_capability_after_fork) {
1449 if (setuid(g_root_user_id) != 0) {
1450 E("set root user id failed (errno: %d)\n", errno);
1455 if (sdbd_set_groups(SDK_USER_NAME, g_sdk_group_id, g_default_groups, SDB_DEFAULT_GROUPS_CNT) < 0) {
1456 E("set groups failed (errno: %d)\n", errno);
1460 if (setgid(g_sdk_group_id) != 0) {
1461 E("set group id failed (errno: %d)\n", errno);
1465 if (setuid(g_sdk_user_id) != 0) {
1466 E("set user id failed (errno: %d)\n", errno);
1468 // if(is_drop_capability_after_fork) {
1473 if (chdir(g_sdk_home_dir) < 0) {
1474 E("unable to change working directory to %s\n", g_sdk_home_dir);
1477 // TODO: use pam later
1478 if (g_sdk_home_dir_env) {
1479 putenv(g_sdk_home_dir_env);
1485 int set_root_privileges() {
1487 if (sdbd_set_groups(ROOT_USER_NAME, g_root_group_id, NULL, 0) < 0) {
1488 E("set root groups failed (errno: %d)\n", errno);
1491 if (setgid(g_root_group_id) != 0) {
1492 E("set root group id failed (errno: %d)\n", errno);
1495 if (setuid(g_root_user_id) != 0) {
1496 E("set root user id failed (errno: %d)\n", errno);
1499 if (chdir(g_root_home_dir) < 0) {
1500 E("unable to change root working directory to %s\n", g_sdk_home_dir);
1503 // TODO: use pam later
1504 if (g_root_home_dir_env) {
1505 putenv(g_root_home_dir_env);
1511 #define SDB_PW_GR_DEFAULT_SIZE (16*1024)
1512 static long get_passwd_bufsize() {
1515 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
1517 bufsize = SDB_PW_GR_DEFAULT_SIZE;
1523 static long get_group_bufsize() {
1526 bufsize = sysconf(_SC_GETGR_R_SIZE_MAX);
1528 bufsize = SDB_PW_GR_DEFAULT_SIZE;
1534 static int init_sdb_default_groups() {
1540 bufsize = get_group_bufsize();
1541 buf = malloc(bufsize);
1543 E("failed to allocate gruop buf(%ld)\n", bufsize);
1547 for (i = 0; g_default_groups[i].name != NULL; i++) {
1548 memset(buf, 0, bufsize);
1549 if (sdbd_get_group(g_default_groups[i].name, &grp, buf, bufsize) == 0) {
1550 g_default_groups[i].gid = grp.gr_gid;
1552 E("failed get group info.(errno: %d)\n", errno);
1560 static void set_static_root_userinfo() {
1561 g_root_user_id = STATIC_ROOT_USER_ID;
1562 g_root_group_id = STATIC_ROOT_GROUP_ID;
1563 g_root_home_dir = STATIC_ROOT_HOME_DIR;
1566 static void set_static_sdk_userinfo() {
1567 g_sdk_user_id = STATIC_SDK_USER_ID;
1568 g_sdk_group_id = STATIC_SDK_GROUP_ID;
1569 g_sdk_home_dir = STATIC_SDK_HOME_DIR;
1572 static int init_root_userinfo() {
1577 bufsize = get_passwd_bufsize();
1578 buf = malloc(bufsize);
1580 E("failed to allocate passwd buf(%ld)\n", bufsize);
1581 set_static_root_userinfo();
1583 if (sdbd_get_user_pwd(ROOT_USER_NAME, &pwd, buf, bufsize) < 0) {
1584 E("failed to get root user passwd info.(errno: %d)\n", errno);
1585 set_static_root_userinfo();
1587 D("username=%s, uid=%d, gid=%d, dir=%s\n", pwd.pw_name, pwd.pw_uid, pwd.pw_gid, pwd.pw_dir);
1589 g_root_user_id = pwd.pw_uid;
1590 g_root_group_id = pwd.pw_gid;
1591 g_root_home_dir = strdup(pwd.pw_dir);
1596 int env_size = strlen("HOME=") + strlen(g_root_home_dir) + 1;
1597 g_root_home_dir_env = malloc(env_size);
1598 if(g_root_home_dir_env == NULL) {
1599 E("failed to allocate for home dir env string\n");
1601 snprintf(g_root_home_dir_env, env_size, "HOME=%s", g_root_home_dir);
1607 static int init_sdk_userinfo() {
1612 if (is_init_sdk_userinfo) {
1616 if (init_sdb_default_groups() < 0) {
1617 E("failed to initialize default groups.\n");
1620 bufsize = get_passwd_bufsize();
1621 buf = malloc(bufsize);
1623 E("failed to allocate passwd buf(%ld)\n", bufsize);
1624 set_static_sdk_userinfo();
1626 if (sdbd_get_user_pwd(SDK_USER_NAME, &pwd, buf, bufsize) < 0) {
1627 E("get user passwd info.(errno: %d)\n", errno);
1628 set_static_sdk_userinfo();
1630 D("username=%s, uid=%d, gid=%d, dir=%s\n", pwd.pw_name, pwd.pw_uid, pwd.pw_gid, pwd.pw_dir);
1632 g_sdk_user_id = pwd.pw_uid;
1633 g_sdk_group_id = pwd.pw_gid;
1634 g_sdk_home_dir = strdup(pwd.pw_dir);
1639 int env_size = strlen("HOME=") + strlen(g_sdk_home_dir) + 1;
1640 g_sdk_home_dir_env = malloc(env_size);
1641 if(g_sdk_home_dir_env == NULL) {
1642 E("failed to allocate for home dir env string\n");
1644 snprintf(g_sdk_home_dir_env, env_size, "HOME=%s", g_sdk_home_dir);
1647 is_init_sdk_userinfo = 1;
1651 static int safe_system(char *cmd, char *argv[], char *envp[]) {
1660 execve(cmd, argv, envp);
1661 E("- exec '%s' failed: (errno:%d) -\n", cmd, errno);
1665 pid_t p = waitpid(pid, &status, 0);
1674 static void init_sdk_requirements() {
1677 // set env variable for temporary
1678 // TODO: should use pam instead later!!
1679 putenv("TERM=linux");
1680 putenv("HOME=/root");
1682 init_sdk_userinfo();
1683 init_root_userinfo();
1685 if (g_sdk_home_dir != NULL && stat(g_sdk_home_dir, &st) == 0) {
1686 if (st.st_uid != g_sdk_user_id || st.st_gid != g_sdk_group_id) {
1687 char* cmd = "/usr/bin/chown";
1693 envp[envp_cnt++] = g_strdup("TERM=linux");
1694 envp[envp_cnt++] = g_strdup("DISPLAY=:0");
1695 envp[envp_cnt] = NULL;
1697 snprintf(params, sizeof(params), "%s %s:%s %s -R", cmd, SDK_USER_NAME, SDK_USER_NAME, g_sdk_home_dir);
1704 if (safe_system(cmd, args, envp) < 0) {
1705 E("failed to change ownership to sdk user to %s\n", g_sdk_home_dir);
1708 /* free environment variables */
1710 for (i = 0; i < envp_cnt; i++) {
1719 if (is_emulator()) {
1720 register_bootdone_cb();
1724 static void init_capabilities(void) {
1728 memset(&g_capabilities, 0, sizeof(g_capabilities));
1730 // CPU Architecture of model
1731 ret = system_info_get_platform_string("http://tizen.org/feature/platform.core.cpu.arch", &value);
1732 if (ret != SYSTEM_INFO_ERROR_NONE) {
1733 snprintf(g_capabilities.cpu_arch, sizeof(g_capabilities.cpu_arch),
1735 E("fail to get the CPU architecture of model:%d\n", errno);
1737 snprintf(g_capabilities.cpu_arch, sizeof(g_capabilities.cpu_arch),
1739 if (value != NULL) {
1745 // Secure protocol support
1746 if(!request_capability_to_plugin(CAPABILITY_SECURE, g_capabilities.secure_protocol,
1747 sizeof(g_capabilities.secure_protocol))) {
1748 E("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_SECURE);
1749 snprintf(g_capabilities.secure_protocol, sizeof(g_capabilities.secure_protocol),
1754 // Interactive shell support
1755 if(!request_capability_to_plugin(CAPABILITY_INTER_SHELL, g_capabilities.intershell_support,
1756 sizeof(g_capabilities.intershell_support))) {
1757 E("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_INTER_SHELL);
1758 snprintf(g_capabilities.intershell_support, sizeof(g_capabilities.intershell_support),
1763 // File push/pull support
1764 if(!request_capability_to_plugin(CAPABILITY_FILESYNC, g_capabilities.filesync_support,
1765 sizeof(g_capabilities.filesync_support))) {
1766 E("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_FILESYNC);
1767 snprintf(g_capabilities.filesync_support, sizeof(g_capabilities.filesync_support),
1772 // USB protocol support
1773 if(!request_capability_to_plugin(CAPABILITY_USB_PROTOCOL, g_capabilities.usbproto_support,
1774 sizeof(g_capabilities.usbproto_support))) {
1775 E("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_USB_PROTOCOL);
1776 snprintf(g_capabilities.usbproto_support, sizeof(g_capabilities.usbproto_support),
1781 // Socket protocol support
1782 if(!request_capability_to_plugin(CAPABILITY_SOCK_PROTOCOL, g_capabilities.sockproto_support,
1783 sizeof(g_capabilities.sockproto_support))) {
1784 E("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_SOCK_PROTOCOL);
1785 snprintf(g_capabilities.sockproto_support, sizeof(g_capabilities.sockproto_support),
1789 // Sdbd root permission
1790 snprintf(g_capabilities.root_permission, sizeof(g_capabilities.root_permission),
1793 // Root command support
1794 if(!request_capability_to_plugin(CAPABILITY_ROOT_ONOFF, g_capabilities.rootonoff_support,
1795 sizeof(g_capabilities.rootonoff_support))) {
1796 E("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_ROOT_ONOFF);
1797 snprintf(g_capabilities.rootonoff_support, sizeof(g_capabilities.rootonoff_support),
1802 // Encryption support
1803 if(!request_capability_to_plugin(CAPABILITY_ENCRYPTION, g_capabilities.encryption_support,
1804 sizeof(g_capabilities.encryption_support))) {
1805 E("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_ENCRYPTION);
1806 snprintf(g_capabilities.encryption_support, sizeof(g_capabilities.encryption_support),
1812 ret = is_container_enabled();
1813 snprintf(g_capabilities.zone_support, sizeof(g_capabilities.zone_support),
1814 "%s", ret == 1 ? ENABLED : DISABLED);
1816 // Multi-User support
1817 // XXX: There is no clear way to determine whether multi-user support.
1818 // Since TZ_SYS_DEFAULT_USER is set to "owner" for multi-user support,
1819 // guess whether multiuser support through that information.
1820 const char* sys_default_user = tzplatform_getenv(TZ_SYS_DEFAULT_USER);
1821 if (sys_default_user != NULL && !strcmp(sys_default_user, "owner")) {
1822 snprintf(g_capabilities.multiuser_support, sizeof(g_capabilities.multiuser_support),
1825 snprintf(g_capabilities.multiuser_support, sizeof(g_capabilities.multiuser_support),
1829 // Window size synchronization support
1830 snprintf(g_capabilities.syncwinsz_support, sizeof(g_capabilities.syncwinsz_support),
1834 if (SDK_TOOL_PATH == NULL) {
1835 E("fail to get SDK tool path.\n");
1836 snprintf(g_capabilities.sdk_toolpath, sizeof(g_capabilities.sdk_toolpath),
1839 snprintf(g_capabilities.sdk_toolpath, sizeof(g_capabilities.sdk_toolpath),
1840 "%s", SDK_TOOL_PATH);
1844 ret = system_info_get_platform_string("http://tizen.org/feature/profile", &value);
1845 if (ret != SYSTEM_INFO_ERROR_NONE) {
1846 snprintf(g_capabilities.profile_name, sizeof(g_capabilities.profile_name),
1848 E("fail to get profile name:%d\n", errno);
1850 snprintf(g_capabilities.profile_name, sizeof(g_capabilities.profile_name),
1852 if (value != NULL) {
1859 ret = system_info_get_platform_string("http://tizen.org/system/manufacturer", &value);
1860 if (ret != SYSTEM_INFO_ERROR_NONE) {
1861 snprintf(g_capabilities.vendor_name, sizeof(g_capabilities.vendor_name),
1863 E("fail to get the Vendor name:%d\n", errno);
1865 snprintf(g_capabilities.vendor_name, sizeof(g_capabilities.vendor_name),
1867 if (value != NULL) {
1873 // Target name of the launch possible
1874 if(!request_capability_to_plugin(CAPABILITY_CAN_LAUNCH, g_capabilities.can_launch,
1875 sizeof(g_capabilities.can_launch))) {
1876 E("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_CAN_LAUNCH);
1877 snprintf(g_capabilities.can_launch, sizeof(g_capabilities.can_launch),
1883 value = vconf_get_str(VCONFKEY_SETAPPL_DEVICE_NAME_STR);
1885 snprintf(g_capabilities.device_name, sizeof(g_capabilities.device_name),
1887 if (value != NULL) {
1891 snprintf(g_capabilities.device_name, sizeof(g_capabilities.device_name),
1893 E("fail to get the Device name:%d\n", errno);
1898 ret = system_info_get_platform_string("http://tizen.org/feature/platform.version", &value);
1899 if (ret != SYSTEM_INFO_ERROR_NONE) {
1900 snprintf(g_capabilities.platform_version, sizeof(g_capabilities.platform_version),
1902 E("fail to get platform version:%d\n", errno);
1904 snprintf(g_capabilities.platform_version, sizeof(g_capabilities.platform_version),
1906 if (value != NULL) {
1913 if(!request_capability_to_plugin(CAPABILITY_PRODUCT_VER, g_capabilities.product_version,
1914 sizeof(g_capabilities.product_version))) {
1915 E("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_PRODUCT_VER);
1916 snprintf(g_capabilities.product_version, sizeof(g_capabilities.product_version),
1922 snprintf(g_capabilities.sdbd_version, sizeof(g_capabilities.sdbd_version),
1923 "%d.%d.%d", SDB_VERSION_MAJOR, SDB_VERSION_MINOR, SDB_VERSION_PATCH);
1926 // Sdbd plugin version
1927 if(!request_capability_to_plugin(CAPABILITY_PLUGIN_VER, g_capabilities.sdbd_plugin_version,
1928 sizeof(g_capabilities.sdbd_plugin_version))) {
1929 E("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_PLUGIN_VER);
1930 snprintf(g_capabilities.sdbd_plugin_version, sizeof(g_capabilities.sdbd_plugin_version),
1936 if(!request_capability_to_plugin(CAPABILITY_LOG_ENABLE, g_capabilities.log_enable,
1937 sizeof(g_capabilities.log_enable))) {
1938 E("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_LOG_ENABLE);
1939 snprintf(g_capabilities.log_enable, sizeof(g_capabilities.log_enable),
1944 if(!request_capability_to_plugin(CAPABILITY_LOG_PATH, g_capabilities.log_path,
1945 sizeof(g_capabilities.log_path))) {
1946 E("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_LOG_PATH);
1947 snprintf(g_capabilities.log_path, sizeof(g_capabilities.log_path),
1951 // Application command support
1952 if(!request_capability_to_plugin(CAPABILITY_APPCMD, g_capabilities.appcmd_support,
1953 sizeof(g_capabilities.appcmd_support))) {
1954 E("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_APPCMD);
1955 snprintf(g_capabilities.appcmd_support, sizeof(g_capabilities.appcmd_support),
1959 // appid2pid support
1960 ret = is_appid2pid_supported();
1961 snprintf(g_capabilities.appid2pid_support, sizeof(g_capabilities.appid2pid_support),
1962 "%s", ret == 1 ? ENABLED : DISABLED);
1964 // pkgcmd debug mode support
1965 if(!request_capability_to_plugin(CAPABILITY_DEBUGMODE, g_capabilities.pkgcmd_debugmode,
1966 sizeof(g_capabilities.pkgcmd_debugmode))) {
1967 E("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_DEBUGMODE);
1968 snprintf(g_capabilities.pkgcmd_debugmode, sizeof(g_capabilities.pkgcmd_debugmode),
1972 // Capability version
1973 snprintf(g_capabilities.sdbd_cap_version, sizeof(g_capabilities.sdbd_cap_version),
1974 "%d.%d", SDBD_CAP_VERSION_MAJOR, SDBD_CAP_VERSION_MINOR);
1977 static int is_support_usbproto()
1979 return (!strncmp(g_capabilities.usbproto_support, PLUGIN_RET_ENABLED, strlen(PLUGIN_RET_ENABLED)));
1982 static int is_support_sockproto()
1984 return (!strncmp(g_capabilities.sockproto_support, PLUGIN_RET_ENABLED, strlen(PLUGIN_RET_ENABLED)));
1987 #define EMULATOR_MODEL_NAME "Emulator"
1988 static void check_emulator_or_device()
1990 char model_name[256]={0,};
1993 // Get the model name from model_config.xml
1994 ret = get_device_name(model_name, sizeof model_name);
1996 if(!strncmp(model_name, EMULATOR_MODEL_NAME, sizeof(EMULATOR_MODEL_NAME))){
1998 I("This target type is Emulator\n");
2001 I("This target type is Device\n");
2005 E("failed to get the model name.\n");
2009 static void fork_prepare_handler(void)
2011 sdb_mutex_lock(&D_lock);
2014 static void fork_parent_handler(void)
2016 sdb_mutex_unlock(&D_lock);
2019 static void fork_child_handler(void)
2021 sdb_mutex_unlock(&D_lock);
2024 int sdb_main(int server_port)
2026 check_emulator_or_device();
2030 init_capabilities();
2033 //start_device_log();
2035 init_drop_privileges();
2036 init_sdk_requirements();
2037 if (!request_validity_to_plugin(PLUGIN_SYNC_CMD_VERIFY_LAUNCH, NULL)) {
2038 E("sdbd should be launched in develop mode.\n");
2044 pthread_atfork(fork_prepare_handler, fork_parent_handler, fork_child_handler);
2046 atexit(sdb_cleanup);
2047 #if defined(HAVE_FORKEXEC)
2048 // No SIGCHLD. Let the service subproc handle its children.
2049 signal(SIGPIPE, SIG_IGN);
2052 init_transport_registration();
2054 /* don't listen on a port (default 5037) if running in secure mode */
2055 /* don't run as root if we are running in secure mode */
2057 if (should_drop_privileges()) {
2059 struct __user_cap_header_struct header;
2060 struct __user_cap_data_struct cap;
2062 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
2065 /* add extra groups:
2066 ** SID_TTY to access /dev/ptmx
2068 gid_t groups[] = { SID_TTY, SID_APP_LOGGING, SID_SYS_LOGGING };
2069 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
2072 /* then switch user and group to "developer" */
2073 if (setgid(GID_DEVELOPER) != 0) {
2074 fprintf(stderr, "set group id failed errno: %d\n", errno);
2077 if (setuid(SID_DEVELOPER) != 0) {
2078 fprintf(stderr, "set user id failed errno: %d\n", errno);
2082 /* set CAP_SYS_BOOT capability, so "sdb reboot" will succeed */
2083 header.version = _LINUX_CAPABILITY_VERSION;
2085 cap.effective = cap.permitted = (1 << CAP_SYS_BOOT);
2086 cap.inheritable = 0;
2087 capset(&header, &cap);
2089 I("Local port disabled\n");
2091 char local_name[30];
2092 build_local_name(local_name, sizeof(local_name), server_port);
2093 if(install_listener(local_name, "*smartsocket*", NULL)) {
2098 /* choose the usb gadget backend */
2099 if (access(USB_NODE_FILE, F_OK) == 0) {
2100 /* legacy kernel-based sdb gadget */
2101 usb_init = &linux_usb_init;
2102 usb_cleanup = &linux_usb_cleanup;
2103 usb_write = &linux_usb_write;
2104 usb_read = &linux_usb_read;
2105 usb_close = &linux_usb_close;
2106 usb_kick = &linux_usb_kick;
2108 /* functionfs based gadget */
2109 usb_init = &ffs_usb_init;
2110 usb_cleanup = &ffs_usb_cleanup;
2111 usb_write = &ffs_usb_write;
2112 usb_read = &ffs_usb_read;
2113 usb_close = &ffs_usb_close;
2114 usb_kick = &ffs_usb_kick;
2117 if (is_support_usbproto()) {
2121 if (is_support_sockproto()) {
2122 /* by default don't listen on local transport but
2123 * listen if suitable command line argument has been provided */
2124 if (sdbd_commandline_args.sdbd_port >= 0) {
2125 local_init(sdbd_commandline_args.sdbd_port);
2127 local_init(DEFAULT_SDB_LOCAL_TRANSPORT_PORT);
2131 #if 0 /* tizen specific */
2132 D("sdb_main(): pre init_jdwp()\n");
2134 D("sdb_main(): post init_jdwp()\n");
2137 sdb_notify_startup(0, "READY=1");
2139 I("Event loop starting\n");
2143 if (is_support_usbproto()) {
2150 int copy_packet(apacket* dest, apacket* src) {
2153 E("dest packet is NULL\n");
2158 E("src packet is NULL\n");
2162 dest->next = src->next;
2163 dest->ptr = src->ptr;
2164 dest->len = src->len;
2166 int data_length = src->msg.data_length;
2167 if(data_length > MAX_PAYLOAD) {
2168 data_length = MAX_PAYLOAD;
2170 memcpy(&(dest->msg), &(src->msg), sizeof(amessage) + data_length);
2175 int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s)
2177 atransport *transport = NULL;
2180 if(!strcmp(service, "kill")) {
2181 fprintf(stderr,"sdb server killed by remote request\n");
2183 sdb_write(reply_fd, "OKAY", 4);
2184 if (is_support_usbproto()) {
2190 if(!strncmp(service,"forward:",8) || !strncmp(service,"killforward:",12)) {
2191 char *local, *remote, *err;
2193 atransport *transport;
2195 int createForward = strncmp(service,"kill",4);
2197 local = service + (createForward ? 8 : 12);
2198 remote = strchr(local,';');
2200 sendfailmsg(reply_fd, "malformed forward spec");
2205 if((local[0] == 0) || (remote[0] == 0) || (remote[0] == '*')){
2206 sendfailmsg(reply_fd, "malformed forward spec");
2210 transport = acquire_one_transport(CS_ANY, ttype, serial, &err);
2212 sendfailmsg(reply_fd, err);
2216 if (createForward) {
2217 r = install_listener(local, remote, transport);
2219 r = remove_listener(local, remote, transport);
2222 /* 1st OKAY is connect, 2nd OKAY is status */
2223 writex(reply_fd, "OKAYOKAY", 8);
2227 if (createForward) {
2228 sendfailmsg(reply_fd, (r == -1) ? "cannot rebind smartsocket" : "cannot bind socket");
2230 sendfailmsg(reply_fd, "cannot remove listener");
2235 if(!strncmp(service,"get-state",strlen("get-state"))) {
2236 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
2237 char *state = connection_state_name(transport);
2238 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(state),state);
2239 writex(reply_fd, buf, strlen(buf));
2245 int recovery_mode = 0;
2247 int main(int argc, char **argv)
2249 /* If sdbd runs inside the emulator this will enable sdb tracing via
2250 * sdb-debug qemud service in the emulator. */
2251 #if 0 /* tizen specific */
2252 sdb_qemu_trace_init();
2253 if((argc > 1) && (!strcmp(argv[1],"recovery"))) {
2254 sdb_device_banner = "recovery";
2259 apply_sdbd_commandline_defaults(&sdbd_commandline_args);
2260 int parse_ret = parse_sdbd_commandline(&sdbd_commandline_args, argc, argv);
2262 // TODO: Add detailed error messages
2263 // TODO: Add individual messages for help and usage
2264 if(parse_ret != SDBD_COMMANDLINE_SUCCESS) {
2265 if (parse_ret == SDBD_COMMANDLINE_HELP
2266 || parse_ret == SDBD_COMMANDLINE_USAGE) {
2267 // User requested help or usage
2268 print_sdbd_usage_message(stdout);
2269 return EXIT_SUCCESS;
2272 // Print usage message because of invalid options
2273 print_sdbd_usage_message(stderr);
2274 return EXIT_FAILURE;
2277 I("Handling main()\n");
2279 //sdbd will never die on emulator!
2280 signal(SIGTERM, handle_sig_term); /* tizen specific */
2281 return sdb_main(DEFAULT_SDB_PORT);