1 /* 'ln' program to create links between files.
2 Copyright (C) 1986-2022 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. */
21 #include <sys/types.h>
25 #include "backupfile.h"
28 #include "fcntl-safer.h"
29 #include "filenamecat.h"
31 #include "force-link.h"
33 #include "hash-triple.h"
37 #include "unlinkdir.h"
39 #include "canonicalize.h"
41 /* The official name of this program (e.g., no 'g' prefix). */
42 #define PROGRAM_NAME "ln"
45 proper_name ("Mike Parker"), \
46 proper_name ("David MacKenzie")
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 */
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. */
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
},
113 /* Return an errno value for a system call that returned STATUS.
114 This is zero if STATUS is zero, and is errno otherwise. */
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. */
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
;
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. */
162 atomic_link (char const *source
, int destdir_fd
, char const *dest_base
)
164 return (symbolic_link
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. */
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
;
189 link_errno
= atomic_link (source
, destdir_fd
, dest_base
);
191 /* Get SOURCE_STATS if later code will need it, if only for sharper
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
));
205 if (!symbolic_link
&& !hard_dir_link
&& S_ISDIR (source_stats
.st_mode
))
207 error (0, 0, _("%s: hard link not allowed for directory"),
213 source
= rel_source
= convert_abs_rel (source
, dest
);
215 bool force
= (remove_existing_files
|| interactive
216 || backup_type
!= no_backups
);
219 struct stat dest_stats
;
220 if (fstatat (destdir_fd
, dest_base
, &dest_stats
, AT_SYMLINK_NOFOLLOW
)
225 error (0, errno
, _("failed to access %s"), quoteaf (dest
));
230 else if (S_ISDIR (dest_stats
.st_mode
))
232 error (0, 0, _("%s: cannot overwrite directory"), quotef (dest
));
235 else if (seen_file (dest_set
, dest
, &dest_stats
))
237 /* The current target was created as a hard link to another
240 _("will not overwrite just-created %s with %s"),
241 quoteaf_n (0, dest
), quoteaf_n (1, source
));
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
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
));
275 if (link_errno
< 0 || link_errno
== EEXIST
)
279 fprintf (stderr
, _("%s: replace %s? "),
280 program_name
, quoteaf (dest
));
288 if (backup_type
!= no_backups
)
290 backup_base
= find_backup_file_name (destdir_fd
,
293 if (renameat (destdir_fd
, dest_base
,
294 destdir_fd
, backup_base
)
297 int rename_errno
= errno
;
300 if (rename_errno
!= ENOENT
)
302 error (0, rename_errno
, _("cannot backup %s"),
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. */
331 ? force_symlinkat (source
, destdir_fd
, dest_base
,
333 : force_linkat (AT_FDCWD
, source
, destdir_fd
, dest_base
,
334 logical
? AT_SYMLINK_FOLLOW
: 0,
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. */
343 /* Right after creating a hard link, do this: (note dest name and
344 source_stats, which are also the just-linked-destinations stats) */
346 record_file (dest_set
, dest
, &source_stats
);
350 char const *quoted_backup
= "";
351 char const *backup_sep
= "";
354 char *backup
= backup_base
;
356 ptrdiff_t destdirlen
= dest_base
- dest
;
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
);
367 printf ("%s%s%s %c> %s\n", quoted_backup
, backup_sep
,
368 quoteaf_n (0, dest
), symbolic_link
? '-' : '=',
369 quoteaf_n (1, source
));
374 error (0, link_errno
,
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
));
389 if (renameat (destdir_fd
, backup_base
, destdir_fd
, dest_base
) != 0)
390 error (0, errno
, _("cannot un-backup %s"), quoteaf (dest
));
396 return link_errno
<= 0;
406 if (status
!= EXIT_SUCCESS
)
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
);
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\
428 emit_mandatory_arg_note ();
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\
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\
448 -S, --suffix=SUFFIX override the usual backup suffix\n\
449 -t, --target-directory=DIRECTORY specify the DIRECTORY in which to create\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\
454 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
455 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
456 emit_backup_suffix_note ();
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
);
468 main (int argc
, char **argv
)
472 bool make_backups
= false;
473 char const *backup_suffix
= NULL
;
474 char *version_control_string
= NULL
;
475 char const *target_directory
= NULL
;
477 bool no_target_directory
= false;
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
))
501 version_control_string
= optarg
;
505 hard_dir_link
= true;
508 remove_existing_files
= true;
512 remove_existing_files
= false;
519 dereference_dest_dir_symlinks
= false;
528 symbolic_link
= true;
531 if (target_directory
)
532 die (EXIT_FAILURE
, 0, _("multiple target directories specified"));
536 if (stat (optarg
, &st
) != 0)
537 die (EXIT_FAILURE
, errno
, _("failed to access %s"),
539 if (! S_ISDIR (st
.st_mode
))
540 die (EXIT_FAILURE
, 0, _("target %s is not a directory"),
543 target_directory
= optarg
;
546 no_target_directory
= true;
553 backup_suffix
= optarg
;
555 case_GETOPT_HELP_CHAR
;
556 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
558 usage (EXIT_FAILURE
);
563 n_files
= argc
- optind
;
564 file
= argv
+ optind
;
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"));
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"));
591 _("missing destination file operand after %s"),
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
;
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
)
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
);
616 if (!O_DIRECTORY
&& 0 <= destdir_fd
)
619 err
= (fstat (destdir_fd
, &st
) != 0 ? errno
620 : S_ISDIR (st
.st_mode
) ? 0 : ENOTDIR
);
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
)
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. */
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. */
653 /* No destination hard link can be clobbered when making
655 && backup_type
!= numbered_backups
)
657 dest_set
= hash_initialize (DEST_INFO_INITIAL_CAPACITY
,
662 if (dest_set
== NULL
)
667 for (int i
= 0; i
< n_files
; ++i
)
670 char *dest
= file_name_concat (target_directory
,
671 last_component (file
[i
]),
673 strip_trailing_slashes (dest_base
);
674 ok
&= do_link (file
[i
], destdir_fd
, dest_base
, dest
, -1);
680 hash_free (dest_set
);
685 ok
= do_link (file
[0], AT_FDCWD
, file
[1], file
[1], link_errno
);
687 return ok
? EXIT_SUCCESS
: EXIT_FAILURE
;