* tests/sample-test: Update copyright date to 2007.
[coreutils.git] / src / ln.c
blobfae370807b340f21d025aac7493a2d36912d1e3b
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)
7 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, 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. */
20 #include <config.h>
21 #include <stdio.h>
22 #include <sys/types.h>
23 #include <getopt.h>
25 #include "system.h"
26 #include "same.h"
27 #include "backupfile.h"
28 #include "error.h"
29 #include "filenamecat.h"
30 #include "quote.h"
31 #include "yesno.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
40 #endif
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) \
50 stat (File, Stat_buf)
51 #else
52 # define STAT_LIKE_LINK(File, Stat_buf) \
53 lstat (File, Stat_buf)
54 #endif
56 /* The name by which the program was run, for error messages. */
57 char *program_name;
59 /* FIXME: document */
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. */
72 static bool verbose;
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},
100 {NULL, 0, NULL, 0}
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. */
108 static bool
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]));
114 struct stat st;
115 int stat_result =
116 (dereference_dest_dir_symlinks ? stat (file, &st) : lstat (file, &st));
117 int err = (stat_result == 0 ? 0 : errno);
118 bool is_a_dir = !err && S_ISDIR (st.st_mode);
119 if (err && err != ENOENT)
120 error (EXIT_FAILURE, err, _("accessing %s"), quote (file));
121 if (is_a_dir < looks_like_a_dir)
122 error (EXIT_FAILURE, err, _("target %s is not a directory"), quote (file));
123 return is_a_dir;
126 /* Make a link DEST to the (usually) existing file SOURCE.
127 Symbolic links to nonexistent files are allowed.
128 Return true if successful. */
130 static bool
131 do_link (const char *source, const char *dest)
133 struct stat source_stats;
134 struct stat dest_stats;
135 char *dest_backup = NULL;
136 bool dest_lstat_ok = false;
137 bool source_is_dir = false;
138 bool ok;
140 /* Use stat here instead of lstat.
141 On SVR4, link does not follow symlinks, so this check disallows
142 making hard links to symlinks that point to directories. Big deal.
143 On other systems, link follows symlinks, so this check is right. */
144 if (!symbolic_link)
146 if (STAT_LIKE_LINK (source, &source_stats) != 0)
148 error (0, errno, _("accessing %s"), quote (source));
149 return false;
152 if (ENABLE_HARD_LINK_TO_SYMLINK_WARNING
153 && S_ISLNK (source_stats.st_mode))
155 error (0, 0, _("%s: warning: making a hard link to a symbolic link\
156 is not portable"),
157 quote (source));
160 if (S_ISDIR (source_stats.st_mode))
162 source_is_dir = true;
163 if (! hard_dir_link)
165 error (0, 0, _("%s: hard link not allowed for directory"),
166 quote (source));
167 return false;
172 if (remove_existing_files || interactive || backup_type != no_backups)
174 dest_lstat_ok = (lstat (dest, &dest_stats) == 0);
175 if (!dest_lstat_ok && errno != ENOENT)
177 error (0, errno, _("accessing %s"), quote (dest));
178 return false;
182 /* If --force (-f) has been specified without --backup, then before
183 making a link ln must remove the destination file if it exists.
184 (with --backup, it just renames any existing destination file)
185 But if the source and destination are the same, don't remove
186 anything and fail right here. */
187 if ((remove_existing_files
188 /* Ensure that "ln --backup f f" fails here, with the
189 "... same file" diagnostic, below. Otherwise, subsequent
190 code would give a misleading "file not found" diagnostic.
191 This case is different than the others handled here, since
192 the command in question doesn't use --force. */
193 || (!symbolic_link && backup_type != no_backups))
194 && dest_lstat_ok
195 /* Allow `ln -sf --backup k k' to succeed in creating the
196 self-referential symlink, but don't allow the hard-linking
197 equivalent: `ln -f k k' (with or without --backup) to get
198 beyond this point, because the error message you'd get is
199 misleading. */
200 && (backup_type == no_backups || !symbolic_link)
201 && (!symbolic_link || stat (source, &source_stats) == 0)
202 && SAME_INODE (source_stats, dest_stats)
203 /* The following detects whether removing DEST will also remove
204 SOURCE. If the file has only one link then both are surely
205 the same link. Otherwise check whether they point to the same
206 name in the same directory. */
207 && (source_stats.st_nlink == 1 || same_name (source, dest)))
209 error (0, 0, _("%s and %s are the same file"),
210 quote_n (0, source), quote_n (1, dest));
211 return false;
214 if (dest_lstat_ok)
216 if (S_ISDIR (dest_stats.st_mode))
218 error (0, 0, _("%s: cannot overwrite directory"), quote (dest));
219 return false;
221 if (interactive)
223 fprintf (stderr, _("%s: replace %s? "), program_name, quote (dest));
224 if (!yesno ())
225 return true;
226 remove_existing_files = true;
229 if (backup_type != no_backups)
231 dest_backup = find_backup_file_name (dest, backup_type);
232 if (rename (dest, dest_backup) != 0)
234 int rename_errno = errno;
235 free (dest_backup);
236 dest_backup = NULL;
237 if (rename_errno != ENOENT)
239 error (0, rename_errno, _("cannot backup %s"), quote (dest));
240 return false;
246 ok = ((symbolic_link ? symlink (source, dest) : link (source, dest))
247 == 0);
249 /* If the attempt to create a link failed and we are removing or
250 backing up destinations, unlink the destination and try again.
252 POSIX 1003.1-2004 requires that ln -f A B must unlink B even on
253 failure (e.g., when A does not exist). This is counterintuitive,
254 and we submitted a defect report
255 <http://www.opengroup.org/austin/mailarchives/ag-review/msg01794.html>
256 (2004-06-24). If the committee does not fix the standard we'll
257 have to change the behavior of ln -f, at least if POSIXLY_CORRECT
258 is set. In the meantime ln -f A B will not unlink B unless the
259 attempt to link A to B failed because B already existed.
261 Try to unlink DEST even if we may have backed it up successfully.
262 In some unusual cases (when DEST and DEST_BACKUP are hard-links
263 that refer to the same file), rename succeeds and DEST remains.
264 If we didn't remove DEST in that case, the subsequent symlink or link
265 call would fail. */
267 if (!ok && errno == EEXIST && (remove_existing_files || dest_backup))
269 if (unlink (dest) != 0)
271 error (0, errno, _("cannot remove %s"), quote (dest));
272 free (dest_backup);
273 return false;
276 ok = ((symbolic_link ? symlink (source, dest) : link (source, dest))
277 == 0);
280 if (ok)
282 if (verbose)
284 if (dest_backup)
285 printf ("%s ~ ", quote (dest_backup));
286 printf ("%s %c> %s\n", quote_n (0, dest), (symbolic_link ? '-' : '='),
287 quote_n (1, source));
290 else
292 error (0, errno,
293 (symbolic_link
294 ? (errno != ENAMETOOLONG && *source
295 ? _("creating symbolic link %s")
296 : _("creating symbolic link %s -> %s"))
297 : (errno == EMLINK && !source_is_dir
298 ? _("creating hard link to %.0s%s")
299 : (errno == EDQUOT || errno == EEXIST || errno == ENOSPC
300 || errno == EROFS)
301 ? _("creating hard link %s")
302 : _("creating hard link %s => %s"))),
303 quote_n (0, dest), quote_n (1, source));
305 if (dest_backup)
307 if (rename (dest_backup, dest) != 0)
308 error (0, errno, _("cannot un-backup %s"), quote (dest));
312 free (dest_backup);
313 return ok;
316 void
317 usage (int status)
319 if (status != EXIT_SUCCESS)
320 fprintf (stderr, _("Try `%s --help' for more information.\n"),
321 program_name);
322 else
324 printf (_("\
325 Usage: %s [OPTION]... [-T] TARGET LINK_NAME (1st form)\n\
326 or: %s [OPTION]... TARGET (2nd form)\n\
327 or: %s [OPTION]... TARGET... DIRECTORY (3rd form)\n\
328 or: %s [OPTION]... -t DIRECTORY TARGET... (4th form)\n\
330 program_name, program_name, program_name, program_name);
331 fputs (_("\
332 In the 1st form, create a link to TARGET with the name LINK_NAME.\n\
333 In the 2nd form, create a link to TARGET in the current directory.\n\
334 In the 3rd and 4th forms, create links to each TARGET in DIRECTORY.\n\
335 Create hard links by default, symbolic links with --symbolic.\n\
336 When creating hard links, each TARGET must exist.\n\
338 "), stdout);
339 fputs (_("\
340 Mandatory arguments to long options are mandatory for short options too.\n\
341 "), stdout);
342 fputs (_("\
343 --backup[=CONTROL] make a backup of each existing destination file\n\
344 -b like --backup but does not accept an argument\n\
345 -d, -F, --directory allow the superuser to attempt to hard link\n\
346 directories (note: will probably fail due to\n\
347 system restrictions, even for the superuser)\n\
348 -f, --force remove existing destination files\n\
349 "), stdout);
350 fputs (_("\
351 -n, --no-dereference treat destination that is a symlink to a\n\
352 directory as if it were a normal file\n\
353 -i, --interactive prompt whether to remove destinations\n\
354 -s, --symbolic make symbolic links instead of hard links\n\
355 "), stdout);
356 fputs (_("\
357 -S, --suffix=SUFFIX override the usual backup suffix\n\
358 -t, --target-directory=DIRECTORY specify the DIRECTORY in which to create\n\
359 the links\n\
360 -T, --no-target-directory treat LINK_NAME as a normal file\n\
361 -v, --verbose print name of each linked file\n\
362 "), stdout);
363 fputs (HELP_OPTION_DESCRIPTION, stdout);
364 fputs (VERSION_OPTION_DESCRIPTION, stdout);
365 fputs (_("\
367 The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
368 The version control method may be selected via the --backup option or through\n\
369 the VERSION_CONTROL environment variable. Here are the values:\n\
371 "), stdout);
372 fputs (_("\
373 none, off never make backups (even if --backup is given)\n\
374 numbered, t make numbered backups\n\
375 existing, nil numbered if numbered backups exist, simple otherwise\n\
376 simple, never always make simple backups\n\
377 "), stdout);
378 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
380 exit (status);
384 main (int argc, char **argv)
386 int c;
387 bool ok;
388 bool make_backups = false;
389 char *backup_suffix_string;
390 char *version_control_string = NULL;
391 char const *target_directory = NULL;
392 bool no_target_directory = false;
393 int n_files;
394 char **file;
396 initialize_main (&argc, &argv);
397 program_name = argv[0];
398 setlocale (LC_ALL, "");
399 bindtextdomain (PACKAGE, LOCALEDIR);
400 textdomain (PACKAGE);
402 atexit (close_stdout);
404 /* FIXME: consider not calling getenv for SIMPLE_BACKUP_SUFFIX unless
405 we'll actually use backup_suffix_string. */
406 backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
408 symbolic_link = remove_existing_files = interactive = verbose
409 = hard_dir_link = false;
411 while ((c = getopt_long (argc, argv, "bdfinst:vFS:T", long_options, NULL))
412 != -1)
414 switch (c)
416 case 'b':
417 make_backups = true;
418 if (optarg)
419 version_control_string = optarg;
420 break;
421 case 'd':
422 case 'F':
423 hard_dir_link = true;
424 break;
425 case 'f':
426 remove_existing_files = true;
427 interactive = false;
428 break;
429 case 'i':
430 remove_existing_files = false;
431 interactive = true;
432 break;
433 case 'n':
434 dereference_dest_dir_symlinks = false;
435 break;
436 case 's':
437 symbolic_link = true;
438 break;
439 case 't':
440 if (target_directory)
441 error (EXIT_FAILURE, 0, _("multiple target directories specified"));
442 else
444 struct stat st;
445 if (stat (optarg, &st) != 0)
446 error (EXIT_FAILURE, errno, _("accessing %s"), quote (optarg));
447 if (! S_ISDIR (st.st_mode))
448 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
449 quote (optarg));
451 target_directory = optarg;
452 break;
453 case 'T':
454 no_target_directory = true;
455 break;
456 case 'v':
457 verbose = true;
458 break;
459 case 'S':
460 make_backups = true;
461 backup_suffix_string = optarg;
462 break;
463 case_GETOPT_HELP_CHAR;
464 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
465 default:
466 usage (EXIT_FAILURE);
467 break;
471 n_files = argc - optind;
472 file = argv + optind;
474 if (n_files <= 0)
476 error (0, 0, _("missing file operand"));
477 usage (EXIT_FAILURE);
480 if (no_target_directory)
482 if (target_directory)
483 error (EXIT_FAILURE, 0,
484 _("Cannot combine --target-directory "
485 "and --no-target-directory"));
486 if (n_files != 2)
488 if (n_files < 2)
489 error (0, 0,
490 _("missing destination file operand after %s"),
491 quote (file[0]));
492 else
493 error (0, 0, _("extra operand %s"), quote (file[2]));
494 usage (EXIT_FAILURE);
497 else if (!target_directory)
499 if (n_files < 2)
500 target_directory = ".";
501 else if (2 <= n_files && target_directory_operand (file[n_files - 1]))
502 target_directory = file[--n_files];
503 else if (2 < n_files)
504 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
505 quote (file[n_files - 1]));
508 if (backup_suffix_string)
509 simple_backup_suffix = xstrdup (backup_suffix_string);
511 backup_type = (make_backups
512 ? xget_version (_("backup type"), version_control_string)
513 : no_backups);
515 if (target_directory)
517 int i;
518 ok = true;
519 for (i = 0; i < n_files; ++i)
521 char *dest_base;
522 char *dest = file_name_concat (target_directory,
523 last_component (file[i]),
524 &dest_base);
525 strip_trailing_slashes (dest_base);
526 ok &= do_link (file[i], dest);
527 free (dest);
530 else
531 ok = do_link (file[0], file[1]);
533 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);