1 /* 'ln' program to create links between files.
2 Copyright (C) 1986-2016 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. */
21 #include <sys/types.h>
25 #include "backupfile.h"
28 #include "filenamecat.h"
31 #include "hash-triple.h"
35 #include "canonicalize.h"
37 /* The official name of this program (e.g., no 'g' prefix). */
38 #define PROGRAM_NAME "ln"
41 proper_name ("Mike Parker"), \
42 proper_name ("David MacKenzie")
45 static enum backup_type backup_type
;
47 /* If true, make symbolic links; otherwise, make hard links. */
48 static bool symbolic_link
;
50 /* If true, make symbolic links relative */
53 /* If true, hard links are logical rather than physical. */
54 static bool logical
= !!LINK_FOLLOWS_SYMLINKS
;
56 /* If true, ask the user before removing existing files. */
57 static bool interactive
;
59 /* If true, remove existing files unconditionally. */
60 static bool remove_existing_files
;
62 /* If true, list each file as it is moved. */
65 /* If true, allow the superuser to *attempt* to make hard links
66 to directories. However, it appears that this option is not useful
67 in practice, since even the superuser is prohibited from hard-linking
68 directories on most existing systems (Solaris being an exception). */
69 static bool hard_dir_link
;
71 /* If nonzero, and the specified destination is a symbolic link to a
72 directory, treat it just as if it were a directory. Otherwise, the
73 command 'ln --force --no-dereference file symlink-to-dir' deletes
74 symlink-to-dir before creating the new link. */
75 static bool dereference_dest_dir_symlinks
= true;
77 /* This is a set of destination name/inode/dev triples for hard links
78 created by ln. Use this data structure to avoid data loss via a
79 sequence of commands like this:
80 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 */
81 static Hash_table
*dest_set
;
83 /* Initial size of the dest_set hash table. */
84 enum { DEST_INFO_INITIAL_CAPACITY
= 61 };
86 static struct option
const long_options
[] =
88 {"backup", optional_argument
, NULL
, 'b'},
89 {"directory", no_argument
, NULL
, 'F'},
90 {"no-dereference", no_argument
, NULL
, 'n'},
91 {"no-target-directory", no_argument
, NULL
, 'T'},
92 {"force", no_argument
, NULL
, 'f'},
93 {"interactive", no_argument
, NULL
, 'i'},
94 {"suffix", required_argument
, NULL
, 'S'},
95 {"target-directory", required_argument
, NULL
, 't'},
96 {"logical", no_argument
, NULL
, 'L'},
97 {"physical", no_argument
, NULL
, 'P'},
98 {"relative", no_argument
, NULL
, 'r'},
99 {"symbolic", no_argument
, NULL
, 's'},
100 {"verbose", no_argument
, NULL
, 'v'},
101 {GETOPT_HELP_OPTION_DECL
},
102 {GETOPT_VERSION_OPTION_DECL
},
106 /* Return true when the passed ERR implies
107 that a file does not or could not exist. */
110 errno_nonexisting (int err
)
112 return err
== ENOENT
|| err
== ENAMETOOLONG
|| err
== ENOTDIR
|| err
== ELOOP
;
116 /* FILE is the last operand of this command. Return true if FILE is a
117 directory. But report an error if there is a problem accessing FILE,
118 or if FILE does not exist but would have to refer to an existing
119 directory if it referred to anything at all. */
122 target_directory_operand (char const *file
)
124 char const *b
= last_component (file
);
125 size_t blen
= strlen (b
);
126 bool looks_like_a_dir
= (blen
== 0 || ISSLASH (b
[blen
- 1]));
129 (dereference_dest_dir_symlinks
? stat (file
, &st
) : lstat (file
, &st
));
130 int err
= (stat_result
== 0 ? 0 : errno
);
131 bool is_a_dir
= !err
&& S_ISDIR (st
.st_mode
);
132 if (err
&& ! errno_nonexisting (errno
))
133 die (EXIT_FAILURE
, err
, _("failed to access %s"), quoteaf (file
));
134 if (is_a_dir
< looks_like_a_dir
)
135 die (EXIT_FAILURE
, err
, _("target %s is not a directory"),
140 /* Return FROM represented as relative to the dir of TARGET.
141 The result is malloced. */
144 convert_abs_rel (const char *from
, const char *target
)
146 /* Get dirname to generate paths relative to. We don't resolve
147 the full TARGET as the last component could be an existing symlink. */
148 char *targetdir
= dir_name (target
);
150 char *realdest
= canonicalize_filename_mode (targetdir
, CAN_MISSING
);
151 char *realfrom
= canonicalize_filename_mode (from
, CAN_MISSING
);
153 char *relative_from
= NULL
;
154 if (realdest
&& realfrom
)
156 /* Write to a PATH_MAX buffer. */
157 relative_from
= xmalloc (PATH_MAX
);
159 if (!relpath (realfrom
, realdest
, relative_from
, PATH_MAX
))
161 free (relative_from
);
162 relative_from
= NULL
;
170 return relative_from
? relative_from
: xstrdup (from
);
173 /* Make a link DEST to the (usually) existing file SOURCE.
174 Symbolic links to nonexistent files are allowed.
175 Return true if successful. */
178 do_link (const char *source
, const char *dest
)
180 struct stat source_stats
;
181 struct stat dest_stats
;
182 char *dest_backup
= NULL
;
183 char *rel_source
= NULL
;
184 bool dest_lstat_ok
= false;
185 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 ok
= ((symbolic_link
? symlink (source
, dest
)
305 : linkat (AT_FDCWD
, source
, AT_FDCWD
, dest
,
306 logical
? AT_SYMLINK_FOLLOW
: 0))
309 /* If the attempt to create a link failed and we are removing or
310 backing up destinations, unlink the destination and try again.
312 On the surface, POSIX describes an algorithm that states that
313 'ln -f A B' will call unlink() on B before ever attempting
314 link() on A. But strictly following this has the counterintuitive
315 effect of losing the contents of B, if A does not exist.
316 Fortunately, POSIX 2008 clarified that an application is free
317 to fail early if it can prove that continuing onwards cannot
318 succeed, so we are justified in trying link() before blindly
319 removing B, thus sometimes calling link() a second time during
320 a successful 'ln -f A B'.
322 Try to unlink DEST even if we may have backed it up successfully.
323 In some unusual cases (when DEST and DEST_BACKUP are hard-links
324 that refer to the same file), rename succeeds and DEST remains.
325 If we didn't remove DEST in that case, the subsequent symlink or link
328 if (!ok
&& errno
== EEXIST
&& (remove_existing_files
|| dest_backup
))
330 if (unlink (dest
) != 0)
332 error (0, errno
, _("cannot remove %s"), quoteaf (dest
));
338 ok
= ((symbolic_link
? symlink (source
, dest
)
339 : linkat (AT_FDCWD
, source
, AT_FDCWD
, dest
,
340 logical
? AT_SYMLINK_FOLLOW
: 0))
346 /* Right after creating a hard link, do this: (note dest name and
347 source_stats, which are also the just-linked-destinations stats) */
349 record_file (dest_set
, dest
, &source_stats
);
354 printf ("%s ~ ", quoteaf (dest_backup
));
355 printf ("%s %c> %s\n", quoteaf_n (0, dest
),
356 (symbolic_link
? '-' : '='), quoteaf_n (1, source
));
363 ? (errno
!= ENAMETOOLONG
&& *source
364 ? _("failed to create symbolic link %s")
365 : _("failed to create symbolic link %s -> %s"))
366 : (errno
== EMLINK
&& !source_is_dir
367 ? _("failed to create hard link to %.0s%s")
368 : (errno
== EDQUOT
|| errno
== EEXIST
|| errno
== ENOSPC
370 ? _("failed to create hard link %s")
371 : _("failed to create hard link %s => %s"))),
372 quoteaf_n (0, dest
), quoteaf_n (1, source
));
376 if (rename (dest_backup
, dest
) != 0)
377 error (0, errno
, _("cannot un-backup %s"), quoteaf (dest
));
389 if (status
!= EXIT_SUCCESS
)
394 Usage: %s [OPTION]... [-T] TARGET LINK_NAME (1st form)\n\
395 or: %s [OPTION]... TARGET (2nd form)\n\
396 or: %s [OPTION]... TARGET... DIRECTORY (3rd form)\n\
397 or: %s [OPTION]... -t DIRECTORY TARGET... (4th form)\n\
399 program_name
, program_name
, program_name
, program_name
);
401 In the 1st form, create a link to TARGET with the name LINK_NAME.\n\
402 In the 2nd form, create a link to TARGET in the current directory.\n\
403 In the 3rd and 4th forms, create links to each TARGET in DIRECTORY.\n\
404 Create hard links by default, symbolic links with --symbolic.\n\
405 By default, each destination (name of new link) should not already exist.\n\
406 When creating hard links, each TARGET must exist. Symbolic links\n\
407 can hold arbitrary text; if later resolved, a relative link is\n\
408 interpreted in relation to its parent directory.\n\
411 emit_mandatory_arg_note ();
414 --backup[=CONTROL] make a backup of each existing destination file\n\
415 -b like --backup but does not accept an argument\n\
416 -d, -F, --directory allow the superuser to attempt to hard link\n\
417 directories (note: will probably fail due to\n\
418 system restrictions, even for the superuser)\n\
419 -f, --force remove existing destination files\n\
422 -i, --interactive prompt whether to remove destinations\n\
423 -L, --logical dereference TARGETs that are symbolic links\n\
424 -n, --no-dereference treat LINK_NAME as a normal file if\n\
425 it is a symbolic link to a directory\n\
426 -P, --physical make hard links directly to symbolic links\n\
427 -r, --relative create symbolic links relative to link location\n\
428 -s, --symbolic make symbolic links instead of hard links\n\
431 -S, --suffix=SUFFIX override the usual backup suffix\n\
432 -t, --target-directory=DIRECTORY specify the DIRECTORY in which to create\n\
434 -T, --no-target-directory treat LINK_NAME as a normal file always\n\
435 -v, --verbose print name of each linked file\n\
437 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
438 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
439 emit_backup_suffix_note ();
442 Using -s ignores -L and -P. Otherwise, the last option specified controls\n\
443 behavior when a TARGET is a symbolic link, defaulting to %s.\n\
444 "), LINK_FOLLOWS_SYMLINKS
? "-L" : "-P");
445 emit_ancillary_info (PROGRAM_NAME
);
451 main (int argc
, char **argv
)
455 bool make_backups
= false;
456 char *version_control_string
= NULL
;
457 char const *target_directory
= NULL
;
458 bool no_target_directory
= false;
462 initialize_main (&argc
, &argv
);
463 set_program_name (argv
[0]);
464 setlocale (LC_ALL
, "");
465 bindtextdomain (PACKAGE
, LOCALEDIR
);
466 textdomain (PACKAGE
);
468 atexit (close_stdin
);
470 symbolic_link
= remove_existing_files
= interactive
= verbose
471 = hard_dir_link
= false;
473 while ((c
= getopt_long (argc
, argv
, "bdfinrst:vFLPS:T", long_options
, NULL
))
481 version_control_string
= optarg
;
485 hard_dir_link
= true;
488 remove_existing_files
= true;
492 remove_existing_files
= false;
499 dereference_dest_dir_symlinks
= false;
508 symbolic_link
= true;
511 if (target_directory
)
512 die (EXIT_FAILURE
, 0, _("multiple target directories specified"));
516 if (stat (optarg
, &st
) != 0)
517 die (EXIT_FAILURE
, errno
, _("failed to access %s"),
519 if (! S_ISDIR (st
.st_mode
))
520 die (EXIT_FAILURE
, 0, _("target %s is not a directory"),
523 target_directory
= optarg
;
526 no_target_directory
= true;
533 simple_backup_suffix
= optarg
;
535 case_GETOPT_HELP_CHAR
;
536 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
538 usage (EXIT_FAILURE
);
543 n_files
= argc
- optind
;
544 file
= argv
+ optind
;
548 error (0, 0, _("missing file operand"));
549 usage (EXIT_FAILURE
);
552 if (no_target_directory
)
554 if (target_directory
)
555 die (EXIT_FAILURE
, 0,
556 _("cannot combine --target-directory "
557 "and --no-target-directory"));
562 _("missing destination file operand after %s"),
565 error (0, 0, _("extra operand %s"), quoteaf (file
[2]));
566 usage (EXIT_FAILURE
);
569 else if (!target_directory
)
572 target_directory
= ".";
573 else if (2 <= n_files
&& target_directory_operand (file
[n_files
- 1]))
574 target_directory
= file
[--n_files
];
575 else if (2 < n_files
)
576 die (EXIT_FAILURE
, 0, _("target %s is not a directory"),
577 quoteaf (file
[n_files
- 1]));
580 backup_type
= (make_backups
581 ? xget_version (_("backup type"), version_control_string
)
584 if (relative
&& !symbolic_link
)
586 die (EXIT_FAILURE
, 0,
587 _("cannot do --relative without --symbolic"));
591 if (target_directory
)
595 /* Create the data structure we'll use to record which hard links we
596 create. Used to ensure that ln detects an obscure corner case that
597 might result in user data loss. Create it only if needed. */
599 && remove_existing_files
600 /* Don't bother trying to protect symlinks, since ln clobbering
601 a just-created symlink won't ever lead to real data loss. */
603 /* No destination hard link can be clobbered when making
605 && backup_type
!= numbered_backups
)
608 dest_set
= hash_initialize (DEST_INFO_INITIAL_CAPACITY
,
613 if (dest_set
== NULL
)
618 for (i
= 0; i
< n_files
; ++i
)
621 char *dest
= file_name_concat (target_directory
,
622 last_component (file
[i
]),
624 strip_trailing_slashes (dest_base
);
625 ok
&= do_link (file
[i
], dest
);
630 ok
= do_link (file
[0], file
[1]);
632 return ok
? EXIT_SUCCESS
: EXIT_FAILURE
;