Revert "Modify the packet size in transport protocol."
[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
35 #include "sysdeps.h"
36 #include "log.h"
37 #include "sdb.h"
38 #include "strutils.h"
39 #if !SDB_HOST
40 #include "commandline_sdbd.h"
41 #endif
42 #include "utils.h"
43 #include "sdktools.h"
44 #include "plugin.h"
45 #include "sdbd_plugin.h"
46
47 #ifdef SUPPORT_ENCRYPT
48 #include "plugin_encrypt.h"
49 #endif
50
51 #if !SDB_HOST
52 #include <linux/prctl.h>
53 #define SDB_PIDPATH "/tmp/.sdbd.pid"
54 #endif
55 #include <system_info.h>
56 #include <vconf.h>
57 #include <glib.h>
58
59 #define PROC_CMDLINE_PATH "/proc/cmdline"
60 #define USB_SERIAL_PATH "/sys/class/usb_mode/usb0/iSerial"
61
62 #include <sys/ioctl.h>
63 #include <net/if.h>
64 #include <netinet/in.h>
65 #include <arpa/inet.h>
66 #define GUEST_IP_INTERFACE "eth0"
67
68 SDB_MUTEX_DEFINE(zone_check_lock);
69 #if SDB_TRACE
70 SDB_MUTEX_DEFINE( D_lock );
71 #endif
72
73 int HOST = 0;
74 uid_t g_sdk_user_id;
75 gid_t g_sdk_group_id;
76 char* g_sdk_home_dir = NULL;
77 char* g_sdk_home_dir_env = NULL;
78 pcap g_capabilities;
79 int rootshell_mode; // 0: sdk user, 1: root
80 int booting_done; // 0: platform booting is in progess 1: platform booting is done
81
82 struct group_info
83 {
84     const char *name;
85     gid_t gid;
86 };
87 struct group_info g_default_groups[] = {
88     {"priv_externalstorage", -1},
89     {"priv_externalstorage_appdata", -1},
90     {"priv_mediastorage", -1},
91     {"log", -1},
92     {NULL, -1}
93 };
94 #define SDB_DEFAULT_GROUPS_CNT  ((sizeof(g_default_groups)/sizeof(g_default_groups[0]))-1)
95
96 int is_init_sdk_userinfo = 0;
97 int is_pwlocked = 0;    // 0 if unlocked, 1 otherwise
98
99 #if !SDB_HOST
100 SdbdCommandlineArgs sdbd_commandline_args;
101 #endif
102
103 static int is_support_usbproto();
104 static int is_support_sockproto();
105
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;
112
113 int g_is_emulator = -1;
114 int is_emulator(void) {
115 #if SDB_HOST
116     return 0;
117 #else
118     if (g_is_emulator >= 0) {
119         return g_is_emulator;
120     } else {
121         D("failed to initialize check emulator\n");
122     }
123
124     return sdbd_commandline_args.emulator.host != NULL;
125 #endif
126 }
127
128 int is_container_enabled(void) {
129     bool value;
130     int ret;
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);
134         return 0;
135     } else {
136         D("tizen container: %d\n", value);
137         if (value == true)
138             return 1;
139         else
140             return 0;
141     }
142 }
143
144 void handle_sig_term(int sig) {
145 #ifdef SDB_PIDPATH
146     if (access(SDB_PIDPATH, F_OK) == 0)
147         sdb_unlink(SDB_PIDPATH);
148 #endif
149 }
150
151 static const char *sdb_device_banner = "device";
152
153 void fatal(const char *fmt, ...)
154 {
155     va_list ap;
156     va_start(ap, fmt);
157     fprintf(stderr, "error: ");
158     vfprintf(stderr, fmt, ap);
159     fprintf(stderr, "\n");
160     va_end(ap);
161     exit(-1);
162 }
163
164 void fatal_errno(const char *fmt, ...)
165 {
166     va_list ap;
167     va_start(ap, fmt);
168     fprintf(stderr, "errno: %d: ", errno);
169     vfprintf(stderr, fmt, ap);
170     fprintf(stderr, "\n");
171     va_end(ap);
172     exit(-1);
173 }
174
175 static int is_enable_sdbd_log()
176 {
177     return (!strncmp(g_capabilities.log_enable, PLUGIN_RET_ENABLED, strlen(PLUGIN_RET_ENABLED)));
178 }
179
180 int   sdb_trace_mask;
181
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
185  * enable all tracing
186  */
187 void  sdb_trace_init(void)
188 {
189     const char*  p = getenv("SDB_TRACE");
190     const char*  q;
191
192     static const struct {
193         const char*  tag;
194         int           flag;
195     } tags[] = {
196         { "1", 0 },
197         { "all", 0 },
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 },
211         { NULL, 0 }
212     };
213
214     if (p == NULL) {
215         if (is_enable_sdbd_log())
216             p = "all";
217         else
218             return;
219     }
220
221     /* use a comma/column/semi-colum/space separated list */
222     while (*p) {
223         int  len, tagn;
224
225         q = strpbrk(p, " ,:;");
226         if (q == NULL) {
227             q = p + strlen(p);
228         }
229         len = q - p;
230
231         for (tagn = 0; tags[tagn].tag != NULL; tagn++)
232         {
233             int  taglen = strlen(tags[tagn].tag);
234
235             if (len == taglen && !memcmp(tags[tagn].tag, p, len) )
236             {
237                 int  flag = tags[tagn].flag;
238                 if (flag == 0) {
239                     sdb_trace_mask = ~0;
240                     return;
241                 }
242                 sdb_trace_mask |= (1 << flag);
243                 break;
244             }
245         }
246         p = q;
247         if (*p)
248             p++;
249     }
250 }
251
252 #if !SDB_HOST
253 /*
254  * Implements SDB tracing inside the emulator.
255  */
256
257 #include <stdarg.h>
258
259 /*
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.
262  */
263
264 #undef open
265 #undef write
266 #define open    sdb_open
267 #define write   sdb_write
268 #include "qemu_pipe.h"
269 #undef open
270 #undef write
271 #define open    ___xxx_open
272 #define write   ___xxx_write
273
274 /* A handle to sdb-debug qemud service in the emulator. */
275 int   sdb_debug_qemu = -1;
276
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)
280 {
281     char con_name[32];
282
283     if (sdb_debug_qemu >= 0) {
284         return 0;
285     }
286
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;
291 }
292
293 void sdb_qemu_trace(const char* fmt, ...)
294 {
295     va_list args;
296     va_start(args, fmt);
297     char msg[1024];
298
299     if (sdb_debug_qemu >= 0) {
300         vsnprintf(msg, sizeof(msg), fmt, args);
301         sdb_write(sdb_debug_qemu, msg, strlen(msg));
302     }
303 }
304 #endif
305 #endif  /* !SDB_HOST */
306
307 apacket *get_apacket(void)
308 {
309     apacket *p = malloc(sizeof(apacket));
310     if(p == 0) fatal("failed to allocate an apacket");
311     memset(p, 0, sizeof(apacket) - MAX_PAYLOAD);
312     return p;
313 }
314
315 void put_apacket(apacket *p)
316 {
317     if (p != NULL) {
318         free(p);
319         p = NULL;
320     }
321 }
322
323 void handle_online(void)
324 {
325     D("sdb: online\n");
326 }
327
328 void handle_offline(atransport *t)
329 {
330     D("sdb: offline\n");
331     //Close the associated usb
332     run_transport_disconnects(t);
333 }
334
335 #if TRACE_PACKETS
336 #define DUMPMAX 32
337 void print_packet(const char *label, apacket *p)
338 {
339     char *tag;
340     char *x;
341     unsigned count;
342
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;
351     }
352
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;
356     x = (char*) p->data;
357     if(count > DUMPMAX) {
358         count = DUMPMAX;
359         tag = "\n";
360     } else {
361         tag = "\"\n";
362     }
363     while(count-- > 0){
364         if((*x >= ' ') && (*x < 127)) {
365             fputc(*x, stderr);
366         } else {
367             fputc('.', stderr);
368         }
369         x++;
370     }
371     fprintf(stderr, tag);
372 }
373 #endif
374
375 #ifdef SUPPORT_ENCRYPT
376 /* 
377 desc. : 암호화 실패 메시지 전송
378 parameter : [in] apacket* p : sdbd로 들어온 메시지
379                         [in] atransport *t : 현재 연결에 대한 atransport
380                         [in] unsigned failed_value : 실패 값
381 */
382 void send_encr_fail(apacket* p, atransport *t, unsigned failed_value){
383         apacket* enc_p;
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);
390 }
391
392 /* 
393 desc. : 암호화 메시지 핸들링
394 parameter : [in] apacket* p : sdbd로 들어온 메시지
395                         [in/out] atransport *t : 현재 연결에 대한 atransport
396 ret : 0 : 정상적으로 메시지 전송
397           -1: 메시지 전송 실패
398 */
399 int handle_encr_packet(apacket* p, atransport *t){
400         static int sessionID = 0;
401         int retVal = 0;
402     apacket* enc_p = NULL;
403
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;
415                                         sessionID++;
416                                         send_packet(enc_p, t);
417                                 }
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);                          
423                                         return -1;
424                                 }
425                         }
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);
431                                 
432                                 return -1;
433                         }
434                 } else { // init 실패
435                         D("security_init error\n");
436                         send_encr_fail(p, t, ENCR_ON_FAIL);
437                         t->encryption = ENCR_OFF;
438                         if (retVal == -1)
439                         {
440                                 security_deinit(t->sessionID);
441                         }
442                         //here!! do security_deinit(), but when plugin pointer is null -> not deinit
443                         return -1;
444                 }
445         }
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);
456                         }
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);
462                                 return -1;
463                         }
464                 }
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);
470                         return -1;
471                 }
472         }
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);
481                 }
482                 else { // 암호화 모드 off에 실패한 경우
483                         D("security_deinit error\n");
484                         send_encr_fail(p, t, ENCR_OFF_FAIL); // 암호화 모드 off 실패 메시지 전송
485                         return -1;
486                 }
487         }
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 메시지 전송
499                 }
500                 send_packet(enc_p, t);
501         }
502         else if (p->msg.arg0 == ENCR_ON_FAIL) // 암호화 모드를 on 하는 도중 실패한 경우 받는 메시지
503         {
504                 t->encryption = ENCR_OFF; // 암호화 모드를 다시 off
505                 D("encryption on failed\n");
506         }
507         else if (p->msg.arg0 == ENCR_OFF_FAIL) // 암호화 모드를 off하는 도중 실패한 경우 받는 메시지
508         {
509                 //t->encryption = ENCR_ON;
510                 D("encryption off failed\n");
511         }
512         //put_apacket(enc_p);
513         return 0;
514         
515 }
516 #endif
517
518
519 static void send_ready(unsigned local, unsigned remote, atransport *t)
520 {
521     D("Calling send_ready \n");
522     apacket *p = get_apacket();
523     p->msg.command = A_OKAY;
524     p->msg.arg0 = local;
525     p->msg.arg1 = remote;
526     send_packet(p, t);
527 }
528
529 static void send_close(unsigned local, unsigned remote, atransport *t)
530 {
531     D("Calling send_close \n");
532     apacket *p = get_apacket();
533     p->msg.command = A_CLSE;
534     p->msg.arg0 = local;
535     p->msg.arg1 = remote;
536     send_packet(p, t);
537 }
538
539 static void send_connect(atransport *t)
540 {
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의 패킷 크기를 암호화 오버로드 만큼 줄임
547 #else
548     cp->msg.arg1 = MAX_PAYLOAD;
549 #endif
550     char device_name[256]={0,};
551     int r = 0;
552     int status = 0;
553     if (request_lock_state_to_plugin(LOCKTYPE_PASSWORD) == 1) {
554         status = 1;
555         t->connection_state = CS_PWLOCK;
556     }
557
558     if (is_emulator()) {
559         r = get_emulator_name(device_name, sizeof device_name);
560     } else {
561         r = get_device_name(device_name, sizeof device_name);
562     }
563     if (r < 0) {
564         snprintf((char*) cp->data, sizeof cp->data, "%s::%s::%d", sdb_device_banner, DEFAULT_DEVICENAME, status);
565     } else {
566         snprintf((char*) cp->data, sizeof cp->data, "%s::%s::%d", sdb_device_banner, device_name, status);
567     }
568
569     D("CNXN data:%s\n", (char*)cp->data);
570     cp->msg.data_length = strlen((char*) cp->data) + 1;
571
572     send_packet(cp, t);
573 #if SDB_HOST
574         /* XXX why sleep here? */
575     // allow the device some time to respond to the connect message
576     sdb_sleep_ms(1000);
577 #endif
578 }
579
580 void send_device_status()
581 {
582     D("broadcast device status\n");
583     apacket* cp = get_apacket();
584     cp->msg.command = A_STAT;
585     cp->msg.arg0 = is_pwlocked;
586     cp->msg.arg1 = 0;
587
588     broadcast_transport(cp);
589
590     //all broadcasted packets are memory copied
591     //so, we should call put_apacket
592     put_apacket(cp);
593 }
594
595 static char *connection_state_name(atransport *t)
596 {
597     if (t == NULL) {
598         return "unknown";
599     }
600
601     switch(t->connection_state) {
602     case CS_BOOTLOADER:
603         return "bootloader";
604     case CS_DEVICE:
605         return "device";
606     case CS_OFFLINE:
607         return "offline";
608     default:
609         return "unknown";
610     }
611 }
612
613 static int get_str_cmdline(char *src, char *dest, char str[], int str_size) {
614     char *s = strstr(src, dest);
615     if (s == NULL) {
616         return -1;
617     }
618     char *e = strstr(s, " ");
619     if (e == NULL) {
620         return -1;
621     }
622
623     int len = e-s-strlen(dest);
624
625     if (len >= str_size) {
626         D("buffer size(%d) should be bigger than %d\n", str_size, len+1);
627         return -1;
628     }
629
630     strncpy(str, s + strlen(dest), len);
631     str[len]='\0';
632     return len;
633 }
634
635 int get_emulator_forward_port() {
636     SdbdCommandlineArgs *sdbd_args = &sdbd_commandline_args; /* alias */
637
638     if (sdbd_args->emulator.host == NULL) {
639         return -1;
640     }
641
642     return sdbd_args->emulator.port;
643 }
644
645 int get_emulator_name(char str[], int str_size) {
646     SdbdCommandlineArgs *sdbd_args = &sdbd_commandline_args; /* alias */
647
648     if (sdbd_args->emulator.host == NULL) {
649         return -1;
650     }
651
652     s_strncpy(str, sdbd_args->emulator.host, str_size);
653     return 0;
654 }
655
656 int get_device_name(char str[], int str_size) {
657     char *value = NULL;
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);
661         return -1;
662     } else {
663         s_strncpy(str, value, str_size);
664         D("returns model_name:%s\n", value);
665         if (value != NULL) {
666             free(value);
667         }
668         return 0;
669     }
670     /*
671     int fd = unix_open(USB_SERIAL_PATH, O_RDONLY);
672     if (fd < 0) {
673         D("fail to read:%s (%d)\n", USB_SERIAL_PATH, errno);
674         return -1;
675     }
676
677     if(read_line(fd, str, str_size)) {
678         D("device serial name: %s\n", str);
679         sdb_close(fd);
680         return 0;
681     }
682     sdb_close(fd);
683     */
684     return -1;
685 }
686
687 static int get_cmdline_value(char *split, char str[], int str_size) {
688     char cmdline[512];
689     int fd = unix_open(PROC_CMDLINE_PATH, O_RDONLY);
690
691     if (fd < 0) {
692         D("fail to read /proc/cmdline\n");
693         return -1;
694     }
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);
699             sdb_close(fd);
700             return -1;
701         }
702     }
703     sdb_close(fd);
704     return 0;
705 }
706
707 int get_emulator_hostip(char str[], int str_size) {
708     return get_cmdline_value("host_ip=", str, str_size);
709 }
710
711 int get_emulator_guestip(char str[], int str_size) {
712     int           s;
713     struct ifreq ifr;
714     struct sockaddr_in *sin;
715
716     s = socket(AF_INET, SOCK_DGRAM, 0);
717     if(s < 0) {
718         D("socket error\n");
719         return -1;
720     }
721
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");
725         sdb_close(s);
726         return -1;
727     }
728
729     if(ioctl(s, SIOCGIFADDR, &ifr) < 0) {
730         D("ioctl addr error\n");
731         sdb_close(s);
732         return -1;
733     }
734     sin = (struct sockaddr_in *)&ifr.ifr_addr;
735     snprintf(str, str_size, "%s", inet_ntoa(sin->sin_addr));
736     sdb_close(s);
737
738     return 0;
739 }
740
741 void parse_banner(char *banner, atransport *t)
742 {
743     char *type, *product, *end;
744
745     D("parse_banner: %s\n", banner);
746     type = banner;
747     product = strchr(type, ':');
748     if(product) {
749         *product++ = 0;
750     } else {
751         product = "";
752     }
753
754         /* remove trailing ':' */
755     end = strchr(product, ':');
756     if(end) *end = 0;
757
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) {
762         free(t->product);
763         t->product = strdup(product);
764     }
765
766     if(!strcmp(type, "bootloader")){
767         D("setting connection_state to CS_BOOTLOADER\n");
768         t->connection_state = CS_BOOTLOADER;
769         update_transports();
770         return;
771     }
772
773     if(!strcmp(type, "device")) {
774         D("setting connection_state to CS_DEVICE\n");
775         t->connection_state = CS_DEVICE;
776         update_transports();
777         return;
778     }
779
780     if(!strcmp(type, "recovery")) {
781         D("setting connection_state to CS_RECOVERY\n");
782         t->connection_state = CS_RECOVERY;
783         update_transports();
784         return;
785     }
786
787     if(!strcmp(type, "sideload")) {
788         D("setting connection_state to CS_SIDELOAD\n");
789         t->connection_state = CS_SIDELOAD;
790         update_transports();
791         return;
792     }
793
794     t->connection_state = CS_HOST;
795 }
796
797 void handle_packet(apacket *p, atransport *t)
798 {
799     // Verify pointer p
800     int result = access((const char *) p, F_OK);
801     if ((result == -1) && (errno == EFAULT)) {
802         fatal("Invalid apacket = [0x%p]", p);
803     }
804
805     asocket *s;
806
807     D("handle_packet() %c%c%c%c\n", ((char*) (&(p->msg.command)))[0],
808                 ((char*) (&(p->msg.command)))[1],
809                 ((char*) (&(p->msg.command)))[2],
810                 ((char*) (&(p->msg.command)))[3]);
811
812     print_packet("recv", p);
813
814     switch(p->msg.command){
815     case A_SYNC:
816         if(p->msg.arg0){
817             send_packet(p, t);
818             if(HOST) send_connect(t);
819         } else {
820             t->connection_state = CS_OFFLINE;
821             handle_offline(t);
822             send_packet(p, t);
823         }
824         return;
825
826     case A_CNXN: /* CONNECT(version, maxdata, "system-id-string") */
827             /* XXX verify version, etc */
828         if(t->connection_state != CS_OFFLINE) {
829             t->connection_state = CS_OFFLINE;
830             handle_offline(t);
831         }
832         parse_banner((char*) p->data, t);
833         handle_online();
834         if(!HOST) send_connect(t);
835         break;
836
837     case A_OPEN: /* OPEN(local-id, 0, "destination") */
838         if (request_lock_state_to_plugin(LOCKTYPE_PASSWORD) == 1 && t->connection_state == CS_PWLOCK) {
839             // in case of already locked before get A_CNXN
840             D("open failed due to password locked before get A_CNXN:%d\n", t->connection_state);
841             send_close(0, p->msg.arg0, t);
842         } else {
843             if(t->connection_state != CS_OFFLINE) {
844                 char *name = (char*) p->data;
845                 name[p->msg.data_length > 0 ? p->msg.data_length - 1 : 0] = 0;
846                 s = create_local_service_socket(name);
847                 if(s == 0) {
848                     send_close(0, p->msg.arg0, t);
849                 } else {
850                     s->peer = create_remote_socket(p->msg.arg0, t);
851                     s->peer->peer = s;
852                     send_ready(s->id, s->peer->id, t);
853                     s->ready(s);
854                 }
855             }
856         }
857         break;
858
859     case A_OKAY: /* READY(local-id, remote-id, "") */
860         if(t->connection_state != CS_OFFLINE) {
861             if((s = find_local_socket(p->msg.arg1))) {
862                 if(s->peer == 0) {
863                     s->peer = create_remote_socket(p->msg.arg0, t);
864                     s->peer->peer = s;
865                 }
866                 s->ready(s);
867             }
868         }
869         break;
870
871     case A_CLSE: /* CLOSE(local-id, remote-id, "") */
872         if(t->connection_state != CS_OFFLINE) {
873             if((s = find_local_socket(p->msg.arg1))) {
874                 s->close(s);
875             }
876         }
877         break;
878
879     case A_WRTE:
880         if(t->connection_state != CS_OFFLINE) {
881             if((s = find_local_socket(p->msg.arg1))) {
882                 unsigned rid = p->msg.arg0;
883                 p->len = p->msg.data_length;
884
885                 if(s->enqueue(s, p) == 0) {
886                     D("Enqueue the socket\n");
887                     send_ready(s->id, rid, t);
888                 }
889                 return;
890             }
891         }
892         break;
893 #ifdef SUPPORT_ENCRYPT
894         case A_ENCR: // 암호화 메시지인 경우
895                 if(t->connection_state != CS_OFFLINE) {
896                         handle_encr_packet(p, t);
897                 }
898                 break;
899 #endif
900
901     default:
902         printf("handle_packet: what is %08x?!\n", p->msg.command);
903     }
904
905     put_apacket(p);
906 }
907
908 alistener listener_list = {
909     .next = &listener_list,
910     .prev = &listener_list,
911 };
912
913 static void ss_listener_event_func(int _fd, unsigned ev, void *_l)
914 {
915     asocket *s;
916
917     if(ev & FDE_READ) {
918         struct sockaddr addr;
919         socklen_t alen;
920         int fd;
921
922         alen = sizeof(addr);
923         fd = sdb_socket_accept(_fd, &addr, &alen);
924         if(fd < 0) return;
925
926         sdb_socket_setbufsize(fd, CHUNK_SIZE);
927
928         s = create_local_socket(fd);
929         if(s) {
930             connect_to_smartsocket(s);
931             return;
932         }
933
934         sdb_close(fd);
935     }
936 }
937
938 static void listener_event_func(int _fd, unsigned ev, void *_l)
939 {
940     alistener *l = _l;
941     asocket *s;
942
943     if(ev & FDE_READ) {
944         struct sockaddr addr;
945         socklen_t alen;
946         int fd;
947
948         alen = sizeof(addr);
949         fd = sdb_socket_accept(_fd, &addr, &alen);
950         if(fd < 0) return;
951
952         s = create_local_socket(fd);
953         if(s) {
954             s->transport = l->transport;
955             connect_to_remote(s, l->connect_to);
956             return;
957         }
958
959         sdb_close(fd);
960     }
961 }
962
963 static void  free_listener(alistener*  l)
964 {
965     if (l->next) {
966         l->next->prev = l->prev;
967         l->prev->next = l->next;
968         l->next = l->prev = l;
969     }
970
971     // closes the corresponding fd
972     fdevent_remove(&l->fde);
973
974     if (l->local_name)
975         free((char*)l->local_name);
976
977     if (l->connect_to)
978         free((char*)l->connect_to);
979
980     if (l->transport) {
981         remove_transport_disconnect(l->transport, &l->disconnect);
982     }
983     free(l);
984 }
985
986 static void listener_disconnect(void*  _l, atransport*  t)
987 {
988     alistener*  l = _l;
989
990     free_listener(l);
991 }
992
993 int local_name_to_fd(const char *name)
994 {
995     int port;
996
997     if(!strncmp("tcp:", name, 4)){
998         int  ret;
999         port = atoi(name + 4);
1000         ret = socket_loopback_server(port, SOCK_STREAM);
1001         return ret;
1002     }
1003 #ifndef HAVE_WIN32_IPC  /* no Unix-domain sockets on Win32 */
1004     // It's non-sensical to support the "reserved" space on the sdb host side
1005     if(!strncmp(name, "local:", 6)) {
1006         return socket_local_server(name + 6,
1007                 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
1008     } else if(!strncmp(name, "localabstract:", 14)) {
1009         return socket_local_server(name + 14,
1010                 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
1011     } else if(!strncmp(name, "localfilesystem:", 16)) {
1012         return socket_local_server(name + 16,
1013                 ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
1014     }
1015
1016 #endif
1017     printf("unknown local portname '%s'\n", name);
1018     return -1;
1019 }
1020
1021 static int remove_listener(const char *local_name, const char *connect_to, atransport* transport)
1022 {
1023     alistener *l;
1024
1025     for (l = listener_list.next; l != &listener_list; l = l->next) {
1026         if (!strcmp(local_name, l->local_name) &&
1027             !strcmp(connect_to, l->connect_to) &&
1028             l->transport && l->transport == transport) {
1029
1030             listener_disconnect(l, transport);
1031             return 0;
1032         }
1033     }
1034
1035     return -1;
1036 }
1037
1038 static int install_listener(const char *local_name, const char *connect_to, atransport* transport)
1039 {
1040     alistener *l;
1041
1042     //printf("install_listener('%s','%s')\n", local_name, connect_to);
1043
1044     for(l = listener_list.next; l != &listener_list; l = l->next){
1045         if(strcmp(local_name, l->local_name) == 0) {
1046             char *cto;
1047
1048                 /* can't repurpose a smartsocket */
1049             if(l->connect_to[0] == '*') {
1050                 return -1;
1051             }
1052
1053             cto = strdup(connect_to);
1054             if(cto == 0) {
1055                 return -1;
1056             }
1057
1058             //printf("rebinding '%s' to '%s'\n", local_name, connect_to);
1059             free((void*) l->connect_to);
1060             l->connect_to = cto;
1061             if (l->transport != transport) {
1062                 remove_transport_disconnect(l->transport, &l->disconnect);
1063                 l->transport = transport;
1064                 add_transport_disconnect(l->transport, &l->disconnect);
1065             }
1066             return 0;
1067         }
1068     }
1069
1070     if((l = calloc(1, sizeof(alistener))) == 0) goto nomem;
1071     if((l->local_name = strdup(local_name)) == 0) goto nomem;
1072     if((l->connect_to = strdup(connect_to)) == 0) goto nomem;
1073
1074
1075     l->fd = local_name_to_fd(local_name);
1076     if(l->fd < 0) {
1077         free((void*) l->local_name);
1078         free((void*) l->connect_to);
1079         free(l);
1080         printf("cannot bind '%s'\n", local_name);
1081         return -2;
1082     }
1083
1084     if (close_on_exec(l->fd) < 0) {
1085         D("fail to close fd exec:%d\n",l->fd);
1086     }
1087     if(!strcmp(l->connect_to, "*smartsocket*")) {
1088         fdevent_install(&l->fde, l->fd, ss_listener_event_func, l);
1089     } else {
1090         fdevent_install(&l->fde, l->fd, listener_event_func, l);
1091     }
1092     fdevent_set(&l->fde, FDE_READ);
1093
1094     l->next = &listener_list;
1095     l->prev = listener_list.prev;
1096     l->next->prev = l;
1097     l->prev->next = l;
1098     l->transport = transport;
1099
1100     if (transport) {
1101         l->disconnect.opaque = l;
1102         l->disconnect.func   = listener_disconnect;
1103         add_transport_disconnect(transport, &l->disconnect);
1104     }
1105     return 0;
1106
1107 nomem:
1108     fatal("cannot allocate listener");
1109     return 0;
1110 }
1111
1112 #ifdef HAVE_WIN32_PROC
1113 static BOOL WINAPI ctrlc_handler(DWORD type)
1114 {
1115     exit(STATUS_CONTROL_C_EXIT);
1116     return TRUE;
1117 }
1118 #endif
1119
1120 static void sdb_cleanup(void)
1121 {
1122     clear_sdbd_commandline_args(&sdbd_commandline_args);
1123
1124     if (is_support_usbproto()) {
1125         usb_cleanup();
1126     }
1127 //    if(required_pid > 0) {
1128 //        kill(required_pid, SIGKILL);
1129 //    }
1130
1131     unload_sdbd_plugin();
1132 }
1133
1134 void start_logging(void)
1135 {
1136 #ifdef HAVE_WIN32_PROC
1137     char    temp[ MAX_PATH ];
1138     FILE*   fnul;
1139     FILE*   flog;
1140
1141     GetTempPath( sizeof(temp) - 8, temp );
1142     strcat( temp, "sdb.log" );
1143
1144     /* Win32 specific redirections */
1145     fnul = fopen( "NUL", "rt" );
1146     if (fnul != NULL)
1147         stdin[0] = fnul[0];
1148
1149     flog = fopen( temp, "at" );
1150     if (flog == NULL)
1151         flog = fnul;
1152
1153     setvbuf( flog, NULL, _IONBF, 0 );
1154
1155     stdout[0] = flog[0];
1156     stderr[0] = flog[0];
1157     fprintf(stderr,"--- sdb starting (pid %d) ---\n", getpid());
1158 #else
1159     int fd;
1160
1161     fd = unix_open("/dev/null", O_RDONLY);
1162     if (fd < 0) {
1163         // hopefully not gonna happen
1164         return;
1165     }
1166     dup2(fd, 0);
1167     sdb_close(fd);
1168
1169     fd = unix_open("/tmp/sdb.log", O_WRONLY | O_CREAT | O_APPEND, 0640);
1170     if(fd < 0) {
1171         fd = unix_open("/dev/null", O_WRONLY);
1172         if (fd < 0) {
1173             // hopefully not gonna happen
1174             return;
1175         }
1176     }
1177     dup2(fd, 1);
1178     dup2(fd, 2);
1179     sdb_close(fd);
1180     fprintf(stderr,"--- sdb starting (pid %d) ---\n", getpid());
1181 #endif
1182 }
1183
1184 #if !SDB_HOST
1185
1186 void start_device_log(void)
1187 {
1188     int fd;
1189     char    path[PATH_MAX] = {0, };
1190     char    path_folder[PATH_MAX] = {0, };
1191     char    path_file[PATH_MAX] = {0, };
1192     struct tm now;
1193     time_t t;
1194 //    char value[PROPERTY_VALUE_MAX];
1195     const char* p_trace = getenv("SDB_TRACE");
1196     const char* p_path = getenv("SDBD_LOG_PATH");
1197     // read the trace mask from persistent property persist.sdb.trace_mask
1198     // give up if the property is not set or cannot be parsed
1199 #if 0 /* tizen specific */
1200     property_get("persist.sdb.trace_mask", value, "");
1201     if (sscanf(value, "%x", &sdb_trace_mask) != 1)
1202         return;
1203 #endif
1204
1205     if ((p_trace == NULL ) && !is_enable_sdbd_log()) {
1206         return;
1207     }
1208
1209     if (p_path)
1210         snprintf(path_folder, sizeof(path_folder), "%s", p_path);
1211     else if (g_capabilities.log_path[0] != '\0')
1212         snprintf(path_folder, sizeof(path_folder), "%s", g_capabilities.log_path);
1213     else
1214         return;
1215
1216     tzset();
1217     time(&t);
1218     localtime_r(&t, &now);
1219
1220     strftime(path_file, sizeof(path_file),
1221                     "sdbd-%Y-%m-%d-%H-%M-%S.txt",
1222                     &now);
1223
1224     snprintf(path, sizeof(path), "%s/%s", path_folder, path_file);
1225
1226     fd = unix_open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1227     if (fd < 0) {
1228         return;
1229     }
1230
1231     // redirect stdout and stderr to the log file
1232     dup2(fd, 1);
1233     dup2(fd, 2);
1234     fprintf(stderr,"--- sdbd starting (pid %d) ---\n", getpid());
1235     sdb_close(fd);
1236
1237     fd = unix_open("/dev/null", O_RDONLY);
1238     if (fd < 0) {
1239         // hopefully not gonna happen
1240         return;
1241     }
1242     dup2(fd, 0);
1243     sdb_close(fd);
1244 }
1245
1246 int daemonize(void) {
1247
1248     // set file creation mask to 0
1249     umask(0);
1250
1251     switch (fork()) {
1252     case -1:
1253         return -1;
1254     case 0:
1255         break;
1256     default:
1257         _exit(0);
1258     }
1259 #ifdef SDB_PIDPATH
1260     FILE *f = fopen(SDB_PIDPATH, "w");
1261
1262     if (f != NULL) {
1263         fprintf(f, "%d\n", getpid());
1264         fclose(f);
1265     }
1266 #endif
1267     if (setsid() == -1)
1268         return -1;
1269
1270     if (chdir("/") < 0)
1271         D("sdbd: unable to change working directory to /\n");
1272
1273     return 0;
1274 }
1275 #endif
1276
1277 #if SDB_HOST
1278 int launch_server(int server_port)
1279 {
1280 #ifdef HAVE_WIN32_PROC
1281     /* we need to start the server in the background                    */
1282     /* we create a PIPE that will be used to wait for the server's "OK" */
1283     /* message since the pipe handles must be inheritable, we use a     */
1284     /* security attribute                                               */
1285     HANDLE                pipe_read, pipe_write;
1286     SECURITY_ATTRIBUTES   sa;
1287     STARTUPINFO           startup;
1288     PROCESS_INFORMATION   pinfo;
1289     char                  program_path[ MAX_PATH ];
1290     int                   ret;
1291
1292     sa.nLength = sizeof(sa);
1293     sa.lpSecurityDescriptor = NULL;
1294     sa.bInheritHandle = TRUE;
1295
1296     /* create pipe, and ensure its read handle isn't inheritable */
1297     ret = CreatePipe( &pipe_read, &pipe_write, &sa, 0 );
1298     if (!ret) {
1299         fprintf(stderr, "CreatePipe() failure, error %ld\n", GetLastError() );
1300         return -1;
1301     }
1302
1303     SetHandleInformation( pipe_read, HANDLE_FLAG_INHERIT, 0 );
1304
1305     ZeroMemory( &startup, sizeof(startup) );
1306     startup.cb = sizeof(startup);
1307     startup.hStdInput  = GetStdHandle( STD_INPUT_HANDLE );
1308     startup.hStdOutput = pipe_write;
1309     startup.hStdError  = GetStdHandle( STD_ERROR_HANDLE );
1310     startup.dwFlags    = STARTF_USESTDHANDLES;
1311
1312     ZeroMemory( &pinfo, sizeof(pinfo) );
1313
1314     /* get path of current program */
1315     GetModuleFileName( NULL, program_path, sizeof(program_path) );
1316
1317     ret = CreateProcess(
1318             program_path,                              /* program path  */
1319             "sdb fork-server server",
1320                                     /* the fork-server argument will set the
1321                                        debug = 2 in the child           */
1322             NULL,                   /* process handle is not inheritable */
1323             NULL,                    /* thread handle is not inheritable */
1324             TRUE,                          /* yes, inherit some handles */
1325             DETACHED_PROCESS, /* the new process doesn't have a console */
1326             NULL,                     /* use parent's environment block */
1327             NULL,                    /* use parent's starting directory */
1328             &startup,                 /* startup info, i.e. std handles */
1329             &pinfo );
1330
1331     CloseHandle( pipe_write );
1332
1333     if (!ret) {
1334         fprintf(stderr, "CreateProcess failure, error %ld\n", GetLastError() );
1335         CloseHandle( pipe_read );
1336         return -1;
1337     }
1338
1339     CloseHandle( pinfo.hProcess );
1340     CloseHandle( pinfo.hThread );
1341
1342     /* wait for the "OK\n" message */
1343     {
1344         char  temp[3];
1345         DWORD  count;
1346
1347         ret = ReadFile( pipe_read, temp, 3, &count, NULL );
1348         CloseHandle( pipe_read );
1349         if ( !ret ) {
1350             fprintf(stderr, "could not read ok from SDB Server, error = %ld\n", GetLastError() );
1351             return -1;
1352         }
1353         if (count != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
1354             fprintf(stderr, "SDB server didn't ACK\n" );
1355             return -1;
1356         }
1357     }
1358 #elif defined(HAVE_FORKEXEC)
1359     char    path[PATH_MAX];
1360     int     fd[2];
1361
1362     // set up a pipe so the child can tell us when it is ready.
1363     // fd[0] will be parent's end, and fd[1] will get mapped to stderr in the child.
1364     if (pipe(fd)) {
1365         fprintf(stderr, "pipe failed in launch_server, errno: %d\n", errno);
1366         return -1;
1367     }
1368     get_my_path(path, PATH_MAX);
1369     pid_t pid = fork();
1370     if(pid < 0) return -1;
1371
1372     if (pid == 0) {
1373         // child side of the fork
1374
1375         // redirect stderr to the pipe
1376         // we use stderr instead of stdout due to stdout's buffering behavior.
1377         sdb_close(fd[0]);
1378         dup2(fd[1], STDERR_FILENO);
1379         sdb_close(fd[1]);
1380
1381         // child process
1382         int result = execl(path, "sdb", "fork-server", "server", NULL);
1383         // this should not return
1384         fprintf(stderr, "OOPS! execl returned %d, errno: %d\n", result, errno);
1385     } else  {
1386         // parent side of the fork
1387
1388         char  temp[3];
1389
1390         temp[0] = 'A'; temp[1] = 'B'; temp[2] = 'C';
1391         // wait for the "OK\n" message
1392         sdb_close(fd[1]);
1393         int ret = sdb_read(fd[0], temp, 3);
1394         int saved_errno = errno;
1395         sdb_close(fd[0]);
1396         if (ret < 0) {
1397             fprintf(stderr, "could not read ok from SDB Server, errno = %d\n", saved_errno);
1398             return -1;
1399         }
1400         if (ret != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
1401             fprintf(stderr, "SDB server didn't ACK\n" );
1402             return -1;
1403         }
1404
1405         setsid();
1406     }
1407 #else
1408 #error "cannot implement background server start on this platform"
1409 #endif
1410     return 0;
1411 }
1412 #endif
1413
1414 /* Constructs a local name of form tcp:port.
1415  * target_str points to the target string, it's content will be overwritten.
1416  * target_size is the capacity of the target string.
1417  * server_port is the port number to use for the local name.
1418  */
1419 void build_local_name(char* target_str, size_t target_size, int server_port)
1420 {
1421   snprintf(target_str, target_size, "tcp:%d", server_port);
1422 }
1423
1424 #if !SDB_HOST
1425 static void init_drop_privileges() {
1426 #ifdef _DROP_PRIVILEGE
1427     rootshell_mode = 0;
1428 #else
1429     rootshell_mode = 1;
1430 #endif
1431 }
1432
1433 int should_drop_privileges() {
1434     if (rootshell_mode == 1) { // if root, then don't drop
1435         return 0;
1436     }
1437     return 1;
1438 }
1439
1440 #include <dbus/dbus.h>
1441 #include <dbus/dbus-glib.h>
1442 #include <dbus/dbus-glib-lowlevel.h>
1443
1444 #define BOOTING_DONE_SIGNAL    "BootingDone"
1445 #define DEVICED_CORE_INTERFACE "org.tizen.system.deviced.core"
1446 #define SDBD_BOOT_INFO_FILE "/tmp/sdbd_boot_info"
1447
1448 static DBusHandlerResult __sdbd_dbus_signal_filter(DBusConnection *conn,
1449                 DBusMessage *message, void *user_data) {
1450         D("got dbus message\n");
1451         const char *interface;
1452
1453         DBusError error;
1454         dbus_error_init(&error);
1455
1456         interface = dbus_message_get_interface(message);
1457         if (interface == NULL) {
1458                 D("reject by security issue - no interface\n");
1459                 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1460         }
1461
1462         if (dbus_message_is_signal(message, DEVICED_CORE_INTERFACE,
1463                         BOOTING_DONE_SIGNAL)) {
1464                 booting_done = 1;
1465                 if (access(SDBD_BOOT_INFO_FILE, F_OK) == 0) {
1466                         D("booting is done before\n");
1467                 } else {
1468                         FILE *f = fopen(SDBD_BOOT_INFO_FILE, "w");
1469                         if (f != NULL) {
1470                                 fprintf(f, "%d", 1);
1471                                 fclose(f);
1472                         }
1473                 }
1474                 D("booting is done\n");
1475         }
1476
1477         D("handled dbus message\n");
1478         return DBUS_HANDLER_RESULT_HANDLED;
1479 }
1480
1481 static void *bootdone_cb(void *x) {
1482         int MAX_LOCAL_BUFSZ = 128;
1483         DBusError error;
1484         DBusConnection *bus;
1485         char rule[MAX_LOCAL_BUFSZ];
1486         GMainLoop *mainloop;
1487
1488 /* g_type_init() is deprecated for glib version 2.35.0 or greater, */
1489 #if !GLIB_CHECK_VERSION(2,35,0)
1490         g_type_init();
1491 #endif
1492
1493         dbus_error_init(&error);
1494         bus = dbus_bus_get(DBUS_BUS_SYSTEM, &error);
1495         if (!bus) {
1496                 D("Failed to connect to the D-BUS daemon: %s", error.message);
1497                 dbus_error_free(&error);
1498                 return NULL;
1499         }
1500         dbus_connection_setup_with_g_main(bus, NULL);
1501
1502         snprintf(rule, MAX_LOCAL_BUFSZ, "type='signal',interface='%s'",
1503                         DEVICED_CORE_INTERFACE);
1504         /* listening to messages */
1505         dbus_bus_add_match(bus, rule, &error);
1506         if (dbus_error_is_set(&error)) {
1507                 D("Fail to rule set: %s", error.message);
1508                 dbus_error_free(&error);
1509                 return NULL;
1510         }
1511
1512         if (dbus_connection_add_filter(bus, __sdbd_dbus_signal_filter, NULL, NULL)
1513                         == FALSE)
1514                 return NULL;
1515
1516         D("booting signal initialized\n");
1517         mainloop = g_main_loop_new(NULL, FALSE);
1518         g_main_loop_run(mainloop);
1519
1520         D("dbus loop exited");
1521
1522         return NULL;
1523 }
1524
1525 void register_bootdone_cb() {
1526         D("registerd bootdone callback\n");
1527
1528         sdb_thread_t t;
1529         if (sdb_thread_create(&t, bootdone_cb, NULL)) {
1530                 D("cannot create service thread\n");
1531                 return;
1532         }
1533 }
1534
1535 static int sdbd_set_groups() {
1536     gid_t *group_ids = NULL;
1537     int ngroups = 0;
1538     int i, j = 0;
1539     int group_match = 0;
1540     int added_group_cnt = 0;
1541
1542     getgrouplist(SDK_USER_NAME, g_sdk_group_id, NULL, &ngroups);
1543     D("group list : ngroups = %d\n", ngroups);
1544     group_ids = malloc((ngroups + SDB_DEFAULT_GROUPS_CNT) * sizeof(gid_t));
1545     if (group_ids == NULL) {
1546         D("failed to allocate group_ids(%d)\n", (ngroups + SDB_DEFAULT_GROUPS_CNT) * sizeof(gid_t));
1547         return -1;
1548     }
1549     if (getgrouplist(SDK_USER_NAME, g_sdk_group_id, group_ids, &ngroups) == -1) {
1550         D("failed to getgrouplist(), ngroups = %d\n", ngroups);
1551         free(group_ids);
1552         return -1;
1553     }
1554
1555     for (i = 0; g_default_groups[i].name != NULL; i++) {
1556         for (j = 0; j < ngroups; j++) {
1557             if (group_ids[j] == g_default_groups[i].gid) {
1558                 group_match = 1;
1559                 break;
1560             }
1561         }
1562         if (group_match == 0 && g_default_groups[i].gid != -1) {
1563             group_ids[ngroups + added_group_cnt] = g_default_groups[i].gid;
1564             added_group_cnt ++;
1565         }
1566         group_match = 0;
1567     }
1568
1569     if (setgroups(ngroups+added_group_cnt, group_ids) != 0) {
1570         D("failed to setgroups().\n");
1571         free(group_ids);
1572         return -1;
1573     }
1574
1575     free(group_ids);
1576     return 0;
1577 }
1578
1579 static int sdbd_get_user_pwd(const char* user_name, struct passwd* pwd, char* buf, size_t bufsize) {
1580     struct passwd *result = NULL;
1581     int ret = 0;
1582
1583     ret = getpwnam_r(user_name, pwd, buf, bufsize, &result);
1584     if (result == NULL) {
1585         if (ret == 0) {
1586             D("Not found passwd : username(%s)\n", user_name);
1587         } else {
1588             errno = ret;
1589             D("failed to getpwnam_r\n");
1590         }
1591         return -1;
1592     }
1593
1594     return 0;
1595 }
1596
1597 static int sdbd_get_group(const char* group_name, struct group* grp, char* buf, size_t bufsize) {
1598     struct group *result = NULL;
1599     int ret = 0;
1600
1601     ret = getgrnam_r(group_name, grp, buf, bufsize, &result);
1602     if (result == NULL) {
1603         if (ret == 0) {
1604             D("Not found group : groupname(%s)\n", group_name);
1605         } else {
1606             errno = ret;
1607             D("failed to getgrnam_r\n");
1608         }
1609         return -1;
1610     }
1611
1612     return 0;
1613 }
1614
1615 int set_sdk_user_privileges() {
1616     if (!is_init_sdk_userinfo) {
1617         D("failed to init sdk user information.\n");
1618         return -1;
1619     }
1620
1621     if (sdbd_set_groups() < 0) {
1622         D("set groups failed (errno: %d)\n", errno);
1623         return -1;
1624     }
1625
1626     if (setgid(g_sdk_group_id) != 0) {
1627         D("set group id failed (errno: %d)\n", errno);
1628         return -1;
1629     }
1630
1631     if (setuid(g_sdk_user_id) != 0) {
1632         D("set user id failed (errno: %d)\n", errno);
1633         return -1;
1634     }
1635
1636     if (chdir(g_sdk_home_dir) < 0) {
1637         D("unable to change working directory to %s\n", g_sdk_home_dir);
1638     }
1639
1640     // TODO: use pam later
1641     if (g_sdk_home_dir_env) {
1642         putenv(g_sdk_home_dir_env);
1643     }
1644
1645     return 0;
1646 }
1647
1648 #define SDB_PW_GR_DEFAULT_SIZE  (16*1024)
1649 static long get_passwd_bufsize() {
1650     long bufsize = 0;
1651
1652     bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
1653     if(bufsize < 0) {
1654         bufsize = SDB_PW_GR_DEFAULT_SIZE;
1655     }
1656
1657     return bufsize;
1658 }
1659
1660 static long get_group_bufsize() {
1661     long bufsize = 0;
1662
1663     bufsize = sysconf(_SC_GETGR_R_SIZE_MAX);
1664     if(bufsize < 0) {
1665         bufsize = SDB_PW_GR_DEFAULT_SIZE;
1666     }
1667
1668     return bufsize;
1669 }
1670
1671 static int init_sdb_default_groups() {
1672     struct group grp;
1673     char *buf = NULL;
1674     long bufsize = 0;
1675     int i = 0;
1676
1677     bufsize = get_group_bufsize();
1678     buf = malloc(bufsize);
1679     if (buf == NULL) {
1680         D("failed to allocate gruop buf(%ld)\n", bufsize);
1681         return -1;
1682     }
1683
1684     for (i = 0; g_default_groups[i].name != NULL; i++) {
1685         memset(buf, 0, bufsize);
1686         if (sdbd_get_group(g_default_groups[i].name, &grp, buf, bufsize) == 0) {
1687             g_default_groups[i].gid = grp.gr_gid;
1688         } else {
1689             D("failed get group info.(errno: %d)\n", errno);
1690         }
1691     }
1692
1693     free(buf);
1694     return 0;
1695 }
1696
1697 static void set_static_userinfo() {
1698     g_sdk_user_id = STATIC_SDK_USER_ID;
1699     g_sdk_group_id = STATIC_SDK_GROUP_ID;
1700     g_sdk_home_dir = STATIC_SDK_HOME_DIR;
1701 }
1702
1703 static int init_sdk_userinfo() {
1704     struct passwd pwd;
1705     char *buf = NULL;
1706     long bufsize = 0;
1707
1708     if (is_init_sdk_userinfo) {
1709         return 0;
1710     }
1711
1712     if (init_sdb_default_groups() < 0) {
1713         D("failed to initialize default groups.\n");
1714     }
1715
1716     bufsize = get_passwd_bufsize();
1717     buf = malloc(bufsize);
1718     if (buf == NULL) {
1719         D("failed to allocate passwd buf(%ld)\n", bufsize);
1720         set_static_userinfo();
1721     } else {
1722         if (sdbd_get_user_pwd(SDK_USER_NAME, &pwd, buf, bufsize) < 0) {
1723             D("get user passwd info.(errno: %d)\n", errno);
1724             set_static_userinfo();
1725         } else {
1726             D("username=%s, uid=%d, gid=%d, dir=%s\n", pwd.pw_name, pwd.pw_uid, pwd.pw_gid, pwd.pw_dir);
1727
1728             g_sdk_user_id = pwd.pw_uid;
1729             g_sdk_group_id = pwd.pw_gid;
1730             g_sdk_home_dir = strdup(pwd.pw_dir);
1731         }
1732         free(buf);
1733     }
1734
1735     int env_size = strlen("HOME=") + strlen(g_sdk_home_dir) + 1;
1736     g_sdk_home_dir_env = malloc(env_size);
1737     if(g_sdk_home_dir_env == NULL) {
1738         D("failed to allocate for home dir env string\n");
1739     } else {
1740         snprintf(g_sdk_home_dir_env, env_size, "HOME=%s", g_sdk_home_dir);
1741     }
1742
1743     is_init_sdk_userinfo = 1;
1744     return 0;
1745 }
1746
1747 static void init_sdk_requirements() {
1748     struct stat st;
1749
1750     // set env variable for temporary
1751     // TODO: should use pam instead later!!
1752     if (!getenv("TERM")) {
1753         putenv("TERM=linux");
1754     }
1755
1756     if (!getenv("HOME")) {
1757         putenv("HOME=/root");
1758     }
1759
1760     init_sdk_userinfo();
1761
1762     if (g_sdk_home_dir != NULL && stat(g_sdk_home_dir, &st) == 0) {
1763         if (st.st_uid != g_sdk_user_id || st.st_gid != g_sdk_group_id) {
1764             char cmd[128];
1765             snprintf(cmd, sizeof(cmd), "chown %s:%s %s -R", SDK_USER_NAME, SDK_USER_NAME, g_sdk_home_dir);
1766             if (system(cmd) < 0) {
1767                 D("failed to change ownership to sdk user to %s\n", g_sdk_home_dir);
1768             }
1769         }
1770     }
1771
1772     if (is_emulator()) {
1773         register_bootdone_cb();
1774     }
1775 }
1776 #endif /* !SDB_HOST */
1777
1778 static void init_capabilities(void) {
1779     int ret = -1;
1780     char *value = NULL;
1781
1782     memset(&g_capabilities, 0, sizeof(g_capabilities));
1783
1784     // CPU Architecture of model
1785     ret = system_info_get_platform_string("http://tizen.org/feature/platform.core.cpu.arch", &value);
1786     if (ret != SYSTEM_INFO_ERROR_NONE) {
1787         snprintf(g_capabilities.cpu_arch, sizeof(g_capabilities.cpu_arch),
1788                     "%s", UNKNOWN);
1789         D("fail to get the CPU architecture of model:%d\n", errno);
1790     } else {
1791         snprintf(g_capabilities.cpu_arch, sizeof(g_capabilities.cpu_arch),
1792                     "%s", value);
1793         if (value != NULL) {
1794             free(value);
1795         }
1796     }
1797
1798
1799     // Secure protocol support
1800     if(!request_capability_to_plugin(CAPABILITY_SECURE, g_capabilities.secure_protocol,
1801                             sizeof(g_capabilities.secure_protocol))) {
1802         D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_SECURE);
1803         snprintf(g_capabilities.secure_protocol, sizeof(g_capabilities.secure_protocol),
1804                     "%s", DISABLED);
1805     }
1806
1807
1808     // Interactive shell support
1809     if(!request_capability_to_plugin(CAPABILITY_INTER_SHELL, g_capabilities.intershell_support,
1810                             sizeof(g_capabilities.intershell_support))) {
1811         D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_INTER_SHELL);
1812         snprintf(g_capabilities.intershell_support, sizeof(g_capabilities.intershell_support),
1813                     "%s", DISABLED);
1814     }
1815
1816
1817     // File push/pull support
1818     if(!request_capability_to_plugin(CAPABILITY_FILESYNC, g_capabilities.filesync_support,
1819                             sizeof(g_capabilities.filesync_support))) {
1820         D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_FILESYNC);
1821         snprintf(g_capabilities.filesync_support, sizeof(g_capabilities.filesync_support),
1822                     "%s", DISABLED);
1823     }
1824
1825
1826     // USB protocol support
1827     if(!request_capability_to_plugin(CAPABILITY_USB_PROTOCOL, g_capabilities.usbproto_support,
1828                             sizeof(g_capabilities.usbproto_support))) {
1829         D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_USB_PROTOCOL);
1830         snprintf(g_capabilities.usbproto_support, sizeof(g_capabilities.usbproto_support),
1831                     "%s", DISABLED);
1832     }
1833
1834
1835     // Socket protocol support
1836     if(!request_capability_to_plugin(CAPABILITY_SOCK_PROTOCOL, g_capabilities.sockproto_support,
1837                             sizeof(g_capabilities.sockproto_support))) {
1838         D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_SOCK_PROTOCOL);
1839         snprintf(g_capabilities.sockproto_support, sizeof(g_capabilities.sockproto_support),
1840                     "%s", DISABLED);
1841     }
1842
1843
1844     // Root command support
1845     if(!request_capability_to_plugin(CAPABILITY_ROOT_ONOFF, g_capabilities.rootonoff_support,
1846                             sizeof(g_capabilities.rootonoff_support))) {
1847         D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_ROOT_ONOFF);
1848         snprintf(g_capabilities.rootonoff_support, sizeof(g_capabilities.rootonoff_support),
1849                     "%s", DISABLED);
1850     }
1851
1852
1853     // Encryption support
1854     if(!request_capability_to_plugin(CAPABILITY_ENCRYPTION, g_capabilities.encryption_support,
1855                             sizeof(g_capabilities.encryption_support))) {
1856         D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_ENCRYPTION);
1857         snprintf(g_capabilities.encryption_support, sizeof(g_capabilities.encryption_support),
1858                     "%s", DISABLED);
1859     }
1860
1861
1862     // Zone support
1863     ret = is_container_enabled();
1864     snprintf(g_capabilities.zone_support, sizeof(g_capabilities.zone_support),
1865                 "%s", ret == 1 ? ENABLED : DISABLED);
1866
1867     // Multi-User support
1868     // XXX: There is no clear way to determine whether multi-user support.
1869     // Since TZ_SYS_DEFAULT_USER is set to "owner" for multi-user support,
1870     // guess whether multiuser support through that information.
1871     const char* sys_default_user = tzplatform_getenv(TZ_SYS_DEFAULT_USER);
1872     if (sys_default_user != NULL && !strcmp(sys_default_user, "owner")) {
1873         snprintf(g_capabilities.multiuser_support, sizeof(g_capabilities.multiuser_support),
1874                     "%s", ENABLED);
1875     } else {
1876         snprintf(g_capabilities.multiuser_support, sizeof(g_capabilities.multiuser_support),
1877                     "%s", DISABLED);
1878     }
1879
1880     // Window size synchronization support
1881     snprintf(g_capabilities.syncwinsz_support, sizeof(g_capabilities.syncwinsz_support),
1882                 "%s", ENABLED);
1883
1884     // SDK Tool path
1885     if (SDK_TOOL_PATH == NULL) {
1886         D("fail to get SDK tool path.\n");
1887         snprintf(g_capabilities.sdk_toolpath, sizeof(g_capabilities.sdk_toolpath),
1888                     "%s", UNKNOWN);
1889     } else {
1890         snprintf(g_capabilities.sdk_toolpath, sizeof(g_capabilities.sdk_toolpath),
1891                     "%s", SDK_TOOL_PATH);
1892     }
1893
1894     // Profile name
1895     ret = system_info_get_platform_string("http://tizen.org/feature/profile", &value);
1896     if (ret != SYSTEM_INFO_ERROR_NONE) {
1897         snprintf(g_capabilities.profile_name, sizeof(g_capabilities.profile_name),
1898                     "%s", UNKNOWN);
1899         D("fail to get profile name:%d\n", errno);
1900     } else {
1901         snprintf(g_capabilities.profile_name, sizeof(g_capabilities.profile_name),
1902                     "%s", value);
1903         if (value != NULL) {
1904             free(value);
1905         }
1906     }
1907
1908
1909     // Vendor name
1910     ret = system_info_get_platform_string("http://tizen.org/system/manufacturer", &value);
1911     if (ret != SYSTEM_INFO_ERROR_NONE) {
1912         snprintf(g_capabilities.vendor_name, sizeof(g_capabilities.vendor_name),
1913                     "%s", UNKNOWN);
1914         D("fail to get the Vendor name:%d\n", errno);
1915     } else {
1916         snprintf(g_capabilities.vendor_name, sizeof(g_capabilities.vendor_name),
1917                     "%s", value);
1918         if (value != NULL) {
1919             free(value);
1920         }
1921     }
1922
1923
1924     // Target name of the launch possible
1925     if(!request_capability_to_plugin(CAPABILITY_CAN_LAUNCH, g_capabilities.can_launch,
1926                             sizeof(g_capabilities.can_launch))) {
1927         D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_CAN_LAUNCH);
1928         snprintf(g_capabilities.can_launch, sizeof(g_capabilities.can_launch),
1929                     "%s", UNKNOWN);
1930     }
1931
1932
1933     // Platform version
1934     ret = system_info_get_platform_string("http://tizen.org/feature/platform.version", &value);
1935     if (ret != SYSTEM_INFO_ERROR_NONE) {
1936         snprintf(g_capabilities.platform_version, sizeof(g_capabilities.platform_version),
1937                     "%s", UNKNOWN);
1938         D("fail to get platform version:%d\n", errno);
1939     } else {
1940         snprintf(g_capabilities.platform_version, sizeof(g_capabilities.platform_version),
1941                     "%s", value);
1942         if (value != NULL) {
1943             free(value);
1944         }
1945     }
1946
1947
1948     // Product version
1949     if(!request_capability_to_plugin(CAPABILITY_PRODUCT_VER, g_capabilities.product_version,
1950                             sizeof(g_capabilities.product_version))) {
1951         D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_PRODUCT_VER);
1952         snprintf(g_capabilities.product_version, sizeof(g_capabilities.product_version),
1953                     "%s", UNKNOWN);
1954     }
1955
1956
1957     // Sdbd version
1958     snprintf(g_capabilities.sdbd_version, sizeof(g_capabilities.sdbd_version),
1959                 "%d.%d.%d", SDB_VERSION_MAJOR, SDB_VERSION_MINOR, SDB_VERSION_PATCH);
1960
1961
1962     // Sdbd plugin version
1963     if(!request_capability_to_plugin(CAPABILITY_PLUGIN_VER, g_capabilities.sdbd_plugin_version,
1964                             sizeof(g_capabilities.sdbd_plugin_version))) {
1965         D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_PLUGIN_VER);
1966         snprintf(g_capabilities.sdbd_plugin_version, sizeof(g_capabilities.sdbd_plugin_version),
1967                     "%s", UNKNOWN);
1968     }
1969
1970
1971     // sdbd log enable
1972     if(!request_capability_to_plugin(CAPABILITY_LOG_ENABLE, g_capabilities.log_enable,
1973                                sizeof(g_capabilities.log_enable))) {
1974            D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_LOG_ENABLE);
1975            snprintf(g_capabilities.log_enable, sizeof(g_capabilities.log_enable),
1976                        "%s", DISABLED);
1977     }
1978
1979     // sdbd log path
1980     if(!request_capability_to_plugin(CAPABILITY_LOG_PATH, g_capabilities.log_path,
1981                                sizeof(g_capabilities.log_path))) {
1982            D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_LOG_PATH);
1983            snprintf(g_capabilities.log_path, sizeof(g_capabilities.log_path),
1984                        "%s", UNKNOWN);
1985     }
1986
1987     // Application command support
1988     if(!request_capability_to_plugin(CAPABILITY_APPCMD, g_capabilities.appcmd_support,
1989                                sizeof(g_capabilities.appcmd_support))) {
1990            D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_APPCMD);
1991            snprintf(g_capabilities.appcmd_support, sizeof(g_capabilities.appcmd_support),
1992                        "%s", UNKNOWN);
1993     }
1994
1995     // Capability version
1996     snprintf(g_capabilities.sdbd_cap_version, sizeof(g_capabilities.sdbd_cap_version),
1997                 "%d.%d", SDBD_CAP_VERSION_MAJOR, SDBD_CAP_VERSION_MINOR);
1998 }
1999
2000 static int is_support_usbproto()
2001 {
2002     return (!strncmp(g_capabilities.usbproto_support, PLUGIN_RET_ENABLED, strlen(PLUGIN_RET_ENABLED)));
2003 }
2004
2005 static int is_support_sockproto()
2006 {
2007     return (!strncmp(g_capabilities.sockproto_support, PLUGIN_RET_ENABLED, strlen(PLUGIN_RET_ENABLED)));
2008 }
2009
2010 #define EMULATOR_MODEL_NAME     "Emulator"
2011 static void check_emulator_or_device()
2012 {
2013     char model_name[256]={0,};
2014     int ret = -1;
2015
2016     // Get the model name from model_config.xml
2017     ret = get_device_name(model_name, sizeof model_name);
2018     if (ret == 0) {
2019         if(!strncmp(model_name, EMULATOR_MODEL_NAME, sizeof(EMULATOR_MODEL_NAME))){
2020             g_is_emulator = 1;
2021             D("This target type is Emulator\n");
2022         } else {
2023             g_is_emulator = 0;
2024             D("This target type is Device\n");
2025         }
2026     } else {
2027         g_is_emulator = -1;
2028         D("failed to get the model name.\n");
2029     }
2030 }
2031
2032 static void fork_prepare_handler(void)
2033 {
2034     sdb_mutex_lock(&D_lock);
2035 }
2036
2037 static void fork_parent_handler(void)
2038 {
2039     sdb_mutex_unlock(&D_lock);
2040 }
2041
2042 static void fork_child_handler(void)
2043 {
2044     sdb_mutex_unlock(&D_lock);
2045 }
2046
2047 int sdb_main(int is_daemon, int server_port)
2048 {
2049 #if !SDB_HOST
2050     check_emulator_or_device();
2051
2052     load_sdbd_plugin();
2053
2054     init_capabilities();
2055
2056     sdb_trace_init();
2057     start_device_log();
2058
2059     init_drop_privileges();
2060     init_sdk_requirements();
2061     if (!request_validity_to_plugin(PLUGIN_SYNC_CMD_VERIFY_LAUNCH, NULL)) {
2062         D("sdbd should be launched in develop mode.\n");
2063         return -1;
2064     }
2065
2066     umask(000);
2067
2068     pthread_atfork(fork_prepare_handler, fork_parent_handler, fork_child_handler);
2069 #endif
2070
2071     atexit(sdb_cleanup);
2072 #ifdef HAVE_WIN32_PROC
2073     SetConsoleCtrlHandler( ctrlc_handler, TRUE );
2074 #elif defined(HAVE_FORKEXEC)
2075     // No SIGCHLD. Let the service subproc handle its children.
2076     signal(SIGPIPE, SIG_IGN);
2077 #endif
2078
2079     init_transport_registration();
2080
2081
2082 #if SDB_HOST
2083     HOST = 1;
2084     usb_init();
2085     local_init(DEFAULT_SDB_LOCAL_TRANSPORT_PORT);
2086
2087     char local_name[30];
2088     build_local_name(local_name, sizeof(local_name), server_port);
2089     if(install_listener(local_name, "*smartsocket*", NULL)) {
2090         exit(1);
2091     }
2092 #else
2093     /* don't listen on a port (default 5037) if running in secure mode */
2094     /* don't run as root if we are running in secure mode */
2095
2096     if (should_drop_privileges()) {
2097 # if 0
2098         struct __user_cap_header_struct header;
2099         struct __user_cap_data_struct cap;
2100
2101         if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
2102             exit(1);
2103         }
2104         /* add extra groups:
2105         ** SID_TTY to access /dev/ptmx
2106         */
2107         gid_t groups[] = { SID_TTY, SID_APP_LOGGING, SID_SYS_LOGGING };
2108         if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
2109             exit(1);
2110         }
2111         /* then switch user and group to "developer" */
2112         if (setgid(GID_DEVELOPER) != 0) {
2113             fprintf(stderr, "set group id failed errno: %d\n", errno);
2114             exit(1);
2115         }
2116         if (setuid(SID_DEVELOPER) != 0) {
2117             fprintf(stderr, "set user id failed errno: %d\n", errno);
2118             exit(1);
2119         }
2120
2121         /* set CAP_SYS_BOOT capability, so "sdb reboot" will succeed */
2122         header.version = _LINUX_CAPABILITY_VERSION;
2123         header.pid = 0;
2124         cap.effective = cap.permitted = (1 << CAP_SYS_BOOT);
2125         cap.inheritable = 0;
2126         capset(&header, &cap);
2127 #endif
2128         D("Local port disabled\n");
2129     } else {
2130         char local_name[30];
2131         build_local_name(local_name, sizeof(local_name), server_port);
2132         if(install_listener(local_name, "*smartsocket*", NULL)) {
2133             exit(1);
2134         }
2135     }
2136
2137     /* choose the usb gadget backend */
2138     if (access(USB_NODE_FILE, F_OK) == 0) {
2139         /* legacy kernel-based sdb gadget */
2140         usb_init =    &linux_usb_init;
2141         usb_cleanup = &linux_usb_cleanup;
2142         usb_write =   &linux_usb_write;
2143         usb_read =    &linux_usb_read;
2144         usb_close =   &linux_usb_close;
2145         usb_kick =    &linux_usb_kick;
2146     } else {
2147         /* functionfs based gadget */
2148         usb_init =    &ffs_usb_init;
2149         usb_cleanup = &ffs_usb_cleanup;
2150         usb_write =   &ffs_usb_write;
2151         usb_read =    &ffs_usb_read;
2152         usb_close =   &ffs_usb_close;
2153         usb_kick =    &ffs_usb_kick;
2154     }
2155
2156     if (is_support_usbproto()) {
2157         // listen on USB
2158         usb_init();
2159     }
2160     if (is_support_sockproto()) {
2161         /* by default don't listen on local transport but
2162          * listen if suitable command line argument has been provided */
2163         if (sdbd_commandline_args.sdbd_port >= 0) {
2164             local_init(sdbd_commandline_args.sdbd_port);
2165         } else {
2166             local_init(DEFAULT_SDB_LOCAL_TRANSPORT_PORT);
2167         }
2168     }
2169
2170 #if 0 /* tizen specific */
2171     D("sdb_main(): pre init_jdwp()\n");
2172     init_jdwp();
2173     D("sdb_main(): post init_jdwp()\n");
2174 #endif
2175 #endif
2176
2177     if (is_daemon)
2178     {
2179         // inform our parent that we are up and running.
2180 #ifdef HAVE_WIN32_PROC
2181         DWORD  count;
2182         WriteFile( GetStdHandle( STD_OUTPUT_HANDLE ), "OK\n", 3, &count, NULL );
2183 #elif defined(HAVE_FORKEXEC)
2184         fprintf(stderr, "OK\n");
2185 #endif
2186         start_logging();
2187     }
2188
2189     D("Event loop starting\n");
2190
2191     fdevent_loop();
2192
2193     if (is_support_usbproto()) {
2194         usb_cleanup();
2195     }
2196
2197     return 0;
2198 }
2199
2200 #if SDB_HOST
2201 void connect_device(char* host, char* buffer, int buffer_size)
2202 {
2203     int port, fd;
2204     char* portstr = strchr(host, ':');
2205     char hostbuf[100];
2206     char serial[100];
2207
2208     s_strncpy(hostbuf, host, sizeof(hostbuf) - 1);
2209     if (portstr) {
2210         if (portstr - host >= sizeof(hostbuf)) {
2211             snprintf(buffer, buffer_size, "bad host name %s", host);
2212             return;
2213         }
2214         // zero terminate the host at the point we found the colon
2215         hostbuf[portstr - host] = 0;
2216         if (sscanf(portstr + 1, "%d", &port) == 0) {
2217             snprintf(buffer, buffer_size, "bad port number %s", portstr);
2218             return;
2219         }
2220     } else {
2221         port = DEFAULT_SDB_LOCAL_TRANSPORT_PORT;
2222     }
2223
2224     snprintf(serial, sizeof(serial), "%s:%d", hostbuf, port);
2225     if (find_transport(serial)) {
2226         snprintf(buffer, buffer_size, "already connected to %s", serial);
2227         return;
2228     }
2229
2230     fd = socket_network_client(hostbuf, port, SOCK_STREAM);
2231     if (fd < 0) {
2232         snprintf(buffer, buffer_size, "unable to connect to %s", host);
2233         return;
2234     }
2235
2236     D("client: connected on remote on fd %d\n", fd);
2237     close_on_exec(fd);
2238     disable_tcp_nagle(fd);
2239     register_socket_transport(fd, serial, port, 0, NULL);
2240     snprintf(buffer, buffer_size, "connected to %s", serial);
2241 }
2242
2243 void connect_emulator(char* port_spec, char* buffer, int buffer_size)
2244 {
2245     char* port_separator = strchr(port_spec, ',');
2246     if (!port_separator) {
2247         snprintf(buffer, buffer_size,
2248                 "unable to parse '%s' as <console port>,<sdb port>",
2249                 port_spec);
2250         return;
2251     }
2252
2253     // Zero-terminate console port and make port_separator point to 2nd port.
2254     *port_separator++ = 0;
2255     int console_port = strtol(port_spec, NULL, 0);
2256     int sdb_port = strtol(port_separator, NULL, 0);
2257     if (!(console_port > 0 && sdb_port > 0)) {
2258         *(port_separator - 1) = ',';
2259         snprintf(buffer, buffer_size,
2260                 "Invalid port numbers: Expected positive numbers, got '%s'",
2261                 port_spec);
2262         return;
2263     }
2264
2265     /* Check if the emulator is already known.
2266      * Note: There's a small but harmless race condition here: An emulator not
2267      * present just yet could be registered by another invocation right
2268      * after doing this check here. However, local_connect protects
2269      * against double-registration too. From here, a better error message
2270      * can be produced. In the case of the race condition, the very specific
2271      * error message won't be shown, but the data doesn't get corrupted. */
2272     atransport* known_emulator = find_emulator_transport_by_sdb_port(sdb_port);
2273     if (known_emulator != NULL) {
2274         snprintf(buffer, buffer_size,
2275                 "Emulator on port %d already registered.", sdb_port);
2276         return;
2277     }
2278
2279     /* Check if more emulators can be registered. Similar unproblematic
2280      * race condition as above. */
2281     int candidate_slot = get_available_local_transport_index();
2282     if (candidate_slot < 0) {
2283         snprintf(buffer, buffer_size, "Cannot accept more emulators.");
2284         return;
2285     }
2286
2287     /* Preconditions met, try to connect to the emulator. */
2288     if (!local_connect_arbitrary_ports(console_port, sdb_port, NULL)) {
2289         snprintf(buffer, buffer_size,
2290                 "Connected to emulator on ports %d,%d", console_port, sdb_port);
2291     } else {
2292         snprintf(buffer, buffer_size,
2293                 "Could not connect to emulator on ports %d,%d",
2294                 console_port, sdb_port);
2295     }
2296 }
2297 #endif
2298
2299 int copy_packet(apacket* dest, apacket* src) {
2300
2301     if(dest == NULL) {
2302         D("dest packet is NULL\n");
2303         return -1;
2304     }
2305
2306     if(src == NULL) {
2307         D("src packet is NULL\n");
2308         return -1;
2309     }
2310
2311     dest->next = src->next;
2312     dest->ptr = src->ptr;
2313     dest->len = src->len;
2314
2315     int data_length = src->msg.data_length;
2316     if(data_length > MAX_PAYLOAD) {
2317         data_length = MAX_PAYLOAD;
2318     }
2319     memcpy(&(dest->msg), &(src->msg), sizeof(amessage) + data_length);
2320
2321     return 0;
2322 }
2323
2324 int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s)
2325 {
2326     atransport *transport = NULL;
2327     char buf[4096];
2328
2329     if(!strcmp(service, "kill")) {
2330         fprintf(stderr,"sdb server killed by remote request\n");
2331         fflush(stdout);
2332         sdb_write(reply_fd, "OKAY", 4);
2333         if (is_support_usbproto()) {
2334             usb_cleanup();
2335         }
2336         exit(0);
2337     }
2338
2339 #if SDB_HOST
2340     // "transport:" is used for switching transport with a specified serial number
2341     // "transport-usb:" is used for switching transport to the only USB transport
2342     // "transport-local:" is used for switching transport to the only local transport
2343     // "transport-any:" is used for switching transport to the only transport
2344     if (!strncmp(service, "transport", strlen("transport"))) {
2345         char* error_string = "unknown failure";
2346         transport_type type = kTransportAny;
2347
2348         if (!strncmp(service, "transport-usb", strlen("transport-usb"))) {
2349             type = kTransportUsb;
2350         } else if (!strncmp(service, "transport-local", strlen("transport-local"))) {
2351             type = kTransportLocal;
2352         } else if (!strncmp(service, "transport-any", strlen("transport-any"))) {
2353             type = kTransportAny;
2354         } else if (!strncmp(service, "transport:", strlen("transport:"))) {
2355             service += strlen("transport:");
2356             serial = service;
2357         }
2358
2359         transport = acquire_one_transport(CS_ANY, type, serial, &error_string);
2360
2361         if (transport) {
2362             s->transport = transport;
2363             sdb_write(reply_fd, "OKAY", 4);
2364         } else {
2365             sendfailmsg(reply_fd, error_string);
2366         }
2367         return 1;
2368     }
2369
2370     // return a list of all connected devices
2371     if (!strcmp(service, "devices")) {
2372         char buffer[4096];
2373         memset(buf, 0, sizeof(buf));
2374         memset(buffer, 0, sizeof(buffer));
2375         D("Getting device list \n");
2376         list_transports(buffer, sizeof(buffer));
2377         snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer),buffer);
2378         D("Wrote device list \n");
2379         writex(reply_fd, buf, strlen(buf));
2380         return 0;
2381     }
2382
2383     // add a new TCP transport, device or emulator
2384     if (!strncmp(service, "connect:", 8)) {
2385         char buffer[4096];
2386         char* host = service + 8;
2387         if (!strncmp(host, "emu:", 4)) {
2388             connect_emulator(host + 4, buffer, sizeof(buffer));
2389         } else {
2390             connect_device(host, buffer, sizeof(buffer));
2391         }
2392         // Send response for emulator and device
2393         snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
2394         writex(reply_fd, buf, strlen(buf));
2395         return 0;
2396     }
2397
2398     // remove TCP transport
2399     if (!strncmp(service, "disconnect:", 11)) {
2400         char buffer[4096];
2401         memset(buffer, 0, sizeof(buffer));
2402         char* serial = service + 11;
2403         if (serial[0] == 0) {
2404             // disconnect from all TCP devices
2405             unregister_all_tcp_transports();
2406         } else {
2407             char hostbuf[100];
2408             // assume port 26101 if no port is specified
2409             if (!strchr(serial, ':')) {
2410                 snprintf(hostbuf, sizeof(hostbuf) - 1, "%s:26101", serial);
2411                 serial = hostbuf;
2412             }
2413             atransport *t = find_transport(serial);
2414
2415             if (t) {
2416                 unregister_transport(t);
2417             } else {
2418                 snprintf(buffer, sizeof(buffer), "No such device %s", serial);
2419             }
2420         }
2421
2422         snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
2423         writex(reply_fd, buf, strlen(buf));
2424         return 0;
2425     }
2426
2427     // returns our value for SDB_SERVER_VERSION
2428     if (!strcmp(service, "version")) {
2429         char version[12];
2430         snprintf(version, sizeof version, "%04x", SDB_SERVER_VERSION);
2431         snprintf(buf, sizeof buf, "OKAY%04x%s", (unsigned)strlen(version), version);
2432         writex(reply_fd, buf, strlen(buf));
2433         return 0;
2434     }
2435
2436     if(!strncmp(service,"get-serialno",strlen("get-serialno"))) {
2437         char *out = "unknown";
2438          transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
2439        if (transport && transport->serial) {
2440             out = transport->serial;
2441         }
2442         snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(out),out);
2443         writex(reply_fd, buf, strlen(buf));
2444         return 0;
2445     }
2446     // indicates a new emulator instance has started
2447        if (!strncmp(service,"emulator:",9)) { /* tizen specific */
2448            char *tmp = strtok(service+9, DEVICEMAP_SEPARATOR);
2449            int  port = 0;
2450
2451            if (tmp == NULL) {
2452                port = atoi(service+9);
2453            } else {
2454                port = atoi(tmp);
2455                tmp = strtok(NULL, DEVICEMAP_SEPARATOR);
2456                if (tmp != NULL) {
2457                    local_connect(port, tmp);
2458                }
2459            }
2460            local_connect(port, NULL);
2461         return 0;
2462     }
2463 #endif // SDB_HOST
2464
2465     if(!strncmp(service,"forward:",8) || !strncmp(service,"killforward:",12)) {
2466         char *local, *remote, *err;
2467         int r;
2468         atransport *transport;
2469
2470         int createForward = strncmp(service,"kill",4);
2471
2472         local = service + (createForward ? 8 : 12);
2473         remote = strchr(local,';');
2474         if(remote == 0) {
2475             sendfailmsg(reply_fd, "malformed forward spec");
2476             return 0;
2477         }
2478
2479         *remote++ = 0;
2480         if((local[0] == 0) || (remote[0] == 0) || (remote[0] == '*')){
2481             sendfailmsg(reply_fd, "malformed forward spec");
2482             return 0;
2483         }
2484
2485         transport = acquire_one_transport(CS_ANY, ttype, serial, &err);
2486         if (!transport) {
2487             sendfailmsg(reply_fd, err);
2488             return 0;
2489         }
2490
2491         if (createForward) {
2492             r = install_listener(local, remote, transport);
2493         } else {
2494             r = remove_listener(local, remote, transport);
2495         }
2496         if(r == 0) {
2497                 /* 1st OKAY is connect, 2nd OKAY is status */
2498             writex(reply_fd, "OKAYOKAY", 8);
2499             return 0;
2500         }
2501
2502         if (createForward) {
2503             sendfailmsg(reply_fd, (r == -1) ? "cannot rebind smartsocket" : "cannot bind socket");
2504         } else {
2505             sendfailmsg(reply_fd, "cannot remove listener");
2506         }
2507         return 0;
2508     }
2509
2510     if(!strncmp(service,"get-state",strlen("get-state"))) {
2511         transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
2512         char *state = connection_state_name(transport);
2513         snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(state),state);
2514         writex(reply_fd, buf, strlen(buf));
2515         return 0;
2516     }
2517     return -1;
2518 }
2519
2520 #if !SDB_HOST
2521 int recovery_mode = 0;
2522 #endif
2523
2524 int main(int argc, char **argv)
2525 {
2526 #if SDB_HOST
2527     sdb_sysdeps_init();
2528     sdb_trace_init();
2529     return sdb_commandline(argc - 1, argv + 1);
2530 #else
2531     /* If sdbd runs inside the emulator this will enable sdb tracing via
2532      * sdb-debug qemud service in the emulator. */
2533 #if 0 /* tizen specific */
2534     sdb_qemu_trace_init();
2535     if((argc > 1) && (!strcmp(argv[1],"recovery"))) {
2536         sdb_device_banner = "recovery";
2537         recovery_mode = 1;
2538     }
2539 #endif
2540
2541     apply_sdbd_commandline_defaults(&sdbd_commandline_args);
2542     int parse_ret = parse_sdbd_commandline(&sdbd_commandline_args, argc, argv);
2543
2544     // TODO: Add detailed error messages
2545     // TODO: Add individual messages for help and usage
2546     if(parse_ret != SDBD_COMMANDLINE_SUCCESS) {
2547         if (parse_ret == SDBD_COMMANDLINE_HELP
2548                 || parse_ret == SDBD_COMMANDLINE_USAGE) {
2549             // User requested help or usage
2550             print_sdbd_usage_message(stdout);
2551             return EXIT_SUCCESS;
2552         }
2553
2554         // Print usage message because of invalid options
2555         print_sdbd_usage_message(stderr);
2556         return EXIT_FAILURE;
2557     }
2558
2559 #if !SDB_HOST
2560     if (daemonize() < 0)
2561         fatal("daemonize() failed: errno:%d", errno);
2562 #endif
2563
2564     D("Handling main()\n");
2565
2566     //sdbd will never die on emulator!
2567     signal(SIGTERM, handle_sig_term); /* tizen specific */
2568     return sdb_main(0, DEFAULT_SDB_PORT);
2569 #endif
2570 }
2571