OSDN Git Service

Add support for su daemon installation and detection in recovery zip.
[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 void exec_log(char *priority, char* logline) {
71   int pid;
72   if ((pid = fork()) == 0) {
73       int zero = open("/dev/zero", O_RDONLY | O_CLOEXEC);
74       int null = open("/dev/null", O_WRONLY | O_CLOEXEC);
75       dup2(null, 0);
76       dup2(null, 1);
77       dup2(null, 2);
78       execl("/system/bin/log", "/system/bin/log", "-p", priority, "-t", LOG_TAG, logline, NULL);
79       _exit(0);
80   }
81 }
82
83 void exec_loge(const char* fmt, ...) {
84     va_list args;
85
86     char logline[PATH_MAX];
87     va_start(args, fmt);
88     vsnprintf(logline, PATH_MAX, fmt, args);
89     va_end(args);
90     exec_log("e", logline);
91 }
92
93 void exec_logw(const char* fmt, ...) {
94     va_list args;
95
96     char logline[PATH_MAX];
97     va_start(args, fmt);
98     vsnprintf(logline, PATH_MAX, fmt, args);
99     va_end(args);
100     exec_log("w", logline);
101 }
102
103 void exec_logd(const char* fmt, ...) {
104     va_list args;
105
106     char logline[PATH_MAX];
107     va_start(args, fmt);
108     vsnprintf(logline, PATH_MAX, fmt, args);
109     va_end(args);
110     exec_log("d", logline);
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     /* Get the command line */
125     snprintf(path, sizeof(path), "/proc/%u/cmdline", from->pid);
126     fd = open(path, O_RDONLY);
127     if (fd < 0) {
128         PLOGE("Opening command line");
129         return -1;
130     }
131     len = read(fd, args, sizeof(args));
132     err = errno;
133     close(fd);
134     if (len < 0 || len == sizeof(args)) {
135         PLOGEV("Reading command line", err);
136         return -1;
137     }
138
139     argv0 = args;
140     argv_rest = NULL;
141     for (i = 0; i < len; i++) {
142         if (args[i] == '\0') {
143             if (!argv_rest) {
144                 argv_rest = &args[i+1];
145             } else {
146                 args[i] = ' ';
147             }
148         }
149     }
150     args[len] = '\0';
151
152     if (argv_rest) {
153         strncpy(from->args, argv_rest, sizeof(from->args));
154         from->args[sizeof(from->args)-1] = '\0';
155     } else {
156         from->args[0] = '\0';
157     }
158
159     /* If this isn't app_process, use the real path instead of argv[0] */
160     snprintf(path, sizeof(path), "/proc/%u/exe", from->pid);
161     len = readlink(path, exe, sizeof(exe));
162     if (len < 0) {
163         PLOGE("Getting exe path");
164         return -1;
165     }
166     exe[len] = '\0';
167     if (strcmp(exe, "/system/bin/app_process")) {
168         argv0 = exe;
169     }
170
171     strncpy(from->bin, argv0, sizeof(from->bin));
172     from->bin[sizeof(from->bin)-1] = '\0';
173
174     struct passwd *pw;
175     pw = getpwuid(from->uid);
176     if (pw && pw->pw_name) {
177         strncpy(from->name, pw->pw_name, sizeof(from->name));
178     }
179
180     if (is_daemon) {
181         from->uid = daemon_from_uid;
182         from->pid = daemon_from_pid;
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     size_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     LOGD("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     "  -c, --command COMMAND         pass COMMAND to the invoked shell\n"
433     "  -h, --help                    display this help message and exit\n"
434     "  -, -l, --login                pretend the shell to be a login shell\n"
435     "  -m, -p,\n"
436     "  --preserve-environment        do not change environment variables\n"
437     "  -s, --shell SHELL             use SHELL instead of the default " DEFAULT_SHELL "\n"
438     "  -u                            display the multiuser mode and exit\n"
439     "  -v, --version                 display version number and exit\n"
440     "  -V                            display version code and exit,\n"
441     "                                this is used almost exclusively by Superuser.apk\n");
442     exit(status);
443 }
444
445 static __attribute__ ((noreturn)) void deny(struct su_context *ctx) {
446     char *cmd = get_command(&ctx->to);
447
448     int send_to_app = 1;
449
450     // no need to log if called by root
451     if (ctx->from.uid == AID_ROOT)
452         send_to_app = 0;
453
454     // dumpstate (which logs to logcat/shell) will spam the crap out of the system with su calls
455     if (strcmp("/system/bin/dumpstate", ctx->from.bin) == 0)
456         send_to_app = 0;
457
458     if (send_to_app)
459         send_result(ctx, DENY);
460
461     LOGW("request rejected (%u->%u %s)", ctx->from.uid, ctx->to.uid, cmd);
462     fprintf(stderr, "%s\n", strerror(EACCES));
463     exit(EXIT_FAILURE);
464 }
465
466 static __attribute__ ((noreturn)) void allow(struct su_context *ctx) {
467     char *arg0;
468     int argc, err;
469
470     umask(ctx->umask);
471     int send_to_app = 1;
472
473     // no need to log if called by root
474     if (ctx->from.uid == AID_ROOT)
475         send_to_app = 0;
476
477     // dumpstate (which logs to logcat/shell) will spam the crap out of the system with su calls
478     if (strcmp("/system/bin/dumpstate", ctx->from.bin) == 0)
479         send_to_app = 0;
480
481     if (send_to_app)
482         send_result(ctx, ALLOW);
483
484     char *binary;
485     argc = ctx->to.optind;
486     if (ctx->to.command) {
487         binary = ctx->to.shell;
488         ctx->to.argv[--argc] = ctx->to.command;
489         ctx->to.argv[--argc] = "-c";
490     }
491     else if (ctx->to.shell) {
492         binary = ctx->to.shell;
493     }
494     else {
495         if (ctx->to.argv[argc]) {
496             binary = ctx->to.argv[argc++];
497         }
498         else {
499             binary = DEFAULT_SHELL;
500         }
501     }
502
503     arg0 = strrchr (binary, '/');
504     arg0 = (arg0) ? arg0 + 1 : binary;
505     if (ctx->to.login) {
506         int s = strlen(arg0) + 2;
507         char *p = malloc(s);
508
509         if (!p)
510             exit(EXIT_FAILURE);
511
512         *p = '-';
513         strcpy(p + 1, arg0);
514         arg0 = p;
515     }
516
517     populate_environment(ctx);
518     set_identity(ctx->to.uid);
519
520 #define PARG(arg)                                    \
521     (argc + (arg) < ctx->to.argc) ? " " : "",                    \
522     (argc + (arg) < ctx->to.argc) ? ctx->to.argv[argc + (arg)] : ""
523
524     LOGD("%u %s executing %u %s using binary %s : %s%s%s%s%s%s%s%s%s%s%s%s%s%s",
525             ctx->from.uid, ctx->from.bin,
526             ctx->to.uid, get_command(&ctx->to), binary,
527             arg0, PARG(0), PARG(1), PARG(2), PARG(3), PARG(4), PARG(5),
528             (ctx->to.optind + 6 < ctx->to.argc) ? " ..." : "");
529
530     ctx->to.argv[--argc] = arg0;
531     execvp(binary, ctx->to.argv + argc);
532     err = errno;
533     PLOGE("exec");
534     fprintf(stderr, "Cannot execute %s: %s\n", binary, strerror(err));
535     exit(EXIT_FAILURE);
536 }
537
538 /*
539  * CyanogenMod-specific behavior
540  *
541  * we can't simply use the property service, since we aren't launched from init
542  * and can't trust the location of the property workspace.
543  * Find the properties ourselves.
544  */
545 int access_disabled(const struct su_initiator *from) {
546     char *data;
547     char build_type[PROPERTY_VALUE_MAX];
548     char debuggable[PROPERTY_VALUE_MAX], enabled[PROPERTY_VALUE_MAX];
549     size_t len;
550
551     data = read_file("/system/build.prop");
552     if (check_property(data, "ro.cm.version")) {
553         get_property(data, build_type, "ro.build.type", "");
554         free(data);
555
556         data = read_file("/default.prop");
557         get_property(data, debuggable, "ro.debuggable", "0");
558         free(data);
559         /* only allow su on debuggable builds */
560         if (strcmp("1", debuggable) != 0) {
561             LOGE("Root access is disabled on non-debug builds");
562             return 1;
563         }
564
565         data = read_file("/data/property/persist.sys.root_access");
566         if (data != NULL) {
567             len = strlen(data);
568             if (len >= PROPERTY_VALUE_MAX)
569                 memcpy(enabled, "1", 2);
570             else
571                 memcpy(enabled, data, len + 1);
572             free(data);
573         } else
574             memcpy(enabled, "1", 2);
575
576         /* enforce persist.sys.root_access on non-eng builds for apps */
577         if (strcmp("eng", build_type) != 0 &&
578                 from->uid != AID_SHELL && from->uid != AID_ROOT &&
579                 (atoi(enabled) & CM_ROOT_ACCESS_APPS_ONLY) != CM_ROOT_ACCESS_APPS_ONLY ) {
580             LOGE("Apps root access is disabled by system setting - "
581                  "enable it under settings -> developer options");
582             return 1;
583         }
584
585         /* disallow su in a shell if appropriate */
586         if (from->uid == AID_SHELL &&
587                 (atoi(enabled) & CM_ROOT_ACCESS_ADB_ONLY) != CM_ROOT_ACCESS_ADB_ONLY ) {
588             LOGE("Shell root access is disabled by a system setting - "
589                  "enable it under settings -> developer options");
590             return 1;
591         }
592
593     }
594     return 0;
595 }
596
597 int main(int argc, char *argv[]) {
598     // start up in daemon mode if prompted
599     if (argc == 2 && strcmp(argv[1], "--daemon") == 0) {
600         return run_daemon();
601     }
602
603     if (geteuid() != AID_ROOT && getuid() != AID_ROOT) {
604         // attempt to connect to daemon...
605         LOGD("starting daemon client %d %d", getuid(), geteuid());
606         return connect_daemon(argc, argv);
607     }
608
609     // Sanitize all secure environment variables (from linker_environ.c in AOSP linker).
610     /* The same list than GLibc at this point */
611     static const char* const unsec_vars[] = {
612         "GCONV_PATH",
613         "GETCONF_DIR",
614         "HOSTALIASES",
615         "LD_AUDIT",
616         "LD_DEBUG",
617         "LD_DEBUG_OUTPUT",
618         "LD_DYNAMIC_WEAK",
619         "LD_LIBRARY_PATH",
620         "LD_ORIGIN_PATH",
621         "LD_PRELOAD",
622         "LD_PROFILE",
623         "LD_SHOW_AUXV",
624         "LD_USE_LOAD_BIAS",
625         "LOCALDOMAIN",
626         "LOCPATH",
627         "MALLOC_TRACE",
628         "MALLOC_CHECK_",
629         "NIS_PATH",
630         "NLSPATH",
631         "RESOLV_HOST_CONF",
632         "RES_OPTIONS",
633         "TMPDIR",
634         "TZDIR",
635         "LD_AOUT_LIBRARY_PATH",
636         "LD_AOUT_PRELOAD",
637         // not listed in linker, used due to system() call
638         "IFS",
639     };
640     const char* const* cp   = unsec_vars;
641     const char* const* endp = cp + sizeof(unsec_vars)/sizeof(unsec_vars[0]);
642     while (cp < endp) {
643         unsetenv(*cp);
644         cp++;
645     }
646
647     /*
648      * set LD_LIBRARY_PATH if the linker has wiped out it due to we're suid.
649      * This occurs on Android 4.0+
650      */
651     setenv("LD_LIBRARY_PATH", "/vendor/lib:/system/lib", 0);
652
653     LOGD("su invoked.");
654
655     struct su_context ctx = {
656         .from = {
657             .pid = -1,
658             .uid = 0,
659             .bin = "",
660             .args = "",
661             .name = "",
662         },
663         .to = {
664             .uid = AID_ROOT,
665             .login = 0,
666             .keepenv = 0,
667             .shell = NULL,
668             .command = NULL,
669             .argv = argv,
670             .argc = argc,
671             .optind = 0,
672             .name = "",
673         },
674         .user = {
675             .android_user_id = 0,
676             .multiuser_mode = MULTIUSER_MODE_OWNER_ONLY,
677             .database_path = REQUESTOR_DATA_PATH REQUESTOR_DATABASE_PATH,
678             .base_path = REQUESTOR_DATA_PATH REQUESTOR
679         },
680     };
681     struct stat st;
682     int c, socket_serv_fd, fd;
683     char buf[64], *result;
684     policy_t dballow;
685     struct option long_opts[] = {
686         { "command",            required_argument,    NULL, 'c' },
687         { "help",            no_argument,        NULL, 'h' },
688         { "login",            no_argument,        NULL, 'l' },
689         { "preserve-environment",    no_argument,        NULL, 'p' },
690         { "shell",            required_argument,    NULL, 's' },
691         { "version",            no_argument,        NULL, 'v' },
692         { NULL, 0, NULL, 0 },
693     };
694
695     while ((c = getopt_long(argc, argv, "+c:hlmps:Vvu", long_opts, NULL)) != -1) {
696         switch(c) {
697         case 'c':
698             ctx.to.shell = DEFAULT_SHELL;
699             ctx.to.command = optarg;
700             break;
701         case 'h':
702             usage(EXIT_SUCCESS);
703             break;
704         case 'l':
705             ctx.to.login = 1;
706             break;
707         case 'm':
708         case 'p':
709             ctx.to.keepenv = 1;
710             break;
711         case 's':
712             ctx.to.shell = optarg;
713             break;
714         case 'V':
715             printf("%d\n", VERSION_CODE);
716             exit(EXIT_SUCCESS);
717         case 'v':
718             printf("%s\n", VERSION);
719             exit(EXIT_SUCCESS);
720         case 'u':
721             switch (get_multiuser_mode()) {
722             case MULTIUSER_MODE_USER:
723                 printf("%s\n", MULTIUSER_VALUE_USER);
724                 break;
725             case MULTIUSER_MODE_OWNER_MANAGED:
726                 printf("%s\n", MULTIUSER_VALUE_OWNER_MANAGED);
727                 break;
728             case MULTIUSER_MODE_OWNER_ONLY:
729                 printf("%s\n", MULTIUSER_VALUE_OWNER_ONLY);
730                 break;
731             case MULTIUSER_MODE_NONE:
732                 printf("%s\n", MULTIUSER_VALUE_NONE);
733                 break;
734             }
735             exit(EXIT_SUCCESS);
736         default:
737             /* Bionic getopt_long doesn't terminate its error output by newline */
738             fprintf(stderr, "\n");
739             usage(2);
740         }
741     }
742     if (optind < argc && !strcmp(argv[optind], "-")) {
743         ctx.to.login = 1;
744         optind++;
745     }
746     /* username or uid */
747     if (optind < argc && strcmp(argv[optind], "--")) {
748         struct passwd *pw;
749         pw = getpwnam(argv[optind]);
750         if (!pw) {
751             char *endptr;
752
753             /* It seems we shouldn't do this at all */
754             errno = 0;
755             ctx.to.uid = strtoul(argv[optind], &endptr, 10);
756             if (errno || *endptr) {
757                 LOGE("Unknown id: %s\n", argv[optind]);
758                 fprintf(stderr, "Unknown id: %s\n", argv[optind]);
759                 exit(EXIT_FAILURE);
760             }
761         } else {
762             ctx.to.uid = pw->pw_uid;
763             if (pw->pw_name)
764                 strncpy(ctx.to.name, pw->pw_name, sizeof(ctx.to.name));
765         }
766         optind++;
767     }
768     if (optind < argc && !strcmp(argv[optind], "--")) {
769         optind++;
770     }
771     ctx.to.optind = optind;
772
773     su_ctx = &ctx;
774     if (from_init(&ctx.from) < 0) {
775         deny(&ctx);
776     }
777
778     read_options(&ctx);
779     user_init(&ctx);
780
781     // the latter two are necessary for stock ROMs like note 2 which do dumb things with su, or crash otherwise
782     if (ctx.from.uid == AID_ROOT) {
783         LOGD("Allowing root/system/radio.");
784         allow(&ctx);
785     }
786
787     // verify superuser is installed
788     if (stat(ctx.user.base_path, &st) < 0) {
789         // send to market (disabled, because people are and think this is hijacking their su)
790         // if (0 == strcmp(JAVA_PACKAGE_NAME, REQUESTOR))
791         //     silent_run("am start -d http://www.clockworkmod.com/superuser/install.html -a android.intent.action.VIEW");
792         PLOGE("stat %s", ctx.user.base_path);
793         deny(&ctx);
794     }
795
796     // odd perms on superuser data dir
797     if (st.st_gid != st.st_uid) {
798         LOGE("Bad uid/gid %d/%d for Superuser Requestor application",
799                 (int)st.st_uid, (int)st.st_gid);
800         deny(&ctx);
801     }
802
803     // always allow if this is the superuser uid
804     // superuser needs to be able to reenable itself when disabled...
805     if (ctx.from.uid == st.st_uid) {
806         allow(&ctx);
807     }
808
809     // check if superuser is disabled completely
810     if (access_disabled(&ctx.from)) {
811         LOGD("access_disabled");
812         deny(&ctx);
813     }
814
815     // autogrant shell at this point
816     if (ctx.from.uid == AID_SHELL) {
817         LOGD("Allowing shell.");
818         allow(&ctx);
819     }
820
821     // deny if this is a non owner request and owner mode only
822     if (ctx.user.multiuser_mode == MULTIUSER_MODE_OWNER_ONLY && ctx.user.android_user_id != 0) {
823         deny(&ctx);
824     }
825
826     ctx.umask = umask(027);
827
828     int ret = mkdir(REQUESTOR_CACHE_PATH, 0770);
829     if (chown(REQUESTOR_CACHE_PATH, st.st_uid, st.st_gid)) {
830         PLOGE("chown (%s, %ld, %ld)", REQUESTOR_CACHE_PATH, st.st_uid, st.st_gid);
831         deny(&ctx);
832     }
833
834     if (setgroups(0, NULL)) {
835         PLOGE("setgroups");
836         deny(&ctx);
837     }
838     if (setegid(st.st_gid)) {
839         PLOGE("setegid (%lu)", st.st_gid);
840         deny(&ctx);
841     }
842     if (seteuid(st.st_uid)) {
843         PLOGE("seteuid (%lu)", st.st_uid);
844         deny(&ctx);
845     }
846
847     dballow = database_check(&ctx);
848     switch (dballow) {
849         case INTERACTIVE:
850             break;
851         case ALLOW:
852             LOGD("db allowed");
853             allow(&ctx);    /* never returns */
854         case DENY:
855         default:
856             LOGD("db denied");
857             deny(&ctx);        /* never returns too */
858     }
859
860     socket_serv_fd = socket_create_temp(ctx.sock_path, sizeof(ctx.sock_path));
861     LOGD(ctx.sock_path);
862     if (socket_serv_fd < 0) {
863         deny(&ctx);
864     }
865
866     signal(SIGHUP, cleanup_signal);
867     signal(SIGPIPE, cleanup_signal);
868     signal(SIGTERM, cleanup_signal);
869     signal(SIGQUIT, cleanup_signal);
870     signal(SIGINT, cleanup_signal);
871     signal(SIGABRT, cleanup_signal);
872
873     if (send_request(&ctx) < 0) {
874         deny(&ctx);
875     }
876
877     atexit(cleanup);
878
879     fd = socket_accept(socket_serv_fd);
880     if (fd < 0) {
881         deny(&ctx);
882     }
883     if (socket_send_request(fd, &ctx)) {
884         deny(&ctx);
885     }
886     if (socket_receive_result(fd, buf, sizeof(buf))) {
887         deny(&ctx);
888     }
889
890     close(fd);
891     close(socket_serv_fd);
892     socket_cleanup(&ctx);
893
894     result = buf;
895
896 #define SOCKET_RESPONSE    "socket:"
897     if (strncmp(result, SOCKET_RESPONSE, sizeof(SOCKET_RESPONSE) - 1))
898         LOGW("SECURITY RISK: Requestor still receives credentials in intent");
899     else
900         result += sizeof(SOCKET_RESPONSE) - 1;
901
902     if (!strcmp(result, "DENY")) {
903         deny(&ctx);
904     } else if (!strcmp(result, "ALLOW")) {
905         allow(&ctx);
906     } else {
907         LOGE("unknown response from Superuser Requestor: %s", result);
908         deny(&ctx);
909     }
910 }