OSDN Git Service

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