Adjust to backup enum rename.
[platform/upstream/coreutils.git] / src / ln.c
1 /* `ln' program to create links between files.
2    Copyright (C) 86, 89, 90, 91, 1995-2004 Free Software Foundation, Inc.
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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
17 \f
18 /* Written by Mike Parker and David MacKenzie. */
19
20 #include <config.h>
21 #include <stdio.h>
22 #include <sys/types.h>
23 #include <getopt.h>
24
25 #include "system.h"
26 #include "same.h"
27 #include "backupfile.h"
28 #include "dirname.h"
29 #include "error.h"
30 #include "quote.h"
31 #include "yesno.h"
32
33 /* The official name of this program (e.g., no `g' prefix).  */
34 #define PROGRAM_NAME "ln"
35
36 #define AUTHORS "Mike Parker", "David MacKenzie"
37
38 #ifndef ENABLE_HARD_LINK_TO_SYMLINK_WARNING
39 # define ENABLE_HARD_LINK_TO_SYMLINK_WARNING 0
40 #endif
41
42 int link ();                    /* Some systems don't declare this anywhere. */
43
44 #ifdef S_ISLNK
45 int symlink ();
46 #endif
47
48 /* In being careful not even to try to make hard links to directories,
49    we have to know whether link(2) follows symlinks.  If it does, then
50    we have to *stat* the `source' to see if the resulting link would be
51    to a directory.  Otherwise, we have to use *lstat* so that we allow
52    users to make hard links to symlinks-that-point-to-directories.  */
53
54 #if LINK_FOLLOWS_SYMLINKS
55 # define STAT_LIKE_LINK(File, Stat_buf) \
56   stat (File, Stat_buf)
57 #else
58 # define STAT_LIKE_LINK(File, Stat_buf) \
59   lstat (File, Stat_buf)
60 #endif
61
62 /* Construct a string NEW_DEST by concatenating DEST, a slash, and
63    basename(SOURCE) in alloca'd memory.  Don't modify DEST or SOURCE.  */
64
65 #define PATH_BASENAME_CONCAT(new_dest, dest, source)                    \
66     do                                                                  \
67       {                                                                 \
68         const char *source_base;                                        \
69         char *tmp_source;                                               \
70         size_t buf_len = strlen (source) + 1;                           \
71                                                                         \
72         tmp_source = alloca (buf_len);                                  \
73         memcpy (tmp_source, (source), buf_len);                         \
74         strip_trailing_slashes (tmp_source);                            \
75         source_base = base_name (tmp_source);                           \
76                                                                         \
77         (new_dest) = alloca (strlen ((dest)) + 1                        \
78                                       + strlen (source_base) + 1);      \
79         stpcpy (stpcpy (stpcpy ((new_dest), (dest)), "/"), source_base);\
80       }                                                                 \
81     while (0)
82
83 /* The name by which the program was run, for error messages.  */
84 char *program_name;
85
86 /* FIXME: document */
87 static enum backup_type backup_type;
88
89 /* A pointer to the function used to make links.  This will point to either
90    `link' or `symlink'. */
91 static int (*linkfunc) ();
92
93 /* If true, make symbolic links; otherwise, make hard links.  */
94 static bool symbolic_link;
95
96 /* If true, ask the user before removing existing files.  */
97 static bool interactive;
98
99 /* If true, remove existing files unconditionally.  */
100 static bool remove_existing_files;
101
102 /* If true, list each file as it is moved. */
103 static bool verbose;
104
105 /* If true, allow the superuser to *attempt* to make hard links
106    to directories.  However, it appears that this option is not useful
107    in practice, since even the superuser is prohibited from hard-linking
108    directories on most (all?) existing systems.  */
109 static bool hard_dir_link;
110
111 /* If nonzero, and the specified destination is a symbolic link to a
112    directory, treat it just as if it were a directory.  Otherwise, the
113    command `ln --force --no-dereference file symlink-to-dir' deletes
114    symlink-to-dir before creating the new link.  */
115 static bool dereference_dest_dir_symlinks = true;
116
117 static struct option const long_options[] =
118 {
119   {"backup", optional_argument, NULL, 'b'},
120   {"directory", no_argument, NULL, 'F'},
121   {"no-dereference", no_argument, NULL, 'n'},
122   {"no-target-directory", no_argument, NULL, 'T'},
123   {"force", no_argument, NULL, 'f'},
124   {"interactive", no_argument, NULL, 'i'},
125   {"suffix", required_argument, NULL, 'S'},
126   {"target-directory", required_argument, NULL, 't'},
127   {"symbolic", no_argument, NULL, 's'},
128   {"verbose", no_argument, NULL, 'v'},
129   {"version-control", required_argument, NULL, 'V'}, /* Deprecated. FIXME. */
130   {GETOPT_HELP_OPTION_DECL},
131   {GETOPT_VERSION_OPTION_DECL},
132   {NULL, 0, NULL, 0}
133 };
134
135 /* FILE is the last operand of this command.  Return true if FILE is a
136    directory.  But report an error there is a problem accessing FILE,
137    or if FILE does not exist but would have to refer to an existing
138    directory if it referred to anything at all.  */
139
140 static bool
141 target_directory_operand (char const *file)
142 {
143   char const *b = base_name (file);
144   size_t blen = strlen (b);
145   bool looks_like_a_dir = (blen == 0 || ISSLASH (b[blen - 1]));
146   struct stat st;
147   int err = ((dereference_dest_dir_symlinks ? stat : lstat) (file, &st) == 0
148              ? 0 : errno);
149   bool is_a_dir = !err && S_ISDIR (st.st_mode);
150   if (err && err != ENOENT)
151     error (EXIT_FAILURE, err, _("accessing %s"), quote (file));
152   if (is_a_dir < looks_like_a_dir)
153     error (EXIT_FAILURE, err, _("target %s is not a directory"), quote (file));
154   return is_a_dir;
155 }
156
157 /* Make a link DEST to the (usually) existing file SOURCE.
158    Symbolic links to nonexistent files are allowed.
159    If DEST_IS_DIR, put the link to SOURCE in the DEST directory.
160    Return true if successful.  */
161
162 static bool
163 do_link (const char *source, const char *dest, bool dest_is_dir)
164 {
165   struct stat source_stats;
166   struct stat dest_stats;
167   char *dest_backup = NULL;
168   bool lstat_ok = false;
169
170   /* Use stat here instead of lstat.
171      On SVR4, link does not follow symlinks, so this check disallows
172      making hard links to symlinks that point to directories.  Big deal.
173      On other systems, link follows symlinks, so this check is right.  */
174   if (!symbolic_link)
175     {
176       if (STAT_LIKE_LINK (source, &source_stats) != 0)
177         {
178           error (0, errno, _("accessing %s"), quote (source));
179           return false;
180         }
181
182       if (ENABLE_HARD_LINK_TO_SYMLINK_WARNING
183           && S_ISLNK (source_stats.st_mode))
184         {
185           error (0, 0, _("%s: warning: making a hard link to a symbolic link\
186  is not portable"),
187                  quote (source));
188         }
189
190       if (!hard_dir_link && S_ISDIR (source_stats.st_mode))
191         {
192           error (0, 0, _("%s: hard link not allowed for directory"),
193                  quote (source));
194           return false;
195         }
196     }
197
198   if (dest_is_dir)
199     {
200       /* Treat DEST as a directory; build the full filename.  */
201       char *new_dest;
202       PATH_BASENAME_CONCAT (new_dest, dest, source);
203       dest = new_dest;
204     }
205
206   if (remove_existing_files || interactive || backup_type != no_backups)
207     {
208       lstat_ok = (lstat (dest, &dest_stats) == 0);
209       if (!lstat_ok && errno != ENOENT)
210         {
211           error (0, errno, _("accessing %s"), quote (dest));
212           return false;
213         }
214     }
215
216   /* If --force (-f) has been specified without --backup, then before
217      making a link ln must remove the destination file if it exists.
218      (with --backup, it just renames any existing destination file)
219      But if the source and destination are the same, don't remove
220      anything and fail right here.  */
221   if (remove_existing_files
222       && lstat_ok
223       /* Allow `ln -sf --backup k k' to succeed in creating the
224          self-referential symlink, but don't allow the hard-linking
225          equivalent: `ln -f k k' (with or without --backup) to get
226          beyond this point, because the error message you'd get is
227          misleading.  */
228       && (backup_type == no_backups || !symbolic_link)
229       && (!symbolic_link || stat (source, &source_stats) == 0)
230       && SAME_INODE (source_stats, dest_stats)
231       /* The following detects whether removing DEST will also remove
232          SOURCE.  If the file has only one link then both are surely
233          the same link.  Otherwise check whether they point to the same
234          name in the same directory.  */
235       && (source_stats.st_nlink == 1 || same_name (source, dest)))
236     {
237       error (0, 0, _("%s and %s are the same file"),
238              quote_n (0, source), quote_n (1, dest));
239       return false;
240     }
241
242   if (lstat_ok)
243     {
244       if (S_ISDIR (dest_stats.st_mode))
245         {
246           error (0, 0, _("%s: cannot overwrite directory"), quote (dest));
247           return false;
248         }
249       if (interactive)
250         {
251           fprintf (stderr, _("%s: replace %s? "), program_name, quote (dest));
252           if (!yesno ())
253             return true;
254         }
255
256       if (backup_type != no_backups)
257         {
258           char *tmp_backup = find_backup_file_name (dest, backup_type);
259           size_t buf_len = strlen (tmp_backup) + 1;
260           dest_backup = alloca (buf_len);
261           memcpy (dest_backup, tmp_backup, buf_len);
262           free (tmp_backup);
263           if (rename (dest, dest_backup))
264             {
265               if (errno != ENOENT)
266                 {
267                   error (0, errno, _("cannot backup %s"), quote (dest));
268                   return false;
269                 }
270               else
271                 dest_backup = NULL;
272             }
273         }
274     }
275
276   if (verbose)
277     {
278       printf ((symbolic_link
279                ? _("create symbolic link %s to %s")
280                : _("create hard link %s to %s")),
281               quote_n (0, dest), quote_n (1, source));
282       if (dest_backup)
283         printf (_(" (backup: %s)"), quote (dest_backup));
284       putchar ('\n');
285     }
286
287   if ((*linkfunc) (source, dest) == 0)
288     return true;
289
290   /* If the attempt to create a link failed and we are removing or
291      backing up destinations, unlink the destination and try again.
292
293      POSIX 1003.1-2004 requires that ln -f A B must unlink B even on
294      failure (e.g., when A does not exist).  This is counterintuitive,
295      and we submitted a defect report
296      <http://www.opengroup.org/sophocles/show_mail.tpl?source=L&listname=austin-review-l&id=1795>
297      (2004-06-24).  If the committee does not fix the standard we'll
298      have to change the behavior of ln -f, at least if POSIXLY_CORRECT
299      is set.  In the meantime ln -f A B will not unlink B unless the
300      attempt to link A to B failed because B already existed.
301
302      Try to unlink DEST even if we may have backed it up successfully.
303      In some unusual cases (when DEST and DEST_BACKUP are hard-links
304      that refer to the same file), rename succeeds and DEST remains.
305      If we didn't remove DEST in that case, the subsequent LINKFUNC
306      call would fail.  */
307
308   if (errno == EEXIST && (remove_existing_files || dest_backup))
309     {
310       if (unlink (dest) != 0)
311         {
312           error (0, errno, _("cannot remove %s"), quote (dest));
313           return false;
314         }
315
316       if (linkfunc (source, dest) == 0)
317         return true;
318     }
319
320   error (0, errno,
321          (symbolic_link
322           ? _("creating symbolic link %s to %s")
323           : _("creating hard link %s to %s")),
324          quote_n (0, dest), quote_n (1, source));
325
326   if (dest_backup)
327     {
328       if (rename (dest_backup, dest))
329         error (0, errno, _("cannot un-backup %s"), quote (dest));
330     }
331   return false;
332 }
333
334 void
335 usage (int status)
336 {
337   if (status != EXIT_SUCCESS)
338     fprintf (stderr, _("Try `%s --help' for more information.\n"),
339              program_name);
340   else
341     {
342       printf (_("\
343 Usage: %s [OPTION]... [-T] TARGET LINK_NAME   (1st form)\n\
344   or:  %s [OPTION]... TARGET                  (2nd form)\n\
345   or:  %s [OPTION]... TARGET... DIRECTORY     (3rd form)\n\
346   or:  %s [OPTION]... -t DIRECTORY TARGET...  (4th form)\n\
347 "),
348               program_name, program_name, program_name, program_name);
349       fputs (_("\
350 In the 1st form, create a link to TARGET with the name LINK_NAME.\n\
351 In the 2nd form, create a link to TARGET in the current directory.\n\
352 In the 3rd and 4th forms, create links to each TARGET in DIRECTORY.\n\
353 Create hard links by default, symbolic links with --symbolic.\n\
354 When creating hard links, each TARGET must exist.\n\
355 \n\
356 "), stdout);
357       fputs (_("\
358 Mandatory arguments to long options are mandatory for short options too.\n\
359 "), stdout);
360       fputs (_("\
361       --backup[=CONTROL]      make a backup of each existing destination file\n\
362   -b                          like --backup but does not accept an argument\n\
363   -d, -F, --directory         allow the superuser to attempt to hard link\n\
364                                 directories (note: will probably fail due to\n\
365                                 system restrictions, even for the superuser)\n\
366   -f, --force                 remove existing destination files\n\
367 "), stdout);
368       fputs (_("\
369   -n, --no-dereference        treat destination that is a symlink to a\n\
370                                 directory as if it were a normal file\n\
371   -i, --interactive           prompt whether to remove destinations\n\
372   -s, --symbolic              make symbolic links instead of hard links\n\
373 "), stdout);
374       fputs (_("\
375   -S, --suffix=SUFFIX         override the usual backup suffix\n\
376   -t, --target-directory=DIRECTORY  specify the DIRECTORY in which to create\n\
377                                 the links\n\
378   -T, --no-target-directory   treat LINK_NAME as a normal file\n\
379   -v, --verbose               print name of each file before linking\n\
380 "), stdout);
381       fputs (HELP_OPTION_DESCRIPTION, stdout);
382       fputs (VERSION_OPTION_DESCRIPTION, stdout);
383       fputs (_("\
384 \n\
385 The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
386 The version control method may be selected via the --backup option or through\n\
387 the VERSION_CONTROL environment variable.  Here are the values:\n\
388 \n\
389 "), stdout);
390       fputs (_("\
391   none, off       never make backups (even if --backup is given)\n\
392   numbered, t     make numbered backups\n\
393   existing, nil   numbered if numbered backups exist, simple otherwise\n\
394   simple, never   always make simple backups\n\
395 "), stdout);
396       printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
397     }
398   exit (status);
399 }
400
401 int
402 main (int argc, char **argv)
403 {
404   int c;
405   bool ok;
406   bool make_backups = false;
407   char *backup_suffix_string;
408   char *version_control_string = NULL;
409   char *target_directory = NULL;
410   bool no_target_directory = false;
411   int n_files;
412   char **file;
413
414   initialize_main (&argc, &argv);
415   program_name = argv[0];
416   setlocale (LC_ALL, "");
417   bindtextdomain (PACKAGE, LOCALEDIR);
418   textdomain (PACKAGE);
419
420   atexit (close_stdout);
421
422   /* FIXME: consider not calling getenv for SIMPLE_BACKUP_SUFFIX unless
423      we'll actually use backup_suffix_string.  */
424   backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
425
426   symbolic_link = remove_existing_files = interactive = verbose
427     = hard_dir_link = false;
428
429   while ((c = getopt_long (argc, argv, "bdfinst:vFS:TV:", long_options, NULL))
430          != -1)
431     {
432       switch (c)
433         {
434         case 0:                 /* Long-named option. */
435           break;
436
437         case 'V':  /* FIXME: this is deprecated.  Remove it in 2001.  */
438           error (0, 0,
439                  _("warning: --version-control (-V) is obsolete;  support for\
440  it\nwill be removed in some future release.  Use --backup=%s instead."
441                    ), optarg);
442           /* Fall through.  */
443
444         case 'b':
445           make_backups = true;
446           if (optarg)
447             version_control_string = optarg;
448           break;
449         case 'd':
450         case 'F':
451           hard_dir_link = true;
452           break;
453         case 'f':
454           remove_existing_files = true;
455           interactive = false;
456           break;
457         case 'i':
458           remove_existing_files = false;
459           interactive = true;
460           break;
461         case 'n':
462           dereference_dest_dir_symlinks = false;
463           break;
464         case 's':
465 #ifdef S_ISLNK
466           symbolic_link = true;
467 #else
468           error (EXIT_FAILURE, 0,
469                  _("symbolic links are not supported on this system"));
470 #endif
471           break;
472         case 't':
473           if (target_directory)
474             error (EXIT_FAILURE, 0, _("multiple target directories specified"));
475           else
476             {
477               struct stat st;
478               if (stat (optarg, &st) != 0)
479                 error (EXIT_FAILURE, errno, _("accessing %s"), quote (optarg));
480               if (! S_ISDIR (st.st_mode))
481                 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
482                        quote (optarg));
483             }
484           target_directory = optarg;
485           break;
486         case 'T':
487           no_target_directory = true;
488           break;
489         case 'v':
490           verbose = true;
491           break;
492         case 'S':
493           make_backups = true;
494           backup_suffix_string = optarg;
495           break;
496         case_GETOPT_HELP_CHAR;
497         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
498         default:
499           usage (EXIT_FAILURE);
500           break;
501         }
502     }
503
504   n_files = argc - optind;
505   file = argv + optind;
506
507   if (n_files <= 0)
508     {
509       error (0, 0, _("missing file operand"));
510       usage (EXIT_FAILURE);
511     }
512
513   if (no_target_directory)
514     {
515       if (target_directory)
516         error (EXIT_FAILURE, 0,
517                _("Cannot combine --target-directory "
518                  "and --no-target-directory"));
519       if (n_files != 2)
520         {
521           if (n_files < 2)
522             error (0, 0,
523                    _("missing destination file operand after %s"),
524                    quote (file[0]));
525           else
526             error (0, 0, _("extra operand %s"), quote (file[2]));
527           usage (EXIT_FAILURE);
528         }
529     }
530   else if (!target_directory)
531     {
532       if (n_files < 2)
533         target_directory = ".";
534       else if (2 <= n_files && target_directory_operand (file[n_files - 1]))
535         target_directory = file[--n_files];
536       else if (2 < n_files)
537         error (EXIT_FAILURE, 0, _("target %s is not a directory"),
538                quote (file[n_files - 1]));
539     }
540
541   if (symbolic_link)
542     linkfunc = symlink;
543   else
544     linkfunc = link;
545
546   if (backup_suffix_string)
547     simple_backup_suffix = xstrdup (backup_suffix_string);
548
549   backup_type = (make_backups
550                  ? xget_version (_("backup type"), version_control_string)
551                  : no_backups);
552
553   if (target_directory)
554     {
555       int i;
556       ok = true;
557       for (i = 0; i < n_files; ++i)
558         ok &= do_link (file[i], target_directory, true);
559     }
560   else
561     ok = do_link (file[0], file[1], false);
562
563   exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);
564 }