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