cap: Add new "pkgcmd_debugmode" capability for pkgcmd debug mode
[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 static void update_version(atransport *t, int version, size_t payload)
798 {
799 #ifdef SUPPORT_ENCRYPT
800     size_t max_payload = MAX_PAYLOAD - 100;
801 #else
802     size_t max_payload = MAX_PAYLOAD;
803 #endif
804     t->protocol_version = min(version, A_VERSION);
805     t->max_payload = min(payload, max_payload);
806     D("update transport version. version=%x, max_payload=%d\n", t->protocol_version, t->max_payload);
807 }
808
809 void handle_packet(apacket *p, atransport *t)
810 {
811     // Verify pointer p
812     int result = access((const char *) p, F_OK);
813     if ((result == -1) && (errno == EFAULT)) {
814         fatal("Invalid apacket = [0x%p]", p);
815     }
816
817     asocket *s;
818
819     D("handle_packet() %c%c%c%c\n", ((char*) (&(p->msg.command)))[0],
820                 ((char*) (&(p->msg.command)))[1],
821                 ((char*) (&(p->msg.command)))[2],
822                 ((char*) (&(p->msg.command)))[3]);
823
824     print_packet("recv", p);
825
826     switch(p->msg.command){
827     case A_SYNC:
828         if(p->msg.arg0){
829             send_packet(p, t);
830             if(HOST) send_connect(t);
831         } else {
832             t->connection_state = CS_OFFLINE;
833             handle_offline(t);
834             send_packet(p, t);
835         }
836         return;
837
838     case A_CNXN: /* CONNECT(version, maxdata, "system-id-string") */
839             /* XXX verify version, etc */
840         if(t->connection_state != CS_OFFLINE) {
841             t->connection_state = CS_OFFLINE;
842             handle_offline(t);
843         }
844         update_version(t, p->msg.arg0, p->msg.arg1);
845         parse_banner((char*) p->data, t);
846         handle_online();
847         if(!HOST) send_connect(t);
848         break;
849
850     case A_OPEN: /* OPEN(local-id, 0, "destination") */
851         if (request_lock_state_to_plugin(LOCKTYPE_PASSWORD) == 1 && t->connection_state == CS_PWLOCK) {
852             // in case of already locked before get A_CNXN
853             D("open failed due to password locked before get A_CNXN:%d\n", t->connection_state);
854             send_close(0, p->msg.arg0, t);
855         } else {
856             if(t->connection_state != CS_OFFLINE) {
857                 char *name = (char*) p->data;
858                 name[p->msg.data_length > 0 ? p->msg.data_length - 1 : 0] = 0;
859                 s = create_local_service_socket(name);
860                 if(s == 0) {
861                     send_close(0, p->msg.arg0, t);
862                 } else {
863                     s->peer = create_remote_socket(p->msg.arg0, t);
864                     s->peer->peer = s;
865                     send_ready(s->id, s->peer->id, t);
866                     s->ready(s);
867                 }
868             }
869         }
870         break;
871
872     case A_OKAY: /* READY(local-id, remote-id, "") */
873         if(t->connection_state != CS_OFFLINE) {
874             if((s = find_local_socket(p->msg.arg1))) {
875                 if(s->peer == 0) {
876                     s->peer = create_remote_socket(p->msg.arg0, t);
877                     s->peer->peer = s;
878                 }
879                 s->ready(s);
880             }
881         }
882         break;
883
884     case A_CLSE: /* CLOSE(local-id, remote-id, "") */
885         if(t->connection_state != CS_OFFLINE) {
886             if((s = find_local_socket(p->msg.arg1))) {
887                 s->close(s);
888             }
889         }
890         break;
891
892     case A_WRTE:
893         if(t->connection_state != CS_OFFLINE) {
894             if((s = find_local_socket(p->msg.arg1))) {
895                 unsigned rid = p->msg.arg0;
896                 p->len = p->msg.data_length;
897
898                 if(s->enqueue(s, p) == 0) {
899                     D("Enqueue the socket\n");
900                     send_ready(s->id, rid, t);
901                 }
902                 return;
903             }
904         }
905         break;
906 #ifdef SUPPORT_ENCRYPT
907         case A_ENCR: // 암호화 메시지인 경우
908                 if(t->connection_state != CS_OFFLINE) {
909                         handle_encr_packet(p, t);
910                 }
911                 break;
912 #endif
913
914     default:
915         printf("handle_packet: what is %08x?!\n", p->msg.command);
916     }
917
918     put_apacket(p);
919 }
920
921 alistener listener_list = {
922     .next = &listener_list,
923     .prev = &listener_list,
924 };
925
926 static void ss_listener_event_func(int _fd, unsigned ev, void *_l)
927 {
928     asocket *s;
929
930     if(ev & FDE_READ) {
931         struct sockaddr addr;
932         socklen_t alen;
933         int fd;
934
935         alen = sizeof(addr);
936         fd = sdb_socket_accept(_fd, &addr, &alen);
937         if(fd < 0) return;
938
939         sdb_socket_setbufsize(fd, CHUNK_SIZE);
940
941         s = create_local_socket(fd);
942         if(s) {
943             connect_to_smartsocket(s);
944             return;
945         }
946
947         sdb_close(fd);
948     }
949 }
950
951 static void listener_event_func(int _fd, unsigned ev, void *_l)
952 {
953     alistener *l = _l;
954     asocket *s;
955
956     if(ev & FDE_READ) {
957         struct sockaddr addr;
958         socklen_t alen;
959         int fd;
960
961         alen = sizeof(addr);
962         fd = sdb_socket_accept(_fd, &addr, &alen);
963         if(fd < 0) return;
964
965         s = create_local_socket(fd);
966         if(s) {
967             s->transport = l->transport;
968             connect_to_remote(s, l->connect_to);
969             return;
970         }
971
972         sdb_close(fd);
973     }
974 }
975
976 static void  free_listener(alistener*  l)
977 {
978     if (l->next) {
979         l->next->prev = l->prev;
980         l->prev->next = l->next;
981         l->next = l->prev = l;
982     }
983
984     // closes the corresponding fd
985     fdevent_remove(&l->fde);
986
987     if (l->local_name)
988         free((char*)l->local_name);
989
990     if (l->connect_to)
991         free((char*)l->connect_to);
992
993     if (l->transport) {
994         remove_transport_disconnect(l->transport, &l->disconnect);
995     }
996     free(l);
997 }
998
999 static void listener_disconnect(void*  _l, atransport*  t)
1000 {
1001     alistener*  l = _l;
1002
1003     free_listener(l);
1004 }
1005
1006 int local_name_to_fd(const char *name)
1007 {
1008     int port;
1009
1010     if(!strncmp("tcp:", name, 4)){
1011         int  ret;
1012         port = atoi(name + 4);
1013         ret = socket_loopback_server(port, SOCK_STREAM);
1014         return ret;
1015     }
1016 #ifndef HAVE_WIN32_IPC  /* no Unix-domain sockets on Win32 */
1017     // It's non-sensical to support the "reserved" space on the sdb host side
1018     if(!strncmp(name, "local:", 6)) {
1019         return socket_local_server(name + 6,
1020                 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
1021     } else if(!strncmp(name, "localabstract:", 14)) {
1022         return socket_local_server(name + 14,
1023                 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
1024     } else if(!strncmp(name, "localfilesystem:", 16)) {
1025         return socket_local_server(name + 16,
1026                 ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
1027     }
1028
1029 #endif
1030     printf("unknown local portname '%s'\n", name);
1031     return -1;
1032 }
1033
1034 static int remove_listener(const char *local_name, const char *connect_to, atransport* transport)
1035 {
1036     alistener *l;
1037
1038     for (l = listener_list.next; l != &listener_list; l = l->next) {
1039         if (!strcmp(local_name, l->local_name) &&
1040             !strcmp(connect_to, l->connect_to) &&
1041             l->transport && l->transport == transport) {
1042
1043             listener_disconnect(l, transport);
1044             return 0;
1045         }
1046     }
1047
1048     return -1;
1049 }
1050
1051 static int install_listener(const char *local_name, const char *connect_to, atransport* transport)
1052 {
1053     alistener *l;
1054
1055     //printf("install_listener('%s','%s')\n", local_name, connect_to);
1056
1057     for(l = listener_list.next; l != &listener_list; l = l->next){
1058         if(strcmp(local_name, l->local_name) == 0) {
1059             char *cto;
1060
1061                 /* can't repurpose a smartsocket */
1062             if(l->connect_to[0] == '*') {
1063                 return -1;
1064             }
1065
1066             cto = strdup(connect_to);
1067             if(cto == 0) {
1068                 return -1;
1069             }
1070
1071             //printf("rebinding '%s' to '%s'\n", local_name, connect_to);
1072             free((void*) l->connect_to);
1073             l->connect_to = cto;
1074             if (l->transport != transport) {
1075                 remove_transport_disconnect(l->transport, &l->disconnect);
1076                 l->transport = transport;
1077                 add_transport_disconnect(l->transport, &l->disconnect);
1078             }
1079             return 0;
1080         }
1081     }
1082
1083     if((l = calloc(1, sizeof(alistener))) == 0) goto nomem;
1084     if((l->local_name = strdup(local_name)) == 0) goto nomem;
1085     if((l->connect_to = strdup(connect_to)) == 0) goto nomem;
1086
1087
1088     l->fd = local_name_to_fd(local_name);
1089     if(l->fd < 0) {
1090         free((void*) l->local_name);
1091         free((void*) l->connect_to);
1092         free(l);
1093         printf("cannot bind '%s'\n", local_name);
1094         return -2;
1095     }
1096
1097     if (close_on_exec(l->fd) < 0) {
1098         D("fail to close fd exec:%d\n",l->fd);
1099     }
1100     if(!strcmp(l->connect_to, "*smartsocket*")) {
1101         fdevent_install(&l->fde, l->fd, ss_listener_event_func, l);
1102     } else {
1103         fdevent_install(&l->fde, l->fd, listener_event_func, l);
1104     }
1105     fdevent_set(&l->fde, FDE_READ);
1106
1107     l->next = &listener_list;
1108     l->prev = listener_list.prev;
1109     l->next->prev = l;
1110     l->prev->next = l;
1111     l->transport = transport;
1112
1113     if (transport) {
1114         l->disconnect.opaque = l;
1115         l->disconnect.func   = listener_disconnect;
1116         add_transport_disconnect(transport, &l->disconnect);
1117     }
1118     return 0;
1119
1120 nomem:
1121     fatal("cannot allocate listener");
1122     return 0;
1123 }
1124
1125 #ifdef HAVE_WIN32_PROC
1126 static BOOL WINAPI ctrlc_handler(DWORD type)
1127 {
1128     exit(STATUS_CONTROL_C_EXIT);
1129     return TRUE;
1130 }
1131 #endif
1132
1133 static void sdb_cleanup(void)
1134 {
1135     clear_sdbd_commandline_args(&sdbd_commandline_args);
1136
1137     if (is_support_usbproto()) {
1138         usb_cleanup();
1139     }
1140 //    if(required_pid > 0) {
1141 //        kill(required_pid, SIGKILL);
1142 //    }
1143
1144     unload_sdbd_plugin();
1145 }
1146
1147 void start_logging(void)
1148 {
1149 #ifdef HAVE_WIN32_PROC
1150     char    temp[ MAX_PATH ];
1151     FILE*   fnul;
1152     FILE*   flog;
1153
1154     GetTempPath( sizeof(temp) - 8, temp );
1155     strcat( temp, "sdb.log" );
1156
1157     /* Win32 specific redirections */
1158     fnul = fopen( "NUL", "rt" );
1159     if (fnul != NULL)
1160         stdin[0] = fnul[0];
1161
1162     flog = fopen( temp, "at" );
1163     if (flog == NULL)
1164         flog = fnul;
1165
1166     setvbuf( flog, NULL, _IONBF, 0 );
1167
1168     stdout[0] = flog[0];
1169     stderr[0] = flog[0];
1170     fprintf(stderr,"--- sdb starting (pid %d) ---\n", getpid());
1171 #else
1172     int fd;
1173
1174     fd = unix_open("/dev/null", O_RDONLY);
1175     if (fd < 0) {
1176         // hopefully not gonna happen
1177         return;
1178     }
1179     dup2(fd, 0);
1180     sdb_close(fd);
1181
1182     fd = unix_open("/tmp/sdb.log", O_WRONLY | O_CREAT | O_APPEND, 0640);
1183     if(fd < 0) {
1184         fd = unix_open("/dev/null", O_WRONLY);
1185         if (fd < 0) {
1186             // hopefully not gonna happen
1187             return;
1188         }
1189     }
1190     dup2(fd, 1);
1191     dup2(fd, 2);
1192     sdb_close(fd);
1193     fprintf(stderr,"--- sdb starting (pid %d) ---\n", getpid());
1194 #endif
1195 }
1196
1197 #if !SDB_HOST
1198
1199 void start_device_log(void)
1200 {
1201     int fd;
1202     char    path[PATH_MAX] = {0, };
1203     char    path_folder[PATH_MAX] = {0, };
1204     char    path_file[PATH_MAX] = {0, };
1205     struct tm now;
1206     time_t t;
1207 //    char value[PROPERTY_VALUE_MAX];
1208     const char* p_trace = getenv("SDB_TRACE");
1209     const char* p_path = getenv("SDBD_LOG_PATH");
1210     // read the trace mask from persistent property persist.sdb.trace_mask
1211     // give up if the property is not set or cannot be parsed
1212
1213     if ((p_trace == NULL ) && !is_enable_sdbd_log()) {
1214         return;
1215     }
1216
1217     if (p_path)
1218         snprintf(path_folder, sizeof(path_folder), "%s", p_path);
1219     else if (g_capabilities.log_path[0] != '\0')
1220         snprintf(path_folder, sizeof(path_folder), "%s", g_capabilities.log_path);
1221     else
1222         return;
1223
1224     tzset();
1225     time(&t);
1226     localtime_r(&t, &now);
1227
1228     strftime(path_file, sizeof(path_file),
1229                     "sdbd-%Y-%m-%d-%H-%M-%S.txt",
1230                     &now);
1231
1232     snprintf(path, sizeof(path), "%s/%s", path_folder, path_file);
1233
1234     fd = unix_open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1235     if (fd < 0) {
1236         return;
1237     }
1238
1239     // redirect stdout and stderr to the log file
1240     dup2(fd, 1);
1241     dup2(fd, 2);
1242     fprintf(stderr,"--- sdbd starting (pid %d) ---\n", getpid());
1243     sdb_close(fd);
1244
1245     fd = unix_open("/dev/null", O_RDONLY);
1246     if (fd < 0) {
1247         // hopefully not gonna happen
1248         return;
1249     }
1250     dup2(fd, 0);
1251     sdb_close(fd);
1252 }
1253
1254 int daemonize(void) {
1255
1256     // set file creation mask to 0
1257     umask(0);
1258
1259     switch (fork()) {
1260     case -1:
1261         return -1;
1262     case 0:
1263         break;
1264     default:
1265         _exit(0);
1266     }
1267 #ifdef SDB_PIDPATH
1268     FILE *f = fopen(SDB_PIDPATH, "w");
1269
1270     if (f != NULL) {
1271         fprintf(f, "%d\n", getpid());
1272         fclose(f);
1273     }
1274 #endif
1275     if (setsid() == -1)
1276         return -1;
1277
1278     if (chdir("/") < 0)
1279         D("sdbd: unable to change working directory to /\n");
1280
1281     return 0;
1282 }
1283 #endif
1284
1285 #if SDB_HOST
1286 int launch_server(int server_port)
1287 {
1288 #ifdef HAVE_WIN32_PROC
1289     /* we need to start the server in the background                    */
1290     /* we create a PIPE that will be used to wait for the server's "OK" */
1291     /* message since the pipe handles must be inheritable, we use a     */
1292     /* security attribute                                               */
1293     HANDLE                pipe_read, pipe_write;
1294     SECURITY_ATTRIBUTES   sa;
1295     STARTUPINFO           startup;
1296     PROCESS_INFORMATION   pinfo;
1297     char                  program_path[ MAX_PATH ];
1298     int                   ret;
1299
1300     sa.nLength = sizeof(sa);
1301     sa.lpSecurityDescriptor = NULL;
1302     sa.bInheritHandle = TRUE;
1303
1304     /* create pipe, and ensure its read handle isn't inheritable */
1305     ret = CreatePipe( &pipe_read, &pipe_write, &sa, 0 );
1306     if (!ret) {
1307         fprintf(stderr, "CreatePipe() failure, error %ld\n", GetLastError() );
1308         return -1;
1309     }
1310
1311     SetHandleInformation( pipe_read, HANDLE_FLAG_INHERIT, 0 );
1312
1313     ZeroMemory( &startup, sizeof(startup) );
1314     startup.cb = sizeof(startup);
1315     startup.hStdInput  = GetStdHandle( STD_INPUT_HANDLE );
1316     startup.hStdOutput = pipe_write;
1317     startup.hStdError  = GetStdHandle( STD_ERROR_HANDLE );
1318     startup.dwFlags    = STARTF_USESTDHANDLES;
1319
1320     ZeroMemory( &pinfo, sizeof(pinfo) );
1321
1322     /* get path of current program */
1323     GetModuleFileName( NULL, program_path, sizeof(program_path) );
1324
1325     ret = CreateProcess(
1326             program_path,                              /* program path  */
1327             "sdb fork-server server",
1328                                     /* the fork-server argument will set the
1329                                        debug = 2 in the child           */
1330             NULL,                   /* process handle is not inheritable */
1331             NULL,                    /* thread handle is not inheritable */
1332             TRUE,                          /* yes, inherit some handles */
1333             DETACHED_PROCESS, /* the new process doesn't have a console */
1334             NULL,                     /* use parent's environment block */
1335             NULL,                    /* use parent's starting directory */
1336             &startup,                 /* startup info, i.e. std handles */
1337             &pinfo );
1338
1339     CloseHandle( pipe_write );
1340
1341     if (!ret) {
1342         fprintf(stderr, "CreateProcess failure, error %ld\n", GetLastError() );
1343         CloseHandle( pipe_read );
1344         return -1;
1345     }
1346
1347     CloseHandle( pinfo.hProcess );
1348     CloseHandle( pinfo.hThread );
1349
1350     /* wait for the "OK\n" message */
1351     {
1352         char  temp[3];
1353         DWORD  count;
1354
1355         ret = ReadFile( pipe_read, temp, 3, &count, NULL );
1356         CloseHandle( pipe_read );
1357         if ( !ret ) {
1358             fprintf(stderr, "could not read ok from SDB Server, error = %ld\n", GetLastError() );
1359             return -1;
1360         }
1361         if (count != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
1362             fprintf(stderr, "SDB server didn't ACK\n" );
1363             return -1;
1364         }
1365     }
1366 #elif defined(HAVE_FORKEXEC)
1367     char    path[PATH_MAX];
1368     int     fd[2];
1369
1370     // set up a pipe so the child can tell us when it is ready.
1371     // fd[0] will be parent's end, and fd[1] will get mapped to stderr in the child.
1372     if (pipe(fd)) {
1373         fprintf(stderr, "pipe failed in launch_server, errno: %d\n", errno);
1374         return -1;
1375     }
1376     get_my_path(path, PATH_MAX);
1377     pid_t pid = fork();
1378     if(pid < 0) return -1;
1379
1380     if (pid == 0) {
1381         // child side of the fork
1382
1383         // redirect stderr to the pipe
1384         // we use stderr instead of stdout due to stdout's buffering behavior.
1385         sdb_close(fd[0]);
1386         dup2(fd[1], STDERR_FILENO);
1387         sdb_close(fd[1]);
1388
1389         // child process
1390         int result = execl(path, "sdb", "fork-server", "server", NULL);
1391         // this should not return
1392         fprintf(stderr, "OOPS! execl returned %d, errno: %d\n", result, errno);
1393     } else  {
1394         // parent side of the fork
1395
1396         char  temp[3];
1397
1398         temp[0] = 'A'; temp[1] = 'B'; temp[2] = 'C';
1399         // wait for the "OK\n" message
1400         sdb_close(fd[1]);
1401         int ret = sdb_read(fd[0], temp, 3);
1402         int saved_errno = errno;
1403         sdb_close(fd[0]);
1404         if (ret < 0) {
1405             fprintf(stderr, "could not read ok from SDB Server, errno = %d\n", saved_errno);
1406             return -1;
1407         }
1408         if (ret != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
1409             fprintf(stderr, "SDB server didn't ACK\n" );
1410             return -1;
1411         }
1412
1413         setsid();
1414     }
1415 #else
1416 #error "cannot implement background server start on this platform"
1417 #endif
1418     return 0;
1419 }
1420 #endif
1421
1422 /* Constructs a local name of form tcp:port.
1423  * target_str points to the target string, it's content will be overwritten.
1424  * target_size is the capacity of the target string.
1425  * server_port is the port number to use for the local name.
1426  */
1427 void build_local_name(char* target_str, size_t target_size, int server_port)
1428 {
1429   snprintf(target_str, target_size, "tcp:%d", server_port);
1430 }
1431
1432 #if !SDB_HOST
1433 static void init_drop_privileges() {
1434 #ifdef _DROP_PRIVILEGE
1435     rootshell_mode = 0;
1436 #else
1437     rootshell_mode = 1;
1438 #endif
1439 }
1440
1441 int should_drop_privileges() {
1442     if (rootshell_mode == 1) { // if root, then don't drop
1443         return 0;
1444     }
1445     return 1;
1446 }
1447
1448 #include <dbus/dbus.h>
1449 #include <dbus/dbus-glib.h>
1450 #include <dbus/dbus-glib-lowlevel.h>
1451
1452 #define BOOTING_DONE_SIGNAL    "BootingDone"
1453 #define DEVICED_CORE_INTERFACE "org.tizen.system.deviced.core"
1454 #define SDBD_BOOT_INFO_FILE "/tmp/sdbd_boot_info"
1455
1456 static DBusHandlerResult __sdbd_dbus_signal_filter(DBusConnection *conn,
1457                 DBusMessage *message, void *user_data) {
1458         D("got dbus message\n");
1459         const char *interface;
1460
1461         DBusError error;
1462         dbus_error_init(&error);
1463
1464         interface = dbus_message_get_interface(message);
1465         if (interface == NULL) {
1466                 D("reject by security issue - no interface\n");
1467                 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1468         }
1469
1470         if (dbus_message_is_signal(message, DEVICED_CORE_INTERFACE,
1471                         BOOTING_DONE_SIGNAL)) {
1472                 booting_done = 1;
1473                 if (access(SDBD_BOOT_INFO_FILE, F_OK) == 0) {
1474                         D("booting is done before\n");
1475                 } else {
1476                         FILE *f = fopen(SDBD_BOOT_INFO_FILE, "w");
1477                         if (f != NULL) {
1478                                 fprintf(f, "%d", 1);
1479                                 fclose(f);
1480                         }
1481                 }
1482                 D("booting is done\n");
1483         }
1484
1485         D("handled dbus message\n");
1486         return DBUS_HANDLER_RESULT_HANDLED;
1487 }
1488
1489 static void *bootdone_cb(void *x) {
1490         int MAX_LOCAL_BUFSZ = 128;
1491         DBusError error;
1492         DBusConnection *bus;
1493         char rule[MAX_LOCAL_BUFSZ];
1494         GMainLoop *mainloop;
1495
1496 /* g_type_init() is deprecated for glib version 2.35.0 or greater, */
1497 #if !GLIB_CHECK_VERSION(2,35,0)
1498         g_type_init();
1499 #endif
1500
1501         dbus_error_init(&error);
1502         bus = dbus_bus_get(DBUS_BUS_SYSTEM, &error);
1503         if (!bus) {
1504                 D("Failed to connect to the D-BUS daemon: %s", error.message);
1505                 dbus_error_free(&error);
1506                 return NULL;
1507         }
1508         dbus_connection_setup_with_g_main(bus, NULL);
1509
1510         snprintf(rule, MAX_LOCAL_BUFSZ, "type='signal',interface='%s'",
1511                         DEVICED_CORE_INTERFACE);
1512         /* listening to messages */
1513         dbus_bus_add_match(bus, rule, &error);
1514         if (dbus_error_is_set(&error)) {
1515                 D("Fail to rule set: %s", error.message);
1516                 dbus_error_free(&error);
1517                 return NULL;
1518         }
1519
1520         if (dbus_connection_add_filter(bus, __sdbd_dbus_signal_filter, NULL, NULL)
1521                         == FALSE)
1522                 return NULL;
1523
1524         D("booting signal initialized\n");
1525         mainloop = g_main_loop_new(NULL, FALSE);
1526         g_main_loop_run(mainloop);
1527
1528         D("dbus loop exited");
1529
1530         return NULL;
1531 }
1532
1533 void register_bootdone_cb() {
1534         D("registerd bootdone callback\n");
1535
1536         sdb_thread_t t;
1537         if (sdb_thread_create(&t, bootdone_cb, NULL)) {
1538                 D("cannot create service thread\n");
1539                 return;
1540         }
1541 }
1542
1543 static int sdbd_set_groups() {
1544     gid_t *group_ids = NULL;
1545     int ngroups = 0;
1546     int i, j = 0;
1547     int group_match = 0;
1548     int added_group_cnt = 0;
1549
1550     getgrouplist(SDK_USER_NAME, g_sdk_group_id, NULL, &ngroups);
1551     D("group list : ngroups = %d\n", ngroups);
1552     group_ids = malloc((ngroups + SDB_DEFAULT_GROUPS_CNT) * sizeof(gid_t));
1553     if (group_ids == NULL) {
1554         D("failed to allocate group_ids(%d)\n", (ngroups + SDB_DEFAULT_GROUPS_CNT) * sizeof(gid_t));
1555         return -1;
1556     }
1557     if (getgrouplist(SDK_USER_NAME, g_sdk_group_id, group_ids, &ngroups) == -1) {
1558         D("failed to getgrouplist(), ngroups = %d\n", ngroups);
1559         free(group_ids);
1560         return -1;
1561     }
1562
1563     for (i = 0; g_default_groups[i].name != NULL; i++) {
1564         for (j = 0; j < ngroups; j++) {
1565             if (group_ids[j] == g_default_groups[i].gid) {
1566                 group_match = 1;
1567                 break;
1568             }
1569         }
1570         if (group_match == 0 && g_default_groups[i].gid != -1) {
1571             group_ids[ngroups + added_group_cnt] = g_default_groups[i].gid;
1572             added_group_cnt ++;
1573         }
1574         group_match = 0;
1575     }
1576
1577     if (setgroups(ngroups+added_group_cnt, group_ids) != 0) {
1578         D("failed to setgroups().\n");
1579         free(group_ids);
1580         return -1;
1581     }
1582
1583     free(group_ids);
1584     return 0;
1585 }
1586
1587 static int sdbd_get_user_pwd(const char* user_name, struct passwd* pwd, char* buf, size_t bufsize) {
1588     struct passwd *result = NULL;
1589     int ret = 0;
1590
1591     ret = getpwnam_r(user_name, pwd, buf, bufsize, &result);
1592     if (result == NULL) {
1593         if (ret == 0) {
1594             D("Not found passwd : username(%s)\n", user_name);
1595         } else {
1596             errno = ret;
1597             D("failed to getpwnam_r\n");
1598         }
1599         return -1;
1600     }
1601
1602     return 0;
1603 }
1604
1605 static int sdbd_get_group(const char* group_name, struct group* grp, char* buf, size_t bufsize) {
1606     struct group *result = NULL;
1607     int ret = 0;
1608
1609     ret = getgrnam_r(group_name, grp, buf, bufsize, &result);
1610     if (result == NULL) {
1611         if (ret == 0) {
1612             D("Not found group : groupname(%s)\n", group_name);
1613         } else {
1614             errno = ret;
1615             D("failed to getgrnam_r\n");
1616         }
1617         return -1;
1618     }
1619
1620     return 0;
1621 }
1622
1623 int set_sdk_user_privileges() {
1624     if (!is_init_sdk_userinfo) {
1625         D("failed to init sdk user information.\n");
1626         return -1;
1627     }
1628
1629     if (sdbd_set_groups() < 0) {
1630         D("set groups failed (errno: %d)\n", errno);
1631         return -1;
1632     }
1633
1634     if (setgid(g_sdk_group_id) != 0) {
1635         D("set group id failed (errno: %d)\n", errno);
1636         return -1;
1637     }
1638
1639     if (setuid(g_sdk_user_id) != 0) {
1640         D("set user id failed (errno: %d)\n", errno);
1641         return -1;
1642     }
1643
1644     if (chdir(g_sdk_home_dir) < 0) {
1645         D("unable to change working directory to %s\n", g_sdk_home_dir);
1646     }
1647
1648     // TODO: use pam later
1649     if (g_sdk_home_dir_env) {
1650         putenv(g_sdk_home_dir_env);
1651     }
1652
1653     return 0;
1654 }
1655
1656 #define SDB_PW_GR_DEFAULT_SIZE  (16*1024)
1657 static long get_passwd_bufsize() {
1658     long bufsize = 0;
1659
1660     bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
1661     if(bufsize < 0) {
1662         bufsize = SDB_PW_GR_DEFAULT_SIZE;
1663     }
1664
1665     return bufsize;
1666 }
1667
1668 static long get_group_bufsize() {
1669     long bufsize = 0;
1670
1671     bufsize = sysconf(_SC_GETGR_R_SIZE_MAX);
1672     if(bufsize < 0) {
1673         bufsize = SDB_PW_GR_DEFAULT_SIZE;
1674     }
1675
1676     return bufsize;
1677 }
1678
1679 static int init_sdb_default_groups() {
1680     struct group grp;
1681     char *buf = NULL;
1682     long bufsize = 0;
1683     int i = 0;
1684
1685     bufsize = get_group_bufsize();
1686     buf = malloc(bufsize);
1687     if (buf == NULL) {
1688         D("failed to allocate gruop buf(%ld)\n", bufsize);
1689         return -1;
1690     }
1691
1692     for (i = 0; g_default_groups[i].name != NULL; i++) {
1693         memset(buf, 0, bufsize);
1694         if (sdbd_get_group(g_default_groups[i].name, &grp, buf, bufsize) == 0) {
1695             g_default_groups[i].gid = grp.gr_gid;
1696         } else {
1697             D("failed get group info.(errno: %d)\n", errno);
1698         }
1699     }
1700
1701     free(buf);
1702     return 0;
1703 }
1704
1705 static void set_static_userinfo() {
1706     g_sdk_user_id = STATIC_SDK_USER_ID;
1707     g_sdk_group_id = STATIC_SDK_GROUP_ID;
1708     g_sdk_home_dir = STATIC_SDK_HOME_DIR;
1709 }
1710
1711 static int init_sdk_userinfo() {
1712     struct passwd pwd;
1713     char *buf = NULL;
1714     long bufsize = 0;
1715
1716     if (is_init_sdk_userinfo) {
1717         return 0;
1718     }
1719
1720     if (init_sdb_default_groups() < 0) {
1721         D("failed to initialize default groups.\n");
1722     }
1723
1724     bufsize = get_passwd_bufsize();
1725     buf = malloc(bufsize);
1726     if (buf == NULL) {
1727         D("failed to allocate passwd buf(%ld)\n", bufsize);
1728         set_static_userinfo();
1729     } else {
1730         if (sdbd_get_user_pwd(SDK_USER_NAME, &pwd, buf, bufsize) < 0) {
1731             D("get user passwd info.(errno: %d)\n", errno);
1732             set_static_userinfo();
1733         } else {
1734             D("username=%s, uid=%d, gid=%d, dir=%s\n", pwd.pw_name, pwd.pw_uid, pwd.pw_gid, pwd.pw_dir);
1735
1736             g_sdk_user_id = pwd.pw_uid;
1737             g_sdk_group_id = pwd.pw_gid;
1738             g_sdk_home_dir = strdup(pwd.pw_dir);
1739         }
1740         free(buf);
1741     }
1742
1743     int env_size = strlen("HOME=") + strlen(g_sdk_home_dir) + 1;
1744     g_sdk_home_dir_env = malloc(env_size);
1745     if(g_sdk_home_dir_env == NULL) {
1746         D("failed to allocate for home dir env string\n");
1747     } else {
1748         snprintf(g_sdk_home_dir_env, env_size, "HOME=%s", g_sdk_home_dir);
1749     }
1750
1751     is_init_sdk_userinfo = 1;
1752     return 0;
1753 }
1754
1755 static void init_sdk_requirements() {
1756     struct stat st;
1757
1758     // set env variable for temporary
1759     // TODO: should use pam instead later!!
1760     if (!getenv("TERM")) {
1761         putenv("TERM=linux");
1762     }
1763
1764     if (!getenv("HOME")) {
1765         putenv("HOME=/root");
1766     }
1767
1768     init_sdk_userinfo();
1769
1770     if (g_sdk_home_dir != NULL && stat(g_sdk_home_dir, &st) == 0) {
1771         if (st.st_uid != g_sdk_user_id || st.st_gid != g_sdk_group_id) {
1772             char cmd[128];
1773             snprintf(cmd, sizeof(cmd), "chown %s:%s %s -R", SDK_USER_NAME, SDK_USER_NAME, g_sdk_home_dir);
1774             if (system(cmd) < 0) {
1775                 D("failed to change ownership to sdk user to %s\n", g_sdk_home_dir);
1776             }
1777         }
1778     }
1779
1780     if (is_emulator()) {
1781         register_bootdone_cb();
1782     }
1783 }
1784 #endif /* !SDB_HOST */
1785
1786 static void init_capabilities(void) {
1787     int ret = -1;
1788     char *value = NULL;
1789
1790     memset(&g_capabilities, 0, sizeof(g_capabilities));
1791
1792     // CPU Architecture of model
1793     ret = system_info_get_platform_string("http://tizen.org/feature/platform.core.cpu.arch", &value);
1794     if (ret != SYSTEM_INFO_ERROR_NONE) {
1795         snprintf(g_capabilities.cpu_arch, sizeof(g_capabilities.cpu_arch),
1796                     "%s", UNKNOWN);
1797         D("fail to get the CPU architecture of model:%d\n", errno);
1798     } else {
1799         snprintf(g_capabilities.cpu_arch, sizeof(g_capabilities.cpu_arch),
1800                     "%s", value);
1801         if (value != NULL) {
1802             free(value);
1803         }
1804     }
1805
1806
1807     // Secure protocol support
1808     if(!request_capability_to_plugin(CAPABILITY_SECURE, g_capabilities.secure_protocol,
1809                             sizeof(g_capabilities.secure_protocol))) {
1810         D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_SECURE);
1811         snprintf(g_capabilities.secure_protocol, sizeof(g_capabilities.secure_protocol),
1812                     "%s", DISABLED);
1813     }
1814
1815
1816     // Interactive shell support
1817     if(!request_capability_to_plugin(CAPABILITY_INTER_SHELL, g_capabilities.intershell_support,
1818                             sizeof(g_capabilities.intershell_support))) {
1819         D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_INTER_SHELL);
1820         snprintf(g_capabilities.intershell_support, sizeof(g_capabilities.intershell_support),
1821                     "%s", DISABLED);
1822     }
1823
1824
1825     // File push/pull support
1826     if(!request_capability_to_plugin(CAPABILITY_FILESYNC, g_capabilities.filesync_support,
1827                             sizeof(g_capabilities.filesync_support))) {
1828         D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_FILESYNC);
1829         snprintf(g_capabilities.filesync_support, sizeof(g_capabilities.filesync_support),
1830                     "%s", DISABLED);
1831     }
1832
1833
1834     // USB protocol support
1835     if(!request_capability_to_plugin(CAPABILITY_USB_PROTOCOL, g_capabilities.usbproto_support,
1836                             sizeof(g_capabilities.usbproto_support))) {
1837         D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_USB_PROTOCOL);
1838         snprintf(g_capabilities.usbproto_support, sizeof(g_capabilities.usbproto_support),
1839                     "%s", DISABLED);
1840     }
1841
1842
1843     // Socket protocol support
1844     if(!request_capability_to_plugin(CAPABILITY_SOCK_PROTOCOL, g_capabilities.sockproto_support,
1845                             sizeof(g_capabilities.sockproto_support))) {
1846         D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_SOCK_PROTOCOL);
1847         snprintf(g_capabilities.sockproto_support, sizeof(g_capabilities.sockproto_support),
1848                     "%s", DISABLED);
1849     }
1850
1851
1852     // Root command support
1853     if(!request_capability_to_plugin(CAPABILITY_ROOT_ONOFF, g_capabilities.rootonoff_support,
1854                             sizeof(g_capabilities.rootonoff_support))) {
1855         D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_ROOT_ONOFF);
1856         snprintf(g_capabilities.rootonoff_support, sizeof(g_capabilities.rootonoff_support),
1857                     "%s", DISABLED);
1858     }
1859
1860
1861     // Encryption support
1862     if(!request_capability_to_plugin(CAPABILITY_ENCRYPTION, g_capabilities.encryption_support,
1863                             sizeof(g_capabilities.encryption_support))) {
1864         D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_ENCRYPTION);
1865         snprintf(g_capabilities.encryption_support, sizeof(g_capabilities.encryption_support),
1866                     "%s", DISABLED);
1867     }
1868
1869
1870     // pkgcmd debug mode support
1871     if(!request_capability_to_plugin(CAPABILITY_DEBUGMODE, g_capabilities.pkgcmd_debugmode,
1872                 sizeof(g_capabilities.pkgcmd_debugmode))) {
1873         D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_DEBUGMODE);
1874         snprintf(g_capabilities.pkgcmd_debugmode, sizeof(g_capabilities.pkgcmd_debugmode),
1875                 "%s", ENABLED);
1876     }
1877
1878
1879     // Zone support
1880     ret = is_container_enabled();
1881     snprintf(g_capabilities.zone_support, sizeof(g_capabilities.zone_support),
1882                 "%s", ret == 1 ? ENABLED : DISABLED);
1883
1884     // Multi-User support
1885     // XXX: There is no clear way to determine whether multi-user support.
1886     // Since TZ_SYS_DEFAULT_USER is set to "owner" for multi-user support,
1887     // guess whether multiuser support through that information.
1888     const char* sys_default_user = tzplatform_getenv(TZ_SYS_DEFAULT_USER);
1889     if (sys_default_user != NULL && !strcmp(sys_default_user, "owner")) {
1890         snprintf(g_capabilities.multiuser_support, sizeof(g_capabilities.multiuser_support),
1891                     "%s", ENABLED);
1892     } else {
1893         snprintf(g_capabilities.multiuser_support, sizeof(g_capabilities.multiuser_support),
1894                     "%s", DISABLED);
1895     }
1896
1897     // Window size synchronization support
1898     snprintf(g_capabilities.syncwinsz_support, sizeof(g_capabilities.syncwinsz_support),
1899                 "%s", ENABLED);
1900
1901     // SDK Tool path
1902     if (SDK_TOOL_PATH == NULL) {
1903         D("fail to get SDK tool path.\n");
1904         snprintf(g_capabilities.sdk_toolpath, sizeof(g_capabilities.sdk_toolpath),
1905                     "%s", UNKNOWN);
1906     } else {
1907         snprintf(g_capabilities.sdk_toolpath, sizeof(g_capabilities.sdk_toolpath),
1908                     "%s", SDK_TOOL_PATH);
1909     }
1910
1911     // Profile name
1912     ret = system_info_get_platform_string("http://tizen.org/feature/profile", &value);
1913     if (ret != SYSTEM_INFO_ERROR_NONE) {
1914         snprintf(g_capabilities.profile_name, sizeof(g_capabilities.profile_name),
1915                     "%s", UNKNOWN);
1916         D("fail to get profile name:%d\n", errno);
1917     } else {
1918         snprintf(g_capabilities.profile_name, sizeof(g_capabilities.profile_name),
1919                     "%s", value);
1920         if (value != NULL) {
1921             free(value);
1922         }
1923     }
1924
1925
1926     // Vendor name
1927     ret = system_info_get_platform_string("http://tizen.org/system/manufacturer", &value);
1928     if (ret != SYSTEM_INFO_ERROR_NONE) {
1929         snprintf(g_capabilities.vendor_name, sizeof(g_capabilities.vendor_name),
1930                     "%s", UNKNOWN);
1931         D("fail to get the Vendor name:%d\n", errno);
1932     } else {
1933         snprintf(g_capabilities.vendor_name, sizeof(g_capabilities.vendor_name),
1934                     "%s", value);
1935         if (value != NULL) {
1936             free(value);
1937         }
1938     }
1939
1940
1941     // Target name of the launch possible
1942     if(!request_capability_to_plugin(CAPABILITY_CAN_LAUNCH, g_capabilities.can_launch,
1943                             sizeof(g_capabilities.can_launch))) {
1944         D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_CAN_LAUNCH);
1945         snprintf(g_capabilities.can_launch, sizeof(g_capabilities.can_launch),
1946                     "%s", UNKNOWN);
1947     }
1948
1949
1950     // Platform version
1951     ret = system_info_get_platform_string("http://tizen.org/feature/platform.version", &value);
1952     if (ret != SYSTEM_INFO_ERROR_NONE) {
1953         snprintf(g_capabilities.platform_version, sizeof(g_capabilities.platform_version),
1954                     "%s", UNKNOWN);
1955         D("fail to get platform version:%d\n", errno);
1956     } else {
1957         snprintf(g_capabilities.platform_version, sizeof(g_capabilities.platform_version),
1958                     "%s", value);
1959         if (value != NULL) {
1960             free(value);
1961         }
1962     }
1963
1964
1965     // Product version
1966     if(!request_capability_to_plugin(CAPABILITY_PRODUCT_VER, g_capabilities.product_version,
1967                             sizeof(g_capabilities.product_version))) {
1968         D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_PRODUCT_VER);
1969         snprintf(g_capabilities.product_version, sizeof(g_capabilities.product_version),
1970                     "%s", UNKNOWN);
1971     }
1972
1973
1974     // Sdbd version
1975     snprintf(g_capabilities.sdbd_version, sizeof(g_capabilities.sdbd_version),
1976                 "%d.%d.%d", SDB_VERSION_MAJOR, SDB_VERSION_MINOR, SDB_VERSION_PATCH);
1977
1978
1979     // Sdbd plugin version
1980     if(!request_capability_to_plugin(CAPABILITY_PLUGIN_VER, g_capabilities.sdbd_plugin_version,
1981                             sizeof(g_capabilities.sdbd_plugin_version))) {
1982         D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_PLUGIN_VER);
1983         snprintf(g_capabilities.sdbd_plugin_version, sizeof(g_capabilities.sdbd_plugin_version),
1984                     "%s", UNKNOWN);
1985     }
1986
1987
1988     // sdbd log enable
1989     if(!request_capability_to_plugin(CAPABILITY_LOG_ENABLE, g_capabilities.log_enable,
1990                                sizeof(g_capabilities.log_enable))) {
1991            D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_LOG_ENABLE);
1992            snprintf(g_capabilities.log_enable, sizeof(g_capabilities.log_enable),
1993                        "%s", DISABLED);
1994     }
1995
1996     // sdbd log path
1997     if(!request_capability_to_plugin(CAPABILITY_LOG_PATH, g_capabilities.log_path,
1998                                sizeof(g_capabilities.log_path))) {
1999            D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_LOG_PATH);
2000            snprintf(g_capabilities.log_path, sizeof(g_capabilities.log_path),
2001                        "%s", UNKNOWN);
2002     }
2003
2004     // Application command support
2005     if(!request_capability_to_plugin(CAPABILITY_APPCMD, g_capabilities.appcmd_support,
2006                                sizeof(g_capabilities.appcmd_support))) {
2007            D("failed to request. (%d:%d) \n", PLUGIN_SYNC_CMD_CAPABILITY, CAPABILITY_APPCMD);
2008            snprintf(g_capabilities.appcmd_support, sizeof(g_capabilities.appcmd_support),
2009                        "%s", UNKNOWN);
2010     }
2011
2012     // Capability version
2013     snprintf(g_capabilities.sdbd_cap_version, sizeof(g_capabilities.sdbd_cap_version),
2014                 "%d.%d", SDBD_CAP_VERSION_MAJOR, SDBD_CAP_VERSION_MINOR);
2015 }
2016
2017 static int is_support_usbproto()
2018 {
2019     return (!strncmp(g_capabilities.usbproto_support, PLUGIN_RET_ENABLED, strlen(PLUGIN_RET_ENABLED)));
2020 }
2021
2022 static int is_support_sockproto()
2023 {
2024     return (!strncmp(g_capabilities.sockproto_support, PLUGIN_RET_ENABLED, strlen(PLUGIN_RET_ENABLED)));
2025 }
2026
2027 #define EMULATOR_MODEL_NAME     "Emulator"
2028 static void check_emulator_or_device()
2029 {
2030     char model_name[256]={0,};
2031     int ret = -1;
2032
2033     // Get the model name from model_config.xml
2034     ret = get_device_name(model_name, sizeof model_name);
2035     if (ret == 0) {
2036         if(!strncmp(model_name, EMULATOR_MODEL_NAME, sizeof(EMULATOR_MODEL_NAME))){
2037             g_is_emulator = 1;
2038             D("This target type is Emulator\n");
2039         } else {
2040             g_is_emulator = 0;
2041             D("This target type is Device\n");
2042         }
2043     } else {
2044         g_is_emulator = -1;
2045         D("failed to get the model name.\n");
2046     }
2047 }
2048
2049 static void fork_prepare_handler(void)
2050 {
2051     sdb_mutex_lock(&D_lock);
2052 }
2053
2054 static void fork_parent_handler(void)
2055 {
2056     sdb_mutex_unlock(&D_lock);
2057 }
2058
2059 static void fork_child_handler(void)
2060 {
2061     sdb_mutex_unlock(&D_lock);
2062 }
2063
2064 int sdb_main(int is_daemon, int server_port)
2065 {
2066 #if !SDB_HOST
2067     check_emulator_or_device();
2068
2069     load_sdbd_plugin();
2070
2071     init_capabilities();
2072
2073     sdb_trace_init();
2074     start_device_log();
2075
2076     init_drop_privileges();
2077     init_sdk_requirements();
2078     if (!request_validity_to_plugin(PLUGIN_SYNC_CMD_VERIFY_LAUNCH, NULL)) {
2079         D("sdbd should be launched in develop mode.\n");
2080         return -1;
2081     }
2082
2083     umask(000);
2084
2085     pthread_atfork(fork_prepare_handler, fork_parent_handler, fork_child_handler);
2086 #endif
2087
2088     atexit(sdb_cleanup);
2089 #ifdef HAVE_WIN32_PROC
2090     SetConsoleCtrlHandler( ctrlc_handler, TRUE );
2091 #elif defined(HAVE_FORKEXEC)
2092     // No SIGCHLD. Let the service subproc handle its children.
2093     signal(SIGPIPE, SIG_IGN);
2094 #endif
2095
2096     init_transport_registration();
2097
2098
2099 #if SDB_HOST
2100     HOST = 1;
2101     usb_init();
2102     local_init(DEFAULT_SDB_LOCAL_TRANSPORT_PORT);
2103
2104     char local_name[30];
2105     build_local_name(local_name, sizeof(local_name), server_port);
2106     if(install_listener(local_name, "*smartsocket*", NULL)) {
2107         exit(1);
2108     }
2109 #else
2110     /* don't listen on a port (default 5037) if running in secure mode */
2111     /* don't run as root if we are running in secure mode */
2112
2113     if (should_drop_privileges()) {
2114 # if 0
2115         struct __user_cap_header_struct header;
2116         struct __user_cap_data_struct cap;
2117
2118         if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
2119             exit(1);
2120         }
2121         /* add extra groups:
2122         ** SID_TTY to access /dev/ptmx
2123         */
2124         gid_t groups[] = { SID_TTY, SID_APP_LOGGING, SID_SYS_LOGGING };
2125         if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
2126             exit(1);
2127         }
2128         /* then switch user and group to "developer" */
2129         if (setgid(GID_DEVELOPER) != 0) {
2130             fprintf(stderr, "set group id failed errno: %d\n", errno);
2131             exit(1);
2132         }
2133         if (setuid(SID_DEVELOPER) != 0) {
2134             fprintf(stderr, "set user id failed errno: %d\n", errno);
2135             exit(1);
2136         }
2137
2138         /* set CAP_SYS_BOOT capability, so "sdb reboot" will succeed */
2139         header.version = _LINUX_CAPABILITY_VERSION;
2140         header.pid = 0;
2141         cap.effective = cap.permitted = (1 << CAP_SYS_BOOT);
2142         cap.inheritable = 0;
2143         capset(&header, &cap);
2144 #endif
2145         D("Local port disabled\n");
2146     } else {
2147         char local_name[30];
2148         build_local_name(local_name, sizeof(local_name), server_port);
2149         if(install_listener(local_name, "*smartsocket*", NULL)) {
2150             exit(1);
2151         }
2152     }
2153
2154     /* choose the usb gadget backend */
2155     if (access(USB_NODE_FILE, F_OK) == 0) {
2156         /* legacy kernel-based sdb gadget */
2157         usb_init =    &linux_usb_init;
2158         usb_cleanup = &linux_usb_cleanup;
2159         usb_write =   &linux_usb_write;
2160         usb_read =    &linux_usb_read;
2161         usb_close =   &linux_usb_close;
2162         usb_kick =    &linux_usb_kick;
2163     } else {
2164         /* functionfs based gadget */
2165         usb_init =    &ffs_usb_init;
2166         usb_cleanup = &ffs_usb_cleanup;
2167         usb_write =   &ffs_usb_write;
2168         usb_read =    &ffs_usb_read;
2169         usb_close =   &ffs_usb_close;
2170         usb_kick =    &ffs_usb_kick;
2171     }
2172
2173     if (is_support_usbproto()) {
2174         // listen on USB
2175         usb_init();
2176     }
2177     if (is_support_sockproto()) {
2178         /* by default don't listen on local transport but
2179          * listen if suitable command line argument has been provided */
2180         if (sdbd_commandline_args.sdbd_port >= 0) {
2181             local_init(sdbd_commandline_args.sdbd_port);
2182         } else {
2183             local_init(DEFAULT_SDB_LOCAL_TRANSPORT_PORT);
2184         }
2185     }
2186
2187 #if 0 /* tizen specific */
2188     D("sdb_main(): pre init_jdwp()\n");
2189     init_jdwp();
2190     D("sdb_main(): post init_jdwp()\n");
2191 #endif
2192 #endif
2193
2194     if (is_daemon)
2195     {
2196         // inform our parent that we are up and running.
2197 #ifdef HAVE_WIN32_PROC
2198         DWORD  count;
2199         WriteFile( GetStdHandle( STD_OUTPUT_HANDLE ), "OK\n", 3, &count, NULL );
2200 #elif defined(HAVE_FORKEXEC)
2201         fprintf(stderr, "OK\n");
2202 #endif
2203         start_logging();
2204     }
2205
2206     D("Event loop starting\n");
2207
2208     fdevent_loop();
2209
2210     if (is_support_usbproto()) {
2211         usb_cleanup();
2212     }
2213
2214     return 0;
2215 }
2216
2217 #if SDB_HOST
2218 void connect_device(char* host, char* buffer, int buffer_size)
2219 {
2220     int port, fd;
2221     char* portstr = strchr(host, ':');
2222     char hostbuf[100];
2223     char serial[100];
2224
2225     s_strncpy(hostbuf, host, sizeof(hostbuf) - 1);
2226     if (portstr) {
2227         if (portstr - host >= sizeof(hostbuf)) {
2228             snprintf(buffer, buffer_size, "bad host name %s", host);
2229             return;
2230         }
2231         // zero terminate the host at the point we found the colon
2232         hostbuf[portstr - host] = 0;
2233         if (sscanf(portstr + 1, "%d", &port) == 0) {
2234             snprintf(buffer, buffer_size, "bad port number %s", portstr);
2235             return;
2236         }
2237     } else {
2238         port = DEFAULT_SDB_LOCAL_TRANSPORT_PORT;
2239     }
2240
2241     snprintf(serial, sizeof(serial), "%s:%d", hostbuf, port);
2242     if (find_transport(serial)) {
2243         snprintf(buffer, buffer_size, "already connected to %s", serial);
2244         return;
2245     }
2246
2247     fd = socket_network_client(hostbuf, port, SOCK_STREAM);
2248     if (fd < 0) {
2249         snprintf(buffer, buffer_size, "unable to connect to %s", host);
2250         return;
2251     }
2252
2253     D("client: connected on remote on fd %d\n", fd);
2254     close_on_exec(fd);
2255     disable_tcp_nagle(fd);
2256     register_socket_transport(fd, serial, port, 0, NULL);
2257     snprintf(buffer, buffer_size, "connected to %s", serial);
2258 }
2259
2260 void connect_emulator(char* port_spec, char* buffer, int buffer_size)
2261 {
2262     char* port_separator = strchr(port_spec, ',');
2263     if (!port_separator) {
2264         snprintf(buffer, buffer_size,
2265                 "unable to parse '%s' as <console port>,<sdb port>",
2266                 port_spec);
2267         return;
2268     }
2269
2270     // Zero-terminate console port and make port_separator point to 2nd port.
2271     *port_separator++ = 0;
2272     int console_port = strtol(port_spec, NULL, 0);
2273     int sdb_port = strtol(port_separator, NULL, 0);
2274     if (!(console_port > 0 && sdb_port > 0)) {
2275         *(port_separator - 1) = ',';
2276         snprintf(buffer, buffer_size,
2277                 "Invalid port numbers: Expected positive numbers, got '%s'",
2278                 port_spec);
2279         return;
2280     }
2281
2282     /* Check if the emulator is already known.
2283      * Note: There's a small but harmless race condition here: An emulator not
2284      * present just yet could be registered by another invocation right
2285      * after doing this check here. However, local_connect protects
2286      * against double-registration too. From here, a better error message
2287      * can be produced. In the case of the race condition, the very specific
2288      * error message won't be shown, but the data doesn't get corrupted. */
2289     atransport* known_emulator = find_emulator_transport_by_sdb_port(sdb_port);
2290     if (known_emulator != NULL) {
2291         snprintf(buffer, buffer_size,
2292                 "Emulator on port %d already registered.", sdb_port);
2293         return;
2294     }
2295
2296     /* Check if more emulators can be registered. Similar unproblematic
2297      * race condition as above. */
2298     int candidate_slot = get_available_local_transport_index();
2299     if (candidate_slot < 0) {
2300         snprintf(buffer, buffer_size, "Cannot accept more emulators.");
2301         return;
2302     }
2303
2304     /* Preconditions met, try to connect to the emulator. */
2305     if (!local_connect_arbitrary_ports(console_port, sdb_port, NULL)) {
2306         snprintf(buffer, buffer_size,
2307                 "Connected to emulator on ports %d,%d", console_port, sdb_port);
2308     } else {
2309         snprintf(buffer, buffer_size,
2310                 "Could not connect to emulator on ports %d,%d",
2311                 console_port, sdb_port);
2312     }
2313 }
2314 #endif
2315
2316 int copy_packet(apacket* dest, apacket* src) {
2317
2318     if(dest == NULL) {
2319         D("dest packet is NULL\n");
2320         return -1;
2321     }
2322
2323     if(src == NULL) {
2324         D("src packet is NULL\n");
2325         return -1;
2326     }
2327
2328     dest->next = src->next;
2329     dest->ptr = src->ptr;
2330     dest->len = src->len;
2331
2332     int data_length = src->msg.data_length;
2333     if(data_length > MAX_PAYLOAD) {
2334         data_length = MAX_PAYLOAD;
2335     }
2336     memcpy(&(dest->msg), &(src->msg), sizeof(amessage) + data_length);
2337
2338     return 0;
2339 }
2340
2341 int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s)
2342 {
2343     atransport *transport = NULL;
2344     char buf[4096];
2345
2346     if(!strcmp(service, "kill")) {
2347         fprintf(stderr,"sdb server killed by remote request\n");
2348         fflush(stdout);
2349         sdb_write(reply_fd, "OKAY", 4);
2350         if (is_support_usbproto()) {
2351             usb_cleanup();
2352         }
2353         exit(0);
2354     }
2355
2356 #if SDB_HOST
2357     // "transport:" is used for switching transport with a specified serial number
2358     // "transport-usb:" is used for switching transport to the only USB transport
2359     // "transport-local:" is used for switching transport to the only local transport
2360     // "transport-any:" is used for switching transport to the only transport
2361     if (!strncmp(service, "transport", strlen("transport"))) {
2362         char* error_string = "unknown failure";
2363         transport_type type = kTransportAny;
2364
2365         if (!strncmp(service, "transport-usb", strlen("transport-usb"))) {
2366             type = kTransportUsb;
2367         } else if (!strncmp(service, "transport-local", strlen("transport-local"))) {
2368             type = kTransportLocal;
2369         } else if (!strncmp(service, "transport-any", strlen("transport-any"))) {
2370             type = kTransportAny;
2371         } else if (!strncmp(service, "transport:", strlen("transport:"))) {
2372             service += strlen("transport:");
2373             serial = service;
2374         }
2375
2376         transport = acquire_one_transport(CS_ANY, type, serial, &error_string);
2377
2378         if (transport) {
2379             s->transport = transport;
2380             sdb_write(reply_fd, "OKAY", 4);
2381         } else {
2382             sendfailmsg(reply_fd, error_string);
2383         }
2384         return 1;
2385     }
2386
2387     // return a list of all connected devices
2388     if (!strcmp(service, "devices")) {
2389         char buffer[4096];
2390         memset(buf, 0, sizeof(buf));
2391         memset(buffer, 0, sizeof(buffer));
2392         D("Getting device list \n");
2393         list_transports(buffer, sizeof(buffer));
2394         snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer),buffer);
2395         D("Wrote device list \n");
2396         writex(reply_fd, buf, strlen(buf));
2397         return 0;
2398     }
2399
2400     // add a new TCP transport, device or emulator
2401     if (!strncmp(service, "connect:", 8)) {
2402         char buffer[4096];
2403         char* host = service + 8;
2404         if (!strncmp(host, "emu:", 4)) {
2405             connect_emulator(host + 4, buffer, sizeof(buffer));
2406         } else {
2407             connect_device(host, buffer, sizeof(buffer));
2408         }
2409         // Send response for emulator and device
2410         snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
2411         writex(reply_fd, buf, strlen(buf));
2412         return 0;
2413     }
2414
2415     // remove TCP transport
2416     if (!strncmp(service, "disconnect:", 11)) {
2417         char buffer[4096];
2418         memset(buffer, 0, sizeof(buffer));
2419         char* serial = service + 11;
2420         if (serial[0] == 0) {
2421             // disconnect from all TCP devices
2422             unregister_all_tcp_transports();
2423         } else {
2424             char hostbuf[100];
2425             // assume port 26101 if no port is specified
2426             if (!strchr(serial, ':')) {
2427                 snprintf(hostbuf, sizeof(hostbuf) - 1, "%s:26101", serial);
2428                 serial = hostbuf;
2429             }
2430             atransport *t = find_transport(serial);
2431
2432             if (t) {
2433                 unregister_transport(t);
2434             } else {
2435                 snprintf(buffer, sizeof(buffer), "No such device %s", serial);
2436             }
2437         }
2438
2439         snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
2440         writex(reply_fd, buf, strlen(buf));
2441         return 0;
2442     }
2443
2444     // returns our value for SDB_SERVER_VERSION
2445     if (!strcmp(service, "version")) {
2446         char version[12];
2447         snprintf(version, sizeof version, "%04x", SDB_SERVER_VERSION);
2448         snprintf(buf, sizeof buf, "OKAY%04x%s", (unsigned)strlen(version), version);
2449         writex(reply_fd, buf, strlen(buf));
2450         return 0;
2451     }
2452
2453     if(!strncmp(service,"get-serialno",strlen("get-serialno"))) {
2454         char *out = "unknown";
2455          transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
2456        if (transport && transport->serial) {
2457             out = transport->serial;
2458         }
2459         snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(out),out);
2460         writex(reply_fd, buf, strlen(buf));
2461         return 0;
2462     }
2463     // indicates a new emulator instance has started
2464        if (!strncmp(service,"emulator:",9)) { /* tizen specific */
2465            char *tmp = strtok(service+9, DEVICEMAP_SEPARATOR);
2466            int  port = 0;
2467
2468            if (tmp == NULL) {
2469                port = atoi(service+9);
2470            } else {
2471                port = atoi(tmp);
2472                tmp = strtok(NULL, DEVICEMAP_SEPARATOR);
2473                if (tmp != NULL) {
2474                    local_connect(port, tmp);
2475                }
2476            }
2477            local_connect(port, NULL);
2478         return 0;
2479     }
2480 #endif // SDB_HOST
2481
2482     if(!strncmp(service,"forward:",8) || !strncmp(service,"killforward:",12)) {
2483         char *local, *remote, *err;
2484         int r;
2485         atransport *transport;
2486
2487         int createForward = strncmp(service,"kill",4);
2488
2489         local = service + (createForward ? 8 : 12);
2490         remote = strchr(local,';');
2491         if(remote == 0) {
2492             sendfailmsg(reply_fd, "malformed forward spec");
2493             return 0;
2494         }
2495
2496         *remote++ = 0;
2497         if((local[0] == 0) || (remote[0] == 0) || (remote[0] == '*')){
2498             sendfailmsg(reply_fd, "malformed forward spec");
2499             return 0;
2500         }
2501
2502         transport = acquire_one_transport(CS_ANY, ttype, serial, &err);
2503         if (!transport) {
2504             sendfailmsg(reply_fd, err);
2505             return 0;
2506         }
2507
2508         if (createForward) {
2509             r = install_listener(local, remote, transport);
2510         } else {
2511             r = remove_listener(local, remote, transport);
2512         }
2513         if(r == 0) {
2514                 /* 1st OKAY is connect, 2nd OKAY is status */
2515             writex(reply_fd, "OKAYOKAY", 8);
2516             return 0;
2517         }
2518
2519         if (createForward) {
2520             sendfailmsg(reply_fd, (r == -1) ? "cannot rebind smartsocket" : "cannot bind socket");
2521         } else {
2522             sendfailmsg(reply_fd, "cannot remove listener");
2523         }
2524         return 0;
2525     }
2526
2527     if(!strncmp(service,"get-state",strlen("get-state"))) {
2528         transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
2529         char *state = connection_state_name(transport);
2530         snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(state),state);
2531         writex(reply_fd, buf, strlen(buf));
2532         return 0;
2533     }
2534     return -1;
2535 }
2536
2537 #if !SDB_HOST
2538 int recovery_mode = 0;
2539 #endif
2540
2541 int main(int argc, char **argv)
2542 {
2543 #if SDB_HOST
2544     sdb_sysdeps_init();
2545     sdb_trace_init();
2546     return sdb_commandline(argc - 1, argv + 1);
2547 #else
2548     /* If sdbd runs inside the emulator this will enable sdb tracing via
2549      * sdb-debug qemud service in the emulator. */
2550 #if 0 /* tizen specific */
2551     sdb_qemu_trace_init();
2552     if((argc > 1) && (!strcmp(argv[1],"recovery"))) {
2553         sdb_device_banner = "recovery";
2554         recovery_mode = 1;
2555     }
2556 #endif
2557
2558     apply_sdbd_commandline_defaults(&sdbd_commandline_args);
2559     int parse_ret = parse_sdbd_commandline(&sdbd_commandline_args, argc, argv);
2560
2561     // TODO: Add detailed error messages
2562     // TODO: Add individual messages for help and usage
2563     if(parse_ret != SDBD_COMMANDLINE_SUCCESS) {
2564         if (parse_ret == SDBD_COMMANDLINE_HELP
2565                 || parse_ret == SDBD_COMMANDLINE_USAGE) {
2566             // User requested help or usage
2567             print_sdbd_usage_message(stdout);
2568             return EXIT_SUCCESS;
2569         }
2570
2571         // Print usage message because of invalid options
2572         print_sdbd_usage_message(stderr);
2573         return EXIT_FAILURE;
2574     }
2575
2576 #if !SDB_HOST
2577     if (daemonize() < 0)
2578         fatal("daemonize() failed: errno:%d", errno);
2579 #endif
2580
2581     D("Handling main()\n");
2582
2583     //sdbd will never die on emulator!
2584     signal(SIGTERM, handle_sig_term); /* tizen specific */
2585     return sdb_main(0, DEFAULT_SDB_PORT);
2586 #endif
2587 }
2588