doc: stat: clarify that %t and %T expand to the file system type
[coreutils/ericb.git] / src / ln.c
blob52649de541adb1f5a640dcb3f30e61f16818644a
1 /* `ln' program to create links between files.
2 Copyright (C) 1986, 1989-1991, 1995-2011 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 /* FIXME: document */
43 static enum backup_type backup_type;
45 /* If true, make symbolic links; otherwise, make hard links. */
46 static bool symbolic_link;
48 /* If true, hard links are logical rather than physical. */
49 static bool logical = !!LINK_FOLLOWS_SYMLINKS;
51 /* If true, ask the user before removing existing files. */
52 static bool interactive;
54 /* If true, remove existing files unconditionally. */
55 static bool remove_existing_files;
57 /* If true, list each file as it is moved. */
58 static bool verbose;
60 /* If true, allow the superuser to *attempt* to make hard links
61 to directories. However, it appears that this option is not useful
62 in practice, since even the superuser is prohibited from hard-linking
63 directories on most existing systems (Solaris being an exception). */
64 static bool hard_dir_link;
66 /* If nonzero, and the specified destination is a symbolic link to a
67 directory, treat it just as if it were a directory. Otherwise, the
68 command `ln --force --no-dereference file symlink-to-dir' deletes
69 symlink-to-dir before creating the new link. */
70 static bool dereference_dest_dir_symlinks = true;
72 /* This is a set of destination name/inode/dev triples for hard links
73 created by ln. Use this data structure to avoid data loss via a
74 sequence of commands like this:
75 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 */
76 static Hash_table *dest_set;
78 /* Initial size of the dest_set hash table. */
79 enum { DEST_INFO_INITIAL_CAPACITY = 61 };
81 static struct option const long_options[] =
83 {"backup", optional_argument, NULL, 'b'},
84 {"directory", no_argument, NULL, 'F'},
85 {"no-dereference", no_argument, NULL, 'n'},
86 {"no-target-directory", no_argument, NULL, 'T'},
87 {"force", no_argument, NULL, 'f'},
88 {"interactive", no_argument, NULL, 'i'},
89 {"suffix", required_argument, NULL, 'S'},
90 {"target-directory", required_argument, NULL, 't'},
91 {"logical", no_argument, NULL, 'L'},
92 {"physical", no_argument, NULL, 'P'},
93 {"symbolic", no_argument, NULL, 's'},
94 {"verbose", no_argument, NULL, 'v'},
95 {GETOPT_HELP_OPTION_DECL},
96 {GETOPT_VERSION_OPTION_DECL},
97 {NULL, 0, NULL, 0}
100 /* FILE is the last operand of this command. Return true if FILE is a
101 directory. But report an error there is a problem accessing FILE,
102 or if FILE does not exist but would have to refer to an existing
103 directory if it referred to anything at all. */
105 static bool
106 target_directory_operand (char const *file)
108 char const *b = last_component (file);
109 size_t blen = strlen (b);
110 bool looks_like_a_dir = (blen == 0 || ISSLASH (b[blen - 1]));
111 struct stat st;
112 int stat_result =
113 (dereference_dest_dir_symlinks ? stat (file, &st) : lstat (file, &st));
114 int err = (stat_result == 0 ? 0 : errno);
115 bool is_a_dir = !err && S_ISDIR (st.st_mode);
116 if (err && err != ENOENT)
117 error (EXIT_FAILURE, err, _("accessing %s"), quote (file));
118 if (is_a_dir < looks_like_a_dir)
119 error (EXIT_FAILURE, err, _("target %s is not a directory"), quote (file));
120 return is_a_dir;
123 /* Make a link DEST to the (usually) existing file SOURCE.
124 Symbolic links to nonexistent files are allowed.
125 Return true if successful. */
127 static bool
128 do_link (const char *source, const char *dest)
130 struct stat source_stats;
131 struct stat dest_stats;
132 char *dest_backup = NULL;
133 bool dest_lstat_ok = false;
134 bool source_is_dir = false;
135 bool ok;
137 if (!symbolic_link)
139 /* Which stat to use depends on whether linkat will follow the
140 symlink. We can't use the shorter
141 (logical?stat:lstat) (source, &source_stats)
142 since stat might be a function-like macro. */
143 if ((logical ? stat (source, &source_stats)
144 : lstat (source, &source_stats))
145 != 0)
147 error (0, errno, _("accessing %s"), quote (source));
148 return false;
151 if (S_ISDIR (source_stats.st_mode))
153 source_is_dir = true;
154 if (! hard_dir_link)
156 error (0, 0, _("%s: hard link not allowed for directory"),
157 quote (source));
158 return false;
163 if (remove_existing_files || interactive || backup_type != no_backups)
165 dest_lstat_ok = (lstat (dest, &dest_stats) == 0);
166 if (!dest_lstat_ok && errno != ENOENT)
168 error (0, errno, _("accessing %s"), quote (dest));
169 return false;
173 /* If the current target was created as a hard link to another
174 source file, then refuse to unlink it. */
175 if (dest_lstat_ok
176 && dest_set != NULL
177 && seen_file (dest_set, dest, &dest_stats))
179 error (0, 0,
180 _("will not overwrite just-created %s with %s"),
181 quote_n (0, dest), quote_n (1, source));
182 return false;
185 /* If --force (-f) has been specified without --backup, then before
186 making a link ln must remove the destination file if it exists.
187 (with --backup, it just renames any existing destination file)
188 But if the source and destination are the same, don't remove
189 anything and fail right here. */
190 if ((remove_existing_files
191 /* Ensure that "ln --backup f f" fails here, with the
192 "... same file" diagnostic, below. Otherwise, subsequent
193 code would give a misleading "file not found" diagnostic.
194 This case is different than the others handled here, since
195 the command in question doesn't use --force. */
196 || (!symbolic_link && backup_type != no_backups))
197 && dest_lstat_ok
198 /* Allow `ln -sf --backup k k' to succeed in creating the
199 self-referential symlink, but don't allow the hard-linking
200 equivalent: `ln -f k k' (with or without --backup) to get
201 beyond this point, because the error message you'd get is
202 misleading. */
203 && (backup_type == no_backups || !symbolic_link)
204 && (!symbolic_link || stat (source, &source_stats) == 0)
205 && SAME_INODE (source_stats, dest_stats)
206 /* The following detects whether removing DEST will also remove
207 SOURCE. If the file has only one link then both are surely
208 the same link. Otherwise check whether they point to the same
209 name in the same directory. */
210 && (source_stats.st_nlink == 1 || same_name (source, dest)))
212 error (0, 0, _("%s and %s are the same file"),
213 quote_n (0, source), quote_n (1, dest));
214 return false;
217 if (dest_lstat_ok)
219 if (S_ISDIR (dest_stats.st_mode))
221 error (0, 0, _("%s: cannot overwrite directory"), quote (dest));
222 return false;
224 if (interactive)
226 fprintf (stderr, _("%s: replace %s? "), program_name, quote (dest));
227 if (!yesno ())
228 return true;
229 remove_existing_files = true;
232 if (backup_type != no_backups)
234 dest_backup = find_backup_file_name (dest, backup_type);
235 if (rename (dest, dest_backup) != 0)
237 int rename_errno = errno;
238 free (dest_backup);
239 dest_backup = NULL;
240 if (rename_errno != ENOENT)
242 error (0, rename_errno, _("cannot backup %s"), quote (dest));
243 return false;
249 ok = ((symbolic_link ? symlink (source, dest)
250 : linkat (AT_FDCWD, source, AT_FDCWD, dest,
251 logical ? AT_SYMLINK_FOLLOW : 0))
252 == 0);
254 /* If the attempt to create a link failed and we are removing or
255 backing up destinations, unlink the destination and try again.
257 On the surface, POSIX describes an algorithm that states that
258 'ln -f A B' will call unlink() on B before ever attempting
259 link() on A. But strictly following this has the counterintuitive
260 effect of losing the contents of B, if A does not exist.
261 Fortunately, POSIX 2008 clarified that an application is free
262 to fail early if it can prove that continuing onwards cannot
263 succeed, so we are justified in trying link() before blindly
264 removing B, thus sometimes calling link() a second time during
265 a successful 'ln -f A B'.
267 Try to unlink DEST even if we may have backed it up successfully.
268 In some unusual cases (when DEST and DEST_BACKUP are hard-links
269 that refer to the same file), rename succeeds and DEST remains.
270 If we didn't remove DEST in that case, the subsequent symlink or link
271 call would fail. */
273 if (!ok && errno == EEXIST && (remove_existing_files || dest_backup))
275 if (unlink (dest) != 0)
277 error (0, errno, _("cannot remove %s"), quote (dest));
278 free (dest_backup);
279 return false;
282 ok = ((symbolic_link ? symlink (source, dest)
283 : linkat (AT_FDCWD, source, AT_FDCWD, dest,
284 logical ? AT_SYMLINK_FOLLOW : 0))
285 == 0);
288 if (ok)
290 /* Right after creating a hard link, do this: (note dest name and
291 source_stats, which are also the just-linked-destinations stats) */
292 record_file (dest_set, dest, &source_stats);
294 if (verbose)
296 if (dest_backup)
297 printf ("%s ~ ", quote (dest_backup));
298 printf ("%s %c> %s\n", quote_n (0, dest), (symbolic_link ? '-' : '='),
299 quote_n (1, source));
302 else
304 error (0, errno,
305 (symbolic_link
306 ? (errno != ENAMETOOLONG && *source
307 ? _("failed to create symbolic link %s")
308 : _("failed to create symbolic link %s -> %s"))
309 : (errno == EMLINK && !source_is_dir
310 ? _("failed to create hard link to %.0s%s")
311 : (errno == EDQUOT || errno == EEXIST || errno == ENOSPC
312 || errno == EROFS)
313 ? _("failed to create hard link %s")
314 : _("failed to create hard link %s => %s"))),
315 quote_n (0, dest), quote_n (1, source));
317 if (dest_backup)
319 if (rename (dest_backup, dest) != 0)
320 error (0, errno, _("cannot un-backup %s"), quote (dest));
324 free (dest_backup);
325 return ok;
328 void
329 usage (int status)
331 if (status != EXIT_SUCCESS)
332 fprintf (stderr, _("Try `%s --help' for more information.\n"),
333 program_name);
334 else
336 printf (_("\
337 Usage: %s [OPTION]... [-T] TARGET LINK_NAME (1st form)\n\
338 or: %s [OPTION]... TARGET (2nd form)\n\
339 or: %s [OPTION]... TARGET... DIRECTORY (3rd form)\n\
340 or: %s [OPTION]... -t DIRECTORY TARGET... (4th form)\n\
342 program_name, program_name, program_name, program_name);
343 fputs (_("\
344 In the 1st form, create a link to TARGET with the name LINK_NAME.\n\
345 In the 2nd form, create a link to TARGET in the current directory.\n\
346 In the 3rd and 4th forms, create links to each TARGET in DIRECTORY.\n\
347 Create hard links by default, symbolic links with --symbolic.\n\
348 By default, each destination (name of new link) should not already exist.\n\
349 When creating hard links, each TARGET must exist. Symbolic links\n\
350 can hold arbitrary text; if later resolved, a relative link is\n\
351 interpreted in relation to its parent directory.\n\
353 "), stdout);
354 fputs (_("\
355 Mandatory arguments to long options are mandatory for short options too.\n\
356 "), stdout);
357 fputs (_("\
358 --backup[=CONTROL] make a backup of each existing destination file\n\
359 -b like --backup but does not accept an argument\n\
360 -d, -F, --directory allow the superuser to attempt to hard link\n\
361 directories (note: will probably fail due to\n\
362 system restrictions, even for the superuser)\n\
363 -f, --force remove existing destination files\n\
364 "), stdout);
365 fputs (_("\
366 -i, --interactive prompt whether to remove destinations\n\
367 -L, --logical dereference TARGETs that are symbolic links\n\
368 -n, --no-dereference treat LINK_NAME as a normal file if\n\
369 it is a symbolic link to a directory\n\
370 -P, --physical make hard links directly to symbolic links\n\
371 -s, --symbolic make symbolic links instead of hard links\n\
372 "), stdout);
373 fputs (_("\
374 -S, --suffix=SUFFIX override the usual backup suffix\n\
375 -t, --target-directory=DIRECTORY specify the DIRECTORY in which to create\n\
376 the links\n\
377 -T, --no-target-directory treat LINK_NAME as a normal file always\n\
378 -v, --verbose print name of each linked file\n\
379 "), stdout);
380 fputs (HELP_OPTION_DESCRIPTION, stdout);
381 fputs (VERSION_OPTION_DESCRIPTION, stdout);
382 fputs (_("\
384 The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
385 The version control method may be selected via the --backup option or through\n\
386 the VERSION_CONTROL environment variable. Here are the values:\n\
388 "), stdout);
389 fputs (_("\
390 none, off never make backups (even if --backup is given)\n\
391 numbered, t make numbered backups\n\
392 existing, nil numbered if numbered backups exist, simple otherwise\n\
393 simple, never always make simple backups\n\
395 "), stdout);
396 printf (_("\
397 Using -s ignores -L and -P. Otherwise, the last option specified controls\n\
398 behavior when a TARGET is a symbolic link, defaulting to %s.\n\
399 "), LINK_FOLLOWS_SYMLINKS ? "-L" : "-P");
400 emit_ancillary_info ();
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:vFLPS: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 'L':
456 logical = true;
457 break;
458 case 'n':
459 dereference_dest_dir_symlinks = false;
460 break;
461 case 'P':
462 logical = false;
463 break;
464 case 's':
465 symbolic_link = true;
466 break;
467 case 't':
468 if (target_directory)
469 error (EXIT_FAILURE, 0, _("multiple target directories specified"));
470 else
472 struct stat st;
473 if (stat (optarg, &st) != 0)
474 error (EXIT_FAILURE, errno, _("accessing %s"), quote (optarg));
475 if (! S_ISDIR (st.st_mode))
476 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
477 quote (optarg));
479 target_directory = optarg;
480 break;
481 case 'T':
482 no_target_directory = true;
483 break;
484 case 'v':
485 verbose = true;
486 break;
487 case 'S':
488 make_backups = true;
489 backup_suffix_string = optarg;
490 break;
491 case_GETOPT_HELP_CHAR;
492 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
493 default:
494 usage (EXIT_FAILURE);
495 break;
499 n_files = argc - optind;
500 file = argv + optind;
502 if (n_files <= 0)
504 error (0, 0, _("missing file operand"));
505 usage (EXIT_FAILURE);
508 if (no_target_directory)
510 if (target_directory)
511 error (EXIT_FAILURE, 0,
512 _("cannot combine --target-directory "
513 "and --no-target-directory"));
514 if (n_files != 2)
516 if (n_files < 2)
517 error (0, 0,
518 _("missing destination file operand after %s"),
519 quote (file[0]));
520 else
521 error (0, 0, _("extra operand %s"), quote (file[2]));
522 usage (EXIT_FAILURE);
525 else if (!target_directory)
527 if (n_files < 2)
528 target_directory = ".";
529 else if (2 <= n_files && target_directory_operand (file[n_files - 1]))
530 target_directory = file[--n_files];
531 else if (2 < n_files)
532 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
533 quote (file[n_files - 1]));
536 if (backup_suffix_string)
537 simple_backup_suffix = xstrdup (backup_suffix_string);
539 backup_type = (make_backups
540 ? xget_version (_("backup type"), version_control_string)
541 : no_backups);
543 if (target_directory)
545 int i;
547 /* Create the data structure we'll use to record which hard links we
548 create. Used to ensure that ln detects an obscure corner case that
549 might result in user data loss. Create it only if needed. */
550 if (2 <= n_files
551 && remove_existing_files
552 /* Don't bother trying to protect symlinks, since ln clobbering
553 a just-created symlink won't ever lead to real data loss. */
554 && ! symbolic_link
555 /* No destination hard link can be clobbered when making
556 numbered backups. */
557 && backup_type != numbered_backups)
560 dest_set = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
561 NULL,
562 triple_hash,
563 triple_compare,
564 triple_free);
565 if (dest_set == NULL)
566 xalloc_die ();
569 ok = true;
570 for (i = 0; i < n_files; ++i)
572 char *dest_base;
573 char *dest = file_name_concat (target_directory,
574 last_component (file[i]),
575 &dest_base);
576 strip_trailing_slashes (dest_base);
577 ok &= do_link (file[i], dest);
578 free (dest);
581 else
582 ok = do_link (file[0], file[1]);
584 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);