1 #include <getopt.h>
2 
3 #include "attribute.h"
4 
attribute_usage()5 void attribute_usage() {
6     fprintf(stderr, "\tattribute <name> [-r|--reverse]\n");
7 }
8 
retrieve_mapping(policydb_t * policydb,struct type_datum * dat,char * name,int reverse)9 static void retrieve_mapping(policydb_t *policydb, struct type_datum *dat, char *name, int reverse) {
10     struct ebitmap_node *n;
11     unsigned int bit;
12 
13     if (reverse) {
14         ebitmap_for_each_bit(&policydb->type_attr_map[dat->s.value - 1], n, bit) {
15             if (!ebitmap_node_get_bit(n, bit))
16                 continue;
17             if (!strcmp(policydb->p_type_val_to_name[bit], name))
18                 continue;
19             printf("%s\n", policydb->p_type_val_to_name[bit]);
20         }
21     } else {
22         ebitmap_for_each_bit(&policydb->attr_type_map[dat->s.value - 1], n, bit) {
23             if (!ebitmap_node_get_bit(n, bit))
24                 continue;
25             printf("%s\n", policydb->p_type_val_to_name[bit]);
26         }
27     }
28 }
29 
list_attribute(policydb_t * policydb,char * name,int reverse)30 static int list_attribute(policydb_t *policydb, char *name, int reverse)
31 {
32     struct type_datum *dat;
33 
34     dat = hashtab_search(policydb->p_types.table, name);
35     if (!dat) {
36         fprintf(stderr, "%s is not defined in this policy.\n", name);
37         return -1;
38     }
39 
40     if (reverse) {
41         if (dat->flavor != TYPE_TYPE) {
42             fprintf(stderr, "%s is an attribute not a type in this policy.\n", name);
43             return -1;
44         }
45     } else {
46         if (dat->flavor != TYPE_ATTRIB) {
47             fprintf(stderr, "%s is a type not an attribute in this policy.\n", name);
48             return -1;
49         }
50     }
51     retrieve_mapping(policydb, dat, name, reverse);
52 
53     return 0;
54 }
55 
attribute_func(int argc,char ** argv,policydb_t * policydb)56 int attribute_func (int argc, char **argv, policydb_t *policydb) {
57     int reverse = 0;
58     char ch;
59 
60     struct option attribute_options[] = {
61         {"reverse", no_argument, NULL, 'r'},
62         {NULL, 0, NULL, 0}
63     };
64 
65     while ((ch = getopt_long(argc, argv, "r", attribute_options, NULL)) != -1) {
66         switch (ch) {
67         case 'r':
68             reverse = 1;
69             break;
70         default:
71             USAGE_ERROR = true;
72             return -1;
73         }
74     }
75 
76     if (argc != 2 && !(reverse && argc == 3)) {
77         USAGE_ERROR = true;
78         return -1;
79     }
80     return list_attribute(policydb, argv[optind], reverse);
81 }
82