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