(ENABLE_HARD_LINK_TO_SYMLINK_WARNING): Define to 0.
[platform/upstream/coreutils.git] / src / ln.c
1 /* `ln' program to create links between files.
2    Copyright (C) 86, 89, 90, 91, 1995-2003 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 #ifdef _AIX
21  #pragma alloca
22 #endif
23
24 #include <config.h>
25 #include <stdio.h>
26 #include <sys/types.h>
27 #include <getopt.h>
28
29 #include "system.h"
30 #include "same.h"
31 #include "backupfile.h"
32 #include "dirname.h"
33 #include "error.h"
34 #include "quote.h"
35
36 /* The official name of this program (e.g., no `g' prefix).  */
37 #define PROGRAM_NAME "ln"
38
39 #define AUTHORS N_ ("Mike Parker and David MacKenzie")
40
41 #ifndef ENABLE_HARD_LINK_TO_SYMLINK_WARNING
42 # define ENABLE_HARD_LINK_TO_SYMLINK_WARNING 0
43 #endif
44
45 /* For long options that have no equivalent short option, use a
46    non-character as a pseudo short option, starting with CHAR_MAX + 1.  */
47 enum
48 {
49   TARGET_DIRECTORY_OPTION = CHAR_MAX + 1
50 };
51
52 int link ();                    /* Some systems don't declare this anywhere. */
53
54 #ifdef S_ISLNK
55 int symlink ();
56 #endif
57
58 /* In being careful not even to try to make hard links to directories,
59    we have to know whether link(2) follows symlinks.  If it does, then
60    we have to *stat* the `source' to see if the resulting link would be
61    to a directory.  Otherwise, we have to use *lstat* so that we allow
62    users to make hard links to symlinks-that-point-to-directories.  */
63
64 #if LINK_FOLLOWS_SYMLINKS
65 # define STAT_LIKE_LINK(File, Stat_buf) \
66   stat (File, Stat_buf)
67 #else
68 # define STAT_LIKE_LINK(File, Stat_buf) \
69   lstat (File, Stat_buf)
70 #endif
71
72 /* Construct a string NEW_DEST by concatenating DEST, a slash, and
73    basename(SOURCE) in alloca'd memory.  Don't modify DEST or SOURCE.  */
74
75 #define PATH_BASENAME_CONCAT(new_dest, dest, source)                    \
76     do                                                                  \
77       {                                                                 \
78         const char *source_base;                                        \
79         char *tmp_source;                                               \
80                                                                         \
81         tmp_source = (char *) alloca (strlen ((source)) + 1);           \
82         strcpy (tmp_source, (source));                                  \
83         strip_trailing_slashes (tmp_source);                            \
84         source_base = base_name (tmp_source);                           \
85                                                                         \
86         (new_dest) = (char *) alloca (strlen ((dest)) + 1               \
87                                       + strlen (source_base) + 1);      \
88         stpcpy (stpcpy (stpcpy ((new_dest), (dest)), "/"), source_base);\
89       }                                                                 \
90     while (0)
91
92 int isdir ();
93 int yesno ();
94
95 /* The name by which the program was run, for error messages.  */
96 char *program_name;
97
98 /* FIXME: document */
99 enum backup_type backup_type;
100
101 /* A pointer to the function used to make links.  This will point to either
102    `link' or `symlink'. */
103 static int (*linkfunc) ();
104
105 /* If nonzero, make symbolic links; otherwise, make hard links.  */
106 static int symbolic_link;
107
108 /* If nonzero, ask the user before removing existing files.  */
109 static int interactive;
110
111 /* If nonzero, remove existing files unconditionally.  */
112 static int remove_existing_files;
113
114 /* If nonzero, list each file as it is moved. */
115 static int verbose;
116
117 /* If nonzero, allow the superuser to make hard links to directories. */
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       && source_stats.st_dev == dest_stats.st_dev
235       && source_stats.st_ino == dest_stats.st_ino
236       /* The following detects whether removing DEST will also remove
237          SOURCE.  If the file has only one link then both are surely
238          the same link.  Otherwise check whether they point to the same
239          name in the same directory.  */
240       && (source_stats.st_nlink == 1 || same_name (source, dest)))
241     {
242       error (0, 0, _("%s and %s are the same file"),
243              quote_n (0, source), quote_n (1, dest));
244       return 1;
245     }
246
247   if (lstat_status == 0 || lstat (dest, &dest_stats) == 0)
248     {
249       if (S_ISDIR (dest_stats.st_mode))
250         {
251           error (0, 0, _("%s: cannot overwrite directory"), quote (dest));
252           return 1;
253         }
254       if (interactive)
255         {
256           fprintf (stderr, _("%s: replace %s? "), program_name, quote (dest));
257           if (!yesno ())
258             return 0;
259         }
260       else if (!remove_existing_files && backup_type == none)
261         {
262           error (0, 0, _("%s: File exists"), quote (dest));
263           return 1;
264         }
265
266       if (backup_type != none)
267         {
268           char *tmp_backup = find_backup_file_name (dest, backup_type);
269           if (tmp_backup == NULL)
270             xalloc_die ();
271           dest_backup = (char *) alloca (strlen (tmp_backup) + 1);
272           strcpy (dest_backup, tmp_backup);
273           free (tmp_backup);
274           if (rename (dest, dest_backup))
275             {
276               if (errno != ENOENT)
277                 {
278                   error (0, errno, _("cannot backup %s"), quote (dest));
279                   return 1;
280                 }
281               else
282                 dest_backup = NULL;
283             }
284           else
285             {
286               backup_succeeded = 1;
287             }
288         }
289
290       /* Try to unlink DEST even if we may have renamed it.  In some unusual
291          cases (when DEST and DEST_BACKUP are hard-links that refer to the
292          same file), rename succeeds and DEST remains.  If we didn't remove
293          DEST in that case, the subsequent LINKFUNC call would fail.  */
294       if (unlink (dest) && errno != ENOENT)
295         {
296           error (0, errno, _("cannot remove %s"), quote (dest));
297           return 1;
298         }
299     }
300   else if (errno != ENOENT)
301     {
302       error (0, errno, _("accessing %s"), quote (dest));
303       return 1;
304     }
305
306   if (verbose)
307     {
308       printf ((symbolic_link
309                ? _("create symbolic link %s to %s")
310                : _("create hard link %s to %s")),
311               quote_n (0, dest), quote_n (1, source));
312       if (backup_succeeded)
313         printf (_(" (backup: %s)"), quote (dest_backup));
314       putchar ('\n');
315     }
316
317   if ((*linkfunc) (source, dest) == 0)
318     {
319       return 0;
320     }
321
322   error (0, errno,
323          (symbolic_link
324           ? _("creating symbolic link %s to %s")
325           : _("creating hard link %s to %s")),
326          quote_n (0, dest), quote_n (1, source));
327
328   if (dest_backup)
329     {
330       if (rename (dest_backup, dest))
331         error (0, errno, _("cannot un-backup %s"), quote (dest));
332     }
333   return 1;
334 }
335
336 void
337 usage (int status)
338 {
339   if (status != 0)
340     fprintf (stderr, _("Try `%s --help' for more information.\n"),
341              program_name);
342   else
343     {
344       printf (_("\
345 Usage: %s [OPTION]... TARGET [LINK_NAME]\n\
346   or:  %s [OPTION]... TARGET... DIRECTORY\n\
347   or:  %s [OPTION]... --target-directory=DIRECTORY TARGET...\n\
348 "),
349               program_name, program_name, program_name);
350       fputs (_("\
351 Create a link to the specified TARGET with optional LINK_NAME.\n\
352 If LINK_NAME is omitted, a link with the same basename as the TARGET is\n\
353 created in the current directory.  When using the second form with more\n\
354 than one TARGET, the last argument must be a directory;  create links\n\
355 in DIRECTORY to each TARGET.  Create hard links by default, symbolic\n\
356 links with --symbolic.  When creating hard links, each TARGET must exist.\n\
357 \n\
358 "), stdout);
359       fputs (_("\
360 Mandatory arguments to long options are mandatory for short options too.\n\
361 "), stdout);
362       fputs (_("\
363       --backup[=CONTROL]      make a backup of each existing destination file\n\
364   -b                          like --backup but does not accept an argument\n\
365   -d, -F, --directory         hard link directories (super-user only)\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       --target-directory=DIRECTORY  specify the DIRECTORY in which to create\n\
377                                 the links\n\
378   -v, --verbose               print name of each file before linking\n\
379 "), stdout);
380       fputs (HELP_OPTION_DESCRIPTION, stdout);
381       fputs (VERSION_OPTION_DESCRIPTION, stdout);
382       fputs (_("\
383 \n\
384 The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
385 The version control method may be selected via the --backup option or through\n\
386 the VERSION_CONTROL environment variable.  Here are the values:\n\
387 \n\
388 "), stdout);
389       fputs (_("\
390   none, off       never make backups (even if --backup is given)\n\
391   numbered, t     make numbered backups\n\
392   existing, nil   numbered if numbered backups exist, simple otherwise\n\
393   simple, never   always make simple backups\n\
394 "), stdout);
395       printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
396     }
397   exit (status);
398 }
399
400 int
401 main (int argc, char **argv)
402 {
403   int c;
404   int errors;
405   int make_backups = 0;
406   char *backup_suffix_string;
407   char *version_control_string = NULL;
408   char *target_directory = NULL;
409   int target_directory_specified;
410   unsigned int n_files;
411   char **file;
412   int dest_is_dir;
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 = 0;
428   errors = 0;
429
430   while ((c = getopt_long (argc, argv, "bdfinsvFS:V:", long_options, NULL))
431          != -1)
432     {
433       switch (c)
434         {
435         case 0:                 /* Long-named option. */
436           break;
437
438         case 'V':  /* FIXME: this is deprecated.  Remove it in 2001.  */
439           error (0, 0,
440                  _("warning: --version-control (-V) is obsolete;  support for\
441  it\nwill be removed in some future release.  Use --backup=%s instead."
442                    ), optarg);
443           /* Fall through.  */
444
445         case 'b':
446           make_backups = 1;
447           if (optarg)
448             version_control_string = optarg;
449           break;
450         case 'd':
451         case 'F':
452           hard_dir_link = 1;
453           break;
454         case 'f':
455           remove_existing_files = 1;
456           interactive = 0;
457           break;
458         case 'i':
459           remove_existing_files = 0;
460           interactive = 1;
461           break;
462         case 'n':
463           dereference_dest_dir_symlinks = 0;
464           break;
465         case 's':
466 #ifdef S_ISLNK
467           symbolic_link = 1;
468 #else
469           error (EXIT_FAILURE, 0,
470                  _("symbolic links are not supported on this system"));
471 #endif
472           break;
473         case TARGET_DIRECTORY_OPTION:
474           target_directory = optarg;
475           break;
476         case 'v':
477           verbose = 1;
478           break;
479         case 'S':
480           make_backups = 1;
481           backup_suffix_string = optarg;
482           break;
483         case_GETOPT_HELP_CHAR;
484         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
485         default:
486           usage (EXIT_FAILURE);
487           break;
488         }
489     }
490
491   if (argc <= optind)
492     {
493       error (0, 0, _("missing file argument"));
494       usage (EXIT_FAILURE);
495     }
496
497   n_files = argc - optind;
498   file = argv + optind;
499
500   target_directory_specified = (target_directory != NULL);
501   if (!target_directory)
502     target_directory = file[n_files - 1];
503
504   /* If target directory is not specified, and there's only one
505      file argument, then pretend `.' was given as the second argument.  */
506   if (!target_directory_specified && n_files == 1)
507     {
508       static char *dummy[2];
509       dummy[0] = file[0];
510       dummy[1] = ".";
511       file = dummy;
512       n_files = 2;
513       dest_is_dir = 1;
514     }
515   else
516     {
517       dest_is_dir = isdir (target_directory);
518     }
519
520   if (symbolic_link)
521     linkfunc = symlink;
522   else
523     linkfunc = link;
524
525   if (target_directory_specified && !dest_is_dir)
526     {
527       error (0, 0, _("%s: specified target directory is not a directory"),
528              quote (target_directory));
529       usage (EXIT_FAILURE);
530     }
531
532   if (backup_suffix_string)
533     simple_backup_suffix = xstrdup (backup_suffix_string);
534
535   backup_type = (make_backups
536                  ? xget_version (_("backup type"), version_control_string)
537                  : none);
538
539   if (target_directory_specified || n_files > 2)
540     {
541       unsigned int i;
542       unsigned int last_file_idx = (target_directory_specified
543                                     ? n_files - 1
544                                     : n_files - 2);
545
546       if (!target_directory_specified && !dest_is_dir)
547         error (EXIT_FAILURE, 0,
548            _("when making multiple links, last argument must be a directory"));
549       for (i = 0; i <= last_file_idx; ++i)
550         errors += do_link (file[i], target_directory);
551     }
552   else
553     {
554       struct stat source_stats;
555       const char *source;
556       char *dest;
557       char *new_dest;
558
559       source = file[0];
560       dest = file[1];
561
562       /* When the destination is specified with a trailing slash and the
563          source exists but is not a directory, convert the user's command
564          `ln source dest/' to `ln source dest/basename(source)'.  */
565
566       if (dest[strlen (dest) - 1] == '/'
567           && lstat (source, &source_stats) == 0
568           && !S_ISDIR (source_stats.st_mode))
569         {
570           PATH_BASENAME_CONCAT (new_dest, dest, source);
571         }
572       else
573         {
574           new_dest = dest;
575         }
576
577       errors = do_link (source, new_dest);
578     }
579
580   exit (errors != 0);
581 }