1 /* `ln' program to create links between files.
2 Copyright (C) 86, 89, 90, 91, 1995-2004 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18 /* Written by Mike Parker and David MacKenzie. */
22 #include <sys/types.h>
27 #include "backupfile.h"
33 /* The official name of this program (e.g., no `g' prefix). */
34 #define PROGRAM_NAME "ln"
36 #define AUTHORS "Mike Parker", "David MacKenzie"
38 #ifndef ENABLE_HARD_LINK_TO_SYMLINK_WARNING
39 # define ENABLE_HARD_LINK_TO_SYMLINK_WARNING 0
42 int link (); /* Some systems don't declare this anywhere. */
48 /* In being careful not even to try to make hard links to directories,
49 we have to know whether link(2) follows symlinks. If it does, then
50 we have to *stat* the `source' to see if the resulting link would be
51 to a directory. Otherwise, we have to use *lstat* so that we allow
52 users to make hard links to symlinks-that-point-to-directories. */
54 #if LINK_FOLLOWS_SYMLINKS
55 # define STAT_LIKE_LINK(File, Stat_buf) \
58 # define STAT_LIKE_LINK(File, Stat_buf) \
59 lstat (File, Stat_buf)
62 /* Construct a string NEW_DEST by concatenating DEST, a slash, and
63 basename(SOURCE) in alloca'd memory. Don't modify DEST or SOURCE. */
65 #define PATH_BASENAME_CONCAT(new_dest, dest, source) \
68 const char *source_base; \
70 size_t buf_len = strlen (source) + 1; \
72 tmp_source = alloca (buf_len); \
73 memcpy (tmp_source, (source), buf_len); \
74 strip_trailing_slashes (tmp_source); \
75 source_base = base_name (tmp_source); \
77 (new_dest) = alloca (strlen ((dest)) + 1 \
78 + strlen (source_base) + 1); \
79 stpcpy (stpcpy (stpcpy ((new_dest), (dest)), "/"), source_base);\
83 /* The name by which the program was run, for error messages. */
87 static enum backup_type backup_type;
89 /* A pointer to the function used to make links. This will point to either
90 `link' or `symlink'. */
91 static int (*linkfunc) ();
93 /* If true, make symbolic links; otherwise, make hard links. */
94 static bool symbolic_link;
96 /* If true, ask the user before removing existing files. */
97 static bool interactive;
99 /* If true, remove existing files unconditionally. */
100 static bool remove_existing_files;
102 /* If true, list each file as it is moved. */
105 /* If true, allow the superuser to *attempt* to make hard links
106 to directories. However, it appears that this option is not useful
107 in practice, since even the superuser is prohibited from hard-linking
108 directories on most (all?) existing systems. */
109 static bool hard_dir_link;
111 /* If nonzero, and the specified destination is a symbolic link to a
112 directory, treat it just as if it were a directory. Otherwise, the
113 command `ln --force --no-dereference file symlink-to-dir' deletes
114 symlink-to-dir before creating the new link. */
115 static bool dereference_dest_dir_symlinks = true;
117 static struct option const long_options[] =
119 {"backup", optional_argument, NULL, 'b'},
120 {"directory", no_argument, NULL, 'F'},
121 {"no-dereference", no_argument, NULL, 'n'},
122 {"no-target-directory", no_argument, NULL, 'T'},
123 {"force", no_argument, NULL, 'f'},
124 {"interactive", no_argument, NULL, 'i'},
125 {"suffix", required_argument, NULL, 'S'},
126 {"target-directory", required_argument, NULL, 't'},
127 {"symbolic", no_argument, NULL, 's'},
128 {"verbose", no_argument, NULL, 'v'},
129 {"version-control", required_argument, NULL, 'V'}, /* Deprecated. FIXME. */
130 {GETOPT_HELP_OPTION_DECL},
131 {GETOPT_VERSION_OPTION_DECL},
135 /* FILE is the last operand of this command. Return true if FILE is a
136 directory. But report an error there is a problem accessing FILE,
137 or if FILE does not exist but would have to refer to an existing
138 directory if it referred to anything at all. */
141 target_directory_operand (char const *file)
143 char const *b = base_name (file);
144 size_t blen = strlen (b);
145 bool looks_like_a_dir = (blen == 0 || ISSLASH (b[blen - 1]));
147 int err = ((dereference_dest_dir_symlinks ? stat : lstat) (file, &st) == 0
149 bool is_a_dir = !err && S_ISDIR (st.st_mode);
150 if (err && err != ENOENT)
151 error (EXIT_FAILURE, err, _("accessing %s"), quote (file));
152 if (is_a_dir < looks_like_a_dir)
153 error (EXIT_FAILURE, err, _("target %s is not a directory"), quote (file));
157 /* Make a link DEST to the (usually) existing file SOURCE.
158 Symbolic links to nonexistent files are allowed.
159 If DEST_IS_DIR, put the link to SOURCE in the DEST directory.
160 Return true if successful. */
163 do_link (const char *source, const char *dest, bool dest_is_dir)
165 struct stat source_stats;
166 struct stat dest_stats;
167 char *dest_backup = NULL;
168 bool lstat_ok = false;
170 /* Use stat here instead of lstat.
171 On SVR4, link does not follow symlinks, so this check disallows
172 making hard links to symlinks that point to directories. Big deal.
173 On other systems, link follows symlinks, so this check is right. */
176 if (STAT_LIKE_LINK (source, &source_stats) != 0)
178 error (0, errno, _("accessing %s"), quote (source));
182 if (ENABLE_HARD_LINK_TO_SYMLINK_WARNING
183 && S_ISLNK (source_stats.st_mode))
185 error (0, 0, _("%s: warning: making a hard link to a symbolic link\
190 if (!hard_dir_link && S_ISDIR (source_stats.st_mode))
192 error (0, 0, _("%s: hard link not allowed for directory"),
200 /* Treat DEST as a directory; build the full filename. */
202 PATH_BASENAME_CONCAT (new_dest, dest, source);
206 if (remove_existing_files || interactive || backup_type != no_backups)
208 lstat_ok = (lstat (dest, &dest_stats) == 0);
209 if (!lstat_ok && errno != ENOENT)
211 error (0, errno, _("accessing %s"), quote (dest));
216 /* If --force (-f) has been specified without --backup, then before
217 making a link ln must remove the destination file if it exists.
218 (with --backup, it just renames any existing destination file)
219 But if the source and destination are the same, don't remove
220 anything and fail right here. */
221 if (remove_existing_files
223 /* Allow `ln -sf --backup k k' to succeed in creating the
224 self-referential symlink, but don't allow the hard-linking
225 equivalent: `ln -f k k' (with or without --backup) to get
226 beyond this point, because the error message you'd get is
228 && (backup_type == no_backups || !symbolic_link)
229 && (!symbolic_link || stat (source, &source_stats) == 0)
230 && SAME_INODE (source_stats, dest_stats)
231 /* The following detects whether removing DEST will also remove
232 SOURCE. If the file has only one link then both are surely
233 the same link. Otherwise check whether they point to the same
234 name in the same directory. */
235 && (source_stats.st_nlink == 1 || same_name (source, dest)))
237 error (0, 0, _("%s and %s are the same file"),
238 quote_n (0, source), quote_n (1, dest));
244 if (S_ISDIR (dest_stats.st_mode))
246 error (0, 0, _("%s: cannot overwrite directory"), quote (dest));
251 fprintf (stderr, _("%s: replace %s? "), program_name, quote (dest));
256 if (backup_type != no_backups)
258 char *tmp_backup = find_backup_file_name (dest, backup_type);
259 size_t buf_len = strlen (tmp_backup) + 1;
260 dest_backup = alloca (buf_len);
261 memcpy (dest_backup, tmp_backup, buf_len);
263 if (rename (dest, dest_backup))
267 error (0, errno, _("cannot backup %s"), quote (dest));
278 printf ((symbolic_link
279 ? _("create symbolic link %s to %s")
280 : _("create hard link %s to %s")),
281 quote_n (0, dest), quote_n (1, source));
283 printf (_(" (backup: %s)"), quote (dest_backup));
287 if ((*linkfunc) (source, dest) == 0)
290 /* If the attempt to create a link failed and we are removing or
291 backing up destinations, unlink the destination and try again.
293 POSIX 1003.1-2004 requires that ln -f A B must unlink B even on
294 failure (e.g., when A does not exist). This is counterintuitive,
295 and we submitted a defect report
296 <http://www.opengroup.org/sophocles/show_mail.tpl?source=L&listname=austin-review-l&id=1795>
297 (2004-06-24). If the committee does not fix the standard we'll
298 have to change the behavior of ln -f, at least if POSIXLY_CORRECT
299 is set. In the meantime ln -f A B will not unlink B unless the
300 attempt to link A to B failed because B already existed.
302 Try to unlink DEST even if we may have backed it up successfully.
303 In some unusual cases (when DEST and DEST_BACKUP are hard-links
304 that refer to the same file), rename succeeds and DEST remains.
305 If we didn't remove DEST in that case, the subsequent LINKFUNC
308 if (errno == EEXIST && (remove_existing_files || dest_backup))
310 if (unlink (dest) != 0)
312 error (0, errno, _("cannot remove %s"), quote (dest));
316 if (linkfunc (source, dest) == 0)
322 ? _("creating symbolic link %s to %s")
323 : _("creating hard link %s to %s")),
324 quote_n (0, dest), quote_n (1, source));
328 if (rename (dest_backup, dest))
329 error (0, errno, _("cannot un-backup %s"), quote (dest));
337 if (status != EXIT_SUCCESS)
338 fprintf (stderr, _("Try `%s --help' for more information.\n"),
343 Usage: %s [OPTION]... [-T] TARGET LINK_NAME (1st form)\n\
344 or: %s [OPTION]... TARGET (2nd form)\n\
345 or: %s [OPTION]... TARGET... DIRECTORY (3rd form)\n\
346 or: %s [OPTION]... -t DIRECTORY TARGET... (4th form)\n\
348 program_name, program_name, program_name, program_name);
350 In the 1st form, create a link to TARGET with the name LINK_NAME.\n\
351 In the 2nd form, create a link to TARGET in the current directory.\n\
352 In the 3rd and 4th forms, create links to each TARGET in DIRECTORY.\n\
353 Create hard links by default, symbolic links with --symbolic.\n\
354 When creating hard links, each TARGET must exist.\n\
358 Mandatory arguments to long options are mandatory for short options too.\n\
361 --backup[=CONTROL] make a backup of each existing destination file\n\
362 -b like --backup but does not accept an argument\n\
363 -d, -F, --directory allow the superuser to attempt to hard link\n\
364 directories (note: will probably fail due to\n\
365 system restrictions, even for the superuser)\n\
366 -f, --force remove existing destination files\n\
369 -n, --no-dereference treat destination that is a symlink to a\n\
370 directory as if it were a normal file\n\
371 -i, --interactive prompt whether to remove destinations\n\
372 -s, --symbolic make symbolic links instead of hard links\n\
375 -S, --suffix=SUFFIX override the usual backup suffix\n\
376 -t, --target-directory=DIRECTORY specify the DIRECTORY in which to create\n\
378 -T, --no-target-directory treat LINK_NAME as a normal file\n\
379 -v, --verbose print name of each file before linking\n\
381 fputs (HELP_OPTION_DESCRIPTION, stdout);
382 fputs (VERSION_OPTION_DESCRIPTION, stdout);
385 The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
386 The version control method may be selected via the --backup option or through\n\
387 the VERSION_CONTROL environment variable. Here are the values:\n\
391 none, off never make backups (even if --backup is given)\n\
392 numbered, t make numbered backups\n\
393 existing, nil numbered if numbered backups exist, simple otherwise\n\
394 simple, never always make simple backups\n\
396 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
402 main (int argc, char **argv)
406 bool make_backups = false;
407 char *backup_suffix_string;
408 char *version_control_string = NULL;
409 char *target_directory = NULL;
410 bool no_target_directory = false;
414 initialize_main (&argc, &argv);
415 program_name = argv[0];
416 setlocale (LC_ALL, "");
417 bindtextdomain (PACKAGE, LOCALEDIR);
418 textdomain (PACKAGE);
420 atexit (close_stdout);
422 /* FIXME: consider not calling getenv for SIMPLE_BACKUP_SUFFIX unless
423 we'll actually use backup_suffix_string. */
424 backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
426 symbolic_link = remove_existing_files = interactive = verbose
427 = hard_dir_link = false;
429 while ((c = getopt_long (argc, argv, "bdfinst:vFS:TV:", long_options, NULL))
434 case 0: /* Long-named option. */
437 case 'V': /* FIXME: this is deprecated. Remove it in 2001. */
439 _("warning: --version-control (-V) is obsolete; support for\
440 it\nwill be removed in some future release. Use --backup=%s instead."
447 version_control_string = optarg;
451 hard_dir_link = true;
454 remove_existing_files = true;
458 remove_existing_files = false;
462 dereference_dest_dir_symlinks = false;
466 symbolic_link = true;
468 error (EXIT_FAILURE, 0,
469 _("symbolic links are not supported on this system"));
473 if (target_directory)
474 error (EXIT_FAILURE, 0, _("multiple target directories specified"));
478 if (stat (optarg, &st) != 0)
479 error (EXIT_FAILURE, errno, _("accessing %s"), quote (optarg));
480 if (! S_ISDIR (st.st_mode))
481 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
484 target_directory = optarg;
487 no_target_directory = true;
494 backup_suffix_string = optarg;
496 case_GETOPT_HELP_CHAR;
497 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
499 usage (EXIT_FAILURE);
504 n_files = argc - optind;
505 file = argv + optind;
509 error (0, 0, _("missing file operand"));
510 usage (EXIT_FAILURE);
513 if (no_target_directory)
515 if (target_directory)
516 error (EXIT_FAILURE, 0,
517 _("Cannot combine --target-directory "
518 "and --no-target-directory"));
523 _("missing destination file operand after %s"),
526 error (0, 0, _("extra operand %s"), quote (file[2]));
527 usage (EXIT_FAILURE);
530 else if (!target_directory)
533 target_directory = ".";
534 else if (2 <= n_files && target_directory_operand (file[n_files - 1]))
535 target_directory = file[--n_files];
536 else if (2 < n_files)
537 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
538 quote (file[n_files - 1]));
546 if (backup_suffix_string)
547 simple_backup_suffix = xstrdup (backup_suffix_string);
549 backup_type = (make_backups
550 ? xget_version (_("backup type"), version_control_string)
553 if (target_directory)
557 for (i = 0; i < n_files; ++i)
558 ok &= do_link (file[i], target_directory, true);
561 ok = do_link (file[0], file[1], false);
563 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);