(noinst_HEADERS): Add nanosleep.h.
[coreutils.git] / src / ln.c
blob671016aa76c50f2ccb50f4c296812fe1d1916d71
1 /* `ln' program to create links between files.
2 Copyright (C) 86, 89, 90, 91, 1995-2000 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18 /* Written by Mike Parker and David MacKenzie. */
20 #ifdef _AIX
21 #pragma alloca
22 #endif
24 #include <config.h>
25 #include <stdio.h>
26 #include <sys/types.h>
27 #include <getopt.h>
29 #include "system.h"
30 #include "same.h"
31 #include "backupfile.h"
32 #include "error.h"
34 /* The official name of this program (e.g., no `g' prefix). */
35 #define PROGRAM_NAME "ln"
37 #define AUTHORS "Mike Parker and David MacKenzie"
39 /* For long options that have no equivalent short option, use a
40 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
41 enum
43 TARGET_DIRECTORY_OPTION = CHAR_MAX + 1
46 int link (); /* Some systems don't declare this anywhere. */
48 #ifdef S_ISLNK
49 int symlink ();
50 #endif
52 /* In being careful not even to try to make hard links to directories,
53 we have to know whether link(2) follows symlinks. If it does, then
54 we have to *stat* the `source' to see if the resulting link would be
55 to a directory. Otherwise, we have to use *lstat* so that we allow
56 users to make hard links to symlinks-that-point-to-directories. */
58 #if LINK_FOLLOWS_SYMLINKS
59 # define STAT_LIKE_LINK(File, Stat_buf) \
60 stat (File, Stat_buf)
61 #else
62 # define STAT_LIKE_LINK(File, Stat_buf) \
63 lstat (File, Stat_buf)
64 #endif
66 /* Construct a string NEW_DEST by concatenating DEST, a slash, and
67 basename(SOURCE) in alloca'd memory. Don't modify DEST or SOURCE. */
69 #define PATH_BASENAME_CONCAT(new_dest, dest, source) \
70 do \
71 { \
72 const char *source_base; \
73 char *tmp_source; \
75 tmp_source = (char *) alloca (strlen ((source)) + 1); \
76 strcpy (tmp_source, (source)); \
77 strip_trailing_slashes (tmp_source); \
78 source_base = base_name (tmp_source); \
80 (new_dest) = (char *) alloca (strlen ((dest)) + 1 \
81 + strlen (source_base) + 1); \
82 stpcpy (stpcpy (stpcpy ((new_dest), (dest)), "/"), source_base);\
83 } \
84 while (0)
86 int isdir ();
87 int yesno ();
88 void strip_trailing_slashes ();
90 /* The name by which the program was run, for error messages. */
91 char *program_name;
93 /* FIXME: document */
94 enum backup_type backup_type;
96 /* A pointer to the function used to make links. This will point to either
97 `link' or `symlink'. */
98 static int (*linkfunc) ();
100 /* If nonzero, make symbolic links; otherwise, make hard links. */
101 static int symbolic_link;
103 /* A string describing type of link to make. For use in verbose
104 diagnostics and in error messages. */
105 static const char *link_type_string;
107 /* If nonzero, ask the user before removing existing files. */
108 static int interactive;
110 /* If nonzero, remove existing files unconditionally. */
111 static int remove_existing_files;
113 /* If nonzero, list each file as it is moved. */
114 static int verbose;
116 /* If nonzero, allow the superuser to make hard links to directories. */
117 static int hard_dir_link;
119 /* If nonzero, and the specified destination is a symbolic link to a
120 directory, treat it just as if it were a directory. Otherwise, the
121 command `ln --force --no-dereference file symlink-to-dir' deletes
122 symlink-to-dir before creating the new link. */
123 static int dereference_dest_dir_symlinks = 1;
125 static struct option const long_options[] =
127 {"backup", optional_argument, NULL, 'b'},
128 {"directory", no_argument, NULL, 'F'},
129 {"no-dereference", no_argument, NULL, 'n'},
130 {"force", no_argument, NULL, 'f'},
131 {"interactive", no_argument, NULL, 'i'},
132 {"suffix", required_argument, NULL, 'S'},
133 {"target-directory", required_argument, NULL, TARGET_DIRECTORY_OPTION},
134 {"symbolic", no_argument, NULL, 's'},
135 {"verbose", no_argument, NULL, 'v'},
136 {"version-control", required_argument, NULL, 'V'}, /* Deprecated. FIXME. */
137 {GETOPT_HELP_OPTION_DECL},
138 {GETOPT_VERSION_OPTION_DECL},
139 {NULL, 0, NULL, 0}
142 /* Make a link DEST to the (usually) existing file SOURCE.
143 Symbolic links to nonexistent files are allowed.
144 If DEST is a directory, put the link to SOURCE in that directory.
145 Return 1 if there is an error, otherwise 0. */
147 static int
148 do_link (const char *source, const char *dest)
150 struct stat source_stats;
151 struct stat dest_stats;
152 char *dest_backup = NULL;
153 int lstat_status;
154 int backup_succeeded = 0;
156 /* Use stat here instead of lstat.
157 On SVR4, link does not follow symlinks, so this check disallows
158 making hard links to symlinks that point to directories. Big deal.
159 On other systems, link follows symlinks, so this check is right. */
160 if (!symbolic_link)
162 if (STAT_LIKE_LINK (source, &source_stats) != 0)
164 error (0, errno, "%s", source);
165 return 1;
168 if (S_ISLNK (source_stats.st_mode))
170 error (0, 0, _("%s: warning: making a hard link to a symbolic link\
171 is not portable"),
172 source);
175 if (!hard_dir_link && S_ISDIR (source_stats.st_mode))
177 error (0, 0, _("%s: hard link not allowed for directory"), source);
178 return 1;
182 lstat_status = lstat (dest, &dest_stats);
183 if (lstat_status != 0 && errno != ENOENT)
185 error (0, errno, "%s", dest);
186 return 1;
189 /* If the destination is a directory or (it is a symlink to a directory
190 and the user has not specified --no-dereference), then form the
191 actual destination name by appending base_name (source) to the
192 specified destination directory. */
193 if ((lstat_status == 0
194 && S_ISDIR (dest_stats.st_mode))
195 #ifdef S_ISLNK
196 || (dereference_dest_dir_symlinks
197 && (lstat_status == 0
198 && S_ISLNK (dest_stats.st_mode)
199 && isdir (dest)))
200 #endif
203 /* Target is a directory; build the full filename. */
204 char *new_dest;
205 PATH_BASENAME_CONCAT (new_dest, dest, source);
206 dest = new_dest;
208 /* Get stats for new DEST. */
209 lstat_status = lstat (dest, &dest_stats);
210 if (lstat_status != 0 && errno != ENOENT)
212 error (0, errno, "%s", dest);
213 return 1;
217 /* If --force (-f) has been specified without --backup, then before
218 making a link ln must remove the destination file if it exists.
219 (with --backup, it just renames any existing destination file)
220 But if the source and destination are the same, don't remove
221 anything and fail right here. */
222 if (remove_existing_files
223 && lstat_status == 0
224 /* Allow `ln -sf --backup k k' to succeed in creating the
225 self-referential symlink, but don't allow the hard-linking
226 equivalent: `ln -f k k' (with or without --backup) to get
227 beyond this point, because the error message you'd get is
228 misleading. */
229 && (backup_type == none || !symlink)
230 && (!symbolic_link || stat (source, &source_stats) == 0)
231 && source_stats.st_dev == dest_stats.st_dev
232 && source_stats.st_ino == dest_stats.st_ino
233 /* The following detects whether removing DEST will also remove
234 SOURCE. If the file has only one link then both are surely
235 the same link. Otherwise check whether they point to the same
236 name in the same directory. */
237 && (source_stats.st_nlink == 1 || same_name (source, dest)))
239 error (0, 0, _("`%s' and `%s' are the same file"), source, dest);
240 return 1;
243 if (lstat_status == 0 || lstat (dest, &dest_stats) == 0)
245 if (S_ISDIR (dest_stats.st_mode))
247 error (0, 0, _("%s: cannot overwrite directory"), dest);
248 return 1;
250 if (interactive)
252 fprintf (stderr, _("%s: replace `%s'? "), program_name, dest);
253 if (!yesno ())
254 return 0;
256 else if (!remove_existing_files && backup_type == none)
258 error (0, 0, _("%s: File exists"), dest);
259 return 1;
262 if (backup_type != none)
264 char *tmp_backup = find_backup_file_name (dest, backup_type);
265 if (tmp_backup == NULL)
266 error (1, 0, _("virtual memory exhausted"));
267 dest_backup = (char *) alloca (strlen (tmp_backup) + 1);
268 strcpy (dest_backup, tmp_backup);
269 free (tmp_backup);
270 if (rename (dest, dest_backup))
272 if (errno != ENOENT)
274 error (0, errno, _("cannot backup `%s'"), dest);
275 return 1;
277 else
278 dest_backup = NULL;
280 else
282 backup_succeeded = 1;
286 /* Try to unlink DEST even if we may have renamed it. In some unusual
287 cases (when DEST and DEST_BACKUP are hard-links that refer to the
288 same file), rename succeeds and DEST remains. If we didn't remove
289 DEST in that case, the subsequent LINKFUNC call would fail. */
290 if (unlink (dest) && errno != ENOENT)
292 error (0, errno, _("cannot remove `%s'"), dest);
293 return 1;
296 else if (errno != ENOENT)
298 error (0, errno, "%s", dest);
299 return 1;
302 if (verbose)
304 printf (_("create %s %s to %s"), link_type_string, dest, source);
305 if (backup_succeeded)
306 printf (_(" (backup: %s)"), dest_backup);
307 putchar ('\n');
310 if ((*linkfunc) (source, dest) == 0)
312 return 0;
315 error (0, errno, _("cannot create %s `%s' to `%s'"), link_type_string,
316 dest, source);
318 if (dest_backup)
320 if (rename (dest_backup, dest))
321 error (0, errno, _("cannot un-backup `%s'"), dest);
323 return 1;
326 void
327 usage (int status)
329 if (status != 0)
330 fprintf (stderr, _("Try `%s --help' for more information.\n"),
331 program_name);
332 else
334 printf (_("\
335 Usage: %s [OPTION]... TARGET [LINK_NAME]\n\
336 or: %s [OPTION]... TARGET... DIRECTORY\n\
337 or: %s [OPTION]... --target-directory=DIRECTORY TARGET...\n\
339 program_name, program_name, program_name);
340 printf (_("\
341 Create a link to the specified TARGET with optional LINK_NAME. If there is\n\
342 more than one TARGET, the last argument must be a directory; create links\n\
343 in DIRECTORY to each TARGET. Create hard links by default, symbolic links\n\
344 with --symbolic. When creating hard links, each TARGET must exist.\n\
346 -b, --backup[=CONTROL] make a backup of each existing destination file\n\
347 -d, -F, --directory hard link directories (super-user only)\n\
348 -f, --force remove existing destination files\n\
349 -n, --no-dereference treat destination that is a symlink to a\n\
350 directory as if it were a normal file\n\
351 -i, --interactive prompt whether to remove destinations\n\
352 -s, --symbolic make symbolic links instead of hard links\n\
353 -S, --suffix=SUFFIX override the usual backup suffix\n\
354 --target-directory=DIRECTORY specify the DIRECTORY in which to create\n\
355 the links\n\
356 -v, --verbose print name of each file before linking\n\
357 --help display this help and exit\n\
358 --version output version information and exit\n\
360 "));
361 printf (_("\
362 The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
363 The version control method may be selected via the --backup option or through\n\
364 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\
370 "));
371 puts (_("\nReport bugs to <bug-fileutils@gnu.org>."));
372 close_stdout ();
374 exit (status);
378 main (int argc, char **argv)
380 int c;
381 int errors;
382 int make_backups = 0;
383 char *backup_suffix_string;
384 char *version_control_string = NULL;
385 char *target_directory = NULL;
386 int target_directory_specified;
387 unsigned int n_files;
388 char **file;
389 int dest_is_dir;
391 program_name = argv[0];
392 setlocale (LC_ALL, "");
393 bindtextdomain (PACKAGE, LOCALEDIR);
394 textdomain (PACKAGE);
396 /* FIXME: consider not calling getenv for SIMPLE_BACKUP_SUFFIX unless
397 we'll actually use backup_suffix_string. */
398 backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
400 symbolic_link = remove_existing_files = interactive = verbose
401 = hard_dir_link = 0;
402 errors = 0;
404 while ((c = getopt_long (argc, argv, "bdfinsvFS:V:", long_options, NULL))
405 != -1)
407 switch (c)
409 case 0: /* Long-named option. */
410 break;
412 case 'V': /* FIXME: this is deprecated. Remove it in 2001. */
413 error (0, 0,
414 _("warning: --version-control (-V) is obsolete; support for\
415 it\nwill be removed in some future release. Use --backup=%s instead."
416 ), optarg);
417 /* Fall through. */
419 case 'b':
420 make_backups = 1;
421 if (optarg)
422 version_control_string = optarg;
423 break;
424 case 'd':
425 case 'F':
426 hard_dir_link = 1;
427 break;
428 case 'f':
429 remove_existing_files = 1;
430 interactive = 0;
431 break;
432 case 'i':
433 remove_existing_files = 0;
434 interactive = 1;
435 break;
436 case 'n':
437 dereference_dest_dir_symlinks = 0;
438 break;
439 case 's':
440 #ifdef S_ISLNK
441 symbolic_link = 1;
442 #else
443 error (1, 0, _("symbolic links are not supported on this system"));
444 #endif
445 break;
446 case TARGET_DIRECTORY_OPTION:
447 target_directory = optarg;
448 break;
449 case 'v':
450 verbose = 1;
451 break;
452 case 'S':
453 make_backups = 1;
454 backup_suffix_string = optarg;
455 break;
456 case_GETOPT_HELP_CHAR;
457 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
458 default:
459 usage (1);
460 break;
464 n_files = argc - optind;
465 file = argv + optind;
467 if (n_files == 0)
469 error (0, 0, _("missing file argument"));
470 usage (1);
473 target_directory_specified = (target_directory != NULL);
474 if (!target_directory)
475 target_directory = file[n_files - 1];
477 /* If there's only one file argument, then pretend `.' was given
478 as the second argument. */
479 if (n_files == 1)
481 static char *dummy[2];
482 dummy[0] = file[0];
483 dummy[1] = ".";
484 file = dummy;
485 n_files = 2;
486 dest_is_dir = 1;
488 else
490 dest_is_dir = isdir (target_directory);
493 #ifdef S_ISLNK
494 if (symbolic_link)
496 linkfunc = symlink;
497 link_type_string = _("symbolic link");
499 else
501 linkfunc = link;
502 link_type_string = _("hard link");
504 #else
505 link_type_string = _("link");
506 #endif
508 if (target_directory_specified && !dest_is_dir)
510 error (0, 0, _("specified target directory, `%s' is not a directory"),
511 target_directory);
512 usage (1);
515 backup_type = (make_backups
516 ? xget_version (_("--version-control"), version_control_string)
517 : none);
519 if (target_directory_specified || n_files > 2)
521 int i;
522 unsigned int last_file_idx = (target_directory_specified
523 ? n_files - 1
524 : n_files - 2);
526 if (!target_directory_specified && !dest_is_dir)
527 error (1, 0,
528 _("when making multiple links, last argument must be a directory"));
529 for (i = 0; i <= last_file_idx; ++i)
530 errors += do_link (file[i], target_directory);
532 else
534 struct stat source_stats;
535 const char *source;
536 char *dest;
537 char *new_dest;
539 source = file[0];
540 dest = file[1];
542 /* When the destination is specified with a trailing slash and the
543 source exists but is not a directory, convert the user's command
544 `ln source dest/' to `ln source dest/basename(source)'. */
546 if (dest[strlen (dest) - 1] == '/'
547 && lstat (source, &source_stats) == 0
548 && !S_ISDIR (source_stats.st_mode))
550 PATH_BASENAME_CONCAT (new_dest, dest, source);
552 else
554 new_dest = dest;
557 errors = do_link (source, new_dest);
560 if (verbose)
561 close_stdout ();
562 exit (errors != 0);