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