(do_link): Allow creation of a hard link to a dangling
[platform/upstream/coreutils.git] / src / ln.c
1 /* `ln' program to create links between files.
2    Copyright (C) 86, 89, 90, 91, 1995-1999 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 "backupfile.h"
31 #include "closeout.h"
32 #include "error.h"
33 #include "dirname.h"
34
35 int link ();                    /* Some systems don't declare this anywhere. */
36
37 #ifdef S_ISLNK
38 int symlink ();
39 #endif
40
41 /* Construct a string NEW_DEST by concatenating DEST, a slash, and
42    basename(SOURCE) in alloca'd memory.  Don't modify DEST or SOURCE.  */
43
44 #define PATH_BASENAME_CONCAT(new_dest, dest, source)                    \
45     do                                                                  \
46       {                                                                 \
47         char *source_base;                                              \
48         char *tmp_source;                                               \
49                                                                         \
50         tmp_source = (char *) alloca (strlen ((source)) + 1);           \
51         strcpy (tmp_source, (source));                                  \
52         strip_trailing_slashes (tmp_source);                            \
53         source_base = base_name (tmp_source);                           \
54                                                                         \
55         (new_dest) = (char *) alloca (strlen ((dest)) + 1               \
56                                       + strlen (source_base) + 1);      \
57         stpcpy (stpcpy (stpcpy ((new_dest), (dest)), "/"), source_base);\
58       }                                                                 \
59     while (0)
60
61 int isdir ();
62 int yesno ();
63 void strip_trailing_slashes ();
64
65 /* The name by which the program was run, for error messages.  */
66 char *program_name;
67
68 /* FIXME: document */
69 enum backup_type backup_type;
70
71 /* A pointer to the function used to make links.  This will point to either
72    `link' or `symlink'. */
73 static int (*linkfunc) ();
74
75 /* If nonzero, make symbolic links; otherwise, make hard links.  */
76 static int symbolic_link;
77
78 /* A string describing type of link to make.  For use in verbose
79    diagnostics and in error messages.  */
80 static const char *link_type_string;
81
82 /* If nonzero, ask the user before removing existing files.  */
83 static int interactive;
84
85 /* If nonzero, remove existing files unconditionally.  */
86 static int remove_existing_files;
87
88 /* If nonzero, list each file as it is moved. */
89 static int verbose;
90
91 /* If nonzero, allow the superuser to make hard links to directories. */
92 static int hard_dir_link;
93
94 /* If nonzero, and the specified destination is a symbolic link to a
95    directory, treat it just as if it were a directory.  Otherwise, the
96    command `ln --force --no-dereference file symlink-to-dir' deletes
97    symlink-to-dir before creating the new link.  */
98 static int dereference_dest_dir_symlinks = 1;
99
100 /* If nonzero, display usage information and exit.  */
101 static int show_help;
102
103 /* If nonzero, print the version on standard output and exit.  */
104 static int show_version;
105
106 static struct option const long_options[] =
107 {
108   {"backup", no_argument, NULL, 'b'},
109   {"directory", no_argument, NULL, 'F'},
110   {"no-dereference", no_argument, NULL, 'n'},
111   {"force", no_argument, NULL, 'f'},
112   {"interactive", no_argument, NULL, 'i'},
113   {"suffix", required_argument, NULL, 'S'},
114   {"symbolic", no_argument, NULL, 's'},
115   {"verbose", no_argument, NULL, 'v'},
116   {"version-control", required_argument, NULL, 'V'},
117   {"help", no_argument, &show_help, 1},
118   {"version", no_argument, &show_version, 1},
119   {NULL, 0, NULL, 0}
120 };
121
122 /* Return nonzero if SOURCE and DEST point to the same name in the same
123    directory.  */
124
125 static int
126 same_name (const char *source, const char *dest)
127 {
128   struct stat source_dir_stats;
129   struct stat dest_dir_stats;
130   char *source_dirname, *dest_dirname;
131
132   source_dirname = dir_name (source);
133   dest_dirname = dir_name (dest);
134   if (source_dirname == NULL || dest_dirname == NULL)
135     error (1, 0, _("virtual memory exhausted"));
136
137   if (stat (source_dirname, &source_dir_stats))
138     {
139       /* Shouldn't happen.  */
140       error (1, errno, "%s", source_dirname);
141     }
142
143   if (stat (dest_dirname, &dest_dir_stats))
144     {
145       /* Shouldn't happen.  */
146       error (1, errno, "%s", dest_dirname);
147     }
148
149   free (source_dirname);
150   free (dest_dirname);
151
152   return (SAME_INODE (source_dir_stats, dest_dir_stats)
153           && STREQ (base_name (source), base_name (dest)));
154 }
155
156 /* Make a link DEST to the (usually) existing file SOURCE.
157    Symbolic links to nonexistent files are allowed.
158    If DEST is a directory, put the link to SOURCE in that directory.
159    Return 1 if there is an error, otherwise 0.  */
160
161 static int
162 do_link (const char *source, const char *dest)
163 {
164   struct stat source_stats;
165   struct stat dest_stats;
166   char *dest_backup = NULL;
167   int lstat_status;
168
169   /* Use stat here instead of lstat.
170      On SVR4, link does not follow symlinks, so this check disallows
171      making hard links to symlinks that point to directories.  Big deal.
172      On other systems, link follows symlinks, so this check is right.  */
173   if (!symbolic_link)
174     {
175       if (stat (source, &source_stats) != 0)
176         {
177           /* This still could be a legitimate request:
178              if SOURCE is a dangling symlink.  */
179           if (errno != ENOENT
180               || lstat (source, &source_stats) != 0)
181             {
182               error (0, errno, "%s", source);
183               return 1;
184             }
185         }
186       if (!hard_dir_link && S_ISDIR (source_stats.st_mode))
187         {
188           error (0, 0, _("%s: hard link not allowed for directory"), source);
189           return 1;
190         }
191     }
192
193   lstat_status = lstat (dest, &dest_stats);
194   if (lstat_status != 0 && errno != ENOENT)
195     {
196       error (0, errno, "%s", dest);
197       return 1;
198     }
199
200   /* If the destination is a directory or (it is a symlink to a directory
201      and the user has not specified --no-dereference), then form the
202      actual destination name by appending base_name (source) to the
203      specified destination directory.  */
204   if ((lstat_status == 0
205        && S_ISDIR (dest_stats.st_mode))
206 #ifdef S_ISLNK
207       || (dereference_dest_dir_symlinks
208           && (lstat_status == 0
209               && S_ISLNK (dest_stats.st_mode)
210               && isdir (dest)))
211 #endif
212      )
213     {
214       /* Target is a directory; build the full filename. */
215       char *new_dest;
216       PATH_BASENAME_CONCAT (new_dest, dest, source);
217       dest = new_dest;
218
219       /* Get stats for new DEST.  */
220       lstat_status = lstat (dest, &dest_stats);
221       if (lstat_status != 0 && errno != ENOENT)
222         {
223           error (0, errno, "%s", dest);
224           return 1;
225         }
226     }
227
228   /* If --force (-f) has been specified without --backup, then before
229      making a link ln must remove the destination file if it exists.
230      (with --backup, it just renames any existing destination file)
231      But if the source and destination are the same, don't remove
232      anything and fail right here.  */
233   if (remove_existing_files
234       && lstat_status == 0
235       /* Allow `ln -sf --backup k k' to succeed in creating the
236          self-referential symlink, but don't allow the hard-linking
237          equivalent: `ln -f k k' (with or without --backup) to get
238          beyond this point, because the error message you'd get is
239          misleading.  */
240       && (backup_type == none || !symlink)
241       && (!symlink || stat (source, &source_stats) == 0)
242       && source_stats.st_dev == dest_stats.st_dev
243       && source_stats.st_ino == dest_stats.st_ino
244       /* The following detects whether removing DEST will also remove
245          SOURCE.  If the file has only one link then both are surely
246          the same link.  Otherwise check whether they point to the same
247          name in the same directory.  */
248       && (source_stats.st_nlink == 1 || same_name (source, dest)))
249     {
250       error (0, 0, _("`%s' and `%s' are the same file"), source, dest);
251       return 1;
252     }
253
254   if (lstat_status == 0 || lstat (dest, &dest_stats) == 0)
255     {
256       if (S_ISDIR (dest_stats.st_mode))
257         {
258           error (0, 0, _("%s: cannot overwrite directory"), dest);
259           return 1;
260         }
261       if (interactive)
262         {
263           fprintf (stderr, _("%s: replace `%s'? "), program_name, dest);
264           if (!yesno ())
265             return 0;
266         }
267       else if (!remove_existing_files && backup_type == none)
268         {
269           error (0, 0, _("%s: File exists"), dest);
270           return 1;
271         }
272
273       if (backup_type != none)
274         {
275           char *tmp_backup = find_backup_file_name (dest, backup_type);
276           if (tmp_backup == NULL)
277             error (1, 0, _("virtual memory exhausted"));
278           dest_backup = (char *) alloca (strlen (tmp_backup) + 1);
279           strcpy (dest_backup, tmp_backup);
280           free (tmp_backup);
281           if (rename (dest, dest_backup))
282             {
283               if (errno != ENOENT)
284                 {
285                   error (0, errno, _("cannot backup `%s'"), dest);
286                   return 1;
287                 }
288               else
289                 dest_backup = NULL;
290             }
291         }
292
293       /* Try to unlink DEST even if we may have renamed it.  In some unusual
294          cases (when DEST and DEST_BACKUP are hard-links that refer to the
295          same file), rename succeeds and DEST remains.  If we didn't remove
296          DEST in that case, the subsequent LINKFUNC call would fail.  */
297       if (unlink (dest) && errno != ENOENT)
298         {
299           error (0, errno, _("cannot remove `%s'"), dest);
300           return 1;
301         }
302     }
303   else if (errno != ENOENT)
304     {
305       error (0, errno, "%s", dest);
306       return 1;
307     }
308
309   if (verbose)
310     printf (_("create %s %s to %s\n"), link_type_string, dest, source);
311
312   if ((*linkfunc) (source, dest) == 0)
313     {
314       return 0;
315     }
316
317   error (0, errno, _("cannot create %s `%s' to `%s'"), link_type_string,
318          dest, source);
319
320   if (dest_backup)
321     {
322       if (rename (dest_backup, dest))
323         error (0, errno, _("cannot un-backup `%s'"), dest);
324     }
325   return 1;
326 }
327
328 void
329 usage (int status)
330 {
331   if (status != 0)
332     fprintf (stderr, _("Try `%s --help' for more information.\n"),
333              program_name);
334   else
335     {
336       printf (_("\
337 Usage: %s [OPTION]... TARGET [LINK_NAME]\n\
338   or:  %s [OPTION]... TARGET... DIRECTORY\n\
339 "),
340               program_name, program_name);
341       printf (_("\
342 Create a link to the specified TARGET with optional LINK_NAME.  If there is\n\
343 more than one TARGET, the last argument must be a directory;  create links\n\
344 in DIRECTORY to each TARGET.  Create hard links by default, symbolic links\n\
345 with --symbolic.  When creating hard links, each TARGET must exist.\n\
346 \n\
347   -b, --backup                make a backup of each existing destination file\n\
348   -d, -F, --directory         hard link directories (super-user only)\n\
349   -f, --force                 remove existing destination files\n\
350   -n, --no-dereference        treat destination that is a symlink to a\n\
351                                 directory as if it were a normal file\n\
352   -i, --interactive           prompt whether to remove destinations\n\
353   -s, --symbolic              make symbolic links instead of hard links\n\
354   -S, --suffix=SUFFIX         override the usual backup suffix\n\
355   -v, --verbose               print name of each file before linking\n\
356   -V, --version-control=WORD  override the usual version control\n\
357       --help                  display this help and exit\n\
358       --version               output version information and exit\n\
359 \n\
360 "));
361       printf (_("\
362 The backup suffix is ~, unless set with SIMPLE_BACKUP_SUFFIX.  The\n\
363 version control may be set with VERSION_CONTROL, values are:\n\
364 \n\
365   none, off       never make backups (even if --backup is given)\n\
366   numbered, t     make numbered backups\n\
367   existing, nil   numbered if numbered backups exist, simple otherwise\n\
368   simple, never   always make simple backups\n\
369 "));
370       puts (_("\nReport bugs to <bug-fileutils@gnu.org>."));
371       close_stdout ();
372     }
373   exit (status);
374 }
375
376 int
377 main (int argc, char **argv)
378 {
379   int c;
380   int errors;
381   int make_backups = 0;
382   char *version;
383
384   program_name = argv[0];
385   setlocale (LC_ALL, "");
386   bindtextdomain (PACKAGE, LOCALEDIR);
387   textdomain (PACKAGE);
388
389   /* FIXME: consider not calling getenv for SIMPLE_BACKUP_SUFFIX unless
390      we'll actually use simple_backup_suffix.  */
391   version = getenv ("SIMPLE_BACKUP_SUFFIX");
392   if (version)
393     simple_backup_suffix = version;
394   version = NULL;
395
396   symbolic_link = remove_existing_files = interactive = verbose
397     = hard_dir_link = 0;
398   errors = 0;
399
400   while ((c = getopt_long (argc, argv, "bdfinsvFS:V:", long_options, NULL))
401          != -1)
402     {
403       switch (c)
404         {
405         case 0:                 /* Long-named option. */
406           break;
407         case 'b':
408           make_backups = 1;
409           break;
410         case 'd':
411         case 'F':
412           hard_dir_link = 1;
413           break;
414         case 'f':
415           remove_existing_files = 1;
416           interactive = 0;
417           break;
418         case 'i':
419           remove_existing_files = 0;
420           interactive = 1;
421           break;
422         case 'n':
423           dereference_dest_dir_symlinks = 0;
424           break;
425         case 's':
426 #ifdef S_ISLNK
427           symbolic_link = 1;
428 #else
429           error (1, 0, _("symbolic links are not supported on this system"));
430 #endif
431           break;
432         case 'v':
433           verbose = 1;
434           break;
435         case 'S':
436           simple_backup_suffix = optarg;
437           break;
438         case 'V':
439           version = optarg;
440           break;
441         default:
442           usage (1);
443           break;
444         }
445     }
446
447   if (show_version)
448     {
449       printf ("ln (%s) %s\n", GNU_PACKAGE, VERSION);
450       close_stdout ();
451       exit (0);
452     }
453
454   if (show_help)
455     usage (0);
456
457   if (optind == argc)
458     {
459       error (0, 0, _("missing file argument"));
460       usage (1);
461     }
462
463   backup_type = (make_backups
464                  ? xget_version (_("--version-control"), version)
465                  : none);
466
467 #ifdef S_ISLNK
468   if (symbolic_link)
469     {
470       linkfunc = symlink;
471       link_type_string = _("symbolic link");
472     }
473   else
474     {
475       linkfunc = link;
476       link_type_string = _("hard link");
477     }
478 #else
479   link_type_string = _("link");
480 #endif
481
482   if (optind == argc - 1)
483     errors = do_link (argv[optind], ".");
484   else if (optind == argc - 2)
485     {
486       struct stat source_stats;
487       char *source;
488       char *dest;
489       char *new_dest;
490
491       source = argv[optind];
492       dest = argv[optind + 1];
493
494       /* When the destination is specified with a trailing slash and the
495          source exists but is not a directory, convert the user's command
496          `ln source dest/' to `ln source dest/basename(source)'.  */
497
498       if (dest[strlen (dest) - 1] == '/'
499           && lstat (source, &source_stats) == 0
500           && !S_ISDIR (source_stats.st_mode))
501         {
502           PATH_BASENAME_CONCAT (new_dest, dest, source);
503         }
504       else
505         {
506           new_dest = dest;
507         }
508
509       errors = do_link (source, new_dest);
510     }
511   else
512     {
513       char *to;
514
515       to = argv[argc - 1];
516       if (!isdir (to))
517         error (1, 0, _("when making multiple links, last argument must be a directory"));
518       for (; optind < argc - 1; ++optind)
519         errors += do_link (argv[optind], to);
520     }
521
522   if (verbose)
523     close_stdout ();
524   exit (errors != 0);
525 }