1 /* 'ln' program to create links between files.
2 Copyright (C) 1986-2017 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 "filenamecat.h"
30 #include "force-link.h"
32 #include "hash-triple.h"
36 #include "canonicalize.h"
38 /* The official name of this program (e.g., no 'g' prefix). */
39 #define PROGRAM_NAME "ln"
42 proper_name ("Mike Parker"), \
43 proper_name ("David MacKenzie")
46 static enum backup_type backup_type
;
48 /* If true, make symbolic links; otherwise, make hard links. */
49 static bool symbolic_link
;
51 /* If true, make symbolic links relative */
54 /* If true, hard links are logical rather than physical. */
55 static bool logical
= !!LINK_FOLLOWS_SYMLINKS
;
57 /* If true, ask the user before removing existing files. */
58 static bool interactive
;
60 /* If true, remove existing files unconditionally. */
61 static bool remove_existing_files
;
63 /* If true, list each file as it is moved. */
66 /* If true, allow the superuser to *attempt* to make hard links
67 to directories. However, it appears that this option is not useful
68 in practice, since even the superuser is prohibited from hard-linking
69 directories on most existing systems (Solaris being an exception). */
70 static bool hard_dir_link
;
72 /* If nonzero, and the specified destination is a symbolic link to a
73 directory, treat it just as if it were a directory. Otherwise, the
74 command 'ln --force --no-dereference file symlink-to-dir' deletes
75 symlink-to-dir before creating the new link. */
76 static bool dereference_dest_dir_symlinks
= true;
78 /* This is a set of destination name/inode/dev triples for hard links
79 created by ln. Use this data structure to avoid data loss via a
80 sequence of commands like this:
81 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 */
82 static Hash_table
*dest_set
;
84 /* Initial size of the dest_set hash table. */
85 enum { DEST_INFO_INITIAL_CAPACITY
= 61 };
87 static struct option
const long_options
[] =
89 {"backup", optional_argument
, NULL
, 'b'},
90 {"directory", no_argument
, NULL
, 'F'},
91 {"no-dereference", no_argument
, NULL
, 'n'},
92 {"no-target-directory", no_argument
, NULL
, 'T'},
93 {"force", no_argument
, NULL
, 'f'},
94 {"interactive", no_argument
, NULL
, 'i'},
95 {"suffix", required_argument
, NULL
, 'S'},
96 {"target-directory", required_argument
, NULL
, 't'},
97 {"logical", no_argument
, NULL
, 'L'},
98 {"physical", no_argument
, NULL
, 'P'},
99 {"relative", no_argument
, NULL
, 'r'},
100 {"symbolic", no_argument
, NULL
, 's'},
101 {"verbose", no_argument
, NULL
, 'v'},
102 {GETOPT_HELP_OPTION_DECL
},
103 {GETOPT_VERSION_OPTION_DECL
},
107 /* Return true when the passed ERR implies
108 that a file does not or could not exist. */
111 errno_nonexisting (int err
)
113 return err
== ENOENT
|| err
== ENAMETOOLONG
|| err
== ENOTDIR
|| err
== ELOOP
;
117 /* FILE is the last operand of this command. Return true if FILE is a
118 directory. But report an error if there is a problem accessing FILE,
119 or if FILE does not exist but would have to refer to an existing
120 directory if it referred to anything at all. */
123 target_directory_operand (char const *file
)
125 char const *b
= last_component (file
);
126 size_t blen
= strlen (b
);
127 bool looks_like_a_dir
= (blen
== 0 || ISSLASH (b
[blen
- 1]));
130 (dereference_dest_dir_symlinks
? stat (file
, &st
) : lstat (file
, &st
));
131 int err
= (stat_result
== 0 ? 0 : errno
);
132 bool is_a_dir
= !err
&& S_ISDIR (st
.st_mode
);
133 if (err
&& ! errno_nonexisting (errno
))
134 die (EXIT_FAILURE
, err
, _("failed to access %s"), quoteaf (file
));
135 if (is_a_dir
< looks_like_a_dir
)
136 die (EXIT_FAILURE
, err
, _("target %s is not a directory"),
141 /* Return FROM represented as relative to the dir of TARGET.
142 The result is malloced. */
145 convert_abs_rel (const char *from
, const char *target
)
147 /* Get dirname to generate paths relative to. We don't resolve
148 the full TARGET as the last component could be an existing symlink. */
149 char *targetdir
= dir_name (target
);
151 char *realdest
= canonicalize_filename_mode (targetdir
, CAN_MISSING
);
152 char *realfrom
= canonicalize_filename_mode (from
, CAN_MISSING
);
154 char *relative_from
= NULL
;
155 if (realdest
&& realfrom
)
157 /* Write to a PATH_MAX buffer. */
158 relative_from
= xmalloc (PATH_MAX
);
160 if (!relpath (realfrom
, realdest
, relative_from
, PATH_MAX
))
162 free (relative_from
);
163 relative_from
= NULL
;
171 return relative_from
? relative_from
: xstrdup (from
);
174 /* Make a link DEST to the (usually) existing file SOURCE.
175 Symbolic links to nonexistent files are allowed.
176 Return true if successful. */
179 do_link (const char *source
, const char *dest
)
181 struct stat source_stats
;
182 struct stat dest_stats
;
183 char *dest_backup
= NULL
;
184 char *rel_source
= NULL
;
185 bool dest_lstat_ok
= false;
186 bool source_is_dir
= false;
190 /* Which stat to use depends on whether linkat will follow the
191 symlink. We can't use the shorter
192 (logical?stat:lstat) (source, &source_stats)
193 since stat might be a function-like macro. */
194 if ((logical
? stat (source
, &source_stats
)
195 : lstat (source
, &source_stats
))
198 error (0, errno
, _("failed to access %s"), quoteaf (source
));
202 if (S_ISDIR (source_stats
.st_mode
))
204 source_is_dir
= true;
207 error (0, 0, _("%s: hard link not allowed for directory"),
214 if (remove_existing_files
|| interactive
|| backup_type
!= no_backups
)
216 dest_lstat_ok
= (lstat (dest
, &dest_stats
) == 0);
217 if (!dest_lstat_ok
&& errno
!= ENOENT
)
219 error (0, errno
, _("failed to access %s"), quoteaf (dest
));
224 /* If the current target was created as a hard link to another
225 source file, then refuse to unlink it. */
228 && seen_file (dest_set
, dest
, &dest_stats
))
231 _("will not overwrite just-created %s with %s"),
232 quoteaf_n (0, dest
), quoteaf_n (1, source
));
236 /* If --force (-f) has been specified without --backup, then before
237 making a link ln must remove the destination file if it exists.
238 (with --backup, it just renames any existing destination file)
239 But if the source and destination are the same, don't remove
240 anything and fail right here. */
241 if ((remove_existing_files
242 /* Ensure that "ln --backup f f" fails here, with the
243 "... same file" diagnostic, below. Otherwise, subsequent
244 code would give a misleading "file not found" diagnostic.
245 This case is different than the others handled here, since
246 the command in question doesn't use --force. */
247 || (!symbolic_link
&& backup_type
!= no_backups
))
249 /* Allow 'ln -sf --backup k k' to succeed in creating the
250 self-referential symlink, but don't allow the hard-linking
251 equivalent: 'ln -f k k' (with or without --backup) to get
252 beyond this point, because the error message you'd get is
254 && (backup_type
== no_backups
|| !symbolic_link
)
255 && (!symbolic_link
|| stat (source
, &source_stats
) == 0)
256 && SAME_INODE (source_stats
, dest_stats
)
257 /* The following detects whether removing DEST will also remove
258 SOURCE. If the file has only one link then both are surely
259 the same link. Otherwise check whether they point to the same
260 name in the same directory. */
261 && (source_stats
.st_nlink
== 1 || same_name (source
, dest
)))
263 error (0, 0, _("%s and %s are the same file"),
264 quoteaf_n (0, source
), quoteaf_n (1, dest
));
270 if (S_ISDIR (dest_stats
.st_mode
))
272 error (0, 0, _("%s: cannot overwrite directory"), quotef (dest
));
277 fprintf (stderr
, _("%s: replace %s? "), program_name
, quoteaf (dest
));
280 remove_existing_files
= true;
283 if (backup_type
!= no_backups
)
285 dest_backup
= find_backup_file_name (dest
, backup_type
);
286 if (rename (dest
, dest_backup
) != 0)
288 int rename_errno
= errno
;
291 if (rename_errno
!= ENOENT
)
293 error (0, rename_errno
, _("cannot backup %s"),
302 source
= rel_source
= convert_abs_rel (source
, dest
);
304 /* If the attempt to create a link fails and we are removing or
305 backing up destinations, unlink the destination and try again.
307 On the surface, POSIX describes an algorithm that states that
308 'ln -f A B' will call unlink() on B before ever attempting
309 link() on A. But strictly following this has the counterintuitive
310 effect of losing the contents of B, if A does not exist.
311 Fortunately, POSIX 2008 clarified that an application is free
312 to fail early if it can prove that continuing onwards cannot
313 succeed, so we are justified in trying link() before blindly
314 removing B, thus sometimes calling link() a second time during
315 a successful 'ln -f A B'.
317 Try to unlink DEST even if we may have backed it up successfully.
318 In some unusual cases (when DEST and DEST_BACKUP are hard-links
319 that refer to the same file), rename succeeds and DEST remains.
320 If we didn't remove DEST in that case, the subsequent symlink or link
322 bool ok_to_remove
= remove_existing_files
|| dest_backup
;
323 bool ok
= 0 <= (symbolic_link
324 ? force_symlinkat (source
, AT_FDCWD
, dest
, ok_to_remove
)
325 : force_linkat (AT_FDCWD
, source
, AT_FDCWD
, dest
,
326 logical
? AT_SYMLINK_FOLLOW
: 0,
331 /* Right after creating a hard link, do this: (note dest name and
332 source_stats, which are also the just-linked-destinations stats) */
334 record_file (dest_set
, dest
, &source_stats
);
339 printf ("%s ~ ", quoteaf (dest_backup
));
340 printf ("%s %c> %s\n", quoteaf_n (0, dest
),
341 (symbolic_link
? '-' : '='), quoteaf_n (1, source
));
348 ? (errno
!= ENAMETOOLONG
&& *source
349 ? _("failed to create symbolic link %s")
350 : _("failed to create symbolic link %s -> %s"))
351 : (errno
== EMLINK
&& !source_is_dir
352 ? _("failed to create hard link to %.0s%s")
353 : (errno
== EDQUOT
|| errno
== EEXIST
|| errno
== ENOSPC
355 ? _("failed to create hard link %s")
356 : _("failed to create hard link %s => %s"))),
357 quoteaf_n (0, dest
), quoteaf_n (1, source
));
361 if (rename (dest_backup
, dest
) != 0)
362 error (0, errno
, _("cannot un-backup %s"), quoteaf (dest
));
374 if (status
!= EXIT_SUCCESS
)
379 Usage: %s [OPTION]... [-T] TARGET LINK_NAME (1st form)\n\
380 or: %s [OPTION]... TARGET (2nd form)\n\
381 or: %s [OPTION]... TARGET... DIRECTORY (3rd form)\n\
382 or: %s [OPTION]... -t DIRECTORY TARGET... (4th form)\n\
384 program_name
, program_name
, program_name
, program_name
);
386 In the 1st form, create a link to TARGET with the name LINK_NAME.\n\
387 In the 2nd form, create a link to TARGET in the current directory.\n\
388 In the 3rd and 4th forms, create links to each TARGET in DIRECTORY.\n\
389 Create hard links by default, symbolic links with --symbolic.\n\
390 By default, each destination (name of new link) should not already exist.\n\
391 When creating hard links, each TARGET must exist. Symbolic links\n\
392 can hold arbitrary text; if later resolved, a relative link is\n\
393 interpreted in relation to its parent directory.\n\
396 emit_mandatory_arg_note ();
399 --backup[=CONTROL] make a backup of each existing destination file\n\
400 -b like --backup but does not accept an argument\n\
401 -d, -F, --directory allow the superuser to attempt to hard link\n\
402 directories (note: will probably fail due to\n\
403 system restrictions, even for the superuser)\n\
404 -f, --force remove existing destination files\n\
407 -i, --interactive prompt whether to remove destinations\n\
408 -L, --logical dereference TARGETs that are symbolic links\n\
409 -n, --no-dereference treat LINK_NAME as a normal file if\n\
410 it is a symbolic link to a directory\n\
411 -P, --physical make hard links directly to symbolic links\n\
412 -r, --relative create symbolic links relative to link location\n\
413 -s, --symbolic make symbolic links instead of hard links\n\
416 -S, --suffix=SUFFIX override the usual backup suffix\n\
417 -t, --target-directory=DIRECTORY specify the DIRECTORY in which to create\n\
419 -T, --no-target-directory treat LINK_NAME as a normal file always\n\
420 -v, --verbose print name of each linked file\n\
422 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
423 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
424 emit_backup_suffix_note ();
427 Using -s ignores -L and -P. Otherwise, the last option specified controls\n\
428 behavior when a TARGET is a symbolic link, defaulting to %s.\n\
429 "), LINK_FOLLOWS_SYMLINKS
? "-L" : "-P");
430 emit_ancillary_info (PROGRAM_NAME
);
436 main (int argc
, char **argv
)
440 bool make_backups
= false;
441 char const *backup_suffix
= NULL
;
442 char *version_control_string
= NULL
;
443 char const *target_directory
= NULL
;
444 bool no_target_directory
= false;
448 initialize_main (&argc
, &argv
);
449 set_program_name (argv
[0]);
450 setlocale (LC_ALL
, "");
451 bindtextdomain (PACKAGE
, LOCALEDIR
);
452 textdomain (PACKAGE
);
454 atexit (close_stdin
);
456 symbolic_link
= remove_existing_files
= interactive
= verbose
457 = hard_dir_link
= false;
459 while ((c
= getopt_long (argc
, argv
, "bdfinrst:vFLPS:T", long_options
, NULL
))
467 version_control_string
= optarg
;
471 hard_dir_link
= true;
474 remove_existing_files
= true;
478 remove_existing_files
= false;
485 dereference_dest_dir_symlinks
= false;
494 symbolic_link
= true;
497 if (target_directory
)
498 die (EXIT_FAILURE
, 0, _("multiple target directories specified"));
502 if (stat (optarg
, &st
) != 0)
503 die (EXIT_FAILURE
, errno
, _("failed to access %s"),
505 if (! S_ISDIR (st
.st_mode
))
506 die (EXIT_FAILURE
, 0, _("target %s is not a directory"),
509 target_directory
= optarg
;
512 no_target_directory
= true;
519 backup_suffix
= optarg
;
521 case_GETOPT_HELP_CHAR
;
522 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
524 usage (EXIT_FAILURE
);
529 n_files
= argc
- optind
;
530 file
= argv
+ optind
;
534 error (0, 0, _("missing file operand"));
535 usage (EXIT_FAILURE
);
538 if (no_target_directory
)
540 if (target_directory
)
541 die (EXIT_FAILURE
, 0,
542 _("cannot combine --target-directory "
543 "and --no-target-directory"));
548 _("missing destination file operand after %s"),
551 error (0, 0, _("extra operand %s"), quoteaf (file
[2]));
552 usage (EXIT_FAILURE
);
555 else if (!target_directory
)
558 target_directory
= ".";
559 else if (2 <= n_files
&& target_directory_operand (file
[n_files
- 1]))
560 target_directory
= file
[--n_files
];
561 else if (2 < n_files
)
562 die (EXIT_FAILURE
, 0, _("target %s is not a directory"),
563 quoteaf (file
[n_files
- 1]));
566 backup_type
= (make_backups
567 ? xget_version (_("backup type"), version_control_string
)
569 set_simple_backup_suffix (backup_suffix
);
571 if (relative
&& !symbolic_link
)
573 die (EXIT_FAILURE
, 0,
574 _("cannot do --relative without --symbolic"));
578 if (target_directory
)
580 /* Create the data structure we'll use to record which hard links we
581 create. Used to ensure that ln detects an obscure corner case that
582 might result in user data loss. Create it only if needed. */
584 && remove_existing_files
585 /* Don't bother trying to protect symlinks, since ln clobbering
586 a just-created symlink won't ever lead to real data loss. */
588 /* No destination hard link can be clobbered when making
590 && backup_type
!= numbered_backups
)
593 dest_set
= hash_initialize (DEST_INFO_INITIAL_CAPACITY
,
598 if (dest_set
== NULL
)
603 for (int i
= 0; i
< n_files
; ++i
)
606 char *dest
= file_name_concat (target_directory
,
607 last_component (file
[i
]),
609 strip_trailing_slashes (dest_base
);
610 ok
&= do_link (file
[i
], dest
);
615 ok
= do_link (file
[0], file
[1]);
617 return ok
? EXIT_SUCCESS
: EXIT_FAILURE
;