all: update gnulib submodule to latest
[coreutils.git] / src / cp.c
blob6949a677e3711e7b7251949b924fced3ba1e90a0
1 /* cp.c -- file copying (main routines)
2 Copyright (C) 1989-2017 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 Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. */
19 #include <config.h>
20 #include <stdio.h>
21 #include <sys/types.h>
22 #include <getopt.h>
23 #include <selinux/selinux.h>
25 #include "system.h"
26 #include "argmatch.h"
27 #include "backupfile.h"
28 #include "copy.h"
29 #include "cp-hash.h"
30 #include "die.h"
31 #include "error.h"
32 #include "filenamecat.h"
33 #include "ignore-value.h"
34 #include "quote.h"
35 #include "stat-time.h"
36 #include "utimens.h"
37 #include "acl.h"
39 #if ! HAVE_LCHOWN
40 # define lchown(name, uid, gid) chown (name, uid, gid)
41 #endif
43 #define ASSIGN_BASENAME_STRDUPA(Dest, File_name) \
44 do \
45 { \
46 char *tmp_abns_; \
47 ASSIGN_STRDUPA (tmp_abns_, (File_name)); \
48 Dest = last_component (tmp_abns_); \
49 strip_trailing_slashes (Dest); \
50 } \
51 while (0)
53 /* The official name of this program (e.g., no 'g' prefix). */
54 #define PROGRAM_NAME "cp"
56 #define AUTHORS \
57 proper_name ("Torbjorn Granlund"), \
58 proper_name ("David MacKenzie"), \
59 proper_name ("Jim Meyering")
61 /* Used by do_copy, make_dir_parents_private, and re_protect
62 to keep a list of leading directories whose protections
63 need to be fixed after copying. */
64 struct dir_attr
66 struct stat st;
67 bool restore_mode;
68 size_t slash_offset;
69 struct dir_attr *next;
72 /* For long options that have no equivalent short option, use a
73 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
74 enum
76 ATTRIBUTES_ONLY_OPTION = CHAR_MAX + 1,
77 COPY_CONTENTS_OPTION,
78 NO_PRESERVE_ATTRIBUTES_OPTION,
79 PARENTS_OPTION,
80 PRESERVE_ATTRIBUTES_OPTION,
81 REFLINK_OPTION,
82 SPARSE_OPTION,
83 STRIP_TRAILING_SLASHES_OPTION,
84 UNLINK_DEST_BEFORE_OPENING
87 /* True if the kernel is SELinux enabled. */
88 static bool selinux_enabled;
90 /* If true, the command "cp x/e_file e_dir" uses "e_dir/x/e_file"
91 as its destination instead of the usual "e_dir/e_file." */
92 static bool parents_option = false;
94 /* Remove any trailing slashes from each SOURCE argument. */
95 static bool remove_trailing_slashes;
97 static char const *const sparse_type_string[] =
99 "never", "auto", "always", NULL
101 static enum Sparse_type const sparse_type[] =
103 SPARSE_NEVER, SPARSE_AUTO, SPARSE_ALWAYS
105 ARGMATCH_VERIFY (sparse_type_string, sparse_type);
107 static char const *const reflink_type_string[] =
109 "auto", "always", NULL
111 static enum Reflink_type const reflink_type[] =
113 REFLINK_AUTO, REFLINK_ALWAYS
115 ARGMATCH_VERIFY (reflink_type_string, reflink_type);
117 static struct option const long_opts[] =
119 {"archive", no_argument, NULL, 'a'},
120 {"attributes-only", no_argument, NULL, ATTRIBUTES_ONLY_OPTION},
121 {"backup", optional_argument, NULL, 'b'},
122 {"copy-contents", no_argument, NULL, COPY_CONTENTS_OPTION},
123 {"dereference", no_argument, NULL, 'L'},
124 {"force", no_argument, NULL, 'f'},
125 {"interactive", no_argument, NULL, 'i'},
126 {"link", no_argument, NULL, 'l'},
127 {"no-clobber", no_argument, NULL, 'n'},
128 {"no-dereference", no_argument, NULL, 'P'},
129 {"no-preserve", required_argument, NULL, NO_PRESERVE_ATTRIBUTES_OPTION},
130 {"no-target-directory", no_argument, NULL, 'T'},
131 {"one-file-system", no_argument, NULL, 'x'},
132 {"parents", no_argument, NULL, PARENTS_OPTION},
133 {"path", no_argument, NULL, PARENTS_OPTION}, /* Deprecated. */
134 {"preserve", optional_argument, NULL, PRESERVE_ATTRIBUTES_OPTION},
135 {"recursive", no_argument, NULL, 'R'},
136 {"remove-destination", no_argument, NULL, UNLINK_DEST_BEFORE_OPENING},
137 {"sparse", required_argument, NULL, SPARSE_OPTION},
138 {"reflink", optional_argument, NULL, REFLINK_OPTION},
139 {"strip-trailing-slashes", no_argument, NULL, STRIP_TRAILING_SLASHES_OPTION},
140 {"suffix", required_argument, NULL, 'S'},
141 {"symbolic-link", no_argument, NULL, 's'},
142 {"target-directory", required_argument, NULL, 't'},
143 {"update", no_argument, NULL, 'u'},
144 {"verbose", no_argument, NULL, 'v'},
145 {GETOPT_SELINUX_CONTEXT_OPTION_DECL},
146 {GETOPT_HELP_OPTION_DECL},
147 {GETOPT_VERSION_OPTION_DECL},
148 {NULL, 0, NULL, 0}
151 void
152 usage (int status)
154 if (status != EXIT_SUCCESS)
155 emit_try_help ();
156 else
158 printf (_("\
159 Usage: %s [OPTION]... [-T] SOURCE DEST\n\
160 or: %s [OPTION]... SOURCE... DIRECTORY\n\
161 or: %s [OPTION]... -t DIRECTORY SOURCE...\n\
163 program_name, program_name, program_name);
164 fputs (_("\
165 Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.\n\
166 "), stdout);
168 emit_mandatory_arg_note ();
170 fputs (_("\
171 -a, --archive same as -dR --preserve=all\n\
172 --attributes-only don't copy the file data, just the attributes\n\
173 --backup[=CONTROL] make a backup of each existing destination file\
175 -b like --backup but does not accept an argument\n\
176 --copy-contents copy contents of special files when recursive\n\
177 -d same as --no-dereference --preserve=links\n\
178 "), stdout);
179 fputs (_("\
180 -f, --force if an existing destination file cannot be\n\
181 opened, remove it and try again (this option\n\
182 is ignored when the -n option is also used)\n\
183 -i, --interactive prompt before overwrite (overrides a previous -n\
185 option)\n\
186 -H follow command-line symbolic links in SOURCE\n\
187 "), stdout);
188 fputs (_("\
189 -l, --link hard link files instead of copying\n\
190 -L, --dereference always follow symbolic links in SOURCE\n\
191 "), stdout);
192 fputs (_("\
193 -n, --no-clobber do not overwrite an existing file (overrides\n\
194 a previous -i option)\n\
195 -P, --no-dereference never follow symbolic links in SOURCE\n\
196 "), stdout);
197 fputs (_("\
198 -p same as --preserve=mode,ownership,timestamps\n\
199 --preserve[=ATTR_LIST] preserve the specified attributes (default:\n\
200 mode,ownership,timestamps), if possible\n\
201 additional attributes: context, links, xattr,\
203 all\n\
204 "), stdout);
205 fputs (_("\
206 --no-preserve=ATTR_LIST don't preserve the specified attributes\n\
207 --parents use full source file name under DIRECTORY\n\
208 "), stdout);
209 fputs (_("\
210 -R, -r, --recursive copy directories recursively\n\
211 --reflink[=WHEN] control clone/CoW copies. See below\n\
212 --remove-destination remove each existing destination file before\n\
213 attempting to open it (contrast with --force)\
214 \n"), stdout);
215 fputs (_("\
216 --sparse=WHEN control creation of sparse files. See below\n\
217 --strip-trailing-slashes remove any trailing slashes from each SOURCE\n\
218 argument\n\
219 "), stdout);
220 fputs (_("\
221 -s, --symbolic-link make symbolic links instead of copying\n\
222 -S, --suffix=SUFFIX override the usual backup suffix\n\
223 -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY\n\
224 -T, --no-target-directory treat DEST as a normal file\n\
225 "), stdout);
226 fputs (_("\
227 -u, --update copy only when the SOURCE file is newer\n\
228 than the destination file or when the\n\
229 destination file is missing\n\
230 -v, --verbose explain what is being done\n\
231 -x, --one-file-system stay on this file system\n\
232 "), stdout);
233 fputs (_("\
234 -Z set SELinux security context of destination\n\
235 file to default type\n\
236 --context[=CTX] like -Z, or if CTX is specified then set the\n\
237 SELinux or SMACK security context to CTX\n\
238 "), stdout);
239 fputs (HELP_OPTION_DESCRIPTION, stdout);
240 fputs (VERSION_OPTION_DESCRIPTION, stdout);
241 fputs (_("\
243 By default, sparse SOURCE files are detected by a crude heuristic and the\n\
244 corresponding DEST file is made sparse as well. That is the behavior\n\
245 selected by --sparse=auto. Specify --sparse=always to create a sparse DEST\n\
246 file whenever the SOURCE file contains a long enough sequence of zero bytes.\n\
247 Use --sparse=never to inhibit creation of sparse files.\n\
249 When --reflink[=always] is specified, perform a lightweight copy, where the\n\
250 data blocks are copied only when modified. If this is not possible the copy\n\
251 fails, or if --reflink=auto is specified, fall back to a standard copy.\n\
252 "), stdout);
253 emit_backup_suffix_note ();
254 fputs (_("\
256 As a special case, cp makes a backup of SOURCE when the force and backup\n\
257 options are given and SOURCE and DEST are the same name for an existing,\n\
258 regular file.\n\
259 "), stdout);
260 emit_ancillary_info (PROGRAM_NAME);
262 exit (status);
265 /* Ensure that the parent directories of CONST_DST_NAME have the
266 correct protections, for the --parents option. This is done
267 after all copying has been completed, to allow permissions
268 that don't include user write/execute.
270 SRC_OFFSET is the index in CONST_DST_NAME of the beginning of the
271 source directory name.
273 ATTR_LIST is a null-terminated linked list of structures that
274 indicates the end of the filename of each intermediate directory
275 in CONST_DST_NAME that may need to have its attributes changed.
276 The command 'cp --parents --preserve a/b/c d/e_dir' changes the
277 attributes of the directories d/e_dir/a and d/e_dir/a/b to match
278 the corresponding source directories regardless of whether they
279 existed before the 'cp' command was given.
281 Return true if the parent of CONST_DST_NAME and any intermediate
282 directories specified by ATTR_LIST have the proper permissions
283 when done. */
285 static bool
286 re_protect (char const *const_dst_name, size_t src_offset,
287 struct dir_attr *attr_list, const struct cp_options *x)
289 struct dir_attr *p;
290 char *dst_name; /* A copy of CONST_DST_NAME we can change. */
291 char *src_name; /* The source name in 'dst_name'. */
293 ASSIGN_STRDUPA (dst_name, const_dst_name);
294 src_name = dst_name + src_offset;
296 for (p = attr_list; p; p = p->next)
298 dst_name[p->slash_offset] = '\0';
300 /* Adjust the times (and if possible, ownership) for the copy.
301 chown turns off set[ug]id bits for non-root,
302 so do the chmod last. */
304 if (x->preserve_timestamps)
306 struct timespec timespec[2];
308 timespec[0] = get_stat_atime (&p->st);
309 timespec[1] = get_stat_mtime (&p->st);
311 if (utimens (dst_name, timespec))
313 error (0, errno, _("failed to preserve times for %s"),
314 quoteaf (dst_name));
315 return false;
319 if (x->preserve_ownership)
321 if (lchown (dst_name, p->st.st_uid, p->st.st_gid) != 0)
323 if (! chown_failure_ok (x))
325 error (0, errno, _("failed to preserve ownership for %s"),
326 quoteaf (dst_name));
327 return false;
329 /* Failing to preserve ownership is OK. Still, try to preserve
330 the group, but ignore the possible error. */
331 ignore_value (lchown (dst_name, -1, p->st.st_gid));
335 if (x->preserve_mode)
337 if (copy_acl (src_name, -1, dst_name, -1, p->st.st_mode) != 0)
338 return false;
340 else if (p->restore_mode)
342 if (lchmod (dst_name, p->st.st_mode) != 0)
344 error (0, errno, _("failed to preserve permissions for %s"),
345 quoteaf (dst_name));
346 return false;
350 dst_name[p->slash_offset] = '/';
352 return true;
355 /* Ensure that the parent directory of CONST_DIR exists, for
356 the --parents option.
358 SRC_OFFSET is the index in CONST_DIR (which is a destination
359 directory) of the beginning of the source directory name.
360 Create any leading directories that don't already exist.
361 If VERBOSE_FMT_STRING is nonzero, use it as a printf format
362 string for printing a message after successfully making a directory.
363 The format should take two string arguments: the names of the
364 source and destination directories.
365 Creates a linked list of attributes of intermediate directories,
366 *ATTR_LIST, for re_protect to use after calling copy.
367 Sets *NEW_DST if this function creates parent of CONST_DIR.
369 Return true if parent of CONST_DIR exists as a directory with the proper
370 permissions when done. */
372 /* FIXME: Synch this function with the one in ../lib/mkdir-p.c. */
374 static bool
375 make_dir_parents_private (char const *const_dir, size_t src_offset,
376 char const *verbose_fmt_string,
377 struct dir_attr **attr_list, bool *new_dst,
378 const struct cp_options *x)
380 struct stat stats;
381 char *dir; /* A copy of CONST_DIR we can change. */
382 char *src; /* Source name in DIR. */
383 char *dst_dir; /* Leading directory of DIR. */
384 size_t dirlen; /* Length of DIR. */
386 ASSIGN_STRDUPA (dir, const_dir);
388 src = dir + src_offset;
390 dirlen = dir_len (dir);
391 dst_dir = alloca (dirlen + 1);
392 memcpy (dst_dir, dir, dirlen);
393 dst_dir[dirlen] = '\0';
395 *attr_list = NULL;
397 /* XXX: If all dirs are present at the destination,
398 no permissions or security contexts will be updated. */
399 if (stat (dst_dir, &stats) != 0)
401 /* A parent of CONST_DIR does not exist.
402 Make all missing intermediate directories. */
403 char *slash;
405 slash = src;
406 while (*slash == '/')
407 slash++;
408 while ((slash = strchr (slash, '/')))
410 struct dir_attr *new IF_LINT ( = NULL);
411 bool missing_dir;
413 *slash = '\0';
414 missing_dir = (stat (dir, &stats) != 0);
416 if (missing_dir || x->preserve_ownership || x->preserve_mode
417 || x->preserve_timestamps)
419 /* Add this directory to the list of directories whose
420 modes might need fixing later. */
421 struct stat src_st;
422 int src_errno = (stat (src, &src_st) != 0
423 ? errno
424 : S_ISDIR (src_st.st_mode)
426 : ENOTDIR);
427 if (src_errno)
429 error (0, src_errno, _("failed to get attributes of %s"),
430 quoteaf (src));
431 return false;
434 new = xmalloc (sizeof *new);
435 new->st = src_st;
436 new->slash_offset = slash - dir;
437 new->restore_mode = false;
438 new->next = *attr_list;
439 *attr_list = new;
442 /* If required set the default context for created dirs. */
443 if (! set_process_security_ctx (src, dir,
444 missing_dir ? new->st.st_mode : 0,
445 missing_dir, x))
446 return false;
448 if (missing_dir)
450 mode_t src_mode;
451 mode_t omitted_permissions;
452 mode_t mkdir_mode;
454 /* This component does not exist. We must set
455 *new_dst and new->st.st_mode inside this loop because,
456 for example, in the command 'cp --parents ../a/../b/c e_dir',
457 make_dir_parents_private creates only e_dir/../a if
458 ./b already exists. */
459 *new_dst = true;
460 src_mode = new->st.st_mode;
462 /* If the ownership or special mode bits might change,
463 omit some permissions at first, so unauthorized users
464 cannot nip in before the file is ready. */
465 omitted_permissions = (src_mode
466 & (x->preserve_ownership
467 ? S_IRWXG | S_IRWXO
468 : x->preserve_mode
469 ? S_IWGRP | S_IWOTH
470 : 0));
472 /* POSIX says mkdir's behavior is implementation-defined when
473 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
474 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
475 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
476 mkdir_mode = x->explicit_no_preserve_mode ? S_IRWXUGO : src_mode;
477 mkdir_mode &= CHMOD_MODE_BITS & ~omitted_permissions;
478 if (mkdir (dir, mkdir_mode) != 0)
480 error (0, errno, _("cannot make directory %s"),
481 quoteaf (dir));
482 return false;
484 else
486 if (verbose_fmt_string != NULL)
487 printf (verbose_fmt_string, src, dir);
490 /* We need search and write permissions to the new directory
491 for writing the directory's contents. Check if these
492 permissions are there. */
494 if (lstat (dir, &stats))
496 error (0, errno, _("failed to get attributes of %s"),
497 quoteaf (dir));
498 return false;
502 if (! x->preserve_mode)
504 if (omitted_permissions & ~stats.st_mode)
505 omitted_permissions &= ~ cached_umask ();
506 if (omitted_permissions & ~stats.st_mode
507 || (stats.st_mode & S_IRWXU) != S_IRWXU)
509 new->st.st_mode = stats.st_mode | omitted_permissions;
510 new->restore_mode = true;
514 if ((stats.st_mode & S_IRWXU) != S_IRWXU)
516 /* Make the new directory searchable and writable.
517 The original permissions will be restored later. */
519 if (lchmod (dir, stats.st_mode | S_IRWXU) != 0)
521 error (0, errno, _("setting permissions for %s"),
522 quoteaf (dir));
523 return false;
527 else if (!S_ISDIR (stats.st_mode))
529 error (0, 0, _("%s exists but is not a directory"),
530 quoteaf (dir));
531 return false;
533 else
534 *new_dst = false;
536 /* For existing dirs, set the security context as per that already
537 set for the process global context. */
538 if (! *new_dst
539 && (x->set_security_context || x->preserve_security_context))
541 if (! set_file_security_ctx (dir, x->preserve_security_context,
542 false, x)
543 && x->require_preserve_context)
544 return false;
547 *slash++ = '/';
549 /* Avoid unnecessary calls to 'stat' when given
550 file names containing multiple adjacent slashes. */
551 while (*slash == '/')
552 slash++;
556 /* We get here if the parent of DIR already exists. */
558 else if (!S_ISDIR (stats.st_mode))
560 error (0, 0, _("%s exists but is not a directory"), quoteaf (dst_dir));
561 return false;
563 else
565 *new_dst = false;
567 return true;
570 /* FILE is the last operand of this command.
571 Return true if FILE is a directory.
572 But report an error and exit if there is a problem accessing FILE,
573 or if FILE does not exist but would have to refer to an existing
574 directory if it referred to anything at all.
576 If the file exists, store the file's status into *ST.
577 Otherwise, set *NEW_DST. */
579 static bool
580 target_directory_operand (char const *file, struct stat *st, bool *new_dst)
582 int err = (stat (file, st) == 0 ? 0 : errno);
583 bool is_a_dir = !err && S_ISDIR (st->st_mode);
584 if (err)
586 if (err != ENOENT)
587 die (EXIT_FAILURE, err, _("failed to access %s"), quoteaf (file));
588 *new_dst = true;
590 return is_a_dir;
593 /* Scan the arguments, and copy each by calling copy.
594 Return true if successful. */
596 static bool
597 do_copy (int n_files, char **file, const char *target_directory,
598 bool no_target_directory, struct cp_options *x)
600 struct stat sb;
601 bool new_dst = false;
602 bool ok = true;
604 if (n_files <= !target_directory)
606 if (n_files <= 0)
607 error (0, 0, _("missing file operand"));
608 else
609 error (0, 0, _("missing destination file operand after %s"),
610 quoteaf (file[0]));
611 usage (EXIT_FAILURE);
614 if (no_target_directory)
616 if (target_directory)
617 die (EXIT_FAILURE, 0,
618 _("cannot combine --target-directory (-t) "
619 "and --no-target-directory (-T)"));
620 if (2 < n_files)
622 error (0, 0, _("extra operand %s"), quoteaf (file[2]));
623 usage (EXIT_FAILURE);
625 /* Update NEW_DST and SB, which may be checked below. */
626 ignore_value (target_directory_operand (file[n_files -1], &sb, &new_dst));
628 else if (!target_directory)
630 if (2 <= n_files
631 && target_directory_operand (file[n_files - 1], &sb, &new_dst))
632 target_directory = file[--n_files];
633 else if (2 < n_files)
634 die (EXIT_FAILURE, 0, _("target %s is not a directory"),
635 quoteaf (file[n_files - 1]));
638 if (target_directory)
640 /* cp file1...filen edir
641 Copy the files 'file1' through 'filen'
642 to the existing directory 'edir'. */
644 /* Initialize these hash tables only if we'll need them.
645 The problems they're used to detect can arise only if
646 there are two or more files to copy. */
647 if (2 <= n_files)
649 dest_info_init (x);
650 src_info_init (x);
653 for (int i = 0; i < n_files; i++)
655 char *dst_name;
656 bool parent_exists = true; /* True if dir_name (dst_name) exists. */
657 struct dir_attr *attr_list;
658 char *arg_in_concat = NULL;
659 char *arg = file[i];
661 /* Trailing slashes are meaningful (i.e., maybe worth preserving)
662 only in the source file names. */
663 if (remove_trailing_slashes)
664 strip_trailing_slashes (arg);
666 if (parents_option)
668 char *arg_no_trailing_slash;
670 /* Use 'arg' without trailing slashes in constructing destination
671 file names. Otherwise, we can end up trying to create a
672 directory via 'mkdir ("dst/foo/"...', which is not portable.
673 It fails, due to the trailing slash, on at least
674 NetBSD 1.[34] systems. */
675 ASSIGN_STRDUPA (arg_no_trailing_slash, arg);
676 strip_trailing_slashes (arg_no_trailing_slash);
678 /* Append all of 'arg' (minus any trailing slash) to 'dest'. */
679 dst_name = file_name_concat (target_directory,
680 arg_no_trailing_slash,
681 &arg_in_concat);
683 /* For --parents, we have to make sure that the directory
684 dir_name (dst_name) exists. We may have to create a few
685 leading directories. */
686 parent_exists =
687 (make_dir_parents_private
688 (dst_name, arg_in_concat - dst_name,
689 (x->verbose ? "%s -> %s\n" : NULL),
690 &attr_list, &new_dst, x));
692 else
694 char *arg_base;
695 /* Append the last component of 'arg' to 'target_directory'. */
697 ASSIGN_BASENAME_STRDUPA (arg_base, arg);
698 /* For 'cp -R source/.. dest', don't copy into 'dest/..'. */
699 dst_name = (STREQ (arg_base, "..")
700 ? xstrdup (target_directory)
701 : file_name_concat (target_directory, arg_base,
702 NULL));
705 if (!parent_exists)
707 /* make_dir_parents_private failed, so don't even
708 attempt the copy. */
709 ok = false;
711 else
713 bool copy_into_self;
714 ok &= copy (arg, dst_name, new_dst, x, &copy_into_self, NULL);
716 if (parents_option)
717 ok &= re_protect (dst_name, arg_in_concat - dst_name,
718 attr_list, x);
721 if (parents_option)
723 while (attr_list)
725 struct dir_attr *p = attr_list;
726 attr_list = attr_list->next;
727 free (p);
731 free (dst_name);
734 else /* !target_directory */
736 char const *new_dest;
737 char const *source = file[0];
738 char const *dest = file[1];
739 bool unused;
741 if (parents_option)
743 error (0, 0,
744 _("with --parents, the destination must be a directory"));
745 usage (EXIT_FAILURE);
748 /* When the force and backup options have been specified and
749 the source and destination are the same name for an existing
750 regular file, convert the user's command, e.g.,
751 'cp --force --backup foo foo' to 'cp --force foo fooSUFFIX'
752 where SUFFIX is determined by any version control options used. */
754 if (x->unlink_dest_after_failed_open
755 && x->backup_type != no_backups
756 && STREQ (source, dest)
757 && !new_dst && S_ISREG (sb.st_mode))
759 static struct cp_options x_tmp;
761 new_dest = find_backup_file_name (dest, x->backup_type);
762 /* Set x->backup_type to 'no_backups' so that the normal backup
763 mechanism is not used when performing the actual copy.
764 backup_type must be set to 'no_backups' only *after* the above
765 call to find_backup_file_name -- that function uses
766 backup_type to determine the suffix it applies. */
767 x_tmp = *x;
768 x_tmp.backup_type = no_backups;
769 x = &x_tmp;
771 else
773 new_dest = dest;
776 ok = copy (source, new_dest, 0, x, &unused, NULL);
779 return ok;
782 static void
783 cp_option_init (struct cp_options *x)
785 cp_options_default (x);
786 x->copy_as_regular = true;
787 x->dereference = DEREF_UNDEFINED;
788 x->unlink_dest_before_opening = false;
789 x->unlink_dest_after_failed_open = false;
790 x->hard_link = false;
791 x->interactive = I_UNSPECIFIED;
792 x->move_mode = false;
793 x->install_mode = false;
794 x->one_file_system = false;
795 x->reflink_mode = REFLINK_NEVER;
797 x->preserve_ownership = false;
798 x->preserve_links = false;
799 x->preserve_mode = false;
800 x->preserve_timestamps = false;
801 x->explicit_no_preserve_mode = false;
802 x->preserve_security_context = false; /* -a or --preserve=context. */
803 x->require_preserve_context = false; /* --preserve=context. */
804 x->set_security_context = false; /* -Z, set sys default context. */
805 x->preserve_xattr = false;
806 x->reduce_diagnostics = false;
807 x->require_preserve_xattr = false;
809 x->data_copy_required = true;
810 x->require_preserve = false;
811 x->recursive = false;
812 x->sparse_mode = SPARSE_AUTO;
813 x->symbolic_link = false;
814 x->set_mode = false;
815 x->mode = 0;
817 /* Not used. */
818 x->stdin_tty = false;
820 x->update = false;
821 x->verbose = false;
823 /* By default, refuse to open a dangling destination symlink, because
824 in general one cannot do that safely, give the current semantics of
825 open's O_EXCL flag, (which POSIX doesn't even allow cp to use, btw).
826 But POSIX requires it. */
827 x->open_dangling_dest_symlink = getenv ("POSIXLY_CORRECT") != NULL;
829 x->dest_info = NULL;
830 x->src_info = NULL;
833 /* Given a string, ARG, containing a comma-separated list of arguments
834 to the --preserve option, set the appropriate fields of X to ON_OFF. */
835 static void
836 decode_preserve_arg (char const *arg, struct cp_options *x, bool on_off)
838 enum File_attribute
840 PRESERVE_MODE,
841 PRESERVE_TIMESTAMPS,
842 PRESERVE_OWNERSHIP,
843 PRESERVE_LINK,
844 PRESERVE_CONTEXT,
845 PRESERVE_XATTR,
846 PRESERVE_ALL
848 static enum File_attribute const preserve_vals[] =
850 PRESERVE_MODE, PRESERVE_TIMESTAMPS,
851 PRESERVE_OWNERSHIP, PRESERVE_LINK, PRESERVE_CONTEXT, PRESERVE_XATTR,
852 PRESERVE_ALL
854 /* Valid arguments to the '--preserve' option. */
855 static char const* const preserve_args[] =
857 "mode", "timestamps",
858 "ownership", "links", "context", "xattr", "all", NULL
860 ARGMATCH_VERIFY (preserve_args, preserve_vals);
862 char *arg_writable = xstrdup (arg);
863 char *s = arg_writable;
866 /* find next comma */
867 char *comma = strchr (s, ',');
868 enum File_attribute val;
870 /* If we found a comma, put a NUL in its place and advance. */
871 if (comma)
872 *comma++ = 0;
874 /* process S. */
875 val = XARGMATCH (on_off ? "--preserve" : "--no-preserve",
876 s, preserve_args, preserve_vals);
877 switch (val)
879 case PRESERVE_MODE:
880 x->preserve_mode = on_off;
881 x->explicit_no_preserve_mode = !on_off;
882 break;
884 case PRESERVE_TIMESTAMPS:
885 x->preserve_timestamps = on_off;
886 break;
888 case PRESERVE_OWNERSHIP:
889 x->preserve_ownership = on_off;
890 break;
892 case PRESERVE_LINK:
893 x->preserve_links = on_off;
894 break;
896 case PRESERVE_CONTEXT:
897 x->require_preserve_context = on_off;
898 x->preserve_security_context = on_off;
899 break;
901 case PRESERVE_XATTR:
902 x->preserve_xattr = on_off;
903 x->require_preserve_xattr = on_off;
904 break;
906 case PRESERVE_ALL:
907 x->preserve_mode = on_off;
908 x->preserve_timestamps = on_off;
909 x->preserve_ownership = on_off;
910 x->preserve_links = on_off;
911 x->explicit_no_preserve_mode = !on_off;
912 if (selinux_enabled)
913 x->preserve_security_context = on_off;
914 x->preserve_xattr = on_off;
915 break;
917 default:
918 abort ();
920 s = comma;
922 while (s);
924 free (arg_writable);
928 main (int argc, char **argv)
930 int c;
931 bool ok;
932 bool make_backups = false;
933 char const *backup_suffix = NULL;
934 char *version_control_string = NULL;
935 struct cp_options x;
936 bool copy_contents = false;
937 char *target_directory = NULL;
938 bool no_target_directory = false;
939 char const *scontext = NULL;
941 initialize_main (&argc, &argv);
942 set_program_name (argv[0]);
943 setlocale (LC_ALL, "");
944 bindtextdomain (PACKAGE, LOCALEDIR);
945 textdomain (PACKAGE);
947 atexit (close_stdin);
949 selinux_enabled = (0 < is_selinux_enabled ());
950 cp_option_init (&x);
952 while ((c = getopt_long (argc, argv, "abdfHilLnprst:uvxPRS:TZ",
953 long_opts, NULL))
954 != -1)
956 switch (c)
958 case SPARSE_OPTION:
959 x.sparse_mode = XARGMATCH ("--sparse", optarg,
960 sparse_type_string, sparse_type);
961 break;
963 case REFLINK_OPTION:
964 if (optarg == NULL)
965 x.reflink_mode = REFLINK_ALWAYS;
966 else
967 x.reflink_mode = XARGMATCH ("--reflink", optarg,
968 reflink_type_string, reflink_type);
969 break;
971 case 'a':
972 /* Like -dR --preserve=all with reduced failure diagnostics. */
973 x.dereference = DEREF_NEVER;
974 x.preserve_links = true;
975 x.preserve_ownership = true;
976 x.preserve_mode = true;
977 x.preserve_timestamps = true;
978 x.require_preserve = true;
979 if (selinux_enabled)
980 x.preserve_security_context = true;
981 x.preserve_xattr = true;
982 x.reduce_diagnostics = true;
983 x.recursive = true;
984 break;
986 case 'b':
987 make_backups = true;
988 if (optarg)
989 version_control_string = optarg;
990 break;
992 case ATTRIBUTES_ONLY_OPTION:
993 x.data_copy_required = false;
994 break;
996 case COPY_CONTENTS_OPTION:
997 copy_contents = true;
998 break;
1000 case 'd':
1001 x.preserve_links = true;
1002 x.dereference = DEREF_NEVER;
1003 break;
1005 case 'f':
1006 x.unlink_dest_after_failed_open = true;
1007 break;
1009 case 'H':
1010 x.dereference = DEREF_COMMAND_LINE_ARGUMENTS;
1011 break;
1013 case 'i':
1014 x.interactive = I_ASK_USER;
1015 break;
1017 case 'l':
1018 x.hard_link = true;
1019 break;
1021 case 'L':
1022 x.dereference = DEREF_ALWAYS;
1023 break;
1025 case 'n':
1026 x.interactive = I_ALWAYS_NO;
1027 break;
1029 case 'P':
1030 x.dereference = DEREF_NEVER;
1031 break;
1033 case NO_PRESERVE_ATTRIBUTES_OPTION:
1034 decode_preserve_arg (optarg, &x, false);
1035 break;
1037 case PRESERVE_ATTRIBUTES_OPTION:
1038 if (optarg == NULL)
1040 /* Fall through to the case for 'p' below. */
1042 else
1044 decode_preserve_arg (optarg, &x, true);
1045 x.require_preserve = true;
1046 break;
1048 FALLTHROUGH;
1050 case 'p':
1051 x.preserve_ownership = true;
1052 x.preserve_mode = true;
1053 x.preserve_timestamps = true;
1054 x.require_preserve = true;
1055 break;
1057 case PARENTS_OPTION:
1058 parents_option = true;
1059 break;
1061 case 'r':
1062 case 'R':
1063 x.recursive = true;
1064 break;
1066 case UNLINK_DEST_BEFORE_OPENING:
1067 x.unlink_dest_before_opening = true;
1068 break;
1070 case STRIP_TRAILING_SLASHES_OPTION:
1071 remove_trailing_slashes = true;
1072 break;
1074 case 's':
1075 x.symbolic_link = true;
1076 break;
1078 case 't':
1079 if (target_directory)
1080 die (EXIT_FAILURE, 0,
1081 _("multiple target directories specified"));
1082 else
1084 struct stat st;
1085 if (stat (optarg, &st) != 0)
1086 die (EXIT_FAILURE, errno, _("failed to access %s"),
1087 quoteaf (optarg));
1088 if (! S_ISDIR (st.st_mode))
1089 die (EXIT_FAILURE, 0, _("target %s is not a directory"),
1090 quoteaf (optarg));
1092 target_directory = optarg;
1093 break;
1095 case 'T':
1096 no_target_directory = true;
1097 break;
1099 case 'u':
1100 x.update = true;
1101 break;
1103 case 'v':
1104 x.verbose = true;
1105 break;
1107 case 'x':
1108 x.one_file_system = true;
1109 break;
1111 case 'Z':
1112 /* politely decline if we're not on a selinux-enabled kernel. */
1113 if (selinux_enabled)
1115 if (optarg)
1116 scontext = optarg;
1117 else
1118 x.set_security_context = true;
1120 else if (optarg)
1122 error (0, 0,
1123 _("warning: ignoring --context; "
1124 "it requires an SELinux-enabled kernel"));
1126 break;
1128 case 'S':
1129 make_backups = true;
1130 backup_suffix = optarg;
1131 break;
1133 case_GETOPT_HELP_CHAR;
1135 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1137 default:
1138 usage (EXIT_FAILURE);
1142 if (x.hard_link && x.symbolic_link)
1144 error (0, 0, _("cannot make both hard and symbolic links"));
1145 usage (EXIT_FAILURE);
1148 if (make_backups && x.interactive == I_ALWAYS_NO)
1150 error (0, 0,
1151 _("options --backup and --no-clobber are mutually exclusive"));
1152 usage (EXIT_FAILURE);
1155 if (x.reflink_mode == REFLINK_ALWAYS && x.sparse_mode != SPARSE_AUTO)
1157 error (0, 0, _("--reflink can be used only with --sparse=auto"));
1158 usage (EXIT_FAILURE);
1161 x.backup_type = (make_backups
1162 ? xget_version (_("backup type"),
1163 version_control_string)
1164 : no_backups);
1165 set_simple_backup_suffix (backup_suffix);
1167 if (x.dereference == DEREF_UNDEFINED)
1169 if (x.recursive && ! x.hard_link)
1170 /* This is compatible with FreeBSD. */
1171 x.dereference = DEREF_NEVER;
1172 else
1173 x.dereference = DEREF_ALWAYS;
1176 if (x.recursive)
1177 x.copy_as_regular = copy_contents;
1179 /* Ensure -Z overrides -a. */
1180 if ((x.set_security_context || scontext)
1181 && ! x.require_preserve_context)
1182 x.preserve_security_context = false;
1184 if (x.preserve_security_context && (x.set_security_context || scontext))
1185 die (EXIT_FAILURE, 0,
1186 _("cannot set target context and preserve it"));
1188 if (x.require_preserve_context && ! selinux_enabled)
1189 die (EXIT_FAILURE, 0,
1190 _("cannot preserve security context "
1191 "without an SELinux-enabled kernel"));
1193 /* FIXME: This handles new files. But what about existing files?
1194 I.e., if updating a tree, new files would have the specified context,
1195 but shouldn't existing files be updated for consistency like this?
1196 if (scontext)
1197 restorecon (dst_path, 0, true);
1199 if (scontext && setfscreatecon (se_const (scontext)) < 0)
1200 die (EXIT_FAILURE, errno,
1201 _("failed to set default file creation context to %s"),
1202 quote (scontext));
1204 #if !USE_XATTR
1205 if (x.require_preserve_xattr)
1206 die (EXIT_FAILURE, 0, _("cannot preserve extended attributes, cp is "
1207 "built without xattr support"));
1208 #endif
1210 /* Allocate space for remembering copied and created files. */
1212 hash_init ();
1214 ok = do_copy (argc - optind, argv + optind,
1215 target_directory, no_target_directory, &x);
1217 #ifdef lint
1218 forget_all ();
1219 #endif
1221 return ok ? EXIT_SUCCESS : EXIT_FAILURE;