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