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