dbus: change from dbus-glib API to GDBus API
[sdk/target/sdbd.git] / src / sdb.c
1 /*
2  * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #define  TRACE_TAG   TRACE_SDB
18
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <ctype.h>
22 #include <stdarg.h>
23 #include <errno.h>
24 #include <string.h>
25 #include <time.h>
26 #include <sys/time.h>
27 #include <signal.h>
28 #include <grp.h>
29 #include <pwd.h>
30 #include <netdb.h>
31 #include <tzplatform_config.h>
32 #include <pthread.h>
33 #include <dlfcn.h>
34 #include <sys/smack.h>
35
36 #include "sysdeps.h"
37 #include "log.h"
38 #include "sdb.h"
39 #include "strutils.h"
40 #include "commandline_sdbd.h"
41 #include "utils.h"
42 #include "sdktools.h"
43 #include "plugin.h"
44 #include "sdbd_plugin.h"
45
46 #ifdef SUPPORT_ENCRYPT
47 #include "plugin_encrypt.h"
48 #endif
49
50 #include <linux/prctl.h>
51 #define SDB_PIDPATH "/tmp/.sdbd.pid"
52 #include <system_info.h>
53 #include <vconf.h>
54 #include <glib.h>
55
56 #define PROC_CMDLINE_PATH "/proc/cmdline"
57 #define USB_SERIAL_PATH "/sys/class/usb_mode/usb0/iSerial"
58 #define APPID2PID_PATH  "/usr/bin/appid2pid"
59
60 #include <sys/ioctl.h>
61 #include <net/if.h>
62 #include <netinet/in.h>
63 #include <arpa/inet.h>
64 #define GUEST_IP_INTERFACE "eth0"
65
66 SDB_MUTEX_DEFINE(zone_check_lock);
67 #if SDB_TRACE
68 SDB_MUTEX_DEFINE( D_lock );
69 #endif
70
71 #define SDB_LOGCONF_PATH "/tmp/.sdbdlog.conf"
72
73 int HOST = 0;
74
75 // sdk user
76 uid_t g_sdk_user_id;
77 gid_t g_sdk_group_id;
78 char* g_sdk_home_dir = NULL;
79 char* g_sdk_home_dir_env = NULL;
80 pcap g_capabilities;
81 int rootshell_mode; // 0: sdk user, 1: root
82 int booting_done; // 0: platform booting is in progess 1: platform booting is done
83
84 // root user
85 uid_t g_root_user_id;
86 gid_t g_root_group_id;
87 char* g_root_home_dir = NULL;
88 char* g_root_home_dir_env = NULL;
89
90 struct group_info
91 {
92     const char *name;
93     gid_t gid;
94 };
95 struct group_info g_default_groups[] = {
96     {"priv_externalstorage", -1},
97     {"priv_externalstorage_appdata", -1},
98     {"priv_mediastorage", -1},
99     {"log", -1},
100     {NULL, -1}
101 };
102
103 #define SDB_DEFAULT_GROUPS_CNT  ((sizeof(g_default_groups)/sizeof(g_default_groups[0]))-1)
104
105 int is_init_sdk_userinfo = 0;
106 int is_pwlocked = 0;    // 0 if unlocked, 1 otherwise
107
108 SdbdCommandlineArgs sdbd_commandline_args;
109
110 static int is_support_usbproto();
111 static int is_support_sockproto();
112
113 void (*usb_init)() = NULL;
114 void (*usb_cleanup)() = NULL;
115 int (*usb_write)(usb_handle *h, const void *data, int len) = NULL;
116 int (*usb_read)(usb_handle *h, void *data, size_t  len) = NULL;
117 int (*usb_close)(usb_handle *h) = NULL;
118 void (*usb_kick)(usb_handle *h) = NULL;
119
120 int g_is_emulator = -1;
121 int is_emulator(void) {
122     if (g_is_emulator >= 0) {
123         return g_is_emulator;
124     } else {
125         D("failed to initialize check emulator\n");
126     }
127
128     return sdbd_commandline_args.emulator.host != NULL;
129 }
130
131 int is_appid2pid_supported(void) {
132
133     if (access(APPID2PID_PATH, F_OK) == 0) {
134         /* It is necessary to confirm that it is possible
135          * to run "appid2pid" in the sdk user/group privileges. */
136         struct stat st;
137         if (stat(APPID2PID_PATH, &st) == 0) {
138             D("appid2pid uid=%d, gid=%d, mode=0x%x.\n", st.st_uid, st.st_gid, st.st_mode);
139             if ( (st.st_uid == STATIC_SDK_USER_ID && st.st_mode & S_IXUSR)
140                 || (st.st_gid == STATIC_SDK_GROUP_ID && st.st_mode & S_IXGRP)
141                 || (st.st_mode & S_IXOTH) ) {
142                 D("appid2pid is supported.\n");
143                 return 1;
144             }
145         }
146     } else {
147         D("failed to access appid2pid file: %d\n", errno);
148     }
149
150     D("appid2pid is NOT supported.\n");
151     return 0;
152 }
153
154 int is_container_enabled(void) {
155     bool value;
156     int ret;
157     ret = system_info_get_platform_bool("tizen.org/feature/container", &value);
158     if (ret != SYSTEM_INFO_ERROR_NONE) {
159         D("failed to get container information: %d\n", errno);
160         return 0;
161     } else {
162         D("tizen container: %d\n", value);
163         if (value == true)
164             return 1;
165         else
166             return 0;
167     }
168 }
169
170 void handle_sig_term(int sig) {
171 #ifdef SDB_PIDPATH
172     if (access(SDB_PIDPATH, F_OK) == 0)
173         sdb_unlink(SDB_PIDPATH);
174 #endif
175 }
176
177 static const char *sdb_device_banner = "device";
178
179 void fatal(const char *fmt, ...)
180 {
181     va_list ap;
182     va_start(ap, fmt);
183     fprintf(stderr, "error: ");
184     vfprintf(stderr, fmt, ap);
185     fprintf(stderr, "\n");
186     va_end(ap);
187     exit(-1);
188 }
189
190 void fatal_errno(const char *fmt, ...)
191 {
192     va_list ap;
193     va_start(ap, fmt);
194     fprintf(stderr, "errno: %d: ", errno);
195     vfprintf(stderr, fmt, ap);
196     fprintf(stderr, "\n");
197     va_end(ap);
198     exit(-1);
199 }
200
201 static char* get_sdb_log_conf(const char* key)
202 {
203     int fd;
204     char line[256] = {0,};
205     char value[256] = {0,};
206
207     if (access(SDB_LOGCONF_PATH, F_OK)) {
208         return NULL;
209     }
210
211     fd = unix_open(SDB_LOGCONF_PATH, O_RDONLY);
212     if (fd < 0) {
213         D("failed to open '%s' file: %d\n", SDB_LOGCONF_PATH, errno);
214         return NULL;
215     }
216
217     if (read_line(fd, line, sizeof(line)) > 0) {
218         char* start = strstr(line, key);
219         if (start != NULL) {
220             // move one more character to remove '=',
221             // including the length of the key string
222             start = start + strlen(key) + 1;
223             char* end = strstr(start, " ");
224             if (end != NULL) {
225                 strncpy(value, start, end - start);
226             } else {
227                 strncpy(value, start, sizeof(value));
228             }
229         } else {
230             sdb_close(fd);
231             return NULL;
232         }
233     }
234     sdb_close(fd);
235     return strdup(value);
236 }
237
238 static int is_enable_sdbd_log()
239 {
240     return (!strncmp(g_capabilities.log_enable, PLUGIN_RET_ENABLED, strlen(PLUGIN_RET_ENABLED)));
241 }
242
243 int   sdb_trace_mask;
244
245 /* read a comma/space/colum/semi-column separated list of tags
246  * from the SDB_TRACE environment variable and build the trace
247  * mask from it. note that '1' and 'all' are special cases to
248  * enable all tracing
249  */
250 void  sdb_trace_init(void)
251 {
252     char*  ptr = get_sdb_log_conf("SDB_TRACE");
253     const char*  p;
254     const char*  q;
255
256     static const struct {
257         const char*  tag;
258         int           flag;
259     } tags[] = {
260         { "1", 0 },
261         { "all", 0 },
262         { "sdb", TRACE_SDB },
263         { "sockets", TRACE_SOCKETS },
264         { "packets", TRACE_PACKETS },
265         { "rwx", TRACE_RWX },
266         { "usb", TRACE_USB },
267         { "sync", TRACE_SYNC },
268         { "sysdeps", TRACE_SYSDEPS },
269         { "transport", TRACE_TRANSPORT },
270         { "jdwp", TRACE_JDWP },
271         { "services", TRACE_SERVICES },
272         { "properties", TRACE_PROPERTIES },
273         { "sdktools", TRACE_SDKTOOLS },
274         { "appcmd", TRACE_APPCMD },
275         { NULL, 0 }
276     };
277
278     if (ptr == NULL) {
279         if (is_enable_sdbd_log())
280             p = "all";
281         else
282             return;
283     } else {
284         p = ptr;
285     }
286
287     /* use a comma/column/semi-colum/space separated list */
288     while (*p) {
289         int  len, tagn;
290
291         q = strpbrk(p, " ,:;");
292         if (q == NULL) {
293             q = p + strlen(p);
294         }
295         len = q - p;
296
297         for (tagn = 0; tags[tagn].tag != NULL; tagn++)
298         {
299             int  taglen = strlen(tags[tagn].tag);
300
301             if (len == taglen && !memcmp(tags[tagn].tag, p, len) )
302             {
303                 int  flag = tags[tagn].flag;
304                 if (flag == 0) {
305                     sdb_trace_mask = ~0;
306                     free(ptr);
307                     return;
308                 }
309                 sdb_trace_mask |= (1 << flag);
310                 break;
311             }
312         }
313         p = q;
314         if (*p)
315             p++;
316     }
317     free(ptr);
318 }
319
320 /*
321  * Implements SDB tracing inside the emulator.
322  */
323
324 #include <stdarg.h>
325
326 /*
327  * Redefine open and write for qemu_pipe.h that contains inlined references
328  * to those routines. We will redifine them back after qemu_pipe.h inclusion.
329  */
330
331 #undef open
332 #undef write
333 #define open    sdb_open
334 #define write   sdb_write
335 #include "qemu_pipe.h"
336 #undef open
337 #undef write
338 #define open    ___xxx_open
339 #define write   ___xxx_write
340
341 /* A handle to sdb-debug qemud service in the emulator. */
342 int   sdb_debug_qemu = -1;
343
344 apacket *get_apacket(void)
345 {
346     apacket *p = malloc(sizeof(apacket));
347     if(p == 0) fatal("failed to allocate an apacket");
348     memset(p, 0, sizeof(apacket) - MAX_PAYLOAD);
349     return p;
350 }
351
352 void put_apacket(apacket *p)
353 {
354     if (p != NULL) {
355         free(p);
356         p = NULL;
357     }
358 }
359
360 void handle_online(void)
361 {
362     D("sdb: online\n");
363 }
364
365 void handle_offline(atransport *t)
366 {
367     D("sdb: offline\n");
368     //Close the associated usb
369     run_transport_disconnects(t);
370 }
371
372 #if TRACE_PACKETS
373 #define DUMPMAX 32
374 void print_packet(const char *label, apacket *p)
375 {
376     char *tag;
377     char *x;
378     unsigned count;
379
380     switch(p->msg.command){
381     case A_SYNC: tag = "SYNC"; break;
382     case A_CNXN: tag = "CNXN" ; break;
383     case A_OPEN: tag = "OPEN"; break;
384     case A_OKAY: tag = "OKAY"; break;
385     case A_CLSE: tag = "CLSE"; break;
386     case A_WRTE: tag = "WRTE"; break;
387     default: tag = "????"; break;
388     }
389
390     fprintf(stderr, "%s: %s %08x %08x %04x \"",
391             label, tag, p->msg.arg0, p->msg.arg1, p->msg.data_length);
392     count = p->msg.data_length;
393     x = (char*) p->data;
394     if(count > DUMPMAX) {
395         count = DUMPMAX;
396         tag = "\n";
397     } else {
398         tag = "\"\n";
399     }
400     while(count-- > 0){
401         if((*x >= ' ') && (*x < 127)) {
402             fputc(*x, stderr);
403         } else {
404             fputc('.', stderr);
405         }
406         x++;
407     }
408     fprintf(stderr, tag);
409 }
410 #endif
411
412 #ifdef SUPPORT_ENCRYPT
413 /*
414 desc. : 암호화 실패 메시지 전송
415 parameter : [in] apacket* p : sdbd로 들어온 메시지
416             [in] atransport *t : 현재 연결에 대한 atransport
417             [in] unsigned failed_value : 실패 값
418 */
419 void send_encr_fail(apacket* p, atransport *t, unsigned failed_value){
420     apacket* enc_p;
421     enc_p = get_apacket();
422     enc_p->msg.command = A_ENCR; // 암호화 메시지
423     enc_p->msg.arg0 = failed_value; // 실패값
424     enc_p->msg.arg1 = p->msg.arg1;
425     send_packet(enc_p, t);
426     //put_apacket(enc_p);
427 }
428
429 /*
430 desc. : 암호화 메시지 핸들링
431 parameter : [in] apacket* p : sdbd로 들어온 메시지
432             [in/out] atransport *t : 현재 연결에 대한 atransport
433 ret : 0 : 정상적으로 메시지 전송
434       -1: 메시지 전송 실패
435 */
436 int handle_encr_packet(apacket* p, atransport *t){
437     static int sessionID = 0;
438     int retVal = 0;
439     apacket* enc_p = NULL;
440
441     if(p->msg.arg0 == ENCR_SET_ON_REQ){ // hello 메시지인 경우
442         t->sessionID = sessionID;
443         if((retVal = security_init(t->sessionID, NULL)) == 1){ // 암호화 handshaking을 위한 init
444             if(security_parse_server_hello(t->sessionID, p) == 1){ // hello 메시지 파싱
445                 D("security_parse_server_hello success\n");
446                 enc_p = get_apacket();
447                 if(security_gen_client_hello(t->sessionID, enc_p) == 1){ // hello 메시지 생성
448                     D("security_gen_client_hello success\n");
449                     enc_p->msg.command = A_ENCR;
450                     enc_p->msg.arg0 = ENCR_SET_ON_REQ;
451                     enc_p->msg.arg1 = p->msg.arg1;
452                     sessionID++;
453                     send_packet(enc_p, t);
454                 }
455                 else { // hello 메시지 생성 실패
456                     D("security_gen_client_hello error\n");
457                     send_encr_fail(p, t, ENCR_ON_FAIL); // 암호화 on 실패 메시지 전송
458                     t->encryption = ENCR_OFF; // 암호화 모드는 off
459                     security_deinit(t->sessionID);
460                     return -1;
461                 }
462             }
463             else{ // hello 메시지 파싱 실패
464                 D("security_parse_server_hello error\n");
465                 send_encr_fail(p, t, ENCR_ON_FAIL);
466                 t->encryption = ENCR_OFF;
467                 security_deinit(t->sessionID);
468
469                 return -1;
470             }
471         } else { // init 실패
472             D("security_init error\n");
473             send_encr_fail(p, t, ENCR_ON_FAIL);
474             t->encryption = ENCR_OFF;
475             if (retVal == -1)
476             {
477                 security_deinit(t->sessionID);
478             }
479             //here!! do security_deinit(), but when plugin pointer is null -> not deinit
480             return -1;
481         }
482     }
483     else if(p->msg.arg0 == ENCR_SET_ON_OK){ // ack 메시지인 경우
484         if(security_parse_server_ack(t->sessionID, p) == 1){    // ack 메시지 파싱
485             enc_p = get_apacket();
486             if(security_gen_client_ack(t->sessionID, enc_p) == 1){ // ack 메시지 생성
487                 D("security_gen_client_ack success\n");
488                 enc_p->msg.command = A_ENCR;
489                 enc_p->msg.arg0 = ENCR_SET_ON_OK;
490                 enc_p->msg.arg1 = p->msg.arg1;
491                 t->encryption = ENCR_ON;
492                 send_packet(enc_p, t);
493             }
494             else { // ack 메시지 생성에 실패한 경우
495                 D("security_gen_client_ack error\n");
496                 send_encr_fail(p, t, ENCR_ON_FAIL);
497                 t->encryption = ENCR_OFF;
498                 security_deinit(t->sessionID);
499                 return -1;
500             }
501         }
502         else { // ack 메시지 파싱에 실패한 경우
503             D("security_parse_server_ack error\n");
504             send_encr_fail(p, t, ENCR_ON_FAIL);
505             t->encryption = ENCR_OFF;
506             security_deinit(t->sessionID);
507             return -1;
508         }
509     }
510     else if(p->msg.arg0 == ENCR_SET_OFF){ // 암호화 모드 off 요청 메시지
511         if(t->encryption == ENCR_ON && security_deinit(t->sessionID) == 1){ // 현재 암호화 모드가 on 상태인 경우
512             enc_p = get_apacket();
513             t->encryption = ENCR_OFF; // 현재 연결에 대한 암호화 모드 off
514             enc_p->msg.command = A_ENCR;
515             enc_p->msg.arg0 = ENCR_SET_OFF;
516             enc_p->msg.arg1 = p->msg.arg1;
517             send_packet(enc_p, t);
518         }
519         else { // 암호화 모드 off에 실패한 경우
520             D("security_deinit error\n");
521             send_encr_fail(p, t, ENCR_OFF_FAIL); // 암호화 모드 off 실패 메시지 전송
522             return -1;
523         }
524     }
525     else if(p->msg.arg0 == ENCR_GET){ // 암호화 모드의 상태 요청 메시지인 경우
526         enc_p = get_apacket();
527         enc_p->msg.command = A_ENCR;
528         enc_p->msg.arg0 = ENCR_GET; // 암호화 모드 status get메시지
529         enc_p->msg.arg1 = p->msg.arg1;
530         if(t->encryption == ENCR_ON){ // 암호화 모드가 on인 경우
531             enc_p->msg.data_length = 13;
532             strncpy((char*)enc_p->data, "encryption:on", enc_p->msg.data_length); // encryption:on 메시지 전송
533         } else if(t->encryption == ENCR_OFF){ // 암호화 모드가 off인 경우
534             enc_p->msg.data_length = 14;
535             strncpy((char*)enc_p->data, "encryption:off", enc_p->msg.data_length); // encryption:off 메시지 전송
536         }
537         send_packet(enc_p, t);
538     }
539     else if (p->msg.arg0 == ENCR_ON_FAIL) // 암호화 모드를 on 하는 도중 실패한 경우 받는 메시지
540     {
541         t->encryption = ENCR_OFF; // 암호화 모드를 다시 off
542         D("encryption on failed\n");
543     }
544     else if (p->msg.arg0 == ENCR_OFF_FAIL) // 암호화 모드를 off하는 도중 실패한 경우 받는 메시지
545     {
546         //t->encryption = ENCR_ON;
547         D("encryption off failed\n");
548     }
549     //put_apacket(enc_p);
550     return 0;
551
552 }
553 #endif
554
555
556 static void send_ready(unsigned local, unsigned remote, atransport *t)
557 {
558     D("Calling send_ready \n");
559     apacket *p = get_apacket();
560     p->msg.command = A_OKAY;
561     p->msg.arg0 = local;
562     p->msg.arg1 = remote;
563     send_packet(p, t);
564 }
565
566 static void send_close(unsigned local, unsigned remote, atransport *t)
567 {
568     D("Calling send_close \n");
569     apacket *p = get_apacket();
570     p->msg.command = A_CLSE;
571     p->msg.arg0 = local;
572     p->msg.arg1 = remote;
573     send_packet(p, t);
574 }
575
576 static void send_connect(atransport *t)
577 {
578     D("Calling send_connect \n");
579     apacket *cp = get_apacket();
580     cp->msg.command = A_CNXN;
581     cp->msg.arg0 = A_VERSION;
582 #ifdef SUPPORT_ENCRYPT
583    cp->msg.arg1 = MAX_PAYLOAD - 100; // connection 시, sdb server의 패킷 크기를 암호화 오버로드 만큼 줄임
584 #else
585     cp->msg.arg1 = MAX_PAYLOAD;
586 #endif
587     char device_name[256]={0,};
588     int r = 0;
589     int status = 0;
590     if (request_lock_state_to_plugin(LOCKTYPE_PASSWORD) == 1) {
591         status = 1;
592         t->connection_state = CS_PWLOCK;
593     }
594
595     if (is_emulator()) {
596         r = get_emulator_name(device_name, sizeof device_name);
597     } else {
598         r = get_device_name(device_name, sizeof device_name);
599     }
600     if (r < 0) {
601         snprintf((char*) cp->data, sizeof cp->data, "%s::%s::%d", sdb_device_banner, DEFAULT_DEVICENAME, status);
602     } else {
603         snprintf((char*) cp->data, sizeof cp->data, "%s::%s::%d", sdb_device_banner, device_name, status);
604     }
605
606     D("CNXN data:%s\n", (char*)cp->data);
607     cp->msg.data_length = strlen((char*) cp->data) + 1;
608
609     send_packet(cp, t);
610 }
611
612 void send_device_status()
613 {
614     D("broadcast device status\n");
615     apacket* cp = get_apacket();
616     cp->msg.command = A_STAT;
617     cp->msg.arg0 = is_pwlocked;
618     cp->msg.arg1 = 0;
619
620     broadcast_transport(cp);
621
622     //all broadcasted packets are memory copied
623     //so, we should call put_apacket
624     put_apacket(cp);
625 }
626
627 static char *connection_state_name(atransport *t)
628 {
629     if (t == NULL) {
630         return "unknown";
631     }
632
633     switch(t->connection_state) {
634     case CS_BOOTLOADER:
635         return "bootloader";
636     case CS_DEVICE:
637         return "device";
638     case CS_OFFLINE:
639         return "offline";
640     default:
641         return "unknown";
642     }
643 }
644
645 static int get_str_cmdline(char *src, char *dest, char str[], int str_size) {
646     char *s = strstr(src, dest);
647     if (s == NULL) {
648         return -1;
649     }
650     char *e = strstr(s, " ");
651     if (e == NULL) {
652         return -1;
653     }
654
655     int len = e-s-strlen(dest);
656
657     if (len >= str_size) {
658         D("buffer size(%d) should be bigger than %d\n", str_size, len+1);
659         return -1;
660     }
661
662     strncpy(str, s + strlen(dest), len);
663     str[len]='\0';
664     return len;
665 }
666
667 int get_emulator_forward_port() {
668     SdbdCommandlineArgs *sdbd_args = &sdbd_commandline_args; /* alias */
669
670     if (sdbd_args->emulator.host == NULL) {
671         return -1;
672     }
673
674     return sdbd_args->emulator.port;
675 }
676
677 int get_emulator_name(char str[], int str_size) {
678     SdbdCommandlineArgs *sdbd_args = &sdbd_commandline_args; /* alias */
679
680     if (sdbd_args->emulator.host == NULL) {
681         return -1;
682     }
683
684     s_strncpy(str, sdbd_args->emulator.host, str_size);
685     return 0;
686 }
687
688 int get_device_name(char str[], int str_size) {
689     char *value = NULL;
690     int r = system_info_get_platform_string("http://tizen.org/system/model_name", &value);
691     if (r != SYSTEM_INFO_ERROR_NONE) {
692         D("fail to get system model:%d\n", errno);
693         return -1;
694     } else {
695         s_strncpy(str, value, str_size);
696         D("returns model_name:%s\n", value);
697         if (value != NULL) {
698             free(value);
699         }
700         return 0;
701     }
702     /*
703     int fd = unix_open(USB_SERIAL_PATH, O_RDONLY);
704     if (fd < 0) {
705         D("fail to read:%s (%d)\n", USB_SERIAL_PATH, errno);
706         return -1;
707     }
708
709     if(read_line(fd, str, str_size)) {
710         D("device serial name: %s\n", str);
711         sdb_close(fd);
712         return 0;
713     }
714     sdb_close(fd);
715     */
716     return -1;
717 }
718
719 static int get_cmdline_value(char *split, char str[], int str_size) {
720     char cmdline[512];
721     int fd = unix_open(PROC_CMDLINE_PATH, O_RDONLY);
722
723     if (fd < 0) {
724         D("fail to read /proc/cmdline\n");
725         return -1;
726     }
727     if(read_line(fd, cmdline, sizeof(cmdline))) {
728         D("qemu cmd: %s\n", cmdline);
729         if (get_str_cmdline(cmdline, split, str, str_size) < 1) {
730             D("could not get the (%s) value from cmdline\n", split);
731             sdb_close(fd);
732             return -1;
733         }
734     }
735     sdb_close(fd);
736     return 0;
737 }
738
739 int get_emulator_hostip(char str[], int str_size) {
740     return get_cmdline_value("host_ip=", str, str_size);
741 }
742
743 int get_emulator_guestip(char str[], int str_size) {
744     int           s;
745     struct ifreq ifr;
746     struct sockaddr_in *sin;
747
748     s = socket(AF_INET, SOCK_DGRAM, 0);
749     if(s < 0) {
750         D("socket error\n");
751         return -1;
752     }
753
754     snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s", GUEST_IP_INTERFACE);
755     if(ioctl(s, SIOCGIFHWADDR, &ifr) < 0) {
756         D("ioctl hwaddr error\n");
757         sdb_close(s);
758         return -1;
759     }
760
761     if(ioctl(s, SIOCGIFADDR, &ifr) < 0) {
762         D("ioctl addr error\n");
763         sdb_close(s);
764         return -1;
765     }
766     sin = (struct sockaddr_in *)&ifr.ifr_addr;
767     snprintf(str, str_size, "%s", inet_ntoa(sin->sin_addr));
768     sdb_close(s);
769
770     return 0;
771 }
772
773 void parse_banner(char *banner, atransport *t)
774 {
775     char *type, *product, *end;
776
777     D("parse_banner: %s\n", banner);
778     type = banner;
779     product = strchr(type, ':');
780     if(product) {
781         *product++ = 0;
782     } else {
783         product = "";
784     }
785
786         /* remove trailing ':' */
787     end = strchr(product, ':');
788     if(end) *end = 0;
789
790         /* save product name in device structure */
791     if (t->product == NULL) {
792         t->product = strdup(product);
793     } else if (strcmp(product, t->product) != 0) {
794         free(t->product);
795         t->product = strdup(product);
796     }
797
798     if(!strcmp(type, "bootloader")){
799         D("setting connection_state to CS_BOOTLOADER\n");
800         t->connection_state = CS_BOOTLOADER;
801         update_transports();
802         return;
803     }
804
805     if(!strcmp(type, "device")) {
806         D("setting connection_state to CS_DEVICE\n");
807         t->connection_state = CS_DEVICE;
808         update_transports();
809         return;
810     }
811
812     if(!strcmp(type, "recovery")) {
813         D("setting connection_state to CS_RECOVERY\n");
814         t->connection_state = CS_RECOVERY;
815         update_transports();
816         return;
817     }
818
819     if(!strcmp(type, "sideload")) {
820         D("setting connection_state to CS_SIDELOAD\n");
821         t->connection_state = CS_SIDELOAD;
822         update_transports();
823         return;
824     }
825
826     t->connection_state = CS_HOST;
827 }
828
829 static void update_version(atransport *t, int version, size_t payload)
830 {
831 #ifdef SUPPORT_ENCRYPT
832     size_t max_payload = MAX_PAYLOAD - 100;
833 #else
834     size_t max_payload = MAX_PAYLOAD;
835 #endif
836     t->protocol_version = min(version, A_VERSION);
837     t->max_payload = min(payload, max_payload);
838     D("update transport version. version=%x, max_payload=%zu\n", t->protocol_version, t->max_payload);
839 }
840
841 void handle_packet(apacket *p, atransport *t)
842 {
843     // Verify pointer p
844     int result = access((const char *) p, F_OK);
845     if ((result == -1) && (errno == EFAULT)) {
846         fatal("Invalid apacket = [0x%p]", p);
847     }
848
849     asocket *s;
850
851     D("handle_packet() %c%c%c%c\n", ((char*) (&(p->msg.command)))[0],
852                 ((char*) (&(p->msg.command)))[1],
853                 ((char*) (&(p->msg.command)))[2],
854                 ((char*) (&(p->msg.command)))[3]);
855
856     print_packet("recv", p);
857
858     switch(p->msg.command){
859     case A_SYNC:
860         if(p->msg.arg0){
861             send_packet(p, t);
862             if(HOST) send_connect(t);
863         } else {
864             t->connection_state = CS_OFFLINE;
865             handle_offline(t);
866             send_packet(p, t);
867         }
868         return;
869
870     case A_CNXN: /* CONNECT(version, maxdata, "system-id-string") */
871             /* XXX verify version, etc */
872         if(t->connection_state != CS_OFFLINE) {
873             t->connection_state = CS_OFFLINE;
874             handle_offline(t);
875         }
876         update_version(t, p->msg.arg0, p->msg.arg1);
877         parse_banner((char*) p->data, t);
878         handle_online();
879         if(!HOST) send_connect(t);
880         break;
881
882     case A_OPEN: /* OPEN(local-id, 0, "destination") */
883         if (request_lock_state_to_plugin(LOCKTYPE_PASSWORD) == 1 && t->connection_state == CS_PWLOCK) {
884             // in case of already locked before get A_CNXN
885             D("open failed due to password locked before get A_CNXN:%d\n", t->connection_state);
886             send_close(0, p->msg.arg0, t);
887         } else {
888             if(t->connection_state != CS_OFFLINE) {
889                 char *name = (char*) p->data;
890                 name[p->msg.data_length > 0 ? p->msg.data_length - 1 : 0] = 0;
891                 s = create_local_service_socket(name);
892                 if(s == 0) {
893                     send_close(0, p->msg.arg0, t);
894                 } else {
895                     s->peer = create_remote_socket(p->msg.arg0, t);
896                     s->peer->peer = s;
897                     send_ready(s->id, s->peer->id, t);
898                     s->ready(s);
899                 }
900             }
901         }
902         break;
903
904     case A_OKAY: /* READY(local-id, remote-id, "") */
905         if(t->connection_state != CS_OFFLINE) {
906             if((s = find_local_socket(p->msg.arg1))) {
907                 if(s->peer == 0) {
908                     s->peer = create_remote_socket(p->msg.arg0, t);
909                     s->peer->peer = s;
910                 }
911                 s->ready(s);
912             }
913         }
914         break;
915
916     case A_CLSE: /* CLOSE(local-id, remote-id, "") */
917         if(t->connection_state != CS_OFFLINE) {
918             if((s = find_local_socket(p->msg.arg1))) {
919                 s->close(s);
920             }
921         }
922         break;
923
924     case A_WRTE:
925         if(t->connection_state != CS_OFFLINE) {
926             if((s = find_local_socket(p->msg.arg1))) {
927                 unsigned rid = p->msg.arg0;
928                 p->len = p->msg.data_length;
929
930                 if(s->enqueue(s, p) == 0) {
931                     D("Enqueue the socket\n");
932                     send_ready(s->id, rid, t);
933                 }
934                 return;
935             }
936         }
937         break;
938 #ifdef SUPPORT_ENCRYPT
939     case A_ENCR: // 암호화 메시지인 경우
940         if(t->connection_state != CS_OFFLINE) {
941             handle_encr_packet(p, t);
942         }
943         break;
944 #endif
945
946     default:
947         printf("handle_packet: what is %08x?!\n", p->msg.command);
948     }
949
950     put_apacket(p);
951 }
952
953 alistener listener_list = {
954     .next = &listener_list,
955     .prev = &listener_list,
956 };
957
958 static void ss_listener_event_func(int _fd, unsigned ev, void *_l)
959 {
960     asocket *s;
961
962     if(ev & FDE_READ) {
963         struct sockaddr addr;
964         socklen_t alen;
965         int fd;
966
967         alen = sizeof(addr);
968         fd = sdb_socket_accept(_fd, &addr, &alen);
969         if(fd < 0) return;
970
971         sdb_socket_setbufsize(fd, CHUNK_SIZE);
972
973         s = create_local_socket(fd);
974         if(s) {
975             connect_to_smartsocket(s);
976             return;
977         }
978
979         sdb_close(fd);
980     }
981 }
982
983 static void listener_event_func(int _fd, unsigned ev, void *_l)
984 {
985     alistener *l = _l;
986     asocket *s;
987
988     if(ev & FDE_READ) {
989         struct sockaddr addr;
990         socklen_t alen;
991         int fd;
992
993         alen = sizeof(addr);
994         fd = sdb_socket_accept(_fd, &addr, &alen);
995         if(fd < 0) return;
996
997         s = create_local_socket(fd);
998         if(s) {
999             s->transport = l->transport;
1000             connect_to_remote(s, l->connect_to);
1001             return;
1002         }
1003
1004         sdb_close(fd);
1005     }
1006 }
1007
1008 static void  free_listener(alistener*  l)
1009 {
1010     if (l->next) {
1011         l->next->prev = l->prev;
1012         l->prev->next = l->next;
1013         l->next = l->prev = l;
1014     }
1015
1016     // closes the corresponding fd
1017     fdevent_remove(&l->fde);
1018
1019     if (l->local_name)
1020         free((char*)l->local_name);
1021
1022     if (l->connect_to)
1023         free((char*)l->connect_to);
1024
1025     if (l->transport) {
1026         remove_transport_disconnect(l->transport, &l->disconnect);
1027     }
1028     free(l);
1029 }
1030
1031 static void listener_disconnect(void*  _l, atransport*  t)
1032 {
1033     alistener*  l = _l;
1034
1035     free_listener(l);
1036 }
1037
1038 int local_name_to_fd(const char *name)
1039 {
1040     int port;
1041
1042     if(!strncmp("tcp:", name, 4)){
1043         int  ret;
1044         port = atoi(name + 4);
1045         ret = socket_loopback_server(port, SOCK_STREAM);
1046         return ret;
1047     }
1048 #ifndef HAVE_WIN32_IPC  /* no Unix-domain sockets on Win32 */
1049     // It's non-sensical to support the "reserved" space on the sdb host side
1050     if(!strncmp(name, "local:", 6)) {
1051         return socket_local_server(name + 6,
1052                 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
1053     } else if(!strncmp(name, "localabstract:", 14)) {
1054         return socket_local_server(name + 14,
1055                 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
1056     } else if(!strncmp(name, "localfilesystem:", 16)) {
1057         return socket_local_server(name + 16,
1058                 ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
1059     }
1060
1061 #endif
1062     printf("unknown local portname '%s'\n", name);
1063     return -1;
1064 }
1065
1066 static int remove_listener(const char *local_name, const char *connect_to, atransport* transport)
1067 {
1068     alistener *l;
1069
1070     for (l = listener_list.next; l != &listener_list; l = l->next) {
1071         if (!strcmp(local_name, l->local_name) &&
1072             !strcmp(connect_to, l->connect_to) &&
1073             l->transport && l->transport == transport) {
1074
1075             listener_disconnect(l, transport);
1076             return 0;
1077         }
1078     }
1079
1080     return -1;
1081 }
1082
1083 static int install_listener(const char *local_name, const char *connect_to, atransport* transport)
1084 {
1085     alistener *l;
1086
1087     //printf("install_listener('%s','%s')\n", local_name, connect_to);
1088
1089     for(l = listener_list.next; l != &listener_list; l = l->next){
1090         if(strcmp(local_name, l->local_name) == 0) {
1091             char *cto;
1092
1093                 /* can't repurpose a smartsocket */
1094             if(l->connect_to[0] == '*') {
1095                 return -1;
1096             }
1097
1098             cto = strdup(connect_to);
1099             if(cto == 0) {
1100                 return -1;
1101             }
1102
1103             //printf("rebinding '%s' to '%s'\n", local_name, connect_to);
1104             free((void*) l->connect_to);
1105             l->connect_to = cto;
1106             if (l->transport != transport) {
1107                 remove_transport_disconnect(l->transport, &l->disconnect);
1108                 l->transport = transport;
1109                 add_transport_disconnect(l->transport, &l->disconnect);
1110             }
1111             return 0;
1112         }
1113     }
1114
1115     if((l = calloc(1, sizeof(alistener))) == 0) goto nomem;
1116     if((l->local_name = strdup(local_name)) == 0) goto nomem;
1117     if((l->connect_to = strdup(connect_to)) == 0) goto nomem;
1118
1119
1120     l->fd = local_name_to_fd(local_name);
1121     if(l->fd < 0) {
1122         free((void*) l->local_name);
1123         free((void*) l->connect_to);
1124         free(l);
1125         printf("cannot bind '%s'\n", local_name);
1126         return -2;
1127     }
1128
1129     if (close_on_exec(l->fd) < 0) {
1130         D("fail to close fd exec:%d\n",l->fd);
1131     }
1132     if(!strcmp(l->connect_to, "*smartsocket*")) {
1133         fdevent_install(&l->fde, l->fd, ss_listener_event_func, l);
1134     } else {
1135         fdevent_install(&l->fde, l->fd, listener_event_func, l);
1136     }
1137     fdevent_set(&l->fde, FDE_READ);
1138
1139     l->next = &listener_list;
1140     l->prev = listener_list.prev;
1141     l->next->prev = l;
1142     l->prev->next = l;
1143     l->transport = transport;
1144
1145     if (transport) {
1146         l->disconnect.opaque = l;
1147         l->disconnect.func   = listener_disconnect;
1148         add_transport_disconnect(transport, &l->disconnect);
1149     }
1150     return 0;
1151
1152 nomem:
1153     fatal("cannot allocate listener");
1154     return 0;
1155 }
1156
1157 static void sdb_cleanup(void)
1158 {
1159     clear_sdbd_commandline_args(&sdbd_commandline_args);
1160
1161     if (is_support_usbproto()) {
1162         usb_cleanup();
1163     }
1164 //    if(required_pid > 0) {
1165 //        kill(required_pid, SIGKILL);
1166 //    }
1167
1168     unload_sdbd_plugin();
1169 }
1170
1171 void start_device_log(void)
1172 {
1173     int fd;
1174     char    path[PATH_MAX] = {0, };
1175     char    path_folder[PATH_MAX] = {0, };
1176     char    path_file[PATH_MAX] = {0, };
1177     struct tm now;
1178     time_t t;
1179
1180     // read the trace mask from persistent property persist.sdb.trace_mask
1181     // give up if the property is not set or cannot be parsed
1182     char* p_trace = get_sdb_log_conf("SDB_TRACE");
1183     if ((p_trace == NULL ) && !is_enable_sdbd_log()) {
1184         return;
1185     } else {
1186         free(p_trace);
1187     }
1188     char* p_path = get_sdb_log_conf("SDBD_LOG_PATH");
1189     if (p_path) {
1190         snprintf(path_folder, sizeof(path_folder), "%s", p_path);
1191         free(p_path);
1192     } else if (g_capabilities.log_path[0] != '\0') {
1193         snprintf(path_folder, sizeof(path_folder), "%s", g_capabilities.log_path);
1194     } else {
1195         return;
1196     }
1197
1198     tzset();
1199     time(&t);
1200     localtime_r(&t, &now);
1201
1202     strftime(path_file, sizeof(path_file),
1203                     "sdbd-%Y-%m-%d-%H-%M-%S.txt",
1204                     &now);
1205
1206     snprintf(path, sizeof(path), "%s/%s", path_folder, path_file);
1207
1208     fd = unix_open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1209     if (fd < 0) {
1210         return;
1211     }
1212
1213     // redirect stdout and stderr to the log file
1214     dup2(fd, 1);
1215     dup2(fd, 2);
1216     fprintf(stderr,"--- sdbd starting (pid %d) ---\n", getpid());
1217     sdb_close(fd);
1218
1219     fd = unix_open("/dev/null", O_RDONLY);
1220     if (fd < 0) {
1221         // hopefully not gonna happen
1222         return;
1223     }
1224     dup2(fd, 0);
1225     sdb_close(fd);
1226 }
1227
1228 int daemonize(void) {
1229
1230     // set file creation mask to 0
1231     umask(0);
1232
1233     switch (fork()) {
1234     case -1:
1235         return -1;
1236     case 0:
1237         break;
1238     default:
1239         _exit(0);
1240     }
1241 #ifdef SDB_PIDPATH
1242     FILE *f = fopen(SDB_PIDPATH, "w");
1243
1244     if (f != NULL) {
1245         fprintf(f, "%d\n", getpid());
1246         fclose(f);
1247     }
1248 #endif
1249     if (setsid() == -1)
1250         return -1;
1251
1252     if (chdir("/") < 0)
1253         D("sdbd: unable to change working directory to /\n");
1254
1255     return 0;
1256 }
1257
1258 /* Constructs a local name of form tcp:port.
1259  * target_str points to the target string, it's content will be overwritten.
1260  * target_size is the capacity of the target string.
1261  * server_port is the port number to use for the local name.
1262  */
1263 void build_local_name(char* target_str, size_t target_size, int server_port)
1264 {
1265   snprintf(target_str, target_size, "tcp:%d", server_port);
1266 }
1267
1268 static void init_drop_privileges() {
1269 #ifdef _DROP_PRIVILEGE
1270     rootshell_mode = 0;
1271 #else
1272     rootshell_mode = 1;
1273 #endif
1274 }
1275
1276 int should_drop_privileges() {
1277     if (rootshell_mode == 1) { // if root, then don't drop
1278         return 0;
1279     }
1280     return 1;
1281 }
1282
1283 #include <gio/gio.h>
1284
1285 #define DEVICED_BUS            "org.tizen.system.deviced"
1286 #define DEVICED_CORE_PATH      "/Org/Tizen/System/DeviceD/Core"
1287 #define BOOTING_DONE_SIGNAL    "BootingDone"
1288 #define DEVICED_CORE_INTERFACE "org.tizen.system.deviced.core"
1289 #define SDBD_BOOT_INFO_FILE    "/tmp/sdbd_boot_info"
1290
1291 static GMainLoop *g_mainloop;
1292
1293 static void booting_done_signal_subscriber(GDBusConnection *connection,
1294     const gchar *sender, const gchar *path, const gchar *interface,
1295     const gchar *signal, GVariant *parameters, gpointer user_data)
1296 {
1297     if (g_strcmp0(signal, BOOTING_DONE_SIGNAL) != 0) {
1298         D("received signal(%s) does not match the desired signal(%s)\n",
1299           signal, BOOTING_DONE_SIGNAL);
1300         return;
1301     }
1302
1303     D("received the \"%s\" signal\n", signal);
1304
1305     booting_done = 1;
1306     if (access(SDBD_BOOT_INFO_FILE, F_OK) == 0) {
1307         D("booting is already done\n");
1308     } else {
1309         FILE *info_file = fopen(SDBD_BOOT_INFO_FILE, "w");
1310         if (info_file != NULL) {
1311             fprintf(info_file, "%d", 1);
1312             fclose(info_file);
1313         }
1314         D("booting is done\n");
1315     }
1316
1317     D("handled the booting done signal\n");
1318     g_main_loop_quit(g_mainloop);
1319 }
1320
1321 static void *bootdone_cb(void *args)
1322 {
1323     GError *error = NULL;
1324     GDBusConnection *connection = NULL;
1325     guint id;
1326
1327     connection = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &error);
1328     if (connection == NULL) {
1329         if (error != NULL) {
1330             D("failed to connect to the system bus: %s\n", error->message);
1331             g_error_free(error);
1332         } else {
1333             D("failed to connect to the system bus\n");
1334         }
1335         return NULL;
1336     }
1337
1338     g_mainloop = g_main_loop_new(NULL, false);
1339     if (g_mainloop == NULL) {
1340         D("failed to create a g_main_loop\n");
1341         goto bootdone_out;
1342     }
1343
1344     id = g_dbus_connection_signal_subscribe(connection,
1345         DEVICED_BUS, DEVICED_CORE_INTERFACE, BOOTING_DONE_SIGNAL,
1346         DEVICED_CORE_PATH, NULL, G_DBUS_SIGNAL_FLAGS_NONE,
1347         booting_done_signal_subscriber, NULL, NULL);
1348     if (id == 0) {
1349         D("failed to subscribe to the booting done signal\n");
1350         goto bootdone_out;
1351     }
1352
1353     D("wait for the booting done signal\n");
1354     g_main_loop_run(g_mainloop);
1355
1356     g_dbus_connection_signal_unsubscribe(connection, id);
1357
1358 bootdone_out:
1359     if (g_mainloop != NULL) {
1360         g_main_loop_unref(g_mainloop);
1361     }
1362     if (connection != NULL) {
1363         g_object_unref(connection);
1364     }
1365     D("exit the bootdone_cb thread\n");
1366
1367     return NULL;
1368 }
1369
1370 void register_bootdone_cb()
1371 {
1372     sdb_thread_t t;
1373     if (sdb_thread_create(&t, bootdone_cb, NULL)) {
1374         D("can not create a service thread to check the booting done\n");
1375         return;
1376     }
1377     D("created the bootdone_cb thread\n");
1378 }
1379
1380 static int sdbd_set_groups(const char *name, int gid, struct group_info default_groups[], int default_groups_size) {
1381     gid_t *group_ids = NULL;
1382     int ngroups = 0;
1383     int i, j = 0;
1384     int group_match = 0;
1385     int added_group_cnt = 0;
1386
1387     getgrouplist(name, gid, NULL, &ngroups);
1388     D("group list : ngroups = %d\n", ngroups);
1389     group_ids = malloc((ngroups + default_groups_size) * sizeof(gid_t));
1390     if (group_ids == NULL) {
1391         D("failed to allocate group_ids(%zu)\n", (ngroups + default_groups_size) * sizeof(gid_t));
1392         return -1;
1393     }
1394     if (getgrouplist(name, gid, group_ids, &ngroups) == -1) {
1395         D("failed to getgrouplist(), ngroups = %d\n", ngroups);
1396         free(group_ids);
1397         return -1;
1398     }
1399     if(default_groups_size >= 1) {
1400         for (i = 0; default_groups[i].name != NULL; i++) {
1401             for (j = 0; j < ngroups; j++) {
1402                 if (group_ids[j] == default_groups[i].gid) {
1403                     group_match = 1;
1404                     break;
1405                 }
1406             }
1407             if (group_match == 0 && default_groups[i].gid != -1) {
1408                 group_ids[ngroups + added_group_cnt] = default_groups[i].gid;
1409                 added_group_cnt ++;
1410             }
1411             group_match = 0;
1412         }
1413     }
1414     if (setgroups(ngroups+added_group_cnt, group_ids) != 0) {
1415         D("failed to setgroups().\n");
1416         free(group_ids);
1417         return -1;
1418     }
1419
1420     free(group_ids);
1421     return 0;
1422 }
1423
1424 static int sdbd_get_user_pwd(const char* user_name, struct passwd* pwd, char* buf, size_t bufsize) {
1425     struct passwd *result = NULL;
1426     int ret = 0;
1427
1428     ret = getpwnam_r(user_name, pwd, buf, bufsize, &result);
1429     if (result == NULL) {
1430         if (ret == 0) {
1431             D("Not found passwd : username(%s)\n", user_name);
1432         } else {
1433             errno = ret;
1434             D("failed to getpwnam_r\n");
1435         }
1436         return -1;
1437     }
1438
1439     return 0;
1440 }
1441
1442 static int sdbd_get_group(const char* group_name, struct group* grp, char* buf, size_t bufsize) {
1443     struct group *result = NULL;
1444     int ret = 0;
1445
1446     ret = getgrnam_r(group_name, grp, buf, bufsize, &result);
1447     if (result == NULL) {
1448         if (ret == 0) {
1449             D("Not found group : groupname(%s)\n", group_name);
1450         } else {
1451             errno = ret;
1452             D("failed to getgrnam_r\n");
1453         }
1454         return -1;
1455     }
1456
1457     return 0;
1458 }
1459
1460 int set_sdk_user_privileges(int is_drop_capability_after_fork) {
1461     if (!is_init_sdk_userinfo) {
1462         D("failed to init sdk user information.\n");
1463         return -1;
1464     }
1465
1466     /*
1467     * If a process switches its real, effective, or saved uids from at least one being 0 to all being non-zero,
1468     * then both the permitted and effective capabilities are cleared.
1469     */
1470     if(is_drop_capability_after_fork) {
1471
1472         if (setuid(g_root_user_id) != 0) {
1473             D("set root user id failed (errno: %d)\n", errno);
1474             return -1;
1475         }
1476     }
1477
1478     if (sdbd_set_groups(SDK_USER_NAME, g_sdk_group_id, g_default_groups, SDB_DEFAULT_GROUPS_CNT) < 0) {
1479         D("set groups failed (errno: %d)\n", errno);
1480         return -1;
1481     }
1482
1483     if (setgid(g_sdk_group_id) != 0) {
1484         D("set group id failed (errno: %d)\n", errno);
1485         return -1;
1486     }
1487
1488     if (setuid(g_sdk_user_id) != 0) {
1489         D("set user id failed (errno: %d)\n", errno);
1490         return -1;
1491 //        if(is_drop_capability_after_fork) {
1492 //            return -1;
1493 //        }
1494     }
1495
1496     if (chdir(g_sdk_home_dir) < 0) {
1497         D("unable to change working directory to %s\n", g_sdk_home_dir);
1498     }
1499
1500     // TODO: use pam later
1501     if (g_sdk_home_dir_env) {
1502         putenv(g_sdk_home_dir_env);
1503     }
1504
1505     return 0;
1506 }
1507
1508 int set_root_privileges() {
1509
1510     if (sdbd_set_groups(ROOT_USER_NAME, g_root_group_id, NULL, 0) < 0) {
1511         D("set root groups failed (errno: %d)\n", errno);
1512     }
1513
1514     if (setgid(g_root_group_id) != 0) {
1515         D("set root group id failed (errno: %d)\n", errno);
1516     }
1517
1518     if (setuid(g_root_user_id) != 0) {
1519         D("set root user id failed (errno: %d)\n", errno);
1520     }
1521
1522     if (chdir(g_root_home_dir) < 0) {
1523         D("unable to change root working directory to %s\n", g_sdk_home_dir);
1524     }
1525
1526     // TODO: use pam later
1527     if (g_root_home_dir_env) {
1528         putenv(g_root_home_dir_env);
1529     }
1530
1531     return 0;
1532 }
1533
1534 #define SDB_PW_GR_DEFAULT_SIZE  (16*1024)
1535 static long get_passwd_bufsize() {
1536     long bufsize = 0;
1537
1538     bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
1539     if(bufsize < 0) {
1540         bufsize = SDB_PW_GR_DEFAULT_SIZE;
1541     }
1542
1543     return bufsize;
1544 }
1545
1546 static long get_group_bufsize() {
1547     long bufsize = 0;
1548
1549     bufsize = sysconf(_SC_GETGR_R_SIZE_MAX);
1550     if(bufsize < 0) {
1551         bufsize = SDB_PW_GR_DEFAULT_SIZE;
1552     }
1553
1554     return bufsize;
1555 }
1556
1557 static int init_sdb_default_groups() {
1558     struct group grp;
1559     char *buf = NULL;
1560     long bufsize = 0;
1561     int i = 0;
1562
1563     bufsize = get_group_bufsize();
1564     buf = malloc(bufsize);
1565     if (buf == NULL) {
1566         D("failed to allocate gruop buf(%ld)\n", bufsize);
1567         return -1;
1568     }
1569
1570     for (i = 0; g_default_groups[i].name != NULL; i++) {
1571         memset(buf, 0, bufsize);
1572         if (sdbd_get_group(g_default_groups[i].name, &grp, buf, bufsize) == 0) {
1573             g_default_groups[i].gid = grp.gr_gid;
1574         } else {
1575             D("failed get group info.(errno: %d)\n", errno);
1576         }
1577     }
1578
1579     free(buf);
1580     return 0;
1581 }
1582
1583 static void set_static_root_userinfo() {
1584     g_root_user_id = STATIC_ROOT_USER_ID;
1585     g_root_group_id = STATIC_ROOT_GROUP_ID;
1586     g_root_home_dir = STATIC_ROOT_HOME_DIR;
1587 }
1588
1589 static void set_static_sdk_userinfo() {
1590     g_sdk_user_id = STATIC_SDK_USER_ID;
1591     g_sdk_group_id = STATIC_SDK_GROUP_ID;
1592     g_sdk_home_dir = STATIC_SDK_HOME_DIR;
1593 }
1594
1595 static int init_root_userinfo() {
1596     struct passwd pwd;
1597     char *buf = NULL;
1598     long bufsize = 0;
1599
1600     bufsize = get_passwd_bufsize();
1601     buf = malloc(bufsize);
1602     if (buf == NULL) {
1603         D("failed to allocate passwd buf(%ld)\n", bufsize);
1604         set_static_root_userinfo();
1605     } else {
1606         if (sdbd_get_user_pwd(ROOT_USER_NAME, &pwd, buf, bufsize) < 0) {
1607             D("failed to get root user passwd info.(errno: %d)\n", errno);
1608             set_static_root_userinfo();
1609         } else {
1610             D("username=%s, uid=%d, gid=%d, dir=%s\n", pwd.pw_name, pwd.pw_uid, pwd.pw_gid, pwd.pw_dir);
1611
1612             g_root_user_id = pwd.pw_uid;
1613             g_root_group_id = pwd.pw_gid;
1614             g_root_home_dir = strdup(pwd.pw_dir);
1615         }
1616         free(buf);
1617     }
1618
1619     int env_size = strlen("HOME=") + strlen(g_root_home_dir) + 1;
1620     g_root_home_dir_env = malloc(env_size);
1621     if(g_root_home_dir_env == NULL) {
1622         D("failed to allocate for home dir env string\n");
1623     } else {
1624         snprintf(g_root_home_dir_env, env_size, "HOME=%s", g_root_home_dir);
1625     }
1626
1627     return 0;
1628 }
1629
1630 static int init_sdk_userinfo() {
1631     struct passwd pwd;
1632     char *buf = NULL;
1633     long bufsize = 0;
1634
1635     if (is_init_sdk_userinfo) {
1636         return 0;
1637     }
1638
1639     if (init_sdb_default_groups() < 0) {
1640         D("failed to initialize default groups.\n");
1641     }
1642
1643     bufsize = get_passwd_bufsize();
1644     buf = malloc(bufsize);
1645     if (buf == NULL) {
1646         D("failed to allocate passwd buf(%ld)\n", bufsize);
1647         set_static_sdk_userinfo();
1648     } else {
1649         if (sdbd_get_user_pwd(SDK_USER_NAME, &pwd, buf, bufsize) < 0) {
1650             D("get user passwd info.(errno: %d)\n", errno);
1651             set_static_sdk_userinfo();
1652         } else {
1653             D("username=%s, uid=%d, gid=%d, dir=%s\n", pwd.pw_name, pwd.pw_uid, pwd.pw_gid, pwd.pw_dir);
1654
1655             g_sdk_user_id = pwd.pw_uid;
1656             g_sdk_group_id = pwd.pw_gid;
1657             g_sdk_home_dir = strdup(pwd.pw_dir);
1658         }
1659         free(buf);
1660     }
1661
1662     int env_size = strlen("HOME=") + strlen(g_sdk_home_dir) + 1;
1663     g_sdk_home_dir_env = malloc(env_size);
1664     if(g_sdk_home_dir_env == NULL) {
1665         D("failed to allocate for home dir env string\n");
1666     } else {
1667         snprintf(g_sdk_home_dir_env, env_size, "HOME=%s", g_sdk_home_dir);
1668     }
1669
1670     is_init_sdk_userinfo = 1;
1671     return 0;
1672 }
1673
1674 static int safe_system(char *cmd, char *argv[], char *envp[]) {
1675     pid_t pid;
1676     int status;
1677
1678     pid = fork();
1679     switch (pid) {
1680         case -1:
1681             return -1;
1682         case 0:
1683             execve(cmd, argv, envp);
1684             D("- exec '%s' failed: (errno:%d) -\n", cmd, errno);
1685             exit(-1);
1686         default:
1687             for (;;) {
1688                 pid_t p = waitpid(pid, &status, 0);
1689                 if (p == pid) {
1690                     break;
1691                 }
1692             }
1693     }
1694     return 0;
1695 }
1696
1697 static void init_sdk_requirements() {
1698     struct stat st;
1699
1700     // set env variable for temporary
1701     // TODO: should use pam instead later!!
1702     putenv("TERM=linux");
1703     putenv("HOME=/root");
1704
1705     init_sdk_userinfo();
1706     init_root_userinfo();
1707
1708     if (g_sdk_home_dir != NULL && stat(g_sdk_home_dir, &st) == 0) {
1709         if (st.st_uid != g_sdk_user_id || st.st_gid != g_sdk_group_id) {
1710             char* cmd = "/usr/bin/chown";
1711             char params[128];
1712             char* envp[128];
1713             int envp_cnt = 0;
1714             int i = 0;
1715
1716             envp[envp_cnt++] = g_strdup("TERM=linux");
1717             envp[envp_cnt++] = g_strdup("DISPLAY=:0");
1718             envp[envp_cnt] = NULL;
1719
1720             snprintf(params, sizeof(params), "%s %s:%s %s -R", cmd, SDK_USER_NAME, SDK_USER_NAME, g_sdk_home_dir);
1721
1722             char* args[] = {
1723                 cmd,
1724                 params,
1725                 NULL,
1726             };
1727             if (safe_system(cmd, args, envp) < 0) {
1728                 D("failed to change ownership to sdk user to %s\n", g_sdk_home_dir);
1729             }
1730
1731             /* free environment variables */
1732             if (envp_cnt > 0) {
1733                 for (i = 0; i < envp_cnt; i++) {
1734                     if (envp[i]) {
1735                         g_free(envp[i]);
1736                     }
1737                 }
1738             }
1739         }
1740     }
1741
1742     if (is_emulator()) {
1743         register_bootdone_cb();
1744     }
1745 }
1746
1747 static void init_capabilities(void) {
1748     int ret = -1;
1749     char *value = NULL;
1750
1751     memset(&g_capabilities, 0, sizeof(g_capabilities));
1752
1753     // CPU Architecture of model
1754     ret = system_info_get_platform_string("http://tizen.org/feature/platform.core.cpu.arch", &value);
1755     if (ret != SYSTEM_INFO_ERROR_NONE) {
1756         snprintf(g_capabilities.cpu_arch, sizeof(g_capabilities.cpu_arch),
1757                     "%s", UNKNOWN);
1758         D("fail to get the CPU architecture of model:%d\n", errno);
1759     } else {
1760         snprintf(g_capabilities.cpu_arch, sizeof(g_capabilities.cpu_arch),
1761                     "%s", value);
1762         if (value != NULL) {
1763             free(value);
1764         }
1765     }
1766
1767
1768     // Secure protocol support
1769     if(!request_capability_to_plugin(CAPABILITY_SECURE, g_capabilities.secure_protocol,
1770                             sizeof(g_capabilities.secure_protocol))) {
1771         D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_SECURE);
1772         snprintf(g_capabilities.secure_protocol, sizeof(g_capabilities.secure_protocol),
1773                     "%s", DISABLED);
1774     }
1775
1776
1777     // Interactive shell support
1778     if(!request_capability_to_plugin(CAPABILITY_INTER_SHELL, g_capabilities.intershell_support,
1779                             sizeof(g_capabilities.intershell_support))) {
1780         D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_INTER_SHELL);
1781         snprintf(g_capabilities.intershell_support, sizeof(g_capabilities.intershell_support),
1782                     "%s", DISABLED);
1783     }
1784
1785
1786     // File push/pull support
1787     if(!request_capability_to_plugin(CAPABILITY_FILESYNC, g_capabilities.filesync_support,
1788                             sizeof(g_capabilities.filesync_support))) {
1789         D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_FILESYNC);
1790         snprintf(g_capabilities.filesync_support, sizeof(g_capabilities.filesync_support),
1791                     "%s", DISABLED);
1792     }
1793
1794
1795     // USB protocol support
1796     if(!request_capability_to_plugin(CAPABILITY_USB_PROTOCOL, g_capabilities.usbproto_support,
1797                             sizeof(g_capabilities.usbproto_support))) {
1798         D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_USB_PROTOCOL);
1799         snprintf(g_capabilities.usbproto_support, sizeof(g_capabilities.usbproto_support),
1800                     "%s", DISABLED);
1801     }
1802
1803
1804     // Socket protocol support
1805     if(!request_capability_to_plugin(CAPABILITY_SOCK_PROTOCOL, g_capabilities.sockproto_support,
1806                             sizeof(g_capabilities.sockproto_support))) {
1807         D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_SOCK_PROTOCOL);
1808         snprintf(g_capabilities.sockproto_support, sizeof(g_capabilities.sockproto_support),
1809                     "%s", DISABLED);
1810     }
1811
1812     // Sdbd root permission
1813     snprintf(g_capabilities.root_permission, sizeof(g_capabilities.root_permission),
1814                 "%s", DISABLED);
1815
1816     // Root command support
1817     if(!request_capability_to_plugin(CAPABILITY_ROOT_ONOFF, g_capabilities.rootonoff_support,
1818                             sizeof(g_capabilities.rootonoff_support))) {
1819         D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_ROOT_ONOFF);
1820         snprintf(g_capabilities.rootonoff_support, sizeof(g_capabilities.rootonoff_support),
1821                     "%s", DISABLED);
1822     }
1823
1824
1825     // Encryption support
1826     if(!request_capability_to_plugin(CAPABILITY_ENCRYPTION, g_capabilities.encryption_support,
1827                             sizeof(g_capabilities.encryption_support))) {
1828         D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_ENCRYPTION);
1829         snprintf(g_capabilities.encryption_support, sizeof(g_capabilities.encryption_support),
1830                     "%s", DISABLED);
1831     }
1832
1833
1834     // Zone support
1835     ret = is_container_enabled();
1836     snprintf(g_capabilities.zone_support, sizeof(g_capabilities.zone_support),
1837                 "%s", ret == 1 ? ENABLED : DISABLED);
1838
1839     // Multi-User support
1840     // XXX: There is no clear way to determine whether multi-user support.
1841     // Since TZ_SYS_DEFAULT_USER is set to "owner" for multi-user support,
1842     // guess whether multiuser support through that information.
1843     const char* sys_default_user = tzplatform_getenv(TZ_SYS_DEFAULT_USER);
1844     if (sys_default_user != NULL && !strcmp(sys_default_user, "owner")) {
1845         snprintf(g_capabilities.multiuser_support, sizeof(g_capabilities.multiuser_support),
1846                     "%s", ENABLED);
1847     } else {
1848         snprintf(g_capabilities.multiuser_support, sizeof(g_capabilities.multiuser_support),
1849                     "%s", DISABLED);
1850     }
1851
1852     // Window size synchronization support
1853     snprintf(g_capabilities.syncwinsz_support, sizeof(g_capabilities.syncwinsz_support),
1854                 "%s", ENABLED);
1855
1856     // SDK Tool path
1857     if (SDK_TOOL_PATH == NULL) {
1858         D("fail to get SDK tool path.\n");
1859         snprintf(g_capabilities.sdk_toolpath, sizeof(g_capabilities.sdk_toolpath),
1860                     "%s", UNKNOWN);
1861     } else {
1862         snprintf(g_capabilities.sdk_toolpath, sizeof(g_capabilities.sdk_toolpath),
1863                     "%s", SDK_TOOL_PATH);
1864     }
1865
1866     // Profile name
1867     ret = system_info_get_platform_string("http://tizen.org/feature/profile", &value);
1868     if (ret != SYSTEM_INFO_ERROR_NONE) {
1869         snprintf(g_capabilities.profile_name, sizeof(g_capabilities.profile_name),
1870                     "%s", UNKNOWN);
1871         D("fail to get profile name:%d\n", errno);
1872     } else {
1873         snprintf(g_capabilities.profile_name, sizeof(g_capabilities.profile_name),
1874                     "%s", value);
1875         if (value != NULL) {
1876             free(value);
1877         }
1878     }
1879
1880
1881     // Vendor name
1882     ret = system_info_get_platform_string("http://tizen.org/system/manufacturer", &value);
1883     if (ret != SYSTEM_INFO_ERROR_NONE) {
1884         snprintf(g_capabilities.vendor_name, sizeof(g_capabilities.vendor_name),
1885                     "%s", UNKNOWN);
1886         D("fail to get the Vendor name:%d\n", errno);
1887     } else {
1888         snprintf(g_capabilities.vendor_name, sizeof(g_capabilities.vendor_name),
1889                     "%s", value);
1890         if (value != NULL) {
1891             free(value);
1892         }
1893     }
1894
1895
1896     // Target name of the launch possible
1897     if(!request_capability_to_plugin(CAPABILITY_CAN_LAUNCH, g_capabilities.can_launch,
1898                             sizeof(g_capabilities.can_launch))) {
1899         D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_CAN_LAUNCH);
1900         snprintf(g_capabilities.can_launch, sizeof(g_capabilities.can_launch),
1901                     "%s", UNKNOWN);
1902     }
1903
1904
1905     // Platform version
1906     ret = system_info_get_platform_string("http://tizen.org/feature/platform.version", &value);
1907     if (ret != SYSTEM_INFO_ERROR_NONE) {
1908         snprintf(g_capabilities.platform_version, sizeof(g_capabilities.platform_version),
1909                     "%s", UNKNOWN);
1910         D("fail to get platform version:%d\n", errno);
1911     } else {
1912         snprintf(g_capabilities.platform_version, sizeof(g_capabilities.platform_version),
1913                     "%s", value);
1914         if (value != NULL) {
1915             free(value);
1916         }
1917     }
1918
1919
1920     // Product version
1921     if(!request_capability_to_plugin(CAPABILITY_PRODUCT_VER, g_capabilities.product_version,
1922                             sizeof(g_capabilities.product_version))) {
1923         D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_PRODUCT_VER);
1924         snprintf(g_capabilities.product_version, sizeof(g_capabilities.product_version),
1925                     "%s", UNKNOWN);
1926     }
1927
1928
1929     // Sdbd version
1930     snprintf(g_capabilities.sdbd_version, sizeof(g_capabilities.sdbd_version),
1931                 "%d.%d.%d", SDB_VERSION_MAJOR, SDB_VERSION_MINOR, SDB_VERSION_PATCH);
1932
1933
1934     // Sdbd plugin version
1935     if(!request_capability_to_plugin(CAPABILITY_PLUGIN_VER, g_capabilities.sdbd_plugin_version,
1936                             sizeof(g_capabilities.sdbd_plugin_version))) {
1937         D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_PLUGIN_VER);
1938         snprintf(g_capabilities.sdbd_plugin_version, sizeof(g_capabilities.sdbd_plugin_version),
1939                     "%s", UNKNOWN);
1940     }
1941
1942
1943     // sdbd log enable
1944     if(!request_capability_to_plugin(CAPABILITY_LOG_ENABLE, g_capabilities.log_enable,
1945                                sizeof(g_capabilities.log_enable))) {
1946            D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_LOG_ENABLE);
1947            snprintf(g_capabilities.log_enable, sizeof(g_capabilities.log_enable),
1948                        "%s", DISABLED);
1949     }
1950
1951     // sdbd log path
1952     if(!request_capability_to_plugin(CAPABILITY_LOG_PATH, g_capabilities.log_path,
1953                                sizeof(g_capabilities.log_path))) {
1954            D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_LOG_PATH);
1955            snprintf(g_capabilities.log_path, sizeof(g_capabilities.log_path),
1956                        "%s", UNKNOWN);
1957     }
1958
1959     // Application command support
1960     if(!request_capability_to_plugin(CAPABILITY_APPCMD, g_capabilities.appcmd_support,
1961                                sizeof(g_capabilities.appcmd_support))) {
1962            D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_APPCMD);
1963            snprintf(g_capabilities.appcmd_support, sizeof(g_capabilities.appcmd_support),
1964                        "%s", UNKNOWN);
1965     }
1966
1967     // appid2pid support
1968     ret = is_appid2pid_supported();
1969     snprintf(g_capabilities.appid2pid_support, sizeof(g_capabilities.appid2pid_support),
1970                 "%s", ret == 1 ? ENABLED : DISABLED);
1971
1972     // pkgcmd debug mode support
1973     if(!request_capability_to_plugin(CAPABILITY_DEBUGMODE, g_capabilities.pkgcmd_debugmode,
1974                 sizeof(g_capabilities.pkgcmd_debugmode))) {
1975         D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_DEBUGMODE);
1976         snprintf(g_capabilities.pkgcmd_debugmode, sizeof(g_capabilities.pkgcmd_debugmode),
1977                 "%s", ENABLED);
1978     }
1979
1980     // Capability version
1981     snprintf(g_capabilities.sdbd_cap_version, sizeof(g_capabilities.sdbd_cap_version),
1982                 "%d.%d", SDBD_CAP_VERSION_MAJOR, SDBD_CAP_VERSION_MINOR);
1983 }
1984
1985 static int is_support_usbproto()
1986 {
1987     return (!strncmp(g_capabilities.usbproto_support, PLUGIN_RET_ENABLED, strlen(PLUGIN_RET_ENABLED)));
1988 }
1989
1990 static int is_support_sockproto()
1991 {
1992     return (!strncmp(g_capabilities.sockproto_support, PLUGIN_RET_ENABLED, strlen(PLUGIN_RET_ENABLED)));
1993 }
1994
1995 #define EMULATOR_MODEL_NAME     "Emulator"
1996 static void check_emulator_or_device()
1997 {
1998     char model_name[256]={0,};
1999     int ret = -1;
2000
2001     // Get the model name from model_config.xml
2002     ret = get_device_name(model_name, sizeof model_name);
2003     if (ret == 0) {
2004         if(!strncmp(model_name, EMULATOR_MODEL_NAME, sizeof(EMULATOR_MODEL_NAME))){
2005             g_is_emulator = 1;
2006             D("This target type is Emulator\n");
2007         } else {
2008             g_is_emulator = 0;
2009             D("This target type is Device\n");
2010         }
2011     } else {
2012         g_is_emulator = -1;
2013         D("failed to get the model name.\n");
2014     }
2015 }
2016
2017 static void fork_prepare_handler(void)
2018 {
2019     sdb_mutex_lock(&D_lock);
2020 }
2021
2022 static void fork_parent_handler(void)
2023 {
2024     sdb_mutex_unlock(&D_lock);
2025 }
2026
2027 static void fork_child_handler(void)
2028 {
2029     sdb_mutex_unlock(&D_lock);
2030 }
2031
2032 int sdb_main(int server_port)
2033 {
2034     check_emulator_or_device();
2035
2036     load_sdbd_plugin();
2037
2038     init_capabilities();
2039
2040     sdb_trace_init();
2041     start_device_log();
2042
2043     init_drop_privileges();
2044     init_sdk_requirements();
2045     if (!request_validity_to_plugin(PLUGIN_SYNC_CMD_VERIFY_LAUNCH, NULL)) {
2046         D("sdbd should be launched in develop mode.\n");
2047         return -1;
2048     }
2049
2050     umask(000);
2051
2052     pthread_atfork(fork_prepare_handler, fork_parent_handler, fork_child_handler);
2053
2054     atexit(sdb_cleanup);
2055 #if defined(HAVE_FORKEXEC)
2056     // No SIGCHLD. Let the service subproc handle its children.
2057     signal(SIGPIPE, SIG_IGN);
2058 #endif
2059
2060     init_transport_registration();
2061
2062     /* don't listen on a port (default 5037) if running in secure mode */
2063     /* don't run as root if we are running in secure mode */
2064
2065     if (should_drop_privileges()) {
2066 # if 0
2067         struct __user_cap_header_struct header;
2068         struct __user_cap_data_struct cap;
2069
2070         if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
2071             exit(1);
2072         }
2073         /* add extra groups:
2074         ** SID_TTY to access /dev/ptmx
2075         */
2076         gid_t groups[] = { SID_TTY, SID_APP_LOGGING, SID_SYS_LOGGING };
2077         if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
2078             exit(1);
2079         }
2080         /* then switch user and group to "developer" */
2081         if (setgid(GID_DEVELOPER) != 0) {
2082             fprintf(stderr, "set group id failed errno: %d\n", errno);
2083             exit(1);
2084         }
2085         if (setuid(SID_DEVELOPER) != 0) {
2086             fprintf(stderr, "set user id failed errno: %d\n", errno);
2087             exit(1);
2088         }
2089
2090         /* set CAP_SYS_BOOT capability, so "sdb reboot" will succeed */
2091         header.version = _LINUX_CAPABILITY_VERSION;
2092         header.pid = 0;
2093         cap.effective = cap.permitted = (1 << CAP_SYS_BOOT);
2094         cap.inheritable = 0;
2095         capset(&header, &cap);
2096 #endif
2097         D("Local port disabled\n");
2098     } else {
2099         char local_name[30];
2100         build_local_name(local_name, sizeof(local_name), server_port);
2101         if(install_listener(local_name, "*smartsocket*", NULL)) {
2102             exit(1);
2103         }
2104     }
2105
2106     /* choose the usb gadget backend */
2107     if (access(USB_NODE_FILE, F_OK) == 0) {
2108         /* legacy kernel-based sdb gadget */
2109         usb_init =    &linux_usb_init;
2110         usb_cleanup = &linux_usb_cleanup;
2111         usb_write =   &linux_usb_write;
2112         usb_read =    &linux_usb_read;
2113         usb_close =   &linux_usb_close;
2114         usb_kick =    &linux_usb_kick;
2115     } else {
2116         /* functionfs based gadget */
2117         usb_init =    &ffs_usb_init;
2118         usb_cleanup = &ffs_usb_cleanup;
2119         usb_write =   &ffs_usb_write;
2120         usb_read =    &ffs_usb_read;
2121         usb_close =   &ffs_usb_close;
2122         usb_kick =    &ffs_usb_kick;
2123     }
2124
2125     if (is_support_usbproto()) {
2126         // listen on USB
2127         usb_init();
2128     }
2129     if (is_support_sockproto()) {
2130         /* by default don't listen on local transport but
2131          * listen if suitable command line argument has been provided */
2132         if (sdbd_commandline_args.sdbd_port >= 0) {
2133             local_init(sdbd_commandline_args.sdbd_port);
2134         } else {
2135             local_init(DEFAULT_SDB_LOCAL_TRANSPORT_PORT);
2136         }
2137     }
2138
2139 #if 0 /* tizen specific */
2140     D("sdb_main(): pre init_jdwp()\n");
2141     init_jdwp();
2142     D("sdb_main(): post init_jdwp()\n");
2143 #endif
2144
2145     D("Event loop starting\n");
2146
2147     fdevent_loop();
2148
2149     if (is_support_usbproto()) {
2150         usb_cleanup();
2151     }
2152
2153     return 0;
2154 }
2155
2156 int copy_packet(apacket* dest, apacket* src) {
2157
2158     if(dest == NULL) {
2159         D("dest packet is NULL\n");
2160         return -1;
2161     }
2162
2163     if(src == NULL) {
2164         D("src packet is NULL\n");
2165         return -1;
2166     }
2167
2168     dest->next = src->next;
2169     dest->ptr = src->ptr;
2170     dest->len = src->len;
2171
2172     int data_length = src->msg.data_length;
2173     if(data_length > MAX_PAYLOAD) {
2174         data_length = MAX_PAYLOAD;
2175     }
2176     memcpy(&(dest->msg), &(src->msg), sizeof(amessage) + data_length);
2177
2178     return 0;
2179 }
2180
2181 int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s)
2182 {
2183     atransport *transport = NULL;
2184     char buf[4096];
2185
2186     if(!strcmp(service, "kill")) {
2187         fprintf(stderr,"sdb server killed by remote request\n");
2188         fflush(stdout);
2189         sdb_write(reply_fd, "OKAY", 4);
2190         if (is_support_usbproto()) {
2191             usb_cleanup();
2192         }
2193         exit(0);
2194     }
2195
2196     if(!strncmp(service,"forward:",8) || !strncmp(service,"killforward:",12)) {
2197         char *local, *remote, *err;
2198         int r;
2199         atransport *transport;
2200
2201         int createForward = strncmp(service,"kill",4);
2202
2203         local = service + (createForward ? 8 : 12);
2204         remote = strchr(local,';');
2205         if(remote == 0) {
2206             sendfailmsg(reply_fd, "malformed forward spec");
2207             return 0;
2208         }
2209
2210         *remote++ = 0;
2211         if((local[0] == 0) || (remote[0] == 0) || (remote[0] == '*')){
2212             sendfailmsg(reply_fd, "malformed forward spec");
2213             return 0;
2214         }
2215
2216         transport = acquire_one_transport(CS_ANY, ttype, serial, &err);
2217         if (!transport) {
2218             sendfailmsg(reply_fd, err);
2219             return 0;
2220         }
2221
2222         if (createForward) {
2223             r = install_listener(local, remote, transport);
2224         } else {
2225             r = remove_listener(local, remote, transport);
2226         }
2227         if(r == 0) {
2228                 /* 1st OKAY is connect, 2nd OKAY is status */
2229             writex(reply_fd, "OKAYOKAY", 8);
2230             return 0;
2231         }
2232
2233         if (createForward) {
2234             sendfailmsg(reply_fd, (r == -1) ? "cannot rebind smartsocket" : "cannot bind socket");
2235         } else {
2236             sendfailmsg(reply_fd, "cannot remove listener");
2237         }
2238         return 0;
2239     }
2240
2241     if(!strncmp(service,"get-state",strlen("get-state"))) {
2242         transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
2243         char *state = connection_state_name(transport);
2244         snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(state),state);
2245         writex(reply_fd, buf, strlen(buf));
2246         return 0;
2247     }
2248     return -1;
2249 }
2250
2251 int recovery_mode = 0;
2252
2253 int main(int argc, char **argv)
2254 {
2255     /* If sdbd runs inside the emulator this will enable sdb tracing via
2256      * sdb-debug qemud service in the emulator. */
2257 #if 0 /* tizen specific */
2258     sdb_qemu_trace_init();
2259     if((argc > 1) && (!strcmp(argv[1],"recovery"))) {
2260         sdb_device_banner = "recovery";
2261         recovery_mode = 1;
2262     }
2263 #endif
2264
2265     apply_sdbd_commandline_defaults(&sdbd_commandline_args);
2266     int parse_ret = parse_sdbd_commandline(&sdbd_commandline_args, argc, argv);
2267
2268     // TODO: Add detailed error messages
2269     // TODO: Add individual messages for help and usage
2270     if(parse_ret != SDBD_COMMANDLINE_SUCCESS) {
2271         if (parse_ret == SDBD_COMMANDLINE_HELP
2272                 || parse_ret == SDBD_COMMANDLINE_USAGE) {
2273             // User requested help or usage
2274             print_sdbd_usage_message(stdout);
2275             return EXIT_SUCCESS;
2276         }
2277
2278         // Print usage message because of invalid options
2279         print_sdbd_usage_message(stderr);
2280         return EXIT_FAILURE;
2281     }
2282
2283     if (daemonize() < 0)
2284         fatal("daemonize() failed: errno:%d", errno);
2285
2286     D("Handling main()\n");
2287
2288     //sdbd will never die on emulator!
2289     signal(SIGTERM, handle_sig_term); /* tizen specific */
2290     return sdb_main(DEFAULT_SDB_PORT);
2291 }
2292