1 /* cp.c -- file copying (main routines)
2 Copyright (C) 1989-2023 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 Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. */
21 #include <sys/types.h>
23 #include <selinux/label.h>
27 #include "backupfile.h"
32 #include "filenamecat.h"
33 #include "ignore-value.h"
35 #include "stat-time.h"
36 #include "targetdir.h"
40 /* The official name of this program (e.g., no 'g' prefix). */
41 #define PROGRAM_NAME "cp"
44 proper_name ("Torbjorn Granlund"), \
45 proper_name ("David MacKenzie"), \
46 proper_name ("Jim Meyering")
48 /* Used by do_copy, make_dir_parents_private, and re_protect
49 to keep a list of leading directories whose protections
50 need to be fixed after copying. */
56 struct dir_attr
*next
;
59 /* For long options that have no equivalent short option, use a
60 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
63 ATTRIBUTES_ONLY_OPTION
= CHAR_MAX
+ 1,
65 NO_PRESERVE_ATTRIBUTES_OPTION
,
67 PRESERVE_ATTRIBUTES_OPTION
,
70 STRIP_TRAILING_SLASHES_OPTION
,
71 UNLINK_DEST_BEFORE_OPENING
74 /* True if the kernel is SELinux enabled. */
75 static bool selinux_enabled
;
77 /* If true, the command "cp x/e_file e_dir" uses "e_dir/x/e_file"
78 as its destination instead of the usual "e_dir/e_file." */
79 static bool parents_option
= false;
81 /* Remove any trailing slashes from each SOURCE argument. */
82 static bool remove_trailing_slashes
;
84 static char const *const sparse_type_string
[] =
86 "never", "auto", "always", NULL
88 static enum Sparse_type
const sparse_type
[] =
90 SPARSE_NEVER
, SPARSE_AUTO
, SPARSE_ALWAYS
92 ARGMATCH_VERIFY (sparse_type_string
, sparse_type
);
94 static char const *const reflink_type_string
[] =
96 "auto", "always", "never", NULL
98 static enum Reflink_type
const reflink_type
[] =
100 REFLINK_AUTO
, REFLINK_ALWAYS
, REFLINK_NEVER
102 ARGMATCH_VERIFY (reflink_type_string
, reflink_type
);
104 static struct option
const long_opts
[] =
106 {"archive", no_argument
, NULL
, 'a'},
107 {"attributes-only", no_argument
, NULL
, ATTRIBUTES_ONLY_OPTION
},
108 {"backup", optional_argument
, NULL
, 'b'},
109 {"copy-contents", no_argument
, NULL
, COPY_CONTENTS_OPTION
},
110 {"dereference", no_argument
, NULL
, 'L'},
111 {"force", no_argument
, NULL
, 'f'},
112 {"interactive", no_argument
, NULL
, 'i'},
113 {"link", no_argument
, NULL
, 'l'},
114 {"no-clobber", no_argument
, NULL
, 'n'},
115 {"no-dereference", no_argument
, NULL
, 'P'},
116 {"no-preserve", required_argument
, NULL
, NO_PRESERVE_ATTRIBUTES_OPTION
},
117 {"no-target-directory", no_argument
, NULL
, 'T'},
118 {"one-file-system", no_argument
, NULL
, 'x'},
119 {"parents", no_argument
, NULL
, PARENTS_OPTION
},
120 {"path", no_argument
, NULL
, PARENTS_OPTION
}, /* Deprecated. */
121 {"preserve", optional_argument
, NULL
, PRESERVE_ATTRIBUTES_OPTION
},
122 {"recursive", no_argument
, NULL
, 'R'},
123 {"remove-destination", no_argument
, NULL
, UNLINK_DEST_BEFORE_OPENING
},
124 {"sparse", required_argument
, NULL
, SPARSE_OPTION
},
125 {"reflink", optional_argument
, NULL
, REFLINK_OPTION
},
126 {"strip-trailing-slashes", no_argument
, NULL
, STRIP_TRAILING_SLASHES_OPTION
},
127 {"suffix", required_argument
, NULL
, 'S'},
128 {"symbolic-link", no_argument
, NULL
, 's'},
129 {"target-directory", required_argument
, NULL
, 't'},
130 {"update", no_argument
, NULL
, 'u'},
131 {"verbose", no_argument
, NULL
, 'v'},
132 {GETOPT_SELINUX_CONTEXT_OPTION_DECL
},
133 {GETOPT_HELP_OPTION_DECL
},
134 {GETOPT_VERSION_OPTION_DECL
},
141 if (status
!= EXIT_SUCCESS
)
146 Usage: %s [OPTION]... [-T] SOURCE DEST\n\
147 or: %s [OPTION]... SOURCE... DIRECTORY\n\
148 or: %s [OPTION]... -t DIRECTORY SOURCE...\n\
150 program_name
, program_name
, program_name
);
152 Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.\n\
155 emit_mandatory_arg_note ();
158 -a, --archive same as -dR --preserve=all\n\
159 --attributes-only don't copy the file data, just the attributes\n\
160 --backup[=CONTROL] make a backup of each existing destination file\
162 -b like --backup but does not accept an argument\n\
163 --copy-contents copy contents of special files when recursive\n\
164 -d same as --no-dereference --preserve=links\n\
167 -f, --force if an existing destination file cannot be\n\
168 opened, remove it and try again (this option\n\
169 is ignored when the -n option is also used)\n\
170 -i, --interactive prompt before overwrite (overrides a previous -n\
173 -H follow command-line symbolic links in SOURCE\n\
176 -l, --link hard link files instead of copying\n\
177 -L, --dereference always follow symbolic links in SOURCE\n\
180 -n, --no-clobber do not overwrite an existing file (overrides\n\
181 a previous -i option)\n\
182 -P, --no-dereference never follow symbolic links in SOURCE\n\
185 -p same as --preserve=mode,ownership,timestamps\n\
186 --preserve[=ATTR_LIST] preserve the specified attributes\n\
189 --no-preserve=ATTR_LIST don't preserve the specified attributes\n\
190 --parents use full source file name under DIRECTORY\n\
193 -R, -r, --recursive copy directories recursively\n\
194 --reflink[=WHEN] control clone/CoW copies. See below\n\
195 --remove-destination remove each existing destination file before\n\
196 attempting to open it (contrast with --force)\
199 --sparse=WHEN control creation of sparse files. See below\n\
200 --strip-trailing-slashes remove any trailing slashes from each SOURCE\n\
204 -s, --symbolic-link make symbolic links instead of copying\n\
205 -S, --suffix=SUFFIX override the usual backup suffix\n\
206 -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY\n\
207 -T, --no-target-directory treat DEST as a normal file\n\
210 -u, --update copy only when the SOURCE file is newer\n\
211 than the destination file or when the\n\
212 destination file is missing\n\
213 -v, --verbose explain what is being done\n\
214 -x, --one-file-system stay on this file system\n\
217 -Z set SELinux security context of destination\n\
218 file to default type\n\
219 --context[=CTX] like -Z, or if CTX is specified then set the\n\
220 SELinux or SMACK security context to CTX\n\
222 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
223 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
226 ATTR_LIST is a comma-separated list of attributes. Attributes are 'mode' for\n\
227 permissions (including any ACL and xattr permissions), 'ownership' for user\n\
228 and group, 'timestamps' for file timestamps, 'links' for hard links, 'context'\n\
229 for security context, 'xattr' for extended attributes, and 'all' for all\n\
234 By default, sparse SOURCE files are detected by a crude heuristic and the\n\
235 corresponding DEST file is made sparse as well. That is the behavior\n\
236 selected by --sparse=auto. Specify --sparse=always to create a sparse DEST\n\
237 file whenever the SOURCE file contains a long enough sequence of zero bytes.\n\
238 Use --sparse=never to inhibit creation of sparse files.\n\
242 When --reflink[=always] is specified, perform a lightweight copy, where the\n\
243 data blocks are copied only when modified. If this is not possible the copy\n\
244 fails, or if --reflink=auto is specified, fall back to a standard copy.\n\
245 Use --reflink=never to ensure a standard copy is performed.\n\
247 emit_backup_suffix_note ();
250 As a special case, cp makes a backup of SOURCE when the force and backup\n\
251 options are given and SOURCE and DEST are the same name for an existing,\n\
254 emit_ancillary_info (PROGRAM_NAME
);
259 /* Ensure that parents of CONST_DST_NAME aka DST_DIRFD+DST_RELNAME have the
260 correct protections, for the --parents option. This is done
261 after all copying has been completed, to allow permissions
262 that don't include user write/execute.
264 ATTR_LIST is a null-terminated linked list of structures that
265 indicates the end of the filename of each intermediate directory
266 in CONST_DST_NAME that may need to have its attributes changed.
267 The command 'cp --parents --preserve a/b/c d/e_dir' changes the
268 attributes of the directories d/e_dir/a and d/e_dir/a/b to match
269 the corresponding source directories regardless of whether they
270 existed before the 'cp' command was given.
272 Return true if the parent of CONST_DST_NAME and any intermediate
273 directories specified by ATTR_LIST have the proper permissions
277 re_protect (char const *const_dst_name
, int dst_dirfd
, char const *dst_relname
,
278 struct dir_attr
*attr_list
, const struct cp_options
*x
)
281 char *dst_name
; /* A copy of CONST_DST_NAME we can change. */
282 char *src_name
; /* The source name in 'dst_name'. */
284 ASSIGN_STRDUPA (dst_name
, const_dst_name
);
285 src_name
= dst_name
+ (dst_relname
- const_dst_name
);
287 for (p
= attr_list
; p
; p
= p
->next
)
289 dst_name
[p
->slash_offset
] = '\0';
291 /* Adjust the times (and if possible, ownership) for the copy.
292 chown turns off set[ug]id bits for non-root,
293 so do the chmod last. */
295 if (x
->preserve_timestamps
)
297 struct timespec timespec
[2];
299 timespec
[0] = get_stat_atime (&p
->st
);
300 timespec
[1] = get_stat_mtime (&p
->st
);
302 if (utimensat (dst_dirfd
, src_name
, timespec
, 0))
304 error (0, errno
, _("failed to preserve times for %s"),
310 if (x
->preserve_ownership
)
312 if (lchownat (dst_dirfd
, src_name
, p
->st
.st_uid
, p
->st
.st_gid
) != 0)
314 if (! chown_failure_ok (x
))
316 error (0, errno
, _("failed to preserve ownership for %s"),
320 /* Failing to preserve ownership is OK. Still, try to preserve
321 the group, but ignore the possible error. */
322 ignore_value (lchownat (dst_dirfd
, src_name
, -1, p
->st
.st_gid
));
326 if (x
->preserve_mode
)
328 if (copy_acl (src_name
, -1, dst_name
, -1, p
->st
.st_mode
) != 0)
331 else if (p
->restore_mode
)
333 if (lchmodat (dst_dirfd
, src_name
, p
->st
.st_mode
) != 0)
335 error (0, errno
, _("failed to preserve permissions for %s"),
341 dst_name
[p
->slash_offset
] = '/';
346 /* Ensure that the parent directory of CONST_DIR exists, for
347 the --parents option.
349 SRC_OFFSET is the index in CONST_DIR (which is a destination
350 directory) of the beginning of the source directory name.
351 Create any leading directories that don't already exist.
352 DST_DIRFD is a file descriptor for the target directory.
353 If VERBOSE_FMT_STRING is nonzero, use it as a printf format
354 string for printing a message after successfully making a directory.
355 The format should take two string arguments: the names of the
356 source and destination directories.
357 Creates a linked list of attributes of intermediate directories,
358 *ATTR_LIST, for re_protect to use after calling copy.
359 Sets *NEW_DST if this function creates parent of CONST_DIR.
361 Return true if parent of CONST_DIR exists as a directory with the proper
362 permissions when done. */
364 /* FIXME: Synch this function with the one in ../lib/mkdir-p.c. */
367 make_dir_parents_private (char const *const_dir
, size_t src_offset
,
369 char const *verbose_fmt_string
,
370 struct dir_attr
**attr_list
, bool *new_dst
,
371 const struct cp_options
*x
)
374 char *dir
; /* A copy of CONST_DIR we can change. */
375 char *src
; /* Source name in DIR. */
376 char *dst_dir
; /* Leading directory of DIR. */
377 idx_t dirlen
= dir_len (const_dir
);
381 /* Succeed immediately if the parent of CONST_DIR must already exist,
382 as the target directory has already been checked. */
383 if (dirlen
<= src_offset
)
386 ASSIGN_STRDUPA (dir
, const_dir
);
388 src
= dir
+ src_offset
;
390 dst_dir
= alloca (dirlen
+ 1);
391 memcpy (dst_dir
, dir
, dirlen
);
392 dst_dir
[dirlen
] = '\0';
393 char const *dst_reldir
= dst_dir
+ src_offset
;
394 while (*dst_reldir
== '/')
397 /* XXX: If all dirs are present at the destination,
398 no permissions or security contexts will be updated. */
399 if (fstatat (dst_dirfd
, dst_reldir
, &stats
, 0) != 0)
401 /* A parent of CONST_DIR does not exist.
402 Make all missing intermediate directories. */
406 while (*slash
== '/')
410 while ((slash
= strchr (slash
, '/')))
412 struct dir_attr
*new;
416 missing_dir
= fstatat (dst_dirfd
, dst_reldir
, &stats
, 0) != 0;
418 if (missing_dir
|| x
->preserve_ownership
|| x
->preserve_mode
419 || x
->preserve_timestamps
)
421 /* Add this directory to the list of directories whose
422 modes might need fixing later. */
424 int src_errno
= (stat (src
, &src_st
) != 0
426 : S_ISDIR (src_st
.st_mode
)
431 error (0, src_errno
, _("failed to get attributes of %s"),
436 new = xmalloc (sizeof *new);
438 new->slash_offset
= slash
- dir
;
439 new->restore_mode
= false;
440 new->next
= *attr_list
;
444 /* If required set the default context for created dirs. */
445 if (! set_process_security_ctx (src
, dir
,
446 missing_dir
? new->st
.st_mode
: 0,
453 mode_t omitted_permissions
;
456 /* This component does not exist. We must set
457 *new_dst and new->st.st_mode inside this loop because,
458 for example, in the command 'cp --parents ../a/../b/c e_dir',
459 make_dir_parents_private creates only e_dir/../a if
460 ./b already exists. */
462 src_mode
= new->st
.st_mode
;
464 /* If the ownership or special mode bits might change,
465 omit some permissions at first, so unauthorized users
466 cannot nip in before the file is ready. */
467 omitted_permissions
= (src_mode
468 & (x
->preserve_ownership
474 /* POSIX says mkdir's behavior is implementation-defined when
475 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
476 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
477 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
478 mkdir_mode
= x
->explicit_no_preserve_mode
? S_IRWXUGO
: src_mode
;
479 mkdir_mode
&= CHMOD_MODE_BITS
& ~omitted_permissions
;
480 if (mkdirat (dst_dirfd
, dst_reldir
, mkdir_mode
) != 0)
482 error (0, errno
, _("cannot make directory %s"),
488 if (verbose_fmt_string
!= NULL
)
489 printf (verbose_fmt_string
, src
, dir
);
492 /* We need search and write permissions to the new directory
493 for writing the directory's contents. Check if these
494 permissions are there. */
496 if (fstatat (dst_dirfd
, dst_reldir
, &stats
, AT_SYMLINK_NOFOLLOW
))
498 error (0, errno
, _("failed to get attributes of %s"),
504 if (! x
->preserve_mode
)
506 if (omitted_permissions
& ~stats
.st_mode
)
507 omitted_permissions
&= ~ cached_umask ();
508 if (omitted_permissions
& ~stats
.st_mode
509 || (stats
.st_mode
& S_IRWXU
) != S_IRWXU
)
511 new->st
.st_mode
= stats
.st_mode
| omitted_permissions
;
512 new->restore_mode
= true;
516 mode_t accessible
= stats
.st_mode
| S_IRWXU
;
517 if (stats
.st_mode
!= accessible
)
519 /* Make the new directory searchable and writable.
520 The original permissions will be restored later. */
522 if (lchmodat (dst_dirfd
, dst_reldir
, accessible
) != 0)
524 error (0, errno
, _("setting permissions for %s"),
530 else if (!S_ISDIR (stats
.st_mode
))
532 error (0, 0, _("%s exists but is not a directory"),
539 /* For existing dirs, set the security context as per that already
540 set for the process global context. */
542 && (x
->set_security_context
|| x
->preserve_security_context
))
544 if (! set_file_security_ctx (dir
, false, x
)
545 && x
->require_preserve_context
)
551 /* Avoid unnecessary calls to 'stat' when given
552 file names containing multiple adjacent slashes. */
553 while (*slash
== '/')
558 /* We get here if the parent of DIR already exists. */
560 else if (!S_ISDIR (stats
.st_mode
))
562 error (0, 0, _("%s exists but is not a directory"), quoteaf (dst_dir
));
572 /* Scan the arguments, and copy each by calling copy.
573 Return true if successful. */
576 do_copy (int n_files
, char **file
, char const *target_directory
,
577 bool no_target_directory
, struct cp_options
*x
)
580 bool new_dst
= false;
583 if (n_files
<= !target_directory
)
586 error (0, 0, _("missing file operand"));
588 error (0, 0, _("missing destination file operand after %s"),
590 usage (EXIT_FAILURE
);
594 int target_dirfd
= AT_FDCWD
;
595 if (no_target_directory
)
597 if (target_directory
)
598 die (EXIT_FAILURE
, 0,
599 _("cannot combine --target-directory (-t) "
600 "and --no-target-directory (-T)"));
603 error (0, 0, _("extra operand %s"), quoteaf (file
[2]));
604 usage (EXIT_FAILURE
);
607 else if (target_directory
)
609 target_dirfd
= target_directory_operand (target_directory
, &sb
);
610 if (! target_dirfd_valid (target_dirfd
))
611 die (EXIT_FAILURE
, errno
, _("target directory %s"),
612 quoteaf (target_directory
));
616 char const *lastfile
= file
[n_files
- 1];
617 int fd
= target_directory_operand (lastfile
, &sb
);
618 if (target_dirfd_valid (fd
))
621 target_directory
= lastfile
;
630 /* The last operand LASTFILE cannot be opened as a directory.
631 If there are more than two operands, report an error.
633 Also, report an error if LASTFILE is known to be a directory
634 even though it could not be opened, which can happen if
635 opening failed with EACCES on a platform lacking O_PATH.
636 In this case use stat to test whether LASTFILE is a
637 directory, in case opening a non-directory with (O_SEARCH
638 | O_DIRECTORY) failed with EACCES not ENOTDIR. */
640 || (O_PATHSEARCH
== O_SEARCH
&& err
== EACCES
641 && (sb
.st_mode
|| stat (lastfile
, &sb
) == 0)
642 && S_ISDIR (sb
.st_mode
)))
643 die (EXIT_FAILURE
, err
, _("target %s"), quoteaf (lastfile
));
647 if (target_directory
)
649 /* cp file1...filen edir
650 Copy the files 'file1' through 'filen'
651 to the existing directory 'edir'. */
653 /* Initialize these hash tables only if we'll need them.
654 The problems they're used to detect can arise only if
655 there are two or more files to copy. */
662 for (int i
= 0; i
< n_files
; i
++)
665 bool parent_exists
= true; /* True if dir_name (dst_name) exists. */
666 struct dir_attr
*attr_list
;
667 char *arg_in_concat
= NULL
;
670 /* Trailing slashes are meaningful (i.e., maybe worth preserving)
671 only in the source file names. */
672 if (remove_trailing_slashes
)
673 strip_trailing_slashes (arg
);
677 char *arg_no_trailing_slash
;
679 /* Use 'arg' without trailing slashes in constructing destination
680 file names. Otherwise, we can end up trying to create a
681 directory using a name with trailing slash, which fails on
682 NetBSD 1.[34] systems. */
683 ASSIGN_STRDUPA (arg_no_trailing_slash
, arg
);
684 strip_trailing_slashes (arg_no_trailing_slash
);
686 /* Append all of 'arg' (minus any trailing slash) to 'dest'. */
687 dst_name
= file_name_concat (target_directory
,
688 arg_no_trailing_slash
,
691 /* For --parents, we have to make sure that the directory
692 dir_name (dst_name) exists. We may have to create a few
693 leading directories. */
695 (make_dir_parents_private
696 (dst_name
, arg_in_concat
- dst_name
, target_dirfd
,
697 (x
->verbose
? "%s -> %s\n" : NULL
),
698 &attr_list
, &new_dst
, x
));
700 while (*arg_in_concat
== '/')
706 /* Append the last component of 'arg' to 'target_directory'. */
707 ASSIGN_STRDUPA (arg_base
, last_component (arg
));
708 strip_trailing_slashes (arg_base
);
709 /* For 'cp -R source/.. dest', don't copy into 'dest/..'. */
710 arg_base
+= STREQ (arg_base
, "..");
711 dst_name
= file_name_concat (target_directory
, arg_base
,
717 /* make_dir_parents_private failed, so don't even
724 ok
&= copy (arg
, dst_name
, target_dirfd
, arg_in_concat
,
725 new_dst
, x
, ©_into_self
, NULL
);
728 ok
&= re_protect (dst_name
, target_dirfd
, arg_in_concat
,
736 struct dir_attr
*p
= attr_list
;
737 attr_list
= attr_list
->next
;
745 else /* !target_directory */
747 char const *source
= file
[0];
748 char const *dest
= file
[1];
754 _("with --parents, the destination must be a directory"));
755 usage (EXIT_FAILURE
);
758 /* When the force and backup options have been specified and
759 the source and destination are the same name for an existing
760 regular file, convert the user's command, e.g.,
761 'cp --force --backup foo foo' to 'cp --force foo fooSUFFIX'
762 where SUFFIX is determined by any version control options used. */
764 if (x
->unlink_dest_after_failed_open
765 && x
->backup_type
!= no_backups
766 && STREQ (source
, dest
)
768 && (sb
.st_mode
!= 0 || stat (dest
, &sb
) == 0) && S_ISREG (sb
.st_mode
))
770 static struct cp_options x_tmp
;
772 dest
= find_backup_file_name (AT_FDCWD
, dest
, x
->backup_type
);
773 /* Set x->backup_type to 'no_backups' so that the normal backup
774 mechanism is not used when performing the actual copy.
775 backup_type must be set to 'no_backups' only *after* the above
776 call to find_backup_file_name -- that function uses
777 backup_type to determine the suffix it applies. */
779 x_tmp
.backup_type
= no_backups
;
783 ok
= copy (source
, dest
, AT_FDCWD
, dest
, -new_dst
, x
, &unused
, NULL
);
790 cp_option_init (struct cp_options
*x
)
792 cp_options_default (x
);
793 x
->copy_as_regular
= true;
794 x
->dereference
= DEREF_UNDEFINED
;
795 x
->unlink_dest_before_opening
= false;
796 x
->unlink_dest_after_failed_open
= false;
797 x
->hard_link
= false;
798 x
->interactive
= I_UNSPECIFIED
;
799 x
->move_mode
= false;
800 x
->install_mode
= false;
801 x
->one_file_system
= false;
802 x
->reflink_mode
= REFLINK_AUTO
;
804 x
->preserve_ownership
= false;
805 x
->preserve_links
= false;
806 x
->preserve_mode
= false;
807 x
->preserve_timestamps
= false;
808 x
->explicit_no_preserve_mode
= false;
809 x
->preserve_security_context
= false; /* -a or --preserve=context. */
810 x
->require_preserve_context
= false; /* --preserve=context. */
811 x
->set_security_context
= NULL
; /* -Z, set sys default context. */
812 x
->preserve_xattr
= false;
813 x
->reduce_diagnostics
= false;
814 x
->require_preserve_xattr
= false;
816 x
->data_copy_required
= true;
817 x
->require_preserve
= false;
818 x
->recursive
= false;
819 x
->sparse_mode
= SPARSE_AUTO
;
820 x
->symbolic_link
= false;
825 x
->stdin_tty
= false;
830 /* By default, refuse to open a dangling destination symlink, because
831 in general one cannot do that safely, give the current semantics of
832 open's O_EXCL flag, (which POSIX doesn't even allow cp to use, btw).
833 But POSIX requires it. */
834 x
->open_dangling_dest_symlink
= getenv ("POSIXLY_CORRECT") != NULL
;
840 /* Given a string, ARG, containing a comma-separated list of arguments
841 to the --preserve option, set the appropriate fields of X to ON_OFF. */
843 decode_preserve_arg (char const *arg
, struct cp_options
*x
, bool on_off
)
855 static enum File_attribute
const preserve_vals
[] =
857 PRESERVE_MODE
, PRESERVE_TIMESTAMPS
,
858 PRESERVE_OWNERSHIP
, PRESERVE_LINK
, PRESERVE_CONTEXT
, PRESERVE_XATTR
,
861 /* Valid arguments to the '--preserve' option. */
862 static char const *const preserve_args
[] =
864 "mode", "timestamps",
865 "ownership", "links", "context", "xattr", "all", NULL
867 ARGMATCH_VERIFY (preserve_args
, preserve_vals
);
869 char *arg_writable
= xstrdup (arg
);
870 char *s
= arg_writable
;
873 /* find next comma */
874 char *comma
= strchr (s
, ',');
875 enum File_attribute val
;
877 /* If we found a comma, put a NUL in its place and advance. */
882 val
= XARGMATCH (on_off
? "--preserve" : "--no-preserve",
883 s
, preserve_args
, preserve_vals
);
887 x
->preserve_mode
= on_off
;
888 x
->explicit_no_preserve_mode
= !on_off
;
891 case PRESERVE_TIMESTAMPS
:
892 x
->preserve_timestamps
= on_off
;
895 case PRESERVE_OWNERSHIP
:
896 x
->preserve_ownership
= on_off
;
900 x
->preserve_links
= on_off
;
903 case PRESERVE_CONTEXT
:
904 x
->require_preserve_context
= on_off
;
905 x
->preserve_security_context
= on_off
;
909 x
->preserve_xattr
= on_off
;
910 x
->require_preserve_xattr
= on_off
;
914 x
->preserve_mode
= on_off
;
915 x
->preserve_timestamps
= on_off
;
916 x
->preserve_ownership
= on_off
;
917 x
->preserve_links
= on_off
;
918 x
->explicit_no_preserve_mode
= !on_off
;
920 x
->preserve_security_context
= on_off
;
921 x
->preserve_xattr
= on_off
;
935 main (int argc
, char **argv
)
939 bool make_backups
= false;
940 char const *backup_suffix
= NULL
;
941 char *version_control_string
= NULL
;
943 bool copy_contents
= false;
944 char *target_directory
= NULL
;
945 bool no_target_directory
= false;
946 char const *scontext
= NULL
;
948 initialize_main (&argc
, &argv
);
949 set_program_name (argv
[0]);
950 setlocale (LC_ALL
, "");
951 bindtextdomain (PACKAGE
, LOCALEDIR
);
952 textdomain (PACKAGE
);
954 atexit (close_stdin
);
956 selinux_enabled
= (0 < is_selinux_enabled ());
959 while ((c
= getopt_long (argc
, argv
, "abdfHilLnprst:uvxPRS:TZ",
966 x
.sparse_mode
= XARGMATCH ("--sparse", optarg
,
967 sparse_type_string
, sparse_type
);
972 x
.reflink_mode
= REFLINK_ALWAYS
;
974 x
.reflink_mode
= XARGMATCH ("--reflink", optarg
,
975 reflink_type_string
, reflink_type
);
979 /* Like -dR --preserve=all with reduced failure diagnostics. */
980 x
.dereference
= DEREF_NEVER
;
981 x
.preserve_links
= true;
982 x
.preserve_ownership
= true;
983 x
.preserve_mode
= true;
984 x
.preserve_timestamps
= true;
985 x
.require_preserve
= true;
987 x
.preserve_security_context
= true;
988 x
.preserve_xattr
= true;
989 x
.reduce_diagnostics
= true;
996 version_control_string
= optarg
;
999 case ATTRIBUTES_ONLY_OPTION
:
1000 x
.data_copy_required
= false;
1003 case COPY_CONTENTS_OPTION
:
1004 copy_contents
= true;
1008 x
.preserve_links
= true;
1009 x
.dereference
= DEREF_NEVER
;
1013 x
.unlink_dest_after_failed_open
= true;
1017 x
.dereference
= DEREF_COMMAND_LINE_ARGUMENTS
;
1021 x
.interactive
= I_ASK_USER
;
1029 x
.dereference
= DEREF_ALWAYS
;
1033 x
.interactive
= I_ALWAYS_NO
;
1037 x
.dereference
= DEREF_NEVER
;
1040 case NO_PRESERVE_ATTRIBUTES_OPTION
:
1041 decode_preserve_arg (optarg
, &x
, false);
1044 case PRESERVE_ATTRIBUTES_OPTION
:
1047 /* Fall through to the case for 'p' below. */
1051 decode_preserve_arg (optarg
, &x
, true);
1052 x
.require_preserve
= true;
1058 x
.preserve_ownership
= true;
1059 x
.preserve_mode
= true;
1060 x
.preserve_timestamps
= true;
1061 x
.require_preserve
= true;
1064 case PARENTS_OPTION
:
1065 parents_option
= true;
1073 case UNLINK_DEST_BEFORE_OPENING
:
1074 x
.unlink_dest_before_opening
= true;
1077 case STRIP_TRAILING_SLASHES_OPTION
:
1078 remove_trailing_slashes
= true;
1082 x
.symbolic_link
= true;
1086 if (target_directory
)
1087 die (EXIT_FAILURE
, 0,
1088 _("multiple target directories specified"));
1089 target_directory
= optarg
;
1093 no_target_directory
= true;
1105 x
.one_file_system
= true;
1109 /* politely decline if we're not on a selinux-enabled kernel. */
1110 if (selinux_enabled
)
1116 x
.set_security_context
= selabel_open (SELABEL_CTX_FILE
,
1118 if (! x
.set_security_context
)
1119 error (0, errno
, _("warning: ignoring --context"));
1125 _("warning: ignoring --context; "
1126 "it requires an SELinux-enabled kernel"));
1131 make_backups
= true;
1132 backup_suffix
= optarg
;
1135 case_GETOPT_HELP_CHAR
;
1137 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
1140 usage (EXIT_FAILURE
);
1144 if (x
.hard_link
&& x
.symbolic_link
)
1146 error (0, 0, _("cannot make both hard and symbolic links"));
1147 usage (EXIT_FAILURE
);
1150 if (x
.interactive
== I_ALWAYS_NO
)
1153 if (make_backups
&& x
.interactive
== I_ALWAYS_NO
)
1156 _("options --backup and --no-clobber are mutually exclusive"));
1157 usage (EXIT_FAILURE
);
1160 if (x
.reflink_mode
== REFLINK_ALWAYS
&& x
.sparse_mode
!= SPARSE_AUTO
)
1162 error (0, 0, _("--reflink can be used only with --sparse=auto"));
1163 usage (EXIT_FAILURE
);
1166 x
.backup_type
= (make_backups
1167 ? xget_version (_("backup type"),
1168 version_control_string
)
1170 set_simple_backup_suffix (backup_suffix
);
1172 if (x
.dereference
== DEREF_UNDEFINED
)
1174 if (x
.recursive
&& ! x
.hard_link
)
1175 /* This is compatible with FreeBSD. */
1176 x
.dereference
= DEREF_NEVER
;
1178 x
.dereference
= DEREF_ALWAYS
;
1182 x
.copy_as_regular
= copy_contents
;
1184 /* Ensure -Z overrides -a. */
1185 if ((x
.set_security_context
|| scontext
)
1186 && ! x
.require_preserve_context
)
1187 x
.preserve_security_context
= false;
1189 if (x
.preserve_security_context
&& (x
.set_security_context
|| scontext
))
1190 die (EXIT_FAILURE
, 0,
1191 _("cannot set target context and preserve it"));
1193 if (x
.require_preserve_context
&& ! selinux_enabled
)
1194 die (EXIT_FAILURE
, 0,
1195 _("cannot preserve security context "
1196 "without an SELinux-enabled kernel"));
1198 /* FIXME: This handles new files. But what about existing files?
1199 I.e., if updating a tree, new files would have the specified context,
1200 but shouldn't existing files be updated for consistency like this?
1201 if (scontext && !restorecon (NULL, dst_path, 0))
1204 if (scontext
&& setfscreatecon (scontext
) < 0)
1205 die (EXIT_FAILURE
, errno
,
1206 _("failed to set default file creation context to %s"),
1210 if (x
.require_preserve_xattr
)
1211 die (EXIT_FAILURE
, 0, _("cannot preserve extended attributes, cp is "
1212 "built without xattr support"));
1215 /* Allocate space for remembering copied and created files. */
1219 ok
= do_copy (argc
- optind
, argv
+ optind
,
1220 target_directory
, no_target_directory
, &x
);
1222 main_exit (ok
? EXIT_SUCCESS
: EXIT_FAILURE
);