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 nonzero, make symbolic links; otherwise, make hard links. */
94 static int symbolic_link;
96 /* If nonzero, ask the user before removing existing files. */
97 static int interactive;
99 /* If nonzero, remove existing files unconditionally. */
100 static int remove_existing_files;
102 /* If nonzero, list each file as it is moved. */
105 /* If nonzero, 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 int 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 int dereference_dest_dir_symlinks = 1;
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 1 if there is an error, otherwise 0. */
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 int lstat_status = -1;
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 != none)
208 lstat_status = lstat (dest, &dest_stats);
209 if (lstat_status != 0 && 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 == none || !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));
242 if (lstat_status == 0)
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 != none)
259 char *tmp_backup = find_backup_file_name (dest, backup_type);
260 if (tmp_backup == NULL)
262 buf_len = strlen (tmp_backup) + 1;
263 dest_backup = alloca (buf_len);
264 memcpy (dest_backup, tmp_backup, buf_len);
266 if (rename (dest, dest_backup))
270 error (0, errno, _("cannot backup %s"), quote (dest));
281 printf ((symbolic_link
282 ? _("create symbolic link %s to %s")
283 : _("create hard link %s to %s")),
284 quote_n (0, dest), quote_n (1, source));
286 printf (_(" (backup: %s)"), quote (dest_backup));
290 if ((*linkfunc) (source, dest) == 0)
295 /* If the attempt to create a link failed and we are removing or
296 backing up destinations, unlink the destination and try again.
298 POSIX 1003.1-2004 requires that ln -f A B must unlink B even on
299 failure (e.g., when A does not exist). This is counterintuitive,
300 and we submitted a defect report
301 <http://www.opengroup.org/sophocles/show_mail.tpl?source=L&listname=austin-review-l&id=1795>
302 (2004-06-24). If the committee does not fix the standard we'll
303 have to change the behavior of ln -f, at least if POSIXLY_CORRECT
304 is set. In the meantime ln -f A B will not unlink B unless the
305 attempt to link A to B failed because B already existed.
307 Try to unlink DEST even if we may have backed it up successfully.
308 In some unusual cases (when DEST and DEST_BACKUP are hard-links
309 that refer to the same file), rename succeeds and DEST remains.
310 If we didn't remove DEST in that case, the subsequent LINKFUNC
313 if (errno == EEXIST && (remove_existing_files || dest_backup))
315 if (unlink (dest) != 0)
317 error (0, errno, _("cannot remove %s"), quote (dest));
321 if (linkfunc (source, dest) == 0)
327 ? _("creating symbolic link %s to %s")
328 : _("creating hard link %s to %s")),
329 quote_n (0, dest), quote_n (1, source));
333 if (rename (dest_backup, dest))
334 error (0, errno, _("cannot un-backup %s"), quote (dest));
342 if (status != EXIT_SUCCESS)
343 fprintf (stderr, _("Try `%s --help' for more information.\n"),
348 Usage: %s [OPTION]... [-T] TARGET LINK_NAME (1st form)\n\
349 or: %s [OPTION]... TARGET (2nd form)\n\
350 or: %s [OPTION]... TARGET... DIRECTORY (3rd form)\n\
351 or: %s [OPTION]... -t DIRECTORY TARGET... (4th form)\n\
353 program_name, program_name, program_name, program_name);
355 In the 1st form, create a link to TARGET with the name LINK_NAME.\n\
356 In the 2nd form, create a link to TARGET in the current directory.\n\
357 In the 3rd and 4th forms, create links to each TARGET in DIRECTORY.\n\
358 Create hard links by default, symbolic links with --symbolic.\n\
359 When creating hard links, each TARGET must exist.\n\
363 Mandatory arguments to long options are mandatory for short options too.\n\
366 --backup[=CONTROL] make a backup of each existing destination file\n\
367 -b like --backup but does not accept an argument\n\
368 -d, -F, --directory allow the superuser to attempt to hard link\n\
369 directories (note: will probably fail due to\n\
370 system restrictions, even for the superuser)\n\
371 -f, --force remove existing destination files\n\
374 -n, --no-dereference treat destination that is a symlink to a\n\
375 directory as if it were a normal file\n\
376 -i, --interactive prompt whether to remove destinations\n\
377 -s, --symbolic make symbolic links instead of hard links\n\
380 -S, --suffix=SUFFIX override the usual backup suffix\n\
381 -t, --target-directory=DIRECTORY specify the DIRECTORY in which to create\n\
383 -T, --no-target-directory treat LINK_NAME as a normal file\n\
384 -v, --verbose print name of each file before linking\n\
386 fputs (HELP_OPTION_DESCRIPTION, stdout);
387 fputs (VERSION_OPTION_DESCRIPTION, stdout);
390 The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
391 The version control method may be selected via the --backup option or through\n\
392 the VERSION_CONTROL environment variable. Here are the values:\n\
396 none, off never make backups (even if --backup is given)\n\
397 numbered, t make numbered backups\n\
398 existing, nil numbered if numbered backups exist, simple otherwise\n\
399 simple, never always make simple backups\n\
401 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
407 main (int argc, char **argv)
411 int make_backups = 0;
412 char *backup_suffix_string;
413 char *version_control_string = NULL;
414 char *target_directory = NULL;
415 bool no_target_directory = false;
419 initialize_main (&argc, &argv);
420 program_name = argv[0];
421 setlocale (LC_ALL, "");
422 bindtextdomain (PACKAGE, LOCALEDIR);
423 textdomain (PACKAGE);
425 atexit (close_stdout);
427 /* FIXME: consider not calling getenv for SIMPLE_BACKUP_SUFFIX unless
428 we'll actually use backup_suffix_string. */
429 backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
431 symbolic_link = remove_existing_files = interactive = verbose
435 while ((c = getopt_long (argc, argv, "bdfinst:vFS:TV:", long_options, NULL))
440 case 0: /* Long-named option. */
443 case 'V': /* FIXME: this is deprecated. Remove it in 2001. */
445 _("warning: --version-control (-V) is obsolete; support for\
446 it\nwill be removed in some future release. Use --backup=%s instead."
453 version_control_string = optarg;
460 remove_existing_files = 1;
464 remove_existing_files = 0;
468 dereference_dest_dir_symlinks = 0;
474 error (EXIT_FAILURE, 0,
475 _("symbolic links are not supported on this system"));
479 if (target_directory)
480 error (EXIT_FAILURE, 0, _("multiple target directories specified"));
484 if (stat (optarg, &st) != 0)
485 error (EXIT_FAILURE, errno, _("accessing %s"), quote (optarg));
486 if (! S_ISDIR (st.st_mode))
487 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
490 target_directory = optarg;
493 no_target_directory = true;
500 backup_suffix_string = optarg;
502 case_GETOPT_HELP_CHAR;
503 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
505 usage (EXIT_FAILURE);
510 n_files = argc - optind;
511 file = argv + optind;
515 error (0, 0, _("missing file operand"));
516 usage (EXIT_FAILURE);
519 if (no_target_directory)
521 if (target_directory)
522 error (EXIT_FAILURE, 0,
523 _("Cannot combine --target-directory "
524 "and --no-target-directory"));
529 _("missing destination file operand after %s"),
532 error (0, 0, _("extra operand %s"), quote (file[2]));
533 usage (EXIT_FAILURE);
536 else if (!target_directory)
539 target_directory = ".";
540 else if (2 <= n_files && target_directory_operand (file[n_files - 1]))
541 target_directory = file[--n_files];
542 else if (2 < n_files)
543 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
544 quote (file[n_files - 1]));
552 if (backup_suffix_string)
553 simple_backup_suffix = xstrdup (backup_suffix_string);
555 backup_type = (make_backups
556 ? xget_version (_("backup type"), version_control_string)
559 if (target_directory)
562 for (i = 0; i < n_files; ++i)
563 errors |= do_link (file[i], target_directory, true);
566 errors = do_link (file[0], file[1], false);
568 exit (errors == 0 ? EXIT_SUCCESS : EXIT_FAILURE);