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