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