2 * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
4 * Licensed under the Apache License, Version 2.0 (the License);
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an AS IS BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #define TRACE_TAG TRACE_SDB
31 #include <tzplatform_config.h>
40 #include "commandline_sdbd.h"
45 #include "sdbd_plugin.h"
47 #ifdef SUPPORT_ENCRYPT
48 #include "plugin_encrypt.h"
52 #include <linux/prctl.h>
53 #define SDB_PIDPATH "/tmp/.sdbd.pid"
55 #include <system_info.h>
59 #define PROC_CMDLINE_PATH "/proc/cmdline"
60 #define USB_SERIAL_PATH "/sys/class/usb_mode/usb0/iSerial"
62 #include <sys/ioctl.h>
64 #include <netinet/in.h>
65 #include <arpa/inet.h>
66 #define GUEST_IP_INTERFACE "eth0"
68 SDB_MUTEX_DEFINE(zone_check_lock);
70 SDB_MUTEX_DEFINE( D_lock );
76 char* g_sdk_home_dir = NULL;
77 char* g_sdk_home_dir_env = NULL;
79 int rootshell_mode; // 0: sdk user, 1: root
80 int booting_done; // 0: platform booting is in progess 1: platform booting is done
87 struct group_info g_default_groups[] = {
88 {"priv_externalstorage", -1},
89 {"priv_externalstorage_appdata", -1},
90 {"priv_mediastorage", -1},
94 #define SDB_DEFAULT_GROUPS_CNT ((sizeof(g_default_groups)/sizeof(g_default_groups[0]))-1)
96 int is_init_sdk_userinfo = 0;
97 int is_pwlocked = 0; // 0 if unlocked, 1 otherwise
100 SdbdCommandlineArgs sdbd_commandline_args;
103 static int is_support_usbproto();
104 static int is_support_sockproto();
106 void (*usb_init)() = NULL;
107 void (*usb_cleanup)() = NULL;
108 int (*usb_write)(usb_handle *h, const void *data, int len) = NULL;
109 int (*usb_read)(usb_handle *h, void *data, size_t len) = NULL;
110 int (*usb_close)(usb_handle *h) = NULL;
111 void (*usb_kick)(usb_handle *h) = NULL;
113 int g_is_emulator = -1;
114 int is_emulator(void) {
118 if (g_is_emulator >= 0) {
119 return g_is_emulator;
121 D("failed to initialize check emulator\n");
124 return sdbd_commandline_args.emulator.host != NULL;
128 int is_container_enabled(void) {
131 ret = system_info_get_platform_bool("tizen.org/feature/container", &value);
132 if (ret != SYSTEM_INFO_ERROR_NONE) {
133 D("failed to get container information: %d\n", errno);
136 D("tizen container: %d\n", value);
144 void handle_sig_term(int sig) {
146 if (access(SDB_PIDPATH, F_OK) == 0)
147 sdb_unlink(SDB_PIDPATH);
151 static const char *sdb_device_banner = "device";
153 void fatal(const char *fmt, ...)
157 fprintf(stderr, "error: ");
158 vfprintf(stderr, fmt, ap);
159 fprintf(stderr, "\n");
164 void fatal_errno(const char *fmt, ...)
168 fprintf(stderr, "errno: %d: ", errno);
169 vfprintf(stderr, fmt, ap);
170 fprintf(stderr, "\n");
175 static int is_enable_sdbd_log()
177 return (!strncmp(g_capabilities.log_enable, PLUGIN_RET_ENABLED, strlen(PLUGIN_RET_ENABLED)));
182 /* read a comma/space/colum/semi-column separated list of tags
183 * from the SDB_TRACE environment variable and build the trace
184 * mask from it. note that '1' and 'all' are special cases to
187 void sdb_trace_init(void)
189 const char* p = getenv("SDB_TRACE");
192 static const struct {
198 { "sdb", TRACE_SDB },
199 { "sockets", TRACE_SOCKETS },
200 { "packets", TRACE_PACKETS },
201 { "rwx", TRACE_RWX },
202 { "usb", TRACE_USB },
203 { "sync", TRACE_SYNC },
204 { "sysdeps", TRACE_SYSDEPS },
205 { "transport", TRACE_TRANSPORT },
206 { "jdwp", TRACE_JDWP },
207 { "services", TRACE_SERVICES },
208 { "properties", TRACE_PROPERTIES },
209 { "sdktools", TRACE_SDKTOOLS },
210 { "appcmd", TRACE_APPCMD },
215 if (is_enable_sdbd_log())
221 /* use a comma/column/semi-colum/space separated list */
225 q = strpbrk(p, " ,:;");
231 for (tagn = 0; tags[tagn].tag != NULL; tagn++)
233 int taglen = strlen(tags[tagn].tag);
235 if (len == taglen && !memcmp(tags[tagn].tag, p, len) )
237 int flag = tags[tagn].flag;
242 sdb_trace_mask |= (1 << flag);
254 * Implements SDB tracing inside the emulator.
260 * Redefine open and write for qemu_pipe.h that contains inlined references
261 * to those routines. We will redifine them back after qemu_pipe.h inclusion.
266 #define open sdb_open
267 #define write sdb_write
268 #include "qemu_pipe.h"
271 #define open ___xxx_open
272 #define write ___xxx_write
274 /* A handle to sdb-debug qemud service in the emulator. */
275 int sdb_debug_qemu = -1;
277 /* Initializes connection with the sdb-debug qemud service in the emulator. */
278 #if 0 /* doen't support in Tizen */
279 static int sdb_qemu_trace_init(void)
283 if (sdb_debug_qemu >= 0) {
287 /* sdb debugging QEMUD service connection request. */
288 snprintf(con_name, sizeof(con_name), "qemud:sdb-debug");
289 sdb_debug_qemu = qemu_pipe_open(con_name);
290 return (sdb_debug_qemu >= 0) ? 0 : -1;
293 void sdb_qemu_trace(const char* fmt, ...)
299 if (sdb_debug_qemu >= 0) {
300 vsnprintf(msg, sizeof(msg), fmt, args);
301 sdb_write(sdb_debug_qemu, msg, strlen(msg));
305 #endif /* !SDB_HOST */
307 apacket *get_apacket(void)
309 apacket *p = malloc(sizeof(apacket));
310 if(p == 0) fatal("failed to allocate an apacket");
311 memset(p, 0, sizeof(apacket) - MAX_PAYLOAD);
315 void put_apacket(apacket *p)
323 void handle_online(void)
328 void handle_offline(atransport *t)
331 //Close the associated usb
332 run_transport_disconnects(t);
337 void print_packet(const char *label, apacket *p)
343 switch(p->msg.command){
344 case A_SYNC: tag = "SYNC"; break;
345 case A_CNXN: tag = "CNXN" ; break;
346 case A_OPEN: tag = "OPEN"; break;
347 case A_OKAY: tag = "OKAY"; break;
348 case A_CLSE: tag = "CLSE"; break;
349 case A_WRTE: tag = "WRTE"; break;
350 default: tag = "????"; break;
353 fprintf(stderr, "%s: %s %08x %08x %04x \"",
354 label, tag, p->msg.arg0, p->msg.arg1, p->msg.data_length);
355 count = p->msg.data_length;
357 if(count > DUMPMAX) {
364 if((*x >= ' ') && (*x < 127)) {
371 fprintf(stderr, tag);
375 #ifdef SUPPORT_ENCRYPT
377 desc. : 암호화 실패 메시지 전송
378 parameter : [in] apacket* p : sdbd로 들어온 메시지
379 [in] atransport *t : 현재 연결에 대한 atransport
380 [in] unsigned failed_value : 실패 값
382 void send_encr_fail(apacket* p, atransport *t, unsigned failed_value){
384 enc_p = get_apacket();
385 enc_p->msg.command = A_ENCR; // 암호화 메시지
386 enc_p->msg.arg0 = failed_value; // 실패값
387 enc_p->msg.arg1 = p->msg.arg1;
388 send_packet(enc_p, t);
389 //put_apacket(enc_p);
394 parameter : [in] apacket* p : sdbd로 들어온 메시지
395 [in/out] atransport *t : 현재 연결에 대한 atransport
396 ret : 0 : 정상적으로 메시지 전송
399 int handle_encr_packet(apacket* p, atransport *t){
400 static int sessionID = 0;
402 apacket* enc_p = NULL;
404 if(p->msg.arg0 == ENCR_SET_ON_REQ){ // hello 메시지인 경우
405 t->sessionID = sessionID;
406 if((retVal = security_init(t->sessionID, NULL)) == 1){ // 암호화 handshaking을 위한 init
407 if(security_parse_server_hello(t->sessionID, p) == 1){ // hello 메시지 파싱
408 D("security_parse_server_hello success\n");
409 enc_p = get_apacket();
410 if(security_gen_client_hello(t->sessionID, enc_p) == 1){ // hello 메시지 생성
411 D("security_gen_client_hello success\n");
412 enc_p->msg.command = A_ENCR;
413 enc_p->msg.arg0 = ENCR_SET_ON_REQ;
414 enc_p->msg.arg1 = p->msg.arg1;
416 send_packet(enc_p, t);
418 else { // hello 메시지 생성 실패
419 D("security_gen_client_hello error\n");
420 send_encr_fail(p, t, ENCR_ON_FAIL); // 암호화 on 실패 메시지 전송
421 t->encryption = ENCR_OFF; // 암호화 모드는 off
422 security_deinit(t->sessionID);
426 else{ // hello 메시지 파싱 실패
427 D("security_parse_server_hello error\n");
428 send_encr_fail(p, t, ENCR_ON_FAIL);
429 t->encryption = ENCR_OFF;
430 security_deinit(t->sessionID);
435 D("security_init error\n");
436 send_encr_fail(p, t, ENCR_ON_FAIL);
437 t->encryption = ENCR_OFF;
440 security_deinit(t->sessionID);
442 //here!! do security_deinit(), but when plugin pointer is null -> not deinit
446 else if(p->msg.arg0 == ENCR_SET_ON_OK){ // ack 메시지인 경우
447 if(security_parse_server_ack(t->sessionID, p) == 1){ // ack 메시지 파싱
448 enc_p = get_apacket();
449 if(security_gen_client_ack(t->sessionID, enc_p) == 1){ // ack 메시지 생성
450 D("security_gen_client_ack success\n");
451 enc_p->msg.command = A_ENCR;
452 enc_p->msg.arg0 = ENCR_SET_ON_OK;
453 enc_p->msg.arg1 = p->msg.arg1;
454 t->encryption = ENCR_ON;
455 send_packet(enc_p, t);
457 else { // ack 메시지 생성에 실패한 경우
458 D("security_gen_client_ack error\n");
459 send_encr_fail(p, t, ENCR_ON_FAIL);
460 t->encryption = ENCR_OFF;
461 security_deinit(t->sessionID);
465 else { // ack 메시지 파싱에 실패한 경우
466 D("security_parse_server_ack error\n");
467 send_encr_fail(p, t, ENCR_ON_FAIL);
468 t->encryption = ENCR_OFF;
469 security_deinit(t->sessionID);
473 else if(p->msg.arg0 == ENCR_SET_OFF){ // 암호화 모드 off 요청 메시지
474 if(t->encryption == ENCR_ON && security_deinit(t->sessionID) == 1){ // 현재 암호화 모드가 on 상태인 경우
475 enc_p = get_apacket();
476 t->encryption = ENCR_OFF; // 현재 연결에 대한 암호화 모드 off
477 enc_p->msg.command = A_ENCR;
478 enc_p->msg.arg0 = ENCR_SET_OFF;
479 enc_p->msg.arg1 = p->msg.arg1;
480 send_packet(enc_p, t);
482 else { // 암호화 모드 off에 실패한 경우
483 D("security_deinit error\n");
484 send_encr_fail(p, t, ENCR_OFF_FAIL); // 암호화 모드 off 실패 메시지 전송
488 else if(p->msg.arg0 == ENCR_GET){ // 암호화 모드의 상태 요청 메시지인 경우
489 enc_p = get_apacket();
490 enc_p->msg.command = A_ENCR;
491 enc_p->msg.arg0 = ENCR_GET; // 암호화 모드 status get메시지
492 enc_p->msg.arg1 = p->msg.arg1;
493 if(t->encryption == ENCR_ON){ // 암호화 모드가 on인 경우
494 enc_p->msg.data_length = 13;
495 strncpy((char*)enc_p->data, "encryption:on", enc_p->msg.data_length); // encryption:on 메시지 전송
496 } else if(t->encryption == ENCR_OFF){ // 암호화 모드가 off인 경우
497 enc_p->msg.data_length = 14;
498 strncpy((char*)enc_p->data, "encryption:off", enc_p->msg.data_length); // encryption:off 메시지 전송
500 send_packet(enc_p, t);
502 else if (p->msg.arg0 == ENCR_ON_FAIL) // 암호화 모드를 on 하는 도중 실패한 경우 받는 메시지
504 t->encryption = ENCR_OFF; // 암호화 모드를 다시 off
505 D("encryption on failed\n");
507 else if (p->msg.arg0 == ENCR_OFF_FAIL) // 암호화 모드를 off하는 도중 실패한 경우 받는 메시지
509 //t->encryption = ENCR_ON;
510 D("encryption off failed\n");
512 //put_apacket(enc_p);
519 static void send_ready(unsigned local, unsigned remote, atransport *t)
521 D("Calling send_ready \n");
522 apacket *p = get_apacket();
523 p->msg.command = A_OKAY;
525 p->msg.arg1 = remote;
529 static void send_close(unsigned local, unsigned remote, atransport *t)
531 D("Calling send_close \n");
532 apacket *p = get_apacket();
533 p->msg.command = A_CLSE;
535 p->msg.arg1 = remote;
539 static void send_connect(atransport *t)
541 D("Calling send_connect \n");
542 apacket *cp = get_apacket();
543 cp->msg.command = A_CNXN;
544 cp->msg.arg0 = A_VERSION;
545 #ifdef SUPPORT_ENCRYPT
546 cp->msg.arg1 = MAX_PAYLOAD - 100; // connection 시, sdb server의 패킷 크기를 암호화 오버로드 만큼 줄임
548 cp->msg.arg1 = MAX_PAYLOAD;
550 char device_name[256]={0,};
553 if (request_lock_state_to_plugin(LOCKTYPE_PASSWORD) == 1) {
555 t->connection_state = CS_PWLOCK;
559 r = get_emulator_name(device_name, sizeof device_name);
561 r = get_device_name(device_name, sizeof device_name);
564 snprintf((char*) cp->data, sizeof cp->data, "%s::%s::%d", sdb_device_banner, DEFAULT_DEVICENAME, status);
566 snprintf((char*) cp->data, sizeof cp->data, "%s::%s::%d", sdb_device_banner, device_name, status);
569 D("CNXN data:%s\n", (char*)cp->data);
570 cp->msg.data_length = strlen((char*) cp->data) + 1;
574 /* XXX why sleep here? */
575 // allow the device some time to respond to the connect message
580 void send_device_status()
582 D("broadcast device status\n");
583 apacket* cp = get_apacket();
584 cp->msg.command = A_STAT;
585 cp->msg.arg0 = is_pwlocked;
588 broadcast_transport(cp);
590 //all broadcasted packets are memory copied
591 //so, we should call put_apacket
595 static char *connection_state_name(atransport *t)
601 switch(t->connection_state) {
613 static int get_str_cmdline(char *src, char *dest, char str[], int str_size) {
614 char *s = strstr(src, dest);
618 char *e = strstr(s, " ");
623 int len = e-s-strlen(dest);
625 if (len >= str_size) {
626 D("buffer size(%d) should be bigger than %d\n", str_size, len+1);
630 strncpy(str, s + strlen(dest), len);
635 int get_emulator_forward_port() {
636 SdbdCommandlineArgs *sdbd_args = &sdbd_commandline_args; /* alias */
638 if (sdbd_args->emulator.host == NULL) {
642 return sdbd_args->emulator.port;
645 int get_emulator_name(char str[], int str_size) {
646 SdbdCommandlineArgs *sdbd_args = &sdbd_commandline_args; /* alias */
648 if (sdbd_args->emulator.host == NULL) {
652 s_strncpy(str, sdbd_args->emulator.host, str_size);
656 int get_device_name(char str[], int str_size) {
658 int r = system_info_get_platform_string("http://tizen.org/system/model_name", &value);
659 if (r != SYSTEM_INFO_ERROR_NONE) {
660 D("fail to get system model:%d\n", errno);
663 s_strncpy(str, value, str_size);
664 D("returns model_name:%s\n", value);
671 int fd = unix_open(USB_SERIAL_PATH, O_RDONLY);
673 D("fail to read:%s (%d)\n", USB_SERIAL_PATH, errno);
677 if(read_line(fd, str, str_size)) {
678 D("device serial name: %s\n", str);
687 static int get_cmdline_value(char *split, char str[], int str_size) {
689 int fd = unix_open(PROC_CMDLINE_PATH, O_RDONLY);
692 D("fail to read /proc/cmdline\n");
695 if(read_line(fd, cmdline, sizeof(cmdline))) {
696 D("qemu cmd: %s\n", cmdline);
697 if (get_str_cmdline(cmdline, split, str, str_size) < 1) {
698 D("could not get the (%s) value from cmdline\n", split);
707 int get_emulator_hostip(char str[], int str_size) {
708 return get_cmdline_value("host_ip=", str, str_size);
711 int get_emulator_guestip(char str[], int str_size) {
714 struct sockaddr_in *sin;
716 s = socket(AF_INET, SOCK_DGRAM, 0);
722 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s", GUEST_IP_INTERFACE);
723 if(ioctl(s, SIOCGIFHWADDR, &ifr) < 0) {
724 D("ioctl hwaddr error\n");
729 if(ioctl(s, SIOCGIFADDR, &ifr) < 0) {
730 D("ioctl addr error\n");
734 sin = (struct sockaddr_in *)&ifr.ifr_addr;
735 snprintf(str, str_size, "%s", inet_ntoa(sin->sin_addr));
741 void parse_banner(char *banner, atransport *t)
743 char *type, *product, *end;
745 D("parse_banner: %s\n", banner);
747 product = strchr(type, ':');
754 /* remove trailing ':' */
755 end = strchr(product, ':');
758 /* save product name in device structure */
759 if (t->product == NULL) {
760 t->product = strdup(product);
761 } else if (strcmp(product, t->product) != 0) {
763 t->product = strdup(product);
766 if(!strcmp(type, "bootloader")){
767 D("setting connection_state to CS_BOOTLOADER\n");
768 t->connection_state = CS_BOOTLOADER;
773 if(!strcmp(type, "device")) {
774 D("setting connection_state to CS_DEVICE\n");
775 t->connection_state = CS_DEVICE;
780 if(!strcmp(type, "recovery")) {
781 D("setting connection_state to CS_RECOVERY\n");
782 t->connection_state = CS_RECOVERY;
787 if(!strcmp(type, "sideload")) {
788 D("setting connection_state to CS_SIDELOAD\n");
789 t->connection_state = CS_SIDELOAD;
794 t->connection_state = CS_HOST;
797 static void update_version(atransport *t, int version, size_t payload)
799 #ifdef SUPPORT_ENCRYPT
800 size_t max_payload = MAX_PAYLOAD - 100;
802 size_t max_payload = MAX_PAYLOAD;
804 t->protocol_version = min(version, A_VERSION);
805 t->max_payload = min(payload, max_payload);
806 D("update transport version. version=%x, max_payload=%d\n", t->protocol_version, t->max_payload);
809 void handle_packet(apacket *p, atransport *t)
812 int result = access((const char *) p, F_OK);
813 if ((result == -1) && (errno == EFAULT)) {
814 fatal("Invalid apacket = [0x%p]", p);
819 D("handle_packet() %c%c%c%c\n", ((char*) (&(p->msg.command)))[0],
820 ((char*) (&(p->msg.command)))[1],
821 ((char*) (&(p->msg.command)))[2],
822 ((char*) (&(p->msg.command)))[3]);
824 print_packet("recv", p);
826 switch(p->msg.command){
830 if(HOST) send_connect(t);
832 t->connection_state = CS_OFFLINE;
838 case A_CNXN: /* CONNECT(version, maxdata, "system-id-string") */
839 /* XXX verify version, etc */
840 if(t->connection_state != CS_OFFLINE) {
841 t->connection_state = CS_OFFLINE;
844 update_version(t, p->msg.arg0, p->msg.arg1);
845 parse_banner((char*) p->data, t);
847 if(!HOST) send_connect(t);
850 case A_OPEN: /* OPEN(local-id, 0, "destination") */
851 if (request_lock_state_to_plugin(LOCKTYPE_PASSWORD) == 1 && t->connection_state == CS_PWLOCK) {
852 // in case of already locked before get A_CNXN
853 D("open failed due to password locked before get A_CNXN:%d\n", t->connection_state);
854 send_close(0, p->msg.arg0, t);
856 if(t->connection_state != CS_OFFLINE) {
857 char *name = (char*) p->data;
858 name[p->msg.data_length > 0 ? p->msg.data_length - 1 : 0] = 0;
859 s = create_local_service_socket(name);
861 send_close(0, p->msg.arg0, t);
863 s->peer = create_remote_socket(p->msg.arg0, t);
865 send_ready(s->id, s->peer->id, t);
872 case A_OKAY: /* READY(local-id, remote-id, "") */
873 if(t->connection_state != CS_OFFLINE) {
874 if((s = find_local_socket(p->msg.arg1))) {
876 s->peer = create_remote_socket(p->msg.arg0, t);
884 case A_CLSE: /* CLOSE(local-id, remote-id, "") */
885 if(t->connection_state != CS_OFFLINE) {
886 if((s = find_local_socket(p->msg.arg1))) {
893 if(t->connection_state != CS_OFFLINE) {
894 if((s = find_local_socket(p->msg.arg1))) {
895 unsigned rid = p->msg.arg0;
896 p->len = p->msg.data_length;
898 if(s->enqueue(s, p) == 0) {
899 D("Enqueue the socket\n");
900 send_ready(s->id, rid, t);
906 #ifdef SUPPORT_ENCRYPT
907 case A_ENCR: // 암호화 메시지인 경우
908 if(t->connection_state != CS_OFFLINE) {
909 handle_encr_packet(p, t);
915 printf("handle_packet: what is %08x?!\n", p->msg.command);
921 alistener listener_list = {
922 .next = &listener_list,
923 .prev = &listener_list,
926 static void ss_listener_event_func(int _fd, unsigned ev, void *_l)
931 struct sockaddr addr;
936 fd = sdb_socket_accept(_fd, &addr, &alen);
939 sdb_socket_setbufsize(fd, CHUNK_SIZE);
941 s = create_local_socket(fd);
943 connect_to_smartsocket(s);
951 static void listener_event_func(int _fd, unsigned ev, void *_l)
957 struct sockaddr addr;
962 fd = sdb_socket_accept(_fd, &addr, &alen);
965 s = create_local_socket(fd);
967 s->transport = l->transport;
968 connect_to_remote(s, l->connect_to);
976 static void free_listener(alistener* l)
979 l->next->prev = l->prev;
980 l->prev->next = l->next;
981 l->next = l->prev = l;
984 // closes the corresponding fd
985 fdevent_remove(&l->fde);
988 free((char*)l->local_name);
991 free((char*)l->connect_to);
994 remove_transport_disconnect(l->transport, &l->disconnect);
999 static void listener_disconnect(void* _l, atransport* t)
1006 int local_name_to_fd(const char *name)
1010 if(!strncmp("tcp:", name, 4)){
1012 port = atoi(name + 4);
1013 ret = socket_loopback_server(port, SOCK_STREAM);
1016 #ifndef HAVE_WIN32_IPC /* no Unix-domain sockets on Win32 */
1017 // It's non-sensical to support the "reserved" space on the sdb host side
1018 if(!strncmp(name, "local:", 6)) {
1019 return socket_local_server(name + 6,
1020 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
1021 } else if(!strncmp(name, "localabstract:", 14)) {
1022 return socket_local_server(name + 14,
1023 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
1024 } else if(!strncmp(name, "localfilesystem:", 16)) {
1025 return socket_local_server(name + 16,
1026 ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
1030 printf("unknown local portname '%s'\n", name);
1034 static int remove_listener(const char *local_name, const char *connect_to, atransport* transport)
1038 for (l = listener_list.next; l != &listener_list; l = l->next) {
1039 if (!strcmp(local_name, l->local_name) &&
1040 !strcmp(connect_to, l->connect_to) &&
1041 l->transport && l->transport == transport) {
1043 listener_disconnect(l, transport);
1051 static int install_listener(const char *local_name, const char *connect_to, atransport* transport)
1055 //printf("install_listener('%s','%s')\n", local_name, connect_to);
1057 for(l = listener_list.next; l != &listener_list; l = l->next){
1058 if(strcmp(local_name, l->local_name) == 0) {
1061 /* can't repurpose a smartsocket */
1062 if(l->connect_to[0] == '*') {
1066 cto = strdup(connect_to);
1071 //printf("rebinding '%s' to '%s'\n", local_name, connect_to);
1072 free((void*) l->connect_to);
1073 l->connect_to = cto;
1074 if (l->transport != transport) {
1075 remove_transport_disconnect(l->transport, &l->disconnect);
1076 l->transport = transport;
1077 add_transport_disconnect(l->transport, &l->disconnect);
1083 if((l = calloc(1, sizeof(alistener))) == 0) goto nomem;
1084 if((l->local_name = strdup(local_name)) == 0) goto nomem;
1085 if((l->connect_to = strdup(connect_to)) == 0) goto nomem;
1088 l->fd = local_name_to_fd(local_name);
1090 free((void*) l->local_name);
1091 free((void*) l->connect_to);
1093 printf("cannot bind '%s'\n", local_name);
1097 if (close_on_exec(l->fd) < 0) {
1098 D("fail to close fd exec:%d\n",l->fd);
1100 if(!strcmp(l->connect_to, "*smartsocket*")) {
1101 fdevent_install(&l->fde, l->fd, ss_listener_event_func, l);
1103 fdevent_install(&l->fde, l->fd, listener_event_func, l);
1105 fdevent_set(&l->fde, FDE_READ);
1107 l->next = &listener_list;
1108 l->prev = listener_list.prev;
1111 l->transport = transport;
1114 l->disconnect.opaque = l;
1115 l->disconnect.func = listener_disconnect;
1116 add_transport_disconnect(transport, &l->disconnect);
1121 fatal("cannot allocate listener");
1125 #ifdef HAVE_WIN32_PROC
1126 static BOOL WINAPI ctrlc_handler(DWORD type)
1128 exit(STATUS_CONTROL_C_EXIT);
1133 static void sdb_cleanup(void)
1135 clear_sdbd_commandline_args(&sdbd_commandline_args);
1137 if (is_support_usbproto()) {
1140 // if(required_pid > 0) {
1141 // kill(required_pid, SIGKILL);
1144 unload_sdbd_plugin();
1147 void start_logging(void)
1149 #ifdef HAVE_WIN32_PROC
1150 char temp[ MAX_PATH ];
1154 GetTempPath( sizeof(temp) - 8, temp );
1155 strcat( temp, "sdb.log" );
1157 /* Win32 specific redirections */
1158 fnul = fopen( "NUL", "rt" );
1162 flog = fopen( temp, "at" );
1166 setvbuf( flog, NULL, _IONBF, 0 );
1168 stdout[0] = flog[0];
1169 stderr[0] = flog[0];
1170 fprintf(stderr,"--- sdb starting (pid %d) ---\n", getpid());
1174 fd = unix_open("/dev/null", O_RDONLY);
1176 // hopefully not gonna happen
1182 fd = unix_open("/tmp/sdb.log", O_WRONLY | O_CREAT | O_APPEND, 0640);
1184 fd = unix_open("/dev/null", O_WRONLY);
1186 // hopefully not gonna happen
1193 fprintf(stderr,"--- sdb starting (pid %d) ---\n", getpid());
1199 void start_device_log(void)
1202 char path[PATH_MAX] = {0, };
1203 char path_folder[PATH_MAX] = {0, };
1204 char path_file[PATH_MAX] = {0, };
1207 // char value[PROPERTY_VALUE_MAX];
1208 const char* p_trace = getenv("SDB_TRACE");
1209 const char* p_path = getenv("SDBD_LOG_PATH");
1210 // read the trace mask from persistent property persist.sdb.trace_mask
1211 // give up if the property is not set or cannot be parsed
1213 if ((p_trace == NULL ) && !is_enable_sdbd_log()) {
1218 snprintf(path_folder, sizeof(path_folder), "%s", p_path);
1219 else if (g_capabilities.log_path[0] != '\0')
1220 snprintf(path_folder, sizeof(path_folder), "%s", g_capabilities.log_path);
1226 localtime_r(&t, &now);
1228 strftime(path_file, sizeof(path_file),
1229 "sdbd-%Y-%m-%d-%H-%M-%S.txt",
1232 snprintf(path, sizeof(path), "%s/%s", path_folder, path_file);
1234 fd = unix_open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1239 // redirect stdout and stderr to the log file
1242 fprintf(stderr,"--- sdbd starting (pid %d) ---\n", getpid());
1245 fd = unix_open("/dev/null", O_RDONLY);
1247 // hopefully not gonna happen
1254 int daemonize(void) {
1256 // set file creation mask to 0
1268 FILE *f = fopen(SDB_PIDPATH, "w");
1271 fprintf(f, "%d\n", getpid());
1279 D("sdbd: unable to change working directory to /\n");
1286 int launch_server(int server_port)
1288 #ifdef HAVE_WIN32_PROC
1289 /* we need to start the server in the background */
1290 /* we create a PIPE that will be used to wait for the server's "OK" */
1291 /* message since the pipe handles must be inheritable, we use a */
1292 /* security attribute */
1293 HANDLE pipe_read, pipe_write;
1294 SECURITY_ATTRIBUTES sa;
1295 STARTUPINFO startup;
1296 PROCESS_INFORMATION pinfo;
1297 char program_path[ MAX_PATH ];
1300 sa.nLength = sizeof(sa);
1301 sa.lpSecurityDescriptor = NULL;
1302 sa.bInheritHandle = TRUE;
1304 /* create pipe, and ensure its read handle isn't inheritable */
1305 ret = CreatePipe( &pipe_read, &pipe_write, &sa, 0 );
1307 fprintf(stderr, "CreatePipe() failure, error %ld\n", GetLastError() );
1311 SetHandleInformation( pipe_read, HANDLE_FLAG_INHERIT, 0 );
1313 ZeroMemory( &startup, sizeof(startup) );
1314 startup.cb = sizeof(startup);
1315 startup.hStdInput = GetStdHandle( STD_INPUT_HANDLE );
1316 startup.hStdOutput = pipe_write;
1317 startup.hStdError = GetStdHandle( STD_ERROR_HANDLE );
1318 startup.dwFlags = STARTF_USESTDHANDLES;
1320 ZeroMemory( &pinfo, sizeof(pinfo) );
1322 /* get path of current program */
1323 GetModuleFileName( NULL, program_path, sizeof(program_path) );
1325 ret = CreateProcess(
1326 program_path, /* program path */
1327 "sdb fork-server server",
1328 /* the fork-server argument will set the
1329 debug = 2 in the child */
1330 NULL, /* process handle is not inheritable */
1331 NULL, /* thread handle is not inheritable */
1332 TRUE, /* yes, inherit some handles */
1333 DETACHED_PROCESS, /* the new process doesn't have a console */
1334 NULL, /* use parent's environment block */
1335 NULL, /* use parent's starting directory */
1336 &startup, /* startup info, i.e. std handles */
1339 CloseHandle( pipe_write );
1342 fprintf(stderr, "CreateProcess failure, error %ld\n", GetLastError() );
1343 CloseHandle( pipe_read );
1347 CloseHandle( pinfo.hProcess );
1348 CloseHandle( pinfo.hThread );
1350 /* wait for the "OK\n" message */
1355 ret = ReadFile( pipe_read, temp, 3, &count, NULL );
1356 CloseHandle( pipe_read );
1358 fprintf(stderr, "could not read ok from SDB Server, error = %ld\n", GetLastError() );
1361 if (count != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
1362 fprintf(stderr, "SDB server didn't ACK\n" );
1366 #elif defined(HAVE_FORKEXEC)
1367 char path[PATH_MAX];
1370 // set up a pipe so the child can tell us when it is ready.
1371 // fd[0] will be parent's end, and fd[1] will get mapped to stderr in the child.
1373 fprintf(stderr, "pipe failed in launch_server, errno: %d\n", errno);
1376 get_my_path(path, PATH_MAX);
1378 if(pid < 0) return -1;
1381 // child side of the fork
1383 // redirect stderr to the pipe
1384 // we use stderr instead of stdout due to stdout's buffering behavior.
1386 dup2(fd[1], STDERR_FILENO);
1390 int result = execl(path, "sdb", "fork-server", "server", NULL);
1391 // this should not return
1392 fprintf(stderr, "OOPS! execl returned %d, errno: %d\n", result, errno);
1394 // parent side of the fork
1398 temp[0] = 'A'; temp[1] = 'B'; temp[2] = 'C';
1399 // wait for the "OK\n" message
1401 int ret = sdb_read(fd[0], temp, 3);
1402 int saved_errno = errno;
1405 fprintf(stderr, "could not read ok from SDB Server, errno = %d\n", saved_errno);
1408 if (ret != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
1409 fprintf(stderr, "SDB server didn't ACK\n" );
1416 #error "cannot implement background server start on this platform"
1422 /* Constructs a local name of form tcp:port.
1423 * target_str points to the target string, it's content will be overwritten.
1424 * target_size is the capacity of the target string.
1425 * server_port is the port number to use for the local name.
1427 void build_local_name(char* target_str, size_t target_size, int server_port)
1429 snprintf(target_str, target_size, "tcp:%d", server_port);
1433 static void init_drop_privileges() {
1434 #ifdef _DROP_PRIVILEGE
1441 int should_drop_privileges() {
1442 if (rootshell_mode == 1) { // if root, then don't drop
1448 #include <dbus/dbus.h>
1449 #include <dbus/dbus-glib.h>
1450 #include <dbus/dbus-glib-lowlevel.h>
1452 #define BOOTING_DONE_SIGNAL "BootingDone"
1453 #define DEVICED_CORE_INTERFACE "org.tizen.system.deviced.core"
1454 #define SDBD_BOOT_INFO_FILE "/tmp/sdbd_boot_info"
1456 static DBusHandlerResult __sdbd_dbus_signal_filter(DBusConnection *conn,
1457 DBusMessage *message, void *user_data) {
1458 D("got dbus message\n");
1459 const char *interface;
1462 dbus_error_init(&error);
1464 interface = dbus_message_get_interface(message);
1465 if (interface == NULL) {
1466 D("reject by security issue - no interface\n");
1467 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1470 if (dbus_message_is_signal(message, DEVICED_CORE_INTERFACE,
1471 BOOTING_DONE_SIGNAL)) {
1473 if (access(SDBD_BOOT_INFO_FILE, F_OK) == 0) {
1474 D("booting is done before\n");
1476 FILE *f = fopen(SDBD_BOOT_INFO_FILE, "w");
1478 fprintf(f, "%d", 1);
1482 D("booting is done\n");
1485 D("handled dbus message\n");
1486 return DBUS_HANDLER_RESULT_HANDLED;
1489 static void *bootdone_cb(void *x) {
1490 int MAX_LOCAL_BUFSZ = 128;
1492 DBusConnection *bus;
1493 char rule[MAX_LOCAL_BUFSZ];
1494 GMainLoop *mainloop;
1496 /* g_type_init() is deprecated for glib version 2.35.0 or greater, */
1497 #if !GLIB_CHECK_VERSION(2,35,0)
1501 dbus_error_init(&error);
1502 bus = dbus_bus_get(DBUS_BUS_SYSTEM, &error);
1504 D("Failed to connect to the D-BUS daemon: %s", error.message);
1505 dbus_error_free(&error);
1508 dbus_connection_setup_with_g_main(bus, NULL);
1510 snprintf(rule, MAX_LOCAL_BUFSZ, "type='signal',interface='%s'",
1511 DEVICED_CORE_INTERFACE);
1512 /* listening to messages */
1513 dbus_bus_add_match(bus, rule, &error);
1514 if (dbus_error_is_set(&error)) {
1515 D("Fail to rule set: %s", error.message);
1516 dbus_error_free(&error);
1520 if (dbus_connection_add_filter(bus, __sdbd_dbus_signal_filter, NULL, NULL)
1524 D("booting signal initialized\n");
1525 mainloop = g_main_loop_new(NULL, FALSE);
1526 g_main_loop_run(mainloop);
1528 D("dbus loop exited");
1533 void register_bootdone_cb() {
1534 D("registerd bootdone callback\n");
1537 if (sdb_thread_create(&t, bootdone_cb, NULL)) {
1538 D("cannot create service thread\n");
1543 static int sdbd_set_groups() {
1544 gid_t *group_ids = NULL;
1547 int group_match = 0;
1548 int added_group_cnt = 0;
1550 getgrouplist(SDK_USER_NAME, g_sdk_group_id, NULL, &ngroups);
1551 D("group list : ngroups = %d\n", ngroups);
1552 group_ids = malloc((ngroups + SDB_DEFAULT_GROUPS_CNT) * sizeof(gid_t));
1553 if (group_ids == NULL) {
1554 D("failed to allocate group_ids(%d)\n", (ngroups + SDB_DEFAULT_GROUPS_CNT) * sizeof(gid_t));
1557 if (getgrouplist(SDK_USER_NAME, g_sdk_group_id, group_ids, &ngroups) == -1) {
1558 D("failed to getgrouplist(), ngroups = %d\n", ngroups);
1563 for (i = 0; g_default_groups[i].name != NULL; i++) {
1564 for (j = 0; j < ngroups; j++) {
1565 if (group_ids[j] == g_default_groups[i].gid) {
1570 if (group_match == 0 && g_default_groups[i].gid != -1) {
1571 group_ids[ngroups + added_group_cnt] = g_default_groups[i].gid;
1577 if (setgroups(ngroups+added_group_cnt, group_ids) != 0) {
1578 D("failed to setgroups().\n");
1587 static int sdbd_get_user_pwd(const char* user_name, struct passwd* pwd, char* buf, size_t bufsize) {
1588 struct passwd *result = NULL;
1591 ret = getpwnam_r(user_name, pwd, buf, bufsize, &result);
1592 if (result == NULL) {
1594 D("Not found passwd : username(%s)\n", user_name);
1597 D("failed to getpwnam_r\n");
1605 static int sdbd_get_group(const char* group_name, struct group* grp, char* buf, size_t bufsize) {
1606 struct group *result = NULL;
1609 ret = getgrnam_r(group_name, grp, buf, bufsize, &result);
1610 if (result == NULL) {
1612 D("Not found group : groupname(%s)\n", group_name);
1615 D("failed to getgrnam_r\n");
1623 int set_sdk_user_privileges() {
1624 if (!is_init_sdk_userinfo) {
1625 D("failed to init sdk user information.\n");
1629 if (sdbd_set_groups() < 0) {
1630 D("set groups failed (errno: %d)\n", errno);
1634 if (setgid(g_sdk_group_id) != 0) {
1635 D("set group id failed (errno: %d)\n", errno);
1639 if (setuid(g_sdk_user_id) != 0) {
1640 D("set user id failed (errno: %d)\n", errno);
1644 if (chdir(g_sdk_home_dir) < 0) {
1645 D("unable to change working directory to %s\n", g_sdk_home_dir);
1648 // TODO: use pam later
1649 if (g_sdk_home_dir_env) {
1650 putenv(g_sdk_home_dir_env);
1656 #define SDB_PW_GR_DEFAULT_SIZE (16*1024)
1657 static long get_passwd_bufsize() {
1660 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
1662 bufsize = SDB_PW_GR_DEFAULT_SIZE;
1668 static long get_group_bufsize() {
1671 bufsize = sysconf(_SC_GETGR_R_SIZE_MAX);
1673 bufsize = SDB_PW_GR_DEFAULT_SIZE;
1679 static int init_sdb_default_groups() {
1685 bufsize = get_group_bufsize();
1686 buf = malloc(bufsize);
1688 D("failed to allocate gruop buf(%ld)\n", bufsize);
1692 for (i = 0; g_default_groups[i].name != NULL; i++) {
1693 memset(buf, 0, bufsize);
1694 if (sdbd_get_group(g_default_groups[i].name, &grp, buf, bufsize) == 0) {
1695 g_default_groups[i].gid = grp.gr_gid;
1697 D("failed get group info.(errno: %d)\n", errno);
1705 static void set_static_userinfo() {
1706 g_sdk_user_id = STATIC_SDK_USER_ID;
1707 g_sdk_group_id = STATIC_SDK_GROUP_ID;
1708 g_sdk_home_dir = STATIC_SDK_HOME_DIR;
1711 static int init_sdk_userinfo() {
1716 if (is_init_sdk_userinfo) {
1720 if (init_sdb_default_groups() < 0) {
1721 D("failed to initialize default groups.\n");
1724 bufsize = get_passwd_bufsize();
1725 buf = malloc(bufsize);
1727 D("failed to allocate passwd buf(%ld)\n", bufsize);
1728 set_static_userinfo();
1730 if (sdbd_get_user_pwd(SDK_USER_NAME, &pwd, buf, bufsize) < 0) {
1731 D("get user passwd info.(errno: %d)\n", errno);
1732 set_static_userinfo();
1734 D("username=%s, uid=%d, gid=%d, dir=%s\n", pwd.pw_name, pwd.pw_uid, pwd.pw_gid, pwd.pw_dir);
1736 g_sdk_user_id = pwd.pw_uid;
1737 g_sdk_group_id = pwd.pw_gid;
1738 g_sdk_home_dir = strdup(pwd.pw_dir);
1743 int env_size = strlen("HOME=") + strlen(g_sdk_home_dir) + 1;
1744 g_sdk_home_dir_env = malloc(env_size);
1745 if(g_sdk_home_dir_env == NULL) {
1746 D("failed to allocate for home dir env string\n");
1748 snprintf(g_sdk_home_dir_env, env_size, "HOME=%s", g_sdk_home_dir);
1751 is_init_sdk_userinfo = 1;
1755 static void init_sdk_requirements() {
1758 // set env variable for temporary
1759 // TODO: should use pam instead later!!
1760 if (!getenv("TERM")) {
1761 putenv("TERM=linux");
1764 if (!getenv("HOME")) {
1765 putenv("HOME=/root");
1768 init_sdk_userinfo();
1770 if (g_sdk_home_dir != NULL && stat(g_sdk_home_dir, &st) == 0) {
1771 if (st.st_uid != g_sdk_user_id || st.st_gid != g_sdk_group_id) {
1773 snprintf(cmd, sizeof(cmd), "chown %s:%s %s -R", SDK_USER_NAME, SDK_USER_NAME, g_sdk_home_dir);
1774 if (system(cmd) < 0) {
1775 D("failed to change ownership to sdk user to %s\n", g_sdk_home_dir);
1780 if (is_emulator()) {
1781 register_bootdone_cb();
1784 #endif /* !SDB_HOST */
1786 static void init_capabilities(void) {
1790 memset(&g_capabilities, 0, sizeof(g_capabilities));
1792 // CPU Architecture of model
1793 ret = system_info_get_platform_string("http://tizen.org/feature/platform.core.cpu.arch", &value);
1794 if (ret != SYSTEM_INFO_ERROR_NONE) {
1795 snprintf(g_capabilities.cpu_arch, sizeof(g_capabilities.cpu_arch),
1797 D("fail to get the CPU architecture of model:%d\n", errno);
1799 snprintf(g_capabilities.cpu_arch, sizeof(g_capabilities.cpu_arch),
1801 if (value != NULL) {
1807 // Secure protocol support
1808 if(!request_capability_to_plugin(CAPABILITY_SECURE, g_capabilities.secure_protocol,
1809 sizeof(g_capabilities.secure_protocol))) {
1810 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_SECURE);
1811 snprintf(g_capabilities.secure_protocol, sizeof(g_capabilities.secure_protocol),
1816 // Interactive shell support
1817 if(!request_capability_to_plugin(CAPABILITY_INTER_SHELL, g_capabilities.intershell_support,
1818 sizeof(g_capabilities.intershell_support))) {
1819 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_INTER_SHELL);
1820 snprintf(g_capabilities.intershell_support, sizeof(g_capabilities.intershell_support),
1825 // File push/pull support
1826 if(!request_capability_to_plugin(CAPABILITY_FILESYNC, g_capabilities.filesync_support,
1827 sizeof(g_capabilities.filesync_support))) {
1828 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_FILESYNC);
1829 snprintf(g_capabilities.filesync_support, sizeof(g_capabilities.filesync_support),
1834 // USB protocol support
1835 if(!request_capability_to_plugin(CAPABILITY_USB_PROTOCOL, g_capabilities.usbproto_support,
1836 sizeof(g_capabilities.usbproto_support))) {
1837 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_USB_PROTOCOL);
1838 snprintf(g_capabilities.usbproto_support, sizeof(g_capabilities.usbproto_support),
1843 // Socket protocol support
1844 if(!request_capability_to_plugin(CAPABILITY_SOCK_PROTOCOL, g_capabilities.sockproto_support,
1845 sizeof(g_capabilities.sockproto_support))) {
1846 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_SOCK_PROTOCOL);
1847 snprintf(g_capabilities.sockproto_support, sizeof(g_capabilities.sockproto_support),
1852 // Root command support
1853 if(!request_capability_to_plugin(CAPABILITY_ROOT_ONOFF, g_capabilities.rootonoff_support,
1854 sizeof(g_capabilities.rootonoff_support))) {
1855 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_ROOT_ONOFF);
1856 snprintf(g_capabilities.rootonoff_support, sizeof(g_capabilities.rootonoff_support),
1861 // Encryption support
1862 if(!request_capability_to_plugin(CAPABILITY_ENCRYPTION, g_capabilities.encryption_support,
1863 sizeof(g_capabilities.encryption_support))) {
1864 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_ENCRYPTION);
1865 snprintf(g_capabilities.encryption_support, sizeof(g_capabilities.encryption_support),
1870 // pkgcmd debug mode support
1871 if(!request_capability_to_plugin(CAPABILITY_DEBUGMODE, g_capabilities.pkgcmd_debugmode,
1872 sizeof(g_capabilities.pkgcmd_debugmode))) {
1873 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_DEBUGMODE);
1874 snprintf(g_capabilities.pkgcmd_debugmode, sizeof(g_capabilities.pkgcmd_debugmode),
1880 ret = is_container_enabled();
1881 snprintf(g_capabilities.zone_support, sizeof(g_capabilities.zone_support),
1882 "%s", ret == 1 ? ENABLED : DISABLED);
1884 // Multi-User support
1885 // XXX: There is no clear way to determine whether multi-user support.
1886 // Since TZ_SYS_DEFAULT_USER is set to "owner" for multi-user support,
1887 // guess whether multiuser support through that information.
1888 const char* sys_default_user = tzplatform_getenv(TZ_SYS_DEFAULT_USER);
1889 if (sys_default_user != NULL && !strcmp(sys_default_user, "owner")) {
1890 snprintf(g_capabilities.multiuser_support, sizeof(g_capabilities.multiuser_support),
1893 snprintf(g_capabilities.multiuser_support, sizeof(g_capabilities.multiuser_support),
1897 // Window size synchronization support
1898 snprintf(g_capabilities.syncwinsz_support, sizeof(g_capabilities.syncwinsz_support),
1902 if (SDK_TOOL_PATH == NULL) {
1903 D("fail to get SDK tool path.\n");
1904 snprintf(g_capabilities.sdk_toolpath, sizeof(g_capabilities.sdk_toolpath),
1907 snprintf(g_capabilities.sdk_toolpath, sizeof(g_capabilities.sdk_toolpath),
1908 "%s", SDK_TOOL_PATH);
1912 ret = system_info_get_platform_string("http://tizen.org/feature/profile", &value);
1913 if (ret != SYSTEM_INFO_ERROR_NONE) {
1914 snprintf(g_capabilities.profile_name, sizeof(g_capabilities.profile_name),
1916 D("fail to get profile name:%d\n", errno);
1918 snprintf(g_capabilities.profile_name, sizeof(g_capabilities.profile_name),
1920 if (value != NULL) {
1927 ret = system_info_get_platform_string("http://tizen.org/system/manufacturer", &value);
1928 if (ret != SYSTEM_INFO_ERROR_NONE) {
1929 snprintf(g_capabilities.vendor_name, sizeof(g_capabilities.vendor_name),
1931 D("fail to get the Vendor name:%d\n", errno);
1933 snprintf(g_capabilities.vendor_name, sizeof(g_capabilities.vendor_name),
1935 if (value != NULL) {
1941 // Target name of the launch possible
1942 if(!request_capability_to_plugin(CAPABILITY_CAN_LAUNCH, g_capabilities.can_launch,
1943 sizeof(g_capabilities.can_launch))) {
1944 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_CAN_LAUNCH);
1945 snprintf(g_capabilities.can_launch, sizeof(g_capabilities.can_launch),
1951 ret = system_info_get_platform_string("http://tizen.org/feature/platform.version", &value);
1952 if (ret != SYSTEM_INFO_ERROR_NONE) {
1953 snprintf(g_capabilities.platform_version, sizeof(g_capabilities.platform_version),
1955 D("fail to get platform version:%d\n", errno);
1957 snprintf(g_capabilities.platform_version, sizeof(g_capabilities.platform_version),
1959 if (value != NULL) {
1966 if(!request_capability_to_plugin(CAPABILITY_PRODUCT_VER, g_capabilities.product_version,
1967 sizeof(g_capabilities.product_version))) {
1968 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_PRODUCT_VER);
1969 snprintf(g_capabilities.product_version, sizeof(g_capabilities.product_version),
1975 snprintf(g_capabilities.sdbd_version, sizeof(g_capabilities.sdbd_version),
1976 "%d.%d.%d", SDB_VERSION_MAJOR, SDB_VERSION_MINOR, SDB_VERSION_PATCH);
1979 // Sdbd plugin version
1980 if(!request_capability_to_plugin(CAPABILITY_PLUGIN_VER, g_capabilities.sdbd_plugin_version,
1981 sizeof(g_capabilities.sdbd_plugin_version))) {
1982 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_PLUGIN_VER);
1983 snprintf(g_capabilities.sdbd_plugin_version, sizeof(g_capabilities.sdbd_plugin_version),
1989 if(!request_capability_to_plugin(CAPABILITY_LOG_ENABLE, g_capabilities.log_enable,
1990 sizeof(g_capabilities.log_enable))) {
1991 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_LOG_ENABLE);
1992 snprintf(g_capabilities.log_enable, sizeof(g_capabilities.log_enable),
1997 if(!request_capability_to_plugin(CAPABILITY_LOG_PATH, g_capabilities.log_path,
1998 sizeof(g_capabilities.log_path))) {
1999 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_LOG_PATH);
2000 snprintf(g_capabilities.log_path, sizeof(g_capabilities.log_path),
2004 // Application command support
2005 if(!request_capability_to_plugin(CAPABILITY_APPCMD, g_capabilities.appcmd_support,
2006 sizeof(g_capabilities.appcmd_support))) {
2007 D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_APPCMD);
2008 snprintf(g_capabilities.appcmd_support, sizeof(g_capabilities.appcmd_support),
2012 // Capability version
2013 snprintf(g_capabilities.sdbd_cap_version, sizeof(g_capabilities.sdbd_cap_version),
2014 "%d.%d", SDBD_CAP_VERSION_MAJOR, SDBD_CAP_VERSION_MINOR);
2017 static int is_support_usbproto()
2019 return (!strncmp(g_capabilities.usbproto_support, PLUGIN_RET_ENABLED, strlen(PLUGIN_RET_ENABLED)));
2022 static int is_support_sockproto()
2024 return (!strncmp(g_capabilities.sockproto_support, PLUGIN_RET_ENABLED, strlen(PLUGIN_RET_ENABLED)));
2027 #define EMULATOR_MODEL_NAME "Emulator"
2028 static void check_emulator_or_device()
2030 char model_name[256]={0,};
2033 // Get the model name from model_config.xml
2034 ret = get_device_name(model_name, sizeof model_name);
2036 if(!strncmp(model_name, EMULATOR_MODEL_NAME, sizeof(EMULATOR_MODEL_NAME))){
2038 D("This target type is Emulator\n");
2041 D("This target type is Device\n");
2045 D("failed to get the model name.\n");
2049 static void fork_prepare_handler(void)
2051 sdb_mutex_lock(&D_lock);
2054 static void fork_parent_handler(void)
2056 sdb_mutex_unlock(&D_lock);
2059 static void fork_child_handler(void)
2061 sdb_mutex_unlock(&D_lock);
2064 int sdb_main(int is_daemon, int server_port)
2067 check_emulator_or_device();
2071 init_capabilities();
2076 init_drop_privileges();
2077 init_sdk_requirements();
2078 if (!request_validity_to_plugin(PLUGIN_SYNC_CMD_VERIFY_LAUNCH, NULL)) {
2079 D("sdbd should be launched in develop mode.\n");
2085 pthread_atfork(fork_prepare_handler, fork_parent_handler, fork_child_handler);
2088 atexit(sdb_cleanup);
2089 #ifdef HAVE_WIN32_PROC
2090 SetConsoleCtrlHandler( ctrlc_handler, TRUE );
2091 #elif defined(HAVE_FORKEXEC)
2092 // No SIGCHLD. Let the service subproc handle its children.
2093 signal(SIGPIPE, SIG_IGN);
2096 init_transport_registration();
2102 local_init(DEFAULT_SDB_LOCAL_TRANSPORT_PORT);
2104 char local_name[30];
2105 build_local_name(local_name, sizeof(local_name), server_port);
2106 if(install_listener(local_name, "*smartsocket*", NULL)) {
2110 /* don't listen on a port (default 5037) if running in secure mode */
2111 /* don't run as root if we are running in secure mode */
2113 if (should_drop_privileges()) {
2115 struct __user_cap_header_struct header;
2116 struct __user_cap_data_struct cap;
2118 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
2121 /* add extra groups:
2122 ** SID_TTY to access /dev/ptmx
2124 gid_t groups[] = { SID_TTY, SID_APP_LOGGING, SID_SYS_LOGGING };
2125 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
2128 /* then switch user and group to "developer" */
2129 if (setgid(GID_DEVELOPER) != 0) {
2130 fprintf(stderr, "set group id failed errno: %d\n", errno);
2133 if (setuid(SID_DEVELOPER) != 0) {
2134 fprintf(stderr, "set user id failed errno: %d\n", errno);
2138 /* set CAP_SYS_BOOT capability, so "sdb reboot" will succeed */
2139 header.version = _LINUX_CAPABILITY_VERSION;
2141 cap.effective = cap.permitted = (1 << CAP_SYS_BOOT);
2142 cap.inheritable = 0;
2143 capset(&header, &cap);
2145 D("Local port disabled\n");
2147 char local_name[30];
2148 build_local_name(local_name, sizeof(local_name), server_port);
2149 if(install_listener(local_name, "*smartsocket*", NULL)) {
2154 /* choose the usb gadget backend */
2155 if (access(USB_NODE_FILE, F_OK) == 0) {
2156 /* legacy kernel-based sdb gadget */
2157 usb_init = &linux_usb_init;
2158 usb_cleanup = &linux_usb_cleanup;
2159 usb_write = &linux_usb_write;
2160 usb_read = &linux_usb_read;
2161 usb_close = &linux_usb_close;
2162 usb_kick = &linux_usb_kick;
2164 /* functionfs based gadget */
2165 usb_init = &ffs_usb_init;
2166 usb_cleanup = &ffs_usb_cleanup;
2167 usb_write = &ffs_usb_write;
2168 usb_read = &ffs_usb_read;
2169 usb_close = &ffs_usb_close;
2170 usb_kick = &ffs_usb_kick;
2173 if (is_support_usbproto()) {
2177 if (is_support_sockproto()) {
2178 /* by default don't listen on local transport but
2179 * listen if suitable command line argument has been provided */
2180 if (sdbd_commandline_args.sdbd_port >= 0) {
2181 local_init(sdbd_commandline_args.sdbd_port);
2183 local_init(DEFAULT_SDB_LOCAL_TRANSPORT_PORT);
2187 #if 0 /* tizen specific */
2188 D("sdb_main(): pre init_jdwp()\n");
2190 D("sdb_main(): post init_jdwp()\n");
2196 // inform our parent that we are up and running.
2197 #ifdef HAVE_WIN32_PROC
2199 WriteFile( GetStdHandle( STD_OUTPUT_HANDLE ), "OK\n", 3, &count, NULL );
2200 #elif defined(HAVE_FORKEXEC)
2201 fprintf(stderr, "OK\n");
2206 D("Event loop starting\n");
2210 if (is_support_usbproto()) {
2218 void connect_device(char* host, char* buffer, int buffer_size)
2221 char* portstr = strchr(host, ':');
2225 s_strncpy(hostbuf, host, sizeof(hostbuf) - 1);
2227 if (portstr - host >= sizeof(hostbuf)) {
2228 snprintf(buffer, buffer_size, "bad host name %s", host);
2231 // zero terminate the host at the point we found the colon
2232 hostbuf[portstr - host] = 0;
2233 if (sscanf(portstr + 1, "%d", &port) == 0) {
2234 snprintf(buffer, buffer_size, "bad port number %s", portstr);
2238 port = DEFAULT_SDB_LOCAL_TRANSPORT_PORT;
2241 snprintf(serial, sizeof(serial), "%s:%d", hostbuf, port);
2242 if (find_transport(serial)) {
2243 snprintf(buffer, buffer_size, "already connected to %s", serial);
2247 fd = socket_network_client(hostbuf, port, SOCK_STREAM);
2249 snprintf(buffer, buffer_size, "unable to connect to %s", host);
2253 D("client: connected on remote on fd %d\n", fd);
2255 disable_tcp_nagle(fd);
2256 register_socket_transport(fd, serial, port, 0, NULL);
2257 snprintf(buffer, buffer_size, "connected to %s", serial);
2260 void connect_emulator(char* port_spec, char* buffer, int buffer_size)
2262 char* port_separator = strchr(port_spec, ',');
2263 if (!port_separator) {
2264 snprintf(buffer, buffer_size,
2265 "unable to parse '%s' as <console port>,<sdb port>",
2270 // Zero-terminate console port and make port_separator point to 2nd port.
2271 *port_separator++ = 0;
2272 int console_port = strtol(port_spec, NULL, 0);
2273 int sdb_port = strtol(port_separator, NULL, 0);
2274 if (!(console_port > 0 && sdb_port > 0)) {
2275 *(port_separator - 1) = ',';
2276 snprintf(buffer, buffer_size,
2277 "Invalid port numbers: Expected positive numbers, got '%s'",
2282 /* Check if the emulator is already known.
2283 * Note: There's a small but harmless race condition here: An emulator not
2284 * present just yet could be registered by another invocation right
2285 * after doing this check here. However, local_connect protects
2286 * against double-registration too. From here, a better error message
2287 * can be produced. In the case of the race condition, the very specific
2288 * error message won't be shown, but the data doesn't get corrupted. */
2289 atransport* known_emulator = find_emulator_transport_by_sdb_port(sdb_port);
2290 if (known_emulator != NULL) {
2291 snprintf(buffer, buffer_size,
2292 "Emulator on port %d already registered.", sdb_port);
2296 /* Check if more emulators can be registered. Similar unproblematic
2297 * race condition as above. */
2298 int candidate_slot = get_available_local_transport_index();
2299 if (candidate_slot < 0) {
2300 snprintf(buffer, buffer_size, "Cannot accept more emulators.");
2304 /* Preconditions met, try to connect to the emulator. */
2305 if (!local_connect_arbitrary_ports(console_port, sdb_port, NULL)) {
2306 snprintf(buffer, buffer_size,
2307 "Connected to emulator on ports %d,%d", console_port, sdb_port);
2309 snprintf(buffer, buffer_size,
2310 "Could not connect to emulator on ports %d,%d",
2311 console_port, sdb_port);
2316 int copy_packet(apacket* dest, apacket* src) {
2319 D("dest packet is NULL\n");
2324 D("src packet is NULL\n");
2328 dest->next = src->next;
2329 dest->ptr = src->ptr;
2330 dest->len = src->len;
2332 int data_length = src->msg.data_length;
2333 if(data_length > MAX_PAYLOAD) {
2334 data_length = MAX_PAYLOAD;
2336 memcpy(&(dest->msg), &(src->msg), sizeof(amessage) + data_length);
2341 int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s)
2343 atransport *transport = NULL;
2346 if(!strcmp(service, "kill")) {
2347 fprintf(stderr,"sdb server killed by remote request\n");
2349 sdb_write(reply_fd, "OKAY", 4);
2350 if (is_support_usbproto()) {
2357 // "transport:" is used for switching transport with a specified serial number
2358 // "transport-usb:" is used for switching transport to the only USB transport
2359 // "transport-local:" is used for switching transport to the only local transport
2360 // "transport-any:" is used for switching transport to the only transport
2361 if (!strncmp(service, "transport", strlen("transport"))) {
2362 char* error_string = "unknown failure";
2363 transport_type type = kTransportAny;
2365 if (!strncmp(service, "transport-usb", strlen("transport-usb"))) {
2366 type = kTransportUsb;
2367 } else if (!strncmp(service, "transport-local", strlen("transport-local"))) {
2368 type = kTransportLocal;
2369 } else if (!strncmp(service, "transport-any", strlen("transport-any"))) {
2370 type = kTransportAny;
2371 } else if (!strncmp(service, "transport:", strlen("transport:"))) {
2372 service += strlen("transport:");
2376 transport = acquire_one_transport(CS_ANY, type, serial, &error_string);
2379 s->transport = transport;
2380 sdb_write(reply_fd, "OKAY", 4);
2382 sendfailmsg(reply_fd, error_string);
2387 // return a list of all connected devices
2388 if (!strcmp(service, "devices")) {
2390 memset(buf, 0, sizeof(buf));
2391 memset(buffer, 0, sizeof(buffer));
2392 D("Getting device list \n");
2393 list_transports(buffer, sizeof(buffer));
2394 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer),buffer);
2395 D("Wrote device list \n");
2396 writex(reply_fd, buf, strlen(buf));
2400 // add a new TCP transport, device or emulator
2401 if (!strncmp(service, "connect:", 8)) {
2403 char* host = service + 8;
2404 if (!strncmp(host, "emu:", 4)) {
2405 connect_emulator(host + 4, buffer, sizeof(buffer));
2407 connect_device(host, buffer, sizeof(buffer));
2409 // Send response for emulator and device
2410 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
2411 writex(reply_fd, buf, strlen(buf));
2415 // remove TCP transport
2416 if (!strncmp(service, "disconnect:", 11)) {
2418 memset(buffer, 0, sizeof(buffer));
2419 char* serial = service + 11;
2420 if (serial[0] == 0) {
2421 // disconnect from all TCP devices
2422 unregister_all_tcp_transports();
2425 // assume port 26101 if no port is specified
2426 if (!strchr(serial, ':')) {
2427 snprintf(hostbuf, sizeof(hostbuf) - 1, "%s:26101", serial);
2430 atransport *t = find_transport(serial);
2433 unregister_transport(t);
2435 snprintf(buffer, sizeof(buffer), "No such device %s", serial);
2439 snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
2440 writex(reply_fd, buf, strlen(buf));
2444 // returns our value for SDB_SERVER_VERSION
2445 if (!strcmp(service, "version")) {
2447 snprintf(version, sizeof version, "%04x", SDB_SERVER_VERSION);
2448 snprintf(buf, sizeof buf, "OKAY%04x%s", (unsigned)strlen(version), version);
2449 writex(reply_fd, buf, strlen(buf));
2453 if(!strncmp(service,"get-serialno",strlen("get-serialno"))) {
2454 char *out = "unknown";
2455 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
2456 if (transport && transport->serial) {
2457 out = transport->serial;
2459 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(out),out);
2460 writex(reply_fd, buf, strlen(buf));
2463 // indicates a new emulator instance has started
2464 if (!strncmp(service,"emulator:",9)) { /* tizen specific */
2465 char *tmp = strtok(service+9, DEVICEMAP_SEPARATOR);
2469 port = atoi(service+9);
2472 tmp = strtok(NULL, DEVICEMAP_SEPARATOR);
2474 local_connect(port, tmp);
2477 local_connect(port, NULL);
2482 if(!strncmp(service,"forward:",8) || !strncmp(service,"killforward:",12)) {
2483 char *local, *remote, *err;
2485 atransport *transport;
2487 int createForward = strncmp(service,"kill",4);
2489 local = service + (createForward ? 8 : 12);
2490 remote = strchr(local,';');
2492 sendfailmsg(reply_fd, "malformed forward spec");
2497 if((local[0] == 0) || (remote[0] == 0) || (remote[0] == '*')){
2498 sendfailmsg(reply_fd, "malformed forward spec");
2502 transport = acquire_one_transport(CS_ANY, ttype, serial, &err);
2504 sendfailmsg(reply_fd, err);
2508 if (createForward) {
2509 r = install_listener(local, remote, transport);
2511 r = remove_listener(local, remote, transport);
2514 /* 1st OKAY is connect, 2nd OKAY is status */
2515 writex(reply_fd, "OKAYOKAY", 8);
2519 if (createForward) {
2520 sendfailmsg(reply_fd, (r == -1) ? "cannot rebind smartsocket" : "cannot bind socket");
2522 sendfailmsg(reply_fd, "cannot remove listener");
2527 if(!strncmp(service,"get-state",strlen("get-state"))) {
2528 transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
2529 char *state = connection_state_name(transport);
2530 snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(state),state);
2531 writex(reply_fd, buf, strlen(buf));
2538 int recovery_mode = 0;
2541 int main(int argc, char **argv)
2546 return sdb_commandline(argc - 1, argv + 1);
2548 /* If sdbd runs inside the emulator this will enable sdb tracing via
2549 * sdb-debug qemud service in the emulator. */
2550 #if 0 /* tizen specific */
2551 sdb_qemu_trace_init();
2552 if((argc > 1) && (!strcmp(argv[1],"recovery"))) {
2553 sdb_device_banner = "recovery";
2558 apply_sdbd_commandline_defaults(&sdbd_commandline_args);
2559 int parse_ret = parse_sdbd_commandline(&sdbd_commandline_args, argc, argv);
2561 // TODO: Add detailed error messages
2562 // TODO: Add individual messages for help and usage
2563 if(parse_ret != SDBD_COMMANDLINE_SUCCESS) {
2564 if (parse_ret == SDBD_COMMANDLINE_HELP
2565 || parse_ret == SDBD_COMMANDLINE_USAGE) {
2566 // User requested help or usage
2567 print_sdbd_usage_message(stdout);
2568 return EXIT_SUCCESS;
2571 // Print usage message because of invalid options
2572 print_sdbd_usage_message(stderr);
2573 return EXIT_FAILURE;
2577 if (daemonize() < 0)
2578 fatal("daemonize() failed: errno:%d", errno);
2581 D("Handling main()\n");
2583 //sdbd will never die on emulator!
2584 signal(SIGTERM, handle_sig_term); /* tizen specific */
2585 return sdb_main(0, DEFAULT_SDB_PORT);