OSDN Git Service

android: fix 64-bit targets building errors
[android-x86/external-koush-Superuser.git] / Superuser / jni / su / su.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 #include <sys/types.h>
19 #include <sys/socket.h>
20 #include <sys/uio.h>
21 #include <sys/un.h>
22 #include <sys/wait.h>
23 #include <sys/select.h>
24 #include <sys/time.h>
25 #include <unistd.h>
26 #include <limits.h>
27 #include <fcntl.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <getopt.h>
31 #include <stdint.h>
32 #include <pwd.h>
33 #include <sys/stat.h>
34 #include <stdarg.h>
35 #include <sys/types.h>
36 #include <sys/endian.h>
37
38 #include "su.h"
39 #include "utils.h"
40
41 extern int is_daemon;
42 extern int daemon_from_uid;
43 extern int daemon_from_pid;
44
45 unsigned get_shell_uid() {
46   struct passwd* ppwd = getpwnam("shell");
47   if (NULL == ppwd) {
48     return 2000;
49   }
50
51   return ppwd->pw_uid;
52 }
53
54 unsigned get_system_uid() {
55   struct passwd* ppwd = getpwnam("system");
56   if (NULL == ppwd) {
57     return 1000;
58   }
59
60   return ppwd->pw_uid;
61 }
62
63 unsigned get_radio_uid() {
64   struct passwd* ppwd = getpwnam("radio");
65   if (NULL == ppwd) {
66     return 1001;
67   }
68
69   return ppwd->pw_uid;
70 }
71
72 int fork_zero_fucks() {
73     int pid = fork();
74     if (pid) {
75         int status;
76         waitpid(pid, &status, 0);
77         return pid;
78     }
79     else {
80         if ((pid = fork()))
81             exit(0);
82         return 0;
83     }
84 }
85
86 void exec_log(int priority, const char* fmt, ...) {
87     static int log_fd = -1;
88     struct iovec vec[3];
89     va_list args;
90     char msg[PATH_MAX];
91
92     if (log_fd < 0) {
93         log_fd = open("/dev/log/main", O_WRONLY);
94         if (log_fd < 0) {
95             return;
96         }
97     }
98
99     va_start(args, fmt);
100     vsnprintf(msg, PATH_MAX, fmt, args);
101     va_end(args);
102
103     vec[0].iov_base   = (unsigned char *) &priority;
104     vec[0].iov_len    = 1;
105     vec[1].iov_base   = (void *) LOG_TAG;
106     vec[1].iov_len    = strlen(LOG_TAG) + 1;
107     vec[2].iov_base   = (void *) msg;
108     vec[2].iov_len    = strlen(msg) + 1;
109
110     writev(log_fd, vec, 3);
111 }
112
113 static int from_init(struct su_initiator *from) {
114     char path[PATH_MAX], exe[PATH_MAX];
115     char args[4096], *argv0, *argv_rest;
116     int fd;
117     ssize_t len;
118     int i;
119     int err;
120
121     from->uid = getuid();
122     from->pid = getppid();
123
124     if (is_daemon) {
125         from->uid = daemon_from_uid;
126         from->pid = daemon_from_pid;
127     }
128
129     /* Get the command line */
130     snprintf(path, sizeof(path), "/proc/%u/cmdline", from->pid);
131     fd = open(path, O_RDONLY);
132     if (fd < 0) {
133         PLOGE("Opening command line");
134         return -1;
135     }
136     len = read(fd, args, sizeof(args));
137     err = errno;
138     close(fd);
139     if (len < 0 || len == sizeof(args)) {
140         PLOGEV("Reading command line", err);
141         return -1;
142     }
143
144     argv0 = args;
145     argv_rest = NULL;
146     for (i = 0; i < len; i++) {
147         if (args[i] == '\0') {
148             if (!argv_rest) {
149                 argv_rest = &args[i+1];
150             } else {
151                 args[i] = ' ';
152             }
153         }
154     }
155     args[len] = '\0';
156
157     if (argv_rest) {
158         strncpy(from->args, argv_rest, sizeof(from->args));
159         from->args[sizeof(from->args)-1] = '\0';
160     } else {
161         from->args[0] = '\0';
162     }
163
164     /* If this isn't app_process, use the real path instead of argv[0] */
165     snprintf(path, sizeof(path), "/proc/%u/exe", from->pid);
166     len = readlink(path, exe, sizeof(exe));
167     if (len < 0) {
168         PLOGE("Getting exe path");
169         return -1;
170     }
171     exe[len] = '\0';
172     if (strcmp(exe, "/system/bin/app_process")) {
173         argv0 = exe;
174     }
175
176     strncpy(from->bin, argv0, sizeof(from->bin));
177     from->bin[sizeof(from->bin)-1] = '\0';
178
179     struct passwd *pw;
180     pw = getpwuid(from->uid);
181     if (pw && pw->pw_name) {
182         strncpy(from->name, pw->pw_name, sizeof(from->name));
183     }
184
185     return 0;
186 }
187
188 static int get_multiuser_mode() {
189     char *data;
190     char sdk_ver[PROPERTY_VALUE_MAX];
191
192     data = read_file("/system/build.prop");
193     get_property(data, sdk_ver, "ro.build.version.sdk", "0");
194     free(data);
195
196     int sdk = atoi(sdk_ver);
197     if (sdk < 17)
198         return MULTIUSER_MODE_NONE;
199
200     int ret = MULTIUSER_MODE_OWNER_ONLY;
201     char mode[12];
202     FILE *fp;
203     if ((fp = fopen(REQUESTOR_MULTIUSER_MODE, "r"))) {
204         fgets(mode, sizeof(mode), fp);
205         int last = strlen(mode) - 1;
206         if (mode[last] == '\n')
207             mode[last] = '\0';
208         if (strcmp(mode, MULTIUSER_VALUE_USER) == 0) {
209             ret = MULTIUSER_MODE_USER;
210         } else if (strcmp(mode, MULTIUSER_VALUE_OWNER_MANAGED) == 0) {
211             ret = MULTIUSER_MODE_OWNER_MANAGED;
212         }
213         else {
214             ret = MULTIUSER_MODE_OWNER_ONLY;
215         }
216         fclose(fp);
217     }
218     return ret;
219 }
220
221 static void read_options(struct su_context *ctx) {
222     ctx->user.multiuser_mode = get_multiuser_mode();
223 }
224
225 static void user_init(struct su_context *ctx) {
226     if (ctx->from.uid > 99999) {
227         ctx->user.android_user_id = ctx->from.uid / 100000;
228         if (ctx->user.multiuser_mode == MULTIUSER_MODE_USER) {
229             snprintf(ctx->user.database_path, PATH_MAX, "%s/%d/%s", REQUESTOR_USER_PATH, ctx->user.android_user_id, REQUESTOR_DATABASE_PATH);
230             snprintf(ctx->user.base_path, PATH_MAX, "%s/%d/%s", REQUESTOR_USER_PATH, ctx->user.android_user_id, REQUESTOR);
231         }
232     }
233 }
234
235 static void populate_environment(const struct su_context *ctx) {
236     struct passwd *pw;
237
238     if (ctx->to.keepenv)
239         return;
240
241     pw = getpwuid(ctx->to.uid);
242     if (pw) {
243         setenv("HOME", pw->pw_dir, 1);
244         if (ctx->to.shell)
245             setenv("SHELL", ctx->to.shell, 1);
246         else
247             setenv("SHELL", DEFAULT_SHELL, 1);
248         if (ctx->to.login || ctx->to.uid) {
249             setenv("USER", pw->pw_name, 1);
250             setenv("LOGNAME", pw->pw_name, 1);
251         }
252     }
253 }
254
255 void set_identity(unsigned int uid) {
256     /*
257      * Set effective uid back to root, otherwise setres[ug]id will fail
258      * if uid isn't root.
259      */
260     if (seteuid(0)) {
261         PLOGE("seteuid (root)");
262         exit(EXIT_FAILURE);
263     }
264     if (setresgid(uid, uid, uid)) {
265         PLOGE("setresgid (%u)", uid);
266         exit(EXIT_FAILURE);
267     }
268     if (setresuid(uid, uid, uid)) {
269         PLOGE("setresuid (%u)", uid);
270         exit(EXIT_FAILURE);
271     }
272 }
273
274 static void socket_cleanup(struct su_context *ctx) {
275     if (ctx && ctx->sock_path[0]) {
276         if (unlink(ctx->sock_path))
277             PLOGE("unlink (%s)", ctx->sock_path);
278         ctx->sock_path[0] = 0;
279     }
280 }
281
282 /*
283  * For use in signal handlers/atexit-function
284  * NOTE: su_ctx points to main's local variable.
285  *       It's OK due to the program uses exit(3), not return from main()
286  */
287 static struct su_context *su_ctx = NULL;
288
289 static void cleanup(void) {
290     socket_cleanup(su_ctx);
291 }
292
293 static void cleanup_signal(int sig) {
294     socket_cleanup(su_ctx);
295     exit(128 + sig);
296 }
297
298 static int socket_create_temp(char *path, size_t len) {
299     int fd;
300     struct sockaddr_un sun;
301
302     fd = socket(AF_LOCAL, SOCK_STREAM, 0);
303     if (fd < 0) {
304         PLOGE("socket");
305         return -1;
306     }
307     if (fcntl(fd, F_SETFD, FD_CLOEXEC)) {
308         PLOGE("fcntl FD_CLOEXEC");
309         goto err;
310     }
311
312     memset(&sun, 0, sizeof(sun));
313     sun.sun_family = AF_LOCAL;
314     snprintf(path, len, "%s/.socket%d", REQUESTOR_CACHE_PATH, getpid());
315     memset(sun.sun_path, 0, sizeof(sun.sun_path));
316     snprintf(sun.sun_path, sizeof(sun.sun_path), "%s", path);
317
318     /*
319      * Delete the socket to protect from situations when
320      * something bad occured previously and the kernel reused pid from that process.
321      * Small probability, isn't it.
322      */
323     unlink(sun.sun_path);
324
325     if (bind(fd, (struct sockaddr*)&sun, sizeof(sun)) < 0) {
326         PLOGE("bind");
327         goto err;
328     }
329
330     if (listen(fd, 1) < 0) {
331         PLOGE("listen");
332         goto err;
333     }
334
335     return fd;
336 err:
337     close(fd);
338     return -1;
339 }
340
341 static int socket_accept(int serv_fd) {
342     struct timeval tv;
343     fd_set fds;
344     int fd, rc;
345
346     /* Wait 20 seconds for a connection, then give up. */
347     tv.tv_sec = 20;
348     tv.tv_usec = 0;
349     FD_ZERO(&fds);
350     FD_SET(serv_fd, &fds);
351     do {
352         rc = select(serv_fd + 1, &fds, NULL, NULL, &tv);
353     } while (rc < 0 && errno == EINTR);
354     if (rc < 1) {
355         PLOGE("select");
356         return -1;
357     }
358
359     fd = accept(serv_fd, NULL, NULL);
360     if (fd < 0) {
361         PLOGE("accept");
362         return -1;
363     }
364
365     return fd;
366 }
367
368 static int socket_send_request(int fd, const struct su_context *ctx) {
369 #define write_data(fd, data, data_len)              \
370 do {                                                \
371     uint32_t __len = htonl(data_len);               \
372     __len = write((fd), &__len, sizeof(__len));     \
373     if (__len != sizeof(__len)) {                   \
374         PLOGE("write(" #data ")");                  \
375         return -1;                                  \
376     }                                               \
377     __len = write((fd), data, data_len);            \
378     if (__len != data_len) {                        \
379         PLOGE("write(" #data ")");                  \
380         return -1;                                  \
381     }                                               \
382 } while (0)
383
384 #define write_string_data(fd, name, data)        \
385 do {                                        \
386     write_data(fd, name, strlen(name));     \
387     write_data(fd, data, strlen(data));     \
388 } while (0)
389
390 // stringify everything.
391 #define write_token(fd, name, data)         \
392 do {                                        \
393     char buf[16];                           \
394     snprintf(buf, sizeof(buf), "%d", data); \
395     write_string_data(fd, name, buf);            \
396 } while (0)
397
398     write_token(fd, "version", PROTO_VERSION);
399     write_token(fd, "binary.version", VERSION_CODE);
400     write_token(fd, "pid", ctx->from.pid);
401     write_string_data(fd, "from.name", ctx->from.name);
402     write_string_data(fd, "to.name", ctx->to.name);
403     write_token(fd, "from.uid", ctx->from.uid);
404     write_token(fd, "to.uid", ctx->to.uid);
405     write_string_data(fd, "from.bin", ctx->from.bin);
406     // TODO: Fix issue where not using -c does not result a in a command
407     write_string_data(fd, "command", get_command(&ctx->to));
408     write_token(fd, "eof", PROTO_VERSION);
409     return 0;
410 }
411
412 static int socket_receive_result(int fd, char *result, ssize_t result_len) {
413     ssize_t len;
414
415     LOGV("waiting for user");
416     len = read(fd, result, result_len-1);
417     if (len < 0) {
418         PLOGE("read(result)");
419         return -1;
420     }
421     result[len] = '\0';
422
423     return 0;
424 }
425
426 static void usage(int status) {
427     FILE *stream = (status == EXIT_SUCCESS) ? stdout : stderr;
428
429     fprintf(stream,
430     "Usage: su [options] [--] [-] [LOGIN] [--] [args...]\n\n"
431     "Options:\n"
432     "  --daemon                      start the su daemon agent\n"
433     "  -c, --command COMMAND         pass COMMAND to the invoked shell\n"
434     "  -h, --help                    display this help message and exit\n"
435     "  -, -l, --login                pretend the shell to be a login shell\n"
436     "  -m, -p,\n"
437     "  --preserve-environment        do not change environment variables\n"
438     "  -s, --shell SHELL             use SHELL instead of the default " DEFAULT_SHELL "\n"
439     "  -u                            display the multiuser mode and exit\n"
440     "  -v, --version                 display version number and exit\n"
441     "  -V                            display version code and exit,\n"
442     "                                this is used almost exclusively by Superuser.apk\n");
443     exit(status);
444 }
445
446 static __attribute__ ((noreturn)) void deny(struct su_context *ctx) {
447     char *cmd = get_command(&ctx->to);
448
449     int send_to_app = 1;
450
451     // no need to log if called by root
452     if (ctx->from.uid == AID_ROOT)
453         send_to_app = 0;
454
455     // dumpstate (which logs to logcat/shell) will spam the crap out of the system with su calls
456     if (strcmp("/system/bin/dumpstate", ctx->from.bin) == 0)
457         send_to_app = 0;
458
459     if (send_to_app)
460         send_result(ctx, DENY);
461
462     LOGW("request rejected (%u->%u %s)", ctx->from.uid, ctx->to.uid, cmd);
463     fprintf(stderr, "%s\n", strerror(EACCES));
464     exit(EXIT_FAILURE);
465 }
466
467 static __attribute__ ((noreturn)) void allow(struct su_context *ctx) {
468     char *arg0;
469     int argc, err;
470
471     umask(ctx->umask);
472     int send_to_app = 1;
473
474     // no need to log if called by root
475     if (ctx->from.uid == AID_ROOT)
476         send_to_app = 0;
477
478     // dumpstate (which logs to logcat/shell) will spam the crap out of the system with su calls
479     if (strcmp("/system/bin/dumpstate", ctx->from.bin) == 0)
480         send_to_app = 0;
481
482     if (send_to_app)
483         send_result(ctx, ALLOW);
484
485     char *binary;
486     argc = ctx->to.optind;
487     if (ctx->to.command) {
488         binary = ctx->to.shell;
489         ctx->to.argv[--argc] = ctx->to.command;
490         ctx->to.argv[--argc] = "-c";
491     }
492     else if (ctx->to.shell) {
493         binary = ctx->to.shell;
494     }
495     else {
496         if (ctx->to.argv[argc]) {
497             binary = ctx->to.argv[argc++];
498         }
499         else {
500             binary = DEFAULT_SHELL;
501         }
502     }
503
504     arg0 = strrchr (binary, '/');
505     arg0 = (arg0) ? arg0 + 1 : binary;
506     if (ctx->to.login) {
507         int s = strlen(arg0) + 2;
508         char *p = malloc(s);
509
510         if (!p)
511             exit(EXIT_FAILURE);
512
513         *p = '-';
514         strcpy(p + 1, arg0);
515         arg0 = p;
516     }
517
518     populate_environment(ctx);
519     set_identity(ctx->to.uid);
520
521 #define PARG(arg)                                    \
522     (argc + (arg) < ctx->to.argc) ? " " : "",                    \
523     (argc + (arg) < ctx->to.argc) ? ctx->to.argv[argc + (arg)] : ""
524
525     LOGD("%u %s executing %u %s using binary %s : %s%s%s%s%s%s%s%s%s%s%s%s%s%s",
526             ctx->from.uid, ctx->from.bin,
527             ctx->to.uid, get_command(&ctx->to), binary,
528             arg0, PARG(0), PARG(1), PARG(2), PARG(3), PARG(4), PARG(5),
529             (ctx->to.optind + 6 < ctx->to.argc) ? " ..." : "");
530
531     ctx->to.argv[--argc] = arg0;
532     execvp(binary, ctx->to.argv + argc);
533     err = errno;
534     PLOGE("exec");
535     fprintf(stderr, "Cannot execute %s: %s\n", binary, strerror(err));
536     exit(EXIT_FAILURE);
537 }
538
539 /*
540  * CyanogenMod-specific behavior
541  *
542  * we can't simply use the property service, since we aren't launched from init
543  * and can't trust the location of the property workspace.
544  * Find the properties ourselves.
545  */
546 int access_disabled(const struct su_initiator *from) {
547 #ifndef SUPERUSER_EMBEDDED
548     return 0;
549 #else
550     char *data;
551     char build_type[PROPERTY_VALUE_MAX];
552     char debuggable[PROPERTY_VALUE_MAX], enabled[PROPERTY_VALUE_MAX];
553     size_t len;
554
555     data = read_file("/system/build.prop");
556     if (check_property(data, "ro.cm.version")) {
557         get_property(data, build_type, "ro.build.type", "");
558         free(data);
559
560         data = read_file("/default.prop");
561         get_property(data, debuggable, "ro.debuggable", "0");
562         free(data);
563         /* only allow su on debuggable builds */
564         if (strcmp("1", debuggable) != 0) {
565             LOGE("Root access is disabled on non-debug builds");
566             return 1;
567         }
568
569         data = read_file("/data/property/persist.sys.root_access");
570         if (data != NULL) {
571             len = strlen(data);
572             if (len >= PROPERTY_VALUE_MAX)
573                 memcpy(enabled, "0", 2);
574             else
575                 memcpy(enabled, data, len + 1);
576             free(data);
577         } else
578             memcpy(enabled, "0", 2);
579
580         /* enforce persist.sys.root_access on non-eng builds for apps */
581         if (strcmp("eng", build_type) != 0 &&
582                 from->uid != AID_SHELL && from->uid != AID_ROOT &&
583                 (atoi(enabled) & CM_ROOT_ACCESS_APPS_ONLY) != CM_ROOT_ACCESS_APPS_ONLY ) {
584             LOGE("Apps root access is disabled by system setting - "
585                  "enable it under settings -> developer options");
586             return 1;
587         }
588
589         /* disallow su in a shell if appropriate */
590         if (from->uid == AID_SHELL &&
591                 (atoi(enabled) & CM_ROOT_ACCESS_ADB_ONLY) != CM_ROOT_ACCESS_ADB_ONLY ) {
592             LOGE("Shell root access is disabled by a system setting - "
593                  "enable it under settings -> developer options");
594             return 1;
595         }
596
597     }
598     return 0;
599 #endif
600 }
601
602 static int get_api_version() {
603   char sdk_ver[PROPERTY_VALUE_MAX];
604   char *data = read_file("/system/build.prop");
605   get_property(data, sdk_ver, "ro.build.version.sdk", "0");
606   int ver = atoi(sdk_ver);
607   free(data);
608   return ver;
609 }
610
611 static void fork_for_samsung(void)
612 {
613     // Samsung CONFIG_SEC_RESTRICT_SETUID wants the parent process to have
614     // EUID 0, or else our setresuid() calls will be denied.  So make sure
615     // all such syscalls are executed by a child process.
616     int rv;
617
618     switch (fork()) {
619     case 0:
620         return;
621     case -1:
622         PLOGE("fork");
623         exit(1);
624     default:
625         if (wait(&rv) < 0) {
626             exit(1);
627         } else {
628             exit(WEXITSTATUS(rv));
629         }
630     }
631 }
632
633 int main(int argc, char *argv[]) {
634     return su_main(argc, argv, 1);
635 }
636
637 int su_main(int argc, char *argv[], int need_client) {
638     // start up in daemon mode if prompted
639     if (argc == 2 && strcmp(argv[1], "--daemon") == 0) {
640         return run_daemon();
641     }
642
643     int ppid = getppid();
644     fork_for_samsung();
645
646     // Sanitize all secure environment variables (from linker_environ.c in AOSP linker).
647     /* The same list than GLibc at this point */
648     static const char* const unsec_vars[] = {
649         "GCONV_PATH",
650         "GETCONF_DIR",
651         "HOSTALIASES",
652         "LD_AUDIT",
653         "LD_DEBUG",
654         "LD_DEBUG_OUTPUT",
655         "LD_DYNAMIC_WEAK",
656         "LD_LIBRARY_PATH",
657         "LD_ORIGIN_PATH",
658         "LD_PRELOAD",
659         "LD_PROFILE",
660         "LD_SHOW_AUXV",
661         "LD_USE_LOAD_BIAS",
662         "LOCALDOMAIN",
663         "LOCPATH",
664         "MALLOC_TRACE",
665         "MALLOC_CHECK_",
666         "NIS_PATH",
667         "NLSPATH",
668         "RESOLV_HOST_CONF",
669         "RES_OPTIONS",
670         "TMPDIR",
671         "TZDIR",
672         "LD_AOUT_LIBRARY_PATH",
673         "LD_AOUT_PRELOAD",
674         // not listed in linker, used due to system() call
675         "IFS",
676     };
677     const char* const* cp   = unsec_vars;
678     const char* const* endp = cp + sizeof(unsec_vars)/sizeof(unsec_vars[0]);
679     while (cp < endp) {
680         unsetenv(*cp);
681         cp++;
682     }
683
684     LOGD("su invoked.");
685
686     struct su_context ctx = {
687         .from = {
688             .pid = -1,
689             .uid = 0,
690             .bin = "",
691             .args = "",
692             .name = "",
693         },
694         .to = {
695             .uid = AID_ROOT,
696             .login = 0,
697             .keepenv = 0,
698             .shell = NULL,
699             .command = NULL,
700             .argv = argv,
701             .argc = argc,
702             .optind = 0,
703             .name = "",
704         },
705         .user = {
706             .android_user_id = 0,
707             .multiuser_mode = MULTIUSER_MODE_OWNER_ONLY,
708             .database_path = REQUESTOR_DATA_PATH REQUESTOR_DATABASE_PATH,
709             .base_path = REQUESTOR_DATA_PATH REQUESTOR
710         },
711     };
712     struct stat st;
713     int c, socket_serv_fd, fd;
714     char buf[64], *result;
715     policy_t dballow;
716     struct option long_opts[] = {
717         { "command",            required_argument,    NULL, 'c' },
718         { "help",            no_argument,        NULL, 'h' },
719         { "login",            no_argument,        NULL, 'l' },
720         { "preserve-environment",    no_argument,        NULL, 'p' },
721         { "shell",            required_argument,    NULL, 's' },
722         { "version",            no_argument,        NULL, 'v' },
723         { NULL, 0, NULL, 0 },
724     };
725
726     while ((c = getopt_long(argc, argv, "+c:hlmps:Vvu", long_opts, NULL)) != -1) {
727         switch(c) {
728         case 'c':
729             ctx.to.shell = DEFAULT_SHELL;
730             ctx.to.command = optarg;
731             break;
732         case 'h':
733             usage(EXIT_SUCCESS);
734             break;
735         case 'l':
736             ctx.to.login = 1;
737             break;
738         case 'm':
739         case 'p':
740             ctx.to.keepenv = 1;
741             break;
742         case 's':
743             ctx.to.shell = optarg;
744             break;
745         case 'V':
746             printf("%d\n", VERSION_CODE);
747             exit(EXIT_SUCCESS);
748         case 'v':
749             printf("%s\n", VERSION);
750             exit(EXIT_SUCCESS);
751         case 'u':
752             switch (get_multiuser_mode()) {
753             case MULTIUSER_MODE_USER:
754                 printf("%s\n", MULTIUSER_VALUE_USER);
755                 break;
756             case MULTIUSER_MODE_OWNER_MANAGED:
757                 printf("%s\n", MULTIUSER_VALUE_OWNER_MANAGED);
758                 break;
759             case MULTIUSER_MODE_OWNER_ONLY:
760                 printf("%s\n", MULTIUSER_VALUE_OWNER_ONLY);
761                 break;
762             case MULTIUSER_MODE_NONE:
763                 printf("%s\n", MULTIUSER_VALUE_NONE);
764                 break;
765             }
766             exit(EXIT_SUCCESS);
767         default:
768             /* Bionic getopt_long doesn't terminate its error output by newline */
769             fprintf(stderr, "\n");
770             usage(2);
771         }
772     }
773
774     if (need_client) {
775         // attempt to use the daemon client if not root,
776         // or this is api 18 and adb shell (/data is not readable even as root)
777         // or just always use it on API 19+ (ART)
778         if ((geteuid() != AID_ROOT && getuid() != AID_ROOT) ||
779             (get_api_version() >= 18 && getuid() == AID_SHELL) ||
780             get_api_version() >= 19) {
781             // attempt to connect to daemon...
782             LOGD("starting daemon client %d %d", getuid(), geteuid());
783             return connect_daemon(argc, argv, ppid);
784         }
785     }
786
787     if (optind < argc && !strcmp(argv[optind], "-")) {
788         ctx.to.login = 1;
789         optind++;
790     }
791     /* username or uid */
792     if (optind < argc && strcmp(argv[optind], "--")) {
793         struct passwd *pw;
794         pw = getpwnam(argv[optind]);
795         if (!pw) {
796             char *endptr;
797
798             /* It seems we shouldn't do this at all */
799             errno = 0;
800             ctx.to.uid = strtoul(argv[optind], &endptr, 10);
801             if (errno || *endptr) {
802                 LOGE("Unknown id: %s\n", argv[optind]);
803                 fprintf(stderr, "Unknown id: %s\n", argv[optind]);
804                 exit(EXIT_FAILURE);
805             }
806         } else {
807             ctx.to.uid = pw->pw_uid;
808             if (pw->pw_name)
809                 strncpy(ctx.to.name, pw->pw_name, sizeof(ctx.to.name));
810         }
811         optind++;
812     }
813     if (optind < argc && !strcmp(argv[optind], "--")) {
814         optind++;
815     }
816     ctx.to.optind = optind;
817
818     su_ctx = &ctx;
819     if (from_init(&ctx.from) < 0) {
820         deny(&ctx);
821     }
822
823     read_options(&ctx);
824     user_init(&ctx);
825
826     // the latter two are necessary for stock ROMs like note 2 which do dumb things with su, or crash otherwise
827     if (ctx.from.uid == AID_ROOT) {
828         LOGD("Allowing root/system/radio.");
829         allow(&ctx);
830     }
831
832     // verify superuser is installed
833     if (stat(ctx.user.base_path, &st) < 0) {
834         // send to market (disabled, because people are and think this is hijacking their su)
835         // if (0 == strcmp(JAVA_PACKAGE_NAME, REQUESTOR))
836         //     silent_run("am start -d http://www.clockworkmod.com/superuser/install.html -a android.intent.action.VIEW");
837         PLOGE("stat %s", ctx.user.base_path);
838         deny(&ctx);
839     }
840
841     // odd perms on superuser data dir
842     if (st.st_gid != st.st_uid) {
843         LOGE("Bad uid/gid %d/%d for Superuser Requestor application",
844                 (int)st.st_uid, (int)st.st_gid);
845         deny(&ctx);
846     }
847
848     // always allow if this is the superuser uid
849     // superuser needs to be able to reenable itself when disabled...
850     if (ctx.from.uid == st.st_uid) {
851         allow(&ctx);
852     }
853
854     // check if superuser is disabled completely
855     if (access_disabled(&ctx.from)) {
856         LOGD("access_disabled");
857         deny(&ctx);
858     }
859
860     // autogrant shell at this point
861     if (ctx.from.uid == AID_SHELL) {
862         LOGD("Allowing shell.");
863         allow(&ctx);
864     }
865
866     // deny if this is a non owner request and owner mode only
867     if (ctx.user.multiuser_mode == MULTIUSER_MODE_OWNER_ONLY && ctx.user.android_user_id != 0) {
868         deny(&ctx);
869     }
870
871     ctx.umask = umask(027);
872
873     int ret = mkdir(REQUESTOR_CACHE_PATH, 0770);
874     if (chown(REQUESTOR_CACHE_PATH, st.st_uid, st.st_gid)) {
875         PLOGE("chown (%s, %ld, %ld)", REQUESTOR_CACHE_PATH, st.st_uid, st.st_gid);
876         deny(&ctx);
877     }
878
879     if (setgroups(0, NULL)) {
880         PLOGE("setgroups");
881         deny(&ctx);
882     }
883     if (setegid(st.st_gid)) {
884         PLOGE("setegid (%lu)", st.st_gid);
885         deny(&ctx);
886     }
887     if (seteuid(st.st_uid)) {
888         PLOGE("seteuid (%lu)", st.st_uid);
889         deny(&ctx);
890     }
891
892     dballow = database_check(&ctx);
893     switch (dballow) {
894         case INTERACTIVE:
895             break;
896         case ALLOW:
897             LOGD("db allowed");
898             allow(&ctx);    /* never returns */
899         case DENY:
900         default:
901             LOGD("db denied");
902             deny(&ctx);        /* never returns too */
903     }
904
905     socket_serv_fd = socket_create_temp(ctx.sock_path, sizeof(ctx.sock_path));
906     LOGD(ctx.sock_path);
907     if (socket_serv_fd < 0) {
908         deny(&ctx);
909     }
910
911     signal(SIGHUP, cleanup_signal);
912     signal(SIGPIPE, cleanup_signal);
913     signal(SIGTERM, cleanup_signal);
914     signal(SIGQUIT, cleanup_signal);
915     signal(SIGINT, cleanup_signal);
916     signal(SIGABRT, cleanup_signal);
917
918     if (send_request(&ctx) < 0) {
919         deny(&ctx);
920     }
921
922     atexit(cleanup);
923
924     fd = socket_accept(socket_serv_fd);
925     if (fd < 0) {
926         deny(&ctx);
927     }
928     if (socket_send_request(fd, &ctx)) {
929         deny(&ctx);
930     }
931     if (socket_receive_result(fd, buf, sizeof(buf))) {
932         deny(&ctx);
933     }
934
935     close(fd);
936     close(socket_serv_fd);
937     socket_cleanup(&ctx);
938
939     result = buf;
940
941 #define SOCKET_RESPONSE    "socket:"
942     if (strncmp(result, SOCKET_RESPONSE, sizeof(SOCKET_RESPONSE) - 1))
943         LOGW("SECURITY RISK: Requestor still receives credentials in intent");
944     else
945         result += sizeof(SOCKET_RESPONSE) - 1;
946
947     if (!strcmp(result, "DENY")) {
948         deny(&ctx);
949     } else if (!strcmp(result, "ALLOW")) {
950         allow(&ctx);
951     } else {
952         LOGE("unknown response from Superuser Requestor: %s", result);
953         deny(&ctx);
954     }
955 }