*** empty log message ***
[coreutils.git] / src / ln.c
blob21f55dcd6f11591c8cb4853166f6b9d661a23f30
1 /* `ln' program to create links between files.
2 Copyright (C) 86, 89, 90, 91, 1995-2001 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"
33 #include "quote.h"
35 /* The official name of this program (e.g., no `g' prefix). */
36 #define PROGRAM_NAME "ln"
38 #define AUTHORS "Mike Parker and David MacKenzie"
40 /* For long options that have no equivalent short option, use a
41 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
42 enum
44 TARGET_DIRECTORY_OPTION = CHAR_MAX + 1
47 int link (); /* Some systems don't declare this anywhere. */
49 #ifdef S_ISLNK
50 int symlink ();
51 #endif
53 /* In being careful not even to try to make hard links to directories,
54 we have to know whether link(2) follows symlinks. If it does, then
55 we have to *stat* the `source' to see if the resulting link would be
56 to a directory. Otherwise, we have to use *lstat* so that we allow
57 users to make hard links to symlinks-that-point-to-directories. */
59 #if LINK_FOLLOWS_SYMLINKS
60 # define STAT_LIKE_LINK(File, Stat_buf) \
61 stat (File, Stat_buf)
62 #else
63 # define STAT_LIKE_LINK(File, Stat_buf) \
64 lstat (File, Stat_buf)
65 #endif
67 /* Construct a string NEW_DEST by concatenating DEST, a slash, and
68 basename(SOURCE) in alloca'd memory. Don't modify DEST or SOURCE. */
70 #define PATH_BASENAME_CONCAT(new_dest, dest, source) \
71 do \
72 { \
73 const char *source_base; \
74 char *tmp_source; \
76 tmp_source = (char *) alloca (strlen ((source)) + 1); \
77 strcpy (tmp_source, (source)); \
78 strip_trailing_slashes (tmp_source); \
79 source_base = base_name (tmp_source); \
81 (new_dest) = (char *) alloca (strlen ((dest)) + 1 \
82 + strlen (source_base) + 1); \
83 stpcpy (stpcpy (stpcpy ((new_dest), (dest)), "/"), source_base);\
84 } \
85 while (0)
87 int isdir ();
88 int yesno ();
89 void strip_trailing_slashes ();
91 /* The name by which the program was run, for error messages. */
92 char *program_name;
94 /* FIXME: document */
95 enum backup_type backup_type;
97 /* A pointer to the function used to make links. This will point to either
98 `link' or `symlink'. */
99 static int (*linkfunc) ();
101 /* If nonzero, make symbolic links; otherwise, make hard links. */
102 static int symbolic_link;
104 /* If nonzero, ask the user before removing existing files. */
105 static int interactive;
107 /* If nonzero, remove existing files unconditionally. */
108 static int remove_existing_files;
110 /* If nonzero, list each file as it is moved. */
111 static int verbose;
113 /* If nonzero, allow the superuser to make hard links to directories. */
114 static int hard_dir_link;
116 /* If nonzero, and the specified destination is a symbolic link to a
117 directory, treat it just as if it were a directory. Otherwise, the
118 command `ln --force --no-dereference file symlink-to-dir' deletes
119 symlink-to-dir before creating the new link. */
120 static int dereference_dest_dir_symlinks = 1;
122 static struct option const long_options[] =
124 {"backup", optional_argument, NULL, 'b'},
125 {"directory", no_argument, NULL, 'F'},
126 {"no-dereference", no_argument, NULL, 'n'},
127 {"force", no_argument, NULL, 'f'},
128 {"interactive", no_argument, NULL, 'i'},
129 {"suffix", required_argument, NULL, 'S'},
130 {"target-directory", required_argument, NULL, TARGET_DIRECTORY_OPTION},
131 {"symbolic", no_argument, NULL, 's'},
132 {"verbose", no_argument, NULL, 'v'},
133 {"version-control", required_argument, NULL, 'V'}, /* Deprecated. FIXME. */
134 {GETOPT_HELP_OPTION_DECL},
135 {GETOPT_VERSION_OPTION_DECL},
136 {NULL, 0, NULL, 0}
139 /* Make a link DEST to the (usually) existing file SOURCE.
140 Symbolic links to nonexistent files are allowed.
141 If DEST is a directory, put the link to SOURCE in that directory.
142 Return 1 if there is an error, otherwise 0. */
144 static int
145 do_link (const char *source, const char *dest)
147 struct stat source_stats;
148 struct stat dest_stats;
149 char *dest_backup = NULL;
150 int lstat_status;
151 int backup_succeeded = 0;
153 /* Use stat here instead of lstat.
154 On SVR4, link does not follow symlinks, so this check disallows
155 making hard links to symlinks that point to directories. Big deal.
156 On other systems, link follows symlinks, so this check is right. */
157 if (!symbolic_link)
159 if (STAT_LIKE_LINK (source, &source_stats) != 0)
161 error (0, errno, _("accessing %s"), quote (source));
162 return 1;
165 if (S_ISLNK (source_stats.st_mode))
167 error (0, 0, _("%s: warning: making a hard link to a symbolic link\
168 is not portable"),
169 quote (source));
172 if (!hard_dir_link && S_ISDIR (source_stats.st_mode))
174 error (0, 0, _("%s: hard link not allowed for directory"),
175 quote (source));
176 return 1;
180 lstat_status = lstat (dest, &dest_stats);
181 if (lstat_status != 0 && errno != ENOENT)
183 error (0, errno, _("accessing %s"), quote (dest));
184 return 1;
187 /* If the destination is a directory or (it is a symlink to a directory
188 and the user has not specified --no-dereference), then form the
189 actual destination name by appending base_name (source) to the
190 specified destination directory. */
191 if ((lstat_status == 0
192 && S_ISDIR (dest_stats.st_mode))
193 #ifdef S_ISLNK
194 || (dereference_dest_dir_symlinks
195 && (lstat_status == 0
196 && S_ISLNK (dest_stats.st_mode)
197 && isdir (dest)))
198 #endif
201 /* Target is a directory; build the full filename. */
202 char *new_dest;
203 PATH_BASENAME_CONCAT (new_dest, dest, source);
204 dest = new_dest;
206 /* Get stats for new DEST. */
207 lstat_status = lstat (dest, &dest_stats);
208 if (lstat_status != 0 && errno != ENOENT)
210 error (0, errno, _("accessing %s"), quote (dest));
211 return 1;
215 /* If --force (-f) has been specified without --backup, then before
216 making a link ln must remove the destination file if it exists.
217 (with --backup, it just renames any existing destination file)
218 But if the source and destination are the same, don't remove
219 anything and fail right here. */
220 if (remove_existing_files
221 && lstat_status == 0
222 /* Allow `ln -sf --backup k k' to succeed in creating the
223 self-referential symlink, but don't allow the hard-linking
224 equivalent: `ln -f k k' (with or without --backup) to get
225 beyond this point, because the error message you'd get is
226 misleading. */
227 && (backup_type == none || !symlink)
228 && (!symbolic_link || stat (source, &source_stats) == 0)
229 && source_stats.st_dev == dest_stats.st_dev
230 && source_stats.st_ino == dest_stats.st_ino
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));
239 return 1;
242 if (lstat_status == 0 || lstat (dest, &dest_stats) == 0)
244 if (S_ISDIR (dest_stats.st_mode))
246 error (0, 0, _("%s: cannot overwrite directory"), quote (dest));
247 return 1;
249 if (interactive)
251 fprintf (stderr, _("%s: replace %s? "), program_name, quote (dest));
252 if (!yesno ())
253 return 0;
255 else if (!remove_existing_files && backup_type == none)
257 error (0, 0, _("%s: File exists"), quote (dest));
258 return 1;
261 if (backup_type != none)
263 char *tmp_backup = find_backup_file_name (dest, backup_type);
264 if (tmp_backup == NULL)
265 xalloc_die ();
266 dest_backup = (char *) alloca (strlen (tmp_backup) + 1);
267 strcpy (dest_backup, tmp_backup);
268 free (tmp_backup);
269 if (rename (dest, dest_backup))
271 if (errno != ENOENT)
273 error (0, errno, _("cannot backup %s"), quote (dest));
274 return 1;
276 else
277 dest_backup = NULL;
279 else
281 backup_succeeded = 1;
285 /* Try to unlink DEST even if we may have renamed it. In some unusual
286 cases (when DEST and DEST_BACKUP are hard-links that refer to the
287 same file), rename succeeds and DEST remains. If we didn't remove
288 DEST in that case, the subsequent LINKFUNC call would fail. */
289 if (unlink (dest) && errno != ENOENT)
291 error (0, errno, _("cannot remove %s"), quote (dest));
292 return 1;
295 else if (errno != ENOENT)
297 error (0, errno, _("accessing %s"), quote (dest));
298 return 1;
301 if (verbose)
303 printf ((symbolic_link
304 ? _("create symbolic link %s to %s")
305 : _("create hard link %s to %s")),
306 quote_n (0, dest), quote_n (1, source));
307 if (backup_succeeded)
308 printf (_(" (backup: %s)"), quote (dest_backup));
309 putchar ('\n');
312 if ((*linkfunc) (source, dest) == 0)
314 return 0;
317 error (0, errno,
318 (symbolic_link
319 ? _("creating symbolic link %s to %s")
320 : _("creating hard link %s to %s")),
321 quote_n (0, dest), quote_n (1, source));
323 if (dest_backup)
325 if (rename (dest_backup, dest))
326 error (0, errno, _("cannot un-backup %s"), quote (dest));
328 return 1;
331 void
332 usage (int status)
334 if (status != 0)
335 fprintf (stderr, _("Try `%s --help' for more information.\n"),
336 program_name);
337 else
339 printf (_("\
340 Usage: %s [OPTION]... TARGET [LINK_NAME]\n\
341 or: %s [OPTION]... TARGET... DIRECTORY\n\
342 or: %s [OPTION]... --target-directory=DIRECTORY TARGET...\n\
344 program_name, program_name, program_name);
345 printf (_("\
346 Create a link to the specified TARGET with optional LINK_NAME.\n\
347 If LINK_NAME is omitted, a link with the same basename as the TARGET is\n\
348 created in the current directory. When using the second form with more\n\
349 than one TARGET, the last argument must be a directory; create links\n\
350 in DIRECTORY to each TARGET. Create hard links by default, symbolic\n\
351 links with --symbolic. When creating hard links, each TARGET must exist.\n\
353 --backup[=CONTROL] make a backup of each existing destination file\n\
354 -b like --backup but does not accept an argument\n\
355 -d, -F, --directory hard link directories (super-user only)\n\
356 -f, --force remove existing destination files\n\
357 -n, --no-dereference treat destination that is a symlink to a\n\
358 directory as if it were a normal file\n\
359 -i, --interactive prompt whether to remove destinations\n\
360 -s, --symbolic make symbolic links instead of hard links\n\
361 -S, --suffix=SUFFIX override the usual backup suffix\n\
362 --target-directory=DIRECTORY specify the DIRECTORY in which to create\n\
363 the links\n\
364 -v, --verbose print name of each file before linking\n\
365 --help display this help and exit\n\
366 --version output version information and exit\n\
368 "));
369 printf (_("\
370 The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
371 The version control method may be selected via the --backup option or through\n\
372 the VERSION_CONTROL environment variable. Here are the values:\n\
374 none, off never make backups (even if --backup is given)\n\
375 numbered, t make numbered backups\n\
376 existing, nil numbered if numbered backups exist, simple otherwise\n\
377 simple, never always make simple backups\n\
378 "));
379 puts (_("\nReport bugs to <bug-fileutils@gnu.org>."));
381 exit (status);
385 main (int argc, char **argv)
387 int c;
388 int errors;
389 int make_backups = 0;
390 char *backup_suffix_string;
391 char *version_control_string = NULL;
392 char *target_directory = NULL;
393 int target_directory_specified;
394 unsigned int n_files;
395 char **file;
396 int dest_is_dir;
398 program_name = argv[0];
399 setlocale (LC_ALL, "");
400 bindtextdomain (PACKAGE, LOCALEDIR);
401 textdomain (PACKAGE);
403 atexit (close_stdout);
405 /* FIXME: consider not calling getenv for SIMPLE_BACKUP_SUFFIX unless
406 we'll actually use backup_suffix_string. */
407 backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
409 symbolic_link = remove_existing_files = interactive = verbose
410 = hard_dir_link = 0;
411 errors = 0;
413 while ((c = getopt_long (argc, argv, "bdfinsvFS:V:", long_options, NULL))
414 != -1)
416 switch (c)
418 case 0: /* Long-named option. */
419 break;
421 case 'V': /* FIXME: this is deprecated. Remove it in 2001. */
422 error (0, 0,
423 _("warning: --version-control (-V) is obsolete; support for\
424 it\nwill be removed in some future release. Use --backup=%s instead."
425 ), optarg);
426 /* Fall through. */
428 case 'b':
429 make_backups = 1;
430 if (optarg)
431 version_control_string = optarg;
432 break;
433 case 'd':
434 case 'F':
435 hard_dir_link = 1;
436 break;
437 case 'f':
438 remove_existing_files = 1;
439 interactive = 0;
440 break;
441 case 'i':
442 remove_existing_files = 0;
443 interactive = 1;
444 break;
445 case 'n':
446 dereference_dest_dir_symlinks = 0;
447 break;
448 case 's':
449 #ifdef S_ISLNK
450 symbolic_link = 1;
451 #else
452 error (1, 0, _("symbolic links are not supported on this system"));
453 #endif
454 break;
455 case TARGET_DIRECTORY_OPTION:
456 target_directory = optarg;
457 break;
458 case 'v':
459 verbose = 1;
460 break;
461 case 'S':
462 make_backups = 1;
463 backup_suffix_string = optarg;
464 break;
465 case_GETOPT_HELP_CHAR;
466 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
467 default:
468 usage (1);
469 break;
473 n_files = argc - optind;
474 file = argv + optind;
476 if (n_files == 0)
478 error (0, 0, _("missing file argument"));
479 usage (1);
482 target_directory_specified = (target_directory != NULL);
483 if (!target_directory)
484 target_directory = file[n_files - 1];
486 /* If there's only one file argument, then pretend `.' was given
487 as the second argument. */
488 if (n_files == 1)
490 static char *dummy[2];
491 dummy[0] = file[0];
492 dummy[1] = ".";
493 file = dummy;
494 n_files = 2;
495 dest_is_dir = 1;
497 else
499 dest_is_dir = isdir (target_directory);
502 if (symbolic_link)
503 linkfunc = symlink;
504 else
505 linkfunc = link;
507 if (target_directory_specified && !dest_is_dir)
509 error (0, 0, _("specified target directory, %s is not a directory"),
510 quote (target_directory));
511 usage (1);
514 if (backup_suffix_string)
515 simple_backup_suffix = xstrdup (backup_suffix_string);
517 backup_type = (make_backups
518 ? xget_version (_("backup type"), version_control_string)
519 : none);
521 if (target_directory_specified || n_files > 2)
523 unsigned int i;
524 unsigned int last_file_idx = (target_directory_specified
525 ? n_files - 1
526 : n_files - 2);
528 if (!target_directory_specified && !dest_is_dir)
529 error (1, 0,
530 _("when making multiple links, last argument must be a directory"));
531 for (i = 0; i <= last_file_idx; ++i)
532 errors += do_link (file[i], target_directory);
534 else
536 struct stat source_stats;
537 const char *source;
538 char *dest;
539 char *new_dest;
541 source = file[0];
542 dest = file[1];
544 /* When the destination is specified with a trailing slash and the
545 source exists but is not a directory, convert the user's command
546 `ln source dest/' to `ln source dest/basename(source)'. */
548 if (dest[strlen (dest) - 1] == '/'
549 && lstat (source, &source_stats) == 0
550 && !S_ISDIR (source_stats.st_mode))
552 PATH_BASENAME_CONCAT (new_dest, dest, source);
554 else
556 new_dest = dest;
559 errors = do_link (source, new_dest);
562 exit (errors != 0);