(main): Using --reply now evokes a warning.
[platform/upstream/coreutils.git] / src / cp.c
1 /* cp.c  -- file copying (main routines)
2    Copyright (C) 89, 90, 91, 1995-2005 Free Software Foundation.
3
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 2, or (at your option)
7    any later version.
8
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.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software Foundation,
16    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17
18    Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. */
19
20 #include <config.h>
21 #include <stdio.h>
22 #include <sys/types.h>
23 #include <assert.h>
24 #include <getopt.h>
25
26 #include "system.h"
27 #include "argmatch.h"
28 #include "backupfile.h"
29 #include "copy.h"
30 #include "cp-hash.h"
31 #include "error.h"
32 #include "dirname.h"
33 #include "filenamecat.h"
34 #include "quote.h"
35 #include "quotearg.h"
36 #include "utimens.h"
37
38 #define ASSIGN_BASENAME_STRDUPA(Dest, File_name)        \
39   do                                                    \
40     {                                                   \
41       char *tmp_abns_;                                  \
42       ASSIGN_STRDUPA (tmp_abns_, (File_name));          \
43       strip_trailing_slashes (tmp_abns_);               \
44       Dest = base_name (tmp_abns_);                     \
45     }                                                   \
46   while (0)
47
48 /* The official name of this program (e.g., no `g' prefix).  */
49 #define PROGRAM_NAME "cp"
50
51 #define AUTHORS "Torbjorn Granlund", "David MacKenzie", "Jim Meyering"
52
53 /* Used by do_copy, make_dir_parents_private, and re_protect
54    to keep a list of leading directories whose protections
55    need to be fixed after copying. */
56 struct dir_attr
57 {
58   bool is_new_dir;
59   size_t slash_offset;
60   struct dir_attr *next;
61 };
62
63 /* For long options that have no equivalent short option, use a
64    non-character as a pseudo short option, starting with CHAR_MAX + 1.  */
65 enum
66 {
67   COPY_CONTENTS_OPTION = CHAR_MAX + 1,
68   NO_PRESERVE_ATTRIBUTES_OPTION,
69   PARENTS_OPTION,
70   PRESERVE_ATTRIBUTES_OPTION,
71   REPLY_OPTION,
72   SPARSE_OPTION,
73   STRIP_TRAILING_SLASHES_OPTION,
74   UNLINK_DEST_BEFORE_OPENING
75 };
76
77 /* Initial number of entries in each hash table entry's table of inodes.  */
78 #define INITIAL_HASH_MODULE 100
79
80 /* Initial number of entries in the inode hash table.  */
81 #define INITIAL_ENTRY_TAB_SIZE 70
82
83 /* The invocation name of this program.  */
84 char *program_name;
85
86 /* If true, the command "cp x/e_file e_dir" uses "e_dir/x/e_file"
87    as its destination instead of the usual "e_dir/e_file." */
88 static bool parents_option = false;
89
90 /* Remove any trailing slashes from each SOURCE argument.  */
91 static bool remove_trailing_slashes;
92
93 static char const *const sparse_type_string[] =
94 {
95   "never", "auto", "always", NULL
96 };
97 static enum Sparse_type const sparse_type[] =
98 {
99   SPARSE_NEVER, SPARSE_AUTO, SPARSE_ALWAYS
100 };
101 ARGMATCH_VERIFY (sparse_type_string, sparse_type);
102
103 /* Valid arguments to the `--reply' option. */
104 static char const* const reply_args[] =
105 {
106   "yes", "no", "query", NULL
107 };
108 /* The values that correspond to the above strings. */
109 static int const reply_vals[] =
110 {
111   I_ALWAYS_YES, I_ALWAYS_NO, I_ASK_USER
112 };
113 ARGMATCH_VERIFY (reply_args, reply_vals);
114
115 static struct option const long_opts[] =
116 {
117   {"archive", no_argument, NULL, 'a'},
118   {"backup", optional_argument, NULL, 'b'},
119   {"copy-contents", no_argument, NULL, COPY_CONTENTS_OPTION},
120   {"dereference", no_argument, NULL, 'L'},
121   {"force", no_argument, NULL, 'f'},
122   {"interactive", no_argument, NULL, 'i'},
123   {"link", no_argument, NULL, 'l'},
124   {"no-dereference", no_argument, NULL, 'P'},
125   {"no-preserve", required_argument, NULL, NO_PRESERVE_ATTRIBUTES_OPTION},
126   {"no-target-directory", no_argument, NULL, 'T'},
127   {"one-file-system", no_argument, NULL, 'x'},
128   {"parents", no_argument, NULL, PARENTS_OPTION},
129   {"path", no_argument, NULL, PARENTS_OPTION},   /* Deprecated.  */
130   {"preserve", optional_argument, NULL, PRESERVE_ATTRIBUTES_OPTION},
131   {"recursive", no_argument, NULL, 'R'},
132   {"remove-destination", no_argument, NULL, UNLINK_DEST_BEFORE_OPENING},
133   {"reply", required_argument, NULL, REPLY_OPTION}, /* Deprecated 2005-07-03,
134                                                        remove in 2008. */
135   {"sparse", required_argument, NULL, SPARSE_OPTION},
136   {"strip-trailing-slashes", no_argument, NULL, STRIP_TRAILING_SLASHES_OPTION},
137   {"suffix", required_argument, NULL, 'S'},
138   {"symbolic-link", no_argument, NULL, 's'},
139   {"target-directory", required_argument, NULL, 't'},
140   {"update", no_argument, NULL, 'u'},
141   {"verbose", no_argument, NULL, 'v'},
142   {GETOPT_HELP_OPTION_DECL},
143   {GETOPT_VERSION_OPTION_DECL},
144   {NULL, 0, NULL, 0}
145 };
146
147 void
148 usage (int status)
149 {
150   if (status != EXIT_SUCCESS)
151     fprintf (stderr, _("Try `%s --help' for more information.\n"),
152              program_name);
153   else
154     {
155       printf (_("\
156 Usage: %s [OPTION]... [-T] SOURCE DEST\n\
157   or:  %s [OPTION]... SOURCE... DIRECTORY\n\
158   or:  %s [OPTION]... -t DIRECTORY SOURCE...\n\
159 "),
160               program_name, program_name, program_name);
161       fputs (_("\
162 Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.\n\
163 \n\
164 "), stdout);
165       fputs (_("\
166 Mandatory arguments to long options are mandatory for short options too.\n\
167 "), stdout);
168       fputs (_("\
169   -a, --archive                same as -dpR\n\
170       --backup[=CONTROL]       make a backup of each existing destination file\n\
171   -b                           like --backup but does not accept an argument\n\
172       --copy-contents          copy contents of special files when recursive\n\
173   -d                           same as --no-dereference --preserve=link\n\
174 "), stdout);
175       fputs (_("\
176   -f, --force                  if an existing destination file cannot be\n\
177                                  opened, remove it and try again\n\
178   -i, --interactive            prompt before overwrite\n\
179   -H                           follow command-line symbolic links\n\
180 "), stdout);
181       fputs (_("\
182   -l, --link                   link files instead of copying\n\
183   -L, --dereference            always follow symbolic links\n\
184 "), stdout);
185       fputs (_("\
186   -P, --no-dereference         never follow symbolic links\n\
187 "), stdout);
188       fputs (_("\
189   -p                           same as --preserve=mode,ownership,timestamps\n\
190       --preserve[=ATTR_LIST]   preserve the specified attributes (default:\n\
191                                  mode,ownership,timestamps), if possible\n\
192                                  additional attributes: links, all\n\
193 "), stdout);
194       fputs (_("\
195       --no-preserve=ATTR_LIST  don't preserve the specified attributes\n\
196       --parents                use full source file name under DIRECTORY\n\
197 "), stdout);
198       fputs (_("\
199   -R, -r, --recursive          copy directories recursively\n\
200       --remove-destination     remove each existing destination file before\n\
201                                  attempting to open it (contrast with --force)\n\
202 "), stdout);
203       fputs (_("\
204       --sparse=WHEN            control creation of sparse files\n\
205       --strip-trailing-slashes remove any trailing slashes from each SOURCE\n\
206                                  argument\n\
207 "), stdout);
208       fputs (_("\
209   -s, --symbolic-link          make symbolic links instead of copying\n\
210   -S, --suffix=SUFFIX          override the usual backup suffix\n\
211   -t, --target-directory=DIRECTORY  copy all SOURCE arguments into DIRECTORY\n\
212   -T, --no-target-directory    treat DEST as a normal file\n\
213 "), stdout);
214       fputs (_("\
215   -u, --update                 copy only when the SOURCE file is newer\n\
216                                  than the destination file or when the\n\
217                                  destination file is missing\n\
218   -v, --verbose                explain what is being done\n\
219   -x, --one-file-system        stay on this file system\n\
220 "), stdout);
221       fputs (HELP_OPTION_DESCRIPTION, stdout);
222       fputs (VERSION_OPTION_DESCRIPTION, stdout);
223       fputs (_("\
224 \n\
225 By default, sparse SOURCE files are detected by a crude heuristic and the\n\
226 corresponding DEST file is made sparse as well.  That is the behavior\n\
227 selected by --sparse=auto.  Specify --sparse=always to create a sparse DEST\n\
228 file whenever the SOURCE file contains a long enough sequence of zero bytes.\n\
229 Use --sparse=never to inhibit creation of sparse files.\n\
230 \n\
231 "), stdout);
232       fputs (_("\
233 The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
234 The version control method may be selected via the --backup option or through\n\
235 the VERSION_CONTROL environment variable.  Here are the values:\n\
236 \n\
237 "), stdout);
238       fputs (_("\
239   none, off       never make backups (even if --backup is given)\n\
240   numbered, t     make numbered backups\n\
241   existing, nil   numbered if numbered backups exist, simple otherwise\n\
242   simple, never   always make simple backups\n\
243 "), stdout);
244       fputs (_("\
245 \n\
246 As a special case, cp makes a backup of SOURCE when the force and backup\n\
247 options are given and SOURCE and DEST are the same name for an existing,\n\
248 regular file.\n\
249 "), stdout);
250       printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
251     }
252   exit (status);
253 }
254
255 /* Ensure that the parent directories of CONST_DST_NAME have the
256    correct protections, for the --parents option.  This is done
257    after all copying has been completed, to allow permissions
258    that don't include user write/execute.
259
260    SRC_OFFSET is the index in CONST_DST_NAME of the beginning of the
261    source directory name.
262
263    ATTR_LIST is a null-terminated linked list of structures that
264    indicates the end of the filename of each intermediate directory
265    in CONST_DST_NAME that may need to have its attributes changed.
266    The command `cp --parents --preserve a/b/c d/e_dir' changes the
267    attributes of the directories d/e_dir/a and d/e_dir/a/b to match
268    the corresponding source directories regardless of whether they
269    existed before the `cp' command was given.
270
271    Return true if the parent of CONST_DST_NAME and any intermediate
272    directories specified by ATTR_LIST have the proper permissions
273    when done.  */
274
275 static bool
276 re_protect (char const *const_dst_name, size_t src_offset,
277             struct dir_attr *attr_list, const struct cp_options *x)
278 {
279   struct dir_attr *p;
280   char *dst_name;               /* A copy of CONST_DST_NAME we can change. */
281   char *src_name;               /* The source name in `dst_name'. */
282
283   ASSIGN_STRDUPA (dst_name, const_dst_name);
284   src_name = dst_name + src_offset;
285
286   for (p = attr_list; p; p = p->next)
287     {
288       struct stat src_sb;
289
290       dst_name[p->slash_offset] = '\0';
291
292       if (XSTAT (x, src_name, &src_sb))
293         {
294           error (0, errno, _("failed to get attributes of %s"),
295                  quote (src_name));
296           return false;
297         }
298
299       /* Adjust the times (and if possible, ownership) for the copy.
300          chown turns off set[ug]id bits for non-root,
301          so do the chmod last.  */
302
303       if (x->preserve_timestamps)
304         {
305           struct timespec timespec[2];
306
307           timespec[0].tv_sec = src_sb.st_atime;
308           timespec[0].tv_nsec = TIMESPEC_NS (src_sb.st_atim);
309           timespec[1].tv_sec = src_sb.st_mtime;
310           timespec[1].tv_nsec = TIMESPEC_NS (src_sb.st_mtim);
311
312           if (utimens (dst_name, timespec))
313             {
314               error (0, errno, _("failed to preserve times for %s"),
315                      quote (dst_name));
316               return false;
317             }
318         }
319
320       if (x->preserve_ownership)
321         {
322           if (chown (dst_name, src_sb.st_uid, src_sb.st_gid) != 0
323               && ! chown_failure_ok (x))
324             {
325               error (0, errno, _("failed to preserve ownership for %s"),
326                      quote (dst_name));
327               return false;
328             }
329         }
330
331       if (x->preserve_mode | p->is_new_dir)
332         {
333           if (chmod (dst_name, src_sb.st_mode & x->umask_kill))
334             {
335               error (0, errno, _("failed to preserve permissions for %s"),
336                      quote (dst_name));
337               return false;
338             }
339         }
340
341       dst_name[p->slash_offset] = '/';
342     }
343   return true;
344 }
345
346 /* Ensure that the parent directory of CONST_DIR exists, for
347    the --parents option.
348
349    SRC_OFFSET is the index in CONST_DIR (which is a destination
350    directory) of the beginning of the source directory name.
351    Create any leading directories that don't already exist,
352    giving them permissions MODE.
353    If VERBOSE_FMT_STRING is nonzero, use it as a printf format
354    string for printing a message after successfully making a directory.
355    The format should take two string arguments: the names of the
356    source and destination directories.
357    Creates a linked list of attributes of intermediate directories,
358    *ATTR_LIST, for re_protect to use after calling copy.
359    Sets *NEW_DST if this function creates parent of CONST_DIR.
360
361    Return true if parent of CONST_DIR exists as a directory with the proper
362    permissions when done.  */
363
364 /* FIXME: Synch this function with the one in ../lib/mkdir-p.c.  */
365
366 static bool
367 make_dir_parents_private (char const *const_dir, size_t src_offset,
368                           mode_t mode, char const *verbose_fmt_string,
369                           struct dir_attr **attr_list, bool *new_dst,
370                           int (*xstat) ())
371 {
372   struct stat stats;
373   char *dir;            /* A copy of CONST_DIR we can change.  */
374   char *src;            /* Source name in DIR.  */
375   char *dst_dir;        /* Leading directory of DIR.  */
376   size_t dirlen;        /* Length of DIR.  */
377
378   ASSIGN_STRDUPA (dir, const_dir);
379
380   src = dir + src_offset;
381
382   dirlen = dir_len (dir);
383   dst_dir = alloca (dirlen + 1);
384   memcpy (dst_dir, dir, dirlen);
385   dst_dir[dirlen] = '\0';
386
387   *attr_list = NULL;
388
389   if ((*xstat) (dst_dir, &stats))
390     {
391       /* A parent of CONST_DIR does not exist.
392          Make all missing intermediate directories. */
393       char *slash;
394
395       slash = src;
396       while (*slash == '/')
397         slash++;
398       while ((slash = strchr (slash, '/')))
399         {
400           /* Add this directory to the list of directories whose modes need
401              fixing later. */
402           struct dir_attr *new = xmalloc (sizeof *new);
403           new->slash_offset = slash - dir;
404           new->next = *attr_list;
405           *attr_list = new;
406
407           *slash = '\0';
408           if ((*xstat) (dir, &stats))
409             {
410               /* This component does not exist.  We must set
411                  *new_dst and new->is_new_dir inside this loop because,
412                  for example, in the command `cp --parents ../a/../b/c e_dir',
413                  make_dir_parents_private creates only e_dir/../a if
414                  ./b already exists. */
415               *new_dst = true;
416               new->is_new_dir = true;
417               if (mkdir (dir, mode))
418                 {
419                   error (0, errno, _("cannot make directory %s"),
420                          quote (dir));
421                   return false;
422                 }
423               else
424                 {
425                   if (verbose_fmt_string != NULL)
426                     printf (verbose_fmt_string, src, dir);
427                 }
428             }
429           else if (!S_ISDIR (stats.st_mode))
430             {
431               error (0, 0, _("%s exists but is not a directory"),
432                      quote (dir));
433               return false;
434             }
435           else
436             {
437               new->is_new_dir = false;
438               *new_dst = false;
439             }
440           *slash++ = '/';
441
442           /* Avoid unnecessary calls to `stat' when given
443              file names containing multiple adjacent slashes.  */
444           while (*slash == '/')
445             slash++;
446         }
447     }
448
449   /* We get here if the parent of DIR already exists.  */
450
451   else if (!S_ISDIR (stats.st_mode))
452     {
453       error (0, 0, _("%s exists but is not a directory"), quote (dst_dir));
454       return false;
455     }
456   else
457     {
458       *new_dst = false;
459     }
460   return true;
461 }
462
463 /* FILE is the last operand of this command.
464    Return true if FILE is a directory.
465    But report an error and exit if there is a problem accessing FILE,
466    or if FILE does not exist but would have to refer to an existing
467    directory if it referred to anything at all.
468
469    If the file exists, store the file's status into *ST.
470    Otherwise, set *NEW_DST.  */
471
472 static bool
473 target_directory_operand (char const *file, struct stat *st, bool *new_dst)
474 {
475   char const *b = base_name (file);
476   size_t blen = strlen (b);
477   bool looks_like_a_dir = (blen == 0 || ISSLASH (b[blen - 1]));
478   int err = (stat (file, st) == 0 ? 0 : errno);
479   bool is_a_dir = !err && S_ISDIR (st->st_mode);
480   if (err)
481     {
482       if (err != ENOENT)
483         error (EXIT_FAILURE, err, _("accessing %s"), quote (file));
484       *new_dst = true;
485     }
486   if (is_a_dir < looks_like_a_dir)
487     error (EXIT_FAILURE, err, _("target %s is not a directory"), quote (file));
488   return is_a_dir;
489 }
490
491 /* Scan the arguments, and copy each by calling copy.
492    Return true if successful.  */
493
494 static bool
495 do_copy (int n_files, char **file, const char *target_directory,
496          bool no_target_directory, struct cp_options *x)
497 {
498   struct stat sb;
499   bool new_dst = false;
500   bool ok = true;
501
502   if (n_files <= !target_directory)
503     {
504       if (n_files <= 0)
505         error (0, 0, _("missing file operand"));
506       else
507         error (0, 0, _("missing destination file operand after %s"),
508                quote (file[0]));
509       usage (EXIT_FAILURE);
510     }
511
512   if (no_target_directory)
513     {
514       if (target_directory)
515         error (EXIT_FAILURE, 0,
516                _("Cannot combine --target-directory (-t) "
517                  "and --no-target-directory (-T)"));
518       if (2 < n_files)
519         {
520           error (0, 0, _("extra operand %s"), quote (file[2]));
521           usage (EXIT_FAILURE);
522         }
523     }
524   else if (!target_directory)
525     {
526       if (2 <= n_files
527           && target_directory_operand (file[n_files - 1], &sb, &new_dst))
528         target_directory = file[--n_files];
529       else if (2 < n_files)
530         error (EXIT_FAILURE, 0, _("target %s is not a directory"),
531                quote (file[n_files - 1]));
532     }
533
534   if (target_directory)
535     {
536       /* cp file1...filen edir
537          Copy the files `file1' through `filen'
538          to the existing directory `edir'. */
539       int i;
540       int (*xstat)() = (x->dereference == DEREF_COMMAND_LINE_ARGUMENTS
541                         || x->dereference == DEREF_ALWAYS
542                         ? stat
543                         : lstat);
544
545       /* Initialize these hash tables only if we'll need them.
546          The problems they're used to detect can arise only if
547          there are two or more files to copy.  */
548       if (2 <= n_files)
549         {
550           dest_info_init (x);
551           src_info_init (x);
552         }
553
554       for (i = 0; i < n_files; i++)
555         {
556           char *dst_name;
557           bool parent_exists = true;  /* True if dir_name (dst_name) exists. */
558           struct dir_attr *attr_list;
559           char *arg_in_concat = NULL;
560           char *arg = file[i];
561
562           /* Trailing slashes are meaningful (i.e., maybe worth preserving)
563              only in the source file names.  */
564           if (remove_trailing_slashes)
565             strip_trailing_slashes (arg);
566
567           if (parents_option)
568             {
569               char *arg_no_trailing_slash;
570
571               /* Use `arg' without trailing slashes in constructing destination
572                  file names.  Otherwise, we can end up trying to create a
573                  directory via `mkdir ("dst/foo/"...', which is not portable.
574                  It fails, due to the trailing slash, on at least
575                  NetBSD 1.[34] systems.  */
576               ASSIGN_STRDUPA (arg_no_trailing_slash, arg);
577               strip_trailing_slashes (arg_no_trailing_slash);
578
579               /* Append all of `arg' (minus any trailing slash) to `dest'.  */
580               dst_name = file_name_concat (target_directory,
581                                            arg_no_trailing_slash,
582                                            &arg_in_concat);
583
584               /* For --parents, we have to make sure that the directory
585                  dir_name (dst_name) exists.  We may have to create a few
586                  leading directories. */
587               parent_exists =
588                 (make_dir_parents_private
589                  (dst_name, arg_in_concat - dst_name, S_IRWXU,
590                   (x->verbose ? "%s -> %s\n" : NULL),
591                   &attr_list, &new_dst, xstat));
592             }
593           else
594             {
595               char *arg_base;
596               /* Append the last component of `arg' to `target_directory'.  */
597
598               ASSIGN_BASENAME_STRDUPA (arg_base, arg);
599               /* For `cp -R source/.. dest', don't copy into `dest/..'. */
600               dst_name = (STREQ (arg_base, "..")
601                           ? xstrdup (target_directory)
602                           : file_name_concat (target_directory, arg_base,
603                                               NULL));
604             }
605
606           if (!parent_exists)
607             {
608               /* make_dir_parents_private failed, so don't even
609                  attempt the copy.  */
610               ok = false;
611             }
612           else
613             {
614               bool copy_into_self;
615               ok &= copy (arg, dst_name, new_dst, x, &copy_into_self, NULL);
616
617               if (parents_option)
618                 ok &= re_protect (dst_name, arg_in_concat - dst_name,
619                                   attr_list, x);
620             }
621
622           free (dst_name);
623         }
624     }
625   else /* !target_directory */
626     {
627       char const *new_dest;
628       char const *source = file[0];
629       char const *dest = file[1];
630       bool unused;
631
632       if (parents_option)
633         {
634           error (0, 0,
635                  _("with --parents, the destination must be a directory"));
636           usage (EXIT_FAILURE);
637         }
638
639       /* When the force and backup options have been specified and
640          the source and destination are the same name for an existing
641          regular file, convert the user's command, e.g.,
642          `cp --force --backup foo foo' to `cp --force foo fooSUFFIX'
643          where SUFFIX is determined by any version control options used.  */
644
645       if (x->unlink_dest_after_failed_open
646           && x->backup_type != no_backups
647           && STREQ (source, dest)
648           && !new_dst && S_ISREG (sb.st_mode))
649         {
650           static struct cp_options x_tmp;
651
652           new_dest = find_backup_file_name (dest, x->backup_type);
653           /* Set x->backup_type to `no_backups' so that the normal backup
654              mechanism is not used when performing the actual copy.
655              backup_type must be set to `no_backups' only *after* the above
656              call to find_backup_file_name -- that function uses
657              backup_type to determine the suffix it applies.  */
658           x_tmp = *x;
659           x_tmp.backup_type = no_backups;
660           x = &x_tmp;
661         }
662       else
663         {
664           new_dest = dest;
665         }
666
667       ok = copy (source, new_dest, 0, x, &unused, NULL);
668     }
669
670   return ok;
671 }
672
673 static void
674 cp_option_init (struct cp_options *x)
675 {
676   x->copy_as_regular = true;
677   x->dereference = DEREF_UNDEFINED;
678   x->unlink_dest_before_opening = false;
679   x->unlink_dest_after_failed_open = false;
680   x->hard_link = false;
681   x->interactive = I_UNSPECIFIED;
682   x->chown_privileges = chown_privileges ();
683   x->move_mode = false;
684   x->one_file_system = false;
685
686   x->preserve_ownership = false;
687   x->preserve_links = false;
688   x->preserve_mode = false;
689   x->preserve_timestamps = false;
690
691   x->require_preserve = false;
692   x->recursive = false;
693   x->sparse_mode = SPARSE_AUTO;
694   x->symbolic_link = false;
695   x->set_mode = false;
696   x->mode = 0;
697
698   /* Not used.  */
699   x->stdin_tty = false;
700
701   /* Find out the current file creation mask, to knock the right bits
702      when using chmod.  The creation mask is set to be liberal, so
703      that created directories can be written, even if it would not
704      have been allowed with the mask this process was started with.  */
705   x->umask_kill = ~ umask (0);
706
707   x->update = false;
708   x->verbose = false;
709   x->dest_info = NULL;
710   x->src_info = NULL;
711 }
712
713 /* Given a string, ARG, containing a comma-separated list of arguments
714    to the --preserve option, set the appropriate fields of X to ON_OFF.  */
715 static void
716 decode_preserve_arg (char const *arg, struct cp_options *x, bool on_off)
717 {
718   enum File_attribute
719     {
720       PRESERVE_MODE,
721       PRESERVE_TIMESTAMPS,
722       PRESERVE_OWNERSHIP,
723       PRESERVE_LINK,
724       PRESERVE_ALL
725     };
726   static enum File_attribute const preserve_vals[] =
727     {
728       PRESERVE_MODE, PRESERVE_TIMESTAMPS,
729       PRESERVE_OWNERSHIP, PRESERVE_LINK, PRESERVE_ALL
730     };
731   /* Valid arguments to the `--preserve' option. */
732   static char const* const preserve_args[] =
733     {
734       "mode", "timestamps",
735       "ownership", "links", "all", NULL
736     };
737   ARGMATCH_VERIFY (preserve_args, preserve_vals);
738
739   char *arg_writable = xstrdup (arg);
740   char *s = arg_writable;
741   do
742     {
743       /* find next comma */
744       char *comma = strchr (s, ',');
745       enum File_attribute val;
746
747       /* If we found a comma, put a NUL in its place and advance.  */
748       if (comma)
749         *comma++ = 0;
750
751       /* process S.  */
752       val = XARGMATCH ("--preserve", s, preserve_args, preserve_vals);
753       switch (val)
754         {
755         case PRESERVE_MODE:
756           x->preserve_mode = on_off;
757           break;
758
759         case PRESERVE_TIMESTAMPS:
760           x->preserve_timestamps = on_off;
761           break;
762
763         case PRESERVE_OWNERSHIP:
764           x->preserve_ownership = on_off;
765           break;
766
767         case PRESERVE_LINK:
768           x->preserve_links = on_off;
769           break;
770
771         case PRESERVE_ALL:
772           x->preserve_mode = on_off;
773           x->preserve_timestamps = on_off;
774           x->preserve_ownership = on_off;
775           x->preserve_links = on_off;
776           break;
777
778         default:
779           abort ();
780         }
781       s = comma;
782     }
783   while (s);
784
785   free (arg_writable);
786 }
787
788 int
789 main (int argc, char **argv)
790 {
791   int c;
792   bool ok;
793   bool make_backups = false;
794   char *backup_suffix_string;
795   char *version_control_string = NULL;
796   struct cp_options x;
797   bool copy_contents = false;
798   char *target_directory = NULL;
799   bool no_target_directory = false;
800
801   initialize_main (&argc, &argv);
802   program_name = argv[0];
803   setlocale (LC_ALL, "");
804   bindtextdomain (PACKAGE, LOCALEDIR);
805   textdomain (PACKAGE);
806
807   atexit (close_stdout);
808
809   cp_option_init (&x);
810
811   /* FIXME: consider not calling getenv for SIMPLE_BACKUP_SUFFIX unless
812      we'll actually use backup_suffix_string.  */
813   backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
814
815   while ((c = getopt_long (argc, argv, "abdfHilLprst:uvxPRS:T",
816                            long_opts, NULL))
817          != -1)
818     {
819       switch (c)
820         {
821         case SPARSE_OPTION:
822           x.sparse_mode = XARGMATCH ("--sparse", optarg,
823                                      sparse_type_string, sparse_type);
824           break;
825
826         case 'a':               /* Like -dpPR. */
827           x.dereference = DEREF_NEVER;
828           x.preserve_links = true;
829           x.preserve_ownership = true;
830           x.preserve_mode = true;
831           x.preserve_timestamps = true;
832           x.require_preserve = true;
833           x.recursive = true;
834           break;
835
836         case 'b':
837           make_backups = true;
838           if (optarg)
839             version_control_string = optarg;
840           break;
841
842         case COPY_CONTENTS_OPTION:
843           copy_contents = true;
844           break;
845
846         case 'd':
847           x.preserve_links = true;
848           x.dereference = DEREF_NEVER;
849           break;
850
851         case 'f':
852           x.unlink_dest_after_failed_open = true;
853           break;
854
855         case 'H':
856           x.dereference = DEREF_COMMAND_LINE_ARGUMENTS;
857           break;
858
859         case 'i':
860           x.interactive = I_ASK_USER;
861           break;
862
863         case 'l':
864           x.hard_link = true;
865           break;
866
867         case 'L':
868           x.dereference = DEREF_ALWAYS;
869           break;
870
871         case 'P':
872           x.dereference = DEREF_NEVER;
873           break;
874
875         case NO_PRESERVE_ATTRIBUTES_OPTION:
876           decode_preserve_arg (optarg, &x, false);
877           break;
878
879         case PRESERVE_ATTRIBUTES_OPTION:
880           if (optarg == NULL)
881             {
882               /* Fall through to the case for `p' below.  */
883             }
884           else
885             {
886               decode_preserve_arg (optarg, &x, true);
887               x.require_preserve = true;
888               break;
889             }
890
891         case 'p':
892           x.preserve_ownership = true;
893           x.preserve_mode = true;
894           x.preserve_timestamps = true;
895           x.require_preserve = true;
896           break;
897
898         case PARENTS_OPTION:
899           parents_option = true;
900           break;
901
902         case 'r':
903         case 'R':
904           x.recursive = true;
905           break;
906
907         case REPLY_OPTION: /* Deprecated */
908           x.interactive = XARGMATCH ("--reply", optarg,
909                                      reply_args, reply_vals);
910           error (0, 0,
911                  _("the --reply option is deprecated; use -i or -f instead"));
912           break;
913
914         case UNLINK_DEST_BEFORE_OPENING:
915           x.unlink_dest_before_opening = true;
916           break;
917
918         case STRIP_TRAILING_SLASHES_OPTION:
919           remove_trailing_slashes = true;
920           break;
921
922         case 's':
923 #ifdef S_ISLNK
924           x.symbolic_link = true;
925 #else
926           error (EXIT_FAILURE, 0,
927                  _("symbolic links are not supported on this system"));
928 #endif
929           break;
930
931         case 't':
932           if (target_directory)
933             error (EXIT_FAILURE, 0,
934                    _("multiple target directories specified"));
935           else
936             {
937               struct stat st;
938               if (stat (optarg, &st) != 0)
939                 error (EXIT_FAILURE, errno, _("accessing %s"), quote (optarg));
940               if (! S_ISDIR (st.st_mode))
941                 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
942                        quote (optarg));
943             }
944           target_directory = optarg;
945           break;
946
947         case 'T':
948           no_target_directory = true;
949           break;
950
951         case 'u':
952           x.update = true;
953           break;
954
955         case 'v':
956           x.verbose = true;
957           break;
958
959         case 'x':
960           x.one_file_system = true;
961           break;
962
963         case 'S':
964           make_backups = true;
965           backup_suffix_string = optarg;
966           break;
967
968         case_GETOPT_HELP_CHAR;
969
970         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
971
972         default:
973           usage (EXIT_FAILURE);
974         }
975     }
976
977   if (x.hard_link & x.symbolic_link)
978     {
979       error (0, 0, _("cannot make both hard and symbolic links"));
980       usage (EXIT_FAILURE);
981     }
982
983   if (backup_suffix_string)
984     simple_backup_suffix = xstrdup (backup_suffix_string);
985
986   x.backup_type = (make_backups
987                    ? xget_version (_("backup type"),
988                                    version_control_string)
989                    : no_backups);
990
991   if (x.preserve_mode)
992     x.umask_kill = ~ (mode_t) 0;
993
994   if (x.dereference == DEREF_UNDEFINED)
995     {
996       if (x.recursive)
997         /* This is compatible with FreeBSD.  */
998         x.dereference = DEREF_NEVER;
999       else
1000         x.dereference = DEREF_ALWAYS;
1001     }
1002
1003   /* The key difference between -d (--no-dereference) and not is the version
1004      of `stat' to call.  */
1005
1006   if (x.recursive)
1007     x.copy_as_regular = copy_contents;
1008
1009   /* If --force (-f) was specified and we're in link-creation mode,
1010      first remove any existing destination file.  */
1011   if (x.unlink_dest_after_failed_open & (x.hard_link | x.symbolic_link))
1012     x.unlink_dest_before_opening = true;
1013
1014   /* Allocate space for remembering copied and created files.  */
1015
1016   hash_init ();
1017
1018   ok = do_copy (argc - optind, argv + optind,
1019                 target_directory, no_target_directory, &x);
1020
1021   forget_all ();
1022
1023   exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);
1024 }