tests: remove crufty test=test_name code from old tests
[coreutils/ericb.git] / src / chcon.c
blob34e92e41179a19b3b13b83399b5b314db3925694
1 /* chcon -- change security context of files
2 Copyright (C) 2005-2012 Free Software Foundation, Inc.
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 of the License, or
7 (at your option) any later version.
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.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 #include <config.h>
18 #include <stdio.h>
19 #include <sys/types.h>
20 #include <getopt.h>
22 #include "system.h"
23 #include "dev-ino.h"
24 #include "error.h"
25 #include "ignore-value.h"
26 #include "quote.h"
27 #include "quotearg.h"
28 #include "root-dev-ino.h"
29 #include "selinux-at.h"
30 #include "xfts.h"
32 /* The official name of this program (e.g., no 'g' prefix). */
33 #define PROGRAM_NAME "chcon"
35 #define AUTHORS \
36 proper_name ("Russell Coker"), \
37 proper_name ("Jim Meyering")
39 /* If nonzero, and the systems has support for it, change the context
40 of symbolic links rather than any files they point to. */
41 static bool affect_symlink_referent;
43 /* If true, change the modes of directories recursively. */
44 static bool recurse;
46 /* Level of verbosity. */
47 static bool verbose;
49 /* Pointer to the device and inode numbers of '/', when --recursive.
50 Otherwise NULL. */
51 static struct dev_ino *root_dev_ino;
53 /* The name of the context file is being given. */
54 static char const *specified_context;
56 /* Specific components of the context */
57 static char const *specified_user;
58 static char const *specified_role;
59 static char const *specified_range;
60 static char const *specified_type;
62 /* For long options that have no equivalent short option, use a
63 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
64 enum
66 DEREFERENCE_OPTION = CHAR_MAX + 1,
67 NO_PRESERVE_ROOT,
68 PRESERVE_ROOT,
69 REFERENCE_FILE_OPTION
72 static struct option const long_options[] =
74 {"recursive", no_argument, NULL, 'R'},
75 {"dereference", no_argument, NULL, DEREFERENCE_OPTION},
76 {"no-dereference", no_argument, NULL, 'h'},
77 {"no-preserve-root", no_argument, NULL, NO_PRESERVE_ROOT},
78 {"preserve-root", no_argument, NULL, PRESERVE_ROOT},
79 {"reference", required_argument, NULL, REFERENCE_FILE_OPTION},
80 {"user", required_argument, NULL, 'u'},
81 {"role", required_argument, NULL, 'r'},
82 {"type", required_argument, NULL, 't'},
83 {"range", required_argument, NULL, 'l'},
84 {"verbose", no_argument, NULL, 'v'},
85 {GETOPT_HELP_OPTION_DECL},
86 {GETOPT_VERSION_OPTION_DECL},
87 {NULL, 0, NULL, 0}
90 /* Given a security context, CONTEXT, derive a context_t (*RET),
91 setting any portions selected via the global variables, specified_user,
92 specified_role, etc. */
93 static int
94 compute_context_from_mask (security_context_t context, context_t *ret)
96 bool ok = true;
97 context_t new_context = context_new (context);
98 if (!new_context)
100 error (0, errno, _("failed to create security context: %s"),
101 quotearg_colon (context));
102 return 1;
105 #define SET_COMPONENT(C, comp) \
106 do \
108 if (specified_ ## comp \
109 && context_ ## comp ## _set ((C), specified_ ## comp)) \
111 error (0, errno, \
112 _("failed to set %s security context component to %s"), \
113 #comp, quote (specified_ ## comp)); \
114 ok = false; \
117 while (0)
119 SET_COMPONENT (new_context, user);
120 SET_COMPONENT (new_context, range);
121 SET_COMPONENT (new_context, role);
122 SET_COMPONENT (new_context, type);
124 if (!ok)
126 int saved_errno = errno;
127 context_free (new_context);
128 errno = saved_errno;
129 return 1;
132 *ret = new_context;
133 return 0;
136 /* Change the context of FILE, using specified components.
137 If it is a directory and -R is given, recurse.
138 Return 0 if successful, 1 if errors occurred. */
140 static int
141 change_file_context (int fd, char const *file)
143 security_context_t file_context = NULL;
144 context_t context;
145 security_context_t context_string;
146 int errors = 0;
148 if (specified_context == NULL)
150 int status = (affect_symlink_referent
151 ? getfileconat (fd, file, &file_context)
152 : lgetfileconat (fd, file, &file_context));
154 if (status < 0 && errno != ENODATA)
156 error (0, errno, _("failed to get security context of %s"),
157 quote (file));
158 return 1;
161 /* If the file doesn't have a context, and we're not setting all of
162 the context components, there isn't really an obvious default.
163 Thus, we just give up. */
164 if (file_context == NULL)
166 error (0, 0, _("can't apply partial context to unlabeled file %s"),
167 quote (file));
168 return 1;
171 if (compute_context_from_mask (file_context, &context))
172 return 1;
174 else
176 /* FIXME: this should be done exactly once, in main. */
177 context = context_new (specified_context);
178 if (!context)
179 abort ();
182 context_string = context_str (context);
184 if (file_context == NULL || ! STREQ (context_string, file_context))
186 int fail = (affect_symlink_referent
187 ? setfileconat (fd, file, context_string)
188 : lsetfileconat (fd, file, context_string));
190 if (fail)
192 errors = 1;
193 error (0, errno, _("failed to change context of %s to %s"),
194 quote_n (0, file), quote_n (1, context_string));
198 context_free (context);
199 freecon (file_context);
201 return errors;
204 /* Change the context of FILE.
205 Return true if successful. This function is called
206 once for every file system object that fts encounters. */
208 static bool
209 process_file (FTS *fts, FTSENT *ent)
211 char const *file_full_name = ent->fts_path;
212 char const *file = ent->fts_accpath;
213 const struct stat *file_stats = ent->fts_statp;
214 bool ok = true;
216 switch (ent->fts_info)
218 case FTS_D:
219 if (recurse)
221 if (ROOT_DEV_INO_CHECK (root_dev_ino, ent->fts_statp))
223 /* This happens e.g., with "chcon -R --preserve-root ... /"
224 and with "chcon -RH --preserve-root ... symlink-to-root". */
225 ROOT_DEV_INO_WARN (file_full_name);
226 /* Tell fts not to traverse into this hierarchy. */
227 fts_set (fts, ent, FTS_SKIP);
228 /* Ensure that we do not process "/" on the second visit. */
229 ignore_value (fts_read (fts));
230 return false;
232 return true;
234 break;
236 case FTS_DP:
237 if (! recurse)
238 return true;
239 break;
241 case FTS_NS:
242 /* For a top-level file or directory, this FTS_NS (stat failed)
243 indicator is determined at the time of the initial fts_open call.
244 With programs like chmod, chown, and chgrp, that modify
245 permissions, it is possible that the file in question is
246 accessible when control reaches this point. So, if this is
247 the first time we've seen the FTS_NS for this file, tell
248 fts_read to stat it "again". */
249 if (ent->fts_level == 0 && ent->fts_number == 0)
251 ent->fts_number = 1;
252 fts_set (fts, ent, FTS_AGAIN);
253 return true;
255 error (0, ent->fts_errno, _("cannot access %s"), quote (file_full_name));
256 ok = false;
257 break;
259 case FTS_ERR:
260 error (0, ent->fts_errno, "%s", quote (file_full_name));
261 ok = false;
262 break;
264 case FTS_DNR:
265 error (0, ent->fts_errno, _("cannot read directory %s"),
266 quote (file_full_name));
267 ok = false;
268 break;
270 case FTS_DC: /* directory that causes cycles */
271 if (cycle_warning_required (fts, ent))
273 emit_cycle_warning (file_full_name);
274 return false;
276 break;
278 default:
279 break;
282 if (ent->fts_info == FTS_DP
283 && ok && ROOT_DEV_INO_CHECK (root_dev_ino, file_stats))
285 ROOT_DEV_INO_WARN (file_full_name);
286 ok = false;
289 if (ok)
291 if (verbose)
292 printf (_("changing security context of %s\n"),
293 quote (file_full_name));
295 if (change_file_context (fts->fts_cwd_fd, file) != 0)
296 ok = false;
299 if ( ! recurse)
300 fts_set (fts, ent, FTS_SKIP);
302 return ok;
305 /* Recursively operate on the specified FILES (the last entry
306 of which is NULL). BIT_FLAGS controls how fts works.
307 Return true if successful. */
309 static bool
310 process_files (char **files, int bit_flags)
312 bool ok = true;
314 FTS *fts = xfts_open (files, bit_flags, NULL);
316 while (1)
318 FTSENT *ent;
320 ent = fts_read (fts);
321 if (ent == NULL)
323 if (errno != 0)
325 /* FIXME: try to give a better message */
326 error (0, errno, _("fts_read failed"));
327 ok = false;
329 break;
332 ok &= process_file (fts, ent);
335 if (fts_close (fts) != 0)
337 error (0, errno, _("fts_close failed"));
338 ok = false;
341 return ok;
344 void
345 usage (int status)
347 if (status != EXIT_SUCCESS)
348 emit_try_help ();
349 else
351 printf (_("\
352 Usage: %s [OPTION]... CONTEXT FILE...\n\
353 or: %s [OPTION]... [-u USER] [-r ROLE] [-l RANGE] [-t TYPE] FILE...\n\
354 or: %s [OPTION]... --reference=RFILE FILE...\n\
356 program_name, program_name, program_name);
357 fputs (_("\
358 Change the security context of each FILE to CONTEXT.\n\
359 With --reference, change the security context of each FILE to that of RFILE.\n\
361 "), stdout);
362 fputs (_("\
363 --dereference affect the referent of each symbolic link (this is\n\
364 the default), rather than the symbolic link itself\n\
365 -h, --no-dereference affect symbolic links instead of any referenced file\n\
366 "), stdout);
367 fputs (_("\
368 -u, --user=USER set user USER in the target security context\n\
369 -r, --role=ROLE set role ROLE in the target security context\n\
370 -t, --type=TYPE set type TYPE in the target security context\n\
371 -l, --range=RANGE set range RANGE in the target security context\n\
372 "), stdout);
373 fputs (_("\
374 --reference=RFILE use RFILE's security context rather than specifying\n\
375 a CONTEXT value\n\
376 "), stdout);
377 fputs (_("\
378 -R, --recursive operate on files and directories recursively\n\
379 "), stdout);
380 fputs (_("\
381 -v, --verbose output a diagnostic for every file processed\n\
382 "), stdout);
383 fputs (_("\
385 The following options modify how a hierarchy is traversed when the -R\n\
386 option is also specified. If more than one is specified, only the final\n\
387 one takes effect.\n\
389 -H if a command line argument is a symbolic link\n\
390 to a directory, traverse it\n\
391 -L traverse every symbolic link to a directory\n\
392 encountered\n\
393 -P do not traverse any symbolic links (default)\n\
395 "), stdout);
396 fputs (HELP_OPTION_DESCRIPTION, stdout);
397 fputs (VERSION_OPTION_DESCRIPTION, stdout);
398 emit_ancillary_info ();
400 exit (status);
404 main (int argc, char **argv)
406 security_context_t ref_context = NULL;
408 /* Bit flags that control how fts works. */
409 int bit_flags = FTS_PHYSICAL;
411 /* 1 if --dereference, 0 if --no-dereference, -1 if neither has been
412 specified. */
413 int dereference = -1;
415 bool ok;
416 bool preserve_root = false;
417 bool component_specified = false;
418 char *reference_file = NULL;
419 int optc;
421 initialize_main (&argc, &argv);
422 set_program_name (argv[0]);
423 setlocale (LC_ALL, "");
424 bindtextdomain (PACKAGE, LOCALEDIR);
425 textdomain (PACKAGE);
427 atexit (close_stdout);
429 while ((optc = getopt_long (argc, argv, "HLPRhvu:r:t:l:", long_options, NULL))
430 != -1)
432 switch (optc)
434 case 'H': /* Traverse command-line symlinks-to-directories. */
435 bit_flags = FTS_COMFOLLOW | FTS_PHYSICAL;
436 break;
438 case 'L': /* Traverse all symlinks-to-directories. */
439 bit_flags = FTS_LOGICAL;
440 break;
442 case 'P': /* Traverse no symlinks-to-directories. */
443 bit_flags = FTS_PHYSICAL;
444 break;
446 case 'h': /* --no-dereference: affect symlinks */
447 dereference = 0;
448 break;
450 case DEREFERENCE_OPTION: /* --dereference: affect the referent
451 of each symlink */
452 dereference = 1;
453 break;
455 case NO_PRESERVE_ROOT:
456 preserve_root = false;
457 break;
459 case PRESERVE_ROOT:
460 preserve_root = true;
461 break;
463 case REFERENCE_FILE_OPTION:
464 reference_file = optarg;
465 break;
467 case 'R':
468 recurse = true;
469 break;
471 case 'f':
472 /* ignore */
473 break;
475 case 'v':
476 verbose = true;
477 break;
479 case 'u':
480 specified_user = optarg;
481 component_specified = true;
482 break;
484 case 'r':
485 specified_role = optarg;
486 component_specified = true;
487 break;
489 case 't':
490 specified_type = optarg;
491 component_specified = true;
492 break;
494 case 'l':
495 specified_range = optarg;
496 component_specified = true;
497 break;
499 case_GETOPT_HELP_CHAR;
500 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
501 default:
502 usage (EXIT_FAILURE);
506 if (recurse)
508 if (bit_flags == FTS_PHYSICAL)
510 if (dereference == 1)
511 error (EXIT_FAILURE, 0,
512 _("-R --dereference requires either -H or -L"));
513 affect_symlink_referent = false;
515 else
517 if (dereference == 0)
518 error (EXIT_FAILURE, 0, _("-R -h requires -P"));
519 affect_symlink_referent = true;
522 else
524 bit_flags = FTS_PHYSICAL;
525 affect_symlink_referent = (dereference != 0);
528 if (argc - optind < (reference_file || component_specified ? 1 : 2))
530 if (argc <= optind)
531 error (0, 0, _("missing operand"));
532 else
533 error (0, 0, _("missing operand after %s"), quote (argv[argc - 1]));
534 usage (EXIT_FAILURE);
537 if (reference_file)
539 if (getfilecon (reference_file, &ref_context) < 0)
540 error (EXIT_FAILURE, errno, _("failed to get security context of %s"),
541 quote (reference_file));
543 specified_context = ref_context;
545 else if (component_specified)
547 /* FIXME: it's already null, so this is a no-op. */
548 specified_context = NULL;
550 else
552 context_t context;
553 specified_context = argv[optind++];
554 context = context_new (specified_context);
555 if (!context)
556 error (EXIT_FAILURE, 0, _("invalid context: %s"),
557 quotearg_colon (specified_context));
558 context_free (context);
561 if (reference_file && component_specified)
563 error (0, 0, _("conflicting security context specifiers given"));
564 usage (EXIT_FAILURE);
567 if (recurse && preserve_root)
569 static struct dev_ino dev_ino_buf;
570 root_dev_ino = get_root_dev_ino (&dev_ino_buf);
571 if (root_dev_ino == NULL)
572 error (EXIT_FAILURE, errno, _("failed to get attributes of %s"),
573 quote ("/"));
575 else
577 root_dev_ino = NULL;
580 ok = process_files (argv + optind, bit_flags | FTS_NOSTAT);
582 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);