Allow sdb to listen on both usb and TCP.
[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 <netdb.h>
30 #include <tzplatform_config.h>
31
32 #include "sysdeps.h"
33 #include "sdb.h"
34 #include "strutils.h"
35 #if !SDB_HOST
36 #include "commandline_sdbd.h"
37 #endif
38
39 #if !SDB_HOST
40 #include <linux/prctl.h>
41 #define SDB_PIDPATH "/tmp/.sdbd.pid"
42 #else
43 #include "usb_vendors.h"
44 #endif
45 #include <system_info.h>
46 #define PROC_CMDLINE_PATH "/proc/cmdline"
47 #if SDB_TRACE
48 SDB_MUTEX_DEFINE( D_lock );
49 #endif
50
51 int HOST = 0;
52 #define HOME_DEV_PATH tzplatform_getenv(TZ_SDK_HOME)
53 #define DEV_NAME tzplatform_getenv(TZ_SDK_USER_NAME)
54 #if !SDB_HOST
55 SdbdCommandlineArgs sdbd_commandline_args;
56 #endif
57
58 int is_emulator(void) {
59 #if SDB_HOST
60         return 0;
61 #else
62         return sdbd_commandline_args.emulator.host != NULL;
63 #endif
64 }
65
66 void handle_sig_term(int sig) {
67 #ifdef SDB_PIDPATH
68     if (access(SDB_PIDPATH, F_OK) == 0)
69         sdb_unlink(SDB_PIDPATH);
70 #endif
71     //kill(getpgid(getpid()),SIGTERM);
72     //killpg(getpgid(getpid()),SIGTERM);
73     if (!is_emulator()) {
74         exit(0);
75     } else {
76         // do nothing on a emulator
77     }
78 }
79
80 static const char *sdb_device_banner = "device";
81
82 void fatal(const char *fmt, ...)
83 {
84     va_list ap;
85     va_start(ap, fmt);
86     fprintf(stderr, "error: ");
87     vfprintf(stderr, fmt, ap);
88     fprintf(stderr, "\n");
89     va_end(ap);
90     exit(-1);
91 }
92
93 void fatal_errno(const char *fmt, ...)
94 {
95     va_list ap;
96     va_start(ap, fmt);
97     fprintf(stderr, "error: %s: ", strerror(errno));
98     vfprintf(stderr, fmt, ap);
99     fprintf(stderr, "\n");
100     va_end(ap);
101     exit(-1);
102 }
103
104 int   sdb_trace_mask;
105
106 /* read a comma/space/colum/semi-column separated list of tags
107  * from the SDB_TRACE environment variable and build the trace
108  * mask from it. note that '1' and 'all' are special cases to
109  * enable all tracing
110  */
111 void  sdb_trace_init(void)
112 {
113     const char*  p = getenv("SDB_TRACE");
114     const char*  q;
115
116     static const struct {
117         const char*  tag;
118         int           flag;
119     } tags[] = {
120         { "1", 0 },
121         { "all", 0 },
122         { "sdb", TRACE_SDB },
123         { "sockets", TRACE_SOCKETS },
124         { "packets", TRACE_PACKETS },
125         { "rwx", TRACE_RWX },
126         { "usb", TRACE_USB },
127         { "sync", TRACE_SYNC },
128         { "sysdeps", TRACE_SYSDEPS },
129         { "transport", TRACE_TRANSPORT },
130         { "jdwp", TRACE_JDWP },
131         { "services", TRACE_SERVICES },
132         { "properties", TRACE_PROPERTIES },
133         { "sdktools", TRACE_SDKTOOLS },
134         { NULL, 0 }
135     };
136
137     if (p == NULL)
138             return;
139
140     /* use a comma/column/semi-colum/space separated list */
141     while (*p) {
142         int  len, tagn;
143
144         q = strpbrk(p, " ,:;");
145         if (q == NULL) {
146             q = p + strlen(p);
147         }
148         len = q - p;
149
150         for (tagn = 0; tags[tagn].tag != NULL; tagn++)
151         {
152             int  taglen = strlen(tags[tagn].tag);
153
154             if (len == taglen && !memcmp(tags[tagn].tag, p, len) )
155             {
156                 int  flag = tags[tagn].flag;
157                 if (flag == 0) {
158                     sdb_trace_mask = ~0;
159                     return;
160                 }
161                 sdb_trace_mask |= (1 << flag);
162                 break;
163             }
164         }
165         p = q;
166         if (*p)
167             p++;
168     }
169 }
170
171 #if !SDB_HOST
172 /*
173  * Implements SDB tracing inside the emulator.
174  */
175
176 #include <stdarg.h>
177
178 /*
179  * Redefine open and write for qemu_pipe.h that contains inlined references
180  * to those routines. We will redifine them back after qemu_pipe.h inclusion.
181  */
182
183 #undef open
184 #undef write
185 #define open    sdb_open
186 #define write   sdb_write
187 #include "qemu_pipe.h"
188 #undef open
189 #undef write
190 #define open    ___xxx_open
191 #define write   ___xxx_write
192
193 /* A handle to sdb-debug qemud service in the emulator. */
194 int   sdb_debug_qemu = -1;
195
196 /* Initializes connection with the sdb-debug qemud service in the emulator. */
197 #if 0 /* doen't support in Tizen */
198 static int sdb_qemu_trace_init(void)
199 {
200     char con_name[32];
201
202     if (sdb_debug_qemu >= 0) {
203         return 0;
204     }
205
206     /* sdb debugging QEMUD service connection request. */
207     snprintf(con_name, sizeof(con_name), "qemud:sdb-debug");
208     sdb_debug_qemu = qemu_pipe_open(con_name);
209     return (sdb_debug_qemu >= 0) ? 0 : -1;
210 }
211
212 void sdb_qemu_trace(const char* fmt, ...)
213 {
214     va_list args;
215     va_start(args, fmt);
216     char msg[1024];
217
218     if (sdb_debug_qemu >= 0) {
219         vsnprintf(msg, sizeof(msg), fmt, args);
220         sdb_write(sdb_debug_qemu, msg, strlen(msg));
221     }
222 }
223 #endif
224 #endif  /* !SDB_HOST */
225
226 apacket *get_apacket(void)
227 {
228     apacket *p = malloc(sizeof(apacket));
229     if(p == 0) fatal("failed to allocate an apacket");
230     memset(p, 0, sizeof(apacket) - MAX_PAYLOAD);
231     return p;
232 }
233
234 void put_apacket(apacket *p)
235 {
236     if (p != NULL) {
237         free(p);
238         p = NULL;
239     }
240 }
241
242 void handle_online(void)
243 {
244     D("sdb: online\n");
245 }
246
247 void handle_offline(atransport *t)
248 {
249     D("sdb: offline\n");
250     //Close the associated usb
251     run_transport_disconnects(t);
252 }
253
254 #if TRACE_PACKETS
255 #define DUMPMAX 32
256 void print_packet(const char *label, apacket *p)
257 {
258     char *tag;
259     char *x;
260     unsigned count;
261
262     switch(p->msg.command){
263     case A_SYNC: tag = "SYNC"; break;
264     case A_CNXN: tag = "CNXN" ; break;
265     case A_OPEN: tag = "OPEN"; break;
266     case A_OKAY: tag = "OKAY"; break;
267     case A_CLSE: tag = "CLSE"; break;
268     case A_WRTE: tag = "WRTE"; break;
269     default: tag = "????"; break;
270     }
271
272     fprintf(stderr, "%s: %s %08x %08x %04x \"",
273             label, tag, p->msg.arg0, p->msg.arg1, p->msg.data_length);
274     count = p->msg.data_length;
275     x = (char*) p->data;
276     if(count > DUMPMAX) {
277         count = DUMPMAX;
278         tag = "\n";
279     } else {
280         tag = "\"\n";
281     }
282     while(count-- > 0){
283         if((*x >= ' ') && (*x < 127)) {
284             fputc(*x, stderr);
285         } else {
286             fputc('.', stderr);
287         }
288         x++;
289     }
290     fprintf(stderr, tag);
291 }
292 #endif
293
294 static void send_ready(unsigned local, unsigned remote, atransport *t)
295 {
296     D("Calling send_ready \n");
297     apacket *p = get_apacket();
298     p->msg.command = A_OKAY;
299     p->msg.arg0 = local;
300     p->msg.arg1 = remote;
301     send_packet(p, t);
302 }
303
304 static void send_close(unsigned local, unsigned remote, atransport *t)
305 {
306     D("Calling send_close \n");
307     apacket *p = get_apacket();
308     p->msg.command = A_CLSE;
309     p->msg.arg0 = local;
310     p->msg.arg1 = remote;
311     send_packet(p, t);
312 }
313 static int device_status = 0; // 0:online, 1: password locked later
314 static void send_connect(atransport *t)
315 {
316     D("Calling send_connect \n");
317     apacket *cp = get_apacket();
318     cp->msg.command = A_CNXN;
319     cp->msg.arg0 = A_VERSION;
320     cp->msg.arg1 = MAX_PAYLOAD;
321
322     char device_name[256]={0,};
323     int r = 0;
324
325     if (is_emulator()) {
326         r = get_emulator_name(device_name, sizeof device_name);
327     } else {
328         r = get_device_name(device_name, sizeof device_name);
329     }
330     if (r < 0) {
331         snprintf((char*) cp->data, sizeof cp->data, "%s::%s::%d", sdb_device_banner, DEFAULT_DEVICENAME, device_status);
332     } else {
333         snprintf((char*) cp->data, sizeof cp->data, "%s::%s::%d", sdb_device_banner, device_name, device_status);
334     }
335
336     D("CNXN data:%s\n", (char*)cp->data);
337     cp->msg.data_length = strlen((char*) cp->data) + 1;
338
339     send_packet(cp, t);
340 #if SDB_HOST
341         /* XXX why sleep here? */
342     // allow the device some time to respond to the connect message
343     sdb_sleep_ms(1000);
344 #endif
345 }
346
347 static char *connection_state_name(atransport *t)
348 {
349     if (t == NULL) {
350         return "unknown";
351     }
352
353     switch(t->connection_state) {
354     case CS_BOOTLOADER:
355         return "bootloader";
356     case CS_DEVICE:
357         return "device";
358     case CS_OFFLINE:
359         return "offline";
360     default:
361         return "unknown";
362     }
363 }
364
365 static int get_str_cmdline(char *src, char *dest, char str[], int str_size) {
366     char *s = strstr(src, dest);
367     if (s == NULL) {
368         return -1;
369     }
370     char *e = strstr(s, " ");
371     if (e == NULL) {
372         return -1;
373     }
374
375     int len = e-s-strlen(dest);
376
377     if (len >= str_size) {
378         D("buffer size(%d) should be bigger than %d\n", str_size, len+1);
379         return -1;
380     }
381
382     s_strncpy(str, s + strlen(dest), len);
383     return len;
384 }
385
386 int get_emulator_forward_port() {
387     SdbdCommandlineArgs *sdbd_args = &sdbd_commandline_args; /* alias */
388
389     if (sdbd_args->emulator.host == NULL) {
390         return -1;
391     }
392
393     return sdbd_args->emulator.port;
394 }
395
396 int get_emulator_name(char str[], int str_size) {
397     SdbdCommandlineArgs *sdbd_args = &sdbd_commandline_args; /* alias */
398
399     if (sdbd_args->emulator.host == NULL) {
400         return -1;
401     }
402
403     s_strncpy(str, sdbd_args->emulator.host, str_size);
404     return 0;
405 }
406
407 int get_device_name(char str[], int str_size) {
408     char *value = NULL;
409     int r = system_info_get_value_string(SYSTEM_INFO_KEY_MODEL, &value);
410     if (r != SYSTEM_INFO_ERROR_NONE) {
411         D("fail to get system model:%d\n", errno);
412         return -1;
413     } else {
414         s_strncpy(str, value, str_size);
415         D("returns model_name:%s\n", value);
416         if (value != NULL) {
417             free(value);
418         }
419         return 0;
420     }
421     /*
422     int fd = unix_open(USB_SERIAL_PATH, O_RDONLY);
423     if (fd < 0) {
424         D("fail to read:%s (%d)\n", USB_SERIAL_PATH, errno);
425         return -1;
426     }
427
428     if(read_line(fd, str, str_size)) {
429         D("device serial name: %s\n", str);
430         sdb_close(fd);
431         return 0;
432     }
433     sdb_close(fd);
434     */
435     return -1;
436 }
437
438 void parse_banner(char *banner, atransport *t)
439 {
440     char *type, *product, *end;
441
442     D("parse_banner: %s\n", banner);
443     type = banner;
444     product = strchr(type, ':');
445     if(product) {
446         *product++ = 0;
447     } else {
448         product = "";
449     }
450
451         /* remove trailing ':' */
452     end = strchr(product, ':');
453     if(end) *end = 0;
454
455         /* save product name in device structure */
456     if (t->product == NULL) {
457         t->product = strdup(product);
458     } else if (strcmp(product, t->product) != 0) {
459         free(t->product);
460         t->product = strdup(product);
461     }
462
463     if(!strcmp(type, "bootloader")){
464         D("setting connection_state to CS_BOOTLOADER\n");
465         t->connection_state = CS_BOOTLOADER;
466         update_transports();
467         return;
468     }
469
470     if(!strcmp(type, "device")) {
471         D("setting connection_state to CS_DEVICE\n");
472         t->connection_state = CS_DEVICE;
473         update_transports();
474         return;
475     }
476
477     if(!strcmp(type, "recovery")) {
478         D("setting connection_state to CS_RECOVERY\n");
479         t->connection_state = CS_RECOVERY;
480         update_transports();
481         return;
482     }
483
484     if(!strcmp(type, "sideload")) {
485         D("setting connection_state to CS_SIDELOAD\n");
486         t->connection_state = CS_SIDELOAD;
487         update_transports();
488         return;
489     }
490
491     t->connection_state = CS_HOST;
492 }
493
494 void handle_packet(apacket *p, atransport *t)
495 {
496     asocket *s;
497
498     D("handle_packet() %c%c%c%c\n", ((char*) (&(p->msg.command)))[0],
499                 ((char*) (&(p->msg.command)))[1],
500                 ((char*) (&(p->msg.command)))[2],
501                 ((char*) (&(p->msg.command)))[3]);
502
503     print_packet("recv", p);
504
505     switch(p->msg.command){
506     case A_SYNC:
507         if(p->msg.arg0){
508             send_packet(p, t);
509             if(HOST) send_connect(t);
510         } else {
511             t->connection_state = CS_OFFLINE;
512             handle_offline(t);
513             send_packet(p, t);
514         }
515         return;
516
517     case A_CNXN: /* CONNECT(version, maxdata, "system-id-string") */
518             /* XXX verify version, etc */
519         if(t->connection_state != CS_OFFLINE) {
520             t->connection_state = CS_OFFLINE;
521             handle_offline(t);
522         }
523         parse_banner((char*) p->data, t);
524         handle_online();
525         if(!HOST) send_connect(t);
526         break;
527
528     case A_OPEN: /* OPEN(local-id, 0, "destination") */
529         if(t->connection_state != CS_OFFLINE) {
530             char *name = (char*) p->data;
531             name[p->msg.data_length > 0 ? p->msg.data_length - 1 : 0] = 0;
532             s = create_local_service_socket(name);
533             if(s == 0) {
534                 send_close(0, p->msg.arg0, t);
535             } else {
536                 s->peer = create_remote_socket(p->msg.arg0, t);
537                 s->peer->peer = s;
538                 send_ready(s->id, s->peer->id, t);
539                 s->ready(s);
540             }
541         }
542         break;
543
544     case A_OKAY: /* READY(local-id, remote-id, "") */
545         if(t->connection_state != CS_OFFLINE) {
546             if((s = find_local_socket(p->msg.arg1))) {
547                 if(s->peer == 0) {
548                     s->peer = create_remote_socket(p->msg.arg0, t);
549                     s->peer->peer = s;
550                 }
551                 s->ready(s);
552             }
553         }
554         break;
555
556     case A_CLSE: /* CLOSE(local-id, remote-id, "") */
557         if(t->connection_state != CS_OFFLINE) {
558             if((s = find_local_socket(p->msg.arg1))) {
559                 s->close(s);
560             }
561         }
562         break;
563
564     case A_WRTE:
565         if(t->connection_state != CS_OFFLINE) {
566             if((s = find_local_socket(p->msg.arg1))) {
567                 unsigned rid = p->msg.arg0;
568                 p->len = p->msg.data_length;
569
570                 if(s->enqueue(s, p) == 0) {
571                     D("Enqueue the socket\n");
572                     send_ready(s->id, rid, t);
573                 }
574                 return;
575             }
576         }
577         break;
578
579     default:
580         printf("handle_packet: what is %08x?!\n", p->msg.command);
581     }
582
583     put_apacket(p);
584 }
585
586 alistener listener_list = {
587     .next = &listener_list,
588     .prev = &listener_list,
589 };
590
591 static void ss_listener_event_func(int _fd, unsigned ev, void *_l)
592 {
593     asocket *s;
594
595     if(ev & FDE_READ) {
596         struct sockaddr addr;
597         socklen_t alen;
598         int fd;
599
600         alen = sizeof(addr);
601         fd = sdb_socket_accept(_fd, &addr, &alen);
602         if(fd < 0) return;
603
604         sdb_socket_setbufsize(fd, CHUNK_SIZE);
605
606         s = create_local_socket(fd);
607         if(s) {
608             connect_to_smartsocket(s);
609             return;
610         }
611
612         sdb_close(fd);
613     }
614 }
615
616 static void listener_event_func(int _fd, unsigned ev, void *_l)
617 {
618     alistener *l = _l;
619     asocket *s;
620
621     if(ev & FDE_READ) {
622         struct sockaddr addr;
623         socklen_t alen;
624         int fd;
625
626         alen = sizeof(addr);
627         fd = sdb_socket_accept(_fd, &addr, &alen);
628         if(fd < 0) return;
629
630         s = create_local_socket(fd);
631         if(s) {
632             s->transport = l->transport;
633             connect_to_remote(s, l->connect_to);
634             return;
635         }
636
637         sdb_close(fd);
638     }
639 }
640
641 static void  free_listener(alistener*  l)
642 {
643     if (l->next) {
644         l->next->prev = l->prev;
645         l->prev->next = l->next;
646         l->next = l->prev = l;
647     }
648
649     // closes the corresponding fd
650     fdevent_remove(&l->fde);
651
652     if (l->local_name)
653         free((char*)l->local_name);
654
655     if (l->connect_to)
656         free((char*)l->connect_to);
657
658     if (l->transport) {
659         remove_transport_disconnect(l->transport, &l->disconnect);
660     }
661     free(l);
662 }
663
664 static void listener_disconnect(void*  _l, atransport*  t)
665 {
666     alistener*  l = _l;
667
668     free_listener(l);
669 }
670
671 int local_name_to_fd(const char *name)
672 {
673     int port;
674
675     if(!strncmp("tcp:", name, 4)){
676         int  ret;
677         port = atoi(name + 4);
678         ret = socket_loopback_server(port, SOCK_STREAM);
679         return ret;
680     }
681 #ifndef HAVE_WIN32_IPC  /* no Unix-domain sockets on Win32 */
682     // It's non-sensical to support the "reserved" space on the sdb host side
683     if(!strncmp(name, "local:", 6)) {
684         return socket_local_server(name + 6,
685                 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
686     } else if(!strncmp(name, "localabstract:", 14)) {
687         return socket_local_server(name + 14,
688                 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
689     } else if(!strncmp(name, "localfilesystem:", 16)) {
690         return socket_local_server(name + 16,
691                 ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
692     }
693
694 #endif
695     printf("unknown local portname '%s'\n", name);
696     return -1;
697 }
698
699 static int remove_listener(const char *local_name, const char *connect_to, atransport* transport)
700 {
701     alistener *l;
702
703     for (l = listener_list.next; l != &listener_list; l = l->next) {
704         if (!strcmp(local_name, l->local_name) &&
705             !strcmp(connect_to, l->connect_to) &&
706             l->transport && l->transport == transport) {
707
708             listener_disconnect(l, transport);
709             return 0;
710         }
711     }
712
713     return -1;
714 }
715
716 static int install_listener(const char *local_name, const char *connect_to, atransport* transport)
717 {
718     alistener *l;
719
720     //printf("install_listener('%s','%s')\n", local_name, connect_to);
721
722     for(l = listener_list.next; l != &listener_list; l = l->next){
723         if(strcmp(local_name, l->local_name) == 0) {
724             char *cto;
725
726                 /* can't repurpose a smartsocket */
727             if(l->connect_to[0] == '*') {
728                 return -1;
729             }
730
731             cto = strdup(connect_to);
732             if(cto == 0) {
733                 return -1;
734             }
735
736             //printf("rebinding '%s' to '%s'\n", local_name, connect_to);
737             free((void*) l->connect_to);
738             l->connect_to = cto;
739             if (l->transport != transport) {
740                 remove_transport_disconnect(l->transport, &l->disconnect);
741                 l->transport = transport;
742                 add_transport_disconnect(l->transport, &l->disconnect);
743             }
744             return 0;
745         }
746     }
747
748     if((l = calloc(1, sizeof(alistener))) == 0) goto nomem;
749     if((l->local_name = strdup(local_name)) == 0) goto nomem;
750     if((l->connect_to = strdup(connect_to)) == 0) goto nomem;
751
752
753     l->fd = local_name_to_fd(local_name);
754     if(l->fd < 0) {
755         free((void*) l->local_name);
756         free((void*) l->connect_to);
757         free(l);
758         printf("cannot bind '%s'\n", local_name);
759         return -2;
760     }
761
762     if (close_on_exec(l->fd) < 0) {
763         D("fail to close fd exec:%d\n",l->fd);
764     }
765     if(!strcmp(l->connect_to, "*smartsocket*")) {
766         fdevent_install(&l->fde, l->fd, ss_listener_event_func, l);
767     } else {
768         fdevent_install(&l->fde, l->fd, listener_event_func, l);
769     }
770     fdevent_set(&l->fde, FDE_READ);
771
772     l->next = &listener_list;
773     l->prev = listener_list.prev;
774     l->next->prev = l;
775     l->prev->next = l;
776     l->transport = transport;
777
778     if (transport) {
779         l->disconnect.opaque = l;
780         l->disconnect.func   = listener_disconnect;
781         add_transport_disconnect(transport, &l->disconnect);
782     }
783     return 0;
784
785 nomem:
786     fatal("cannot allocate listener");
787     return 0;
788 }
789
790 #ifdef HAVE_WIN32_PROC
791 static BOOL WINAPI ctrlc_handler(DWORD type)
792 {
793     exit(STATUS_CONTROL_C_EXIT);
794     return TRUE;
795 }
796 #endif
797
798 static void sdb_cleanup(void)
799 {
800     clear_sdbd_commandline_args(&sdbd_commandline_args);
801     usb_cleanup();
802 //    if(required_pid > 0) {
803 //        kill(required_pid, SIGKILL);
804 //    }
805 }
806
807 void start_logging(void)
808 {
809 #ifdef HAVE_WIN32_PROC
810     char    temp[ MAX_PATH ];
811     FILE*   fnul;
812     FILE*   flog;
813
814     GetTempPath( sizeof(temp) - 8, temp );
815     strcat( temp, "sdb.log" );
816
817     /* Win32 specific redirections */
818     fnul = fopen( "NUL", "rt" );
819     if (fnul != NULL)
820         stdin[0] = fnul[0];
821
822     flog = fopen( temp, "at" );
823     if (flog == NULL)
824         flog = fnul;
825
826     setvbuf( flog, NULL, _IONBF, 0 );
827
828     stdout[0] = flog[0];
829     stderr[0] = flog[0];
830     fprintf(stderr,"--- sdb starting (pid %d) ---\n", getpid());
831 #else
832     int fd;
833
834     fd = unix_open("/dev/null", O_RDONLY);
835     if (fd < 0) {
836         // hopefully not gonna happen
837         return;
838     }
839     dup2(fd, 0);
840     sdb_close(fd);
841
842     fd = unix_open("/tmp/sdb.log", O_WRONLY | O_CREAT | O_APPEND, 0640);
843     if(fd < 0) {
844         fd = unix_open("/dev/null", O_WRONLY);
845         if (fd < 0) {
846             // hopefully not gonna happen
847             return;
848         }
849     }
850     dup2(fd, 1);
851     dup2(fd, 2);
852     sdb_close(fd);
853     fprintf(stderr,"--- sdb starting (pid %d) ---\n", getpid());
854 #endif
855 }
856
857 #if !SDB_HOST
858 void start_device_log(void)
859 {
860     int fd;
861     char    path[PATH_MAX];
862     struct tm now;
863     time_t t;
864 //    char value[PROPERTY_VALUE_MAX];
865     const char* p = getenv("SDB_TRACE");
866     // read the trace mask from persistent property persist.sdb.trace_mask
867     // give up if the property is not set or cannot be parsed
868 #if 0 /* tizen specific */
869     property_get("persist.sdb.trace_mask", value, "");
870     if (sscanf(value, "%x", &sdb_trace_mask) != 1)
871         return;
872 #endif
873
874     if (p == NULL) {
875         return;
876     }
877     tzset();
878     time(&t);
879     localtime_r(&t, &now);
880     strftime(path, sizeof(path),
881                 "/tmp/sdbd-%Y-%m-%d-%H-%M-%S.txt",
882                 &now);
883     fd = unix_open(path, O_WRONLY | O_CREAT | O_TRUNC, 0640);
884     if (fd < 0) {
885         return;
886     }
887
888     // redirect stdout and stderr to the log file
889     dup2(fd, 1);
890     dup2(fd, 2);
891     fprintf(stderr,"--- sdbd starting (pid %d) ---\n", getpid());
892     sdb_close(fd);
893
894     fd = unix_open("/dev/null", O_RDONLY);
895     if (fd < 0) {
896         // hopefully not gonna happen
897         return;
898     }
899     dup2(fd, 0);
900     sdb_close(fd);
901 }
902
903 int daemonize(void) {
904
905     // set file creation mask to 0
906     umask(0);
907
908     switch (fork()) {
909     case -1:
910         return -1;
911     case 0:
912         break;
913     default:
914         _exit(0);
915     }
916 #ifdef SDB_PIDPATH
917     FILE *f = fopen(SDB_PIDPATH, "w");
918
919     if (f != NULL) {
920         fprintf(f, "%d\n", getpid());
921         fclose(f);
922     }
923 #endif
924     if (setsid() == -1)
925         return -1;
926
927     if (chdir("/") < 0)
928         D("sdbd: unable to change working directory to /\n");
929
930     return 0;
931 }
932 #endif
933
934 #if SDB_HOST
935 int launch_server(int server_port)
936 {
937 #ifdef HAVE_WIN32_PROC
938     /* we need to start the server in the background                    */
939     /* we create a PIPE that will be used to wait for the server's "OK" */
940     /* message since the pipe handles must be inheritable, we use a     */
941     /* security attribute                                               */
942     HANDLE                pipe_read, pipe_write;
943     SECURITY_ATTRIBUTES   sa;
944     STARTUPINFO           startup;
945     PROCESS_INFORMATION   pinfo;
946     char                  program_path[ MAX_PATH ];
947     int                   ret;
948
949     sa.nLength = sizeof(sa);
950     sa.lpSecurityDescriptor = NULL;
951     sa.bInheritHandle = TRUE;
952
953     /* create pipe, and ensure its read handle isn't inheritable */
954     ret = CreatePipe( &pipe_read, &pipe_write, &sa, 0 );
955     if (!ret) {
956         fprintf(stderr, "CreatePipe() failure, error %ld\n", GetLastError() );
957         return -1;
958     }
959
960     SetHandleInformation( pipe_read, HANDLE_FLAG_INHERIT, 0 );
961
962     ZeroMemory( &startup, sizeof(startup) );
963     startup.cb = sizeof(startup);
964     startup.hStdInput  = GetStdHandle( STD_INPUT_HANDLE );
965     startup.hStdOutput = pipe_write;
966     startup.hStdError  = GetStdHandle( STD_ERROR_HANDLE );
967     startup.dwFlags    = STARTF_USESTDHANDLES;
968
969     ZeroMemory( &pinfo, sizeof(pinfo) );
970
971     /* get path of current program */
972     GetModuleFileName( NULL, program_path, sizeof(program_path) );
973
974     ret = CreateProcess(
975             program_path,                              /* program path  */
976             "sdb fork-server server",
977                                     /* the fork-server argument will set the
978                                        debug = 2 in the child           */
979             NULL,                   /* process handle is not inheritable */
980             NULL,                    /* thread handle is not inheritable */
981             TRUE,                          /* yes, inherit some handles */
982             DETACHED_PROCESS, /* the new process doesn't have a console */
983             NULL,                     /* use parent's environment block */
984             NULL,                    /* use parent's starting directory */
985             &startup,                 /* startup info, i.e. std handles */
986             &pinfo );
987
988     CloseHandle( pipe_write );
989
990     if (!ret) {
991         fprintf(stderr, "CreateProcess failure, error %ld\n", GetLastError() );
992         CloseHandle( pipe_read );
993         return -1;
994     }
995
996     CloseHandle( pinfo.hProcess );
997     CloseHandle( pinfo.hThread );
998
999     /* wait for the "OK\n" message */
1000     {
1001         char  temp[3];
1002         DWORD  count;
1003
1004         ret = ReadFile( pipe_read, temp, 3, &count, NULL );
1005         CloseHandle( pipe_read );
1006         if ( !ret ) {
1007             fprintf(stderr, "could not read ok from SDB Server, error = %ld\n", GetLastError() );
1008             return -1;
1009         }
1010         if (count != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
1011             fprintf(stderr, "SDB server didn't ACK\n" );
1012             return -1;
1013         }
1014     }
1015 #elif defined(HAVE_FORKEXEC)
1016     char    path[PATH_MAX];
1017     int     fd[2];
1018
1019     // set up a pipe so the child can tell us when it is ready.
1020     // fd[0] will be parent's end, and fd[1] will get mapped to stderr in the child.
1021     if (pipe(fd)) {
1022         fprintf(stderr, "pipe failed in launch_server, errno: %d\n", errno);
1023         return -1;
1024     }
1025     get_my_path(path, PATH_MAX);
1026     pid_t pid = fork();
1027     if(pid < 0) return -1;
1028
1029     if (pid == 0) {
1030         // child side of the fork
1031
1032         // redirect stderr to the pipe
1033         // we use stderr instead of stdout due to stdout's buffering behavior.
1034         sdb_close(fd[0]);
1035         dup2(fd[1], STDERR_FILENO);
1036         sdb_close(fd[1]);
1037
1038         // child process
1039         int result = execl(path, "sdb", "fork-server", "server", NULL);
1040         // this should not return
1041         fprintf(stderr, "OOPS! execl returned %d, errno: %d\n", result, errno);
1042     } else  {
1043         // parent side of the fork
1044
1045         char  temp[3];
1046
1047         temp[0] = 'A'; temp[1] = 'B'; temp[2] = 'C';
1048         // wait for the "OK\n" message
1049         sdb_close(fd[1]);
1050         int ret = sdb_read(fd[0], temp, 3);
1051         int saved_errno = errno;
1052         sdb_close(fd[0]);
1053         if (ret < 0) {
1054             fprintf(stderr, "could not read ok from SDB Server, errno = %d\n", saved_errno);
1055             return -1;
1056         }
1057         if (ret != 3 || temp[0] != 'O' || temp[1] != 'K' || temp[2] != '\n') {
1058             fprintf(stderr, "SDB server didn't ACK\n" );
1059             return -1;
1060         }
1061
1062         setsid();
1063     }
1064 #else
1065 #error "cannot implement background server start on this platform"
1066 #endif
1067     return 0;
1068 }
1069 #endif
1070
1071 /* Constructs a local name of form tcp:port.
1072  * target_str points to the target string, it's content will be overwritten.
1073  * target_size is the capacity of the target string.
1074  * server_port is the port number to use for the local name.
1075  */
1076 void build_local_name(char* target_str, size_t target_size, int server_port)
1077 {
1078   snprintf(target_str, target_size, "tcp:%d", server_port);
1079 }
1080
1081 #if !SDB_HOST
1082 static void init_drop_privileges() {
1083 #ifdef _DROP_PRIVILEGE
1084     rootshell_mode = 0;
1085 #else
1086     rootshell_mode = 1;
1087 #endif
1088 }
1089
1090 int should_drop_privileges() {
1091     if (rootshell_mode == 1) { // if root, then don't drop
1092         return 0;
1093     }
1094     return 1;
1095 }
1096
1097 int set_developer_privileges() {
1098     gid_t groups[] = { SID_DEVELOPER, SID_APP_LOGGING, SID_SYS_LOGGING, SID_INPUT };
1099     if (setgroups(sizeof(groups) / sizeof(groups[0]), groups) != 0) {
1100         D("set groups failed (errno: %d, %s)\n", errno, strerror(errno));
1101     }
1102
1103     // then switch user and group to developer
1104     if (setgid(SID_DEVELOPER) != 0) {
1105         D("set group id failed (errno: %d, %s)\n", errno, strerror(errno));
1106         return -1;
1107     }
1108
1109     if (setuid(SID_DEVELOPER) != 0) {
1110         D("set user id failed (errno: %d, %s)\n", errno, strerror(errno));
1111         return -1;
1112     }
1113
1114     if (chdir(HOME_DEV_PATH) < 0) {
1115         D("sdbd: unable to change working directory to %s\n", HOME_DEV_PATH);
1116     } else {
1117         if (chdir("/") < 0) {
1118             D("sdbd: unable to change working directory to /\n");
1119         }
1120     }
1121     // TODO: use pam later
1122     char * env = "HOME=";
1123     strcat(env, HOME_DEV_PATH);
1124     putenv(env);
1125
1126     return 1;
1127 }
1128 #define ONDEMAND_ROOT_PATH tzplatform_getenv(TZ_SDK_HOME)
1129
1130 static void init_sdk_requirements() {
1131     struct stat st;
1132
1133     // set env variable for temporary
1134     // TODO: should use pam instead later!!
1135     if (!getenv("TERM")) {
1136         putenv("TERM=linux");
1137     }
1138
1139     if (!getenv("HOME")) {
1140         putenv("HOME=/root");
1141     }
1142
1143     if (stat(ONDEMAND_ROOT_PATH, &st) == -1) {
1144         return;
1145     }
1146     if (st.st_uid != SID_DEVELOPER || st.st_gid != SID_DEVELOPER) {
1147         char cmd[128];
1148         snprintf(cmd, sizeof(cmd), "chown %s:%s %s -R", DEV_NAME, DEV_NAME, ONDEMAND_ROOT_PATH);
1149         if (system(cmd) < 0) {
1150             D("failed to change ownership to developer to %s\n", ONDEMAND_ROOT_PATH);
1151         }
1152     }
1153
1154 }
1155 #endif /* !SDB_HOST */
1156
1157 int sdb_main(int is_daemon, int server_port)
1158 {
1159 #if !SDB_HOST
1160     init_drop_privileges();
1161     init_sdk_requirements();
1162     umask(000);
1163 #endif
1164
1165     atexit(sdb_cleanup);
1166 #ifdef HAVE_WIN32_PROC
1167     SetConsoleCtrlHandler( ctrlc_handler, TRUE );
1168 #elif defined(HAVE_FORKEXEC)
1169     // No SIGCHLD. Let the service subproc handle its children.
1170     signal(SIGPIPE, SIG_IGN);
1171 #endif
1172
1173     init_transport_registration();
1174
1175
1176 #if SDB_HOST
1177     HOST = 1;
1178     usb_vendors_init();
1179     usb_init();
1180     local_init(DEFAULT_SDB_LOCAL_TRANSPORT_PORT);
1181
1182     char local_name[30];
1183     build_local_name(local_name, sizeof(local_name), server_port);
1184     if(install_listener(local_name, "*smartsocket*", NULL)) {
1185         exit(1);
1186     }
1187 #else
1188     /* don't listen on a port (default 5037) if running in secure mode */
1189     /* don't run as root if we are running in secure mode */
1190
1191     if (should_drop_privileges()) {
1192 # if 0
1193         struct __user_cap_header_struct header;
1194         struct __user_cap_data_struct cap;
1195
1196         if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
1197             exit(1);
1198         }
1199         /* add extra groups:
1200         ** SID_TTY to access /dev/ptmx
1201         */
1202         gid_t groups[] = { SID_TTY, SID_APP_LOGGING, SID_SYS_LOGGING };
1203         if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
1204             exit(1);
1205         }
1206         /* then switch user and group to "developer" */
1207         if (setgid(SID_DEVELOPER) != 0) {
1208             fprintf(stderr, "set group id failed errno: %d\n", errno);
1209             exit(1);
1210         }
1211         if (setuid(SID_DEVELOPER) != 0) {
1212             fprintf(stderr, "set user id failed errno: %d\n", errno);
1213             exit(1);
1214         }
1215
1216         /* set CAP_SYS_BOOT capability, so "sdb reboot" will succeed */
1217         header.version = _LINUX_CAPABILITY_VERSION;
1218         header.pid = 0;
1219         cap.effective = cap.permitted = (1 << CAP_SYS_BOOT);
1220         cap.inheritable = 0;
1221         capset(&header, &cap);
1222 #endif
1223         D("Local port disabled\n");
1224     } else {
1225         char local_name[30];
1226         build_local_name(local_name, sizeof(local_name), server_port);
1227         if(install_listener(local_name, "*smartsocket*", NULL)) {
1228             exit(1);
1229         }
1230     }
1231
1232     if (!is_emulator()) {
1233         // listen on USB
1234         usb_init();
1235     }
1236
1237     /* by default don't listen on local transport but
1238      * listen if suitable command line argument has been provided */
1239     if (sdbd_commandline_args.sdbd_port >= 0) {
1240         local_init(sdbd_commandline_args.sdbd_port);
1241     }
1242
1243 #if 0 /* tizen specific */
1244     D("sdb_main(): pre init_jdwp()\n");
1245     init_jdwp();
1246     D("sdb_main(): post init_jdwp()\n");
1247 #endif
1248 #endif
1249
1250     if (is_daemon)
1251     {
1252         // inform our parent that we are up and running.
1253 #ifdef HAVE_WIN32_PROC
1254         DWORD  count;
1255         WriteFile( GetStdHandle( STD_OUTPUT_HANDLE ), "OK\n", 3, &count, NULL );
1256 #elif defined(HAVE_FORKEXEC)
1257         fprintf(stderr, "OK\n");
1258 #endif
1259         start_logging();
1260     }
1261
1262     D("Event loop starting\n");
1263
1264     fdevent_loop();
1265
1266     usb_cleanup();
1267
1268     return 0;
1269 }
1270
1271 #if SDB_HOST
1272 void connect_device(char* host, char* buffer, int buffer_size)
1273 {
1274     int port, fd;
1275     char* portstr = strchr(host, ':');
1276     char hostbuf[100];
1277     char serial[100];
1278
1279     strncpy(hostbuf, host, sizeof(hostbuf) - 1);
1280     if (portstr) {
1281         if (portstr - host >= sizeof(hostbuf)) {
1282             snprintf(buffer, buffer_size, "bad host name %s", host);
1283             return;
1284         }
1285         // zero terminate the host at the point we found the colon
1286         hostbuf[portstr - host] = 0;
1287         if (sscanf(portstr + 1, "%d", &port) == 0) {
1288             snprintf(buffer, buffer_size, "bad port number %s", portstr);
1289             return;
1290         }
1291     } else {
1292         port = DEFAULT_SDB_LOCAL_TRANSPORT_PORT;
1293     }
1294
1295     snprintf(serial, sizeof(serial), "%s:%d", hostbuf, port);
1296     if (find_transport(serial)) {
1297         snprintf(buffer, buffer_size, "already connected to %s", serial);
1298         return;
1299     }
1300
1301     fd = socket_network_client(hostbuf, port, SOCK_STREAM);
1302     if (fd < 0) {
1303         snprintf(buffer, buffer_size, "unable to connect to %s", host);
1304         return;
1305     }
1306
1307     D("client: connected on remote on fd %d\n", fd);
1308     close_on_exec(fd);
1309     disable_tcp_nagle(fd);
1310     register_socket_transport(fd, serial, port, 0, NULL);
1311     snprintf(buffer, buffer_size, "connected to %s", serial);
1312 }
1313
1314 void connect_emulator(char* port_spec, char* buffer, int buffer_size)
1315 {
1316     char* port_separator = strchr(port_spec, ',');
1317     if (!port_separator) {
1318         snprintf(buffer, buffer_size,
1319                 "unable to parse '%s' as <console port>,<sdb port>",
1320                 port_spec);
1321         return;
1322     }
1323
1324     // Zero-terminate console port and make port_separator point to 2nd port.
1325     *port_separator++ = 0;
1326     int console_port = strtol(port_spec, NULL, 0);
1327     int sdb_port = strtol(port_separator, NULL, 0);
1328     if (!(console_port > 0 && sdb_port > 0)) {
1329         *(port_separator - 1) = ',';
1330         snprintf(buffer, buffer_size,
1331                 "Invalid port numbers: Expected positive numbers, got '%s'",
1332                 port_spec);
1333         return;
1334     }
1335
1336     /* Check if the emulator is already known.
1337      * Note: There's a small but harmless race condition here: An emulator not
1338      * present just yet could be registered by another invocation right
1339      * after doing this check here. However, local_connect protects
1340      * against double-registration too. From here, a better error message
1341      * can be produced. In the case of the race condition, the very specific
1342      * error message won't be shown, but the data doesn't get corrupted. */
1343     atransport* known_emulator = find_emulator_transport_by_sdb_port(sdb_port);
1344     if (known_emulator != NULL) {
1345         snprintf(buffer, buffer_size,
1346                 "Emulator on port %d already registered.", sdb_port);
1347         return;
1348     }
1349
1350     /* Check if more emulators can be registered. Similar unproblematic
1351      * race condition as above. */
1352     int candidate_slot = get_available_local_transport_index();
1353     if (candidate_slot < 0) {
1354         snprintf(buffer, buffer_size, "Cannot accept more emulators.");
1355         return;
1356     }
1357
1358     /* Preconditions met, try to connect to the emulator. */
1359     if (!local_connect_arbitrary_ports(console_port, sdb_port, NULL)) {
1360         snprintf(buffer, buffer_size,
1361                 "Connected to emulator on ports %d,%d", console_port, sdb_port);
1362     } else {
1363         snprintf(buffer, buffer_size,
1364                 "Could not connect to emulator on ports %d,%d",
1365                 console_port, sdb_port);
1366     }
1367 }
1368 #endif
1369
1370 int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s)
1371 {
1372     atransport *transport = NULL;
1373     char buf[4096];
1374
1375     if(!strcmp(service, "kill")) {
1376         fprintf(stderr,"sdb server killed by remote request\n");
1377         fflush(stdout);
1378         sdb_write(reply_fd, "OKAY", 4);
1379         usb_cleanup();
1380         exit(0);
1381     }
1382
1383 #if SDB_HOST
1384     // "transport:" is used for switching transport with a specified serial number
1385     // "transport-usb:" is used for switching transport to the only USB transport
1386     // "transport-local:" is used for switching transport to the only local transport
1387     // "transport-any:" is used for switching transport to the only transport
1388     if (!strncmp(service, "transport", strlen("transport"))) {
1389         char* error_string = "unknown failure";
1390         transport_type type = kTransportAny;
1391
1392         if (!strncmp(service, "transport-usb", strlen("transport-usb"))) {
1393             type = kTransportUsb;
1394         } else if (!strncmp(service, "transport-local", strlen("transport-local"))) {
1395             type = kTransportLocal;
1396         } else if (!strncmp(service, "transport-any", strlen("transport-any"))) {
1397             type = kTransportAny;
1398         } else if (!strncmp(service, "transport:", strlen("transport:"))) {
1399             service += strlen("transport:");
1400             serial = service;
1401         }
1402
1403         transport = acquire_one_transport(CS_ANY, type, serial, &error_string);
1404
1405         if (transport) {
1406             s->transport = transport;
1407             sdb_write(reply_fd, "OKAY", 4);
1408         } else {
1409             sendfailmsg(reply_fd, error_string);
1410         }
1411         return 1;
1412     }
1413
1414     // return a list of all connected devices
1415     if (!strcmp(service, "devices")) {
1416         char buffer[4096];
1417         memset(buf, 0, sizeof(buf));
1418         memset(buffer, 0, sizeof(buffer));
1419         D("Getting device list \n");
1420         list_transports(buffer, sizeof(buffer));
1421         snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer),buffer);
1422         D("Wrote device list \n");
1423         writex(reply_fd, buf, strlen(buf));
1424         return 0;
1425     }
1426
1427     // add a new TCP transport, device or emulator
1428     if (!strncmp(service, "connect:", 8)) {
1429         char buffer[4096];
1430         char* host = service + 8;
1431         if (!strncmp(host, "emu:", 4)) {
1432             connect_emulator(host + 4, buffer, sizeof(buffer));
1433         } else {
1434             connect_device(host, buffer, sizeof(buffer));
1435         }
1436         // Send response for emulator and device
1437         snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
1438         writex(reply_fd, buf, strlen(buf));
1439         return 0;
1440     }
1441
1442     // remove TCP transport
1443     if (!strncmp(service, "disconnect:", 11)) {
1444         char buffer[4096];
1445         memset(buffer, 0, sizeof(buffer));
1446         char* serial = service + 11;
1447         if (serial[0] == 0) {
1448             // disconnect from all TCP devices
1449             unregister_all_tcp_transports();
1450         } else {
1451             char hostbuf[100];
1452             // assume port 26101 if no port is specified
1453             if (!strchr(serial, ':')) {
1454                 snprintf(hostbuf, sizeof(hostbuf) - 1, "%s:26101", serial);
1455                 serial = hostbuf;
1456             }
1457             atransport *t = find_transport(serial);
1458
1459             if (t) {
1460                 unregister_transport(t);
1461             } else {
1462                 snprintf(buffer, sizeof(buffer), "No such device %s", serial);
1463             }
1464         }
1465
1466         snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer);
1467         writex(reply_fd, buf, strlen(buf));
1468         return 0;
1469     }
1470
1471     // returns our value for SDB_SERVER_VERSION
1472     if (!strcmp(service, "version")) {
1473         char version[12];
1474         snprintf(version, sizeof version, "%04x", SDB_SERVER_VERSION);
1475         snprintf(buf, sizeof buf, "OKAY%04x%s", (unsigned)strlen(version), version);
1476         writex(reply_fd, buf, strlen(buf));
1477         return 0;
1478     }
1479
1480     if(!strncmp(service,"get-serialno",strlen("get-serialno"))) {
1481         char *out = "unknown";
1482          transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1483        if (transport && transport->serial) {
1484             out = transport->serial;
1485         }
1486         snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(out),out);
1487         writex(reply_fd, buf, strlen(buf));
1488         return 0;
1489     }
1490     // indicates a new emulator instance has started
1491        if (!strncmp(service,"emulator:",9)) { /* tizen specific */
1492            char *tmp = strtok(service+9, DEVICEMAP_SEPARATOR);
1493            int  port = 0;
1494
1495            if (tmp == NULL) {
1496                port = atoi(service+9);
1497            } else {
1498                port = atoi(tmp);
1499                tmp = strtok(NULL, DEVICEMAP_SEPARATOR);
1500                if (tmp != NULL) {
1501                    local_connect(port, tmp);
1502                }
1503            }
1504            local_connect(port, NULL);
1505         return 0;
1506     }
1507 #endif // SDB_HOST
1508
1509     if(!strncmp(service,"forward:",8) || !strncmp(service,"killforward:",12)) {
1510         char *local, *remote, *err;
1511         int r;
1512         atransport *transport;
1513
1514         int createForward = strncmp(service,"kill",4);
1515
1516         local = service + (createForward ? 8 : 12);
1517         remote = strchr(local,';');
1518         if(remote == 0) {
1519             sendfailmsg(reply_fd, "malformed forward spec");
1520             return 0;
1521         }
1522
1523         *remote++ = 0;
1524         if((local[0] == 0) || (remote[0] == 0) || (remote[0] == '*')){
1525             sendfailmsg(reply_fd, "malformed forward spec");
1526             return 0;
1527         }
1528
1529         transport = acquire_one_transport(CS_ANY, ttype, serial, &err);
1530         if (!transport) {
1531             sendfailmsg(reply_fd, err);
1532             return 0;
1533         }
1534
1535         if (createForward) {
1536             r = install_listener(local, remote, transport);
1537         } else {
1538             r = remove_listener(local, remote, transport);
1539         }
1540         if(r == 0) {
1541                 /* 1st OKAY is connect, 2nd OKAY is status */
1542             writex(reply_fd, "OKAYOKAY", 8);
1543             return 0;
1544         }
1545
1546         if (createForward) {
1547             sendfailmsg(reply_fd, (r == -1) ? "cannot rebind smartsocket" : "cannot bind socket");
1548         } else {
1549             sendfailmsg(reply_fd, "cannot remove listener");
1550         }
1551         return 0;
1552     }
1553
1554     if(!strncmp(service,"get-state",strlen("get-state"))) {
1555         transport = acquire_one_transport(CS_ANY, ttype, serial, NULL);
1556         char *state = connection_state_name(transport);
1557         snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(state),state);
1558         writex(reply_fd, buf, strlen(buf));
1559         return 0;
1560     }
1561     return -1;
1562 }
1563
1564 #if !SDB_HOST
1565 int recovery_mode = 0;
1566 #endif
1567
1568 int main(int argc, char **argv)
1569 {
1570     sdb_trace_init(); /* tizen specific */
1571 #if SDB_HOST
1572     sdb_sysdeps_init();
1573     sdb_trace_init();
1574     return sdb_commandline(argc - 1, argv + 1);
1575 #else
1576     /* If sdbd runs inside the emulator this will enable sdb tracing via
1577      * sdb-debug qemud service in the emulator. */
1578 #if 0 /* tizen specific */
1579     sdb_qemu_trace_init();
1580     if((argc > 1) && (!strcmp(argv[1],"recovery"))) {
1581         sdb_device_banner = "recovery";
1582         recovery_mode = 1;
1583     }
1584 #endif
1585
1586     apply_sdbd_commandline_defaults(&sdbd_commandline_args);
1587     int parse_ret = parse_sdbd_commandline(&sdbd_commandline_args, argc, argv);
1588
1589     // TODO: Add detailed error messages
1590     // TODO: Add individual messages for help and usage
1591     if(parse_ret != SDBD_COMMANDLINE_SUCCESS) {
1592         if (parse_ret == SDBD_COMMANDLINE_HELP
1593                 || parse_ret == SDBD_COMMANDLINE_USAGE) {
1594             // User requested help or usage
1595             print_sdbd_usage_message(stdout);
1596             return EXIT_SUCCESS;
1597         }
1598
1599         // Print usage message because of invalid options
1600         print_sdbd_usage_message(stderr);
1601         return EXIT_FAILURE;
1602     }
1603
1604 #if !SDB_HOST
1605     if (daemonize() < 0)
1606         fatal("daemonize() failed: %.200s", strerror(errno));
1607 #endif
1608
1609     start_device_log();
1610     D("Handling main()\n");
1611
1612     //sdbd will never die on emulator!
1613     signal(SIGTERM, handle_sig_term); /* tizen specific */
1614     return sdb_main(0, DEFAULT_SDB_PORT);
1615 #endif
1616 }