doc: improve various BLOCKSIZE and SIZE help
[coreutils.git] / src / ln.c
blob6a1dc32077bfa7642bb1e0e28a7eea5c13b7c2d5
1 /* `ln' program to create links between files.
2 Copyright (C) 1986, 1989-1991, 1995-2009 Free Software Foundation, Inc.
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.
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.
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/>. */
17 /* Written by Mike Parker and David MacKenzie. */
19 #include <config.h>
20 #include <stdio.h>
21 #include <sys/types.h>
22 #include <getopt.h>
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"
35 /* The official name of this program (e.g., no `g' prefix). */
36 #define PROGRAM_NAME "ln"
38 #define AUTHORS \
39 proper_name ("Mike Parker"), \
40 proper_name ("David MacKenzie")
42 /* In being careful not even to try to make hard links to directories,
43 we have to know whether link(2) follows symlinks. If it does, then
44 we have to *stat* the `source' to see if the resulting link would be
45 to a directory. Otherwise, we have to use *lstat* so that we allow
46 users to make hard links to symlinks-that-point-to-directories. */
48 #if LINK_FOLLOWS_SYMLINKS
49 # define STAT_LIKE_LINK(File, Stat_buf) \
50 stat (File, Stat_buf)
51 #else
52 # define STAT_LIKE_LINK(File, Stat_buf) \
53 lstat (File, Stat_buf)
54 #endif
56 /* FIXME: document */
57 static enum backup_type backup_type;
59 /* If true, make symbolic links; otherwise, make hard links. */
60 static bool symbolic_link;
62 /* If true, ask the user before removing existing files. */
63 static bool interactive;
65 /* If true, remove existing files unconditionally. */
66 static bool remove_existing_files;
68 /* If true, list each file as it is moved. */
69 static bool verbose;
71 /* If true, allow the superuser to *attempt* to make hard links
72 to directories. However, it appears that this option is not useful
73 in practice, since even the superuser is prohibited from hard-linking
74 directories on most (all?) existing systems. */
75 static bool hard_dir_link;
77 /* If nonzero, and the specified destination is a symbolic link to a
78 directory, treat it just as if it were a directory. Otherwise, the
79 command `ln --force --no-dereference file symlink-to-dir' deletes
80 symlink-to-dir before creating the new link. */
81 static bool dereference_dest_dir_symlinks = true;
83 /* This is a set of destination name/inode/dev triples for hard links
84 created by ln. Use this data structure to avoid data loss via a
85 sequence of commands like this:
86 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 */
87 static Hash_table *dest_set;
89 /* Initial size of the dest_set hash table. */
90 enum { DEST_INFO_INITIAL_CAPACITY = 61 };
92 static struct option const long_options[] =
94 {"backup", optional_argument, NULL, 'b'},
95 {"directory", no_argument, NULL, 'F'},
96 {"no-dereference", no_argument, NULL, 'n'},
97 {"no-target-directory", no_argument, NULL, 'T'},
98 {"force", no_argument, NULL, 'f'},
99 {"interactive", no_argument, NULL, 'i'},
100 {"suffix", required_argument, NULL, 'S'},
101 {"target-directory", required_argument, NULL, 't'},
102 {"symbolic", no_argument, NULL, 's'},
103 {"verbose", no_argument, NULL, 'v'},
104 {GETOPT_HELP_OPTION_DECL},
105 {GETOPT_VERSION_OPTION_DECL},
106 {NULL, 0, NULL, 0}
109 /* FILE is the last operand of this command. Return true if FILE is a
110 directory. But report an error there is a problem accessing FILE,
111 or if FILE does not exist but would have to refer to an existing
112 directory if it referred to anything at all. */
114 static bool
115 target_directory_operand (char const *file)
117 char const *b = last_component (file);
118 size_t blen = strlen (b);
119 bool looks_like_a_dir = (blen == 0 || ISSLASH (b[blen - 1]));
120 struct stat st;
121 int stat_result =
122 (dereference_dest_dir_symlinks ? stat (file, &st) : lstat (file, &st));
123 int err = (stat_result == 0 ? 0 : errno);
124 bool is_a_dir = !err && S_ISDIR (st.st_mode);
125 if (err && err != ENOENT)
126 error (EXIT_FAILURE, err, _("accessing %s"), quote (file));
127 if (is_a_dir < looks_like_a_dir)
128 error (EXIT_FAILURE, err, _("target %s is not a directory"), quote (file));
129 return is_a_dir;
132 /* Make a link DEST to the (usually) existing file SOURCE.
133 Symbolic links to nonexistent files are allowed.
134 Return true if successful. */
136 static bool
137 do_link (const char *source, const char *dest)
139 struct stat source_stats;
140 struct stat dest_stats;
141 char *dest_backup = NULL;
142 bool dest_lstat_ok = false;
143 bool source_is_dir = false;
144 bool ok;
146 /* Use stat here instead of lstat.
147 On SVR4, link does not follow symlinks, so this check disallows
148 making hard links to symlinks that point to directories. Big deal.
149 On other systems, link follows symlinks, so this check is right.
151 FIXME - POSIX 2008 added the AT_SYMLINK_FOLLOW flag to linkat so
152 that we can specify either behavior, via the new options -L
153 (hard-link to symlinks) and -P (hard-link to the referent). Once
154 gnulib has a decent implementation, we should use it here. */
155 if (!symbolic_link)
157 if (STAT_LIKE_LINK (source, &source_stats) != 0)
159 error (0, errno, _("accessing %s"), quote (source));
160 return false;
163 if (S_ISDIR (source_stats.st_mode))
165 source_is_dir = true;
166 if (! hard_dir_link)
168 error (0, 0, _("%s: hard link not allowed for directory"),
169 quote (source));
170 return false;
175 if (remove_existing_files || interactive || backup_type != no_backups)
177 dest_lstat_ok = (lstat (dest, &dest_stats) == 0);
178 if (!dest_lstat_ok && errno != ENOENT)
180 error (0, errno, _("accessing %s"), quote (dest));
181 return false;
185 /* If the current target was created as a hard link to another
186 source file, then refuse to unlink it. */
187 if (dest_lstat_ok
188 && dest_set != NULL
189 && seen_file (dest_set, dest, &dest_stats))
191 error (0, 0,
192 _("will not overwrite just-created %s with %s"),
193 quote_n (0, dest), quote_n (1, source));
194 return false;
197 /* If --force (-f) has been specified without --backup, then before
198 making a link ln must remove the destination file if it exists.
199 (with --backup, it just renames any existing destination file)
200 But if the source and destination are the same, don't remove
201 anything and fail right here. */
202 if ((remove_existing_files
203 /* Ensure that "ln --backup f f" fails here, with the
204 "... same file" diagnostic, below. Otherwise, subsequent
205 code would give a misleading "file not found" diagnostic.
206 This case is different than the others handled here, since
207 the command in question doesn't use --force. */
208 || (!symbolic_link && backup_type != no_backups))
209 && dest_lstat_ok
210 /* Allow `ln -sf --backup k k' to succeed in creating the
211 self-referential symlink, but don't allow the hard-linking
212 equivalent: `ln -f k k' (with or without --backup) to get
213 beyond this point, because the error message you'd get is
214 misleading. */
215 && (backup_type == no_backups || !symbolic_link)
216 && (!symbolic_link || stat (source, &source_stats) == 0)
217 && SAME_INODE (source_stats, dest_stats)
218 /* The following detects whether removing DEST will also remove
219 SOURCE. If the file has only one link then both are surely
220 the same link. Otherwise check whether they point to the same
221 name in the same directory. */
222 && (source_stats.st_nlink == 1 || same_name (source, dest)))
224 error (0, 0, _("%s and %s are the same file"),
225 quote_n (0, source), quote_n (1, dest));
226 return false;
229 if (dest_lstat_ok)
231 if (S_ISDIR (dest_stats.st_mode))
233 error (0, 0, _("%s: cannot overwrite directory"), quote (dest));
234 return false;
236 if (interactive)
238 fprintf (stderr, _("%s: replace %s? "), program_name, quote (dest));
239 if (!yesno ())
240 return true;
241 remove_existing_files = true;
244 if (backup_type != no_backups)
246 dest_backup = find_backup_file_name (dest, backup_type);
247 if (rename (dest, dest_backup) != 0)
249 int rename_errno = errno;
250 free (dest_backup);
251 dest_backup = NULL;
252 if (rename_errno != ENOENT)
254 error (0, rename_errno, _("cannot backup %s"), quote (dest));
255 return false;
261 ok = ((symbolic_link ? symlink (source, dest) : link (source, dest))
262 == 0);
264 /* If the attempt to create a link failed and we are removing or
265 backing up destinations, unlink the destination and try again.
267 On the surface, POSIX describes an algorithm that states that
268 'ln -f A B' will call unlink() on B before ever attempting
269 link() on A. But strictly following this has the counterintuitive
270 effect of losing the contents of B, if A does not exist.
271 Fortunately, POSIX 2008 clarified that an application is free
272 to fail early if it can prove that continuing onwards cannot
273 succeed, so we are justified in trying link() before blindly
274 removing B, thus sometimes calling link() a second time during
275 a successful 'ln -f A B'.
277 Try to unlink DEST even if we may have backed it up successfully.
278 In some unusual cases (when DEST and DEST_BACKUP are hard-links
279 that refer to the same file), rename succeeds and DEST remains.
280 If we didn't remove DEST in that case, the subsequent symlink or link
281 call would fail. */
283 if (!ok && errno == EEXIST && (remove_existing_files || dest_backup))
285 if (unlink (dest) != 0)
287 error (0, errno, _("cannot remove %s"), quote (dest));
288 free (dest_backup);
289 return false;
292 ok = ((symbolic_link ? symlink (source, dest) : link (source, dest))
293 == 0);
296 if (ok)
298 /* Right after creating a hard link, do this: (note dest name and
299 source_stats, which are also the just-linked-destinations stats) */
300 record_file (dest_set, dest, &source_stats);
302 if (verbose)
304 if (dest_backup)
305 printf ("%s ~ ", quote (dest_backup));
306 printf ("%s %c> %s\n", quote_n (0, dest), (symbolic_link ? '-' : '='),
307 quote_n (1, source));
310 else
312 error (0, errno,
313 (symbolic_link
314 ? (errno != ENAMETOOLONG && *source
315 ? _("creating symbolic link %s")
316 : _("creating symbolic link %s -> %s"))
317 : (errno == EMLINK && !source_is_dir
318 ? _("creating hard link to %.0s%s")
319 : (errno == EDQUOT || errno == EEXIST || errno == ENOSPC
320 || errno == EROFS)
321 ? _("creating hard link %s")
322 : _("creating hard link %s => %s"))),
323 quote_n (0, dest), quote_n (1, source));
325 if (dest_backup)
327 if (rename (dest_backup, dest) != 0)
328 error (0, errno, _("cannot un-backup %s"), quote (dest));
332 free (dest_backup);
333 return ok;
336 void
337 usage (int status)
339 if (status != EXIT_SUCCESS)
340 fprintf (stderr, _("Try `%s --help' for more information.\n"),
341 program_name);
342 else
344 printf (_("\
345 Usage: %s [OPTION]... [-T] TARGET LINK_NAME (1st form)\n\
346 or: %s [OPTION]... TARGET (2nd form)\n\
347 or: %s [OPTION]... TARGET... DIRECTORY (3rd form)\n\
348 or: %s [OPTION]... -t DIRECTORY TARGET... (4th form)\n\
350 program_name, program_name, program_name, program_name);
351 fputs (_("\
352 In the 1st form, create a link to TARGET with the name LINK_NAME.\n\
353 In the 2nd form, create a link to TARGET in the current directory.\n\
354 In the 3rd and 4th forms, create links to each TARGET in DIRECTORY.\n\
355 Create hard links by default, symbolic links with --symbolic.\n\
356 When creating hard links, each TARGET must exist. Symbolic links\n\
357 can hold arbitrary text; if later resolved, a relative link is\n\
358 interpreted in relation to its parent directory.\n\
360 "), stdout);
361 fputs (_("\
362 Mandatory arguments to long options are mandatory for short options too.\n\
363 "), stdout);
364 fputs (_("\
365 --backup[=CONTROL] make a backup of each existing destination file\n\
366 -b like --backup but does not accept an argument\n\
367 -d, -F, --directory allow the superuser to attempt to hard link\n\
368 directories (note: will probably fail due to\n\
369 system restrictions, even for the superuser)\n\
370 -f, --force remove existing destination files\n\
371 "), stdout);
372 fputs (_("\
373 -n, --no-dereference treat destination that is a symlink to a\n\
374 directory as if it were a normal file\n\
375 -i, --interactive prompt whether to remove destinations\n\
376 -s, --symbolic make symbolic links instead of hard links\n\
377 "), stdout);
378 fputs (_("\
379 -S, --suffix=SUFFIX override the usual backup suffix\n\
380 -t, --target-directory=DIRECTORY specify the DIRECTORY in which to create\n\
381 the links\n\
382 -T, --no-target-directory treat LINK_NAME as a normal file\n\
383 -v, --verbose print name of each linked file\n\
384 "), stdout);
385 fputs (HELP_OPTION_DESCRIPTION, stdout);
386 fputs (VERSION_OPTION_DESCRIPTION, stdout);
387 fputs (_("\
389 The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
390 The version control method may be selected via the --backup option or through\n\
391 the VERSION_CONTROL environment variable. Here are the values:\n\
393 "), stdout);
394 fputs (_("\
395 none, off never make backups (even if --backup is given)\n\
396 numbered, t make numbered backups\n\
397 existing, nil numbered if numbered backups exist, simple otherwise\n\
398 simple, never always make simple backups\n\
399 "), stdout);
400 emit_bug_reporting_address ();
402 exit (status);
406 main (int argc, char **argv)
408 int c;
409 bool ok;
410 bool make_backups = false;
411 char *backup_suffix_string;
412 char *version_control_string = NULL;
413 char const *target_directory = NULL;
414 bool no_target_directory = false;
415 int n_files;
416 char **file;
418 initialize_main (&argc, &argv);
419 set_program_name (argv[0]);
420 setlocale (LC_ALL, "");
421 bindtextdomain (PACKAGE, LOCALEDIR);
422 textdomain (PACKAGE);
424 atexit (close_stdin);
426 /* FIXME: consider not calling getenv for SIMPLE_BACKUP_SUFFIX unless
427 we'll actually use backup_suffix_string. */
428 backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
430 symbolic_link = remove_existing_files = interactive = verbose
431 = hard_dir_link = false;
433 while ((c = getopt_long (argc, argv, "bdfinst:vFS:T", long_options, NULL))
434 != -1)
436 switch (c)
438 case 'b':
439 make_backups = true;
440 if (optarg)
441 version_control_string = optarg;
442 break;
443 case 'd':
444 case 'F':
445 hard_dir_link = true;
446 break;
447 case 'f':
448 remove_existing_files = true;
449 interactive = false;
450 break;
451 case 'i':
452 remove_existing_files = false;
453 interactive = true;
454 break;
455 case 'n':
456 dereference_dest_dir_symlinks = false;
457 break;
458 case 's':
459 symbolic_link = true;
460 break;
461 case 't':
462 if (target_directory)
463 error (EXIT_FAILURE, 0, _("multiple target directories specified"));
464 else
466 struct stat st;
467 if (stat (optarg, &st) != 0)
468 error (EXIT_FAILURE, errno, _("accessing %s"), quote (optarg));
469 if (! S_ISDIR (st.st_mode))
470 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
471 quote (optarg));
473 target_directory = optarg;
474 break;
475 case 'T':
476 no_target_directory = true;
477 break;
478 case 'v':
479 verbose = true;
480 break;
481 case 'S':
482 make_backups = true;
483 backup_suffix_string = optarg;
484 break;
485 case_GETOPT_HELP_CHAR;
486 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
487 default:
488 usage (EXIT_FAILURE);
489 break;
493 n_files = argc - optind;
494 file = argv + optind;
496 if (n_files <= 0)
498 error (0, 0, _("missing file operand"));
499 usage (EXIT_FAILURE);
502 if (no_target_directory)
504 if (target_directory)
505 error (EXIT_FAILURE, 0,
506 _("cannot combine --target-directory "
507 "and --no-target-directory"));
508 if (n_files != 2)
510 if (n_files < 2)
511 error (0, 0,
512 _("missing destination file operand after %s"),
513 quote (file[0]));
514 else
515 error (0, 0, _("extra operand %s"), quote (file[2]));
516 usage (EXIT_FAILURE);
519 else if (!target_directory)
521 if (n_files < 2)
522 target_directory = ".";
523 else if (2 <= n_files && target_directory_operand (file[n_files - 1]))
524 target_directory = file[--n_files];
525 else if (2 < n_files)
526 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
527 quote (file[n_files - 1]));
530 if (backup_suffix_string)
531 simple_backup_suffix = xstrdup (backup_suffix_string);
533 backup_type = (make_backups
534 ? xget_version (_("backup type"), version_control_string)
535 : no_backups);
537 if (target_directory)
539 int i;
541 /* Create the data structure we'll use to record which hard links we
542 create. Used to ensure that ln detects an obscure corner case that
543 might result in user data loss. Create it only if needed. */
544 if (2 <= n_files
545 && remove_existing_files
546 /* Don't bother trying to protect symlinks, since ln clobbering
547 a just-created symlink won't ever lead to real data loss. */
548 && ! symbolic_link
549 /* No destination hard link can be clobbered when making
550 numbered backups. */
551 && backup_type != numbered_backups)
554 dest_set = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
555 NULL,
556 triple_hash,
557 triple_compare,
558 triple_free);
559 if (dest_set == NULL)
560 xalloc_die ();
563 ok = true;
564 for (i = 0; i < n_files; ++i)
566 char *dest_base;
567 char *dest = file_name_concat (target_directory,
568 last_component (file[i]),
569 &dest_base);
570 strip_trailing_slashes (dest_base);
571 ok &= do_link (file[i], dest);
572 free (dest);
575 else
576 ok = do_link (file[0], file[1]);
578 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);