1#include <semanage/fcontext_record.h>
2#include <semanage/semanage.h>
3#include <semanage/fcontexts_local.h>
4#include <sepol/sepol.h>
5
6#include <errno.h>
7#include <stdio.h>
8#include <stdlib.h>
9
10int main(const int argc, const char **argv) {
11	semanage_handle_t *sh = NULL;
12	semanage_fcontext_t *fcontext;
13	semanage_context_t *con;
14	semanage_fcontext_key_t *k;
15
16	int exist = 0;
17	sh = semanage_handle_create();
18	if (sh == NULL) {
19		perror("Can't create semanage handle\n");
20		return -1;
21	}
22        if (semanage_access_check(sh) < 0) {
23		perror("Semanage access check failed\n");
24		return -1;
25	}
26        if (semanage_connect(sh) < 0) {
27		perror("Semanage connect failed\n");
28		return -1;
29	}
30
31	if (semanage_fcontext_key_create(sh, argv[2], SEMANAGE_FCONTEXT_REG, &k) < 0) {
32		fprintf(stderr, "Could not create key for %s", argv[2]);
33		return -1;
34	}
35
36	if(semanage_fcontext_exists(sh, k, &exist) < 0) {
37		fprintf(stderr,"Could not check if key exists for %s", argv[2]);
38		return -1;
39	}
40	if (exist) {
41		fprintf(stderr,"Could create %s mapping already exists", argv[2]);
42		return -1;
43	}
44
45	if (semanage_fcontext_create(sh, &fcontext) < 0) {
46		fprintf(stderr,"Could not create file context for %s", argv[2]);
47		return -1;
48	}
49	semanage_fcontext_set_expr(sh, fcontext, argv[2]);
50
51	if (semanage_context_from_string(sh, argv[1], &con)) {
52		fprintf(stderr,"Could not create context using %s for file context %s", argv[1], argv[2]);
53		return -1;
54	}
55
56	if (semanage_fcontext_set_con(sh, fcontext, con) < 0) {
57		fprintf(stderr,"Could not set file context for %s", argv[2]);
58		return -1;
59	}
60
61	semanage_fcontext_set_type(fcontext, SEMANAGE_FCONTEXT_REG);
62
63	if(semanage_fcontext_modify_local(sh, k, fcontext) < 0) {
64		fprintf(stderr,"Could not add file context for %s", argv[2]);
65		return -1;
66	}
67	semanage_fcontext_key_free(k);
68	semanage_fcontext_free(fcontext);
69
70	return 0;
71}
72
73