1 /* cp.c -- file copying (main routines)
2 Copyright (C) 1989-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 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"
39 /* The official name of this program (e.g., no 'g' prefix). */
40 #define PROGRAM_NAME "cp"
43 proper_name ("Torbjorn Granlund"), \
44 proper_name ("David MacKenzie"), \
45 proper_name ("Jim Meyering")
47 /* Used by do_copy, make_dir_parents_private, and re_protect
48 to keep a list of leading directories whose protections
49 need to be fixed after copying. */
55 struct dir_attr
*next
;
58 /* For long options that have no equivalent short option, use a
59 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
62 ATTRIBUTES_ONLY_OPTION
= CHAR_MAX
+ 1,
64 NO_PRESERVE_ATTRIBUTES_OPTION
,
66 PRESERVE_ATTRIBUTES_OPTION
,
69 STRIP_TRAILING_SLASHES_OPTION
,
70 UNLINK_DEST_BEFORE_OPENING
73 /* True if the kernel is SELinux enabled. */
74 static bool selinux_enabled
;
76 /* If true, the command "cp x/e_file e_dir" uses "e_dir/x/e_file"
77 as its destination instead of the usual "e_dir/e_file." */
78 static bool parents_option
= false;
80 /* Remove any trailing slashes from each SOURCE argument. */
81 static bool remove_trailing_slashes
;
83 static char const *const sparse_type_string
[] =
85 "never", "auto", "always", NULL
87 static enum Sparse_type
const sparse_type
[] =
89 SPARSE_NEVER
, SPARSE_AUTO
, SPARSE_ALWAYS
91 ARGMATCH_VERIFY (sparse_type_string
, sparse_type
);
93 static char const *const reflink_type_string
[] =
95 "auto", "always", "never", NULL
97 static enum Reflink_type
const reflink_type
[] =
99 REFLINK_AUTO
, REFLINK_ALWAYS
, REFLINK_NEVER
101 ARGMATCH_VERIFY (reflink_type_string
, reflink_type
);
103 static struct option
const long_opts
[] =
105 {"archive", no_argument
, NULL
, 'a'},
106 {"attributes-only", no_argument
, NULL
, ATTRIBUTES_ONLY_OPTION
},
107 {"backup", optional_argument
, NULL
, 'b'},
108 {"copy-contents", no_argument
, NULL
, COPY_CONTENTS_OPTION
},
109 {"dereference", no_argument
, NULL
, 'L'},
110 {"force", no_argument
, NULL
, 'f'},
111 {"interactive", no_argument
, NULL
, 'i'},
112 {"link", no_argument
, NULL
, 'l'},
113 {"no-clobber", no_argument
, NULL
, 'n'},
114 {"no-dereference", no_argument
, NULL
, 'P'},
115 {"no-preserve", required_argument
, NULL
, NO_PRESERVE_ATTRIBUTES_OPTION
},
116 {"no-target-directory", no_argument
, NULL
, 'T'},
117 {"one-file-system", no_argument
, NULL
, 'x'},
118 {"parents", no_argument
, NULL
, PARENTS_OPTION
},
119 {"path", no_argument
, NULL
, PARENTS_OPTION
}, /* Deprecated. */
120 {"preserve", optional_argument
, NULL
, PRESERVE_ATTRIBUTES_OPTION
},
121 {"recursive", no_argument
, NULL
, 'R'},
122 {"remove-destination", no_argument
, NULL
, UNLINK_DEST_BEFORE_OPENING
},
123 {"sparse", required_argument
, NULL
, SPARSE_OPTION
},
124 {"reflink", optional_argument
, NULL
, REFLINK_OPTION
},
125 {"strip-trailing-slashes", no_argument
, NULL
, STRIP_TRAILING_SLASHES_OPTION
},
126 {"suffix", required_argument
, NULL
, 'S'},
127 {"symbolic-link", no_argument
, NULL
, 's'},
128 {"target-directory", required_argument
, NULL
, 't'},
129 {"update", no_argument
, NULL
, 'u'},
130 {"verbose", no_argument
, NULL
, 'v'},
131 {GETOPT_SELINUX_CONTEXT_OPTION_DECL
},
132 {GETOPT_HELP_OPTION_DECL
},
133 {GETOPT_VERSION_OPTION_DECL
},
140 if (status
!= EXIT_SUCCESS
)
145 Usage: %s [OPTION]... [-T] SOURCE DEST\n\
146 or: %s [OPTION]... SOURCE... DIRECTORY\n\
147 or: %s [OPTION]... -t DIRECTORY SOURCE...\n\
149 program_name
, program_name
, program_name
);
151 Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.\n\
154 emit_mandatory_arg_note ();
157 -a, --archive same as -dR --preserve=all\n\
158 --attributes-only don't copy the file data, just the attributes\n\
159 --backup[=CONTROL] make a backup of each existing destination file\
161 -b like --backup but does not accept an argument\n\
162 --copy-contents copy contents of special files when recursive\n\
163 -d same as --no-dereference --preserve=links\n\
166 -f, --force if an existing destination file cannot be\n\
167 opened, remove it and try again (this option\n\
168 is ignored when the -n option is also used)\n\
169 -i, --interactive prompt before overwrite (overrides a previous -n\
172 -H follow command-line symbolic links in SOURCE\n\
175 -l, --link hard link files instead of copying\n\
176 -L, --dereference always follow symbolic links in SOURCE\n\
179 -n, --no-clobber do not overwrite an existing file (overrides\n\
180 a previous -i option)\n\
181 -P, --no-dereference never follow symbolic links in SOURCE\n\
184 -p same as --preserve=mode,ownership,timestamps\n\
185 --preserve[=ATTR_LIST] preserve the specified attributes (default:\n\
186 mode,ownership,timestamps), if possible\n\
187 additional attributes: context, links, xattr,\
192 --no-preserve=ATTR_LIST don't preserve the specified attributes\n\
193 --parents use full source file name under DIRECTORY\n\
196 -R, -r, --recursive copy directories recursively\n\
197 --reflink[=WHEN] control clone/CoW copies. See below\n\
198 --remove-destination remove each existing destination file before\n\
199 attempting to open it (contrast with --force)\
202 --sparse=WHEN control creation of sparse files. See below\n\
203 --strip-trailing-slashes remove any trailing slashes from each SOURCE\n\
207 -s, --symbolic-link make symbolic links instead of copying\n\
208 -S, --suffix=SUFFIX override the usual backup suffix\n\
209 -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY\n\
210 -T, --no-target-directory treat DEST as a normal file\n\
213 -u, --update copy only when the SOURCE file is newer\n\
214 than the destination file or when the\n\
215 destination file is missing\n\
216 -v, --verbose explain what is being done\n\
217 -x, --one-file-system stay on this file system\n\
220 -Z set SELinux security context of destination\n\
221 file to default type\n\
222 --context[=CTX] like -Z, or if CTX is specified then set the\n\
223 SELinux or SMACK security context to CTX\n\
225 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
226 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
229 By default, sparse SOURCE files are detected by a crude heuristic and the\n\
230 corresponding DEST file is made sparse as well. That is the behavior\n\
231 selected by --sparse=auto. Specify --sparse=always to create a sparse DEST\n\
232 file whenever the SOURCE file contains a long enough sequence of zero bytes.\n\
233 Use --sparse=never to inhibit creation of sparse files.\n\
237 When --reflink[=always] is specified, perform a lightweight copy, where the\n\
238 data blocks are copied only when modified. If this is not possible the copy\n\
239 fails, or if --reflink=auto is specified, fall back to a standard copy.\n\
240 Use --reflink=never to ensure a standard copy is performed.\n\
242 emit_backup_suffix_note ();
245 As a special case, cp makes a backup of SOURCE when the force and backup\n\
246 options are given and SOURCE and DEST are the same name for an existing,\n\
249 emit_ancillary_info (PROGRAM_NAME
);
254 /* Ensure that parents of CONST_DST_NAME aka DST_DIRFD+DST_RELNAME have the
255 correct protections, for the --parents option. This is done
256 after all copying has been completed, to allow permissions
257 that don't include user write/execute.
259 ATTR_LIST is a null-terminated linked list of structures that
260 indicates the end of the filename of each intermediate directory
261 in CONST_DST_NAME that may need to have its attributes changed.
262 The command 'cp --parents --preserve a/b/c d/e_dir' changes the
263 attributes of the directories d/e_dir/a and d/e_dir/a/b to match
264 the corresponding source directories regardless of whether they
265 existed before the 'cp' command was given.
267 Return true if the parent of CONST_DST_NAME and any intermediate
268 directories specified by ATTR_LIST have the proper permissions
272 re_protect (char const *const_dst_name
, int dst_dirfd
, char const *dst_relname
,
273 struct dir_attr
*attr_list
, const struct cp_options
*x
)
276 char *dst_name
; /* A copy of CONST_DST_NAME we can change. */
277 char *src_name
; /* The source name in 'dst_name'. */
279 ASSIGN_STRDUPA (dst_name
, const_dst_name
);
280 src_name
= dst_name
+ (dst_relname
- const_dst_name
);
282 for (p
= attr_list
; p
; p
= p
->next
)
284 dst_name
[p
->slash_offset
] = '\0';
286 /* Adjust the times (and if possible, ownership) for the copy.
287 chown turns off set[ug]id bits for non-root,
288 so do the chmod last. */
290 if (x
->preserve_timestamps
)
292 struct timespec timespec
[2];
294 timespec
[0] = get_stat_atime (&p
->st
);
295 timespec
[1] = get_stat_mtime (&p
->st
);
297 if (utimensat (dst_dirfd
, src_name
, timespec
, 0))
299 error (0, errno
, _("failed to preserve times for %s"),
305 if (x
->preserve_ownership
)
307 if (lchownat (dst_dirfd
, src_name
, p
->st
.st_uid
, p
->st
.st_gid
) != 0)
309 if (! chown_failure_ok (x
))
311 error (0, errno
, _("failed to preserve ownership for %s"),
315 /* Failing to preserve ownership is OK. Still, try to preserve
316 the group, but ignore the possible error. */
317 ignore_value (lchownat (dst_dirfd
, src_name
, -1, p
->st
.st_gid
));
321 if (x
->preserve_mode
)
323 if (copy_acl (src_name
, -1, dst_name
, -1, p
->st
.st_mode
) != 0)
326 else if (p
->restore_mode
)
328 if (lchmodat (dst_dirfd
, src_name
, p
->st
.st_mode
) != 0)
330 error (0, errno
, _("failed to preserve permissions for %s"),
336 dst_name
[p
->slash_offset
] = '/';
341 /* Ensure that the parent directory of CONST_DIR exists, for
342 the --parents option.
344 SRC_OFFSET is the index in CONST_DIR (which is a destination
345 directory) of the beginning of the source directory name.
346 Create any leading directories that don't already exist.
347 DST_DIRFD is a file descriptor for the target directory.
348 If VERBOSE_FMT_STRING is nonzero, use it as a printf format
349 string for printing a message after successfully making a directory.
350 The format should take two string arguments: the names of the
351 source and destination directories.
352 Creates a linked list of attributes of intermediate directories,
353 *ATTR_LIST, for re_protect to use after calling copy.
354 Sets *NEW_DST if this function creates parent of CONST_DIR.
356 Return true if parent of CONST_DIR exists as a directory with the proper
357 permissions when done. */
359 /* FIXME: Synch this function with the one in ../lib/mkdir-p.c. */
362 make_dir_parents_private (char const *const_dir
, size_t src_offset
,
364 char const *verbose_fmt_string
,
365 struct dir_attr
**attr_list
, bool *new_dst
,
366 const struct cp_options
*x
)
369 char *dir
; /* A copy of CONST_DIR we can change. */
370 char *src
; /* Source name in DIR. */
371 char *dst_dir
; /* Leading directory of DIR. */
372 idx_t dirlen
= dir_len (const_dir
);
376 /* Succeed immediately if the parent of CONST_DIR must already exist,
377 as the target directory has already been checked. */
378 if (dirlen
<= src_offset
)
381 ASSIGN_STRDUPA (dir
, const_dir
);
383 src
= dir
+ src_offset
;
385 dst_dir
= alloca (dirlen
+ 1);
386 memcpy (dst_dir
, dir
, dirlen
);
387 dst_dir
[dirlen
] = '\0';
388 char const *dst_reldir
= dst_dir
+ src_offset
;
389 while (*dst_reldir
== '/')
392 /* XXX: If all dirs are present at the destination,
393 no permissions or security contexts will be updated. */
394 if (statat (dst_dirfd
, dst_reldir
, &stats
) != 0)
396 /* A parent of CONST_DIR does not exist.
397 Make all missing intermediate directories. */
401 while (*slash
== '/')
405 while ((slash
= strchr (slash
, '/')))
407 struct dir_attr
*new IF_LINT ( = NULL
);
411 missing_dir
= statat (dst_dirfd
, dst_reldir
, &stats
) != 0;
413 if (missing_dir
|| x
->preserve_ownership
|| x
->preserve_mode
414 || x
->preserve_timestamps
)
416 /* Add this directory to the list of directories whose
417 modes might need fixing later. */
419 int src_errno
= (stat (src
, &src_st
) != 0
421 : S_ISDIR (src_st
.st_mode
)
426 error (0, src_errno
, _("failed to get attributes of %s"),
431 new = xmalloc (sizeof *new);
433 new->slash_offset
= slash
- dir
;
434 new->restore_mode
= false;
435 new->next
= *attr_list
;
439 /* If required set the default context for created dirs. */
440 if (! set_process_security_ctx (src
, dir
,
441 missing_dir
? new->st
.st_mode
: 0,
448 mode_t omitted_permissions
;
451 /* This component does not exist. We must set
452 *new_dst and new->st.st_mode inside this loop because,
453 for example, in the command 'cp --parents ../a/../b/c e_dir',
454 make_dir_parents_private creates only e_dir/../a if
455 ./b already exists. */
457 src_mode
= new->st
.st_mode
;
459 /* If the ownership or special mode bits might change,
460 omit some permissions at first, so unauthorized users
461 cannot nip in before the file is ready. */
462 omitted_permissions
= (src_mode
463 & (x
->preserve_ownership
469 /* POSIX says mkdir's behavior is implementation-defined when
470 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
471 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
472 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
473 mkdir_mode
= x
->explicit_no_preserve_mode
? S_IRWXUGO
: src_mode
;
474 mkdir_mode
&= CHMOD_MODE_BITS
& ~omitted_permissions
;
475 if (mkdirat (dst_dirfd
, dst_reldir
, mkdir_mode
) != 0)
477 error (0, errno
, _("cannot make directory %s"),
483 if (verbose_fmt_string
!= NULL
)
484 printf (verbose_fmt_string
, src
, dir
);
487 /* We need search and write permissions to the new directory
488 for writing the directory's contents. Check if these
489 permissions are there. */
491 if (lstatat (dst_dirfd
, dst_reldir
, &stats
))
493 error (0, errno
, _("failed to get attributes of %s"),
499 if (! x
->preserve_mode
)
501 if (omitted_permissions
& ~stats
.st_mode
)
502 omitted_permissions
&= ~ cached_umask ();
503 if (omitted_permissions
& ~stats
.st_mode
504 || (stats
.st_mode
& S_IRWXU
) != S_IRWXU
)
506 new->st
.st_mode
= stats
.st_mode
| omitted_permissions
;
507 new->restore_mode
= true;
511 mode_t accessible
= stats
.st_mode
| S_IRWXU
;
512 if (stats
.st_mode
!= accessible
)
514 /* Make the new directory searchable and writable.
515 The original permissions will be restored later. */
517 if (lchmodat (dst_dirfd
, dst_reldir
, accessible
) != 0)
519 error (0, errno
, _("setting permissions for %s"),
525 else if (!S_ISDIR (stats
.st_mode
))
527 error (0, 0, _("%s exists but is not a directory"),
534 /* For existing dirs, set the security context as per that already
535 set for the process global context. */
537 && (x
->set_security_context
|| x
->preserve_security_context
))
539 if (! set_file_security_ctx (dir
, false, x
)
540 && x
->require_preserve_context
)
546 /* Avoid unnecessary calls to 'stat' when given
547 file names containing multiple adjacent slashes. */
548 while (*slash
== '/')
553 /* We get here if the parent of DIR already exists. */
555 else if (!S_ISDIR (stats
.st_mode
))
557 error (0, 0, _("%s exists but is not a directory"), quoteaf (dst_dir
));
567 /* Must F designate the working directory? */
569 ATTRIBUTE_PURE
static bool
570 must_be_working_directory (char const *f
)
572 /* Return true for ".", "./.", ".///./", etc. */
585 /* Return a file descriptor open to FILE, for use in openat.
586 As an optimization, return AT_FDCWD if FILE must be the working directory.
587 Fail if FILE is not a directory.
588 On failure return a negative value; this is -1 unless AT_FDCWD == -1. */
591 target_directory_operand (char const *file
)
593 if (must_be_working_directory (file
))
596 int fd
= open (file
, O_PATHSEARCH
| O_DIRECTORY
);
598 if (!O_DIRECTORY
&& 0 <= fd
)
600 /* On old systems like Solaris 10 that do not support O_DIRECTORY,
601 check by hand whether DIRECTORY is a directory. */
604 if (fstat (fd
, &st
) != 0 ? (err
= errno
, true)
605 : !S_ISDIR (st
.st_mode
) && (err
= ENOTDIR
, true))
613 return fd
- (AT_FDCWD
== -1 && fd
< 0);
616 /* Return true if FD represents success for target_directory_operand. */
619 target_dirfd_valid (int fd
)
621 return fd
!= -1 - (AT_FDCWD
== -1);
624 /* Scan the arguments, and copy each by calling copy.
625 Return true if successful. */
628 do_copy (int n_files
, char **file
, char const *target_directory
,
629 bool no_target_directory
, struct cp_options
*x
)
632 bool new_dst
= false;
635 if (n_files
<= !target_directory
)
638 error (0, 0, _("missing file operand"));
640 error (0, 0, _("missing destination file operand after %s"),
642 usage (EXIT_FAILURE
);
646 int target_dirfd
= AT_FDCWD
;
647 if (no_target_directory
)
649 if (target_directory
)
650 die (EXIT_FAILURE
, 0,
651 _("cannot combine --target-directory (-t) "
652 "and --no-target-directory (-T)"));
655 error (0, 0, _("extra operand %s"), quoteaf (file
[2]));
656 usage (EXIT_FAILURE
);
659 else if (target_directory
)
661 target_dirfd
= target_directory_operand (target_directory
);
662 if (! target_dirfd_valid (target_dirfd
))
663 die (EXIT_FAILURE
, errno
, _("target directory %s"),
664 quoteaf (target_directory
));
668 char const *lastfile
= file
[n_files
- 1];
669 int fd
= target_directory_operand (lastfile
);
670 if (target_dirfd_valid (fd
))
673 target_directory
= lastfile
;
682 /* The last operand LASTFILE cannot be opened as a directory.
683 If there are more than two operands, report an error.
685 Also, report an error if LASTFILE is known to be a directory
686 even though it could not be opened, which can happen if
687 opening failed with EACCES on a platform lacking O_PATH.
688 In this case use stat to test whether LASTFILE is a
689 directory, in case opening a non-directory with (O_SEARCH
690 | O_DIRECTORY) failed with EACCES not ENOTDIR. */
692 || (O_PATHSEARCH
== O_SEARCH
&& err
== EACCES
693 && stat (lastfile
, &sb
) == 0 && S_ISDIR (sb
.st_mode
)))
694 die (EXIT_FAILURE
, err
, _("target %s"), quoteaf (lastfile
));
698 if (target_directory
)
700 /* cp file1...filen edir
701 Copy the files 'file1' through 'filen'
702 to the existing directory 'edir'. */
704 /* Initialize these hash tables only if we'll need them.
705 The problems they're used to detect can arise only if
706 there are two or more files to copy. */
713 for (int i
= 0; i
< n_files
; i
++)
716 bool parent_exists
= true; /* True if dir_name (dst_name) exists. */
717 struct dir_attr
*attr_list
;
718 char *arg_in_concat
= NULL
;
721 /* Trailing slashes are meaningful (i.e., maybe worth preserving)
722 only in the source file names. */
723 if (remove_trailing_slashes
)
724 strip_trailing_slashes (arg
);
728 char *arg_no_trailing_slash
;
730 /* Use 'arg' without trailing slashes in constructing destination
731 file names. Otherwise, we can end up trying to create a
732 directory using a name with trailing slash, which fails on
733 NetBSD 1.[34] systems. */
734 ASSIGN_STRDUPA (arg_no_trailing_slash
, arg
);
735 strip_trailing_slashes (arg_no_trailing_slash
);
737 /* Append all of 'arg' (minus any trailing slash) to 'dest'. */
738 dst_name
= file_name_concat (target_directory
,
739 arg_no_trailing_slash
,
742 /* For --parents, we have to make sure that the directory
743 dir_name (dst_name) exists. We may have to create a few
744 leading directories. */
746 (make_dir_parents_private
747 (dst_name
, arg_in_concat
- dst_name
, target_dirfd
,
748 (x
->verbose
? "%s -> %s\n" : NULL
),
749 &attr_list
, &new_dst
, x
));
751 while (*arg_in_concat
== '/')
757 /* Append the last component of 'arg' to 'target_directory'. */
758 ASSIGN_STRDUPA (arg_base
, last_component (arg
));
759 strip_trailing_slashes (arg_base
);
760 /* For 'cp -R source/.. dest', don't copy into 'dest/..'. */
761 arg_base
+= STREQ (arg_base
, "..");
762 dst_name
= file_name_concat (target_directory
, arg_base
,
768 /* make_dir_parents_private failed, so don't even
775 ok
&= copy (arg
, dst_name
, target_dirfd
, arg_in_concat
,
776 new_dst
, x
, ©_into_self
, NULL
);
779 ok
&= re_protect (dst_name
, target_dirfd
, arg_in_concat
,
787 struct dir_attr
*p
= attr_list
;
788 attr_list
= attr_list
->next
;
801 else /* !target_directory */
803 char const *source
= file
[0];
804 char const *dest
= file
[1];
810 _("with --parents, the destination must be a directory"));
811 usage (EXIT_FAILURE
);
814 /* When the force and backup options have been specified and
815 the source and destination are the same name for an existing
816 regular file, convert the user's command, e.g.,
817 'cp --force --backup foo foo' to 'cp --force foo fooSUFFIX'
818 where SUFFIX is determined by any version control options used. */
820 if (x
->unlink_dest_after_failed_open
821 && x
->backup_type
!= no_backups
822 && STREQ (source
, dest
)
824 && (sb
.st_mode
!= 0 || stat (dest
, &sb
) == 0) && S_ISREG (sb
.st_mode
))
826 static struct cp_options x_tmp
;
828 dest
= find_backup_file_name (AT_FDCWD
, dest
, x
->backup_type
);
829 /* Set x->backup_type to 'no_backups' so that the normal backup
830 mechanism is not used when performing the actual copy.
831 backup_type must be set to 'no_backups' only *after* the above
832 call to find_backup_file_name -- that function uses
833 backup_type to determine the suffix it applies. */
835 x_tmp
.backup_type
= no_backups
;
839 ok
= copy (source
, dest
, AT_FDCWD
, dest
, -new_dst
, x
, &unused
, NULL
);
846 cp_option_init (struct cp_options
*x
)
848 cp_options_default (x
);
849 x
->copy_as_regular
= true;
850 x
->dereference
= DEREF_UNDEFINED
;
851 x
->unlink_dest_before_opening
= false;
852 x
->unlink_dest_after_failed_open
= false;
853 x
->hard_link
= false;
854 x
->interactive
= I_UNSPECIFIED
;
855 x
->move_mode
= false;
856 x
->install_mode
= false;
857 x
->one_file_system
= false;
858 x
->reflink_mode
= REFLINK_AUTO
;
860 x
->preserve_ownership
= false;
861 x
->preserve_links
= false;
862 x
->preserve_mode
= false;
863 x
->preserve_timestamps
= false;
864 x
->explicit_no_preserve_mode
= false;
865 x
->preserve_security_context
= false; /* -a or --preserve=context. */
866 x
->require_preserve_context
= false; /* --preserve=context. */
867 x
->set_security_context
= NULL
; /* -Z, set sys default context. */
868 x
->preserve_xattr
= false;
869 x
->reduce_diagnostics
= false;
870 x
->require_preserve_xattr
= false;
872 x
->data_copy_required
= true;
873 x
->require_preserve
= false;
874 x
->recursive
= false;
875 x
->sparse_mode
= SPARSE_AUTO
;
876 x
->symbolic_link
= false;
881 x
->stdin_tty
= false;
886 /* By default, refuse to open a dangling destination symlink, because
887 in general one cannot do that safely, give the current semantics of
888 open's O_EXCL flag, (which POSIX doesn't even allow cp to use, btw).
889 But POSIX requires it. */
890 x
->open_dangling_dest_symlink
= getenv ("POSIXLY_CORRECT") != NULL
;
896 /* Given a string, ARG, containing a comma-separated list of arguments
897 to the --preserve option, set the appropriate fields of X to ON_OFF. */
899 decode_preserve_arg (char const *arg
, struct cp_options
*x
, bool on_off
)
911 static enum File_attribute
const preserve_vals
[] =
913 PRESERVE_MODE
, PRESERVE_TIMESTAMPS
,
914 PRESERVE_OWNERSHIP
, PRESERVE_LINK
, PRESERVE_CONTEXT
, PRESERVE_XATTR
,
917 /* Valid arguments to the '--preserve' option. */
918 static char const *const preserve_args
[] =
920 "mode", "timestamps",
921 "ownership", "links", "context", "xattr", "all", NULL
923 ARGMATCH_VERIFY (preserve_args
, preserve_vals
);
925 char *arg_writable
= xstrdup (arg
);
926 char *s
= arg_writable
;
929 /* find next comma */
930 char *comma
= strchr (s
, ',');
931 enum File_attribute val
;
933 /* If we found a comma, put a NUL in its place and advance. */
938 val
= XARGMATCH (on_off
? "--preserve" : "--no-preserve",
939 s
, preserve_args
, preserve_vals
);
943 x
->preserve_mode
= on_off
;
944 x
->explicit_no_preserve_mode
= !on_off
;
947 case PRESERVE_TIMESTAMPS
:
948 x
->preserve_timestamps
= on_off
;
951 case PRESERVE_OWNERSHIP
:
952 x
->preserve_ownership
= on_off
;
956 x
->preserve_links
= on_off
;
959 case PRESERVE_CONTEXT
:
960 x
->require_preserve_context
= on_off
;
961 x
->preserve_security_context
= on_off
;
965 x
->preserve_xattr
= on_off
;
966 x
->require_preserve_xattr
= on_off
;
970 x
->preserve_mode
= on_off
;
971 x
->preserve_timestamps
= on_off
;
972 x
->preserve_ownership
= on_off
;
973 x
->preserve_links
= on_off
;
974 x
->explicit_no_preserve_mode
= !on_off
;
976 x
->preserve_security_context
= on_off
;
977 x
->preserve_xattr
= on_off
;
991 main (int argc
, char **argv
)
995 bool make_backups
= false;
996 char const *backup_suffix
= NULL
;
997 char *version_control_string
= NULL
;
999 bool copy_contents
= false;
1000 char *target_directory
= NULL
;
1001 bool no_target_directory
= false;
1002 char const *scontext
= NULL
;
1004 initialize_main (&argc
, &argv
);
1005 set_program_name (argv
[0]);
1006 setlocale (LC_ALL
, "");
1007 bindtextdomain (PACKAGE
, LOCALEDIR
);
1008 textdomain (PACKAGE
);
1010 atexit (close_stdin
);
1012 selinux_enabled
= (0 < is_selinux_enabled ());
1013 cp_option_init (&x
);
1015 while ((c
= getopt_long (argc
, argv
, "abdfHilLnprst:uvxPRS:TZ",
1022 x
.sparse_mode
= XARGMATCH ("--sparse", optarg
,
1023 sparse_type_string
, sparse_type
);
1026 case REFLINK_OPTION
:
1028 x
.reflink_mode
= REFLINK_ALWAYS
;
1030 x
.reflink_mode
= XARGMATCH ("--reflink", optarg
,
1031 reflink_type_string
, reflink_type
);
1035 /* Like -dR --preserve=all with reduced failure diagnostics. */
1036 x
.dereference
= DEREF_NEVER
;
1037 x
.preserve_links
= true;
1038 x
.preserve_ownership
= true;
1039 x
.preserve_mode
= true;
1040 x
.preserve_timestamps
= true;
1041 x
.require_preserve
= true;
1042 if (selinux_enabled
)
1043 x
.preserve_security_context
= true;
1044 x
.preserve_xattr
= true;
1045 x
.reduce_diagnostics
= true;
1050 make_backups
= true;
1052 version_control_string
= optarg
;
1055 case ATTRIBUTES_ONLY_OPTION
:
1056 x
.data_copy_required
= false;
1059 case COPY_CONTENTS_OPTION
:
1060 copy_contents
= true;
1064 x
.preserve_links
= true;
1065 x
.dereference
= DEREF_NEVER
;
1069 x
.unlink_dest_after_failed_open
= true;
1073 x
.dereference
= DEREF_COMMAND_LINE_ARGUMENTS
;
1077 x
.interactive
= I_ASK_USER
;
1085 x
.dereference
= DEREF_ALWAYS
;
1089 x
.interactive
= I_ALWAYS_NO
;
1093 x
.dereference
= DEREF_NEVER
;
1096 case NO_PRESERVE_ATTRIBUTES_OPTION
:
1097 decode_preserve_arg (optarg
, &x
, false);
1100 case PRESERVE_ATTRIBUTES_OPTION
:
1103 /* Fall through to the case for 'p' below. */
1107 decode_preserve_arg (optarg
, &x
, true);
1108 x
.require_preserve
= true;
1114 x
.preserve_ownership
= true;
1115 x
.preserve_mode
= true;
1116 x
.preserve_timestamps
= true;
1117 x
.require_preserve
= true;
1120 case PARENTS_OPTION
:
1121 parents_option
= true;
1129 case UNLINK_DEST_BEFORE_OPENING
:
1130 x
.unlink_dest_before_opening
= true;
1133 case STRIP_TRAILING_SLASHES_OPTION
:
1134 remove_trailing_slashes
= true;
1138 x
.symbolic_link
= true;
1142 if (target_directory
)
1143 die (EXIT_FAILURE
, 0,
1144 _("multiple target directories specified"));
1145 target_directory
= optarg
;
1149 no_target_directory
= true;
1161 x
.one_file_system
= true;
1165 /* politely decline if we're not on a selinux-enabled kernel. */
1166 if (selinux_enabled
)
1172 x
.set_security_context
= selabel_open (SELABEL_CTX_FILE
,
1174 if (! x
.set_security_context
)
1175 error (0, errno
, _("warning: ignoring --context"));
1181 _("warning: ignoring --context; "
1182 "it requires an SELinux-enabled kernel"));
1187 make_backups
= true;
1188 backup_suffix
= optarg
;
1191 case_GETOPT_HELP_CHAR
;
1193 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
1196 usage (EXIT_FAILURE
);
1200 if (x
.hard_link
&& x
.symbolic_link
)
1202 error (0, 0, _("cannot make both hard and symbolic links"));
1203 usage (EXIT_FAILURE
);
1206 if (x
.interactive
== I_ALWAYS_NO
)
1209 if (make_backups
&& x
.interactive
== I_ALWAYS_NO
)
1212 _("options --backup and --no-clobber are mutually exclusive"));
1213 usage (EXIT_FAILURE
);
1216 if (x
.reflink_mode
== REFLINK_ALWAYS
&& x
.sparse_mode
!= SPARSE_AUTO
)
1218 error (0, 0, _("--reflink can be used only with --sparse=auto"));
1219 usage (EXIT_FAILURE
);
1222 x
.backup_type
= (make_backups
1223 ? xget_version (_("backup type"),
1224 version_control_string
)
1226 set_simple_backup_suffix (backup_suffix
);
1228 if (x
.dereference
== DEREF_UNDEFINED
)
1230 if (x
.recursive
&& ! x
.hard_link
)
1231 /* This is compatible with FreeBSD. */
1232 x
.dereference
= DEREF_NEVER
;
1234 x
.dereference
= DEREF_ALWAYS
;
1238 x
.copy_as_regular
= copy_contents
;
1240 /* Ensure -Z overrides -a. */
1241 if ((x
.set_security_context
|| scontext
)
1242 && ! x
.require_preserve_context
)
1243 x
.preserve_security_context
= false;
1245 if (x
.preserve_security_context
&& (x
.set_security_context
|| scontext
))
1246 die (EXIT_FAILURE
, 0,
1247 _("cannot set target context and preserve it"));
1249 if (x
.require_preserve_context
&& ! selinux_enabled
)
1250 die (EXIT_FAILURE
, 0,
1251 _("cannot preserve security context "
1252 "without an SELinux-enabled kernel"));
1254 /* FIXME: This handles new files. But what about existing files?
1255 I.e., if updating a tree, new files would have the specified context,
1256 but shouldn't existing files be updated for consistency like this?
1257 if (scontext && !restorecon (NULL, dst_path, 0))
1260 if (scontext
&& setfscreatecon (scontext
) < 0)
1261 die (EXIT_FAILURE
, errno
,
1262 _("failed to set default file creation context to %s"),
1266 if (x
.require_preserve_xattr
)
1267 die (EXIT_FAILURE
, 0, _("cannot preserve extended attributes, cp is "
1268 "built without xattr support"));
1271 /* Allocate space for remembering copied and created files. */
1275 ok
= do_copy (argc
- optind
, argv
+ optind
,
1276 target_directory
, no_target_directory
, &x
);
1282 return ok
? EXIT_SUCCESS
: EXIT_FAILURE
;