Update FSF postal mail address.
[platform/upstream/coreutils.git] / src / ln.c
1 /* `ln' program to create links between files.
2    Copyright (C) 86, 89, 90, 91, 1995-2004 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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 #include "yesno.h"
32
33 /* The official name of this program (e.g., no `g' prefix).  */
34 #define PROGRAM_NAME "ln"
35
36 #define AUTHORS "Mike Parker", "David MacKenzie"
37
38 #ifndef ENABLE_HARD_LINK_TO_SYMLINK_WARNING
39 # define ENABLE_HARD_LINK_TO_SYMLINK_WARNING 0
40 #endif
41
42 /* In being careful not even to try to make hard links to directories,
43    we have to know whether link(2) follows symlinks.  If it does, then
44    we have to *stat* the `source' to see if the resulting link would be
45    to a directory.  Otherwise, we have to use *lstat* so that we allow
46    users to make hard links to symlinks-that-point-to-directories.  */
47
48 #if LINK_FOLLOWS_SYMLINKS
49 # define STAT_LIKE_LINK(File, Stat_buf) \
50   stat (File, Stat_buf)
51 #else
52 # define STAT_LIKE_LINK(File, Stat_buf) \
53   lstat (File, Stat_buf)
54 #endif
55
56 /* Construct a string NEW_DEST by concatenating DEST, a slash, and
57    basename(SOURCE) in alloca'd memory.  Don't modify DEST or SOURCE.  */
58
59 #define PATH_BASENAME_CONCAT(new_dest, dest, source)                    \
60     do                                                                  \
61       {                                                                 \
62         const char *source_base;                                        \
63         char *tmp_source;                                               \
64         size_t buf_len = strlen (source) + 1;                           \
65                                                                         \
66         tmp_source = alloca (buf_len);                                  \
67         memcpy (tmp_source, (source), buf_len);                         \
68         strip_trailing_slashes (tmp_source);                            \
69         source_base = base_name (tmp_source);                           \
70                                                                         \
71         (new_dest) = alloca (strlen ((dest)) + 1                        \
72                                       + strlen (source_base) + 1);      \
73         stpcpy (stpcpy (stpcpy ((new_dest), (dest)), "/"), source_base);\
74       }                                                                 \
75     while (0)
76
77 /* The name by which the program was run, for error messages.  */
78 char *program_name;
79
80 /* FIXME: document */
81 static enum backup_type backup_type;
82
83 /* A pointer to the function used to make links.  This will point to either
84    `link' or `symlink'. */
85 static int (*linkfunc) ();
86
87 /* If true, make symbolic links; otherwise, make hard links.  */
88 static bool symbolic_link;
89
90 /* If true, ask the user before removing existing files.  */
91 static bool interactive;
92
93 /* If true, remove existing files unconditionally.  */
94 static bool remove_existing_files;
95
96 /* If true, list each file as it is moved. */
97 static bool verbose;
98
99 /* If true, allow the superuser to *attempt* to make hard links
100    to directories.  However, it appears that this option is not useful
101    in practice, since even the superuser is prohibited from hard-linking
102    directories on most (all?) existing systems.  */
103 static bool hard_dir_link;
104
105 /* If nonzero, and the specified destination is a symbolic link to a
106    directory, treat it just as if it were a directory.  Otherwise, the
107    command `ln --force --no-dereference file symlink-to-dir' deletes
108    symlink-to-dir before creating the new link.  */
109 static bool dereference_dest_dir_symlinks = true;
110
111 static struct option const long_options[] =
112 {
113   {"backup", optional_argument, NULL, 'b'},
114   {"directory", no_argument, NULL, 'F'},
115   {"no-dereference", no_argument, NULL, 'n'},
116   {"no-target-directory", no_argument, NULL, 'T'},
117   {"force", no_argument, NULL, 'f'},
118   {"interactive", no_argument, NULL, 'i'},
119   {"suffix", required_argument, NULL, 'S'},
120   {"target-directory", required_argument, NULL, 't'},
121   {"symbolic", no_argument, NULL, 's'},
122   {"verbose", no_argument, NULL, 'v'},
123   {"version-control", required_argument, NULL, 'V'}, /* Deprecated. FIXME. */
124   {GETOPT_HELP_OPTION_DECL},
125   {GETOPT_VERSION_OPTION_DECL},
126   {NULL, 0, NULL, 0}
127 };
128
129 /* FILE is the last operand of this command.  Return true if FILE is a
130    directory.  But report an error there is a problem accessing FILE,
131    or if FILE does not exist but would have to refer to an existing
132    directory if it referred to anything at all.  */
133
134 static bool
135 target_directory_operand (char const *file)
136 {
137   char const *b = base_name (file);
138   size_t blen = strlen (b);
139   bool looks_like_a_dir = (blen == 0 || ISSLASH (b[blen - 1]));
140   struct stat st;
141   int err = ((dereference_dest_dir_symlinks ? stat : lstat) (file, &st) == 0
142              ? 0 : errno);
143   bool is_a_dir = !err && S_ISDIR (st.st_mode);
144   if (err && err != ENOENT)
145     error (EXIT_FAILURE, err, _("accessing %s"), quote (file));
146   if (is_a_dir < looks_like_a_dir)
147     error (EXIT_FAILURE, err, _("target %s is not a directory"), quote (file));
148   return is_a_dir;
149 }
150
151 /* Make a link DEST to the (usually) existing file SOURCE.
152    Symbolic links to nonexistent files are allowed.
153    If DEST_IS_DIR, put the link to SOURCE in the DEST directory.
154    Return true if successful.  */
155
156 static bool
157 do_link (const char *source, const char *dest, bool dest_is_dir)
158 {
159   struct stat source_stats;
160   struct stat dest_stats;
161   char *dest_backup = NULL;
162   bool lstat_ok = false;
163
164   /* Use stat here instead of lstat.
165      On SVR4, link does not follow symlinks, so this check disallows
166      making hard links to symlinks that point to directories.  Big deal.
167      On other systems, link follows symlinks, so this check is right.  */
168   if (!symbolic_link)
169     {
170       if (STAT_LIKE_LINK (source, &source_stats) != 0)
171         {
172           error (0, errno, _("accessing %s"), quote (source));
173           return false;
174         }
175
176       if (ENABLE_HARD_LINK_TO_SYMLINK_WARNING
177           && S_ISLNK (source_stats.st_mode))
178         {
179           error (0, 0, _("%s: warning: making a hard link to a symbolic link\
180  is not portable"),
181                  quote (source));
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"),
187                  quote (source));
188           return false;
189         }
190     }
191
192   if (dest_is_dir)
193     {
194       /* Treat DEST as a directory; build the full filename.  */
195       char *new_dest;
196       PATH_BASENAME_CONCAT (new_dest, dest, source);
197       dest = new_dest;
198     }
199
200   if (remove_existing_files || interactive || backup_type != no_backups)
201     {
202       lstat_ok = (lstat (dest, &dest_stats) == 0);
203       if (!lstat_ok && errno != ENOENT)
204         {
205           error (0, errno, _("accessing %s"), quote (dest));
206           return false;
207         }
208     }
209
210   /* If --force (-f) has been specified without --backup, then before
211      making a link ln must remove the destination file if it exists.
212      (with --backup, it just renames any existing destination file)
213      But if the source and destination are the same, don't remove
214      anything and fail right here.  */
215   if (remove_existing_files
216       && lstat_ok
217       /* Allow `ln -sf --backup k k' to succeed in creating the
218          self-referential symlink, but don't allow the hard-linking
219          equivalent: `ln -f k k' (with or without --backup) to get
220          beyond this point, because the error message you'd get is
221          misleading.  */
222       && (backup_type == no_backups || !symbolic_link)
223       && (!symbolic_link || stat (source, &source_stats) == 0)
224       && SAME_INODE (source_stats, dest_stats)
225       /* The following detects whether removing DEST will also remove
226          SOURCE.  If the file has only one link then both are surely
227          the same link.  Otherwise check whether they point to the same
228          name in the same directory.  */
229       && (source_stats.st_nlink == 1 || same_name (source, dest)))
230     {
231       error (0, 0, _("%s and %s are the same file"),
232              quote_n (0, source), quote_n (1, dest));
233       return false;
234     }
235
236   if (lstat_ok)
237     {
238       if (S_ISDIR (dest_stats.st_mode))
239         {
240           error (0, 0, _("%s: cannot overwrite directory"), quote (dest));
241           return false;
242         }
243       if (interactive)
244         {
245           fprintf (stderr, _("%s: replace %s? "), program_name, quote (dest));
246           if (!yesno ())
247             return true;
248         }
249
250       if (backup_type != no_backups)
251         {
252           char *tmp_backup = find_backup_file_name (dest, backup_type);
253           size_t buf_len = strlen (tmp_backup) + 1;
254           dest_backup = alloca (buf_len);
255           memcpy (dest_backup, tmp_backup, buf_len);
256           free (tmp_backup);
257           if (rename (dest, dest_backup))
258             {
259               if (errno != ENOENT)
260                 {
261                   error (0, errno, _("cannot backup %s"), quote (dest));
262                   return false;
263                 }
264               else
265                 dest_backup = NULL;
266             }
267         }
268     }
269
270   if (verbose)
271     {
272       printf ((symbolic_link
273                ? _("create symbolic link %s to %s")
274                : _("create hard link %s to %s")),
275               quote_n (0, dest), quote_n (1, source));
276       if (dest_backup)
277         printf (_(" (backup: %s)"), quote (dest_backup));
278       putchar ('\n');
279     }
280
281   if ((*linkfunc) (source, dest) == 0)
282     return true;
283
284   /* If the attempt to create a link failed and we are removing or
285      backing up destinations, unlink the destination and try again.
286
287      POSIX 1003.1-2004 requires that ln -f A B must unlink B even on
288      failure (e.g., when A does not exist).  This is counterintuitive,
289      and we submitted a defect report
290      <http://www.opengroup.org/sophocles/show_mail.tpl?source=L&listname=austin-review-l&id=1795>
291      (2004-06-24).  If the committee does not fix the standard we'll
292      have to change the behavior of ln -f, at least if POSIXLY_CORRECT
293      is set.  In the meantime ln -f A B will not unlink B unless the
294      attempt to link A to B failed because B already existed.
295
296      Try to unlink DEST even if we may have backed it up successfully.
297      In some unusual cases (when DEST and DEST_BACKUP are hard-links
298      that refer to the same file), rename succeeds and DEST remains.
299      If we didn't remove DEST in that case, the subsequent LINKFUNC
300      call would fail.  */
301
302   if (errno == EEXIST && (remove_existing_files || dest_backup))
303     {
304       if (unlink (dest) != 0)
305         {
306           error (0, errno, _("cannot remove %s"), quote (dest));
307           return false;
308         }
309
310       if (linkfunc (source, dest) == 0)
311         return true;
312     }
313
314   error (0, errno,
315          (symbolic_link
316           ? _("creating symbolic link %s to %s")
317           : _("creating hard link %s to %s")),
318          quote_n (0, dest), quote_n (1, source));
319
320   if (dest_backup)
321     {
322       if (rename (dest_backup, dest))
323         error (0, errno, _("cannot un-backup %s"), quote (dest));
324     }
325   return false;
326 }
327
328 void
329 usage (int status)
330 {
331   if (status != EXIT_SUCCESS)
332     fprintf (stderr, _("Try `%s --help' for more information.\n"),
333              program_name);
334   else
335     {
336       printf (_("\
337 Usage: %s [OPTION]... [-T] TARGET LINK_NAME   (1st form)\n\
338   or:  %s [OPTION]... TARGET                  (2nd form)\n\
339   or:  %s [OPTION]... TARGET... DIRECTORY     (3rd form)\n\
340   or:  %s [OPTION]... -t DIRECTORY TARGET...  (4th form)\n\
341 "),
342               program_name, program_name, program_name, program_name);
343       fputs (_("\
344 In the 1st form, create a link to TARGET with the name LINK_NAME.\n\
345 In the 2nd form, create a link to TARGET in the current directory.\n\
346 In the 3rd and 4th forms, create links to each TARGET in DIRECTORY.\n\
347 Create hard links by default, symbolic links with --symbolic.\n\
348 When creating hard links, each TARGET must exist.\n\
349 \n\
350 "), stdout);
351       fputs (_("\
352 Mandatory arguments to long options are mandatory for short options too.\n\
353 "), stdout);
354       fputs (_("\
355       --backup[=CONTROL]      make a backup of each existing destination file\n\
356   -b                          like --backup but does not accept an argument\n\
357   -d, -F, --directory         allow the superuser to attempt to hard link\n\
358                                 directories (note: will probably fail due to\n\
359                                 system restrictions, even for the superuser)\n\
360   -f, --force                 remove existing destination files\n\
361 "), stdout);
362       fputs (_("\
363   -n, --no-dereference        treat destination that is a symlink to a\n\
364                                 directory as if it were a normal file\n\
365   -i, --interactive           prompt whether to remove destinations\n\
366   -s, --symbolic              make symbolic links instead of hard links\n\
367 "), stdout);
368       fputs (_("\
369   -S, --suffix=SUFFIX         override the usual backup suffix\n\
370   -t, --target-directory=DIRECTORY  specify the DIRECTORY in which to create\n\
371                                 the links\n\
372   -T, --no-target-directory   treat LINK_NAME as a normal file\n\
373   -v, --verbose               print name of each file before linking\n\
374 "), stdout);
375       fputs (HELP_OPTION_DESCRIPTION, stdout);
376       fputs (VERSION_OPTION_DESCRIPTION, stdout);
377       fputs (_("\
378 \n\
379 The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
380 The version control method may be selected via the --backup option or through\n\
381 the VERSION_CONTROL environment variable.  Here are the values:\n\
382 \n\
383 "), stdout);
384       fputs (_("\
385   none, off       never make backups (even if --backup is given)\n\
386   numbered, t     make numbered backups\n\
387   existing, nil   numbered if numbered backups exist, simple otherwise\n\
388   simple, never   always make simple backups\n\
389 "), stdout);
390       printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
391     }
392   exit (status);
393 }
394
395 int
396 main (int argc, char **argv)
397 {
398   int c;
399   bool ok;
400   bool make_backups = false;
401   char *backup_suffix_string;
402   char *version_control_string = NULL;
403   char *target_directory = NULL;
404   bool no_target_directory = false;
405   int n_files;
406   char **file;
407
408   initialize_main (&argc, &argv);
409   program_name = argv[0];
410   setlocale (LC_ALL, "");
411   bindtextdomain (PACKAGE, LOCALEDIR);
412   textdomain (PACKAGE);
413
414   atexit (close_stdout);
415
416   /* FIXME: consider not calling getenv for SIMPLE_BACKUP_SUFFIX unless
417      we'll actually use backup_suffix_string.  */
418   backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
419
420   symbolic_link = remove_existing_files = interactive = verbose
421     = hard_dir_link = false;
422
423   while ((c = getopt_long (argc, argv, "bdfinst:vFS:TV:", long_options, NULL))
424          != -1)
425     {
426       switch (c)
427         {
428         case 'V':  /* FIXME: this is deprecated.  Remove it in 2001.  */
429           error (0, 0,
430                  _("warning: --version-control (-V) is obsolete;  support for\
431  it\nwill be removed in some future release.  Use --backup=%s instead."
432                    ), optarg);
433           /* Fall through.  */
434
435         case 'b':
436           make_backups = true;
437           if (optarg)
438             version_control_string = optarg;
439           break;
440         case 'd':
441         case 'F':
442           hard_dir_link = true;
443           break;
444         case 'f':
445           remove_existing_files = true;
446           interactive = false;
447           break;
448         case 'i':
449           remove_existing_files = false;
450           interactive = true;
451           break;
452         case 'n':
453           dereference_dest_dir_symlinks = false;
454           break;
455         case 's':
456 #ifdef S_ISLNK
457           symbolic_link = true;
458 #else
459           error (EXIT_FAILURE, 0,
460                  _("symbolic links are not supported on this system"));
461 #endif
462           break;
463         case 't':
464           if (target_directory)
465             error (EXIT_FAILURE, 0, _("multiple target directories specified"));
466           else
467             {
468               struct stat st;
469               if (stat (optarg, &st) != 0)
470                 error (EXIT_FAILURE, errno, _("accessing %s"), quote (optarg));
471               if (! S_ISDIR (st.st_mode))
472                 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
473                        quote (optarg));
474             }
475           target_directory = optarg;
476           break;
477         case 'T':
478           no_target_directory = true;
479           break;
480         case 'v':
481           verbose = true;
482           break;
483         case 'S':
484           make_backups = true;
485           backup_suffix_string = optarg;
486           break;
487         case_GETOPT_HELP_CHAR;
488         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
489         default:
490           usage (EXIT_FAILURE);
491           break;
492         }
493     }
494
495   n_files = argc - optind;
496   file = argv + optind;
497
498   if (n_files <= 0)
499     {
500       error (0, 0, _("missing file operand"));
501       usage (EXIT_FAILURE);
502     }
503
504   if (no_target_directory)
505     {
506       if (target_directory)
507         error (EXIT_FAILURE, 0,
508                _("Cannot combine --target-directory "
509                  "and --no-target-directory"));
510       if (n_files != 2)
511         {
512           if (n_files < 2)
513             error (0, 0,
514                    _("missing destination file operand after %s"),
515                    quote (file[0]));
516           else
517             error (0, 0, _("extra operand %s"), quote (file[2]));
518           usage (EXIT_FAILURE);
519         }
520     }
521   else if (!target_directory)
522     {
523       if (n_files < 2)
524         target_directory = ".";
525       else if (2 <= n_files && target_directory_operand (file[n_files - 1]))
526         target_directory = file[--n_files];
527       else if (2 < n_files)
528         error (EXIT_FAILURE, 0, _("target %s is not a directory"),
529                quote (file[n_files - 1]));
530     }
531
532   if (symbolic_link)
533     linkfunc = symlink;
534   else
535     linkfunc = link;
536
537   if (backup_suffix_string)
538     simple_backup_suffix = xstrdup (backup_suffix_string);
539
540   backup_type = (make_backups
541                  ? xget_version (_("backup type"), version_control_string)
542                  : no_backups);
543
544   if (target_directory)
545     {
546       int i;
547       ok = true;
548       for (i = 0; i < n_files; ++i)
549         ok &= do_link (file[i], target_directory, true);
550     }
551   else
552     ok = do_link (file[0], file[1], false);
553
554   exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);
555 }