send noti to sensord when sdb is booting up
[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 typedef struct stinfo stinfo;
42
43 struct stinfo {
44     void (*func)(int fd, void *cookie);
45     int fd;
46     void *cookie;
47 };
48
49
50 void *service_bootstrap_func(void *x)
51 {
52     stinfo *sti = x;
53     sti->func(sti->fd, sti->cookie);
54     free(sti);
55     return 0;
56 }
57
58 #if SDB_HOST
59 SDB_MUTEX_DEFINE( dns_lock );
60
61 static void dns_service(int fd, void *cookie)
62 {
63     char *hostname = cookie;
64     struct hostent *hp;
65     unsigned zero = 0;
66
67     sdb_mutex_lock(&dns_lock);
68     hp = gethostbyname(hostname);
69     free(cookie);
70     if(hp == 0) {
71         writex(fd, &zero, 4);
72     } else {
73         writex(fd, hp->h_addr, 4);
74     }
75     sdb_mutex_unlock(&dns_lock);
76     sdb_close(fd);
77 }
78 #else
79
80 #if 0
81 extern int recovery_mode;
82
83 static void recover_service(int s, void *cookie)
84 {
85     unsigned char buf[4096];
86     unsigned count = (unsigned) cookie;
87     int fd;
88
89     fd = sdb_creat("/tmp/update", 0644);
90     if(fd < 0) {
91         sdb_close(s);
92         return;
93     }
94
95     while(count > 0) {
96         unsigned xfer = (count > 4096) ? 4096 : count;
97         if(readx(s, buf, xfer)) break;
98         if(writex(fd, buf, xfer)) break;
99         count -= xfer;
100     }
101
102     if(count == 0) {
103         writex(s, "OKAY", 4);
104     } else {
105         writex(s, "FAIL", 4);
106     }
107     sdb_close(fd);
108     sdb_close(s);
109
110     fd = sdb_creat("/tmp/update.begin", 0644);
111     sdb_close(fd);
112 }
113
114 void restart_root_service(int fd, void *cookie)
115 {
116     char buf[100];
117     char value[PROPERTY_VALUE_MAX];
118
119     if (getuid() == 0) {
120         snprintf(buf, sizeof(buf), "sdbd is already running as root\n");
121         writex(fd, buf, strlen(buf));
122         sdb_close(fd);
123     } else {
124         property_get("ro.debuggable", value, "");
125         if (strcmp(value, "1") != 0) {
126             snprintf(buf, sizeof(buf), "sdbd cannot run as root in production builds\n");
127             writex(fd, buf, strlen(buf));
128             sdb_close(fd);
129             return;
130         }
131
132         property_set("service.sdb.root", "1");
133         snprintf(buf, sizeof(buf), "restarting sdbd as root\n");
134         writex(fd, buf, strlen(buf));
135         sdb_close(fd);
136     }
137 }
138 #endif
139
140 void restart_tcp_service(int fd, void *cookie)
141 {
142     char buf[100];
143     char value[PROPERTY_VALUE_MAX];
144     int port = (int)cookie;
145
146     if (port <= 0) {
147         snprintf(buf, sizeof(buf), "invalid port\n");
148         writex(fd, buf, strlen(buf));
149         sdb_close(fd);
150         return;
151     }
152
153     snprintf(value, sizeof(value), "%d", port);
154     property_set("service.sdb.tcp.port", value);
155     snprintf(buf, sizeof(buf), "restarting in TCP mode port: %d\n", port);
156     writex(fd, buf, strlen(buf));
157     sdb_close(fd);
158 }
159
160 void rootshell_service(int fd, void *cookie)
161 {
162     char buf[100];
163     char *mode = (char*) cookie;
164
165     if (!strcmp(mode, "on")) {
166         if (rootshell_mode == 1) {
167             //snprintf(buf, sizeof(buf), "Already changed to developer mode\n");
168             // do not show message
169         } else {
170             if (access("/bin/su", F_OK) == 0) {
171                 rootshell_mode = 1;
172                 //allows a permitted user to execute a command as the superuser
173                 snprintf(buf, sizeof(buf), "Switched to 'root' account mode\n");
174             } else {
175                 snprintf(buf, sizeof(buf), "Permission denied\n");
176             }
177             writex(fd, buf, strlen(buf));
178         }
179     } else if (!strcmp(mode, "off")) {
180         if (rootshell_mode == 1) {
181             rootshell_mode = 0;
182             snprintf(buf, sizeof(buf), "Switched to 'developer' account mode\n");
183             writex(fd, buf, strlen(buf));
184         }
185     } else {
186         snprintf(buf, sizeof(buf), "Unknown command option\n");
187         writex(fd, buf, strlen(buf));
188     }
189     D("set rootshell to %s\n", rootshell_mode == 1 ? "root" : "developer");
190     sdb_close(fd);
191 }
192
193 void restart_usb_service(int fd, void *cookie)
194 {
195     char buf[100];
196
197     property_set("service.sdb.tcp.port", "0");
198     snprintf(buf, sizeof(buf), "restarting in USB mode\n");
199     writex(fd, buf, strlen(buf));
200     sdb_close(fd);
201 }
202
203 void reboot_service(int fd, void *arg)
204 {
205 #if 0
206     char buf[100];
207     int pid, ret;
208
209     sync();
210
211     /* Attempt to unmount the SD card first.
212      * No need to bother checking for errors.
213      */
214     pid = fork();
215     if (pid == 0) {
216         /* ask vdc to unmount it */
217         // prevent: Use of untrusted string value (TAINTED_STRING)
218         execl("/system/bin/vdc", "/system/bin/vdc", "volume", "unmount",
219                 getenv("EXTERNAL_STORAGE"), "force", NULL);
220     } else if (pid > 0) {
221         /* wait until vdc succeeds or fails */
222         waitpid(pid, &ret, 0);
223     }
224
225     ret = android_reboot(ANDROID_RB_RESTART2, 0, (char *) arg);
226     if (ret < 0) {
227         snprintf(buf, sizeof(buf), "reboot failed: %s\n", strerror(errno));
228         writex(fd, buf, strlen(buf));
229     }
230     free(arg);
231     sdb_close(fd);
232 #endif
233 }
234
235 #if !SDB_HOST
236 #define EVENT_SIZE  ( sizeof (struct inotify_event) )
237 #define BUF_LEN     ( 1024 * ( EVENT_SIZE + 16 ) )
238 #define CS_PATH     "/opt/usr/share/crash/report"
239
240 void inoti_service(int fd, void *arg)
241 {
242     int wd;
243     int ifd;
244     char buffer[BUF_LEN];
245
246     D( "inoti_service start\n");
247     ifd = inotify_init();
248
249     if ( ifd < 0 ) {
250         D( "inotify_init failed\n");
251         return;
252     }
253
254     wd = inotify_add_watch( ifd, CS_PATH, IN_CREATE);
255
256     for ( ; ; ) {
257         int length, i = 0;
258         length = sdb_read( ifd, buffer, BUF_LEN );
259
260         if ( length < 0 ) {
261             D( "inoti read failed\n");
262             goto done;
263         }
264
265         while ( i < length ) {
266             struct inotify_event *event = ( struct inotify_event * )&buffer[i];
267             if (event->len) {
268                 if ( event->mask & IN_CREATE) {
269                     if (!(event->mask & IN_ISDIR)) {
270                         char *cspath = NULL;
271                         int len = asprintf(&cspath, "%s/%s", CS_PATH, event->name);
272                         D( "The file %s was created.\n", cspath);
273                         writex(fd, cspath, len);
274                         if (cspath != NULL) {
275                             free(cspath);
276                         }
277                     }
278                 }
279             }
280             i += EVENT_SIZE + event->len;
281         }
282     }
283
284 done:
285     inotify_rm_watch( ifd, wd );
286     sdb_close(ifd);
287     sdb_close(fd);
288     D( "inoti_service end\n");
289 }
290 #endif
291 #endif
292
293 #if 0
294 static void echo_service(int fd, void *cookie)
295 {
296     char buf[4096];
297     int r;
298     char *p;
299     int c;
300
301     for(;;) {
302         r = read(fd, buf, 4096);
303         if(r == 0) goto done;
304         if(r < 0) {
305             if(errno == EINTR) continue;
306             else goto done;
307         }
308
309         c = r;
310         p = buf;
311         while(c > 0) {
312             r = write(fd, p, c);
313             if(r > 0) {
314                 c -= r;
315                 p += r;
316                 continue;
317             }
318             if((r < 0) && (errno == EINTR)) continue;
319             goto done;
320         }
321     }
322 done:
323     close(fd);
324 }
325 #endif
326
327 static int create_service_thread(void (*func)(int, void *), void *cookie)
328 {
329     stinfo *sti;
330     sdb_thread_t t;
331     int s[2];
332
333     if(sdb_socketpair(s)) {
334         D("cannot create service socket pair\n");
335         return -1;
336     }
337
338     sti = malloc(sizeof(stinfo));
339     if(sti == 0) fatal("cannot allocate stinfo");
340     sti->func = func;
341     sti->cookie = cookie;
342     sti->fd = s[1];
343
344     if(sdb_thread_create( &t, service_bootstrap_func, sti)){
345         free(sti);
346         sdb_close(s[0]);
347         sdb_close(s[1]);
348         D("cannot create service thread\n");
349         return -1;
350     }
351
352     D("service thread started, %d:%d\n",s[0], s[1]);
353     return s[0];
354 }
355
356 #if !SDB_HOST
357
358 static int create_subprocess(const char *cmd, const char *arg0, const char *arg1, pid_t *pid)
359 {
360 #ifdef HAVE_WIN32_PROC
361     D("create_subprocess(cmd=%s, arg0=%s, arg1=%s)\n", cmd, arg0, arg1);
362     fprintf(stderr, "error: create_subprocess not implemented on Win32 (%s %s %s)\n", cmd, arg0, arg1);
363     return -1;
364 #else /* !HAVE_WIN32_PROC */
365     char *devname;
366     int ptm;
367
368     ptm = unix_open("/dev/ptmx", O_RDWR); // | O_NOCTTY);
369     if(ptm < 0){
370         D("[ cannot open /dev/ptmx - %s ]\n",strerror(errno));
371         return -1;
372     }
373     if (fcntl(ptm, F_SETFD, FD_CLOEXEC) < 0) {
374         D("[ cannot set cloexec to /dev/ptmx - %s ]\n",strerror(errno));
375     }
376
377     if(grantpt(ptm) || unlockpt(ptm) ||
378        ((devname = (char*) ptsname(ptm)) == 0)){
379         D("[ trouble with /dev/ptmx - %s ]\n", strerror(errno));
380         sdb_close(ptm);
381         return -1;
382     }
383
384     *pid = fork();
385     if(*pid < 0) {
386         D("- fork failed: %s -\n", strerror(errno));
387         sdb_close(ptm);
388         return -1;
389     }
390
391     if(*pid == 0){
392         int pts;
393
394         setsid();
395
396         pts = unix_open(devname, O_RDWR);
397         if(pts < 0) {
398             fprintf(stderr, "child failed to open pseudo-term slave: %s\n", devname);
399             exit(-1);
400         }
401
402         dup2(pts, 0);
403         dup2(pts, 1);
404         dup2(pts, 2);
405
406         sdb_close(pts);
407         sdb_close(ptm);
408
409         // set OOM adjustment to zero
410         {
411             char text[64];
412             snprintf(text, sizeof text, "/proc/%d/oom_adj", getpid());
413             int fd = sdb_open(text, O_WRONLY);
414             if (fd >= 0) {
415                 sdb_write(fd, "0", 1);
416                 sdb_close(fd);
417             } else {
418                // FIXME: not supposed to be here
419                D("sdb: unable to open %s due to %s\n", text, strerror(errno));
420             }
421         }
422
423         verify_commands(arg1);
424
425         execl(cmd, cmd, arg0, arg1, NULL);
426         fprintf(stderr, "- exec '%s' failed: %s (%d) -\n",
427                 cmd, strerror(errno), errno);
428         exit(-1);
429     } else {
430         // Don't set child's OOM adjustment to zero.
431         // Let the child do it itself, as sometimes the parent starts
432         // running before the child has a /proc/pid/oom_adj.
433         // """sdb: unable to open /proc/644/oom_adj""" seen in some logs.
434         return ptm;
435     }
436 #endif /* !HAVE_WIN32_PROC */
437 }
438 #endif  /* !SDB_HOST */
439
440 #if SDB_HOST
441 #define SHELL_COMMAND "/bin/sh"
442 #else
443 #define SHELL_COMMAND "/bin/sh" /* tizen specific */
444 #endif
445
446 #if !SDB_HOST
447 static void subproc_waiter_service(int fd, void *cookie)
448 {
449     pid_t pid = (pid_t)cookie;
450
451     D("entered. fd=%d of pid=%d\n", fd, pid);
452     for (;;) {
453         int status;
454         pid_t p = waitpid(pid, &status, 0);
455         if (p == pid) {
456             D("fd=%d, post waitpid(pid=%d) status=%04x\n", fd, p, status);
457             
458             if (WIFEXITED(status)) {
459                 D("*** Exit code %d\n", WEXITSTATUS(status));
460                 break;
461             } else if (WIFSIGNALED(status)) {
462                 D("*** Killed by signal %d\n", WTERMSIG(status));
463                 break;
464             } else {
465                 D("*** Killed by unknown code %d\n", status);
466                 break;
467             }
468          }
469     }
470     D("shell exited fd=%d of pid=%d err=%d\n", fd, pid, errno);
471     if (SHELL_EXIT_NOTIFY_FD >=0) {
472       int res;
473       res = writex(SHELL_EXIT_NOTIFY_FD, &fd, sizeof(fd));
474       D("notified shell exit via fd=%d for pid=%d res=%d errno=%d\n",
475         SHELL_EXIT_NOTIFY_FD, pid, res, errno);
476     }
477 }
478
479 static int create_subproc_thread(const char *name)
480 {
481     stinfo *sti;
482     sdb_thread_t t;
483     int ret_fd;
484     pid_t pid;
485
486     if(name) {
487         ret_fd = create_subprocess(SHELL_COMMAND, "-c", name, &pid);
488     } else {
489         ret_fd = create_subprocess(SHELL_COMMAND, "-", 0, &pid);
490     }
491     D("create_subprocess() ret_fd=%d pid=%d\n", ret_fd, pid);
492
493     if (ret_fd < 0) {
494         D("cannot create service thread\n");
495         return -1;
496     }
497     sti = malloc(sizeof(stinfo));
498     if(sti == 0) fatal("cannot allocate stinfo");
499     sti->func = subproc_waiter_service;
500     sti->cookie = (void*)pid;
501     sti->fd = ret_fd;
502
503     if(sdb_thread_create( &t, service_bootstrap_func, sti)){
504         free(sti);
505         sdb_close(ret_fd);
506         D("cannot create service thread\n");
507         return -1;
508     }
509
510     D("service thread started, fd=%d pid=%d\n",ret_fd, pid);
511     return ret_fd;
512 }
513
514 static int create_sync_subprocess(void (*func)(int, void *), void* cookie) {
515     stinfo *sti;
516     sdb_thread_t t;
517     int s[2];
518
519     if(sdb_socketpair(s)) {
520         D("cannot create service socket pair\n");
521         return -1;
522     }
523
524     pid_t pid = fork();
525
526     if (pid == 0) {
527         sdb_close(s[0]);
528         func(s[1], cookie);
529         exit(-1);
530     } else if (pid > 0) {
531         sdb_close(s[1]);
532         // FIXME: do not wait child process hear
533         //waitpid(pid, &ret, 0);
534     }
535     if (pid < 0) {
536         D("- fork failed: %s -\n", strerror(errno));
537         sdb_close(s[0]);
538         sdb_close(s[1]);
539         D("cannot create sync service sub process\n");
540         return -1;
541     }
542
543     sti = malloc(sizeof(stinfo));
544     if(sti == 0) fatal("cannot allocate stinfo");
545     sti->func = subproc_waiter_service;
546     sti->cookie = (void*)pid;
547     sti->fd = s[0];
548
549     if(sdb_thread_create( &t, service_bootstrap_func, sti)){
550         free(sti);
551         sdb_close(s[0]);
552         sdb_close(s[1]);
553         printf("cannot create service monitor thread\n");
554         return -1;
555     }
556
557     D("service process started, fd=%d pid=%d\n",s[0], pid);
558     return s[0];
559 }
560
561 static int create_syncproc_thread()
562 {
563     int ret_fd;
564
565     ret_fd = create_sync_subprocess(file_sync_service, NULL);
566     // FIXME: file missing bug when root on mode
567     /*
568     if (should_drop_privileges()) {
569         ret_fd = create_sync_subprocess(file_sync_service, NULL);
570     } else {
571         ret_fd = create_service_thread(file_sync_service, NULL);
572     }
573     */
574
575     return ret_fd;
576 }
577
578 #endif
579
580 int service_to_fd(const char *name)
581 {
582     int ret = -1;
583
584     if(!strncmp(name, "tcp:", 4)) {
585         int port = atoi(name + 4);
586         name = strchr(name + 4, ':');
587         if(name == 0) {
588             ret = socket_loopback_client(port, SOCK_STREAM);
589             if (ret >= 0)
590                 disable_tcp_nagle(ret);
591         } else {
592 #if SDB_HOST
593             sdb_mutex_lock(&dns_lock);
594             ret = socket_network_client(name + 1, port, SOCK_STREAM);
595             sdb_mutex_unlock(&dns_lock);
596 #else
597             return -1;
598 #endif
599         }
600 #ifndef HAVE_WINSOCK   /* winsock doesn't implement unix domain sockets */
601     } else if(!strncmp(name, "local:", 6)) {
602         ret = socket_local_client(name + 6,
603                 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_STREAM);
604     } else if(!strncmp(name, "localreserved:", 14)) {
605         ret = socket_local_client(name + 14,
606                 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_STREAM);
607     } else if(!strncmp(name, "localabstract:", 14)) {
608         ret = socket_local_client(name + 14,
609                 ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
610     } else if(!strncmp(name, "localfilesystem:", 16)) {
611         ret = socket_local_client(name + 16,
612                 ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
613 #endif
614 #if SDB_HOST
615     } else if(!strncmp("dns:", name, 4)){
616         char *n = strdup(name + 4);
617         if(n == 0) return -1;
618         ret = create_service_thread(dns_service, n);
619 #else /* !SDB_HOST */
620     }/* else if(!strncmp("dev:", name, 4)) {// tizen specific
621         ret = unix_open(name + 4, O_RDWR);
622     } else if(!strncmp(name, "framebuffer:", 12)) {
623         ret = create_service_thread(framebuffer_service, 0);
624     } else if(recovery_mode && !strncmp(name, "recover:", 8)) {
625         ret = create_service_thread(recover_service, (void*) atoi(name + 8));
626     } else if (!strncmp(name, "jdwp:", 5)) {
627         ret = create_jdwp_connection_fd(atoi(name+5));
628     } else if (!strncmp(name, "log:", 4)) {
629         ret = create_service_thread(log_service, get_log_file_path(name + 4));
630     }*/ else if(!HOST && !strncmp(name, "shell:", 6)) {
631         if(name[6]) {
632             ret = create_subproc_thread(name + 6);
633         } else {
634             ret = create_subproc_thread(0);
635         }
636     } else if(!strncmp(name, "sync:", 5)) {
637         //ret = create_service_thread(file_sync_service, NULL);
638         ret = create_syncproc_thread();
639     }/*  else if(!strncmp(name, "remount:", 8)) {
640         ret = create_service_thread(remount_service, NULL);
641     } else if(!strncmp(name, "reboot:", 7)) {
642         void* arg = strdup(name + 7);
643         if(arg == 0) return -1;
644         ret = create_service_thread(reboot_service, arg);
645     } else if(!strncmp(name, "root:", 5)) {
646         ret = create_service_thread(restart_root_service, NULL);
647     } else if(!strncmp(name, "backup:", 7)) {
648         char* arg = strdup(name+7);
649         if (arg == NULL) return -1;
650         ret = backup_service(BACKUP, arg);
651     } else if(!strncmp(name, "restore:", 8)) {
652         ret = backup_service(RESTORE, NULL);
653     }*/ else if(!strncmp(name, "root:", 5)) {
654         ret = create_service_thread(rootshell_service, (void *)(name+5));
655     } else if(!strncmp(name, "tcpip:", 6)) {
656         int port;
657         /*if (sscanf(name + 6, "%d", &port) == 0) {
658             port = 0;
659         }*/
660         port = DEFAULT_SDB_LOCAL_TRANSPORT_PORT;
661         ret = create_service_thread(restart_tcp_service, (void *)port);
662     } else if(!strncmp(name, "usb:", 4)) {
663         ret = create_service_thread(restart_usb_service, NULL);
664     } else if(!strncmp(name, "cs:", 5)) {
665         ret = create_service_thread(inoti_service, NULL);
666 #endif
667 #if 0
668     } else if(!strncmp(name, "echo:", 5)){
669         ret = create_service_thread(echo_service, 0);
670 #endif
671     }
672     if (ret >= 0) {
673         if (close_on_exec(ret) < 0) {
674             D("failed to close fd exec\n");
675         }
676     }
677     return ret;
678 }
679
680 #if SDB_HOST
681 struct state_info {
682     transport_type transport;
683     char* serial;
684     int state;
685 };
686
687 static void wait_for_state(int fd, void* cookie)
688 {
689     struct state_info* sinfo = cookie;
690     char* err = "unknown error";
691
692     D("wait_for_state %d\n", sinfo->state);
693
694     atransport *t = acquire_one_transport(sinfo->state, sinfo->transport, sinfo->serial, &err);
695     if(t != 0) {
696         writex(fd, "OKAY", 4);
697     } else {
698         sendfailmsg(fd, err);
699     }
700
701     if (sinfo->serial)
702         free(sinfo->serial);
703     free(sinfo);
704     sdb_close(fd);
705     D("wait_for_state is done\n");
706 }
707 #endif
708
709 #if SDB_HOST
710 asocket*  host_service_to_socket(const char*  name, const char *serial)
711 {
712     if (!strcmp(name,"track-devices")) {
713         return create_device_tracker();
714     } else if (!strncmp(name, "wait-for-", strlen("wait-for-"))) {
715         struct state_info* sinfo = malloc(sizeof(struct state_info));
716
717         if (serial)
718             sinfo->serial = strdup(serial);
719         else
720             sinfo->serial = NULL;
721
722         name += strlen("wait-for-");
723
724         if (!strncmp(name, "local", strlen("local"))) {
725             sinfo->transport = kTransportLocal;
726             sinfo->state = CS_DEVICE;
727         } else if (!strncmp(name, "usb", strlen("usb"))) {
728             sinfo->transport = kTransportUsb;
729             sinfo->state = CS_DEVICE;
730         } else if (!strncmp(name, "any", strlen("any"))) {
731             sinfo->transport = kTransportAny;
732             sinfo->state = CS_DEVICE;
733         } else {
734             free(sinfo);
735             return NULL;
736         }
737
738         int fd = create_service_thread(wait_for_state, sinfo);
739         return create_local_socket(fd);
740     }
741     return NULL;
742 }
743 #endif /* SDB_HOST */