2 ** Copyright 2010, Adam Shanks (@ChainsDD)
3 ** Copyright 2008, Zinx Verituse (@zinxv)
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
9 ** http://www.apache.org/licenses/LICENSE-2.0
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.
18 #define _GNU_SOURCE /* for unshare() */
20 #include <sys/types.h>
21 #include <sys/socket.h>
24 #include <sys/select.h>
34 #include <sys/mount.h>
37 #include <sys/types.h>
44 #ifdef SUPERUSER_EMBEDDED
45 #include <cutils/multiuser.h>
53 int daemon_from_uid = 0;
54 int daemon_from_pid = 0;
56 // Constants for the atty bitfield
62 * Receive a file descriptor from a Unix socket.
63 * Contributed by @mkasick
65 * Returns the file descriptor on success, or -1 if a file
66 * descriptor was not actually included in the message
68 * On error the function terminates by calling exit(-1)
70 static int recv_fd(int sockfd) {
71 // Need to receive data from the message, otherwise don't care about it.
79 char cmsgbuf[CMSG_SPACE(sizeof(int))];
84 .msg_control = cmsgbuf,
85 .msg_controllen = sizeof(cmsgbuf),
88 if (recvmsg(sockfd, &msg, MSG_WAITALL) != 1) {
92 // Was a control message actually sent?
93 switch (msg.msg_controllen) {
95 // No, so the file descriptor was closed and won't be used.
98 // Yes, grab the file descriptor from it.
104 struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
107 cmsg->cmsg_len != CMSG_LEN(sizeof(int)) ||
108 cmsg->cmsg_level != SOL_SOCKET ||
109 cmsg->cmsg_type != SCM_RIGHTS) {
111 LOGE("unable to read fd");
115 return *(int *)CMSG_DATA(cmsg);
119 * Send a file descriptor through a Unix socket.
120 * Contributed by @mkasick
122 * On error the function terminates by calling exit(-1)
124 * fd may be -1, in which case the dummy data is sent,
125 * but no control message with the FD is sent.
127 static void send_fd(int sockfd, int fd) {
128 // Need to send some data in the message, this will do.
134 struct msghdr msg = {
139 char cmsgbuf[CMSG_SPACE(sizeof(int))];
142 // Is the file descriptor actually open?
143 if (fcntl(fd, F_GETFD) == -1) {
144 if (errno != EBADF) {
147 // It's closed, don't send a control message or sendmsg will EBADF.
149 // It's open, send the file descriptor in a control message.
150 msg.msg_control = cmsgbuf;
151 msg.msg_controllen = sizeof(cmsgbuf);
153 struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
155 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
156 cmsg->cmsg_level = SOL_SOCKET;
157 cmsg->cmsg_type = SCM_RIGHTS;
159 *(int *)CMSG_DATA(cmsg) = fd;
163 if (sendmsg(sockfd, &msg, 0) != 1) {
165 PLOGE("unable to send fd");
170 static int read_int(int fd) {
172 int len = read(fd, &val, sizeof(int));
173 if (len != sizeof(int)) {
174 LOGE("unable to read int: %d", len);
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");
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);
194 char* val = malloc(sizeof(char) * (len + 1));
196 LOGE("unable to malloc string");
200 int amount = read(fd, val, len);
202 LOGE("unable to read string");
208 static void write_string(int fd, char* val) {
209 int len = strlen(val);
211 int written = write(fd, val, len);
212 if (written != len) {
213 PLOGE("unable to write string");
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");
224 if (!emulated_source || !emulated_target) {
225 // No emulated storage is present
229 // Create a second private mount namespace for our process
230 if (unshare(CLONE_NEWNS) < 0) {
235 if (mount("rootfs", "/", NULL, MS_SLAVE | MS_REC, NULL) < 0) {
236 PLOGE("mount rootfs as slave");
240 // /mnt/shell/emulated -> /storage/emulated
241 if (mount(emulated_source, emulated_target, NULL, MS_BIND, NULL) < 0) {
242 PLOGE("mount emulated storage");
245 char target_user[PATH_MAX];
246 snprintf(target_user, PATH_MAX, "%s/%d", emulated_target, user_id);
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");
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");
261 if (-1 == dup2(errfd, STDERR_FILENO)) {
262 PLOGE("dup2 child errfd");
266 if (-1 == dup2(infd, STDIN_FILENO)) {
267 PLOGE("dup2 child infd");
275 return su_main(argc, argv, 0);
278 static int pid_to_exe(int pid, char *exe) {
282 snprintf(path, sizeof(path), "/proc/%u/exe", pid);
283 len = readlink(path, exe, sizeof(path));
285 PLOGE("Getting exe path");
292 static int daemon_accept(int fd) {
293 char mypath[PATH_MAX], remotepath[PATH_MAX];
294 int caller_is_self = 0;
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);
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");
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;
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;
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);
332 int argc = read_int(fd);
333 if (argc < 0 || argc > 512) {
334 LOGE("unable to allocate args: %d", argc);
337 LOGD("remote args: %d", argc);
338 char** argv = (char**)malloc(sizeof(char*) * (argc + 1));
341 for (i = 0; i < argc; i++) {
342 argv[i] = read_string(fd);
348 // Fork the child process. The fork has to happen before calling
349 // setsid() and opening the pseudo-terminal so that the parent
353 // fork failed, send a return code and bail out
354 PLOGE("unable to fork");
355 write(fd, &child, sizeof(int));
361 // In parent, wait for the child to exit, and send the exit code
367 LOGD("waiting for child exit");
368 if (waitpid(child, &status, 0) > 0) {
369 code = WEXITSTATUS(status);
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");
382 LOGD("child exited");
386 // We are in the child now
387 // Close the unix socket file descriptor
390 // Become session leader
391 if (setsid() == (pid_t) -1) {
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);
402 PLOGE("open(pts_slave) daemon");
407 LOGD("daemon: stdin using PTY");
411 LOGD("daemon: stdout using PTY");
415 LOGD("daemon: stderr using PTY");
419 // If a TTY was sent directly, make it the CTTY.
421 ioctl(infd, TIOCSCTTY, 1);
426 #ifdef SUPERUSER_EMBEDDED
428 mount_emulated_storage(multiuser_get_user_id(daemon_from_uid));
432 return run_daemon_child(infd, outfd, errfd, argc, argv);
436 if (getuid() != 0 || getgid() != 0) {
437 PLOGE("daemon requires root. uid/gid not root");
442 struct sockaddr_un sun;
444 fd = socket(AF_LOCAL, SOCK_STREAM, 0);
449 if (fcntl(fd, F_SETFD, FD_CLOEXEC)) {
450 PLOGE("fcntl FD_CLOEXEC");
454 memset(&sun, 0, sizeof(sun));
455 sun.sun_family = AF_LOCAL;
456 sprintf(sun.sun_path, "%s/server", REQUESTOR_DAEMON_PATH);
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.
463 unlink(sun.sun_path);
464 unlink(REQUESTOR_DAEMON_PATH);
466 int previous_umask = umask(027);
467 mkdir(REQUESTOR_DAEMON_PATH, 0777);
469 memset(sun.sun_path, 0, sizeof(sun.sun_path));
470 memcpy(sun.sun_path, "\0" "SUPERUSER", strlen("SUPERUSER") + 1);
472 if (bind(fd, (struct sockaddr*)&sun, sizeof(sun)) < 0) {
473 PLOGE("daemon bind");
477 chmod(REQUESTOR_DAEMON_PATH, 0755);
478 chmod(sun.sun_path, 0777);
480 umask(previous_umask);
482 if (listen(fd, 10) < 0) {
483 PLOGE("daemon listen");
488 while ((client = accept(fd, NULL, NULL)) > 0) {
489 if (fork_zero_fucks() == 0) {
491 return daemon_accept(client);
498 LOGE("daemon exiting");
504 // List of signals which cause process termination
505 static int quit_signals[] = { SIGALRM, SIGHUP, SIGPIPE, SIGQUIT, SIGTERM, SIGINT, 0 };
507 static void sighandler(int __attribute__((unused))sig) {
510 // Assume we'll only be called before death
511 // See note before sigaction() in set_stdin_raw()
513 // Now, close all standard I/O to cause the pumps
514 // to exit so we can continue and retrieve the exit
517 close(STDOUT_FILENO);
518 close(STDERR_FILENO);
520 // Put back all the default handlers
521 struct sigaction act;
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");
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
539 static void setup_sighandlers(void) {
540 struct sigaction act;
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");
557 int connect_daemon(int argc, char *argv[], int ppid) {
560 char pts_slave[PATH_MAX];
562 struct sockaddr_un sun;
564 // Open a socket to the daemon
565 int socketfd = socket(AF_LOCAL, SOCK_STREAM, 0);
570 if (fcntl(socketfd, F_SETFD, FD_CLOEXEC)) {
571 PLOGE("fcntl FD_CLOEXEC");
575 memset(&sun, 0, sizeof(sun));
576 sun.sun_family = AF_LOCAL;
577 sprintf(sun.sun_path, "%s/server", REQUESTOR_DAEMON_PATH);
579 memset(sun.sun_path, 0, sizeof(sun.sun_path));
580 memcpy(sun.sun_path, "\0" "SUPERUSER", strlen("SUPERUSER") + 1);
582 if (0 != connect(socketfd, (struct sockaddr*)&sun, sizeof(sun))) {
587 LOGD("connecting client %d", getpid());
589 int mount_storage = getenv("MOUNT_EMULATED_STORAGE") != NULL;
591 // Determine which one of our streams are attached to a TTY
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;
603 // We need a PTY. Get one.
604 ptmx = pts_open(pts_slave, sizeof(pts_slave));
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);
619 write_int(socketfd, uid);
621 write_int(socketfd, ppid);
622 write_int(socketfd, mount_storage);
625 if (atty & ATTY_IN) {
627 send_fd(socketfd, -1);
629 send_fd(socketfd, STDIN_FILENO);
633 if (atty & ATTY_OUT) {
635 watch_sigwinch_async(STDOUT_FILENO, ptmx);
638 send_fd(socketfd, -1);
640 send_fd(socketfd, STDOUT_FILENO);
644 if (atty & ATTY_ERR) {
646 send_fd(socketfd, -1);
648 send_fd(socketfd, STDERR_FILENO);
651 // Number of command line arguments
652 write_int(socketfd, mount_storage ? argc - 1 : argc);
654 // Command line arguments
656 for (i = 0; i < argc; i++) {
657 if (i == 1 && mount_storage) {
660 write_string(socketfd, argv[i]);
663 // Wait for acknowledgement from daemon
666 if (atty & ATTY_IN) {
668 pump_stdin_async(ptmx);
670 if (atty & ATTY_OUT) {
671 pump_stdout_blocking(ptmx);
675 int code = read_int(socketfd);
677 LOGD("client exited %d", code);