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