OSDN Git Service

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