maint: make update-copyright handle more cases
[coreutils.git] / src / cp.c
blob8785076160ddb941c6ef8dfcfa5ccd9b6213a976
1 /* cp.c -- file copying (main routines)
2 Copyright (C) 89, 90, 91, 1995-2009 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 COPY_CONTENTS_OPTION = CHAR_MAX + 1,
76 NO_PRESERVE_ATTRIBUTES_OPTION,
77 PARENTS_OPTION,
78 PRESERVE_ATTRIBUTES_OPTION,
79 SPARSE_OPTION,
80 STRIP_TRAILING_SLASHES_OPTION,
81 UNLINK_DEST_BEFORE_OPENING
84 /* True if the kernel is SELinux enabled. */
85 static bool selinux_enabled;
87 /* If true, the command "cp x/e_file e_dir" uses "e_dir/x/e_file"
88 as its destination instead of the usual "e_dir/e_file." */
89 static bool parents_option = false;
91 /* Remove any trailing slashes from each SOURCE argument. */
92 static bool remove_trailing_slashes;
94 static char const *const sparse_type_string[] =
96 "never", "auto", "always", NULL
98 static enum Sparse_type const sparse_type[] =
100 SPARSE_NEVER, SPARSE_AUTO, SPARSE_ALWAYS
102 ARGMATCH_VERIFY (sparse_type_string, sparse_type);
104 static struct option const long_opts[] =
106 {"archive", no_argument, NULL, 'a'},
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 {"strip-trailing-slashes", no_argument, NULL, STRIP_TRAILING_SLASHES_OPTION},
125 {"suffix", required_argument, NULL, 'S'},
126 {"symbolic-link", no_argument, NULL, 's'},
127 {"target-directory", required_argument, NULL, 't'},
128 {"update", no_argument, NULL, 'u'},
129 {"verbose", no_argument, NULL, 'v'},
130 {GETOPT_HELP_OPTION_DECL},
131 {GETOPT_VERSION_OPTION_DECL},
132 {NULL, 0, NULL, 0}
135 void
136 usage (int status)
138 if (status != EXIT_SUCCESS)
139 fprintf (stderr, _("Try `%s --help' for more information.\n"),
140 program_name);
141 else
143 printf (_("\
144 Usage: %s [OPTION]... [-T] SOURCE DEST\n\
145 or: %s [OPTION]... SOURCE... DIRECTORY\n\
146 or: %s [OPTION]... -t DIRECTORY SOURCE...\n\
148 program_name, program_name, program_name);
149 fputs (_("\
150 Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.\n\
152 "), stdout);
153 fputs (_("\
154 Mandatory arguments to long options are mandatory for short options too.\n\
155 "), stdout);
156 fputs (_("\
157 -a, --archive same as -dR --preserve=all\n\
158 --backup[=CONTROL] make a backup of each existing destination file\n\
159 -b like --backup but does not accept an argument\n\
160 --copy-contents copy contents of special files when recursive\n\
161 -d same as --no-dereference --preserve=links\n\
162 "), stdout);
163 fputs (_("\
164 -f, --force if an existing destination file cannot be\n\
165 opened, remove it and try again (redundant if\n\
166 the -n option is used)\n\
167 -i, --interactive prompt before overwrite (overrides a previous -n\n\
168 option)\n\
169 -H follow command-line symbolic links in SOURCE\n\
170 "), stdout);
171 fputs (_("\
172 -l, --link link files instead of copying\n\
173 -L, --dereference always follow symbolic links in SOURCE\n\
174 "), stdout);
175 fputs (_("\
176 -n, --no-clobber do not overwrite an existing file (overrides\n\
177 a previous -i option)\n\
178 -P, --no-dereference never follow symbolic links in SOURCE\n\
179 "), stdout);
180 fputs (_("\
181 -p same as --preserve=mode,ownership,timestamps\n\
182 --preserve[=ATTR_LIST] preserve the specified attributes (default:\n\
183 mode,ownership,timestamps), if possible\n\
184 additional attributes: context, links, xattr,\n\
185 all\n\
186 "), stdout);
187 fputs (_("\
188 --no-preserve=ATTR_LIST don't preserve the specified attributes\n\
189 --parents use full source file name under DIRECTORY\n\
190 "), stdout);
191 fputs (_("\
192 -R, -r, --recursive copy directories recursively\n\
193 --remove-destination remove each existing destination file before\n\
194 attempting to open it (contrast with --force)\n\
195 "), stdout);
196 fputs (_("\
197 --sparse=WHEN control creation of sparse files\n\
198 --strip-trailing-slashes remove any trailing slashes from each SOURCE\n\
199 argument\n\
200 "), stdout);
201 fputs (_("\
202 -s, --symbolic-link make symbolic links instead of copying\n\
203 -S, --suffix=SUFFIX override the usual backup suffix\n\
204 -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY\n\
205 -T, --no-target-directory treat DEST as a normal file\n\
206 "), stdout);
207 fputs (_("\
208 -u, --update copy only when the SOURCE file is newer\n\
209 than the destination file or when the\n\
210 destination file is missing\n\
211 -v, --verbose explain what is being done\n\
212 -x, --one-file-system stay on this file system\n\
213 "), stdout);
214 fputs (HELP_OPTION_DESCRIPTION, stdout);
215 fputs (VERSION_OPTION_DESCRIPTION, stdout);
216 fputs (_("\
218 By default, sparse SOURCE files are detected by a crude heuristic and the\n\
219 corresponding DEST file is made sparse as well. That is the behavior\n\
220 selected by --sparse=auto. Specify --sparse=always to create a sparse DEST\n\
221 file whenever the SOURCE file contains a long enough sequence of zero bytes.\n\
222 Use --sparse=never to inhibit creation of sparse files.\n\
223 "), stdout);
224 fputs (_("\
226 The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
227 The version control method may be selected via the --backup option or through\n\
228 the VERSION_CONTROL environment variable. Here are the values:\n\
230 "), stdout);
231 fputs (_("\
232 none, off never make backups (even if --backup is given)\n\
233 numbered, t make numbered backups\n\
234 existing, nil numbered if numbered backups exist, simple otherwise\n\
235 simple, never always make simple backups\n\
236 "), stdout);
237 fputs (_("\
239 As a special case, cp makes a backup of SOURCE when the force and backup\n\
240 options are given and SOURCE and DEST are the same name for an existing,\n\
241 regular file.\n\
242 "), stdout);
243 emit_bug_reporting_address ();
245 exit (status);
248 /* Ensure that the parent directories of CONST_DST_NAME have the
249 correct protections, for the --parents option. This is done
250 after all copying has been completed, to allow permissions
251 that don't include user write/execute.
253 SRC_OFFSET is the index in CONST_DST_NAME of the beginning of the
254 source directory name.
256 ATTR_LIST is a null-terminated linked list of structures that
257 indicates the end of the filename of each intermediate directory
258 in CONST_DST_NAME that may need to have its attributes changed.
259 The command `cp --parents --preserve a/b/c d/e_dir' changes the
260 attributes of the directories d/e_dir/a and d/e_dir/a/b to match
261 the corresponding source directories regardless of whether they
262 existed before the `cp' command was given.
264 Return true if the parent of CONST_DST_NAME and any intermediate
265 directories specified by ATTR_LIST have the proper permissions
266 when done. */
268 static bool
269 re_protect (char const *const_dst_name, size_t src_offset,
270 struct dir_attr *attr_list, const struct cp_options *x)
272 struct dir_attr *p;
273 char *dst_name; /* A copy of CONST_DST_NAME we can change. */
274 char *src_name; /* The source name in `dst_name'. */
276 ASSIGN_STRDUPA (dst_name, const_dst_name);
277 src_name = dst_name + src_offset;
279 for (p = attr_list; p; p = p->next)
281 dst_name[p->slash_offset] = '\0';
283 /* Adjust the times (and if possible, ownership) for the copy.
284 chown turns off set[ug]id bits for non-root,
285 so do the chmod last. */
287 if (x->preserve_timestamps)
289 struct timespec timespec[2];
291 timespec[0] = get_stat_atime (&p->st);
292 timespec[1] = get_stat_mtime (&p->st);
294 if (utimens (dst_name, timespec))
296 error (0, errno, _("failed to preserve times for %s"),
297 quote (dst_name));
298 return false;
302 if (x->preserve_ownership)
304 if (lchown (dst_name, p->st.st_uid, p->st.st_gid) != 0)
306 if (! chown_failure_ok (x))
308 error (0, errno, _("failed to preserve ownership for %s"),
309 quote (dst_name));
310 return false;
312 /* Failing to preserve ownership is OK. Still, try to preserve
313 the group, but ignore the possible error. */
314 ignore_value (lchown (dst_name, -1, p->st.st_gid));
318 if (x->preserve_mode)
320 if (copy_acl (src_name, -1, dst_name, -1, p->st.st_mode) != 0)
321 return false;
323 else if (p->restore_mode)
325 if (lchmod (dst_name, p->st.st_mode) != 0)
327 error (0, errno, _("failed to preserve permissions for %s"),
328 quote (dst_name));
329 return false;
333 dst_name[p->slash_offset] = '/';
335 return true;
338 /* Ensure that the parent directory of CONST_DIR exists, for
339 the --parents option.
341 SRC_OFFSET is the index in CONST_DIR (which is a destination
342 directory) of the beginning of the source directory name.
343 Create any leading directories that don't already exist.
344 If VERBOSE_FMT_STRING is nonzero, use it as a printf format
345 string for printing a message after successfully making a directory.
346 The format should take two string arguments: the names of the
347 source and destination directories.
348 Creates a linked list of attributes of intermediate directories,
349 *ATTR_LIST, for re_protect to use after calling copy.
350 Sets *NEW_DST if this function creates parent of CONST_DIR.
352 Return true if parent of CONST_DIR exists as a directory with the proper
353 permissions when done. */
355 /* FIXME: Synch this function with the one in ../lib/mkdir-p.c. */
357 static bool
358 make_dir_parents_private (char const *const_dir, size_t src_offset,
359 char const *verbose_fmt_string,
360 struct dir_attr **attr_list, bool *new_dst,
361 const struct cp_options *x)
363 struct stat stats;
364 char *dir; /* A copy of CONST_DIR we can change. */
365 char *src; /* Source name in DIR. */
366 char *dst_dir; /* Leading directory of DIR. */
367 size_t dirlen; /* Length of DIR. */
369 ASSIGN_STRDUPA (dir, const_dir);
371 src = dir + src_offset;
373 dirlen = dir_len (dir);
374 dst_dir = alloca (dirlen + 1);
375 memcpy (dst_dir, dir, dirlen);
376 dst_dir[dirlen] = '\0';
378 *attr_list = NULL;
380 if (stat (dst_dir, &stats) != 0)
382 /* A parent of CONST_DIR does not exist.
383 Make all missing intermediate directories. */
384 char *slash;
386 slash = src;
387 while (*slash == '/')
388 slash++;
389 while ((slash = strchr (slash, '/')))
391 struct dir_attr *new IF_LINT (= NULL);
392 bool missing_dir;
394 *slash = '\0';
395 missing_dir = (stat (dir, &stats) != 0);
397 if (missing_dir | x->preserve_ownership | x->preserve_mode
398 | x->preserve_timestamps)
400 /* Add this directory to the list of directories whose
401 modes might need fixing later. */
402 struct stat src_st;
403 int src_errno = (stat (src, &src_st) != 0
404 ? errno
405 : S_ISDIR (src_st.st_mode)
407 : ENOTDIR);
408 if (src_errno)
410 error (0, src_errno, _("failed to get attributes of %s"),
411 quote (src));
412 return false;
415 new = xmalloc (sizeof *new);
416 new->st = src_st;
417 new->slash_offset = slash - dir;
418 new->restore_mode = false;
419 new->next = *attr_list;
420 *attr_list = new;
423 if (missing_dir)
425 mode_t src_mode;
426 mode_t omitted_permissions;
427 mode_t mkdir_mode;
429 /* This component does not exist. We must set
430 *new_dst and new->st.st_mode inside this loop because,
431 for example, in the command `cp --parents ../a/../b/c e_dir',
432 make_dir_parents_private creates only e_dir/../a if
433 ./b already exists. */
434 *new_dst = true;
435 src_mode = new->st.st_mode;
437 /* If the ownership or special mode bits might change,
438 omit some permissions at first, so unauthorized users
439 cannot nip in before the file is ready. */
440 omitted_permissions = (src_mode
441 & (x->preserve_ownership
442 ? S_IRWXG | S_IRWXO
443 : x->preserve_mode
444 ? S_IWGRP | S_IWOTH
445 : 0));
447 /* POSIX says mkdir's behavior is implementation-defined when
448 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
449 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
450 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
451 mkdir_mode = src_mode & CHMOD_MODE_BITS & ~omitted_permissions;
452 if (mkdir (dir, mkdir_mode) != 0)
454 error (0, errno, _("cannot make directory %s"),
455 quote (dir));
456 return false;
458 else
460 if (verbose_fmt_string != NULL)
461 printf (verbose_fmt_string, src, dir);
464 /* We need search and write permissions to the new directory
465 for writing the directory's contents. Check if these
466 permissions are there. */
468 if (lstat (dir, &stats))
470 error (0, errno, _("failed to get attributes of %s"),
471 quote (dir));
472 return false;
476 if (! x->preserve_mode)
478 if (omitted_permissions & ~stats.st_mode)
479 omitted_permissions &= ~ cached_umask ();
480 if (omitted_permissions & ~stats.st_mode
481 || (stats.st_mode & S_IRWXU) != S_IRWXU)
483 new->st.st_mode = stats.st_mode | omitted_permissions;
484 new->restore_mode = true;
488 if ((stats.st_mode & S_IRWXU) != S_IRWXU)
490 /* Make the new directory searchable and writable.
491 The original permissions will be restored later. */
493 if (lchmod (dir, stats.st_mode | S_IRWXU) != 0)
495 error (0, errno, _("setting permissions for %s"),
496 quote (dir));
497 return false;
501 else if (!S_ISDIR (stats.st_mode))
503 error (0, 0, _("%s exists but is not a directory"),
504 quote (dir));
505 return false;
507 else
508 *new_dst = false;
509 *slash++ = '/';
511 /* Avoid unnecessary calls to `stat' when given
512 file names containing multiple adjacent slashes. */
513 while (*slash == '/')
514 slash++;
518 /* We get here if the parent of DIR already exists. */
520 else if (!S_ISDIR (stats.st_mode))
522 error (0, 0, _("%s exists but is not a directory"), quote (dst_dir));
523 return false;
525 else
527 *new_dst = false;
529 return true;
532 /* FILE is the last operand of this command.
533 Return true if FILE is a directory.
534 But report an error and exit if there is a problem accessing FILE,
535 or if FILE does not exist but would have to refer to an existing
536 directory if it referred to anything at all.
538 If the file exists, store the file's status into *ST.
539 Otherwise, set *NEW_DST. */
541 static bool
542 target_directory_operand (char const *file, struct stat *st, bool *new_dst)
544 int err = (stat (file, st) == 0 ? 0 : errno);
545 bool is_a_dir = !err && S_ISDIR (st->st_mode);
546 if (err)
548 if (err != ENOENT)
549 error (EXIT_FAILURE, err, _("accessing %s"), quote (file));
550 *new_dst = true;
552 return is_a_dir;
555 /* Scan the arguments, and copy each by calling copy.
556 Return true if successful. */
558 static bool
559 do_copy (int n_files, char **file, const char *target_directory,
560 bool no_target_directory, struct cp_options *x)
562 struct stat sb;
563 bool new_dst = false;
564 bool ok = true;
566 if (n_files <= !target_directory)
568 if (n_files <= 0)
569 error (0, 0, _("missing file operand"));
570 else
571 error (0, 0, _("missing destination file operand after %s"),
572 quote (file[0]));
573 usage (EXIT_FAILURE);
576 if (no_target_directory)
578 if (target_directory)
579 error (EXIT_FAILURE, 0,
580 _("cannot combine --target-directory (-t) "
581 "and --no-target-directory (-T)"));
582 if (2 < n_files)
584 error (0, 0, _("extra operand %s"), quote (file[2]));
585 usage (EXIT_FAILURE);
588 else if (!target_directory)
590 if (2 <= n_files
591 && target_directory_operand (file[n_files - 1], &sb, &new_dst))
592 target_directory = file[--n_files];
593 else if (2 < n_files)
594 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
595 quote (file[n_files - 1]));
598 if (target_directory)
600 /* cp file1...filen edir
601 Copy the files `file1' through `filen'
602 to the existing directory `edir'. */
603 int i;
605 /* Initialize these hash tables only if we'll need them.
606 The problems they're used to detect can arise only if
607 there are two or more files to copy. */
608 if (2 <= n_files)
610 dest_info_init (x);
611 src_info_init (x);
614 for (i = 0; i < n_files; i++)
616 char *dst_name;
617 bool parent_exists = true; /* True if dir_name (dst_name) exists. */
618 struct dir_attr *attr_list;
619 char *arg_in_concat = NULL;
620 char *arg = file[i];
622 /* Trailing slashes are meaningful (i.e., maybe worth preserving)
623 only in the source file names. */
624 if (remove_trailing_slashes)
625 strip_trailing_slashes (arg);
627 if (parents_option)
629 char *arg_no_trailing_slash;
631 /* Use `arg' without trailing slashes in constructing destination
632 file names. Otherwise, we can end up trying to create a
633 directory via `mkdir ("dst/foo/"...', which is not portable.
634 It fails, due to the trailing slash, on at least
635 NetBSD 1.[34] systems. */
636 ASSIGN_STRDUPA (arg_no_trailing_slash, arg);
637 strip_trailing_slashes (arg_no_trailing_slash);
639 /* Append all of `arg' (minus any trailing slash) to `dest'. */
640 dst_name = file_name_concat (target_directory,
641 arg_no_trailing_slash,
642 &arg_in_concat);
644 /* For --parents, we have to make sure that the directory
645 dir_name (dst_name) exists. We may have to create a few
646 leading directories. */
647 parent_exists =
648 (make_dir_parents_private
649 (dst_name, arg_in_concat - dst_name,
650 (x->verbose ? "%s -> %s\n" : NULL),
651 &attr_list, &new_dst, x));
653 else
655 char *arg_base;
656 /* Append the last component of `arg' to `target_directory'. */
658 ASSIGN_BASENAME_STRDUPA (arg_base, arg);
659 /* For `cp -R source/.. dest', don't copy into `dest/..'. */
660 dst_name = (STREQ (arg_base, "..")
661 ? xstrdup (target_directory)
662 : file_name_concat (target_directory, arg_base,
663 NULL));
666 if (!parent_exists)
668 /* make_dir_parents_private failed, so don't even
669 attempt the copy. */
670 ok = false;
672 else
674 bool copy_into_self;
675 ok &= copy (arg, dst_name, new_dst, x, &copy_into_self, NULL);
677 if (parents_option)
678 ok &= re_protect (dst_name, arg_in_concat - dst_name,
679 attr_list, x);
682 if (parents_option)
684 while (attr_list)
686 struct dir_attr *p = attr_list;
687 attr_list = attr_list->next;
688 free (p);
692 free (dst_name);
695 else /* !target_directory */
697 char const *new_dest;
698 char const *source = file[0];
699 char const *dest = file[1];
700 bool unused;
702 if (parents_option)
704 error (0, 0,
705 _("with --parents, the destination must be a directory"));
706 usage (EXIT_FAILURE);
709 /* When the force and backup options have been specified and
710 the source and destination are the same name for an existing
711 regular file, convert the user's command, e.g.,
712 `cp --force --backup foo foo' to `cp --force foo fooSUFFIX'
713 where SUFFIX is determined by any version control options used. */
715 if (x->unlink_dest_after_failed_open
716 && x->backup_type != no_backups
717 && STREQ (source, dest)
718 && !new_dst && S_ISREG (sb.st_mode))
720 static struct cp_options x_tmp;
722 new_dest = find_backup_file_name (dest, x->backup_type);
723 /* Set x->backup_type to `no_backups' so that the normal backup
724 mechanism is not used when performing the actual copy.
725 backup_type must be set to `no_backups' only *after* the above
726 call to find_backup_file_name -- that function uses
727 backup_type to determine the suffix it applies. */
728 x_tmp = *x;
729 x_tmp.backup_type = no_backups;
730 x = &x_tmp;
732 else
734 new_dest = dest;
737 ok = copy (source, new_dest, 0, x, &unused, NULL);
740 return ok;
743 static void
744 cp_option_init (struct cp_options *x)
746 cp_options_default (x);
747 x->copy_as_regular = true;
748 x->dereference = DEREF_UNDEFINED;
749 x->unlink_dest_before_opening = false;
750 x->unlink_dest_after_failed_open = false;
751 x->hard_link = false;
752 x->interactive = I_UNSPECIFIED;
753 x->move_mode = false;
754 x->one_file_system = false;
756 x->preserve_ownership = false;
757 x->preserve_links = false;
758 x->preserve_mode = false;
759 x->preserve_timestamps = false;
760 x->preserve_security_context = false;
761 x->require_preserve_context = false;
762 x->preserve_xattr = false;
763 x->reduce_diagnostics = false;
764 x->require_preserve_xattr = false;
766 x->require_preserve = false;
767 x->recursive = false;
768 x->sparse_mode = SPARSE_AUTO;
769 x->symbolic_link = false;
770 x->set_mode = false;
771 x->mode = 0;
773 /* Not used. */
774 x->stdin_tty = false;
776 x->update = false;
777 x->verbose = false;
779 /* By default, refuse to open a dangling destination symlink, because
780 in general one cannot do that safely, give the current semantics of
781 open's O_EXCL flag, (which POSIX doesn't even allow cp to use, btw).
782 But POSIX requires it. */
783 x->open_dangling_dest_symlink = getenv ("POSIXLY_CORRECT") != NULL;
785 x->dest_info = NULL;
786 x->src_info = NULL;
789 /* Given a string, ARG, containing a comma-separated list of arguments
790 to the --preserve option, set the appropriate fields of X to ON_OFF. */
791 static void
792 decode_preserve_arg (char const *arg, struct cp_options *x, bool on_off)
794 enum File_attribute
796 PRESERVE_MODE,
797 PRESERVE_TIMESTAMPS,
798 PRESERVE_OWNERSHIP,
799 PRESERVE_LINK,
800 PRESERVE_CONTEXT,
801 PRESERVE_XATTR,
802 PRESERVE_ALL
804 static enum File_attribute const preserve_vals[] =
806 PRESERVE_MODE, PRESERVE_TIMESTAMPS,
807 PRESERVE_OWNERSHIP, PRESERVE_LINK, PRESERVE_CONTEXT, PRESERVE_XATTR,
808 PRESERVE_ALL
810 /* Valid arguments to the `--preserve' option. */
811 static char const* const preserve_args[] =
813 "mode", "timestamps",
814 "ownership", "links", "context", "xattr", "all", NULL
816 ARGMATCH_VERIFY (preserve_args, preserve_vals);
818 char *arg_writable = xstrdup (arg);
819 char *s = arg_writable;
822 /* find next comma */
823 char *comma = strchr (s, ',');
824 enum File_attribute val;
826 /* If we found a comma, put a NUL in its place and advance. */
827 if (comma)
828 *comma++ = 0;
830 /* process S. */
831 val = XARGMATCH ("--preserve", s, preserve_args, preserve_vals);
832 switch (val)
834 case PRESERVE_MODE:
835 x->preserve_mode = on_off;
836 break;
838 case PRESERVE_TIMESTAMPS:
839 x->preserve_timestamps = on_off;
840 break;
842 case PRESERVE_OWNERSHIP:
843 x->preserve_ownership = on_off;
844 break;
846 case PRESERVE_LINK:
847 x->preserve_links = on_off;
848 break;
850 case PRESERVE_CONTEXT:
851 x->preserve_security_context = on_off;
852 x->require_preserve_context = on_off;
853 break;
855 case PRESERVE_XATTR:
856 x->preserve_xattr = on_off;
857 x->require_preserve_xattr = on_off;
858 break;
860 case PRESERVE_ALL:
861 x->preserve_mode = on_off;
862 x->preserve_timestamps = on_off;
863 x->preserve_ownership = on_off;
864 x->preserve_links = on_off;
865 if (selinux_enabled)
866 x->preserve_security_context = on_off;
867 x->preserve_xattr = on_off;
868 break;
870 default:
871 abort ();
873 s = comma;
875 while (s);
877 free (arg_writable);
881 main (int argc, char **argv)
883 int c;
884 bool ok;
885 bool make_backups = false;
886 char *backup_suffix_string;
887 char *version_control_string = NULL;
888 struct cp_options x;
889 bool copy_contents = false;
890 char *target_directory = NULL;
891 bool no_target_directory = false;
893 initialize_main (&argc, &argv);
894 set_program_name (argv[0]);
895 setlocale (LC_ALL, "");
896 bindtextdomain (PACKAGE, LOCALEDIR);
897 textdomain (PACKAGE);
899 atexit (close_stdin);
901 selinux_enabled = (0 < is_selinux_enabled ());
902 cp_option_init (&x);
904 /* FIXME: consider not calling getenv for SIMPLE_BACKUP_SUFFIX unless
905 we'll actually use backup_suffix_string. */
906 backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
908 while ((c = getopt_long (argc, argv, "abdfHilLnprst:uvxPRS:T",
909 long_opts, NULL))
910 != -1)
912 switch (c)
914 case SPARSE_OPTION:
915 x.sparse_mode = XARGMATCH ("--sparse", optarg,
916 sparse_type_string, sparse_type);
917 break;
919 case 'a': /* Like -dR --preserve=all with reduced failure diagnostics. */
920 x.dereference = DEREF_NEVER;
921 x.preserve_links = true;
922 x.preserve_ownership = true;
923 x.preserve_mode = true;
924 x.preserve_timestamps = true;
925 x.require_preserve = true;
926 if (selinux_enabled)
927 x.preserve_security_context = true;
928 x.preserve_xattr = true;
929 x.reduce_diagnostics = true;
930 x.recursive = true;
931 break;
933 case 'b':
934 make_backups = true;
935 if (optarg)
936 version_control_string = optarg;
937 break;
939 case COPY_CONTENTS_OPTION:
940 copy_contents = true;
941 break;
943 case 'd':
944 x.preserve_links = true;
945 x.dereference = DEREF_NEVER;
946 break;
948 case 'f':
949 x.unlink_dest_after_failed_open = true;
950 break;
952 case 'H':
953 x.dereference = DEREF_COMMAND_LINE_ARGUMENTS;
954 break;
956 case 'i':
957 x.interactive = I_ASK_USER;
958 break;
960 case 'l':
961 x.hard_link = true;
962 break;
964 case 'L':
965 x.dereference = DEREF_ALWAYS;
966 break;
968 case 'n':
969 x.interactive = I_ALWAYS_NO;
970 break;
972 case 'P':
973 x.dereference = DEREF_NEVER;
974 break;
976 case NO_PRESERVE_ATTRIBUTES_OPTION:
977 decode_preserve_arg (optarg, &x, false);
978 break;
980 case PRESERVE_ATTRIBUTES_OPTION:
981 if (optarg == NULL)
983 /* Fall through to the case for `p' below. */
985 else
987 decode_preserve_arg (optarg, &x, true);
988 x.require_preserve = true;
989 break;
992 case 'p':
993 x.preserve_ownership = true;
994 x.preserve_mode = true;
995 x.preserve_timestamps = true;
996 x.require_preserve = true;
997 break;
999 case PARENTS_OPTION:
1000 parents_option = true;
1001 break;
1003 case 'r':
1004 case 'R':
1005 x.recursive = true;
1006 break;
1008 case UNLINK_DEST_BEFORE_OPENING:
1009 x.unlink_dest_before_opening = true;
1010 break;
1012 case STRIP_TRAILING_SLASHES_OPTION:
1013 remove_trailing_slashes = true;
1014 break;
1016 case 's':
1017 x.symbolic_link = true;
1018 break;
1020 case 't':
1021 if (target_directory)
1022 error (EXIT_FAILURE, 0,
1023 _("multiple target directories specified"));
1024 else
1026 struct stat st;
1027 if (stat (optarg, &st) != 0)
1028 error (EXIT_FAILURE, errno, _("accessing %s"), quote (optarg));
1029 if (! S_ISDIR (st.st_mode))
1030 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
1031 quote (optarg));
1033 target_directory = optarg;
1034 break;
1036 case 'T':
1037 no_target_directory = true;
1038 break;
1040 case 'u':
1041 x.update = true;
1042 break;
1044 case 'v':
1045 x.verbose = true;
1046 break;
1048 case 'x':
1049 x.one_file_system = true;
1050 break;
1052 case 'S':
1053 make_backups = true;
1054 backup_suffix_string = optarg;
1055 break;
1057 case_GETOPT_HELP_CHAR;
1059 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1061 default:
1062 usage (EXIT_FAILURE);
1066 if (x.hard_link & x.symbolic_link)
1068 error (0, 0, _("cannot make both hard and symbolic links"));
1069 usage (EXIT_FAILURE);
1072 if (make_backups && x.interactive == I_ALWAYS_NO)
1074 error (0, 0,
1075 _("options --backup and --no-clobber are mutually exclusive"));
1076 usage (EXIT_FAILURE);
1079 if (backup_suffix_string)
1080 simple_backup_suffix = xstrdup (backup_suffix_string);
1082 x.backup_type = (make_backups
1083 ? xget_version (_("backup type"),
1084 version_control_string)
1085 : no_backups);
1087 if (x.dereference == DEREF_UNDEFINED)
1089 if (x.recursive)
1090 /* This is compatible with FreeBSD. */
1091 x.dereference = DEREF_NEVER;
1092 else
1093 x.dereference = DEREF_ALWAYS;
1096 if (x.recursive)
1097 x.copy_as_regular = copy_contents;
1099 /* If --force (-f) was specified and we're in link-creation mode,
1100 first remove any existing destination file. */
1101 if (x.unlink_dest_after_failed_open & (x.hard_link | x.symbolic_link))
1102 x.unlink_dest_before_opening = true;
1104 if (x.preserve_security_context)
1106 if (!selinux_enabled)
1107 error (EXIT_FAILURE, 0,
1108 _("cannot preserve security context "
1109 "without an SELinux-enabled kernel"));
1112 #if !USE_XATTR
1113 if (x.require_preserve_xattr)
1114 error (EXIT_FAILURE, 0, _("cannot preserve extended attributes, cp is "
1115 "built without xattr support"));
1116 #endif
1118 /* Allocate space for remembering copied and created files. */
1120 hash_init ();
1122 ok = do_copy (argc - optind, argv + optind,
1123 target_directory, no_target_directory, &x);
1125 forget_all ();
1127 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);