1 /* `ln' program to create links between files.
2 Copyright (C) 86, 89, 90, 91, 1995-2005 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 2, or (at your option)
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, write to the Free Software Foundation,
16 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
18 /* Written by Mike Parker and David MacKenzie. */
22 #include <sys/types.h>
27 #include "backupfile.h"
30 #include "filenamecat.h"
34 /* The official name of this program (e.g., no `g' prefix). */
35 #define PROGRAM_NAME "ln"
37 #define AUTHORS "Mike Parker", "David MacKenzie"
39 #ifndef ENABLE_HARD_LINK_TO_SYMLINK_WARNING
40 # define ENABLE_HARD_LINK_TO_SYMLINK_WARNING 0
43 /* In being careful not even to try to make hard links to directories,
44 we have to know whether link(2) follows symlinks. If it does, then
45 we have to *stat* the `source' to see if the resulting link would be
46 to a directory. Otherwise, we have to use *lstat* so that we allow
47 users to make hard links to symlinks-that-point-to-directories. */
49 #if LINK_FOLLOWS_SYMLINKS
50 # define STAT_LIKE_LINK(File, Stat_buf) \
53 # define STAT_LIKE_LINK(File, Stat_buf) \
54 lstat (File, Stat_buf)
57 /* The name by which the program was run, for error messages. */
61 static enum backup_type backup_type;
63 /* A pointer to the function used to make links. This will point to either
64 `link' or `symlink'. */
65 static int (*linkfunc) ();
67 /* If true, make symbolic links; otherwise, make hard links. */
68 static bool symbolic_link;
70 /* If true, ask the user before removing existing files. */
71 static bool interactive;
73 /* If true, remove existing files unconditionally. */
74 static bool remove_existing_files;
76 /* If true, list each file as it is moved. */
79 /* If true, allow the superuser to *attempt* to make hard links
80 to directories. However, it appears that this option is not useful
81 in practice, since even the superuser is prohibited from hard-linking
82 directories on most (all?) existing systems. */
83 static bool hard_dir_link;
85 /* If nonzero, and the specified destination is a symbolic link to a
86 directory, treat it just as if it were a directory. Otherwise, the
87 command `ln --force --no-dereference file symlink-to-dir' deletes
88 symlink-to-dir before creating the new link. */
89 static bool dereference_dest_dir_symlinks = true;
91 static struct option const long_options[] =
93 {"backup", optional_argument, NULL, 'b'},
94 {"directory", no_argument, NULL, 'F'},
95 {"no-dereference", no_argument, NULL, 'n'},
96 {"no-target-directory", no_argument, NULL, 'T'},
97 {"force", no_argument, NULL, 'f'},
98 {"interactive", no_argument, NULL, 'i'},
99 {"suffix", required_argument, NULL, 'S'},
100 {"target-directory", required_argument, NULL, 't'},
101 {"symbolic", no_argument, NULL, 's'},
102 {"verbose", no_argument, NULL, 'v'},
103 {GETOPT_HELP_OPTION_DECL},
104 {GETOPT_VERSION_OPTION_DECL},
108 /* FILE is the last operand of this command. Return true if FILE is a
109 directory. But report an error there is a problem accessing FILE,
110 or if FILE does not exist but would have to refer to an existing
111 directory if it referred to anything at all. */
114 target_directory_operand (char const *file)
116 char const *b = base_name (file);
117 size_t blen = strlen (b);
118 bool looks_like_a_dir = (blen == 0 || ISSLASH (b[blen - 1]));
120 int err = ((dereference_dest_dir_symlinks ? stat : lstat) (file, &st) == 0
122 bool is_a_dir = !err && S_ISDIR (st.st_mode);
123 if (err && err != ENOENT)
124 error (EXIT_FAILURE, err, _("accessing %s"), quote (file));
125 if (is_a_dir < looks_like_a_dir)
126 error (EXIT_FAILURE, err, _("target %s is not a directory"), quote (file));
130 /* Make a link DEST to the (usually) existing file SOURCE.
131 Symbolic links to nonexistent files are allowed.
132 Return true if successful. */
135 do_link (const char *source, const char *dest)
137 struct stat source_stats;
138 struct stat dest_stats;
139 char *dest_backup = NULL;
140 bool lstat_ok = false;
142 /* Use stat here instead of lstat.
143 On SVR4, link does not follow symlinks, so this check disallows
144 making hard links to symlinks that point to directories. Big deal.
145 On other systems, link follows symlinks, so this check is right. */
148 if (STAT_LIKE_LINK (source, &source_stats) != 0)
150 error (0, errno, _("accessing %s"), quote (source));
154 if (ENABLE_HARD_LINK_TO_SYMLINK_WARNING
155 && S_ISLNK (source_stats.st_mode))
157 error (0, 0, _("%s: warning: making a hard link to a symbolic link\
162 if (!hard_dir_link && S_ISDIR (source_stats.st_mode))
164 error (0, 0, _("%s: hard link not allowed for directory"),
170 if (remove_existing_files || interactive || backup_type != no_backups)
172 lstat_ok = (lstat (dest, &dest_stats) == 0);
173 if (!lstat_ok && errno != ENOENT)
175 error (0, errno, _("accessing %s"), quote (dest));
180 /* If --force (-f) has been specified without --backup, then before
181 making a link ln must remove the destination file if it exists.
182 (with --backup, it just renames any existing destination file)
183 But if the source and destination are the same, don't remove
184 anything and fail right here. */
185 if (remove_existing_files
187 /* Allow `ln -sf --backup k k' to succeed in creating the
188 self-referential symlink, but don't allow the hard-linking
189 equivalent: `ln -f k k' (with or without --backup) to get
190 beyond this point, because the error message you'd get is
192 && (backup_type == no_backups || !symbolic_link)
193 && (!symbolic_link || stat (source, &source_stats) == 0)
194 && SAME_INODE (source_stats, dest_stats)
195 /* The following detects whether removing DEST will also remove
196 SOURCE. If the file has only one link then both are surely
197 the same link. Otherwise check whether they point to the same
198 name in the same directory. */
199 && (source_stats.st_nlink == 1 || same_name (source, dest)))
201 error (0, 0, _("%s and %s are the same file"),
202 quote_n (0, source), quote_n (1, dest));
208 if (S_ISDIR (dest_stats.st_mode))
210 error (0, 0, _("%s: cannot overwrite directory"), quote (dest));
215 fprintf (stderr, _("%s: replace %s? "), program_name, quote (dest));
218 remove_existing_files = true;
221 if (backup_type != no_backups)
223 char *tmp_backup = find_backup_file_name (dest, backup_type);
224 size_t buf_len = strlen (tmp_backup) + 1;
225 dest_backup = alloca (buf_len);
226 memcpy (dest_backup, tmp_backup, buf_len);
228 if (rename (dest, dest_backup))
232 error (0, errno, _("cannot backup %s"), quote (dest));
243 printf ((symbolic_link
244 ? _("create symbolic link %s to %s")
245 : _("create hard link %s to %s")),
246 quote_n (0, dest), quote_n (1, source));
248 printf (_(" (backup: %s)"), quote (dest_backup));
252 if ((*linkfunc) (source, dest) == 0)
255 /* If the attempt to create a link failed and we are removing or
256 backing up destinations, unlink the destination and try again.
258 POSIX 1003.1-2004 requires that ln -f A B must unlink B even on
259 failure (e.g., when A does not exist). This is counterintuitive,
260 and we submitted a defect report
261 <http://www.opengroup.org/sophocles/show_mail.tpl?source=L&listname=austin-review-l&id=1795>
262 (2004-06-24). If the committee does not fix the standard we'll
263 have to change the behavior of ln -f, at least if POSIXLY_CORRECT
264 is set. In the meantime ln -f A B will not unlink B unless the
265 attempt to link A to B failed because B already existed.
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 LINKFUNC
273 if (errno == EEXIST && (remove_existing_files || dest_backup))
275 if (unlink (dest) != 0)
277 error (0, errno, _("cannot remove %s"), quote (dest));
281 if (linkfunc (source, dest) == 0)
287 ? _("creating symbolic link %s to %s")
288 : _("creating hard link %s to %s")),
289 quote_n (0, dest), quote_n (1, source));
293 if (rename (dest_backup, dest))
294 error (0, errno, _("cannot un-backup %s"), quote (dest));
302 if (status != EXIT_SUCCESS)
303 fprintf (stderr, _("Try `%s --help' for more information.\n"),
308 Usage: %s [OPTION]... [-T] TARGET LINK_NAME (1st form)\n\
309 or: %s [OPTION]... TARGET (2nd form)\n\
310 or: %s [OPTION]... TARGET... DIRECTORY (3rd form)\n\
311 or: %s [OPTION]... -t DIRECTORY TARGET... (4th form)\n\
313 program_name, program_name, program_name, program_name);
315 In the 1st form, create a link to TARGET with the name LINK_NAME.\n\
316 In the 2nd form, create a link to TARGET in the current directory.\n\
317 In the 3rd and 4th forms, create links to each TARGET in DIRECTORY.\n\
318 Create hard links by default, symbolic links with --symbolic.\n\
319 When creating hard links, each TARGET must exist.\n\
323 Mandatory arguments to long options are mandatory for short options too.\n\
326 --backup[=CONTROL] make a backup of each existing destination file\n\
327 -b like --backup but does not accept an argument\n\
328 -d, -F, --directory allow the superuser to attempt to hard link\n\
329 directories (note: will probably fail due to\n\
330 system restrictions, even for the superuser)\n\
331 -f, --force remove existing destination files\n\
334 -n, --no-dereference treat destination that is a symlink to a\n\
335 directory as if it were a normal file\n\
336 -i, --interactive prompt whether to remove destinations\n\
337 -s, --symbolic make symbolic links instead of hard links\n\
340 -S, --suffix=SUFFIX override the usual backup suffix\n\
341 -t, --target-directory=DIRECTORY specify the DIRECTORY in which to create\n\
343 -T, --no-target-directory treat LINK_NAME as a normal file\n\
344 -v, --verbose print name of each file before linking\n\
346 fputs (HELP_OPTION_DESCRIPTION, stdout);
347 fputs (VERSION_OPTION_DESCRIPTION, stdout);
350 The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
351 The version control method may be selected via the --backup option or through\n\
352 the VERSION_CONTROL environment variable. Here are the values:\n\
356 none, off never make backups (even if --backup is given)\n\
357 numbered, t make numbered backups\n\
358 existing, nil numbered if numbered backups exist, simple otherwise\n\
359 simple, never always make simple backups\n\
361 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
367 main (int argc, char **argv)
371 bool make_backups = false;
372 char *backup_suffix_string;
373 char *version_control_string = NULL;
374 char const *target_directory = NULL;
375 bool no_target_directory = false;
379 initialize_main (&argc, &argv);
380 program_name = argv[0];
381 setlocale (LC_ALL, "");
382 bindtextdomain (PACKAGE, LOCALEDIR);
383 textdomain (PACKAGE);
385 atexit (close_stdout);
387 /* FIXME: consider not calling getenv for SIMPLE_BACKUP_SUFFIX unless
388 we'll actually use backup_suffix_string. */
389 backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
391 symbolic_link = remove_existing_files = interactive = verbose
392 = hard_dir_link = false;
394 while ((c = getopt_long (argc, argv, "bdfinst:vFS:T", long_options, NULL))
402 version_control_string = optarg;
406 hard_dir_link = true;
409 remove_existing_files = true;
413 remove_existing_files = false;
417 dereference_dest_dir_symlinks = false;
421 symbolic_link = true;
423 error (EXIT_FAILURE, 0,
424 _("symbolic links are not supported on this system"));
428 if (target_directory)
429 error (EXIT_FAILURE, 0, _("multiple target directories specified"));
433 if (stat (optarg, &st) != 0)
434 error (EXIT_FAILURE, errno, _("accessing %s"), quote (optarg));
435 if (! S_ISDIR (st.st_mode))
436 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
439 target_directory = optarg;
442 no_target_directory = true;
449 backup_suffix_string = optarg;
451 case_GETOPT_HELP_CHAR;
452 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
454 usage (EXIT_FAILURE);
459 n_files = argc - optind;
460 file = argv + optind;
464 error (0, 0, _("missing file operand"));
465 usage (EXIT_FAILURE);
468 if (no_target_directory)
470 if (target_directory)
471 error (EXIT_FAILURE, 0,
472 _("Cannot combine --target-directory "
473 "and --no-target-directory"));
478 _("missing destination file operand after %s"),
481 error (0, 0, _("extra operand %s"), quote (file[2]));
482 usage (EXIT_FAILURE);
485 else if (!target_directory)
488 target_directory = ".";
489 else if (2 <= n_files && target_directory_operand (file[n_files - 1]))
490 target_directory = file[--n_files];
491 else if (2 < n_files)
492 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
493 quote (file[n_files - 1]));
501 if (backup_suffix_string)
502 simple_backup_suffix = xstrdup (backup_suffix_string);
504 backup_type = (make_backups
505 ? xget_version (_("backup type"), version_control_string)
508 if (target_directory)
512 for (i = 0; i < n_files; ++i)
515 char *dest = file_name_concat (target_directory, base_name (file[i]),
517 strip_trailing_slashes (dest_base);
518 ok &= do_link (file[i], dest);
523 ok = do_link (file[0], file[1]);
525 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);