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