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 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>
26 #include "backupfile.h"
28 #include "filenamecat.h"
32 /* The official name of this program (e.g., no `g' prefix). */
33 #define PROGRAM_NAME "ln"
35 #define AUTHORS "Mike Parker", "David MacKenzie"
37 #ifndef ENABLE_HARD_LINK_TO_SYMLINK_WARNING
38 # define ENABLE_HARD_LINK_TO_SYMLINK_WARNING 0
41 /* In being careful not even to try to make hard links to directories,
42 we have to know whether link(2) follows symlinks. If it does, then
43 we have to *stat* the `source' to see if the resulting link would be
44 to a directory. Otherwise, we have to use *lstat* so that we allow
45 users to make hard links to symlinks-that-point-to-directories. */
47 #if LINK_FOLLOWS_SYMLINKS
48 # define STAT_LIKE_LINK(File, Stat_buf) \
51 # define STAT_LIKE_LINK(File, Stat_buf) \
52 lstat (File, Stat_buf)
55 /* The name by which the program was run, for error messages. */
59 static enum backup_type backup_type;
61 /* If true, make symbolic links; otherwise, make hard links. */
62 static bool symbolic_link;
64 /* If true, ask the user before removing existing files. */
65 static bool interactive;
67 /* If true, remove existing files unconditionally. */
68 static bool remove_existing_files;
70 /* If true, list each file as it is moved. */
73 /* If true, allow the superuser to *attempt* to make hard links
74 to directories. However, it appears that this option is not useful
75 in practice, since even the superuser is prohibited from hard-linking
76 directories on most (all?) existing systems. */
77 static bool hard_dir_link;
79 /* If nonzero, and the specified destination is a symbolic link to a
80 directory, treat it just as if it were a directory. Otherwise, the
81 command `ln --force --no-dereference file symlink-to-dir' deletes
82 symlink-to-dir before creating the new link. */
83 static bool dereference_dest_dir_symlinks = true;
85 static struct option const long_options[] =
87 {"backup", optional_argument, NULL, 'b'},
88 {"directory", no_argument, NULL, 'F'},
89 {"no-dereference", no_argument, NULL, 'n'},
90 {"no-target-directory", no_argument, NULL, 'T'},
91 {"force", no_argument, NULL, 'f'},
92 {"interactive", no_argument, NULL, 'i'},
93 {"suffix", required_argument, NULL, 'S'},
94 {"target-directory", required_argument, NULL, 't'},
95 {"symbolic", no_argument, NULL, 's'},
96 {"verbose", no_argument, NULL, 'v'},
97 {GETOPT_HELP_OPTION_DECL},
98 {GETOPT_VERSION_OPTION_DECL},
102 /* FILE is the last operand of this command. Return true if FILE is a
103 directory. But report an error there is a problem accessing FILE,
104 or if FILE does not exist but would have to refer to an existing
105 directory if it referred to anything at all. */
108 target_directory_operand (char const *file)
110 char const *b = last_component (file);
111 size_t blen = strlen (b);
112 bool looks_like_a_dir = (blen == 0 || ISSLASH (b[blen - 1]));
115 (dereference_dest_dir_symlinks ? stat (file, &st) : lstat (file, &st));
116 int err = (stat_result == 0 ? 0 : errno);
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 dest_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 dest_lstat_ok = (lstat (dest, &dest_stats) == 0);
174 if (!dest_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
187 /* Ensure that "ln --backup f f" fails here, with the
188 "... same file" diagnostic, below. Otherwise, subsequent
189 code would give a misleading "file not found" diagnostic.
190 This case is different than the others handled here, since
191 the command in question doesn't use --force. */
192 || (!symbolic_link && backup_type != no_backups))
194 /* Allow `ln -sf --backup k k' to succeed in creating the
195 self-referential symlink, but don't allow the hard-linking
196 equivalent: `ln -f k k' (with or without --backup) to get
197 beyond this point, because the error message you'd get is
199 && (backup_type == no_backups || !symbolic_link)
200 && (!symbolic_link || stat (source, &source_stats) == 0)
201 && SAME_INODE (source_stats, dest_stats)
202 /* The following detects whether removing DEST will also remove
203 SOURCE. If the file has only one link then both are surely
204 the same link. Otherwise check whether they point to the same
205 name in the same directory. */
206 && (source_stats.st_nlink == 1 || same_name (source, dest)))
208 error (0, 0, _("%s and %s are the same file"),
209 quote_n (0, source), quote_n (1, dest));
215 if (S_ISDIR (dest_stats.st_mode))
217 error (0, 0, _("%s: cannot overwrite directory"), quote (dest));
222 fprintf (stderr, _("%s: replace %s? "), program_name, quote (dest));
225 remove_existing_files = true;
228 if (backup_type != no_backups)
230 dest_backup = find_backup_file_name (dest, backup_type);
231 if (rename (dest, dest_backup) != 0)
233 int rename_errno = errno;
236 if (rename_errno != ENOENT)
238 error (0, rename_errno, _("cannot backup %s"), quote (dest));
245 ok = ((symbolic_link ? symlink (source, dest) : link (source, dest))
248 /* If the attempt to create a link failed and we are removing or
249 backing up destinations, unlink the destination and try again.
251 POSIX 1003.1-2004 requires that ln -f A B must unlink B even on
252 failure (e.g., when A does not exist). This is counterintuitive,
253 and we submitted a defect report
254 <http://www.opengroup.org/austin/mailarchives/ag-review/msg01794.html>
255 (2004-06-24). If the committee does not fix the standard we'll
256 have to change the behavior of ln -f, at least if POSIXLY_CORRECT
257 is set. In the meantime ln -f A B will not unlink B unless the
258 attempt to link A to B failed because B already existed.
260 Try to unlink DEST even if we may have backed it up successfully.
261 In some unusual cases (when DEST and DEST_BACKUP are hard-links
262 that refer to the same file), rename succeeds and DEST remains.
263 If we didn't remove DEST in that case, the subsequent symlink or link
266 if (!ok && errno == EEXIST && (remove_existing_files || dest_backup))
268 if (unlink (dest) != 0)
270 error (0, errno, _("cannot remove %s"), quote (dest));
275 ok = ((symbolic_link ? symlink (source, dest) : link (source, dest))
284 printf ("%s ~ ", quote (dest_backup));
285 printf ("%s %c> %s\n", quote_n (0, dest), (symbolic_link ? '-' : '='),
286 quote_n (1, source));
293 ? (errno != ENAMETOOLONG && *source
294 ? _("creating symbolic link %s")
295 : _("creating symbolic link %s -> %s"))
296 : (errno == EMLINK && !source_is_dir
297 ? _("creating hard link to %.0s%s")
298 : (errno == EDQUOT || errno == EEXIST || errno == ENOSPC
300 ? _("creating hard link %s")
301 : _("creating hard link %s => %s"))),
302 quote_n (0, dest), quote_n (1, source));
306 if (rename (dest_backup, dest) != 0)
307 error (0, errno, _("cannot un-backup %s"), quote (dest));
318 if (status != EXIT_SUCCESS)
319 fprintf (stderr, _("Try `%s --help' for more information.\n"),
324 Usage: %s [OPTION]... [-T] TARGET LINK_NAME (1st form)\n\
325 or: %s [OPTION]... TARGET (2nd form)\n\
326 or: %s [OPTION]... TARGET... DIRECTORY (3rd form)\n\
327 or: %s [OPTION]... -t DIRECTORY TARGET... (4th form)\n\
329 program_name, program_name, program_name, program_name);
331 In the 1st form, create a link to TARGET with the name LINK_NAME.\n\
332 In the 2nd form, create a link to TARGET in the current directory.\n\
333 In the 3rd and 4th forms, create links to each TARGET in DIRECTORY.\n\
334 Create hard links by default, symbolic links with --symbolic.\n\
335 When creating hard links, each TARGET must exist.\n\
339 Mandatory arguments to long options are mandatory for short options too.\n\
342 --backup[=CONTROL] make a backup of each existing destination file\n\
343 -b like --backup but does not accept an argument\n\
344 -d, -F, --directory allow the superuser to attempt to hard link\n\
345 directories (note: will probably fail due to\n\
346 system restrictions, even for the superuser)\n\
347 -f, --force remove existing destination files\n\
350 -n, --no-dereference treat destination that is a symlink to a\n\
351 directory as if it were a normal file\n\
352 -i, --interactive prompt whether to remove destinations\n\
353 -s, --symbolic make symbolic links instead of hard links\n\
356 -S, --suffix=SUFFIX override the usual backup suffix\n\
357 -t, --target-directory=DIRECTORY specify the DIRECTORY in which to create\n\
359 -T, --no-target-directory treat LINK_NAME as a normal file\n\
360 -v, --verbose print name of each linked file\n\
362 fputs (HELP_OPTION_DESCRIPTION, stdout);
363 fputs (VERSION_OPTION_DESCRIPTION, stdout);
366 The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
367 The version control method may be selected via the --backup option or through\n\
368 the VERSION_CONTROL environment variable. Here are the values:\n\
372 none, off never make backups (even if --backup is given)\n\
373 numbered, t make numbered backups\n\
374 existing, nil numbered if numbered backups exist, simple otherwise\n\
375 simple, never always make simple backups\n\
377 emit_bug_reporting_address ();
383 main (int argc, char **argv)
387 bool make_backups = false;
388 char *backup_suffix_string;
389 char *version_control_string = NULL;
390 char const *target_directory = NULL;
391 bool no_target_directory = false;
395 initialize_main (&argc, &argv);
396 program_name = argv[0];
397 setlocale (LC_ALL, "");
398 bindtextdomain (PACKAGE, LOCALEDIR);
399 textdomain (PACKAGE);
401 atexit (close_stdout);
403 /* FIXME: consider not calling getenv for SIMPLE_BACKUP_SUFFIX unless
404 we'll actually use backup_suffix_string. */
405 backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
407 symbolic_link = remove_existing_files = interactive = verbose
408 = hard_dir_link = false;
410 while ((c = getopt_long (argc, argv, "bdfinst:vFS:T", long_options, NULL))
418 version_control_string = optarg;
422 hard_dir_link = true;
425 remove_existing_files = true;
429 remove_existing_files = false;
433 dereference_dest_dir_symlinks = false;
436 symbolic_link = true;
439 if (target_directory)
440 error (EXIT_FAILURE, 0, _("multiple target directories specified"));
444 if (stat (optarg, &st) != 0)
445 error (EXIT_FAILURE, errno, _("accessing %s"), quote (optarg));
446 if (! S_ISDIR (st.st_mode))
447 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
450 target_directory = optarg;
453 no_target_directory = true;
460 backup_suffix_string = optarg;
462 case_GETOPT_HELP_CHAR;
463 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
465 usage (EXIT_FAILURE);
470 n_files = argc - optind;
471 file = argv + optind;
475 error (0, 0, _("missing file operand"));
476 usage (EXIT_FAILURE);
479 if (no_target_directory)
481 if (target_directory)
482 error (EXIT_FAILURE, 0,
483 _("Cannot combine --target-directory "
484 "and --no-target-directory"));
489 _("missing destination file operand after %s"),
492 error (0, 0, _("extra operand %s"), quote (file[2]));
493 usage (EXIT_FAILURE);
496 else if (!target_directory)
499 target_directory = ".";
500 else if (2 <= n_files && target_directory_operand (file[n_files - 1]))
501 target_directory = file[--n_files];
502 else if (2 < n_files)
503 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
504 quote (file[n_files - 1]));
507 if (backup_suffix_string)
508 simple_backup_suffix = xstrdup (backup_suffix_string);
510 backup_type = (make_backups
511 ? xget_version (_("backup type"), version_control_string)
514 if (target_directory)
518 for (i = 0; i < n_files; ++i)
521 char *dest = file_name_concat (target_directory,
522 last_component (file[i]),
524 strip_trailing_slashes (dest_base);
525 ok &= do_link (file[i], dest);
530 ok = do_link (file[0], file[1]);
532 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);