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