another update from CVS HEAD, for QA
[alioth/jupp.git] / selinux.c
1 #include "config.h"
2
3 __RCSID("$MirOS: contrib/code/jupp/selinux.c,v 1.11 2017/12/06 23:02:05 tg Exp $");
4
5 #if defined(HAVE_SELINUX_CONTEXT_H) && defined(HAVE_SELINUX_SELINUX_H) && \
6     defined(HAVE_SELINUX_FUN)
7 #define WITH_SELINUX
8 #else
9 #undef WITH_SELINUX
10 #endif
11
12 #include "utils.h"
13
14 #ifdef WITH_SELINUX
15 #include <selinux/selinux.h>
16 static int selinux_enabled = -1;
17 #include <err.h>
18 #include <errno.h>
19 #include <string.h>
20 #endif
21
22 int
23 copy_security_context(const char *from_file, const char *to_file)
24 {
25         int status = 0;
26 #ifdef WITH_SELINUX
27         security_context_t from_context;
28         security_context_t to_context;
29
30         if (selinux_enabled == -1)
31                 selinux_enabled = (is_selinux_enabled() > 0);
32
33         if (!selinux_enabled)
34                 return 0;
35
36         if (getfilecon(from_file, &from_context) < 0) {
37                 /*
38                  * If the filesystem doesn't support extended
39                  * attributes, the original had no special security
40                  * context and the target cannot have one either.
41                  */
42                 if (errno == EOPNOTSUPP)
43                         return 0;
44
45                 warn("Could not get security context for %s",
46                       from_file);
47                 return 1;
48         }
49
50         if (getfilecon(to_file, &to_context) < 0) {
51                 warn("Could not get security context for %s",
52                     to_file);
53                 freecon(from_context);
54                 return 1;
55         }
56
57         if (strcmp(from_context, to_context) != 0) {
58                 if (setfilecon(to_file, from_context) < 0) {
59                         warn(
60                               "Could not set security context for %s",
61                               to_file);
62                         status = 1;
63                 }
64         }
65
66         freecon(to_context);
67         freecon(from_context);
68 #endif
69         return status;
70 }