kill: add undocumented -L for compatibility
[coreutils.git] / src / ln.c
blob453167a7dcc52309f804ce60df18df02faa8565a
1 /* 'ln' program to create links between files.
2 Copyright (C) 1986-2015 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 "relpath.h"
32 #include "same.h"
33 #include "yesno.h"
34 #include "canonicalize.h"
36 /* The official name of this program (e.g., no 'g' prefix). */
37 #define PROGRAM_NAME "ln"
39 #define AUTHORS \
40 proper_name ("Mike Parker"), \
41 proper_name ("David MacKenzie")
43 /* FIXME: document */
44 static enum backup_type backup_type;
46 /* If true, make symbolic links; otherwise, make hard links. */
47 static bool symbolic_link;
49 /* If true, make symbolic links relative */
50 static bool relative;
52 /* If true, hard links are logical rather than physical. */
53 static bool logical = !!LINK_FOLLOWS_SYMLINKS;
55 /* If true, ask the user before removing existing files. */
56 static bool interactive;
58 /* If true, remove existing files unconditionally. */
59 static bool remove_existing_files;
61 /* If true, list each file as it is moved. */
62 static bool verbose;
64 /* If true, allow the superuser to *attempt* to make hard links
65 to directories. However, it appears that this option is not useful
66 in practice, since even the superuser is prohibited from hard-linking
67 directories on most existing systems (Solaris being an exception). */
68 static bool hard_dir_link;
70 /* If nonzero, and the specified destination is a symbolic link to a
71 directory, treat it just as if it were a directory. Otherwise, the
72 command 'ln --force --no-dereference file symlink-to-dir' deletes
73 symlink-to-dir before creating the new link. */
74 static bool dereference_dest_dir_symlinks = true;
76 /* This is a set of destination name/inode/dev triples for hard links
77 created by ln. Use this data structure to avoid data loss via a
78 sequence of commands like this:
79 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 */
80 static Hash_table *dest_set;
82 /* Initial size of the dest_set hash table. */
83 enum { DEST_INFO_INITIAL_CAPACITY = 61 };
85 static struct option const long_options[] =
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 {"logical", no_argument, NULL, 'L'},
96 {"physical", no_argument, NULL, 'P'},
97 {"relative", no_argument, NULL, 'r'},
98 {"symbolic", no_argument, NULL, 's'},
99 {"verbose", no_argument, NULL, 'v'},
100 {GETOPT_HELP_OPTION_DECL},
101 {GETOPT_VERSION_OPTION_DECL},
102 {NULL, 0, NULL, 0}
105 /* Return true when the passed ERR implies
106 that a file does not or could not exist. */
108 static bool
109 errno_nonexisting (int err)
111 return err == ENOENT || err == ENAMETOOLONG || err == ENOTDIR || err == ELOOP;
115 /* FILE is the last operand of this command. Return true if FILE is a
116 directory. But report an error if there is a problem accessing FILE,
117 or if FILE does not exist but would have to refer to an existing
118 directory if it referred to anything at all. */
120 static bool
121 target_directory_operand (char const *file)
123 char const *b = last_component (file);
124 size_t blen = strlen (b);
125 bool looks_like_a_dir = (blen == 0 || ISSLASH (b[blen - 1]));
126 struct stat st;
127 int stat_result =
128 (dereference_dest_dir_symlinks ? stat (file, &st) : lstat (file, &st));
129 int err = (stat_result == 0 ? 0 : errno);
130 bool is_a_dir = !err && S_ISDIR (st.st_mode);
131 if (err && ! errno_nonexisting (errno))
132 error (EXIT_FAILURE, err, _("failed to access %s"), quoteaf (file));
133 if (is_a_dir < looks_like_a_dir)
134 error (EXIT_FAILURE, err, _("target %s is not a directory"),
135 quoteaf (file));
136 return is_a_dir;
139 /* Return FROM represented as relative to the dir of TARGET.
140 The result is malloced. */
142 static char *
143 convert_abs_rel (const char *from, const char *target)
145 /* Get dirname to generate paths relative to. We don't resolve
146 the full TARGET as the last component could be an existing symlink. */
147 char *targetdir = dir_name (target);
149 char *realdest = canonicalize_filename_mode (targetdir, CAN_MISSING);
150 char *realfrom = canonicalize_filename_mode (from, CAN_MISSING);
152 char *relative_from = NULL;
153 if (realdest && realfrom)
155 /* Write to a PATH_MAX buffer. */
156 relative_from = xmalloc (PATH_MAX);
158 if (!relpath (realfrom, realdest, relative_from, PATH_MAX))
160 free (relative_from);
161 relative_from = NULL;
165 free (targetdir);
166 free (realdest);
167 free (realfrom);
169 return relative_from ? relative_from : xstrdup (from);
172 /* Make a link DEST to the (usually) existing file SOURCE.
173 Symbolic links to nonexistent files are allowed.
174 Return true if successful. */
176 static bool
177 do_link (const char *source, const char *dest)
179 struct stat source_stats;
180 struct stat dest_stats;
181 char *dest_backup = NULL;
182 char *rel_source = NULL;
183 bool dest_lstat_ok = false;
184 bool source_is_dir = false;
185 bool ok;
187 if (!symbolic_link)
189 /* Which stat to use depends on whether linkat will follow the
190 symlink. We can't use the shorter
191 (logical?stat:lstat) (source, &source_stats)
192 since stat might be a function-like macro. */
193 if ((logical ? stat (source, &source_stats)
194 : lstat (source, &source_stats))
195 != 0)
197 error (0, errno, _("failed to access %s"), quoteaf (source));
198 return false;
201 if (S_ISDIR (source_stats.st_mode))
203 source_is_dir = true;
204 if (! hard_dir_link)
206 error (0, 0, _("%s: hard link not allowed for directory"),
207 quotef (source));
208 return false;
213 if (remove_existing_files || interactive || backup_type != no_backups)
215 dest_lstat_ok = (lstat (dest, &dest_stats) == 0);
216 if (!dest_lstat_ok && errno != ENOENT)
218 error (0, errno, _("failed to access %s"), quoteaf (dest));
219 return false;
223 /* If the current target was created as a hard link to another
224 source file, then refuse to unlink it. */
225 if (dest_lstat_ok
226 && dest_set != NULL
227 && seen_file (dest_set, dest, &dest_stats))
229 error (0, 0,
230 _("will not overwrite just-created %s with %s"),
231 quoteaf_n (0, dest), quoteaf_n (1, source));
232 return false;
235 /* If --force (-f) has been specified without --backup, then before
236 making a link ln must remove the destination file if it exists.
237 (with --backup, it just renames any existing destination file)
238 But if the source and destination are the same, don't remove
239 anything and fail right here. */
240 if ((remove_existing_files
241 /* Ensure that "ln --backup f f" fails here, with the
242 "... same file" diagnostic, below. Otherwise, subsequent
243 code would give a misleading "file not found" diagnostic.
244 This case is different than the others handled here, since
245 the command in question doesn't use --force. */
246 || (!symbolic_link && backup_type != no_backups))
247 && dest_lstat_ok
248 /* Allow 'ln -sf --backup k k' to succeed in creating the
249 self-referential symlink, but don't allow the hard-linking
250 equivalent: 'ln -f k k' (with or without --backup) to get
251 beyond this point, because the error message you'd get is
252 misleading. */
253 && (backup_type == no_backups || !symbolic_link)
254 && (!symbolic_link || stat (source, &source_stats) == 0)
255 && SAME_INODE (source_stats, dest_stats)
256 /* The following detects whether removing DEST will also remove
257 SOURCE. If the file has only one link then both are surely
258 the same link. Otherwise check whether they point to the same
259 name in the same directory. */
260 && (source_stats.st_nlink == 1 || same_name (source, dest)))
262 error (0, 0, _("%s and %s are the same file"),
263 quoteaf_n (0, source), quoteaf_n (1, dest));
264 return false;
267 if (dest_lstat_ok)
269 if (S_ISDIR (dest_stats.st_mode))
271 error (0, 0, _("%s: cannot overwrite directory"), quotef (dest));
272 return false;
274 if (interactive)
276 fprintf (stderr, _("%s: replace %s? "), program_name, quoteaf (dest));
277 if (!yesno ())
278 return true;
279 remove_existing_files = true;
282 if (backup_type != no_backups)
284 dest_backup = find_backup_file_name (dest, backup_type);
285 if (rename (dest, dest_backup) != 0)
287 int rename_errno = errno;
288 free (dest_backup);
289 dest_backup = NULL;
290 if (rename_errno != ENOENT)
292 error (0, rename_errno, _("cannot backup %s"),
293 quoteaf (dest));
294 return false;
300 if (relative)
301 source = rel_source = convert_abs_rel (source, dest);
303 ok = ((symbolic_link ? symlink (source, dest)
304 : linkat (AT_FDCWD, source, AT_FDCWD, dest,
305 logical ? AT_SYMLINK_FOLLOW : 0))
306 == 0);
308 /* If the attempt to create a link failed and we are removing or
309 backing up destinations, unlink the destination and try again.
311 On the surface, POSIX describes an algorithm that states that
312 'ln -f A B' will call unlink() on B before ever attempting
313 link() on A. But strictly following this has the counterintuitive
314 effect of losing the contents of B, if A does not exist.
315 Fortunately, POSIX 2008 clarified that an application is free
316 to fail early if it can prove that continuing onwards cannot
317 succeed, so we are justified in trying link() before blindly
318 removing B, thus sometimes calling link() a second time during
319 a successful 'ln -f A B'.
321 Try to unlink DEST even if we may have backed it up successfully.
322 In some unusual cases (when DEST and DEST_BACKUP are hard-links
323 that refer to the same file), rename succeeds and DEST remains.
324 If we didn't remove DEST in that case, the subsequent symlink or link
325 call would fail. */
327 if (!ok && errno == EEXIST && (remove_existing_files || dest_backup))
329 if (unlink (dest) != 0)
331 error (0, errno, _("cannot remove %s"), quoteaf (dest));
332 free (dest_backup);
333 free (rel_source);
334 return false;
337 ok = ((symbolic_link ? symlink (source, dest)
338 : linkat (AT_FDCWD, source, AT_FDCWD, dest,
339 logical ? AT_SYMLINK_FOLLOW : 0))
340 == 0);
343 if (ok)
345 /* Right after creating a hard link, do this: (note dest name and
346 source_stats, which are also the just-linked-destinations stats) */
347 if (! symbolic_link)
348 record_file (dest_set, dest, &source_stats);
350 if (verbose)
352 if (dest_backup)
353 printf ("%s ~ ", quoteaf (dest_backup));
354 printf ("%s %c> %s\n", quoteaf_n (0, dest),
355 (symbolic_link ? '-' : '='), quoteaf_n (1, source));
358 else
360 error (0, errno,
361 (symbolic_link
362 ? (errno != ENAMETOOLONG && *source
363 ? _("failed to create symbolic link %s")
364 : _("failed to create symbolic link %s -> %s"))
365 : (errno == EMLINK && !source_is_dir
366 ? _("failed to create hard link to %.0s%s")
367 : (errno == EDQUOT || errno == EEXIST || errno == ENOSPC
368 || errno == EROFS)
369 ? _("failed to create hard link %s")
370 : _("failed to create hard link %s => %s"))),
371 quoteaf_n (0, dest), quoteaf_n (1, source));
373 if (dest_backup)
375 if (rename (dest_backup, dest) != 0)
376 error (0, errno, _("cannot un-backup %s"), quoteaf (dest));
380 free (dest_backup);
381 free (rel_source);
382 return ok;
385 void
386 usage (int status)
388 if (status != EXIT_SUCCESS)
389 emit_try_help ();
390 else
392 printf (_("\
393 Usage: %s [OPTION]... [-T] TARGET LINK_NAME (1st form)\n\
394 or: %s [OPTION]... TARGET (2nd form)\n\
395 or: %s [OPTION]... TARGET... DIRECTORY (3rd form)\n\
396 or: %s [OPTION]... -t DIRECTORY TARGET... (4th form)\n\
398 program_name, program_name, program_name, program_name);
399 fputs (_("\
400 In the 1st form, create a link to TARGET with the name LINK_NAME.\n\
401 In the 2nd form, create a link to TARGET in the current directory.\n\
402 In the 3rd and 4th forms, create links to each TARGET in DIRECTORY.\n\
403 Create hard links by default, symbolic links with --symbolic.\n\
404 By default, each destination (name of new link) should not already exist.\n\
405 When creating hard links, each TARGET must exist. Symbolic links\n\
406 can hold arbitrary text; if later resolved, a relative link is\n\
407 interpreted in relation to its parent directory.\n\
408 "), stdout);
410 emit_mandatory_arg_note ();
412 fputs (_("\
413 --backup[=CONTROL] make a backup of each existing destination file\n\
414 -b like --backup but does not accept an argument\n\
415 -d, -F, --directory allow the superuser to attempt to hard link\n\
416 directories (note: will probably fail due to\n\
417 system restrictions, even for the superuser)\n\
418 -f, --force remove existing destination files\n\
419 "), stdout);
420 fputs (_("\
421 -i, --interactive prompt whether to remove destinations\n\
422 -L, --logical dereference TARGETs that are symbolic links\n\
423 -n, --no-dereference treat LINK_NAME as a normal file if\n\
424 it is a symbolic link to a directory\n\
425 -P, --physical make hard links directly to symbolic links\n\
426 -r, --relative create symbolic links relative to link location\n\
427 -s, --symbolic make symbolic links instead of hard links\n\
428 "), stdout);
429 fputs (_("\
430 -S, --suffix=SUFFIX override the usual backup suffix\n\
431 -t, --target-directory=DIRECTORY specify the DIRECTORY in which to create\n\
432 the links\n\
433 -T, --no-target-directory treat LINK_NAME as a normal file always\n\
434 -v, --verbose print name of each linked file\n\
435 "), stdout);
436 fputs (HELP_OPTION_DESCRIPTION, stdout);
437 fputs (VERSION_OPTION_DESCRIPTION, stdout);
438 fputs (_("\
440 The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
441 The version control method may be selected via the --backup option or through\n\
442 the VERSION_CONTROL environment variable. Here are the values:\n\
444 "), stdout);
445 fputs (_("\
446 none, off never make backups (even if --backup is given)\n\
447 numbered, t make numbered backups\n\
448 existing, nil numbered if numbered backups exist, simple otherwise\n\
449 simple, never always make simple backups\n\
450 "), stdout);
451 printf (_("\
453 Using -s ignores -L and -P. Otherwise, the last option specified controls\n\
454 behavior when a TARGET is a symbolic link, defaulting to %s.\n\
455 "), LINK_FOLLOWS_SYMLINKS ? "-L" : "-P");
456 emit_ancillary_info (PROGRAM_NAME);
458 exit (status);
462 main (int argc, char **argv)
464 int c;
465 bool ok;
466 bool make_backups = false;
467 char *backup_suffix_string;
468 char *version_control_string = NULL;
469 char const *target_directory = NULL;
470 bool no_target_directory = false;
471 int n_files;
472 char **file;
474 initialize_main (&argc, &argv);
475 set_program_name (argv[0]);
476 setlocale (LC_ALL, "");
477 bindtextdomain (PACKAGE, LOCALEDIR);
478 textdomain (PACKAGE);
480 atexit (close_stdin);
482 /* FIXME: consider not calling getenv for SIMPLE_BACKUP_SUFFIX unless
483 we'll actually use backup_suffix_string. */
484 backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
486 symbolic_link = remove_existing_files = interactive = verbose
487 = hard_dir_link = false;
489 while ((c = getopt_long (argc, argv, "bdfinrst:vFLPS:T", long_options, NULL))
490 != -1)
492 switch (c)
494 case 'b':
495 make_backups = true;
496 if (optarg)
497 version_control_string = optarg;
498 break;
499 case 'd':
500 case 'F':
501 hard_dir_link = true;
502 break;
503 case 'f':
504 remove_existing_files = true;
505 interactive = false;
506 break;
507 case 'i':
508 remove_existing_files = false;
509 interactive = true;
510 break;
511 case 'L':
512 logical = true;
513 break;
514 case 'n':
515 dereference_dest_dir_symlinks = false;
516 break;
517 case 'P':
518 logical = false;
519 break;
520 case 'r':
521 relative = true;
522 break;
523 case 's':
524 symbolic_link = true;
525 break;
526 case 't':
527 if (target_directory)
528 error (EXIT_FAILURE, 0, _("multiple target directories specified"));
529 else
531 struct stat st;
532 if (stat (optarg, &st) != 0)
533 error (EXIT_FAILURE, errno, _("failed to access %s"),
534 quoteaf (optarg));
535 if (! S_ISDIR (st.st_mode))
536 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
537 quoteaf (optarg));
539 target_directory = optarg;
540 break;
541 case 'T':
542 no_target_directory = true;
543 break;
544 case 'v':
545 verbose = true;
546 break;
547 case 'S':
548 make_backups = true;
549 backup_suffix_string = optarg;
550 break;
551 case_GETOPT_HELP_CHAR;
552 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
553 default:
554 usage (EXIT_FAILURE);
555 break;
559 n_files = argc - optind;
560 file = argv + optind;
562 if (n_files <= 0)
564 error (0, 0, _("missing file operand"));
565 usage (EXIT_FAILURE);
568 if (no_target_directory)
570 if (target_directory)
571 error (EXIT_FAILURE, 0,
572 _("cannot combine --target-directory "
573 "and --no-target-directory"));
574 if (n_files != 2)
576 if (n_files < 2)
577 error (0, 0,
578 _("missing destination file operand after %s"),
579 quoteaf (file[0]));
580 else
581 error (0, 0, _("extra operand %s"), quoteaf (file[2]));
582 usage (EXIT_FAILURE);
585 else if (!target_directory)
587 if (n_files < 2)
588 target_directory = ".";
589 else if (2 <= n_files && target_directory_operand (file[n_files - 1]))
590 target_directory = file[--n_files];
591 else if (2 < n_files)
592 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
593 quoteaf (file[n_files - 1]));
596 if (backup_suffix_string)
597 simple_backup_suffix = xstrdup (backup_suffix_string);
599 backup_type = (make_backups
600 ? xget_version (_("backup type"), version_control_string)
601 : no_backups);
603 if (relative && !symbolic_link)
605 error (EXIT_FAILURE, 0,
606 _("cannot do --relative without --symbolic"));
610 if (target_directory)
612 int i;
614 /* Create the data structure we'll use to record which hard links we
615 create. Used to ensure that ln detects an obscure corner case that
616 might result in user data loss. Create it only if needed. */
617 if (2 <= n_files
618 && remove_existing_files
619 /* Don't bother trying to protect symlinks, since ln clobbering
620 a just-created symlink won't ever lead to real data loss. */
621 && ! symbolic_link
622 /* No destination hard link can be clobbered when making
623 numbered backups. */
624 && backup_type != numbered_backups)
627 dest_set = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
628 NULL,
629 triple_hash,
630 triple_compare,
631 triple_free);
632 if (dest_set == NULL)
633 xalloc_die ();
636 ok = true;
637 for (i = 0; i < n_files; ++i)
639 char *dest_base;
640 char *dest = file_name_concat (target_directory,
641 last_component (file[i]),
642 &dest_base);
643 strip_trailing_slashes (dest_base);
644 ok &= do_link (file[i], dest);
645 free (dest);
648 else
649 ok = do_link (file[0], file[1]);
651 return ok ? EXIT_SUCCESS : EXIT_FAILURE;