1 /* `ln' program to create links between files.
2 Copyright (C) 1986, 1989-1991, 1995-2006 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"
29 #include "filenamecat.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 /* In being careful not even to try to make hard links to directories,
43 we have to know whether link(2) follows symlinks. If it does, then
44 we have to *stat* the `source' to see if the resulting link would be
45 to a directory. Otherwise, we have to use *lstat* so that we allow
46 users to make hard links to symlinks-that-point-to-directories. */
48 #if LINK_FOLLOWS_SYMLINKS
49 # define STAT_LIKE_LINK(File, Stat_buf) \
52 # define STAT_LIKE_LINK(File, Stat_buf) \
53 lstat (File, Stat_buf)
56 /* The name by which the program was run, for error messages. */
60 static enum backup_type backup_type;
62 /* If true, make symbolic links; otherwise, make hard links. */
63 static bool symbolic_link;
65 /* If true, ask the user before removing existing files. */
66 static bool interactive;
68 /* If true, remove existing files unconditionally. */
69 static bool remove_existing_files;
71 /* If true, list each file as it is moved. */
74 /* If true, allow the superuser to *attempt* to make hard links
75 to directories. However, it appears that this option is not useful
76 in practice, since even the superuser is prohibited from hard-linking
77 directories on most (all?) existing systems. */
78 static bool hard_dir_link;
80 /* If nonzero, and the specified destination is a symbolic link to a
81 directory, treat it just as if it were a directory. Otherwise, the
82 command `ln --force --no-dereference file symlink-to-dir' deletes
83 symlink-to-dir before creating the new link. */
84 static bool dereference_dest_dir_symlinks = true;
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 {"symbolic", no_argument, NULL, 's'},
97 {"verbose", no_argument, NULL, 'v'},
98 {GETOPT_HELP_OPTION_DECL},
99 {GETOPT_VERSION_OPTION_DECL},
103 /* FILE is the last operand of this command. Return true if FILE is a
104 directory. But report an error there is a problem accessing FILE,
105 or if FILE does not exist but would have to refer to an existing
106 directory if it referred to anything at all. */
109 target_directory_operand (char const *file)
111 char const *b = last_component (file);
112 size_t blen = strlen (b);
113 bool looks_like_a_dir = (blen == 0 || ISSLASH (b[blen - 1]));
115 int err = ((dereference_dest_dir_symlinks ? stat : lstat) (file, &st) == 0
117 bool is_a_dir = !err && S_ISDIR (st.st_mode);
118 if (err && err != ENOENT)
119 error (EXIT_FAILURE, err, _("accessing %s"), quote (file));
120 if (is_a_dir < looks_like_a_dir)
121 error (EXIT_FAILURE, err, _("target %s is not a directory"), quote (file));
125 /* Make a link DEST to the (usually) existing file SOURCE.
126 Symbolic links to nonexistent files are allowed.
127 Return true if successful. */
130 do_link (const char *source, const char *dest)
132 struct stat source_stats;
133 struct stat dest_stats;
134 char *dest_backup = NULL;
135 bool lstat_ok = false;
136 bool source_is_dir = false;
139 /* Use stat here instead of lstat.
140 On SVR4, link does not follow symlinks, so this check disallows
141 making hard links to symlinks that point to directories. Big deal.
142 On other systems, link follows symlinks, so this check is right. */
145 if (STAT_LIKE_LINK (source, &source_stats) != 0)
147 error (0, errno, _("accessing %s"), quote (source));
151 if (ENABLE_HARD_LINK_TO_SYMLINK_WARNING
152 && S_ISLNK (source_stats.st_mode))
154 error (0, 0, _("%s: warning: making a hard link to a symbolic link\
159 if (S_ISDIR (source_stats.st_mode))
161 source_is_dir = true;
164 error (0, 0, _("%s: hard link not allowed for directory"),
171 if (remove_existing_files || interactive || backup_type != no_backups)
173 lstat_ok = (lstat (dest, &dest_stats) == 0);
174 if (!lstat_ok && errno != ENOENT)
176 error (0, errno, _("accessing %s"), quote (dest));
181 /* If --force (-f) has been specified without --backup, then before
182 making a link ln must remove the destination file if it exists.
183 (with --backup, it just renames any existing destination file)
184 But if the source and destination are the same, don't remove
185 anything and fail right here. */
186 if (remove_existing_files
188 /* Allow `ln -sf --backup k k' to succeed in creating the
189 self-referential symlink, but don't allow the hard-linking
190 equivalent: `ln -f k k' (with or without --backup) to get
191 beyond this point, because the error message you'd get is
193 && (backup_type == no_backups || !symbolic_link)
194 && (!symbolic_link || stat (source, &source_stats) == 0)
195 && SAME_INODE (source_stats, dest_stats)
196 /* The following detects whether removing DEST will also remove
197 SOURCE. If the file has only one link then both are surely
198 the same link. Otherwise check whether they point to the same
199 name in the same directory. */
200 && (source_stats.st_nlink == 1 || same_name (source, dest)))
202 error (0, 0, _("%s and %s are the same file"),
203 quote_n (0, source), quote_n (1, dest));
209 if (S_ISDIR (dest_stats.st_mode))
211 error (0, 0, _("%s: cannot overwrite directory"), quote (dest));
216 fprintf (stderr, _("%s: replace %s? "), program_name, quote (dest));
219 remove_existing_files = true;
222 if (backup_type != no_backups)
224 dest_backup = find_backup_file_name (dest, backup_type);
225 if (rename (dest, dest_backup) != 0)
227 int rename_errno = errno;
230 if (rename_errno != ENOENT)
232 error (0, rename_errno, _("cannot backup %s"), quote (dest));
239 ok = ((symbolic_link ? symlink (source, dest) : link (source, dest))
242 /* If the attempt to create a link failed and we are removing or
243 backing up destinations, unlink the destination and try again.
245 POSIX 1003.1-2004 requires that ln -f A B must unlink B even on
246 failure (e.g., when A does not exist). This is counterintuitive,
247 and we submitted a defect report
248 <http://www.opengroup.org/austin/mailarchives/ag-review/msg01794.html>
249 (2004-06-24). If the committee does not fix the standard we'll
250 have to change the behavior of ln -f, at least if POSIXLY_CORRECT
251 is set. In the meantime ln -f A B will not unlink B unless the
252 attempt to link A to B failed because B already existed.
254 Try to unlink DEST even if we may have backed it up successfully.
255 In some unusual cases (when DEST and DEST_BACKUP are hard-links
256 that refer to the same file), rename succeeds and DEST remains.
257 If we didn't remove DEST in that case, the subsequent LINKFUNC
260 if (!ok && errno == EEXIST && (remove_existing_files || dest_backup))
262 if (unlink (dest) != 0)
264 error (0, errno, _("cannot remove %s"), quote (dest));
269 ok = ((symbolic_link ? symlink (source, dest) : link (source, dest))
278 printf ("%s ~ ", quote (dest_backup));
279 printf ("%s %c> %s\n", quote_n (0, dest), (symbolic_link ? '-' : '='),
280 quote_n (1, source));
287 ? (errno != ENAMETOOLONG && *source
288 ? _("creating symbolic link %s")
289 : _("creating symbolic link %s -> %s"))
290 : (errno == EMLINK && !source_is_dir
291 ? _("creating hard link to %.0s%s")
292 : (errno == EDQUOT || errno == EEXIST || errno == ENOSPC
294 ? _("creating hard link %s")
295 : _("creating hard link %s => %s"))),
296 quote_n (0, dest), quote_n (1, source));
300 if (rename (dest_backup, dest) != 0)
301 error (0, errno, _("cannot un-backup %s"), quote (dest));
312 if (status != EXIT_SUCCESS)
313 fprintf (stderr, _("Try `%s --help' for more information.\n"),
318 Usage: %s [OPTION]... [-T] TARGET LINK_NAME (1st form)\n\
319 or: %s [OPTION]... TARGET (2nd form)\n\
320 or: %s [OPTION]... TARGET... DIRECTORY (3rd form)\n\
321 or: %s [OPTION]... -t DIRECTORY TARGET... (4th form)\n\
323 program_name, program_name, program_name, program_name);
325 In the 1st form, create a link to TARGET with the name LINK_NAME.\n\
326 In the 2nd form, create a link to TARGET in the current directory.\n\
327 In the 3rd and 4th forms, create links to each TARGET in DIRECTORY.\n\
328 Create hard links by default, symbolic links with --symbolic.\n\
329 When creating hard links, each TARGET must exist.\n\
333 Mandatory arguments to long options are mandatory for short options too.\n\
336 --backup[=CONTROL] make a backup of each existing destination file\n\
337 -b like --backup but does not accept an argument\n\
338 -d, -F, --directory allow the superuser to attempt to hard link\n\
339 directories (note: will probably fail due to\n\
340 system restrictions, even for the superuser)\n\
341 -f, --force remove existing destination files\n\
344 -n, --no-dereference treat destination that is a symlink to a\n\
345 directory as if it were a normal file\n\
346 -i, --interactive prompt whether to remove destinations\n\
347 -s, --symbolic make symbolic links instead of hard links\n\
350 -S, --suffix=SUFFIX override the usual backup suffix\n\
351 -t, --target-directory=DIRECTORY specify the DIRECTORY in which to create\n\
353 -T, --no-target-directory treat LINK_NAME as a normal file\n\
354 -v, --verbose print name of each linked file\n\
356 fputs (HELP_OPTION_DESCRIPTION, stdout);
357 fputs (VERSION_OPTION_DESCRIPTION, stdout);
360 The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
361 The version control method may be selected via the --backup option or through\n\
362 the VERSION_CONTROL environment variable. Here are the values:\n\
366 none, off never make backups (even if --backup is given)\n\
367 numbered, t make numbered backups\n\
368 existing, nil numbered if numbered backups exist, simple otherwise\n\
369 simple, never always make simple backups\n\
371 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
377 main (int argc, char **argv)
381 bool make_backups = false;
382 char *backup_suffix_string;
383 char *version_control_string = NULL;
384 char const *target_directory = NULL;
385 bool no_target_directory = false;
389 initialize_main (&argc, &argv);
390 program_name = argv[0];
391 setlocale (LC_ALL, "");
392 bindtextdomain (PACKAGE, LOCALEDIR);
393 textdomain (PACKAGE);
395 atexit (close_stdout);
397 /* FIXME: consider not calling getenv for SIMPLE_BACKUP_SUFFIX unless
398 we'll actually use backup_suffix_string. */
399 backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
401 symbolic_link = remove_existing_files = interactive = verbose
402 = hard_dir_link = false;
404 while ((c = getopt_long (argc, argv, "bdfinst:vFS:T", long_options, NULL))
412 version_control_string = optarg;
416 hard_dir_link = true;
419 remove_existing_files = true;
423 remove_existing_files = false;
427 dereference_dest_dir_symlinks = false;
430 symbolic_link = true;
433 if (target_directory)
434 error (EXIT_FAILURE, 0, _("multiple target directories specified"));
438 if (stat (optarg, &st) != 0)
439 error (EXIT_FAILURE, errno, _("accessing %s"), quote (optarg));
440 if (! S_ISDIR (st.st_mode))
441 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
444 target_directory = optarg;
447 no_target_directory = true;
454 backup_suffix_string = optarg;
456 case_GETOPT_HELP_CHAR;
457 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
459 usage (EXIT_FAILURE);
464 n_files = argc - optind;
465 file = argv + optind;
469 error (0, 0, _("missing file operand"));
470 usage (EXIT_FAILURE);
473 if (no_target_directory)
475 if (target_directory)
476 error (EXIT_FAILURE, 0,
477 _("Cannot combine --target-directory "
478 "and --no-target-directory"));
483 _("missing destination file operand after %s"),
486 error (0, 0, _("extra operand %s"), quote (file[2]));
487 usage (EXIT_FAILURE);
490 else if (!target_directory)
493 target_directory = ".";
494 else if (2 <= n_files && target_directory_operand (file[n_files - 1]))
495 target_directory = file[--n_files];
496 else if (2 < n_files)
497 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
498 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,
516 last_component (file[i]),
518 strip_trailing_slashes (dest_base);
519 ok &= do_link (file[i], dest);
524 ok = do_link (file[0], file[1]);
526 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);