unistr/u8-chr, unistr/u8-strchr: use Boyer-Moore like algorithm.
[gnulib.git] / lib / getfilecon.c
1 /* wrap getfilecon, lgetfilecon, and fgetfilecon
2    Copyright (C) 2009-2010 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 3, or (at your option)
7    any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software Foundation,
16    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
17
18 /* written by Jim Meyering */
19
20 #include <config.h>
21
22 #include <selinux/selinux.h>
23
24 #include <sys/types.h>
25 #include <errno.h>
26 #include <string.h>
27
28 /* FIXME: remove this once there is an errno-gnu module
29    that guarantees the definition of ENODATA.  */
30 #ifndef ENODATA
31 # define ENODATA ENOTSUP
32 #endif
33
34 #undef getfilecon
35 #undef lgetfilecon
36 #undef fgetfilecon
37 int getfilecon (char const *file, security_context_t *con);
38 int lgetfilecon (char const *file, security_context_t *con);
39 int fgetfilecon (int fd, security_context_t *con);
40
41 /* getfilecon, lgetfilecon, and fgetfilecon can all misbehave, be it
42    via an old version of libselinux where these would return 0 and set the
43    result context to NULL, or via a modern kernel+lib operating on a file
44    from a disk whose attributes were set by a kernel from around 2006.
45    In that latter case, the functions return a length of 10 for the
46    "unlabeled" context.  Map both failures to a return value of -1, and
47    set errno to ENOTSUP in the first case, and ENODATA in the latter.  */
48
49 static inline int
50 map_to_failure (int ret, security_context_t *con)
51 {
52   if (ret == 0)
53     {
54       errno = ENOTSUP;
55       return -1;
56     }
57
58   if (ret == 10 && strcmp (*con, "unlabeled") == 0)
59     {
60       freecon (*con);
61       errno = ENODATA;
62       return -1;
63     }
64
65   return ret;
66 }
67
68 int
69 rpl_getfilecon (char const *file, security_context_t *con)
70 {
71   int ret = getfilecon (file, con);
72   return map_to_failure (ret, con);
73 }
74
75 int
76 rpl_lgetfilecon (char const *file, security_context_t *con)
77 {
78   int ret = lgetfilecon (file, con);
79   return map_to_failure (ret, con);
80 }
81
82 int
83 rpl_fgetfilecon (int fd, security_context_t *con)
84 {
85   int ret = fgetfilecon (fd, con);
86   return map_to_failure (ret, con);
87 }