1 /* `ln' program to create links between files.
2 Copyright (C) 1986, 1989-1991, 1995-2011 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"
27 #include "filenamecat.h"
30 #include "hash-triple.h"
35 /* The official name of this program (e.g., no `g' prefix). */
36 #define PROGRAM_NAME "ln"
39 proper_name ("Mike Parker"), \
40 proper_name ("David MacKenzie")
43 static enum backup_type backup_type
;
45 /* If true, make symbolic links; otherwise, make hard links. */
46 static bool symbolic_link
;
48 /* If true, hard links are logical rather than physical. */
49 static bool logical
= !!LINK_FOLLOWS_SYMLINKS
;
51 /* If true, ask the user before removing existing files. */
52 static bool interactive
;
54 /* If true, remove existing files unconditionally. */
55 static bool remove_existing_files
;
57 /* If true, list each file as it is moved. */
60 /* If true, allow the superuser to *attempt* to make hard links
61 to directories. However, it appears that this option is not useful
62 in practice, since even the superuser is prohibited from hard-linking
63 directories on most existing systems (Solaris being an exception). */
64 static bool hard_dir_link
;
66 /* If nonzero, and the specified destination is a symbolic link to a
67 directory, treat it just as if it were a directory. Otherwise, the
68 command `ln --force --no-dereference file symlink-to-dir' deletes
69 symlink-to-dir before creating the new link. */
70 static bool dereference_dest_dir_symlinks
= true;
72 /* This is a set of destination name/inode/dev triples for hard links
73 created by ln. Use this data structure to avoid data loss via a
74 sequence of commands like this:
75 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 */
76 static Hash_table
*dest_set
;
78 /* Initial size of the dest_set hash table. */
79 enum { DEST_INFO_INITIAL_CAPACITY
= 61 };
81 static struct option
const long_options
[] =
83 {"backup", optional_argument
, NULL
, 'b'},
84 {"directory", no_argument
, NULL
, 'F'},
85 {"no-dereference", no_argument
, NULL
, 'n'},
86 {"no-target-directory", no_argument
, NULL
, 'T'},
87 {"force", no_argument
, NULL
, 'f'},
88 {"interactive", no_argument
, NULL
, 'i'},
89 {"suffix", required_argument
, NULL
, 'S'},
90 {"target-directory", required_argument
, NULL
, 't'},
91 {"logical", no_argument
, NULL
, 'L'},
92 {"physical", no_argument
, NULL
, 'P'},
93 {"symbolic", no_argument
, NULL
, 's'},
94 {"verbose", no_argument
, NULL
, 'v'},
95 {GETOPT_HELP_OPTION_DECL
},
96 {GETOPT_VERSION_OPTION_DECL
},
100 /* FILE is the last operand of this command. Return true if FILE is a
101 directory. But report an error there is a problem accessing FILE,
102 or if FILE does not exist but would have to refer to an existing
103 directory if it referred to anything at all. */
106 target_directory_operand (char const *file
)
108 char const *b
= last_component (file
);
109 size_t blen
= strlen (b
);
110 bool looks_like_a_dir
= (blen
== 0 || ISSLASH (b
[blen
- 1]));
113 (dereference_dest_dir_symlinks
? stat (file
, &st
) : lstat (file
, &st
));
114 int err
= (stat_result
== 0 ? 0 : errno
);
115 bool is_a_dir
= !err
&& S_ISDIR (st
.st_mode
);
116 if (err
&& err
!= ENOENT
)
117 error (EXIT_FAILURE
, err
, _("accessing %s"), quote (file
));
118 if (is_a_dir
< looks_like_a_dir
)
119 error (EXIT_FAILURE
, err
, _("target %s is not a directory"), quote (file
));
123 /* Make a link DEST to the (usually) existing file SOURCE.
124 Symbolic links to nonexistent files are allowed.
125 Return true if successful. */
128 do_link (const char *source
, const char *dest
)
130 struct stat source_stats
;
131 struct stat dest_stats
;
132 char *dest_backup
= NULL
;
133 bool dest_lstat_ok
= false;
134 bool source_is_dir
= false;
139 /* Which stat to use depends on whether linkat will follow the
140 symlink. We can't use the shorter
141 (logical?stat:lstat) (source, &source_stats)
142 since stat might be a function-like macro. */
143 if ((logical
? stat (source
, &source_stats
)
144 : lstat (source
, &source_stats
))
147 error (0, errno
, _("accessing %s"), quote (source
));
151 if (S_ISDIR (source_stats
.st_mode
))
153 source_is_dir
= true;
156 error (0, 0, _("%s: hard link not allowed for directory"),
163 if (remove_existing_files
|| interactive
|| backup_type
!= no_backups
)
165 dest_lstat_ok
= (lstat (dest
, &dest_stats
) == 0);
166 if (!dest_lstat_ok
&& errno
!= ENOENT
)
168 error (0, errno
, _("accessing %s"), quote (dest
));
173 /* If the current target was created as a hard link to another
174 source file, then refuse to unlink it. */
177 && seen_file (dest_set
, dest
, &dest_stats
))
180 _("will not overwrite just-created %s with %s"),
181 quote_n (0, dest
), quote_n (1, source
));
185 /* If --force (-f) has been specified without --backup, then before
186 making a link ln must remove the destination file if it exists.
187 (with --backup, it just renames any existing destination file)
188 But if the source and destination are the same, don't remove
189 anything and fail right here. */
190 if ((remove_existing_files
191 /* Ensure that "ln --backup f f" fails here, with the
192 "... same file" diagnostic, below. Otherwise, subsequent
193 code would give a misleading "file not found" diagnostic.
194 This case is different than the others handled here, since
195 the command in question doesn't use --force. */
196 || (!symbolic_link
&& backup_type
!= no_backups
))
198 /* Allow `ln -sf --backup k k' to succeed in creating the
199 self-referential symlink, but don't allow the hard-linking
200 equivalent: `ln -f k k' (with or without --backup) to get
201 beyond this point, because the error message you'd get is
203 && (backup_type
== no_backups
|| !symbolic_link
)
204 && (!symbolic_link
|| stat (source
, &source_stats
) == 0)
205 && SAME_INODE (source_stats
, dest_stats
)
206 /* The following detects whether removing DEST will also remove
207 SOURCE. If the file has only one link then both are surely
208 the same link. Otherwise check whether they point to the same
209 name in the same directory. */
210 && (source_stats
.st_nlink
== 1 || same_name (source
, dest
)))
212 error (0, 0, _("%s and %s are the same file"),
213 quote_n (0, source
), quote_n (1, dest
));
219 if (S_ISDIR (dest_stats
.st_mode
))
221 error (0, 0, _("%s: cannot overwrite directory"), quote (dest
));
226 fprintf (stderr
, _("%s: replace %s? "), program_name
, quote (dest
));
229 remove_existing_files
= true;
232 if (backup_type
!= no_backups
)
234 dest_backup
= find_backup_file_name (dest
, backup_type
);
235 if (rename (dest
, dest_backup
) != 0)
237 int rename_errno
= errno
;
240 if (rename_errno
!= ENOENT
)
242 error (0, rename_errno
, _("cannot backup %s"), quote (dest
));
249 ok
= ((symbolic_link
? symlink (source
, dest
)
250 : linkat (AT_FDCWD
, source
, AT_FDCWD
, dest
,
251 logical
? AT_SYMLINK_FOLLOW
: 0))
254 /* If the attempt to create a link failed and we are removing or
255 backing up destinations, unlink the destination and try again.
257 On the surface, POSIX describes an algorithm that states that
258 'ln -f A B' will call unlink() on B before ever attempting
259 link() on A. But strictly following this has the counterintuitive
260 effect of losing the contents of B, if A does not exist.
261 Fortunately, POSIX 2008 clarified that an application is free
262 to fail early if it can prove that continuing onwards cannot
263 succeed, so we are justified in trying link() before blindly
264 removing B, thus sometimes calling link() a second time during
265 a successful 'ln -f A B'.
267 Try to unlink DEST even if we may have backed it up successfully.
268 In some unusual cases (when DEST and DEST_BACKUP are hard-links
269 that refer to the same file), rename succeeds and DEST remains.
270 If we didn't remove DEST in that case, the subsequent symlink or link
273 if (!ok
&& errno
== EEXIST
&& (remove_existing_files
|| dest_backup
))
275 if (unlink (dest
) != 0)
277 error (0, errno
, _("cannot remove %s"), quote (dest
));
282 ok
= ((symbolic_link
? symlink (source
, dest
)
283 : linkat (AT_FDCWD
, source
, AT_FDCWD
, dest
,
284 logical
? AT_SYMLINK_FOLLOW
: 0))
290 /* Right after creating a hard link, do this: (note dest name and
291 source_stats, which are also the just-linked-destinations stats) */
292 record_file (dest_set
, dest
, &source_stats
);
297 printf ("%s ~ ", quote (dest_backup
));
298 printf ("%s %c> %s\n", quote_n (0, dest
), (symbolic_link
? '-' : '='),
299 quote_n (1, source
));
306 ? (errno
!= ENAMETOOLONG
&& *source
307 ? _("failed to create symbolic link %s")
308 : _("failed to create symbolic link %s -> %s"))
309 : (errno
== EMLINK
&& !source_is_dir
310 ? _("failed to create hard link to %.0s%s")
311 : (errno
== EDQUOT
|| errno
== EEXIST
|| errno
== ENOSPC
313 ? _("failed to create hard link %s")
314 : _("failed to create hard link %s => %s"))),
315 quote_n (0, dest
), quote_n (1, source
));
319 if (rename (dest_backup
, dest
) != 0)
320 error (0, errno
, _("cannot un-backup %s"), quote (dest
));
331 if (status
!= EXIT_SUCCESS
)
332 fprintf (stderr
, _("Try `%s --help' for more information.\n"),
337 Usage: %s [OPTION]... [-T] TARGET LINK_NAME (1st form)\n\
338 or: %s [OPTION]... TARGET (2nd form)\n\
339 or: %s [OPTION]... TARGET... DIRECTORY (3rd form)\n\
340 or: %s [OPTION]... -t DIRECTORY TARGET... (4th form)\n\
342 program_name
, program_name
, program_name
, program_name
);
344 In the 1st form, create a link to TARGET with the name LINK_NAME.\n\
345 In the 2nd form, create a link to TARGET in the current directory.\n\
346 In the 3rd and 4th forms, create links to each TARGET in DIRECTORY.\n\
347 Create hard links by default, symbolic links with --symbolic.\n\
348 By default, each destination (name of new link) should not already exist.\n\
349 When creating hard links, each TARGET must exist. Symbolic links\n\
350 can hold arbitrary text; if later resolved, a relative link is\n\
351 interpreted in relation to its parent directory.\n\
355 Mandatory arguments to long options are mandatory for short options too.\n\
358 --backup[=CONTROL] make a backup of each existing destination file\n\
359 -b like --backup but does not accept an argument\n\
360 -d, -F, --directory allow the superuser to attempt to hard link\n\
361 directories (note: will probably fail due to\n\
362 system restrictions, even for the superuser)\n\
363 -f, --force remove existing destination files\n\
366 -i, --interactive prompt whether to remove destinations\n\
367 -L, --logical dereference TARGETs that are symbolic links\n\
368 -n, --no-dereference treat LINK_NAME as a normal file if\n\
369 it is a symbolic link to a directory\n\
370 -P, --physical make hard links directly to symbolic links\n\
371 -s, --symbolic make symbolic links instead of hard links\n\
374 -S, --suffix=SUFFIX override the usual backup suffix\n\
375 -t, --target-directory=DIRECTORY specify the DIRECTORY in which to create\n\
377 -T, --no-target-directory treat LINK_NAME as a normal file always\n\
378 -v, --verbose print name of each linked file\n\
380 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
381 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
384 The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
385 The version control method may be selected via the --backup option or through\n\
386 the VERSION_CONTROL environment variable. Here are the values:\n\
390 none, off never make backups (even if --backup is given)\n\
391 numbered, t make numbered backups\n\
392 existing, nil numbered if numbered backups exist, simple otherwise\n\
393 simple, never always make simple backups\n\
397 Using -s ignores -L and -P. Otherwise, the last option specified controls\n\
398 behavior when a TARGET is a symbolic link, defaulting to %s.\n\
399 "), LINK_FOLLOWS_SYMLINKS
? "-L" : "-P");
400 emit_ancillary_info ();
406 main (int argc
, char **argv
)
410 bool make_backups
= false;
411 char *backup_suffix_string
;
412 char *version_control_string
= NULL
;
413 char const *target_directory
= NULL
;
414 bool no_target_directory
= false;
418 initialize_main (&argc
, &argv
);
419 set_program_name (argv
[0]);
420 setlocale (LC_ALL
, "");
421 bindtextdomain (PACKAGE
, LOCALEDIR
);
422 textdomain (PACKAGE
);
424 atexit (close_stdin
);
426 /* FIXME: consider not calling getenv for SIMPLE_BACKUP_SUFFIX unless
427 we'll actually use backup_suffix_string. */
428 backup_suffix_string
= getenv ("SIMPLE_BACKUP_SUFFIX");
430 symbolic_link
= remove_existing_files
= interactive
= verbose
431 = hard_dir_link
= false;
433 while ((c
= getopt_long (argc
, argv
, "bdfinst:vFLPS:T", long_options
, NULL
))
441 version_control_string
= optarg
;
445 hard_dir_link
= true;
448 remove_existing_files
= true;
452 remove_existing_files
= false;
459 dereference_dest_dir_symlinks
= false;
465 symbolic_link
= true;
468 if (target_directory
)
469 error (EXIT_FAILURE
, 0, _("multiple target directories specified"));
473 if (stat (optarg
, &st
) != 0)
474 error (EXIT_FAILURE
, errno
, _("accessing %s"), quote (optarg
));
475 if (! S_ISDIR (st
.st_mode
))
476 error (EXIT_FAILURE
, 0, _("target %s is not a directory"),
479 target_directory
= optarg
;
482 no_target_directory
= true;
489 backup_suffix_string
= optarg
;
491 case_GETOPT_HELP_CHAR
;
492 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
494 usage (EXIT_FAILURE
);
499 n_files
= argc
- optind
;
500 file
= argv
+ optind
;
504 error (0, 0, _("missing file operand"));
505 usage (EXIT_FAILURE
);
508 if (no_target_directory
)
510 if (target_directory
)
511 error (EXIT_FAILURE
, 0,
512 _("cannot combine --target-directory "
513 "and --no-target-directory"));
518 _("missing destination file operand after %s"),
521 error (0, 0, _("extra operand %s"), quote (file
[2]));
522 usage (EXIT_FAILURE
);
525 else if (!target_directory
)
528 target_directory
= ".";
529 else if (2 <= n_files
&& target_directory_operand (file
[n_files
- 1]))
530 target_directory
= file
[--n_files
];
531 else if (2 < n_files
)
532 error (EXIT_FAILURE
, 0, _("target %s is not a directory"),
533 quote (file
[n_files
- 1]));
536 if (backup_suffix_string
)
537 simple_backup_suffix
= xstrdup (backup_suffix_string
);
539 backup_type
= (make_backups
540 ? xget_version (_("backup type"), version_control_string
)
543 if (target_directory
)
547 /* Create the data structure we'll use to record which hard links we
548 create. Used to ensure that ln detects an obscure corner case that
549 might result in user data loss. Create it only if needed. */
551 && remove_existing_files
552 /* Don't bother trying to protect symlinks, since ln clobbering
553 a just-created symlink won't ever lead to real data loss. */
555 /* No destination hard link can be clobbered when making
557 && backup_type
!= numbered_backups
)
560 dest_set
= hash_initialize (DEST_INFO_INITIAL_CAPACITY
,
565 if (dest_set
== NULL
)
570 for (i
= 0; i
< n_files
; ++i
)
573 char *dest
= file_name_concat (target_directory
,
574 last_component (file
[i
]),
576 strip_trailing_slashes (dest_base
);
577 ok
&= do_link (file
[i
], dest
);
582 ok
= do_link (file
[0], file
[1]);
584 exit (ok
? EXIT_SUCCESS
: EXIT_FAILURE
);