cp,ln,mv: when skipping exit with nonzero status
[coreutils.git] / src / ln.c
blob1c3307cac915f90081819cf66f1b3b82d5651561
1 /* 'ln' program to create links between files.
2 Copyright (C) 1986-2023 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 <https://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 "die.h"
27 #include "error.h"
28 #include "fcntl-safer.h"
29 #include "filenamecat.h"
30 #include "file-set.h"
31 #include "force-link.h"
32 #include "hash.h"
33 #include "hash-triple.h"
34 #include "priv-set.h"
35 #include "relpath.h"
36 #include "same.h"
37 #include "unlinkdir.h"
38 #include "yesno.h"
39 #include "canonicalize.h"
41 /* The official name of this program (e.g., no 'g' prefix). */
42 #define PROGRAM_NAME "ln"
44 #define AUTHORS \
45 proper_name ("Mike Parker"), \
46 proper_name ("David MacKenzie")
48 /* FIXME: document */
49 static enum backup_type backup_type;
51 /* If true, make symbolic links; otherwise, make hard links. */
52 static bool symbolic_link;
54 /* If true, make symbolic links relative */
55 static bool relative;
57 /* If true, hard links are logical rather than physical. */
58 static bool logical = !!LINK_FOLLOWS_SYMLINKS;
60 /* If true, ask the user before removing existing files. */
61 static bool interactive;
63 /* If true, remove existing files unconditionally. */
64 static bool remove_existing_files;
66 /* If true, list each file as it is moved. */
67 static bool verbose;
69 /* If true, allow the superuser to *attempt* to make hard links
70 to directories. However, it appears that this option is not useful
71 in practice, since even the superuser is prohibited from hard-linking
72 directories on most existing systems (Solaris being an exception). */
73 static bool hard_dir_link;
75 /* If true, watch out for creating or removing hard links to directories. */
76 static bool beware_hard_dir_link;
78 /* If nonzero, and the specified destination is a symbolic link to a
79 directory, treat it just as if it were a directory. Otherwise, the
80 command 'ln --force --no-dereference file symlink-to-dir' deletes
81 symlink-to-dir before creating the new link. */
82 static bool dereference_dest_dir_symlinks = true;
84 /* This is a set of destination name/inode/dev triples for hard links
85 created by ln. Use this data structure to avoid data loss via a
86 sequence of commands like this:
87 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 */
88 static Hash_table *dest_set;
90 /* Initial size of the dest_set hash table. */
91 enum { DEST_INFO_INITIAL_CAPACITY = 61 };
93 static struct option const long_options[] =
95 {"backup", optional_argument, NULL, 'b'},
96 {"directory", no_argument, NULL, 'F'},
97 {"no-dereference", no_argument, NULL, 'n'},
98 {"no-target-directory", no_argument, NULL, 'T'},
99 {"force", no_argument, NULL, 'f'},
100 {"interactive", no_argument, NULL, 'i'},
101 {"suffix", required_argument, NULL, 'S'},
102 {"target-directory", required_argument, NULL, 't'},
103 {"logical", no_argument, NULL, 'L'},
104 {"physical", no_argument, NULL, 'P'},
105 {"relative", no_argument, NULL, 'r'},
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}
113 /* Return an errno value for a system call that returned STATUS.
114 This is zero if STATUS is zero, and is errno otherwise. */
116 static int
117 errnoize (int status)
119 return status < 0 ? errno : 0;
122 /* Return FROM represented as relative to the dir of TARGET.
123 The result is malloced. */
125 static char *
126 convert_abs_rel (char const *from, char const *target)
128 /* Get dirname to generate paths relative to. We don't resolve
129 the full TARGET as the last component could be an existing symlink. */
130 char *targetdir = dir_name (target);
132 char *realdest = canonicalize_filename_mode (targetdir, CAN_MISSING);
133 char *realfrom = canonicalize_filename_mode (from, CAN_MISSING);
135 char *relative_from = NULL;
136 if (realdest && realfrom)
138 /* Write to a PATH_MAX buffer. */
139 relative_from = xmalloc (PATH_MAX);
141 if (!relpath (realfrom, realdest, relative_from, PATH_MAX))
143 free (relative_from);
144 relative_from = NULL;
148 free (targetdir);
149 free (realdest);
150 free (realfrom);
152 return relative_from ? relative_from : xstrdup (from);
155 /* Link SOURCE to DESTDIR_FD + DEST_BASE atomically. DESTDIR_FD is
156 the directory containing DEST_BASE. Return 0 if successful, a
157 positive errno value on failure, and -1 if an atomic link cannot be
158 done. This handles the common case where the destination does not
159 already exist and -r is not specified. */
161 static int
162 atomic_link (char const *source, int destdir_fd, char const *dest_base)
164 return (symbolic_link
165 ? (relative ? -1
166 : errnoize (symlinkat (source, destdir_fd, dest_base)))
167 : beware_hard_dir_link ? -1
168 : errnoize (linkat (AT_FDCWD, source, destdir_fd, dest_base,
169 logical ? AT_SYMLINK_FOLLOW : 0)));
172 /* Link SOURCE to a directory entry under DESTDIR_FD named DEST_BASE.
173 DEST is the full name of the destination, useful for diagnostics.
174 LINK_ERRNO is zero if the link has already been made,
175 positive if attempting the link failed with errno == LINK_ERRNO,
176 -1 if no attempt has been made to create the link.
177 Return true if successful. */
179 static bool
180 do_link (char const *source, int destdir_fd, char const *dest_base,
181 char const *dest, int link_errno)
183 struct stat source_stats;
184 int source_status = 1;
185 char *backup_base = NULL;
186 char *rel_source = NULL;
187 int nofollow_flag = logical ? 0 : AT_SYMLINK_NOFOLLOW;
188 if (link_errno < 0)
189 link_errno = atomic_link (source, destdir_fd, dest_base);
191 /* Get SOURCE_STATS if later code will need it, if only for sharper
192 diagnostics. */
193 if ((link_errno || dest_set) && !symbolic_link)
195 source_status = fstatat (AT_FDCWD, source, &source_stats, nofollow_flag);
196 if (source_status != 0)
198 error (0, errno, _("failed to access %s"), quoteaf (source));
199 return false;
203 if (link_errno)
205 if (!symbolic_link && !hard_dir_link && S_ISDIR (source_stats.st_mode))
207 error (0, 0, _("%s: hard link not allowed for directory"),
208 quotef (source));
209 return false;
212 if (relative)
213 source = rel_source = convert_abs_rel (source, dest);
215 bool force = (remove_existing_files || interactive
216 || backup_type != no_backups);
217 if (force)
219 struct stat dest_stats;
220 if (fstatat (destdir_fd, dest_base, &dest_stats, AT_SYMLINK_NOFOLLOW)
221 != 0)
223 if (errno != ENOENT)
225 error (0, errno, _("failed to access %s"), quoteaf (dest));
226 goto fail;
228 force = false;
230 else if (S_ISDIR (dest_stats.st_mode))
232 error (0, 0, _("%s: cannot overwrite directory"), quotef (dest));
233 goto fail;
235 else if (seen_file (dest_set, dest, &dest_stats))
237 /* The current target was created as a hard link to another
238 source file. */
239 error (0, 0,
240 _("will not overwrite just-created %s with %s"),
241 quoteaf_n (0, dest), quoteaf_n (1, source));
242 goto fail;
244 else
246 /* Beware removing DEST if it is the same directory entry as
247 SOURCE, because in that case removing DEST can cause the
248 subsequent link creation either to fail (for hard links), or
249 to replace a non-symlink DEST with a self-loop (for symbolic
250 links) which loses the contents of DEST. So, when backing
251 up, worry about creating hard links (since the backups cover
252 the symlink case); otherwise, worry about about -f. */
253 if (backup_type != no_backups
254 ? !symbolic_link
255 : remove_existing_files)
257 /* Detect whether removing DEST would also remove SOURCE.
258 If the file has only one link then both are surely the
259 same directory entry. Otherwise check whether they point
260 to the same name in the same directory. */
261 if (source_status != 0)
262 source_status = stat (source, &source_stats);
263 if (source_status == 0
264 && SAME_INODE (source_stats, dest_stats)
265 && (source_stats.st_nlink == 1
266 || same_nameat (AT_FDCWD, source,
267 destdir_fd, dest_base)))
269 error (0, 0, _("%s and %s are the same file"),
270 quoteaf_n (0, source), quoteaf_n (1, dest));
271 goto fail;
275 if (link_errno < 0 || link_errno == EEXIST)
277 if (interactive)
279 fprintf (stderr, _("%s: replace %s? "),
280 program_name, quoteaf (dest));
281 if (!yesno ())
283 free (rel_source);
284 return false;
288 if (backup_type != no_backups)
290 backup_base = find_backup_file_name (destdir_fd,
291 dest_base,
292 backup_type);
293 if (renameat (destdir_fd, dest_base,
294 destdir_fd, backup_base)
295 != 0)
297 int rename_errno = errno;
298 free (backup_base);
299 backup_base = NULL;
300 if (rename_errno != ENOENT)
302 error (0, rename_errno, _("cannot backup %s"),
303 quoteaf (dest));
304 goto fail;
306 force = false;
313 /* If the attempt to create a link fails and we are removing or
314 backing up destinations, unlink the destination and try again.
316 On the surface, POSIX states that 'ln -f A B' unlinks B before trying
317 to link A to B. But strictly following this has the counterintuitive
318 effect of losing the contents of B if A does not exist. Fortunately,
319 POSIX 2008 clarified that an application is free to fail early if it
320 can prove that continuing onwards cannot succeed, so we can try to
321 link A to B before blindly unlinking B, thus sometimes attempting to
322 link a second time during a successful 'ln -f A B'.
324 Try to unlink DEST even if we may have backed it up successfully.
325 In some unusual cases (when DEST and the backup are hard-links
326 that refer to the same file), rename succeeds and DEST remains.
327 If we didn't remove DEST in that case, the subsequent symlink or
328 link call would fail. */
329 link_errno
330 = (symbolic_link
331 ? force_symlinkat (source, destdir_fd, dest_base,
332 force, link_errno)
333 : force_linkat (AT_FDCWD, source, destdir_fd, dest_base,
334 logical ? AT_SYMLINK_FOLLOW : 0,
335 force, link_errno));
336 /* Until now, link_errno < 0 meant the link has not been tried.
337 From here on, link_errno < 0 means the link worked but
338 required removing the destination first. */
341 if (link_errno <= 0)
343 /* Right after creating a hard link, do this: (note dest name and
344 source_stats, which are also the just-linked-destinations stats) */
345 if (! symbolic_link)
346 record_file (dest_set, dest, &source_stats);
348 if (verbose)
350 char const *quoted_backup = "";
351 char const *backup_sep = "";
352 if (backup_base)
354 char *backup = backup_base;
355 void *alloc = NULL;
356 ptrdiff_t destdirlen = dest_base - dest;
357 if (0 < destdirlen)
359 alloc = xmalloc (destdirlen + strlen (backup_base) + 1);
360 backup = memcpy (alloc, dest, destdirlen);
361 strcpy (backup + destdirlen, backup_base);
363 quoted_backup = quoteaf_n (2, backup);
364 backup_sep = " ~ ";
365 free (alloc);
367 printf ("%s%s%s %c> %s\n", quoted_backup, backup_sep,
368 quoteaf_n (0, dest), symbolic_link ? '-' : '=',
369 quoteaf_n (1, source));
372 else
374 error (0, link_errno,
375 (symbolic_link
376 ? (link_errno != ENAMETOOLONG && *source
377 ? _("failed to create symbolic link %s")
378 : _("failed to create symbolic link %s -> %s"))
379 : (link_errno == EMLINK
380 ? _("failed to create hard link to %.0s%s")
381 : (link_errno == EDQUOT || link_errno == EEXIST
382 || link_errno == ENOSPC || link_errno == EROFS)
383 ? _("failed to create hard link %s")
384 : _("failed to create hard link %s => %s"))),
385 quoteaf_n (0, dest), quoteaf_n (1, source));
387 if (backup_base)
389 if (renameat (destdir_fd, backup_base, destdir_fd, dest_base) != 0)
390 error (0, errno, _("cannot un-backup %s"), quoteaf (dest));
394 free (backup_base);
395 free (rel_source);
396 return link_errno <= 0;
398 fail:
399 free (rel_source);
400 return false;
403 void
404 usage (int status)
406 if (status != EXIT_SUCCESS)
407 emit_try_help ();
408 else
410 printf (_("\
411 Usage: %s [OPTION]... [-T] TARGET LINK_NAME\n\
412 or: %s [OPTION]... TARGET\n\
413 or: %s [OPTION]... TARGET... DIRECTORY\n\
414 or: %s [OPTION]... -t DIRECTORY TARGET...\n\
416 program_name, program_name, program_name, program_name);
417 fputs (_("\
418 In the 1st form, create a link to TARGET with the name LINK_NAME.\n\
419 In the 2nd form, create a link to TARGET in the current directory.\n\
420 In the 3rd and 4th forms, create links to each TARGET in DIRECTORY.\n\
421 Create hard links by default, symbolic links with --symbolic.\n\
422 By default, each destination (name of new link) should not already exist.\n\
423 When creating hard links, each TARGET must exist. Symbolic links\n\
424 can hold arbitrary text; if later resolved, a relative link is\n\
425 interpreted in relation to its parent directory.\n\
426 "), stdout);
428 emit_mandatory_arg_note ();
430 fputs (_("\
431 --backup[=CONTROL] make a backup of each existing destination file\n\
432 -b like --backup but does not accept an argument\n\
433 -d, -F, --directory allow the superuser to attempt to hard link\n\
434 directories (note: will probably fail due to\n\
435 system restrictions, even for the superuser)\n\
436 -f, --force remove existing destination files\n\
437 "), stdout);
438 fputs (_("\
439 -i, --interactive prompt whether to remove destinations\n\
440 -L, --logical dereference TARGETs that are symbolic links\n\
441 -n, --no-dereference treat LINK_NAME as a normal file if\n\
442 it is a symbolic link to a directory\n\
443 -P, --physical make hard links directly to symbolic links\n\
444 -r, --relative with -s, create links relative to link location\n\
445 -s, --symbolic make symbolic links instead of hard links\n\
446 "), stdout);
447 fputs (_("\
448 -S, --suffix=SUFFIX override the usual backup suffix\n\
449 -t, --target-directory=DIRECTORY specify the DIRECTORY in which to create\n\
450 the links\n\
451 -T, --no-target-directory treat LINK_NAME as a normal file always\n\
452 -v, --verbose print name of each linked file\n\
453 "), stdout);
454 fputs (HELP_OPTION_DESCRIPTION, stdout);
455 fputs (VERSION_OPTION_DESCRIPTION, stdout);
456 emit_backup_suffix_note ();
457 printf (_("\
459 Using -s ignores -L and -P. Otherwise, the last option specified controls\n\
460 behavior when a TARGET is a symbolic link, defaulting to %s.\n\
461 "), LINK_FOLLOWS_SYMLINKS ? "-L" : "-P");
462 emit_ancillary_info (PROGRAM_NAME);
464 exit (status);
468 main (int argc, char **argv)
470 int c;
471 bool ok;
472 bool make_backups = false;
473 char const *backup_suffix = NULL;
474 char *version_control_string = NULL;
475 char const *target_directory = NULL;
476 int destdir_fd;
477 bool no_target_directory = false;
478 int n_files;
479 char **file;
480 int link_errno = -1;
482 initialize_main (&argc, &argv);
483 set_program_name (argv[0]);
484 setlocale (LC_ALL, "");
485 bindtextdomain (PACKAGE, LOCALEDIR);
486 textdomain (PACKAGE);
488 atexit (close_stdin);
490 symbolic_link = remove_existing_files = interactive = verbose
491 = hard_dir_link = false;
493 while ((c = getopt_long (argc, argv, "bdfinrst:vFLPS:T", long_options, NULL))
494 != -1)
496 switch (c)
498 case 'b':
499 make_backups = true;
500 if (optarg)
501 version_control_string = optarg;
502 break;
503 case 'd':
504 case 'F':
505 hard_dir_link = true;
506 break;
507 case 'f':
508 remove_existing_files = true;
509 interactive = false;
510 break;
511 case 'i':
512 remove_existing_files = false;
513 interactive = true;
514 break;
515 case 'L':
516 logical = true;
517 break;
518 case 'n':
519 dereference_dest_dir_symlinks = false;
520 break;
521 case 'P':
522 logical = false;
523 break;
524 case 'r':
525 relative = true;
526 break;
527 case 's':
528 symbolic_link = true;
529 break;
530 case 't':
531 if (target_directory)
532 die (EXIT_FAILURE, 0, _("multiple target directories specified"));
533 else
535 struct stat st;
536 if (stat (optarg, &st) != 0)
537 die (EXIT_FAILURE, errno, _("failed to access %s"),
538 quoteaf (optarg));
539 if (! S_ISDIR (st.st_mode))
540 die (EXIT_FAILURE, 0, _("target %s is not a directory"),
541 quoteaf (optarg));
543 target_directory = optarg;
544 break;
545 case 'T':
546 no_target_directory = true;
547 break;
548 case 'v':
549 verbose = true;
550 break;
551 case 'S':
552 make_backups = true;
553 backup_suffix = optarg;
554 break;
555 case_GETOPT_HELP_CHAR;
556 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
557 default:
558 usage (EXIT_FAILURE);
559 break;
563 n_files = argc - optind;
564 file = argv + optind;
566 if (n_files <= 0)
568 error (0, 0, _("missing file operand"));
569 usage (EXIT_FAILURE);
572 if (relative && !symbolic_link)
573 die (EXIT_FAILURE, 0, _("cannot do --relative without --symbolic"));
575 if (!hard_dir_link)
577 priv_set_remove_linkdir ();
578 beware_hard_dir_link = !cannot_unlink_dir ();
581 if (no_target_directory)
583 if (target_directory)
584 die (EXIT_FAILURE, 0,
585 _("cannot combine --target-directory "
586 "and --no-target-directory"));
587 if (n_files != 2)
589 if (n_files < 2)
590 error (0, 0,
591 _("missing destination file operand after %s"),
592 quoteaf (file[0]));
593 else
594 error (0, 0, _("extra operand %s"), quoteaf (file[2]));
595 usage (EXIT_FAILURE);
598 else if (n_files < 2 && !target_directory)
600 target_directory = ".";
601 destdir_fd = AT_FDCWD;
603 else
605 if (n_files == 2 && !target_directory)
606 link_errno = atomic_link (file[0], AT_FDCWD, file[1]);
607 if (link_errno < 0 || link_errno == EEXIST || link_errno == ENOTDIR
608 || link_errno == EINVAL)
610 char const *d
611 = target_directory ? target_directory : file[n_files - 1];
612 int flags = (O_PATHSEARCH | O_DIRECTORY
613 | (dereference_dest_dir_symlinks ? 0 : O_NOFOLLOW));
614 destdir_fd = openat_safer (AT_FDCWD, d, flags);
615 int err = errno;
616 if (!O_DIRECTORY && 0 <= destdir_fd)
618 struct stat st;
619 err = (fstat (destdir_fd, &st) != 0 ? errno
620 : S_ISDIR (st.st_mode) ? 0 : ENOTDIR);
621 if (err != 0)
623 close (destdir_fd);
624 destdir_fd = -1;
627 if (0 <= destdir_fd)
629 n_files -= !target_directory;
630 target_directory = d;
632 else if (! (n_files == 2 && !target_directory))
633 die (EXIT_FAILURE, err, _("target %s"), quoteaf (d));
637 backup_type = (make_backups
638 ? xget_version (_("backup type"), version_control_string)
639 : no_backups);
640 set_simple_backup_suffix (backup_suffix);
643 if (target_directory)
645 /* Create the data structure we'll use to record which hard links we
646 create. Used to ensure that ln detects an obscure corner case that
647 might result in user data loss. Create it only if needed. */
648 if (2 <= n_files
649 && remove_existing_files
650 /* Don't bother trying to protect symlinks, since ln clobbering
651 a just-created symlink won't ever lead to real data loss. */
652 && ! symbolic_link
653 /* No destination hard link can be clobbered when making
654 numbered backups. */
655 && backup_type != numbered_backups)
657 dest_set = hash_initialize (DEST_INFO_INITIAL_CAPACITY,
658 NULL,
659 triple_hash,
660 triple_compare,
661 triple_free);
662 if (dest_set == NULL)
663 xalloc_die ();
666 ok = true;
667 for (int i = 0; i < n_files; ++i)
669 char *dest_base;
670 char *dest = file_name_concat (target_directory,
671 last_component (file[i]),
672 &dest_base);
673 strip_trailing_slashes (dest_base);
674 ok &= do_link (file[i], destdir_fd, dest_base, dest, -1);
675 free (dest);
678 else
679 ok = do_link (file[0], AT_FDCWD, file[1], file[1], link_errno);
681 main_exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);