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