Add the can_launch member to capability structure.
[sdk/target/sdbd.git] / src / services.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 #include <stdlib.h>
18 #include <stdio.h>
19 #include <unistd.h>
20 #include <string.h>
21 #include <errno.h>
22 #include <grp.h>
23
24 #include "sysdeps.h"
25
26 #define  TRACE_TAG  TRACE_SERVICES
27 #include "sdb.h"
28 #include "file_sync_service.h"
29
30 #if SDB_HOST
31 #  ifndef HAVE_WINSOCK
32 #    include <netinet/in.h>
33 #    include <netdb.h>
34 #    include <sys/ioctl.h>
35 #  endif
36 #else
37 #   include <sys/inotify.h>
38 #   include "sdktools.h"
39 #endif
40
41 #include "strutils.h"
42 #include "utils.h"
43 #include <system_info.h>
44 #include <tzplatform_config.h>
45
46 #include <vconf.h>
47 #include <limits.h>
48
49 #include <termios.h>
50 #include <sys/ioctl.h>
51
52 typedef struct stinfo stinfo;
53
54 struct stinfo {
55     void (*func)(int fd, void *cookie);
56     int fd;
57     void *cookie;
58 };
59
60 void *service_bootstrap_func(void *x)
61 {
62     stinfo *sti = x;
63     sti->func(sti->fd, sti->cookie);
64     free(sti);
65     return 0;
66 }
67
68 #if SDB_HOST
69 SDB_MUTEX_DEFINE( dns_lock );
70
71 static void dns_service(int fd, void *cookie)
72 {
73     char *hostname = cookie;
74     struct hostent *hp;
75     unsigned zero = 0;
76
77     sdb_mutex_lock(&dns_lock);
78     hp = gethostbyname(hostname);
79     free(cookie);
80     if(hp == 0) {
81         writex(fd, &zero, 4);
82     } else {
83         writex(fd, hp->h_addr, 4);
84     }
85     sdb_mutex_unlock(&dns_lock);
86     sdb_close(fd);
87 }
88 #else
89
90 static int is_support_interactive_shell()
91 {
92     return (!strncmp(g_capabilities.intershell_support, SDBD_CAP_RET_ENABLED, strlen(SDBD_CAP_RET_ENABLED)));
93 }
94
95 #if 0
96 extern int recovery_mode;
97
98 static void recover_service(int s, void *cookie)
99 {
100     unsigned char buf[4096];
101     unsigned count = (unsigned) cookie;
102     int fd;
103
104     fd = sdb_creat("/tmp/update", 0644);
105     if(fd < 0) {
106         sdb_close(s);
107         return;
108     }
109
110     while(count > 0) {
111         unsigned xfer = (count > 4096) ? 4096 : count;
112         if(readx(s, buf, xfer)) break;
113         if(writex(fd, buf, xfer)) break;
114         count -= xfer;
115     }
116
117     if(count == 0) {
118         writex(s, "OKAY", 4);
119     } else {
120         writex(s, "FAIL", 4);
121     }
122     sdb_close(fd);
123     sdb_close(s);
124
125     fd = sdb_creat("/tmp/update.begin", 0644);
126     sdb_close(fd);
127 }
128
129 void restart_root_service(int fd, void *cookie)
130 {
131     char buf[100];
132     char value[PROPERTY_VALUE_MAX];
133
134     if (getuid() == 0) {
135         snprintf(buf, sizeof(buf), "sdbd is already running as root\n");
136         writex(fd, buf, strlen(buf));
137         sdb_close(fd);
138     } else {
139         property_get("ro.debuggable", value, "");
140         if (strcmp(value, "1") != 0) {
141             snprintf(buf, sizeof(buf), "sdbd cannot run as root in production builds\n");
142             writex(fd, buf, strlen(buf));
143             sdb_close(fd);
144             return;
145         }
146
147         property_set("service.sdb.root", "1");
148         snprintf(buf, sizeof(buf), "restarting sdbd as root\n");
149         writex(fd, buf, strlen(buf));
150         sdb_close(fd);
151     }
152 }
153 #endif
154
155 void restart_tcp_service(int fd, void *cookie)
156 {
157     char buf[100];
158     char value[PROPERTY_VALUE_MAX];
159     int port = (int)cookie;
160
161     if (port <= 0) {
162         snprintf(buf, sizeof(buf), "invalid port\n");
163         writex(fd, buf, strlen(buf));
164         sdb_close(fd);
165         return;
166     }
167
168     snprintf(value, sizeof(value), "%d", port);
169     property_set("service.sdb.tcp.port", value);
170     snprintf(buf, sizeof(buf), "restarting in TCP mode port: %d\n", port);
171     writex(fd, buf, strlen(buf));
172     sdb_close(fd);
173 }
174
175 static int is_support_rootonoff()
176 {
177     return (!strncmp(g_capabilities.rootonoff_support, SDBD_CAP_RET_ENABLED, strlen(SDBD_CAP_RET_ENABLED)));
178 }
179
180 void rootshell_service(int fd, void *cookie)
181 {
182     char buf[100];
183     char *mode = (char*) cookie;
184
185     if (!strcmp(mode, "on")) {
186         if (getuid() == 0) {
187             if (rootshell_mode == 1) {
188                 //snprintf(buf, sizeof(buf), "Already changed to sdk user mode\n");
189                 // do not show message
190             } else {
191                 if (is_support_rootonoff()) {
192                     rootshell_mode = 1;
193                     //allows a permitted user to execute a command as the superuser
194                     snprintf(buf, sizeof(buf), "Switched to 'root' account mode\n");
195                 } else {
196                     snprintf(buf, sizeof(buf), "Permission denied\n");
197                 }
198                 writex(fd, buf, strlen(buf));
199             }
200         } else {
201             D("need root permission for root shell: %d\n", getuid());
202             rootshell_mode = 0;
203             snprintf(buf, sizeof(buf), "Permission denied\n");
204             writex(fd, buf, strlen(buf));
205         }
206     } else if (!strcmp(mode, "off")) {
207         if (rootshell_mode == 1) {
208             rootshell_mode = 0;
209             snprintf(buf, sizeof(buf), "Switched to 'sdk user' account mode\n");
210             writex(fd, buf, strlen(buf));
211         }
212     } else {
213         snprintf(buf, sizeof(buf), "Unknown command option : %s\n", mode);
214         writex(fd, buf, strlen(buf));
215     }
216     D("set rootshell to %s\n", rootshell_mode == 1 ? "root" : SDK_USER_NAME);
217     free(mode);
218     sdb_close(fd);
219 }
220
221 enum tzplatform_get_env_error_status {
222     NO_ERROR_TZPLATFORM_ENV = 0,
223     ERROR_TZPLATFORM_ENV_GENERAL = 1,
224     ERROR_TZPLATFORM_ENV_INVALID_VARIABLES = 2,
225 };
226
227 void get_tzplatform_env(int fd, void *cookie) {
228     char buf[PATH_MAX] = { 0, };
229     char *env_name = (char*) cookie;
230     D("environment variable name: %s\n", env_name);
231     enum tzplatform_variable env_id = tzplatform_getid(env_name);
232     if (env_id != _TZPLATFORM_VARIABLES_INVALID_) {
233         const char *env_value = tzplatform_getenv(env_id);
234         if (env_value) {
235             D("environment value : %s\n", env_value);
236             snprintf(buf, sizeof(buf), "%d%s", NO_ERROR_TZPLATFORM_ENV, env_value);
237         } else {
238             D("failed to get environment value using tzplatform_getenv");
239             snprintf(buf, sizeof(buf), "%d", ERROR_TZPLATFORM_ENV_GENERAL);
240         }
241     } else {
242         D("environment name (%s) is invalid\n", env_name);
243         snprintf(buf, sizeof(buf), "%d", ERROR_TZPLATFORM_ENV_INVALID_VARIABLES);
244     }
245     writex(fd, buf, strlen(buf));
246     free(env_name);
247     sdb_close(fd);
248 }
249
250 void restart_usb_service(int fd, void *cookie)
251 {
252     char buf[100];
253
254     property_set("service.sdb.tcp.port", "0");
255     snprintf(buf, sizeof(buf), "restarting in USB mode\n");
256     writex(fd, buf, strlen(buf));
257     sdb_close(fd);
258 }
259
260 void reboot_service(int fd, void *arg)
261 {
262 #if 0
263     char buf[100];
264     int pid, ret;
265
266     sync();
267
268     /* Attempt to unmount the SD card first.
269      * No need to bother checking for errors.
270      */
271     pid = fork();
272     if (pid == 0) {
273         /* ask vdc to unmount it */
274         // prevent: Use of untrusted string value (TAINTED_STRING)
275         execl("/system/bin/vdc", "/system/bin/vdc", "volume", "unmount",
276                 getenv("EXTERNAL_STORAGE"), "force", NULL);
277     } else if (pid > 0) {
278         /* wait until vdc succeeds or fails */
279         waitpid(pid, &ret, 0);
280     }
281
282     ret = android_reboot(ANDROID_RB_RESTART2, 0, (char *) arg);
283     if (ret < 0) {
284         snprintf(buf, sizeof(buf), "reboot failed: %s errno:%d\n", errno);
285         writex(fd, buf, strlen(buf));
286     }
287     free(arg);
288     sdb_close(fd);
289 #endif
290 }
291
292 #if !SDB_HOST
293 #define EVENT_SIZE  ( sizeof (struct inotify_event) )
294 #define BUF_LEN     ( 1024 * ( EVENT_SIZE + 16 ) )
295 #define CS_PATH     tzplatform_getenv(TZ_SYS_CRASH)
296
297 void inoti_service(int fd, void *arg)
298 {
299     int wd;
300     int ifd;
301     char buffer[BUF_LEN];
302
303     D( "inoti_service start\n");
304     ifd = inotify_init();
305
306     if ( ifd < 0 ) {
307         D( "inotify_init failed\n");
308         return;
309     }
310
311     wd = inotify_add_watch( ifd, CS_PATH, IN_CREATE);
312     if ( wd < 0 ) {
313         D("inotify_add_watch failed (errno :%d)\n", errno);
314         sdb_close(ifd);
315         sdb_close(fd);
316         return;
317     }
318
319     for ( ; ; ) {
320         int length, i = 0;
321         length = sdb_read( ifd, buffer, BUF_LEN );
322
323         if ( length < 0 ) {
324             D( "inoti read failed\n");
325             goto done;
326         }
327         while (i >= 0 && i <= (length - EVENT_SIZE)) {
328             struct inotify_event *event = (struct inotify_event *) &buffer[i];
329             if (event->len) {
330                 if (event->mask & IN_CREATE) {
331                     if (!(event->mask & IN_ISDIR)) {
332                         char *cspath = NULL;
333                         int len = asprintf(&cspath, "%s/%s", CS_PATH,
334                                 event->name);
335                         D( "The file %s was created.\n", cspath);
336                         writex(fd, cspath, len);
337                         if (cspath != NULL) {
338                             free(cspath);
339                         }
340                     }
341                 }
342             }
343             if (i + EVENT_SIZE + event->len < event->len) { // in case of integer overflow
344                 break;
345             }
346             i += EVENT_SIZE + event->len;
347         }
348     }
349
350 done:
351     inotify_rm_watch( ifd, wd );
352     sdb_close(ifd);
353     sdb_close(fd);
354     D( "inoti_service end\n");
355 }
356 #endif
357 #endif
358
359 #if 0
360 static void echo_service(int fd, void *cookie)
361 {
362     char buf[4096];
363     int r;
364     char *p;
365     int c;
366
367     for(;;) {
368         r = read(fd, buf, 4096);
369         if(r == 0) goto done;
370         if(r < 0) {
371             if(errno == EINTR) continue;
372             else goto done;
373         }
374
375         c = r;
376         p = buf;
377         while(c > 0) {
378             r = write(fd, p, c);
379             if(r > 0) {
380                 c -= r;
381                 p += r;
382                 continue;
383             }
384             if((r < 0) && (errno == EINTR)) continue;
385             goto done;
386         }
387     }
388 done:
389     close(fd);
390 }
391 #endif
392
393 static int create_service_thread(void (*func)(int, void *), void *cookie)
394 {
395     stinfo *sti;
396     sdb_thread_t t;
397     int s[2];
398
399     if(sdb_socketpair(s)) {
400         D("cannot create service socket pair\n");
401         return -1;
402     }
403
404     sti = malloc(sizeof(stinfo));
405     if(sti == 0) fatal("cannot allocate stinfo");
406     sti->func = func;
407     sti->cookie = cookie;
408     sti->fd = s[1];
409
410     if(sdb_thread_create( &t, service_bootstrap_func, sti)){
411         free(sti);
412         sdb_close(s[0]);
413         sdb_close(s[1]);
414         D("cannot create service thread\n");
415         return -1;
416     }
417
418     D("service thread started, %d:%d\n",s[0], s[1]);
419     return s[0];
420 }
421
422 #if !SDB_HOST
423
424 static void redirect_and_exec(int pts, const char *cmd, char * const argv[], char * const envp[])
425 {
426     dup2(pts, 0);
427     dup2(pts, 1);
428     dup2(pts, 2);
429
430     sdb_close(pts);
431
432     execve(cmd, argv, envp);
433 }
434
435 static int create_subprocess(const char *cmd, pid_t *pid, char * const argv[], char * const envp[])
436 {
437     char devname[64];
438     int ptm;
439
440     ptm = unix_open("/dev/ptmx", O_RDWR); // | O_NOCTTY);
441     if(ptm < 0){
442         D("[ cannot open /dev/ptmx - errno:%d ]\n",errno);
443         return -1;
444     }
445     if (fcntl(ptm, F_SETFD, FD_CLOEXEC) < 0) {
446         D("[ cannot set cloexec to /dev/ptmx - errno:%d ]\n",errno);
447     }
448
449     if(grantpt(ptm) || unlockpt(ptm) ||
450         ptsname_r(ptm, devname, sizeof(devname)) != 0 ){
451         D("[ trouble with /dev/ptmx - errno:%d ]\n", errno);
452         sdb_close(ptm);
453         return -1;
454     }
455
456     *pid = fork();
457     if(*pid < 0) {
458         D("- fork failed: errno:%d -\n", errno);
459         sdb_close(ptm);
460         return -1;
461     }
462
463     if(*pid == 0){
464         int pts;
465
466         setsid();
467
468         pts = unix_open(devname, O_RDWR);
469         if(pts < 0) {
470             fprintf(stderr, "child failed to open pseudo-term slave: %s\n", devname);
471             exit(-1);
472         }
473
474         sdb_close(ptm);
475
476         // set OOM adjustment to zero
477         {
478             char text[64];
479             //snprintf(text, sizeof text, "/proc/%d/oom_score_adj", getpid());
480             snprintf(text, sizeof text, "/proc/%d/oom_adj", getpid());
481             int fd = sdb_open(text, O_WRONLY);
482             if (fd >= 0) {
483                 sdb_write(fd, "0", 1);
484                 sdb_close(fd);
485             } else {
486                // FIXME: not supposed to be here
487                D("sdb: unable to open %s due to errno:%d\n", text, errno);
488             }
489         }
490
491         if (should_drop_privileges()) {
492             if (argv[2] != NULL && getuid() == 0 && request_plugin_verification(SDBD_CMD_VERIFY_ROOTCMD, argv[2])) {
493                 // do nothing
494                 D("sdb: executes root commands!!:%s\n", argv[2]);
495             } else {
496                 set_sdk_user_privileges();
497             }
498         }
499         redirect_and_exec(pts, cmd, argv, envp);
500         fprintf(stderr, "- exec '%s' failed: (errno:%d) -\n",
501                 cmd, errno);
502         exit(-1);
503     } else {
504         // Don't set child's OOM adjustment to zero.
505         // Let the child do it itself, as sometimes the parent starts
506         // running before the child has a /proc/pid/oom_adj.
507         // """sdb: unable to open /proc/644/oom_adj""" seen in some logs.
508         return ptm;
509     }
510 }
511 #endif  /* !SDB_HOST */
512
513 #define SHELL_COMMAND "/bin/sh"
514 #define LOGIN_COMMAND "/bin/login"
515 #define SUPER_USER    "root"
516 #define LOGIN_CONFIG  "/etc/login.defs"
517
518 #if !SDB_HOST
519 static void subproc_waiter_service(int fd, void *cookie)
520 {
521     pid_t pid = (pid_t)cookie;
522
523     D("entered. fd=%d of pid=%d\n", fd, pid);
524     for (;;) {
525         int status;
526         pid_t p = waitpid(pid, &status, 0);
527         if (p == pid) {
528             D("fd=%d, post waitpid(pid=%d) status=%04x\n", fd, p, status);
529             if (WIFEXITED(status)) {
530                 D("*** Exit code %d\n", WEXITSTATUS(status));
531                 break;
532             } else if (WIFSIGNALED(status)) {
533                 D("*** Killed by signal %d\n", WTERMSIG(status));
534                 break;
535             } else {
536                 D("*** Killed by unknown code %d\n", status);
537                 break;
538             }
539          }
540     }
541     D("shell exited fd=%d of pid=%d err=%d\n", fd, pid, errno);
542     if (SHELL_EXIT_NOTIFY_FD >=0) {
543       int res;
544       res = writex(SHELL_EXIT_NOTIFY_FD, &fd, sizeof(fd));
545       D("notified shell exit via fd=%d for pid=%d res=%d errno=%d\n",
546         SHELL_EXIT_NOTIFY_FD, pid, res, errno);
547     }
548 }
549
550 static void get_env(char *key, char **env)
551 {
552     FILE *fp;
553     char buf[1024];
554     char *s, *e, *value;
555
556     fp = fopen (LOGIN_CONFIG, "r");
557     if (NULL == fp) {
558         return;
559     }
560
561     while (fgets(buf, (int) sizeof (buf), fp) != NULL) {
562         s = buf;
563         e = buf + (strlen(buf) - 1);
564
565         // trim string
566         while(*e == ' ' ||  *e == '\n' || *e == '\t') {
567             e--;
568         }
569         *(e+1) ='\0';
570
571         while(*s != '\0' && (*s == ' ' || *s == '\t' || *s == '\n')) {
572             s++;
573         }
574
575         // skip comment or null string
576         if (*s == '#' || *s == '\0') {
577             continue;
578         }
579         value = s + strcspn(s, " \t");
580         *value++ = '\0';
581
582         if(!strcmp(buf, key)) {
583             *env = strdup(value);
584             break;
585         }
586     }
587
588     fclose(fp);
589 }
590
591 static int create_subproc_thread(const char *name, int lines, int columns)
592 {
593     stinfo *sti;
594     sdb_thread_t t;
595     int ret_fd;
596     pid_t pid;
597     char *value = NULL;
598     char *trim_value = NULL;
599     char path[PATH_MAX];
600     memset(path, 0, sizeof(path));
601     char *envp[MAX_TOKENS];
602     int envp_cnt = 0;
603     envp[envp_cnt++] = strdup("TERM=linux");
604     envp[envp_cnt++] = strdup("DISPLAY=:0");
605
606     if (should_drop_privileges()) {
607         if (g_sdk_home_dir_env) {
608             envp[envp_cnt++] = strdup(g_sdk_home_dir_env);
609         } else {
610             envp[envp_cnt++] = strdup("HOME=/home/owner");
611         }
612         get_env("ENV_PATH", &value);
613     } else {
614         get_env("ENV_SUPATH", &value);
615         if(value == NULL) {
616             get_env("ENV_ROOTPATH", &value);
617         }
618         envp[envp_cnt++] = strdup("HOME=/root");
619     }
620     if (value != NULL) {
621         trim_value = str_trim(value);
622         if (trim_value != NULL) {
623             // if string is not including 'PATH=', append it.
624             if (strncmp(trim_value, "PATH", 4)) {
625                 snprintf(path, sizeof(path), "PATH=%s", trim_value);
626             } else {
627                 snprintf(path, sizeof(path), "%s", trim_value);
628             }
629             envp[envp_cnt++] = strdup(path);
630         } else {
631             snprintf(path, sizeof(path), "%s", value);
632             envp[envp_cnt++] = strdup(path);
633         }
634         free(value);
635     }
636
637     /* get environment variables from plugin */
638     char *envp_plugin = NULL;
639     envp_plugin = malloc(SDBD_PLUGIN_OUTBUF_MAX);
640     if (envp_plugin == NULL) {
641         D("Cannot allocate the shell commnad buffer.");
642         return -1;
643     }
644     memset(envp_plugin, 0, SDBD_PLUGIN_OUTBUF_MAX);
645     if (!request_plugin_cmd(SDBD_CMD_SHELL_ENVVAR, "", envp_plugin, SDBD_PLUGIN_OUTBUF_MAX)) {
646         D("Failed to convert the shell command. (%s)\n", name);
647         free(envp_plugin);
648         return -1;
649     } else {
650        if(envp_plugin[0] != '\0') {
651             envp_cnt = tokenize_append(envp_plugin, "\n", envp, MAX_TOKENS, envp_cnt);
652         }
653     }
654     free(envp_plugin);
655
656     if(name) { // in case of shell execution directly
657         // Check the shell command validation.
658         if (!request_plugin_verification(SDBD_CMD_VERIFY_SHELLCMD, name)) {
659             D("This shell command is invalid. (%s)\n", name);
660             return -1;
661         }
662
663         // Convert the shell command.
664         char *new_cmd = NULL;
665         new_cmd = malloc(SDBD_SHELL_CMD_MAX);
666         if(new_cmd == NULL) {
667             D("Cannot allocate the shell commnad buffer.");
668             return -1;
669         }
670
671         memset(new_cmd, 0, SDBD_SHELL_CMD_MAX);
672         if(!request_plugin_cmd(SDBD_CMD_CONV_SHELLCMD, name, new_cmd, SDBD_SHELL_CMD_MAX)) {
673             D("Failed to convert the shell command. (%s)\n", name);
674             free(new_cmd);
675             return -1;
676         }
677
678         D("converted cmd : %s\n", new_cmd);
679
680         char *args[] = {
681             SHELL_COMMAND,
682             "-c",
683             NULL,
684             NULL,
685         };
686         args[2] = new_cmd;
687
688         ret_fd = create_subprocess(SHELL_COMMAND, &pid, (char * const*)args, (char * const*)envp);
689         free(new_cmd);
690     } else { // in case of shell interactively
691         // Check the capability for interactive shell support.
692         if (!is_support_interactive_shell()) {
693             D("This platform dose NOT support the interactive shell\n");
694             return -1;
695         }
696
697         char * const args[] = {
698                 SHELL_COMMAND,
699                 "-",
700                 NULL,
701         };
702         ret_fd = create_subprocess(SHELL_COMMAND, &pid, (char * const*)args, (char * const*)envp);
703 #if 0   // FIXME: should call login command instead of /bin/sh
704         if (should_drop_privileges()) {
705             char *args[] = {
706                 SHELL_COMMAND,
707                 "-",
708                 NULL,
709             };
710             ret_fd = create_subprocess(SHELL_COMMAND, &pid, args, envp);
711         } else {
712             char *args[] = {
713                 LOGIN_COMMAND,
714                 "-f",
715                 SUPER_USER,
716                 NULL,
717             };
718             ret_fd = create_subprocess(LOGIN_COMMAND, &pid, args, envp);
719         }
720 #endif
721     }
722
723     /* free environment variables */
724     int i = 0;
725     if(envp_cnt > 0) {
726         for(i = 0; i < envp_cnt; i++) {
727             if(envp[i]) {
728                 D("envp[%d] = %s\n", i, envp[i]);
729                 free(envp[i]);
730             }
731         }
732     }
733
734     D("create_subprocess() ret_fd=%d pid=%d\n", ret_fd, pid);
735
736     if (ret_fd < 0) {
737         D("cannot create service thread\n");
738         return -1;
739     }
740
741     if (lines > 0 && columns > 0) {
742         D("shell size lines=%d, columns=%d\n", lines, columns);
743         struct winsize win_sz;
744         win_sz.ws_row = lines;
745         win_sz.ws_col = columns;
746
747         if (ioctl(ret_fd, TIOCSWINSZ, &win_sz) < 0) {
748             D("failed to sync window size.\n");
749         }
750     }
751
752     sti = malloc(sizeof(stinfo));
753     if(sti == 0) fatal("cannot allocate stinfo");
754     sti->func = subproc_waiter_service;
755     sti->cookie = (void*)pid;
756     sti->fd = ret_fd;
757
758     if(sdb_thread_create( &t, service_bootstrap_func, sti)){
759         free(sti);
760         sdb_close(ret_fd);
761         D("cannot create service thread\n");
762         return -1;
763     }
764
765     D("service thread started, fd=%d pid=%d\n",ret_fd, pid);
766     return ret_fd;
767 }
768
769 static int create_sync_subprocess(void (*func)(int, void *), void* cookie) {
770     stinfo *sti;
771     sdb_thread_t t;
772     int s[2];
773
774     if(sdb_socketpair(s)) {
775         D("cannot create service socket pair\n");
776         return -1;
777     }
778
779     pid_t pid = fork();
780
781     if (pid == 0) {
782         sdb_close(s[0]);
783         func(s[1], cookie);
784         exit(-1);
785     } else if (pid > 0) {
786         sdb_close(s[1]);
787         // FIXME: do not wait child process hear
788         //waitpid(pid, &ret, 0);
789     }
790     if (pid < 0) {
791         D("- fork failed: errno:%d -\n", errno);
792         sdb_close(s[0]);
793         sdb_close(s[1]);
794         D("cannot create sync service sub process\n");
795         return -1;
796     }
797
798     sti = malloc(sizeof(stinfo));
799     if(sti == 0) fatal("cannot allocate stinfo");
800     sti->func = subproc_waiter_service;
801     sti->cookie = (void*)pid;
802     sti->fd = s[0];
803
804     if(sdb_thread_create( &t, service_bootstrap_func, sti)){
805         free(sti);
806         sdb_close(s[0]);
807         printf("cannot create service monitor thread\n");
808         return -1;
809     }
810
811     D("service process started, fd=%d pid=%d\n",s[0], pid);
812     return s[0];
813 }
814
815 static int create_syncproc_thread()
816 {
817     int ret_fd;
818
819     ret_fd = create_sync_subprocess(file_sync_service, NULL);
820     // FIXME: file missing bug when root on mode
821     /*
822     if (should_drop_privileges()) {
823         ret_fd = create_sync_subprocess(file_sync_service, NULL);
824     } else {
825         ret_fd = create_service_thread(file_sync_service, NULL);
826     }
827     */
828
829     return ret_fd;
830 }
831
832 #endif
833
834 static void get_platforminfo(int fd, void *cookie) {
835     pinfo sysinfo;
836
837     char *value = NULL;
838     s_strncpy(sysinfo.platform_info_version, INFO_VERSION, strlen(INFO_VERSION));
839
840     int r = system_info_get_platform_string("http://tizen.org/system/model_name", &value);
841     if (r != SYSTEM_INFO_ERROR_NONE) {
842         s_strncpy(sysinfo.model_name, UNKNOWN, strlen(UNKNOWN));
843         D("fail to get system model:%d\n", errno);
844     } else {
845         s_strncpy(sysinfo.model_name, value, sizeof(sysinfo.model_name));
846         D("returns model_name:%s\n", value);
847         if (value != NULL) {
848             free(value);
849         }
850     }
851
852     r = system_info_get_platform_string("http://tizen.org/system/platform.name", &value);
853     if (r != SYSTEM_INFO_ERROR_NONE) {
854         s_strncpy(sysinfo.platform_name, UNKNOWN, strlen(UNKNOWN));
855         D("fail to get platform name:%d\n", errno);
856     } else {
857         s_strncpy(sysinfo.platform_name, value, sizeof(sysinfo.platform_name));
858         D("returns platform_name:%s\n", value);
859         if (value != NULL) {
860             free(value);
861         }
862
863     }
864
865     // FIXME: the result is different when using SYSTEM_INFO_KEY_TIZEN_VERSION_NAME
866     r = system_info_get_platform_string("tizen.org/feature/platform.version", &value);
867     if (r != SYSTEM_INFO_ERROR_NONE) {
868         s_strncpy(sysinfo.platform_version, UNKNOWN, strlen(UNKNOWN));
869         D("fail to get platform version:%d\n", errno);
870     } else {
871         s_strncpy(sysinfo.platform_version, value, sizeof(sysinfo.platform_version));
872         D("returns platform_version:%s\n", value);
873         if (value != NULL) {
874             free(value);
875         }
876     }
877
878     r = system_info_get_platform_string("tizen.org/feature/profile", &value);
879     if (r != SYSTEM_INFO_ERROR_NONE) {
880         s_strncpy(sysinfo.profile_name, UNKNOWN, strlen(UNKNOWN));
881         D("fail to get profile name:%d\n", errno);
882     } else {
883         s_strncpy(sysinfo.profile_name, value, sizeof(sysinfo.profile_name));
884         D("returns profile name:%s\n", value);
885         if (value != NULL) {
886             free(value);
887         }
888     }
889
890     writex(fd, &sysinfo, sizeof(pinfo));
891
892     sdb_close(fd);
893 }
894
895 static int put_key_value_string(char* buf, int offset, int buf_size, char* key, char* value) {
896     int len = 0;
897     if ((len = snprintf(buf+offset, buf_size-offset, "%s:%s\n", key, value)) > 0) {
898         return len;
899     }
900     return 0;
901 }
902
903 static void get_capability(int fd, void *cookie) {
904     char cap_buffer[CAPBUF_SIZE] = {0,};
905     uint16_t offset = 0;
906
907     // Secure protocol support
908     offset += put_key_value_string(cap_buffer, offset, CAPBUF_SIZE,
909                                 "secure_protocol", g_capabilities.secure_protocol);
910
911     // Interactive shell support
912     offset += put_key_value_string(cap_buffer, offset, CAPBUF_SIZE,
913                                 "intershell_support", g_capabilities.intershell_support);
914
915     // File push/pull support
916     offset += put_key_value_string(cap_buffer, offset, CAPBUF_SIZE,
917                                 "filesync_support", g_capabilities.filesync_support);
918
919     // USB protocol support
920     offset += put_key_value_string(cap_buffer, offset, CAPBUF_SIZE,
921                                 "usbproto_support", g_capabilities.usbproto_support);
922
923     // Socket protocol support
924     offset += put_key_value_string(cap_buffer, offset, CAPBUF_SIZE,
925                                 "sockproto_support", g_capabilities.sockproto_support);
926
927     // Window size synchronization support
928     offset += put_key_value_string(cap_buffer, offset, CAPBUF_SIZE,
929                                 "syncwinsz_support", g_capabilities.syncwinsz_support);
930
931     // Root command support
932     offset += put_key_value_string(cap_buffer, offset, CAPBUF_SIZE,
933                                 "rootonoff_support", g_capabilities.rootonoff_support);
934
935     // Zone support
936     offset += put_key_value_string(cap_buffer, offset, CAPBUF_SIZE,
937                                 "zone_support", g_capabilities.zone_support);
938
939     // Multi-User support
940     offset += put_key_value_string(cap_buffer, offset, CAPBUF_SIZE,
941                                 "multiuser_support", g_capabilities.multiuser_support);
942
943     // CPU Architecture of model
944     offset += put_key_value_string(cap_buffer, offset, CAPBUF_SIZE,
945                                 "cpu_arch", g_capabilities.cpu_arch);
946
947     // SDK Tool path
948     offset += put_key_value_string(cap_buffer, offset, CAPBUF_SIZE,
949                                 "sdk_toolpath", g_capabilities.sdk_toolpath);
950
951     // Profile name
952     offset += put_key_value_string(cap_buffer, offset, CAPBUF_SIZE,
953                                 "profile_name", g_capabilities.profile_name);
954
955     // Vendor name
956     offset += put_key_value_string(cap_buffer, offset, CAPBUF_SIZE,
957                                 "vendor_name", g_capabilities.vendor_name);
958
959     // Target name of the launch possible
960     offset += put_key_value_string(cap_buffer, offset, CAPBUF_SIZE,
961                                 "can_launch", g_capabilities.can_launch);
962
963     // Platform version
964     offset += put_key_value_string(cap_buffer, offset, CAPBUF_SIZE,
965                                 "platform_version", g_capabilities.platform_version);
966
967     // Product version
968     offset += put_key_value_string(cap_buffer, offset, CAPBUF_SIZE,
969                                 "product_version", g_capabilities.product_version);
970
971     // Sdbd version
972     offset += put_key_value_string(cap_buffer, offset, CAPBUF_SIZE,
973                                 "sdbd_version", g_capabilities.sdbd_version);
974
975     // Sdbd plugin version
976     offset += put_key_value_string(cap_buffer, offset, CAPBUF_SIZE,
977                                 "sdbd_plugin_version", g_capabilities.sdbd_plugin_version);
978
979     // Capability version
980     offset += put_key_value_string(cap_buffer, offset, CAPBUF_SIZE,
981                                 "sdbd_cap_version", g_capabilities.sdbd_cap_version);
982
983     // Sdbd log enable
984    offset += put_key_value_string(cap_buffer, offset, CAPBUF_SIZE,
985                                "log_enable", g_capabilities.log_enable);
986
987     // Sdbd log path
988    offset += put_key_value_string(cap_buffer, offset, CAPBUF_SIZE,
989                                "log_path", g_capabilities.log_path);
990
991     offset++; // for '\0' character
992
993     writex(fd, &offset, sizeof(uint16_t));
994     writex(fd, cap_buffer, offset);
995
996     sdb_close(fd);
997 }
998
999 static void sync_windowsize(int fd, void *cookie) {
1000     int id, lines, columns;
1001     char *size_info = cookie;
1002     asocket *s = NULL;
1003
1004     if (sscanf(size_info, "%d:%d:%d", &id, &lines, &columns) == 3) {
1005         D("window size information: id=%d, lines=%d, columns=%d\n", id, lines, columns);
1006     }
1007     if((s = find_local_socket(id))) {
1008         struct winsize win_sz;
1009         win_sz.ws_row = lines;
1010         win_sz.ws_col = columns;
1011
1012         if (ioctl(s->fd, TIOCSWINSZ, &win_sz) < 0) {
1013             D("failed to sync window size.\n");
1014             return;
1015         }
1016         D("success to sync window size.\n");
1017     }
1018 }
1019
1020 const unsigned COMMAND_TIMEOUT = 10000;
1021 void get_boot(int fd, void *cookie) {
1022     char buf[2] = { 0, };
1023     int time = 0;
1024     int interval = 1000;
1025     while (time < COMMAND_TIMEOUT) {
1026         if (booting_done == 1) {
1027             D("get_boot:platform booting is done\n");
1028             snprintf(buf, sizeof(buf), "%s", "1");
1029             break;
1030         }
1031         D("get_boot:platform booting is in progress\n");
1032         sdb_sleep_ms(interval);
1033         time += interval;
1034     }
1035     writex(fd, buf, strlen(buf));
1036     sdb_close(fd);
1037 }
1038
1039 int service_to_fd(const char *name)
1040 {
1041     int ret = -1;
1042
1043     if(!strncmp(name, "tcp:", 4)) {
1044         int port = atoi(name + 4);
1045         name = strchr(name + 4, ':');
1046         if(name == 0) {
1047             if (is_emulator()){
1048                 ret = socket_ifr_client(port , SOCK_STREAM, "eth0");
1049             } else {
1050                 ret = socket_ifr_client(port , SOCK_STREAM, "usb0");
1051                 if (ret < 0) {
1052                     if (ifconfig(SDB_FORWARD_IFNAME, SDB_FORWARD_INTERNAL_IP, SDB_FORWARD_INTERNAL_MASK, 1) == 0) {
1053                         ret = socket_ifr_client(port , SOCK_STREAM, SDB_FORWARD_IFNAME);
1054                     }
1055                 }
1056             }
1057             if (ret < 0) {
1058                 ret = socket_loopback_client(port, SOCK_STREAM);
1059             }
1060             if (ret >= 0) {
1061                 disable_tcp_nagle(ret);
1062             }
1063         } else {
1064 #if SDB_HOST
1065             sdb_mutex_lock(&dns_lock);
1066             ret = socket_network_client(name + 1, port, SOCK_STREAM);
1067             sdb_mutex_unlock(&dns_lock);
1068 #else
1069             return -1;
1070 #endif
1071         }
1072 #ifndef HAVE_WINSOCK   /* winsock doesn't implement unix domain sockets */
1073     } else if(!strncmp(name, "local:", 6)) {
1074         ret = socket_local_client(name + 6,
1075                 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_STREAM);
1076     } else if(!strncmp(name, "localreserved:", 14)) {
1077         ret = socket_local_client(name + 14,
1078                 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_STREAM);
1079     } else if(!strncmp(name, "localabstract:", 14)) {
1080         ret = socket_local_client(name + 14,
1081                 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
1082     } else if(!strncmp(name, "localfilesystem:", 16)) {
1083         ret = socket_local_client(name + 16,
1084                 ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
1085 #endif
1086 #if SDB_HOST
1087     } else if(!strncmp("dns:", name, 4)){
1088         char *n = strdup(name + 4);
1089         if(n == 0) return -1;
1090         ret = create_service_thread(dns_service, n);
1091 #else /* !SDB_HOST */
1092     }/* else if(!strncmp("dev:", name, 4)) {// tizen specific
1093         ret = unix_open(name + 4, O_RDWR);
1094     } else if(!strncmp(name, "framebuffer:", 12)) {
1095         ret = create_service_thread(framebuffer_service, 0);
1096     } else if(recovery_mode && !strncmp(name, "recover:", 8)) {
1097         ret = create_service_thread(recover_service, (void*) atoi(name + 8));
1098     } else if (!strncmp(name, "jdwp:", 5)) {
1099         ret = create_jdwp_connection_fd(atoi(name+5));
1100     } else if (!strncmp(name, "log:", 4)) {
1101         ret = create_service_thread(log_service, get_log_file_path(name + 4));
1102     }*/ else if(!HOST && !strncmp(name, "shell:", 6)) {
1103         if(name[6]) {
1104             ret = create_subproc_thread(name + 6, 0, 0);
1105         } else {
1106             ret = create_subproc_thread(NULL, 0, 0);
1107         }
1108     } else if(!strncmp(name, "eshell:", 7)) {
1109         int lines, columns;
1110         if (sscanf(name+7, "%d:%d", &lines, &columns) == 2) {
1111             ret = create_subproc_thread(NULL, lines, columns);
1112         }
1113     } else if(!strncmp(name, "sync:", 5)) {
1114         //ret = create_service_thread(file_sync_service, NULL);
1115         ret = create_syncproc_thread();
1116     }/*  else if(!strncmp(name, "remount:", 8)) {
1117         ret = create_service_thread(remount_service, NULL);
1118     } else if(!strncmp(name, "reboot:", 7)) {
1119         void* arg = strdup(name + 7);
1120         if(arg == 0) return -1;
1121         ret = create_service_thread(reboot_service, arg);
1122     } else if(!strncmp(name, "root:", 5)) {
1123         ret = create_service_thread(restart_root_service, NULL);
1124     } else if(!strncmp(name, "backup:", 7)) {
1125         char* arg = strdup(name+7);
1126         if (arg == NULL) return -1;
1127         ret = backup_service(BACKUP, arg);
1128     } else if(!strncmp(name, "restore:", 8)) {
1129         ret = backup_service(RESTORE, NULL);
1130     }*/ else if(!strncmp(name, "root:", 5)) {
1131         char* service_name = NULL;
1132
1133         service_name = strdup(name+5);
1134         ret = create_service_thread(rootshell_service, (void *)(service_name));
1135     } else if(!strncmp(name, "cs:", 5)) {
1136         ret = create_service_thread(inoti_service, NULL);
1137 #endif
1138     } else if(!strncmp(name, "sysinfo:", 8)){
1139         ret = create_service_thread(get_platforminfo, 0);
1140     } else if(!strncmp(name, "capability:", 11)){
1141         ret = create_service_thread(get_capability, 0);
1142     } else if(!strncmp(name, "boot:", 5)){
1143         if (is_emulator()) {
1144             ret = create_service_thread(get_boot, 0);
1145         }
1146     } else if(!strncmp(name, "shellconf:", 10)){
1147         if(!strncmp(name+10, "syncwinsz:", 10)){
1148             ret = create_service_thread(sync_windowsize, (void *)name+20);
1149         }
1150     } else if(!strncmp(name, "tzplatformenv:", 14)) {
1151        char* env_variable = NULL;
1152        env_variable = strdup(name+14);
1153        ret = create_service_thread(get_tzplatform_env, (void *)(env_variable));
1154     }
1155
1156     if (ret >= 0) {
1157         if (close_on_exec(ret) < 0) {
1158             D("failed to close fd exec\n");
1159         }
1160     }
1161     return ret;
1162 }
1163
1164 #if SDB_HOST
1165 struct state_info {
1166     transport_type transport;
1167     char* serial;
1168     int state;
1169 };
1170
1171 static void wait_for_state(int fd, void* cookie)
1172 {
1173     struct state_info* sinfo = cookie;
1174     char* err = "unknown error";
1175
1176     D("wait_for_state %d\n", sinfo->state);
1177
1178     atransport *t = acquire_one_transport(sinfo->state, sinfo->transport, sinfo->serial, &err);
1179     if(t != 0) {
1180         writex(fd, "OKAY", 4);
1181     } else {
1182         sendfailmsg(fd, err);
1183     }
1184
1185     if (sinfo->serial)
1186         free(sinfo->serial);
1187     free(sinfo);
1188     sdb_close(fd);
1189     D("wait_for_state is done\n");
1190 }
1191 #endif
1192
1193 #if SDB_HOST
1194 asocket*  host_service_to_socket(const char*  name, const char *serial)
1195 {
1196     if (!strcmp(name,"track-devices")) {
1197         return create_device_tracker();
1198     } else if (!strncmp(name, "wait-for-", strlen("wait-for-"))) {
1199         struct state_info* sinfo = malloc(sizeof(struct state_info));
1200
1201         if (serial)
1202             sinfo->serial = strdup(serial);
1203         else
1204             sinfo->serial = NULL;
1205
1206         name += strlen("wait-for-");
1207
1208         if (!strncmp(name, "local", strlen("local"))) {
1209             sinfo->transport = kTransportLocal;
1210             sinfo->state = CS_DEVICE;
1211         } else if (!strncmp(name, "usb", strlen("usb"))) {
1212             sinfo->transport = kTransportUsb;
1213             sinfo->state = CS_DEVICE;
1214         } else if (!strncmp(name, "any", strlen("any"))) {
1215             sinfo->transport = kTransportAny;
1216             sinfo->state = CS_DEVICE;
1217         } else {
1218             free(sinfo);
1219             return NULL;
1220         }
1221
1222         int fd = create_service_thread(wait_for_state, sinfo);
1223         return create_local_socket(fd);
1224     }
1225     return NULL;
1226 }
1227 #endif /* SDB_HOST */