OSDN Git Service

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