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