1 #include <unistd.h>
2 #include <sys/types.h>
3 #include <fcntl.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <errno.h>
7 #include <string.h>
8 #include <ctype.h>
9 #include <selinux/selinux.h>
10 #include <selinux/get_context_list.h>
11
usage(const char * name,const char * detail,int rc)12 static __attribute__ ((__noreturn__)) void usage(const char *name, const char *detail, int rc)
13 {
14 fprintf(stderr, "usage: %s [-l level] user [context]\n", name);
15 if (detail)
16 fprintf(stderr, "%s: %s\n", name, detail);
17 exit(rc);
18 }
19
main(int argc,char ** argv)20 int main(int argc, char **argv)
21 {
22 char **list, *cur_context = NULL;
23 char *user = NULL, *level = NULL;
24 int ret, i, opt;
25
26 while ((opt = getopt(argc, argv, "l:")) > 0) {
27 switch (opt) {
28 case 'l':
29 level = strdup(optarg);
30 break;
31 default:
32 usage(argv[0], "invalid option", 1);
33 }
34 }
35
36 if (((argc - optind) < 1) || ((argc - optind) > 2))
37 usage(argv[0], "invalid number of arguments", 2);
38
39 /* If selinux isn't available, bail out. */
40 if (!is_selinux_enabled()) {
41 fprintf(stderr,
42 "getconlist may be used only on a SELinux kernel.\n");
43 free(level);
44 return 1;
45 }
46
47 user = argv[optind];
48
49 /* If a context wasn't passed, use the current context. */
50 if (((argc - optind) < 2)) {
51 if (getcon(&cur_context) < 0) {
52 fprintf(stderr, "Couldn't get current context.\n");
53 free(level);
54 return 2;
55 }
56 } else
57 cur_context = argv[optind + 1];
58
59 /* Get the list and print it */
60 if (level)
61 ret =
62 get_ordered_context_list_with_level(user, level,
63 cur_context, &list);
64 else
65 ret = get_ordered_context_list(user, cur_context, &list);
66 if (ret != -1) {
67 for (i = 0; list[i]; i++)
68 puts(list[i]);
69 freeconary(list);
70 }
71
72 free(level);
73
74 return 0;
75 }
76