dd: synchronize output after write errors
[coreutils.git] / src / chcon.c
blobbfe77b5de4821458bf36f88bb1e2e074a7863cbe
1 /* chcon -- change security context of files
2 Copyright (C) 2005-2022 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 <https://www.gnu.org/licenses/>. */
17 #include <config.h>
18 #include <stdio.h>
19 #include <sys/types.h>
20 #include <getopt.h>
21 #include <selinux/selinux.h>
23 #include "system.h"
24 #include "dev-ino.h"
25 #include "die.h"
26 #include "error.h"
27 #include "ignore-value.h"
28 #include "quote.h"
29 #include "root-dev-ino.h"
30 #include "selinux-at.h"
31 #include "xfts.h"
33 /* The official name of this program (e.g., no 'g' prefix). */
34 #define PROGRAM_NAME "chcon"
36 #define AUTHORS \
37 proper_name ("Russell Coker"), \
38 proper_name ("Jim Meyering")
40 /* If nonzero, and the systems has support for it, change the context
41 of symbolic links rather than any files they point to. */
42 static bool affect_symlink_referent;
44 /* If true, change the modes of directories recursively. */
45 static bool recurse;
47 /* Level of verbosity. */
48 static bool verbose;
50 /* Pointer to the device and inode numbers of '/', when --recursive.
51 Otherwise NULL. */
52 static struct dev_ino *root_dev_ino;
54 /* The name of the context file is being given. */
55 static char const *specified_context;
57 /* Specific components of the context */
58 static char const *specified_user;
59 static char const *specified_role;
60 static char const *specified_range;
61 static char const *specified_type;
63 /* For long options that have no equivalent short option, use a
64 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
65 enum
67 DEREFERENCE_OPTION = CHAR_MAX + 1,
68 NO_PRESERVE_ROOT,
69 PRESERVE_ROOT,
70 REFERENCE_FILE_OPTION
73 static struct option const long_options[] =
75 {"recursive", no_argument, NULL, 'R'},
76 {"dereference", no_argument, NULL, DEREFERENCE_OPTION},
77 {"no-dereference", no_argument, NULL, 'h'},
78 {"no-preserve-root", no_argument, NULL, NO_PRESERVE_ROOT},
79 {"preserve-root", no_argument, NULL, PRESERVE_ROOT},
80 {"reference", required_argument, NULL, REFERENCE_FILE_OPTION},
81 {"user", required_argument, NULL, 'u'},
82 {"role", required_argument, NULL, 'r'},
83 {"type", required_argument, NULL, 't'},
84 {"range", required_argument, NULL, 'l'},
85 {"verbose", no_argument, NULL, 'v'},
86 {GETOPT_HELP_OPTION_DECL},
87 {GETOPT_VERSION_OPTION_DECL},
88 {NULL, 0, NULL, 0}
91 /* Given a security context, CONTEXT, derive a context_t (*RET),
92 setting any portions selected via the global variables, specified_user,
93 specified_role, etc. */
94 static int
95 compute_context_from_mask (char const *context, context_t *ret)
97 bool ok = true;
98 context_t new_context = context_new (context);
99 if (!new_context)
101 error (0, errno, _("failed to create security context: %s"),
102 quote (context));
103 return 1;
106 #define SET_COMPONENT(C, comp) \
107 do \
109 if (specified_ ## comp \
110 && context_ ## comp ## _set ((C), specified_ ## comp)) \
112 error (0, errno, \
113 _("failed to set %s security context component to %s"), \
114 #comp, quote (specified_ ## comp)); \
115 ok = false; \
118 while (0)
120 SET_COMPONENT (new_context, user);
121 SET_COMPONENT (new_context, range);
122 SET_COMPONENT (new_context, role);
123 SET_COMPONENT (new_context, type);
125 if (!ok)
127 int saved_errno = errno;
128 context_free (new_context);
129 errno = saved_errno;
130 return 1;
133 *ret = new_context;
134 return 0;
137 /* Change the context of FILE, using specified components.
138 If it is a directory and -R is given, recurse.
139 Return 0 if successful, 1 if errors occurred. */
141 static int
142 change_file_context (int fd, char const *file)
144 char *file_context = NULL;
145 context_t context IF_LINT (= 0);
146 char const * context_string;
147 int errors = 0;
149 if (specified_context == NULL)
151 int status = (affect_symlink_referent
152 ? getfileconat (fd, file, &file_context)
153 : lgetfileconat (fd, file, &file_context));
155 if (status < 0 && errno != ENODATA)
157 error (0, errno, _("failed to get security context of %s"),
158 quoteaf (file));
159 return 1;
162 /* If the file doesn't have a context, and we're not setting all of
163 the context components, there isn't really an obvious default.
164 Thus, we just give up. */
165 if (file_context == NULL)
167 error (0, 0, _("can't apply partial context to unlabeled file %s"),
168 quoteaf (file));
169 return 1;
172 if (compute_context_from_mask (file_context, &context))
173 return 1;
175 context_string = context_str (context);
177 else
179 context_string = specified_context;
182 if (file_context == NULL || ! STREQ (context_string, file_context))
184 int fail = (affect_symlink_referent
185 ? setfileconat (fd, file, context_string)
186 : lsetfileconat (fd, file, context_string));
188 if (fail)
190 errors = 1;
191 error (0, errno, _("failed to change context of %s to %s"),
192 quoteaf_n (0, file), quote_n (1, context_string));
196 if (specified_context == NULL)
198 context_free (context);
199 freecon (file_context);
202 return errors;
205 /* Change the context of FILE.
206 Return true if successful. This function is called
207 once for every file system object that fts encounters. */
209 static bool
210 process_file (FTS *fts, FTSENT *ent)
212 char const *file_full_name = ent->fts_path;
213 char const *file = ent->fts_accpath;
214 const struct stat *file_stats = ent->fts_statp;
215 bool ok = true;
217 switch (ent->fts_info)
219 case FTS_D:
220 if (recurse)
222 if (ROOT_DEV_INO_CHECK (root_dev_ino, ent->fts_statp))
224 /* This happens e.g., with "chcon -R --preserve-root ... /"
225 and with "chcon -RH --preserve-root ... symlink-to-root". */
226 ROOT_DEV_INO_WARN (file_full_name);
227 /* Tell fts not to traverse into this hierarchy. */
228 fts_set (fts, ent, FTS_SKIP);
229 /* Ensure that we do not process "/" on the second visit. */
230 ignore_value (fts_read (fts));
231 return false;
233 return true;
235 break;
237 case FTS_DP:
238 if (! recurse)
239 return true;
240 break;
242 case FTS_NS:
243 /* For a top-level file or directory, this FTS_NS (stat failed)
244 indicator is determined at the time of the initial fts_open call.
245 With programs like chmod, chown, and chgrp, that modify
246 permissions, it is possible that the file in question is
247 accessible when control reaches this point. So, if this is
248 the first time we've seen the FTS_NS for this file, tell
249 fts_read to stat it "again". */
250 if (ent->fts_level == 0 && ent->fts_number == 0)
252 ent->fts_number = 1;
253 fts_set (fts, ent, FTS_AGAIN);
254 return true;
256 error (0, ent->fts_errno, _("cannot access %s"),
257 quoteaf (file_full_name));
258 ok = false;
259 break;
261 case FTS_ERR:
262 error (0, ent->fts_errno, "%s", quotef (file_full_name));
263 ok = false;
264 break;
266 case FTS_DNR:
267 error (0, ent->fts_errno, _("cannot read directory %s"),
268 quoteaf (file_full_name));
269 ok = false;
270 break;
272 case FTS_DC: /* directory that causes cycles */
273 if (cycle_warning_required (fts, ent))
275 emit_cycle_warning (file_full_name);
276 return false;
278 break;
280 default:
281 break;
284 if (ent->fts_info == FTS_DP
285 && ok && ROOT_DEV_INO_CHECK (root_dev_ino, file_stats))
287 ROOT_DEV_INO_WARN (file_full_name);
288 ok = false;
291 if (ok)
293 if (verbose)
294 printf (_("changing security context of %s\n"),
295 quoteaf (file_full_name));
297 if (change_file_context (fts->fts_cwd_fd, file) != 0)
298 ok = false;
301 if ( ! recurse)
302 fts_set (fts, ent, FTS_SKIP);
304 return ok;
307 /* Recursively operate on the specified FILES (the last entry
308 of which is NULL). BIT_FLAGS controls how fts works.
309 Return true if successful. */
311 static bool
312 process_files (char **files, int bit_flags)
314 bool ok = true;
316 FTS *fts = xfts_open (files, bit_flags, NULL);
318 while (true)
320 FTSENT *ent;
322 ent = fts_read (fts);
323 if (ent == NULL)
325 if (errno != 0)
327 /* FIXME: try to give a better message */
328 error (0, errno, _("fts_read failed"));
329 ok = false;
331 break;
334 ok &= process_file (fts, ent);
337 if (fts_close (fts) != 0)
339 error (0, errno, _("fts_close failed"));
340 ok = false;
343 return ok;
346 void
347 usage (int status)
349 if (status != EXIT_SUCCESS)
350 emit_try_help ();
351 else
353 printf (_("\
354 Usage: %s [OPTION]... CONTEXT FILE...\n\
355 or: %s [OPTION]... [-u USER] [-r ROLE] [-l RANGE] [-t TYPE] FILE...\n\
356 or: %s [OPTION]... --reference=RFILE FILE...\n\
358 program_name, program_name, program_name);
359 fputs (_("\
360 Change the SELinux security context of each FILE to CONTEXT.\n\
361 With --reference, change the security context of each FILE to that of RFILE.\n\
362 "), stdout);
364 emit_mandatory_arg_note ();
366 fputs (_("\
367 --dereference affect the referent of each symbolic link (this is\n\
368 the default), rather than the symbolic link itself\n\
369 -h, --no-dereference affect symbolic links instead of any referenced file\n\
370 "), stdout);
371 fputs (_("\
372 -u, --user=USER set user USER in the target security context\n\
373 -r, --role=ROLE set role ROLE in the target security context\n\
374 -t, --type=TYPE set type TYPE in the target security context\n\
375 -l, --range=RANGE set range RANGE in the target security context\n\
376 "), stdout);
377 fputs (_("\
378 --no-preserve-root do not treat '/' specially (the default)\n\
379 --preserve-root fail to operate recursively on '/'\n\
380 "), stdout);
381 fputs (_("\
382 --reference=RFILE use RFILE's security context rather than specifying\n\
383 a CONTEXT value\n\
384 "), stdout);
385 fputs (_("\
386 -R, --recursive operate on files and directories recursively\n\
387 "), stdout);
388 fputs (_("\
389 -v, --verbose output a diagnostic for every file processed\n\
390 "), stdout);
391 fputs (_("\
393 The following options modify how a hierarchy is traversed when the -R\n\
394 option is also specified. If more than one is specified, only the final\n\
395 one takes effect.\n\
397 -H if a command line argument is a symbolic link\n\
398 to a directory, traverse it\n\
399 -L traverse every symbolic link to a directory\n\
400 encountered\n\
401 -P do not traverse any symbolic links (default)\n\
403 "), stdout);
404 fputs (HELP_OPTION_DESCRIPTION, stdout);
405 fputs (VERSION_OPTION_DESCRIPTION, stdout);
406 emit_ancillary_info (PROGRAM_NAME);
408 exit (status);
412 main (int argc, char **argv)
414 /* Bit flags that control how fts works. */
415 int bit_flags = FTS_PHYSICAL;
417 /* 1 if --dereference, 0 if --no-dereference, -1 if neither has been
418 specified. */
419 int dereference = -1;
421 bool ok;
422 bool preserve_root = false;
423 bool component_specified = false;
424 char *reference_file = NULL;
425 int optc;
427 initialize_main (&argc, &argv);
428 set_program_name (argv[0]);
429 setlocale (LC_ALL, "");
430 bindtextdomain (PACKAGE, LOCALEDIR);
431 textdomain (PACKAGE);
433 atexit (close_stdout);
435 while ((optc = getopt_long (argc, argv, "HLPRhvu:r:t:l:", long_options, NULL))
436 != -1)
438 switch (optc)
440 case 'H': /* Traverse command-line symlinks-to-directories. */
441 bit_flags = FTS_COMFOLLOW | FTS_PHYSICAL;
442 break;
444 case 'L': /* Traverse all symlinks-to-directories. */
445 bit_flags = FTS_LOGICAL;
446 break;
448 case 'P': /* Traverse no symlinks-to-directories. */
449 bit_flags = FTS_PHYSICAL;
450 break;
452 case 'h': /* --no-dereference: affect symlinks */
453 dereference = 0;
454 break;
456 case DEREFERENCE_OPTION: /* --dereference: affect the referent
457 of each symlink */
458 dereference = 1;
459 break;
461 case NO_PRESERVE_ROOT:
462 preserve_root = false;
463 break;
465 case PRESERVE_ROOT:
466 preserve_root = true;
467 break;
469 case REFERENCE_FILE_OPTION:
470 reference_file = optarg;
471 break;
473 case 'R':
474 recurse = true;
475 break;
477 case 'f':
478 /* ignore */
479 break;
481 case 'v':
482 verbose = true;
483 break;
485 case 'u':
486 specified_user = optarg;
487 component_specified = true;
488 break;
490 case 'r':
491 specified_role = optarg;
492 component_specified = true;
493 break;
495 case 't':
496 specified_type = optarg;
497 component_specified = true;
498 break;
500 case 'l':
501 specified_range = optarg;
502 component_specified = true;
503 break;
505 case_GETOPT_HELP_CHAR;
506 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
507 default:
508 usage (EXIT_FAILURE);
512 if (recurse)
514 if (bit_flags == FTS_PHYSICAL)
516 if (dereference == 1)
517 die (EXIT_FAILURE, 0,
518 _("-R --dereference requires either -H or -L"));
519 affect_symlink_referent = false;
521 else
523 if (dereference == 0)
524 die (EXIT_FAILURE, 0, _("-R -h requires -P"));
525 affect_symlink_referent = true;
528 else
530 bit_flags = FTS_PHYSICAL;
531 affect_symlink_referent = (dereference != 0);
534 if (argc - optind < (reference_file || component_specified ? 1 : 2))
536 if (argc <= optind)
537 error (0, 0, _("missing operand"));
538 else
539 error (0, 0, _("missing operand after %s"), quote (argv[argc - 1]));
540 usage (EXIT_FAILURE);
543 if (reference_file)
545 char *ref_context = NULL;
547 if (getfilecon (reference_file, &ref_context) < 0)
548 die (EXIT_FAILURE, errno, _("failed to get security context of %s"),
549 quoteaf (reference_file));
551 specified_context = ref_context;
553 else if (component_specified)
555 /* FIXME: it's already null, so this is a no-op. */
556 specified_context = NULL;
558 else
560 specified_context = argv[optind++];
561 if (0 < is_selinux_enabled ()
562 && security_check_context (specified_context) < 0)
563 die (EXIT_FAILURE, errno, _("invalid context: %s"),
564 quote (specified_context));
567 if (reference_file && component_specified)
569 error (0, 0, _("conflicting security context specifiers given"));
570 usage (EXIT_FAILURE);
573 if (recurse && preserve_root)
575 static struct dev_ino dev_ino_buf;
576 root_dev_ino = get_root_dev_ino (&dev_ino_buf);
577 if (root_dev_ino == NULL)
578 die (EXIT_FAILURE, errno, _("failed to get attributes of %s"),
579 quoteaf ("/"));
581 else
583 root_dev_ino = NULL;
586 ok = process_files (argv + optind, bit_flags | FTS_NOSTAT);
588 return ok ? EXIT_SUCCESS : EXIT_FAILURE;