build: avoid compile warnings in factor.c on some systems
[coreutils.git] / src / cp.c
blob61b31afdc919662514946034af5440c706d2894f
1 /* cp.c -- file copying (main routines)
2 Copyright (C) 1989-2012 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 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 "error.h"
31 #include "filenamecat.h"
32 #include "ignore-value.h"
33 #include "quote.h"
34 #include "stat-time.h"
35 #include "utimens.h"
36 #include "acl.h"
38 #if ! HAVE_LCHOWN
39 # define lchown(name, uid, gid) chown (name, uid, gid)
40 #endif
42 #define ASSIGN_BASENAME_STRDUPA(Dest, File_name) \
43 do \
44 { \
45 char *tmp_abns_; \
46 ASSIGN_STRDUPA (tmp_abns_, (File_name)); \
47 Dest = last_component (tmp_abns_); \
48 strip_trailing_slashes (Dest); \
49 } \
50 while (0)
52 /* The official name of this program (e.g., no 'g' prefix). */
53 #define PROGRAM_NAME "cp"
55 #define AUTHORS \
56 proper_name_utf8 ("Torbjorn Granlund", "Torbj\303\266rn Granlund"), \
57 proper_name ("David MacKenzie"), \
58 proper_name ("Jim Meyering")
60 /* Used by do_copy, make_dir_parents_private, and re_protect
61 to keep a list of leading directories whose protections
62 need to be fixed after copying. */
63 struct dir_attr
65 struct stat st;
66 bool restore_mode;
67 size_t slash_offset;
68 struct dir_attr *next;
71 /* For long options that have no equivalent short option, use a
72 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
73 enum
75 ATTRIBUTES_ONLY_OPTION = CHAR_MAX + 1,
76 COPY_CONTENTS_OPTION,
77 NO_PRESERVE_ATTRIBUTES_OPTION,
78 PARENTS_OPTION,
79 PRESERVE_ATTRIBUTES_OPTION,
80 REFLINK_OPTION,
81 SPARSE_OPTION,
82 STRIP_TRAILING_SLASHES_OPTION,
83 UNLINK_DEST_BEFORE_OPENING
86 /* True if the kernel is SELinux enabled. */
87 static bool selinux_enabled;
89 /* If true, the command "cp x/e_file e_dir" uses "e_dir/x/e_file"
90 as its destination instead of the usual "e_dir/e_file." */
91 static bool parents_option = false;
93 /* Remove any trailing slashes from each SOURCE argument. */
94 static bool remove_trailing_slashes;
96 static char const *const sparse_type_string[] =
98 "never", "auto", "always", NULL
100 static enum Sparse_type const sparse_type[] =
102 SPARSE_NEVER, SPARSE_AUTO, SPARSE_ALWAYS
104 ARGMATCH_VERIFY (sparse_type_string, sparse_type);
106 static char const *const reflink_type_string[] =
108 "auto", "always", NULL
110 static enum Reflink_type const reflink_type[] =
112 REFLINK_AUTO, REFLINK_ALWAYS
114 ARGMATCH_VERIFY (reflink_type_string, reflink_type);
116 static struct option const long_opts[] =
118 {"archive", no_argument, NULL, 'a'},
119 {"attributes-only", no_argument, NULL, ATTRIBUTES_ONLY_OPTION},
120 {"backup", optional_argument, NULL, 'b'},
121 {"copy-contents", no_argument, NULL, COPY_CONTENTS_OPTION},
122 {"dereference", no_argument, NULL, 'L'},
123 {"force", no_argument, NULL, 'f'},
124 {"interactive", no_argument, NULL, 'i'},
125 {"link", no_argument, NULL, 'l'},
126 {"no-clobber", no_argument, NULL, 'n'},
127 {"no-dereference", no_argument, NULL, 'P'},
128 {"no-preserve", required_argument, NULL, NO_PRESERVE_ATTRIBUTES_OPTION},
129 {"no-target-directory", no_argument, NULL, 'T'},
130 {"one-file-system", no_argument, NULL, 'x'},
131 {"parents", no_argument, NULL, PARENTS_OPTION},
132 {"path", no_argument, NULL, PARENTS_OPTION}, /* Deprecated. */
133 {"preserve", optional_argument, NULL, PRESERVE_ATTRIBUTES_OPTION},
134 {"recursive", no_argument, NULL, 'R'},
135 {"remove-destination", no_argument, NULL, UNLINK_DEST_BEFORE_OPENING},
136 {"sparse", required_argument, NULL, SPARSE_OPTION},
137 {"reflink", optional_argument, NULL, REFLINK_OPTION},
138 {"strip-trailing-slashes", no_argument, NULL, STRIP_TRAILING_SLASHES_OPTION},
139 {"suffix", required_argument, NULL, 'S'},
140 {"symbolic-link", no_argument, NULL, 's'},
141 {"target-directory", required_argument, NULL, 't'},
142 {"update", no_argument, NULL, 'u'},
143 {"verbose", no_argument, NULL, 'v'},
144 {GETOPT_HELP_OPTION_DECL},
145 {GETOPT_VERSION_OPTION_DECL},
146 {NULL, 0, NULL, 0}
149 void
150 usage (int status)
152 if (status != EXIT_SUCCESS)
153 emit_try_help ();
154 else
156 printf (_("\
157 Usage: %s [OPTION]... [-T] SOURCE DEST\n\
158 or: %s [OPTION]... SOURCE... DIRECTORY\n\
159 or: %s [OPTION]... -t DIRECTORY SOURCE...\n\
161 program_name, program_name, program_name);
162 fputs (_("\
163 Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.\n\
165 "), stdout);
166 fputs (_("\
167 Mandatory arguments to long options are mandatory for short options too.\n\
168 "), stdout);
169 fputs (_("\
170 -a, --archive same as -dR --preserve=all\n\
171 --attributes-only don't copy the file data, just the attributes\n\
172 --backup[=CONTROL] make a backup of each existing destination file\
174 -b like --backup but does not accept an argument\n\
175 --copy-contents copy contents of special files when recursive\n\
176 -d same as --no-dereference --preserve=links\n\
177 "), stdout);
178 fputs (_("\
179 -f, --force if an existing destination file cannot be\n\
180 opened, remove it and try again (redundant if\
182 the -n option is 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 (HELP_OPTION_DESCRIPTION, stdout);
234 fputs (VERSION_OPTION_DESCRIPTION, stdout);
235 fputs (_("\
237 By default, sparse SOURCE files are detected by a crude heuristic and the\n\
238 corresponding DEST file is made sparse as well. That is the behavior\n\
239 selected by --sparse=auto. Specify --sparse=always to create a sparse DEST\n\
240 file whenever the SOURCE file contains a long enough sequence of zero bytes.\n\
241 Use --sparse=never to inhibit creation of sparse files.\n\
243 When --reflink[=always] is specified, perform a lightweight copy, where the\n\
244 data blocks are copied only when modified. If this is not possible the copy\n\
245 fails, or if --reflink=auto is specified, fall back to a standard copy.\n\
246 "), stdout);
247 fputs (_("\
249 The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
250 The version control method may be selected via the --backup option or through\n\
251 the VERSION_CONTROL environment variable. Here are the values:\n\
253 "), stdout);
254 fputs (_("\
255 none, off never make backups (even if --backup is given)\n\
256 numbered, t make numbered backups\n\
257 existing, nil numbered if numbered backups exist, simple otherwise\n\
258 simple, never always make simple backups\n\
259 "), stdout);
260 fputs (_("\
262 As a special case, cp makes a backup of SOURCE when the force and backup\n\
263 options are given and SOURCE and DEST are the same name for an existing,\n\
264 regular file.\n\
265 "), stdout);
266 emit_ancillary_info ();
268 exit (status);
271 /* Ensure that the parent directories of CONST_DST_NAME have the
272 correct protections, for the --parents option. This is done
273 after all copying has been completed, to allow permissions
274 that don't include user write/execute.
276 SRC_OFFSET is the index in CONST_DST_NAME of the beginning of the
277 source directory name.
279 ATTR_LIST is a null-terminated linked list of structures that
280 indicates the end of the filename of each intermediate directory
281 in CONST_DST_NAME that may need to have its attributes changed.
282 The command 'cp --parents --preserve a/b/c d/e_dir' changes the
283 attributes of the directories d/e_dir/a and d/e_dir/a/b to match
284 the corresponding source directories regardless of whether they
285 existed before the 'cp' command was given.
287 Return true if the parent of CONST_DST_NAME and any intermediate
288 directories specified by ATTR_LIST have the proper permissions
289 when done. */
291 static bool
292 re_protect (char const *const_dst_name, size_t src_offset,
293 struct dir_attr *attr_list, const struct cp_options *x)
295 struct dir_attr *p;
296 char *dst_name; /* A copy of CONST_DST_NAME we can change. */
297 char *src_name; /* The source name in 'dst_name'. */
299 ASSIGN_STRDUPA (dst_name, const_dst_name);
300 src_name = dst_name + src_offset;
302 for (p = attr_list; p; p = p->next)
304 dst_name[p->slash_offset] = '\0';
306 /* Adjust the times (and if possible, ownership) for the copy.
307 chown turns off set[ug]id bits for non-root,
308 so do the chmod last. */
310 if (x->preserve_timestamps)
312 struct timespec timespec[2];
314 timespec[0] = get_stat_atime (&p->st);
315 timespec[1] = get_stat_mtime (&p->st);
317 if (utimens (dst_name, timespec))
319 error (0, errno, _("failed to preserve times for %s"),
320 quote (dst_name));
321 return false;
325 if (x->preserve_ownership)
327 if (lchown (dst_name, p->st.st_uid, p->st.st_gid) != 0)
329 if (! chown_failure_ok (x))
331 error (0, errno, _("failed to preserve ownership for %s"),
332 quote (dst_name));
333 return false;
335 /* Failing to preserve ownership is OK. Still, try to preserve
336 the group, but ignore the possible error. */
337 ignore_value (lchown (dst_name, -1, p->st.st_gid));
341 if (x->preserve_mode)
343 if (copy_acl (src_name, -1, dst_name, -1, p->st.st_mode) != 0)
344 return false;
346 else if (p->restore_mode)
348 if (lchmod (dst_name, p->st.st_mode) != 0)
350 error (0, errno, _("failed to preserve permissions for %s"),
351 quote (dst_name));
352 return false;
356 dst_name[p->slash_offset] = '/';
358 return true;
361 /* Ensure that the parent directory of CONST_DIR exists, for
362 the --parents option.
364 SRC_OFFSET is the index in CONST_DIR (which is a destination
365 directory) of the beginning of the source directory name.
366 Create any leading directories that don't already exist.
367 If VERBOSE_FMT_STRING is nonzero, use it as a printf format
368 string for printing a message after successfully making a directory.
369 The format should take two string arguments: the names of the
370 source and destination directories.
371 Creates a linked list of attributes of intermediate directories,
372 *ATTR_LIST, for re_protect to use after calling copy.
373 Sets *NEW_DST if this function creates parent of CONST_DIR.
375 Return true if parent of CONST_DIR exists as a directory with the proper
376 permissions when done. */
378 /* FIXME: Synch this function with the one in ../lib/mkdir-p.c. */
380 static bool
381 make_dir_parents_private (char const *const_dir, size_t src_offset,
382 char const *verbose_fmt_string,
383 struct dir_attr **attr_list, bool *new_dst,
384 const struct cp_options *x)
386 struct stat stats;
387 char *dir; /* A copy of CONST_DIR we can change. */
388 char *src; /* Source name in DIR. */
389 char *dst_dir; /* Leading directory of DIR. */
390 size_t dirlen; /* Length of DIR. */
392 ASSIGN_STRDUPA (dir, const_dir);
394 src = dir + src_offset;
396 dirlen = dir_len (dir);
397 dst_dir = alloca (dirlen + 1);
398 memcpy (dst_dir, dir, dirlen);
399 dst_dir[dirlen] = '\0';
401 *attr_list = NULL;
403 if (stat (dst_dir, &stats) != 0)
405 /* A parent of CONST_DIR does not exist.
406 Make all missing intermediate directories. */
407 char *slash;
409 slash = src;
410 while (*slash == '/')
411 slash++;
412 while ((slash = strchr (slash, '/')))
414 struct dir_attr *new IF_LINT ( = NULL);
415 bool missing_dir;
417 *slash = '\0';
418 missing_dir = (stat (dir, &stats) != 0);
420 if (missing_dir || x->preserve_ownership || x->preserve_mode
421 || x->preserve_timestamps)
423 /* Add this directory to the list of directories whose
424 modes might need fixing later. */
425 struct stat src_st;
426 int src_errno = (stat (src, &src_st) != 0
427 ? errno
428 : S_ISDIR (src_st.st_mode)
430 : ENOTDIR);
431 if (src_errno)
433 error (0, src_errno, _("failed to get attributes of %s"),
434 quote (src));
435 return false;
438 new = xmalloc (sizeof *new);
439 new->st = src_st;
440 new->slash_offset = slash - dir;
441 new->restore_mode = false;
442 new->next = *attr_list;
443 *attr_list = new;
446 if (missing_dir)
448 mode_t src_mode;
449 mode_t omitted_permissions;
450 mode_t mkdir_mode;
452 /* This component does not exist. We must set
453 *new_dst and new->st.st_mode inside this loop because,
454 for example, in the command 'cp --parents ../a/../b/c e_dir',
455 make_dir_parents_private creates only e_dir/../a if
456 ./b already exists. */
457 *new_dst = true;
458 src_mode = new->st.st_mode;
460 /* If the ownership or special mode bits might change,
461 omit some permissions at first, so unauthorized users
462 cannot nip in before the file is ready. */
463 omitted_permissions = (src_mode
464 & (x->preserve_ownership
465 ? S_IRWXG | S_IRWXO
466 : x->preserve_mode
467 ? S_IWGRP | S_IWOTH
468 : 0));
470 /* POSIX says mkdir's behavior is implementation-defined when
471 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
472 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
473 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
474 mkdir_mode = src_mode & CHMOD_MODE_BITS & ~omitted_permissions;
475 if (mkdir (dir, mkdir_mode) != 0)
477 error (0, errno, _("cannot make directory %s"),
478 quote (dir));
479 return false;
481 else
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 (lstat (dir, &stats))
493 error (0, errno, _("failed to get attributes of %s"),
494 quote (dir));
495 return false;
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 if ((stats.st_mode & S_IRWXU) != S_IRWXU)
513 /* Make the new directory searchable and writable.
514 The original permissions will be restored later. */
516 if (lchmod (dir, stats.st_mode | S_IRWXU) != 0)
518 error (0, errno, _("setting permissions for %s"),
519 quote (dir));
520 return false;
524 else if (!S_ISDIR (stats.st_mode))
526 error (0, 0, _("%s exists but is not a directory"),
527 quote (dir));
528 return false;
530 else
531 *new_dst = false;
532 *slash++ = '/';
534 /* Avoid unnecessary calls to 'stat' when given
535 file names containing multiple adjacent slashes. */
536 while (*slash == '/')
537 slash++;
541 /* We get here if the parent of DIR already exists. */
543 else if (!S_ISDIR (stats.st_mode))
545 error (0, 0, _("%s exists but is not a directory"), quote (dst_dir));
546 return false;
548 else
550 *new_dst = false;
552 return true;
555 /* FILE is the last operand of this command.
556 Return true if FILE is a directory.
557 But report an error and exit if there is a problem accessing FILE,
558 or if FILE does not exist but would have to refer to an existing
559 directory if it referred to anything at all.
561 If the file exists, store the file's status into *ST.
562 Otherwise, set *NEW_DST. */
564 static bool
565 target_directory_operand (char const *file, struct stat *st, bool *new_dst)
567 int err = (stat (file, st) == 0 ? 0 : errno);
568 bool is_a_dir = !err && S_ISDIR (st->st_mode);
569 if (err)
571 if (err != ENOENT)
572 error (EXIT_FAILURE, err, _("accessing %s"), quote (file));
573 *new_dst = true;
575 return is_a_dir;
578 /* Scan the arguments, and copy each by calling copy.
579 Return true if successful. */
581 static bool
582 do_copy (int n_files, char **file, const char *target_directory,
583 bool no_target_directory, struct cp_options *x)
585 struct stat sb;
586 bool new_dst = false;
587 bool ok = true;
589 if (n_files <= !target_directory)
591 if (n_files <= 0)
592 error (0, 0, _("missing file operand"));
593 else
594 error (0, 0, _("missing destination file operand after %s"),
595 quote (file[0]));
596 usage (EXIT_FAILURE);
599 if (no_target_directory)
601 if (target_directory)
602 error (EXIT_FAILURE, 0,
603 _("cannot combine --target-directory (-t) "
604 "and --no-target-directory (-T)"));
605 if (2 < n_files)
607 error (0, 0, _("extra operand %s"), quote (file[2]));
608 usage (EXIT_FAILURE);
610 /* Update NEW_DST and SB, which may be checked below. */
611 ignore_value (target_directory_operand (file[n_files -1], &sb, &new_dst));
613 else if (!target_directory)
615 if (2 <= n_files
616 && target_directory_operand (file[n_files - 1], &sb, &new_dst))
617 target_directory = file[--n_files];
618 else if (2 < n_files)
619 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
620 quote (file[n_files - 1]));
623 if (target_directory)
625 /* cp file1...filen edir
626 Copy the files 'file1' through 'filen'
627 to the existing directory 'edir'. */
628 int i;
630 /* Initialize these hash tables only if we'll need them.
631 The problems they're used to detect can arise only if
632 there are two or more files to copy. */
633 if (2 <= n_files)
635 dest_info_init (x);
636 src_info_init (x);
639 for (i = 0; i < n_files; i++)
641 char *dst_name;
642 bool parent_exists = true; /* True if dir_name (dst_name) exists. */
643 struct dir_attr *attr_list;
644 char *arg_in_concat = NULL;
645 char *arg = file[i];
647 /* Trailing slashes are meaningful (i.e., maybe worth preserving)
648 only in the source file names. */
649 if (remove_trailing_slashes)
650 strip_trailing_slashes (arg);
652 if (parents_option)
654 char *arg_no_trailing_slash;
656 /* Use 'arg' without trailing slashes in constructing destination
657 file names. Otherwise, we can end up trying to create a
658 directory via 'mkdir ("dst/foo/"...', which is not portable.
659 It fails, due to the trailing slash, on at least
660 NetBSD 1.[34] systems. */
661 ASSIGN_STRDUPA (arg_no_trailing_slash, arg);
662 strip_trailing_slashes (arg_no_trailing_slash);
664 /* Append all of 'arg' (minus any trailing slash) to 'dest'. */
665 dst_name = file_name_concat (target_directory,
666 arg_no_trailing_slash,
667 &arg_in_concat);
669 /* For --parents, we have to make sure that the directory
670 dir_name (dst_name) exists. We may have to create a few
671 leading directories. */
672 parent_exists =
673 (make_dir_parents_private
674 (dst_name, arg_in_concat - dst_name,
675 (x->verbose ? "%s -> %s\n" : NULL),
676 &attr_list, &new_dst, x));
678 else
680 char *arg_base;
681 /* Append the last component of 'arg' to 'target_directory'. */
683 ASSIGN_BASENAME_STRDUPA (arg_base, arg);
684 /* For 'cp -R source/.. dest', don't copy into 'dest/..'. */
685 dst_name = (STREQ (arg_base, "..")
686 ? xstrdup (target_directory)
687 : file_name_concat (target_directory, arg_base,
688 NULL));
691 if (!parent_exists)
693 /* make_dir_parents_private failed, so don't even
694 attempt the copy. */
695 ok = false;
697 else
699 bool copy_into_self;
700 ok &= copy (arg, dst_name, new_dst, x, &copy_into_self, NULL);
702 if (parents_option)
703 ok &= re_protect (dst_name, arg_in_concat - dst_name,
704 attr_list, x);
707 if (parents_option)
709 while (attr_list)
711 struct dir_attr *p = attr_list;
712 attr_list = attr_list->next;
713 free (p);
717 free (dst_name);
720 else /* !target_directory */
722 char const *new_dest;
723 char const *source = file[0];
724 char const *dest = file[1];
725 bool unused;
727 if (parents_option)
729 error (0, 0,
730 _("with --parents, the destination must be a directory"));
731 usage (EXIT_FAILURE);
734 /* When the force and backup options have been specified and
735 the source and destination are the same name for an existing
736 regular file, convert the user's command, e.g.,
737 'cp --force --backup foo foo' to 'cp --force foo fooSUFFIX'
738 where SUFFIX is determined by any version control options used. */
740 if (x->unlink_dest_after_failed_open
741 && x->backup_type != no_backups
742 && STREQ (source, dest)
743 && !new_dst && S_ISREG (sb.st_mode))
745 static struct cp_options x_tmp;
747 new_dest = find_backup_file_name (dest, x->backup_type);
748 /* Set x->backup_type to 'no_backups' so that the normal backup
749 mechanism is not used when performing the actual copy.
750 backup_type must be set to 'no_backups' only *after* the above
751 call to find_backup_file_name -- that function uses
752 backup_type to determine the suffix it applies. */
753 x_tmp = *x;
754 x_tmp.backup_type = no_backups;
755 x = &x_tmp;
757 else
759 new_dest = dest;
762 ok = copy (source, new_dest, 0, x, &unused, NULL);
765 return ok;
768 static void
769 cp_option_init (struct cp_options *x)
771 cp_options_default (x);
772 x->copy_as_regular = true;
773 x->dereference = DEREF_UNDEFINED;
774 x->unlink_dest_before_opening = false;
775 x->unlink_dest_after_failed_open = false;
776 x->hard_link = false;
777 x->interactive = I_UNSPECIFIED;
778 x->move_mode = false;
779 x->one_file_system = false;
780 x->reflink_mode = REFLINK_NEVER;
782 x->preserve_ownership = false;
783 x->preserve_links = false;
784 x->preserve_mode = false;
785 x->preserve_timestamps = false;
786 x->explicit_no_preserve_mode = false;
787 x->preserve_security_context = false;
788 x->require_preserve_context = false;
789 x->preserve_xattr = false;
790 x->reduce_diagnostics = false;
791 x->require_preserve_xattr = false;
793 x->data_copy_required = true;
794 x->require_preserve = false;
795 x->recursive = false;
796 x->sparse_mode = SPARSE_AUTO;
797 x->symbolic_link = false;
798 x->set_mode = false;
799 x->mode = 0;
801 /* Not used. */
802 x->stdin_tty = false;
804 x->update = false;
805 x->verbose = false;
807 /* By default, refuse to open a dangling destination symlink, because
808 in general one cannot do that safely, give the current semantics of
809 open's O_EXCL flag, (which POSIX doesn't even allow cp to use, btw).
810 But POSIX requires it. */
811 x->open_dangling_dest_symlink = getenv ("POSIXLY_CORRECT") != NULL;
813 x->dest_info = NULL;
814 x->src_info = NULL;
817 /* Given a string, ARG, containing a comma-separated list of arguments
818 to the --preserve option, set the appropriate fields of X to ON_OFF. */
819 static void
820 decode_preserve_arg (char const *arg, struct cp_options *x, bool on_off)
822 enum File_attribute
824 PRESERVE_MODE,
825 PRESERVE_TIMESTAMPS,
826 PRESERVE_OWNERSHIP,
827 PRESERVE_LINK,
828 PRESERVE_CONTEXT,
829 PRESERVE_XATTR,
830 PRESERVE_ALL
832 static enum File_attribute const preserve_vals[] =
834 PRESERVE_MODE, PRESERVE_TIMESTAMPS,
835 PRESERVE_OWNERSHIP, PRESERVE_LINK, PRESERVE_CONTEXT, PRESERVE_XATTR,
836 PRESERVE_ALL
838 /* Valid arguments to the '--preserve' option. */
839 static char const* const preserve_args[] =
841 "mode", "timestamps",
842 "ownership", "links", "context", "xattr", "all", NULL
844 ARGMATCH_VERIFY (preserve_args, preserve_vals);
846 char *arg_writable = xstrdup (arg);
847 char *s = arg_writable;
850 /* find next comma */
851 char *comma = strchr (s, ',');
852 enum File_attribute val;
854 /* If we found a comma, put a NUL in its place and advance. */
855 if (comma)
856 *comma++ = 0;
858 /* process S. */
859 val = XARGMATCH ("--preserve", s, preserve_args, preserve_vals);
860 switch (val)
862 case PRESERVE_MODE:
863 x->preserve_mode = on_off;
864 x->explicit_no_preserve_mode = !on_off;
865 break;
867 case PRESERVE_TIMESTAMPS:
868 x->preserve_timestamps = on_off;
869 break;
871 case PRESERVE_OWNERSHIP:
872 x->preserve_ownership = on_off;
873 break;
875 case PRESERVE_LINK:
876 x->preserve_links = on_off;
877 break;
879 case PRESERVE_CONTEXT:
880 x->preserve_security_context = on_off;
881 x->require_preserve_context = on_off;
882 break;
884 case PRESERVE_XATTR:
885 x->preserve_xattr = on_off;
886 x->require_preserve_xattr = on_off;
887 break;
889 case PRESERVE_ALL:
890 x->preserve_mode = on_off;
891 x->preserve_timestamps = on_off;
892 x->preserve_ownership = on_off;
893 x->preserve_links = on_off;
894 x->explicit_no_preserve_mode = !on_off;
895 if (selinux_enabled)
896 x->preserve_security_context = on_off;
897 x->preserve_xattr = on_off;
898 break;
900 default:
901 abort ();
903 s = comma;
905 while (s);
907 free (arg_writable);
911 main (int argc, char **argv)
913 int c;
914 bool ok;
915 bool make_backups = false;
916 char *backup_suffix_string;
917 char *version_control_string = NULL;
918 struct cp_options x;
919 bool copy_contents = false;
920 char *target_directory = NULL;
921 bool no_target_directory = false;
923 initialize_main (&argc, &argv);
924 set_program_name (argv[0]);
925 setlocale (LC_ALL, "");
926 bindtextdomain (PACKAGE, LOCALEDIR);
927 textdomain (PACKAGE);
929 atexit (close_stdin);
931 selinux_enabled = (0 < is_selinux_enabled ());
932 cp_option_init (&x);
934 /* FIXME: consider not calling getenv for SIMPLE_BACKUP_SUFFIX unless
935 we'll actually use backup_suffix_string. */
936 backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
938 while ((c = getopt_long (argc, argv, "abdfHilLnprst:uvxPRS:T",
939 long_opts, NULL))
940 != -1)
942 switch (c)
944 case SPARSE_OPTION:
945 x.sparse_mode = XARGMATCH ("--sparse", optarg,
946 sparse_type_string, sparse_type);
947 break;
949 case REFLINK_OPTION:
950 if (optarg == NULL)
951 x.reflink_mode = REFLINK_ALWAYS;
952 else
953 x.reflink_mode = XARGMATCH ("--reflink", optarg,
954 reflink_type_string, reflink_type);
955 break;
957 case 'a':
958 /* Like -dR --preserve=all with reduced failure diagnostics. */
959 x.dereference = DEREF_NEVER;
960 x.preserve_links = true;
961 x.preserve_ownership = true;
962 x.preserve_mode = true;
963 x.preserve_timestamps = true;
964 x.require_preserve = true;
965 if (selinux_enabled)
966 x.preserve_security_context = true;
967 x.preserve_xattr = true;
968 x.reduce_diagnostics = true;
969 x.recursive = true;
970 break;
972 case 'b':
973 make_backups = true;
974 if (optarg)
975 version_control_string = optarg;
976 break;
978 case ATTRIBUTES_ONLY_OPTION:
979 x.data_copy_required = false;
980 break;
982 case COPY_CONTENTS_OPTION:
983 copy_contents = true;
984 break;
986 case 'd':
987 x.preserve_links = true;
988 x.dereference = DEREF_NEVER;
989 break;
991 case 'f':
992 x.unlink_dest_after_failed_open = true;
993 break;
995 case 'H':
996 x.dereference = DEREF_COMMAND_LINE_ARGUMENTS;
997 break;
999 case 'i':
1000 x.interactive = I_ASK_USER;
1001 break;
1003 case 'l':
1004 x.hard_link = true;
1005 break;
1007 case 'L':
1008 x.dereference = DEREF_ALWAYS;
1009 break;
1011 case 'n':
1012 x.interactive = I_ALWAYS_NO;
1013 break;
1015 case 'P':
1016 x.dereference = DEREF_NEVER;
1017 break;
1019 case NO_PRESERVE_ATTRIBUTES_OPTION:
1020 decode_preserve_arg (optarg, &x, false);
1021 break;
1023 case PRESERVE_ATTRIBUTES_OPTION:
1024 if (optarg == NULL)
1026 /* Fall through to the case for 'p' below. */
1028 else
1030 decode_preserve_arg (optarg, &x, true);
1031 x.require_preserve = true;
1032 break;
1035 case 'p':
1036 x.preserve_ownership = true;
1037 x.preserve_mode = true;
1038 x.preserve_timestamps = true;
1039 x.require_preserve = true;
1040 break;
1042 case PARENTS_OPTION:
1043 parents_option = true;
1044 break;
1046 case 'r':
1047 case 'R':
1048 x.recursive = true;
1049 break;
1051 case UNLINK_DEST_BEFORE_OPENING:
1052 x.unlink_dest_before_opening = true;
1053 break;
1055 case STRIP_TRAILING_SLASHES_OPTION:
1056 remove_trailing_slashes = true;
1057 break;
1059 case 's':
1060 x.symbolic_link = true;
1061 break;
1063 case 't':
1064 if (target_directory)
1065 error (EXIT_FAILURE, 0,
1066 _("multiple target directories specified"));
1067 else
1069 struct stat st;
1070 if (stat (optarg, &st) != 0)
1071 error (EXIT_FAILURE, errno, _("accessing %s"), quote (optarg));
1072 if (! S_ISDIR (st.st_mode))
1073 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
1074 quote (optarg));
1076 target_directory = optarg;
1077 break;
1079 case 'T':
1080 no_target_directory = true;
1081 break;
1083 case 'u':
1084 x.update = true;
1085 break;
1087 case 'v':
1088 x.verbose = true;
1089 break;
1091 case 'x':
1092 x.one_file_system = true;
1093 break;
1095 case 'S':
1096 make_backups = true;
1097 backup_suffix_string = optarg;
1098 break;
1100 case_GETOPT_HELP_CHAR;
1102 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1104 default:
1105 usage (EXIT_FAILURE);
1109 if (x.hard_link && x.symbolic_link)
1111 error (0, 0, _("cannot make both hard and symbolic links"));
1112 usage (EXIT_FAILURE);
1115 if (make_backups && x.interactive == I_ALWAYS_NO)
1117 error (0, 0,
1118 _("options --backup and --no-clobber are mutually exclusive"));
1119 usage (EXIT_FAILURE);
1122 if (x.reflink_mode == REFLINK_ALWAYS && x.sparse_mode != SPARSE_AUTO)
1124 error (0, 0, _("--reflink can be used only with --sparse=auto"));
1125 usage (EXIT_FAILURE);
1128 if (backup_suffix_string)
1129 simple_backup_suffix = xstrdup (backup_suffix_string);
1131 x.backup_type = (make_backups
1132 ? xget_version (_("backup type"),
1133 version_control_string)
1134 : no_backups);
1136 if (x.dereference == DEREF_UNDEFINED)
1138 if (x.recursive)
1139 /* This is compatible with FreeBSD. */
1140 x.dereference = DEREF_NEVER;
1141 else
1142 x.dereference = DEREF_ALWAYS;
1145 if (x.recursive)
1146 x.copy_as_regular = copy_contents;
1148 /* If --force (-f) was specified and we're in link-creation mode,
1149 first remove any existing destination file. */
1150 if (x.unlink_dest_after_failed_open && (x.hard_link || x.symbolic_link))
1151 x.unlink_dest_before_opening = true;
1153 if (x.preserve_security_context)
1155 if (!selinux_enabled)
1156 error (EXIT_FAILURE, 0,
1157 _("cannot preserve security context "
1158 "without an SELinux-enabled kernel"));
1161 #if !USE_XATTR
1162 if (x.require_preserve_xattr)
1163 error (EXIT_FAILURE, 0, _("cannot preserve extended attributes, cp is "
1164 "built without xattr support"));
1165 #endif
1167 /* Allocate space for remembering copied and created files. */
1169 hash_init ();
1171 ok = do_copy (argc - optind, argv + optind,
1172 target_directory, no_target_directory, &x);
1174 forget_all ();
1176 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);