OSDN Git Service

Fix building issues with pie-x86
[android-x86/external-koush-Superuser.git] / Superuser / jni / su / daemon.c
1 /*
2 ** Copyright 2010, Adam Shanks (@ChainsDD)
3 ** Copyright 2008, Zinx Verituse (@zinxv)
4 **
5 ** Licensed under the Apache License, Version 2.0 (the "License");
6 ** you may not use this file except in compliance with the License.
7 ** You may obtain a copy of the License at
8 **
9 **     http://www.apache.org/licenses/LICENSE-2.0
10 **
11 ** Unless required by applicable law or agreed to in writing, software
12 ** distributed under the License is distributed on an "AS IS" BASIS,
13 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 ** See the License for the specific language governing permissions and
15 ** limitations under the License.
16 */
17
18 #define _GNU_SOURCE /* for unshare() */
19
20 #include <sys/types.h>
21 #include <sys/socket.h>
22 #include <sys/un.h>
23 #include <sys/wait.h>
24 #include <sys/select.h>
25 #include <sys/time.h>
26 #include <unistd.h>
27 #include <limits.h>
28 #include <fcntl.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <getopt.h>
32 #include <stdint.h>
33 #include <pwd.h>
34 #include <sys/mount.h>
35 #include <sys/stat.h>
36 #include <stdarg.h>
37 #include <sys/types.h>
38 #include <pthread.h>
39 #include <sched.h>
40 #include <termios.h>
41 #include <signal.h>
42 #include <string.h>
43
44 #ifdef SUPERUSER_EMBEDDED
45 #include <cutils/multiuser.h>
46 #endif
47
48 #include "su.h"
49 #include "utils.h"
50 #include "pts.h"
51
52 int is_daemon = 0;
53 int daemon_from_uid = 0;
54 int daemon_from_pid = 0;
55
56 // Constants for the atty bitfield
57 #define ATTY_IN     1
58 #define ATTY_OUT    2
59 #define ATTY_ERR    4
60
61 /*
62  * Receive a file descriptor from a Unix socket.
63  * Contributed by @mkasick
64  *
65  * Returns the file descriptor on success, or -1 if a file
66  * descriptor was not actually included in the message
67  *
68  * On error the function terminates by calling exit(-1)
69  */
70 static int recv_fd(int sockfd) {
71     // Need to receive data from the message, otherwise don't care about it.
72     char iovbuf;
73
74     struct iovec iov = {
75         .iov_base = &iovbuf,
76         .iov_len  = 1,
77     };
78
79     char cmsgbuf[CMSG_SPACE(sizeof(int))];
80
81     struct msghdr msg = {
82         .msg_iov        = &iov,
83         .msg_iovlen     = 1,
84         .msg_control    = cmsgbuf,
85         .msg_controllen = sizeof(cmsgbuf),
86     };
87
88     if (recvmsg(sockfd, &msg, MSG_WAITALL) != 1) {
89         goto error;
90     }
91
92     // Was a control message actually sent?
93     switch (msg.msg_controllen) {
94     case 0:
95         // No, so the file descriptor was closed and won't be used.
96         return -1;
97     case sizeof(cmsgbuf):
98         // Yes, grab the file descriptor from it.
99         break;
100     default:
101         goto error;
102     }
103
104     struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
105
106     if (cmsg             == NULL                  ||
107         cmsg->cmsg_len   != CMSG_LEN(sizeof(int)) ||
108         cmsg->cmsg_level != SOL_SOCKET            ||
109         cmsg->cmsg_type  != SCM_RIGHTS) {
110 error:
111         LOGE("unable to read fd");
112         exit(-1);
113     }
114
115     return *(int *)CMSG_DATA(cmsg);
116 }
117
118 /*
119  * Send a file descriptor through a Unix socket.
120  * Contributed by @mkasick
121  *
122  * On error the function terminates by calling exit(-1)
123  *
124  * fd may be -1, in which case the dummy data is sent,
125  * but no control message with the FD is sent.
126  */
127 static void send_fd(int sockfd, int fd) {
128     // Need to send some data in the message, this will do.
129     struct iovec iov = {
130         .iov_base = "",
131         .iov_len  = 1,
132     };
133
134     struct msghdr msg = {
135         .msg_iov        = &iov,
136         .msg_iovlen     = 1,
137     };
138
139     char cmsgbuf[CMSG_SPACE(sizeof(int))];
140
141     if (fd != -1) {
142         // Is the file descriptor actually open?
143         if (fcntl(fd, F_GETFD) == -1) {
144             if (errno != EBADF) {
145                 goto error;
146             }
147             // It's closed, don't send a control message or sendmsg will EBADF.
148         } else {
149             // It's open, send the file descriptor in a control message.
150             msg.msg_control    = cmsgbuf;
151             msg.msg_controllen = sizeof(cmsgbuf);
152
153             struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
154
155             cmsg->cmsg_len   = CMSG_LEN(sizeof(int));
156             cmsg->cmsg_level = SOL_SOCKET;
157             cmsg->cmsg_type  = SCM_RIGHTS;
158
159             *(int *)CMSG_DATA(cmsg) = fd;
160         }
161     }
162
163     if (sendmsg(sockfd, &msg, 0) != 1) {
164 error:
165         PLOGE("unable to send fd");
166         exit(-1);
167     }
168 }
169
170 static int read_int(int fd) {
171     int val;
172     int len = read(fd, &val, sizeof(int));
173     if (len != sizeof(int)) {
174         LOGE("unable to read int: %d", len);
175         exit(-1);
176     }
177     return val;
178 }
179
180 static void write_int(int fd, int val) {
181     int written = write(fd, &val, sizeof(int));
182     if (written != sizeof(int)) {
183         PLOGE("unable to write int");
184         exit(-1);
185     }
186 }
187
188 static char* read_string(int fd) {
189     int len = read_int(fd);
190     if (len > PATH_MAX || len < 0) {
191         LOGE("invalid string length %d", len);
192         exit(-1);
193     }
194     char* val = malloc(sizeof(char) * (len + 1));
195     if (val == NULL) {
196         LOGE("unable to malloc string");
197         exit(-1);
198     }
199     val[len] = '\0';
200     int amount = read(fd, val, len);
201     if (amount != len) {
202         LOGE("unable to read string");
203         exit(-1);
204     }
205     return val;
206 }
207
208 static void write_string(int fd, char* val) {
209     int len = strlen(val);
210     write_int(fd, len);
211     int written = write(fd, val, len);
212     if (written != len) {
213         PLOGE("unable to write string");
214         exit(-1);
215     }
216 }
217
218 #ifdef SUPERUSER_EMBEDDED
219 static void mount_emulated_storage(int user_id) {
220     const char *emulated_source = getenv("EMULATED_STORAGE_SOURCE");
221     const char *emulated_target = getenv("EMULATED_STORAGE_TARGET");
222     const char* legacy = getenv("EXTERNAL_STORAGE");
223
224     if (!emulated_source || !emulated_target) {
225         // No emulated storage is present
226         return;
227     }
228
229     // Create a second private mount namespace for our process
230     if (unshare(CLONE_NEWNS) < 0) {
231         PLOGE("unshare");
232         return;
233     }
234
235     if (mount("rootfs", "/", NULL, MS_SLAVE | MS_REC, NULL) < 0) {
236         PLOGE("mount rootfs as slave");
237         return;
238     }
239
240     // /mnt/shell/emulated -> /storage/emulated
241     if (mount(emulated_source, emulated_target, NULL, MS_BIND, NULL) < 0) {
242         PLOGE("mount emulated storage");
243     }
244
245     char target_user[PATH_MAX];
246     snprintf(target_user, PATH_MAX, "%s/%d", emulated_target, user_id);
247
248     // /mnt/shell/emulated/<user> -> /storage/emulated/legacy
249     if (mount(target_user, legacy, NULL, MS_BIND | MS_REC, NULL) < 0) {
250         PLOGE("mount legacy path");
251     }
252 }
253 #endif
254
255 static int run_daemon_child(int infd, int outfd, int errfd, int argc, char** argv) {
256     if (-1 == dup2(outfd, STDOUT_FILENO)) {
257         PLOGE("dup2 child outfd");
258         exit(-1);
259     }
260
261     if (-1 == dup2(errfd, STDERR_FILENO)) {
262         PLOGE("dup2 child errfd");
263         exit(-1);
264     }
265
266     if (-1 == dup2(infd, STDIN_FILENO)) {
267         PLOGE("dup2 child infd");
268         exit(-1);
269     }
270
271     close(infd);
272     close(outfd);
273     close(errfd);
274
275     return su_main(argc, argv, 0);
276 }
277
278 static int pid_to_exe(int pid, char *exe) {
279     char path[PATH_MAX];
280     int len;
281
282     snprintf(path, sizeof(path), "/proc/%u/exe", pid);
283     len = readlink(path, exe, sizeof(path));
284     if (len < 0) {
285         PLOGE("Getting exe path");
286         return -1;
287     }
288     exe[len] = '\0';
289     return 0;
290 }
291
292 static int daemon_accept(int fd) {
293     char mypath[PATH_MAX], remotepath[PATH_MAX];
294     int caller_is_self = 0;
295
296     is_daemon = 1;
297     int pid = read_int(fd);
298     LOGD("remote pid: %d", pid);
299     char *pts_slave = read_string(fd);
300     LOGD("remote pts_slave: %s", pts_slave);
301     daemon_from_uid = read_int(fd);
302     LOGD("remote uid: %d", daemon_from_uid);
303     daemon_from_pid = read_int(fd);
304     LOGD("remote req pid: %d", daemon_from_pid);
305
306     struct ucred credentials;
307     socklen_t ucred_length = sizeof(struct ucred);
308     /* fill in the user data structure */
309     if(getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &credentials, &ucred_length)) {
310         LOGE("could obtain credentials from unix domain socket");
311         exit(-1);
312     }
313
314     if (!pid_to_exe(getpid(),mypath) &&
315             !pid_to_exe(credentials.pid,remotepath)) {
316         if (!strncmp(mypath,remotepath,PATH_MAX)) caller_is_self = 1;
317     }
318     // if the credentials on the other side imply that
319     // we're not calling ourselves, we can't trust anything being sent.
320     if (!caller_is_self) {
321         daemon_from_uid = credentials.uid;
322         pid = credentials.pid;
323         daemon_from_pid = credentials.pid;
324     }
325
326     int mount_storage = read_int(fd);
327     // The the FDs for each of the streams
328     int infd  = recv_fd(fd);
329     int outfd = recv_fd(fd);
330     int errfd = recv_fd(fd);
331
332     int argc = read_int(fd);
333     if (argc < 0 || argc > 512) {
334         LOGE("unable to allocate args: %d", argc);
335         exit(-1);
336     }
337     LOGD("remote args: %d", argc);
338     char** argv = (char**)malloc(sizeof(char*) * (argc + 1));
339     argv[argc] = NULL;
340     int i;
341     for (i = 0; i < argc; i++) {
342         argv[i] = read_string(fd);
343     }
344
345     // ack
346     write_int(fd, 1);
347
348     // Fork the child process. The fork has to happen before calling
349     // setsid() and opening the pseudo-terminal so that the parent
350     // is not affected
351     int child = fork();
352     if (child < 0) {
353         // fork failed, send a return code and bail out
354         PLOGE("unable to fork");
355         write(fd, &child, sizeof(int));
356         close(fd);
357         return child;
358     }
359
360     if (child != 0) {
361         // In parent, wait for the child to exit, and send the exit code
362         // across the wire.
363         int status, code;
364
365         free(pts_slave);
366
367         LOGD("waiting for child exit");
368         if (waitpid(child, &status, 0) > 0) {
369             code = WEXITSTATUS(status);
370         }
371         else {
372             code = -1;
373         }
374
375         // Pass the return code back to the client
376         LOGD("sending code");
377         if (write(fd, &code, sizeof(int)) != sizeof(int)) {
378             PLOGE("unable to write exit code");
379         }
380
381         close(fd);
382         LOGD("child exited");
383         return code;
384     }
385
386     // We are in the child now
387     // Close the unix socket file descriptor
388     close (fd);
389
390     // Become session leader
391     if (setsid() == (pid_t) -1) {
392         PLOGE("setsid");
393     }
394
395     int ptsfd;
396     if (pts_slave[0]) {
397         // Opening the TTY has to occur after the
398         // fork() and setsid() so that it becomes
399         // our controlling TTY and not the daemon's
400         ptsfd = open(pts_slave, O_RDWR);
401         if (ptsfd == -1) {
402             PLOGE("open(pts_slave) daemon");
403             exit(-1);
404         }
405
406         if (infd < 0)  {
407             LOGD("daemon: stdin using PTY");
408             infd  = ptsfd;
409         }
410         if (outfd < 0) {
411             LOGD("daemon: stdout using PTY");
412             outfd = ptsfd;
413         }
414         if (errfd < 0) {
415             LOGD("daemon: stderr using PTY");
416             errfd = ptsfd;
417         }
418     } else {
419         // If a TTY was sent directly, make it the CTTY.
420         if (isatty(infd)) {
421             ioctl(infd, TIOCSCTTY, 1);
422         }
423     }
424     free(pts_slave);
425
426 #ifdef SUPERUSER_EMBEDDED
427     if (mount_storage) {
428         mount_emulated_storage(multiuser_get_user_id(daemon_from_uid));
429     }
430 #endif
431
432     return run_daemon_child(infd, outfd, errfd, argc, argv);
433 }
434
435 int run_daemon() {
436     if (getuid() != 0 || getgid() != 0) {
437         PLOGE("daemon requires root. uid/gid not root");
438         return -1;
439     }
440
441     int fd;
442     struct sockaddr_un sun;
443
444     fd = socket(AF_LOCAL, SOCK_STREAM, 0);
445     if (fd < 0) {
446         PLOGE("socket");
447         return -1;
448     }
449     if (fcntl(fd, F_SETFD, FD_CLOEXEC)) {
450         PLOGE("fcntl FD_CLOEXEC");
451         goto err;
452     }
453
454     memset(&sun, 0, sizeof(sun));
455     sun.sun_family = AF_LOCAL;
456     sprintf(sun.sun_path, "%s/server", REQUESTOR_DAEMON_PATH);
457
458     /*
459      * Delete the socket to protect from situations when
460      * something bad occured previously and the kernel reused pid from that process.
461      * Small probability, isn't it.
462      */
463     unlink(sun.sun_path);
464     unlink(REQUESTOR_DAEMON_PATH);
465
466     int previous_umask = umask(027);
467     mkdir(REQUESTOR_DAEMON_PATH, 0777);
468
469     memset(sun.sun_path, 0, sizeof(sun.sun_path));
470     memcpy(sun.sun_path, "\0" "SUPERUSER", strlen("SUPERUSER") + 1);
471
472     if (bind(fd, (struct sockaddr*)&sun, sizeof(sun)) < 0) {
473         PLOGE("daemon bind");
474         goto err;
475     }
476
477     chmod(REQUESTOR_DAEMON_PATH, 0755);
478     chmod(sun.sun_path, 0777);
479
480     umask(previous_umask);
481
482     if (listen(fd, 10) < 0) {
483         PLOGE("daemon listen");
484         goto err;
485     }
486
487     int client;
488     while ((client = accept(fd, NULL, NULL)) > 0) {
489         if (fork_zero_fucks() == 0) {
490             close(fd);
491             return daemon_accept(client);
492         }
493         else {
494             close(client);
495         }
496     }
497
498     LOGE("daemon exiting");
499 err:
500     close(fd);
501     return -1;
502 }
503
504 // List of signals which cause process termination
505 static int quit_signals[] = { SIGALRM, SIGHUP, SIGPIPE, SIGQUIT, SIGTERM, SIGINT, 0 };
506
507 static void sighandler(int __attribute__((unused))sig) {
508     restore_stdin();
509
510     // Assume we'll only be called before death
511     // See note before sigaction() in set_stdin_raw()
512     //
513     // Now, close all standard I/O to cause the pumps
514     // to exit so we can continue and retrieve the exit
515     // code
516     close(STDIN_FILENO);
517     close(STDOUT_FILENO);
518     close(STDERR_FILENO);
519
520     // Put back all the default handlers
521     struct sigaction act;
522     int i;
523
524     memset(&act, '\0', sizeof(act));
525     act.sa_handler = SIG_DFL;
526     for (i = 0; quit_signals[i]; i++) {
527         if (sigaction(quit_signals[i], &act, NULL) < 0) {
528             PLOGE("Error removing signal handler");
529             continue;
530         }
531     }
532 }
533
534 /**
535  * Setup signal handlers trap signals which should result in program termination
536  * so that we can restore the terminal to its normal state and retrieve the 
537  * return code.
538  */
539 static void setup_sighandlers(void) {
540     struct sigaction act;
541     int i;
542
543     // Install the termination handlers
544     // Note: we're assuming that none of these signal handlers are already trapped.
545     // If they are, we'll need to modify this code to save the previous handler and
546     // call it after we restore stdin to its previous state.
547     memset(&act, '\0', sizeof(act));
548     act.sa_handler = &sighandler;
549     for (i = 0; quit_signals[i]; i++) {
550         if (sigaction(quit_signals[i], &act, NULL) < 0) {
551             PLOGE("Error installing signal handler");
552             continue;
553         }
554     }
555 }
556
557 int connect_daemon(int argc, char *argv[], int ppid) {
558     int uid = getuid();
559     int ptmx = -1;
560     char pts_slave[PATH_MAX];
561
562     struct sockaddr_un sun;
563
564     // Open a socket to the daemon
565     int socketfd = socket(AF_LOCAL, SOCK_STREAM, 0);
566     if (socketfd < 0) {
567         PLOGE("socket");
568         exit(-1);
569     }
570     if (fcntl(socketfd, F_SETFD, FD_CLOEXEC)) {
571         PLOGE("fcntl FD_CLOEXEC");
572         exit(-1);
573     }
574
575     memset(&sun, 0, sizeof(sun));
576     sun.sun_family = AF_LOCAL;
577     sprintf(sun.sun_path, "%s/server", REQUESTOR_DAEMON_PATH);
578
579     memset(sun.sun_path, 0, sizeof(sun.sun_path));
580     memcpy(sun.sun_path, "\0" "SUPERUSER", strlen("SUPERUSER") + 1);
581
582     if (0 != connect(socketfd, (struct sockaddr*)&sun, sizeof(sun))) {
583         PLOGE("connect");
584         exit(-1);
585     }
586
587     LOGD("connecting client %d", getpid());
588
589     int mount_storage = getenv("MOUNT_EMULATED_STORAGE") != NULL;
590
591     // Determine which one of our streams are attached to a TTY
592     int atty = 0;
593
594     // Send TTYs directly (instead of proxying with a PTY) if
595     // the SUPERUSER_SEND_TTY environment variable is set.
596     if (getenv("SUPERUSER_SEND_TTY") == NULL) {
597         if (isatty(STDIN_FILENO))  atty |= ATTY_IN;
598         if (isatty(STDOUT_FILENO)) atty |= ATTY_OUT;
599         if (isatty(STDERR_FILENO)) atty |= ATTY_ERR;
600     }
601
602     if (atty) {
603         // We need a PTY. Get one.
604         ptmx = pts_open(pts_slave, sizeof(pts_slave));
605         if (ptmx < 0) {
606             PLOGE("pts_open");
607             exit(-1);
608         }
609     } else {
610         pts_slave[0] = '\0';
611     }
612
613     // Send some info to the daemon, starting with our PID
614     write_int(socketfd, getpid());
615     // Send the slave path to the daemon
616     // (This is "" if we're not using PTYs)
617     write_string(socketfd, pts_slave);
618     // User ID
619     write_int(socketfd, uid);
620     // Parent PID
621     write_int(socketfd, ppid);
622     write_int(socketfd, mount_storage);
623
624     // Send stdin
625     if (atty & ATTY_IN) {
626         // Using PTY
627         send_fd(socketfd, -1);
628     } else {
629         send_fd(socketfd, STDIN_FILENO);
630     }
631
632     // Send stdout
633     if (atty & ATTY_OUT) {
634         // Forward SIGWINCH
635         watch_sigwinch_async(STDOUT_FILENO, ptmx);
636
637         // Using PTY
638         send_fd(socketfd, -1);
639     } else {
640         send_fd(socketfd, STDOUT_FILENO);
641     }
642
643     // Send stderr
644     if (atty & ATTY_ERR) {
645         // Using PTY
646         send_fd(socketfd, -1);
647     } else {
648         send_fd(socketfd, STDERR_FILENO);
649     }
650
651     // Number of command line arguments
652     write_int(socketfd, mount_storage ? argc - 1 : argc);
653
654     // Command line arguments
655     int i;
656     for (i = 0; i < argc; i++) {
657         if (i == 1 && mount_storage) {
658             continue;
659         }
660         write_string(socketfd, argv[i]);
661     }
662
663     // Wait for acknowledgement from daemon
664     read_int(socketfd);
665
666     if (atty & ATTY_IN) {
667         setup_sighandlers();
668         pump_stdin_async(ptmx);
669     }
670     if (atty & ATTY_OUT) {
671         pump_stdout_blocking(ptmx);
672     }
673
674     // Get the exit code
675     int code = read_int(socketfd);
676     close(socketfd);
677     LOGD("client exited %d", code);
678
679     return code;
680 }