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