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