remove redundant const directives
[platform/upstream/coreutils.git] / src / ln.c
1 /* `ln' program to create links between files.
2    Copyright (C) 1986, 1989-1991, 1995-2008 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 "backupfile.h"
26 #include "error.h"
27 #include "filenamecat.h"
28 #include "file-set.h"
29 #include "hash.h"
30 #include "hash-triple.h"
31 #include "quote.h"
32 #include "same.h"
33 #include "yesno.h"
34
35 /* The official name of this program (e.g., no `g' prefix).  */
36 #define PROGRAM_NAME "ln"
37
38 #define AUTHORS \
39   proper_name ("Mike Parker"), \
40   proper_name ("David MacKenzie")
41
42 #ifndef ENABLE_HARD_LINK_TO_SYMLINK_WARNING
43 # define ENABLE_HARD_LINK_TO_SYMLINK_WARNING 0
44 #endif
45
46 /* In being careful not even to try to make hard links to directories,
47    we have to know whether link(2) follows symlinks.  If it does, then
48    we have to *stat* the `source' to see if the resulting link would be
49    to a directory.  Otherwise, we have to use *lstat* so that we allow
50    users to make hard links to symlinks-that-point-to-directories.  */
51
52 #if LINK_FOLLOWS_SYMLINKS
53 # define STAT_LIKE_LINK(File, Stat_buf) \
54   stat (File, Stat_buf)
55 #else
56 # define STAT_LIKE_LINK(File, Stat_buf) \
57   lstat (File, Stat_buf)
58 #endif
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 /* This is a set of destination name/inode/dev triples for hard links
88    created by ln.  Use this data structure to avoid data loss via a
89    sequence of commands like this:
90    rm -rf a b c; mkdir a b c; touch a/f b/f; ln -f a/f b/f c && rm -r a b */
91 static Hash_table *dest_set;
92
93 /* Initial size of the dest_set hash table.  */
94 enum { DEST_INFO_INITIAL_CAPACITY = 61 };
95
96 static struct option const long_options[] =
97 {
98   {"backup", optional_argument, NULL, 'b'},
99   {"directory", no_argument, NULL, 'F'},
100   {"no-dereference", no_argument, NULL, 'n'},
101   {"no-target-directory", no_argument, NULL, 'T'},
102   {"force", no_argument, NULL, 'f'},
103   {"interactive", no_argument, NULL, 'i'},
104   {"suffix", required_argument, NULL, 'S'},
105   {"target-directory", required_argument, NULL, 't'},
106   {"symbolic", no_argument, NULL, 's'},
107   {"verbose", no_argument, NULL, 'v'},
108   {GETOPT_HELP_OPTION_DECL},
109   {GETOPT_VERSION_OPTION_DECL},
110   {NULL, 0, NULL, 0}
111 };
112
113 /* FILE is the last operand of this command.  Return true if FILE is a
114    directory.  But report an error there is a problem accessing FILE,
115    or if FILE does not exist but would have to refer to an existing
116    directory if it referred to anything at all.  */
117
118 static bool
119 target_directory_operand (char const *file)
120 {
121   char const *b = last_component (file);
122   size_t blen = strlen (b);
123   bool looks_like_a_dir = (blen == 0 || ISSLASH (b[blen - 1]));
124   struct stat st;
125   int stat_result =
126     (dereference_dest_dir_symlinks ? stat (file, &st) : lstat (file, &st));
127   int err = (stat_result == 0 ? 0 : errno);
128   bool is_a_dir = !err && S_ISDIR (st.st_mode);
129   if (err && err != ENOENT)
130     error (EXIT_FAILURE, err, _("accessing %s"), quote (file));
131   if (is_a_dir < looks_like_a_dir)
132     error (EXIT_FAILURE, err, _("target %s is not a directory"), quote (file));
133   return is_a_dir;
134 }
135
136 /* Make a link DEST to the (usually) existing file SOURCE.
137    Symbolic links to nonexistent files are allowed.
138    Return true if successful.  */
139
140 static bool
141 do_link (const char *source, const char *dest)
142 {
143   struct stat source_stats;
144   struct stat dest_stats;
145   char *dest_backup = NULL;
146   bool dest_lstat_ok = false;
147   bool source_is_dir = false;
148   bool ok;
149
150   /* Use stat here instead of lstat.
151      On SVR4, link does not follow symlinks, so this check disallows
152      making hard links to symlinks that point to directories.  Big deal.
153      On other systems, link follows symlinks, so this check is right.  */
154   if (!symbolic_link)
155     {
156       if (STAT_LIKE_LINK (source, &source_stats) != 0)
157         {
158           error (0, errno, _("accessing %s"), quote (source));
159           return false;
160         }
161
162       if (ENABLE_HARD_LINK_TO_SYMLINK_WARNING
163           && S_ISLNK (source_stats.st_mode))
164         {
165           error (0, 0, _("%s: warning: making a hard link to a symbolic link\
166  is not portable"),
167                  quote (source));
168         }
169
170       if (S_ISDIR (source_stats.st_mode))
171         {
172           source_is_dir = true;
173           if (! hard_dir_link)
174             {
175               error (0, 0, _("%s: hard link not allowed for directory"),
176                      quote (source));
177               return false;
178             }
179         }
180     }
181
182   if (remove_existing_files || interactive || backup_type != no_backups)
183     {
184       dest_lstat_ok = (lstat (dest, &dest_stats) == 0);
185       if (!dest_lstat_ok && errno != ENOENT)
186         {
187           error (0, errno, _("accessing %s"), quote (dest));
188           return false;
189         }
190     }
191
192   /* If the current target was created as a hard link to another
193      source file, then refuse to unlink it.  */
194   if (dest_lstat_ok
195       && dest_set != NULL
196       && seen_file (dest_set, dest, &dest_stats))
197     {
198       error (0, 0,
199              _("will not overwrite just-created %s with %s"),
200              quote_n (0, dest), quote_n (1, source));
201       return false;
202     }
203
204   /* If --force (-f) has been specified without --backup, then before
205      making a link ln must remove the destination file if it exists.
206      (with --backup, it just renames any existing destination file)
207      But if the source and destination are the same, don't remove
208      anything and fail right here.  */
209   if ((remove_existing_files
210        /* Ensure that "ln --backup f f" fails here, with the
211           "... same file" diagnostic, below.  Otherwise, subsequent
212           code would give a misleading "file not found" diagnostic.
213           This case is different than the others handled here, since
214           the command in question doesn't use --force.  */
215        || (!symbolic_link && backup_type != no_backups))
216       && dest_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 (dest_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           remove_existing_files = true;
249         }
250
251       if (backup_type != no_backups)
252         {
253           dest_backup = find_backup_file_name (dest, backup_type);
254           if (rename (dest, dest_backup) != 0)
255             {
256               int rename_errno = errno;
257               free (dest_backup);
258               dest_backup = NULL;
259               if (rename_errno != ENOENT)
260                 {
261                   error (0, rename_errno, _("cannot backup %s"), quote (dest));
262                   return false;
263                 }
264             }
265         }
266     }
267
268   ok = ((symbolic_link ? symlink (source, dest) : link (source, dest))
269         == 0);
270
271   /* If the attempt to create a link failed and we are removing or
272      backing up destinations, unlink the destination and try again.
273
274      POSIX 1003.1-2004 requires that ln -f A B must unlink B even on
275      failure (e.g., when A does not exist).  This is counterintuitive,
276      and we submitted a defect report
277      <http://www.opengroup.org/austin/mailarchives/ag-review/msg01794.html>
278      (2004-06-24).  If the committee does not fix the standard we'll
279      have to change the behavior of ln -f, at least if POSIXLY_CORRECT
280      is set.  In the meantime ln -f A B will not unlink B unless the
281      attempt to link A to B failed because B already existed.
282
283      Try to unlink DEST even if we may have backed it up successfully.
284      In some unusual cases (when DEST and DEST_BACKUP are hard-links
285      that refer to the same file), rename succeeds and DEST remains.
286      If we didn't remove DEST in that case, the subsequent symlink or link
287      call would fail.  */
288
289   if (!ok && errno == EEXIST && (remove_existing_files || dest_backup))
290     {
291       if (unlink (dest) != 0)
292         {
293           error (0, errno, _("cannot remove %s"), quote (dest));
294           free (dest_backup);
295           return false;
296         }
297
298       ok = ((symbolic_link ? symlink (source, dest) : link (source, dest))
299             == 0);
300     }
301
302   if (ok)
303     {
304       /* Right after creating a hard link, do this: (note dest name and
305          source_stats, which are also the just-linked-destinations stats) */
306       record_file (dest_set, dest, &source_stats);
307
308       if (verbose)
309         {
310           if (dest_backup)
311             printf ("%s ~ ", quote (dest_backup));
312           printf ("%s %c> %s\n", quote_n (0, dest), (symbolic_link ? '-' : '='),
313                   quote_n (1, source));
314         }
315     }
316   else
317     {
318       error (0, errno,
319              (symbolic_link
320               ? (errno != ENAMETOOLONG && *source
321                  ? _("creating symbolic link %s")
322                  : _("creating symbolic link %s -> %s"))
323               : (errno == EMLINK && !source_is_dir
324                  ? _("creating hard link to %.0s%s")
325                  : (errno == EDQUOT || errno == EEXIST || errno == ENOSPC
326                     || errno == EROFS)
327                  ? _("creating hard link %s")
328                  : _("creating hard link %s => %s"))),
329              quote_n (0, dest), quote_n (1, source));
330
331       if (dest_backup)
332         {
333           if (rename (dest_backup, dest) != 0)
334             error (0, errno, _("cannot un-backup %s"), quote (dest));
335         }
336     }
337
338   free (dest_backup);
339   return ok;
340 }
341
342 void
343 usage (int status)
344 {
345   if (status != EXIT_SUCCESS)
346     fprintf (stderr, _("Try `%s --help' for more information.\n"),
347              program_name);
348   else
349     {
350       printf (_("\
351 Usage: %s [OPTION]... [-T] TARGET LINK_NAME   (1st form)\n\
352   or:  %s [OPTION]... TARGET                  (2nd form)\n\
353   or:  %s [OPTION]... TARGET... DIRECTORY     (3rd form)\n\
354   or:  %s [OPTION]... -t DIRECTORY TARGET...  (4th form)\n\
355 "),
356               program_name, program_name, program_name, program_name);
357       fputs (_("\
358 In the 1st form, create a link to TARGET with the name LINK_NAME.\n\
359 In the 2nd form, create a link to TARGET in the current directory.\n\
360 In the 3rd and 4th forms, create links to each TARGET in DIRECTORY.\n\
361 Create hard links by default, symbolic links with --symbolic.\n\
362 When creating hard links, each TARGET must exist.\n\
363 \n\
364 "), stdout);
365       fputs (_("\
366 Mandatory arguments to long options are mandatory for short options too.\n\
367 "), stdout);
368       fputs (_("\
369       --backup[=CONTROL]      make a backup of each existing destination file\n\
370   -b                          like --backup but does not accept an argument\n\
371   -d, -F, --directory         allow the superuser to attempt to hard link\n\
372                                 directories (note: will probably fail due to\n\
373                                 system restrictions, even for the superuser)\n\
374   -f, --force                 remove existing destination files\n\
375 "), stdout);
376       fputs (_("\
377   -n, --no-dereference        treat destination that is a symlink to a\n\
378                                 directory as if it were a normal file\n\
379   -i, --interactive           prompt whether to remove destinations\n\
380   -s, --symbolic              make symbolic links instead of hard links\n\
381 "), stdout);
382       fputs (_("\
383   -S, --suffix=SUFFIX         override the usual backup suffix\n\
384   -t, --target-directory=DIRECTORY  specify the DIRECTORY in which to create\n\
385                                 the links\n\
386   -T, --no-target-directory   treat LINK_NAME as a normal file\n\
387   -v, --verbose               print name of each linked file\n\
388 "), stdout);
389       fputs (HELP_OPTION_DESCRIPTION, stdout);
390       fputs (VERSION_OPTION_DESCRIPTION, stdout);
391       fputs (_("\
392 \n\
393 The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
394 The version control method may be selected via the --backup option or through\n\
395 the VERSION_CONTROL environment variable.  Here are the values:\n\
396 \n\
397 "), stdout);
398       fputs (_("\
399   none, off       never make backups (even if --backup is given)\n\
400   numbered, t     make numbered backups\n\
401   existing, nil   numbered if numbered backups exist, simple otherwise\n\
402   simple, never   always make simple backups\n\
403 "), stdout);
404       emit_bug_reporting_address ();
405     }
406   exit (status);
407 }
408
409 int
410 main (int argc, char **argv)
411 {
412   int c;
413   bool ok;
414   bool make_backups = false;
415   char *backup_suffix_string;
416   char *version_control_string = NULL;
417   char const *target_directory = NULL;
418   bool no_target_directory = false;
419   int n_files;
420   char **file;
421
422   initialize_main (&argc, &argv);
423   set_program_name (argv[0]);
424   setlocale (LC_ALL, "");
425   bindtextdomain (PACKAGE, LOCALEDIR);
426   textdomain (PACKAGE);
427
428   atexit (close_stdin);
429
430   /* FIXME: consider not calling getenv for SIMPLE_BACKUP_SUFFIX unless
431      we'll actually use backup_suffix_string.  */
432   backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
433
434   symbolic_link = remove_existing_files = interactive = verbose
435     = hard_dir_link = false;
436
437   while ((c = getopt_long (argc, argv, "bdfinst:vFS:T", long_options, NULL))
438          != -1)
439     {
440       switch (c)
441         {
442         case 'b':
443           make_backups = true;
444           if (optarg)
445             version_control_string = optarg;
446           break;
447         case 'd':
448         case 'F':
449           hard_dir_link = true;
450           break;
451         case 'f':
452           remove_existing_files = true;
453           interactive = false;
454           break;
455         case 'i':
456           remove_existing_files = false;
457           interactive = true;
458           break;
459         case 'n':
460           dereference_dest_dir_symlinks = false;
461           break;
462         case 's':
463           symbolic_link = true;
464           break;
465         case 't':
466           if (target_directory)
467             error (EXIT_FAILURE, 0, _("multiple target directories specified"));
468           else
469             {
470               struct stat st;
471               if (stat (optarg, &st) != 0)
472                 error (EXIT_FAILURE, errno, _("accessing %s"), quote (optarg));
473               if (! S_ISDIR (st.st_mode))
474                 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
475                        quote (optarg));
476             }
477           target_directory = optarg;
478           break;
479         case 'T':
480           no_target_directory = true;
481           break;
482         case 'v':
483           verbose = true;
484           break;
485         case 'S':
486           make_backups = true;
487           backup_suffix_string = optarg;
488           break;
489         case_GETOPT_HELP_CHAR;
490         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
491         default:
492           usage (EXIT_FAILURE);
493           break;
494         }
495     }
496
497   n_files = argc - optind;
498   file = argv + optind;
499
500   if (n_files <= 0)
501     {
502       error (0, 0, _("missing file operand"));
503       usage (EXIT_FAILURE);
504     }
505
506   if (no_target_directory)
507     {
508       if (target_directory)
509         error (EXIT_FAILURE, 0,
510                _("cannot combine --target-directory "
511                  "and --no-target-directory"));
512       if (n_files != 2)
513         {
514           if (n_files < 2)
515             error (0, 0,
516                    _("missing destination file operand after %s"),
517                    quote (file[0]));
518           else
519             error (0, 0, _("extra operand %s"), quote (file[2]));
520           usage (EXIT_FAILURE);
521         }
522     }
523   else if (!target_directory)
524     {
525       if (n_files < 2)
526         target_directory = ".";
527       else if (2 <= n_files && target_directory_operand (file[n_files - 1]))
528         target_directory = file[--n_files];
529       else if (2 < n_files)
530         error (EXIT_FAILURE, 0, _("target %s is not a directory"),
531                quote (file[n_files - 1]));
532     }
533
534   if (backup_suffix_string)
535     simple_backup_suffix = xstrdup (backup_suffix_string);
536
537   backup_type = (make_backups
538                  ? xget_version (_("backup type"), version_control_string)
539                  : no_backups);
540
541   if (target_directory)
542     {
543       int i;
544
545       /* Create the data structure we'll use to record which hard links we
546          create.  Used to ensure that ln detects an obscure corner case that
547          might result in user data loss.  Create it only if needed.  */
548       if (2 <= n_files
549           && remove_existing_files
550           /* Don't bother trying to protect symlinks, since ln clobbering
551              a just-created symlink won't ever lead to real data loss.  */
552           && ! symbolic_link
553           /* No destination hard link can be clobbered when making
554              numbered backups.  */
555           && backup_type != numbered_backups)
556
557         {
558           dest_set = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
559                                       NULL,
560                                       triple_hash,
561                                       triple_compare,
562                                       triple_free);
563           if (dest_set == NULL)
564             xalloc_die ();
565         }
566
567       ok = true;
568       for (i = 0; i < n_files; ++i)
569         {
570           char *dest_base;
571           char *dest = file_name_concat (target_directory,
572                                          last_component (file[i]),
573                                          &dest_base);
574           strip_trailing_slashes (dest_base);
575           ok &= do_link (file[i], dest);
576           free (dest);
577         }
578     }
579   else
580     ok = do_link (file[0], file[1]);
581
582   exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);
583 }