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