OSDN Git Service

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