(do_link): Use complete strings in diagnostics so they
[platform/upstream/coreutils.git] / src / ln.c
1 /* `ln' program to create links between files.
2    Copyright (C) 86, 89, 90, 91, 1995-2000 Free Software Foundation, Inc.
3
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.
8
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.
13
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.  */
17 \f
18 /* Written by Mike Parker and David MacKenzie. */
19
20 #ifdef _AIX
21  #pragma alloca
22 #endif
23
24 #include <config.h>
25 #include <stdio.h>
26 #include <sys/types.h>
27 #include <getopt.h>
28
29 #include "system.h"
30 #include "same.h"
31 #include "backupfile.h"
32 #include "error.h"
33
34 /* The official name of this program (e.g., no `g' prefix).  */
35 #define PROGRAM_NAME "ln"
36
37 #define AUTHORS "Mike Parker and David MacKenzie"
38
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
42 {
43   TARGET_DIRECTORY_OPTION = CHAR_MAX + 1
44 };
45
46 int link ();                    /* Some systems don't declare this anywhere. */
47
48 #ifdef S_ISLNK
49 int symlink ();
50 #endif
51
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.  */
57
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
65
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.  */
68
69 #define PATH_BASENAME_CONCAT(new_dest, dest, source)                    \
70     do                                                                  \
71       {                                                                 \
72         const char *source_base;                                        \
73         char *tmp_source;                                               \
74                                                                         \
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);                           \
79                                                                         \
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)
85
86 int isdir ();
87 int yesno ();
88 void strip_trailing_slashes ();
89
90 /* The name by which the program was run, for error messages.  */
91 char *program_name;
92
93 /* FIXME: document */
94 enum backup_type backup_type;
95
96 /* A pointer to the function used to make links.  This will point to either
97    `link' or `symlink'. */
98 static int (*linkfunc) ();
99
100 /* If nonzero, make symbolic links; otherwise, make hard links.  */
101 static int symbolic_link;
102
103 /* If nonzero, ask the user before removing existing files.  */
104 static int interactive;
105
106 /* If nonzero, remove existing files unconditionally.  */
107 static int remove_existing_files;
108
109 /* If nonzero, list each file as it is moved. */
110 static int verbose;
111
112 /* If nonzero, allow the superuser to make hard links to directories. */
113 static int hard_dir_link;
114
115 /* If nonzero, and the specified destination is a symbolic link to a
116    directory, treat it just as if it were a directory.  Otherwise, the
117    command `ln --force --no-dereference file symlink-to-dir' deletes
118    symlink-to-dir before creating the new link.  */
119 static int dereference_dest_dir_symlinks = 1;
120
121 static struct option const long_options[] =
122 {
123   {"backup", optional_argument, NULL, 'b'},
124   {"directory", no_argument, NULL, 'F'},
125   {"no-dereference", no_argument, NULL, 'n'},
126   {"force", no_argument, NULL, 'f'},
127   {"interactive", no_argument, NULL, 'i'},
128   {"suffix", required_argument, NULL, 'S'},
129   {"target-directory", required_argument, NULL, TARGET_DIRECTORY_OPTION},
130   {"symbolic", no_argument, NULL, 's'},
131   {"verbose", no_argument, NULL, 'v'},
132   {"version-control", required_argument, NULL, 'V'}, /* Deprecated. FIXME. */
133   {GETOPT_HELP_OPTION_DECL},
134   {GETOPT_VERSION_OPTION_DECL},
135   {NULL, 0, NULL, 0}
136 };
137
138 /* Make a link DEST to the (usually) existing file SOURCE.
139    Symbolic links to nonexistent files are allowed.
140    If DEST is a directory, put the link to SOURCE in that directory.
141    Return 1 if there is an error, otherwise 0.  */
142
143 static int
144 do_link (const char *source, const char *dest)
145 {
146   struct stat source_stats;
147   struct stat dest_stats;
148   char *dest_backup = NULL;
149   int lstat_status;
150   int backup_succeeded = 0;
151
152   /* Use stat here instead of lstat.
153      On SVR4, link does not follow symlinks, so this check disallows
154      making hard links to symlinks that point to directories.  Big deal.
155      On other systems, link follows symlinks, so this check is right.  */
156   if (!symbolic_link)
157     {
158       if (STAT_LIKE_LINK (source, &source_stats) != 0)
159         {
160           error (0, errno, "%s", source);
161           return 1;
162         }
163
164       if (S_ISLNK (source_stats.st_mode))
165         {
166           error (0, 0, _("%s: warning: making a hard link to a symbolic link\
167  is not portable"),
168                  source);
169         }
170
171       if (!hard_dir_link && S_ISDIR (source_stats.st_mode))
172         {
173           error (0, 0, _("%s: hard link not allowed for directory"), source);
174           return 1;
175         }
176     }
177
178   lstat_status = lstat (dest, &dest_stats);
179   if (lstat_status != 0 && errno != ENOENT)
180     {
181       error (0, errno, "%s", dest);
182       return 1;
183     }
184
185   /* If the destination is a directory or (it is a symlink to a directory
186      and the user has not specified --no-dereference), then form the
187      actual destination name by appending base_name (source) to the
188      specified destination directory.  */
189   if ((lstat_status == 0
190        && S_ISDIR (dest_stats.st_mode))
191 #ifdef S_ISLNK
192       || (dereference_dest_dir_symlinks
193           && (lstat_status == 0
194               && S_ISLNK (dest_stats.st_mode)
195               && isdir (dest)))
196 #endif
197      )
198     {
199       /* Target is a directory; build the full filename. */
200       char *new_dest;
201       PATH_BASENAME_CONCAT (new_dest, dest, source);
202       dest = new_dest;
203
204       /* Get stats for new DEST.  */
205       lstat_status = lstat (dest, &dest_stats);
206       if (lstat_status != 0 && errno != ENOENT)
207         {
208           error (0, errno, "%s", dest);
209           return 1;
210         }
211     }
212
213   /* If --force (-f) has been specified without --backup, then before
214      making a link ln must remove the destination file if it exists.
215      (with --backup, it just renames any existing destination file)
216      But if the source and destination are the same, don't remove
217      anything and fail right here.  */
218   if (remove_existing_files
219       && lstat_status == 0
220       /* Allow `ln -sf --backup k k' to succeed in creating the
221          self-referential symlink, but don't allow the hard-linking
222          equivalent: `ln -f k k' (with or without --backup) to get
223          beyond this point, because the error message you'd get is
224          misleading.  */
225       && (backup_type == none || !symlink)
226       && (!symbolic_link || stat (source, &source_stats) == 0)
227       && source_stats.st_dev == dest_stats.st_dev
228       && source_stats.st_ino == dest_stats.st_ino
229       /* The following detects whether removing DEST will also remove
230          SOURCE.  If the file has only one link then both are surely
231          the same link.  Otherwise check whether they point to the same
232          name in the same directory.  */
233       && (source_stats.st_nlink == 1 || same_name (source, dest)))
234     {
235       error (0, 0, _("`%s' and `%s' are the same file"), source, dest);
236       return 1;
237     }
238
239   if (lstat_status == 0 || lstat (dest, &dest_stats) == 0)
240     {
241       if (S_ISDIR (dest_stats.st_mode))
242         {
243           error (0, 0, _("%s: cannot overwrite directory"), dest);
244           return 1;
245         }
246       if (interactive)
247         {
248           fprintf (stderr, _("%s: replace `%s'? "), program_name, dest);
249           if (!yesno ())
250             return 0;
251         }
252       else if (!remove_existing_files && backup_type == none)
253         {
254           error (0, 0, _("%s: File exists"), dest);
255           return 1;
256         }
257
258       if (backup_type != none)
259         {
260           char *tmp_backup = find_backup_file_name (dest, backup_type);
261           if (tmp_backup == NULL)
262             error (1, 0, _("virtual memory exhausted"));
263           dest_backup = (char *) alloca (strlen (tmp_backup) + 1);
264           strcpy (dest_backup, tmp_backup);
265           free (tmp_backup);
266           if (rename (dest, dest_backup))
267             {
268               if (errno != ENOENT)
269                 {
270                   error (0, errno, _("cannot backup `%s'"), dest);
271                   return 1;
272                 }
273               else
274                 dest_backup = NULL;
275             }
276           else
277             {
278               backup_succeeded = 1;
279             }
280         }
281
282       /* Try to unlink DEST even if we may have renamed it.  In some unusual
283          cases (when DEST and DEST_BACKUP are hard-links that refer to the
284          same file), rename succeeds and DEST remains.  If we didn't remove
285          DEST in that case, the subsequent LINKFUNC call would fail.  */
286       if (unlink (dest) && errno != ENOENT)
287         {
288           error (0, errno, _("cannot remove `%s'"), dest);
289           return 1;
290         }
291     }
292   else if (errno != ENOENT)
293     {
294       error (0, errno, "%s", dest);
295       return 1;
296     }
297
298   if (verbose)
299     {
300       printf ((symbolic_link
301                ? _("create symbolic link `%s' to `%s'")
302                : _("create hard link `%s' to `%s'")),
303               dest, source);
304       if (backup_succeeded)
305         printf (_(" (backup: %s)"), dest_backup);
306       putchar ('\n');
307     }
308
309   if ((*linkfunc) (source, dest) == 0)
310     {
311       return 0;
312     }
313
314   error (0, errno,
315          (symbolic_link
316           ? _("create symbolic link `%s' to `%s'")
317           : _("create hard link `%s' to `%s'")),
318          dest, source);
319
320   if (dest_backup)
321     {
322       if (rename (dest_backup, dest))
323         error (0, errno, _("cannot un-backup `%s'"), dest);
324     }
325   return 1;
326 }
327
328 void
329 usage (int status)
330 {
331   if (status != 0)
332     fprintf (stderr, _("Try `%s --help' for more information.\n"),
333              program_name);
334   else
335     {
336       printf (_("\
337 Usage: %s [OPTION]... TARGET [LINK_NAME]\n\
338   or:  %s [OPTION]... TARGET... DIRECTORY\n\
339   or:  %s [OPTION]... --target-directory=DIRECTORY TARGET...\n\
340 "),
341               program_name, program_name, program_name);
342       printf (_("\
343 Create a link to the specified TARGET with optional LINK_NAME.\n\
344 If LINK_NAME is omitted, a link with the same basename as the TARGET is\n\
345 created in the current directory.  When using the second form with more\n\
346 than one TARGET, the last argument must be a directory;  create links\n\
347 in DIRECTORY to each TARGET.  Create hard links by default, symbolic\n\
348 links with --symbolic.  When creating hard links, each TARGET must exist.\n\
349 \n\
350       --backup[=CONTROL]      make a backup of each existing destination file\n\
351   -b                          like --backup but does not accept an argument\n\
352   -d, -F, --directory         hard link directories (super-user only)\n\
353   -f, --force                 remove existing destination files\n\
354   -n, --no-dereference        treat destination that is a symlink to a\n\
355                                 directory as if it were a normal file\n\
356   -i, --interactive           prompt whether to remove destinations\n\
357   -s, --symbolic              make symbolic links instead of hard links\n\
358   -S, --suffix=SUFFIX         override the usual backup suffix\n\
359       --target-directory=DIRECTORY  specify the DIRECTORY in which to create\n\
360                                 the links\n\
361   -v, --verbose               print name of each file before linking\n\
362       --help                  display this help and exit\n\
363       --version               output version information and exit\n\
364 \n\
365 "));
366       printf (_("\
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\
370 \n\
371   none, off       never make backups (even if --backup is given)\n\
372   numbered, t     make numbered backups\n\
373   existing, nil   numbered if numbered backups exist, simple otherwise\n\
374   simple, never   always make simple backups\n\
375 "));
376       puts (_("\nReport bugs to <bug-fileutils@gnu.org>."));
377     }
378   exit (status);
379 }
380
381 int
382 main (int argc, char **argv)
383 {
384   int c;
385   int errors;
386   int make_backups = 0;
387   char *backup_suffix_string;
388   char *version_control_string = NULL;
389   char *target_directory = NULL;
390   int target_directory_specified;
391   unsigned int n_files;
392   char **file;
393   int dest_is_dir;
394
395   program_name = argv[0];
396   setlocale (LC_ALL, "");
397   bindtextdomain (PACKAGE, LOCALEDIR);
398   textdomain (PACKAGE);
399
400   atexit (close_stdout);
401
402   /* FIXME: consider not calling getenv for SIMPLE_BACKUP_SUFFIX unless
403      we'll actually use backup_suffix_string.  */
404   backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
405
406   symbolic_link = remove_existing_files = interactive = verbose
407     = hard_dir_link = 0;
408   errors = 0;
409
410   while ((c = getopt_long (argc, argv, "bdfinsvFS:V:", long_options, NULL))
411          != -1)
412     {
413       switch (c)
414         {
415         case 0:                 /* Long-named option. */
416           break;
417
418         case 'V':  /* FIXME: this is deprecated.  Remove it in 2001.  */
419           error (0, 0,
420                  _("warning: --version-control (-V) is obsolete;  support for\
421  it\nwill be removed in some future release.  Use --backup=%s instead."
422                    ), optarg);
423           /* Fall through.  */
424
425         case 'b':
426           make_backups = 1;
427           if (optarg)
428             version_control_string = optarg;
429           break;
430         case 'd':
431         case 'F':
432           hard_dir_link = 1;
433           break;
434         case 'f':
435           remove_existing_files = 1;
436           interactive = 0;
437           break;
438         case 'i':
439           remove_existing_files = 0;
440           interactive = 1;
441           break;
442         case 'n':
443           dereference_dest_dir_symlinks = 0;
444           break;
445         case 's':
446 #ifdef S_ISLNK
447           symbolic_link = 1;
448 #else
449           error (1, 0, _("symbolic links are not supported on this system"));
450 #endif
451           break;
452         case TARGET_DIRECTORY_OPTION:
453           target_directory = optarg;
454           break;
455         case 'v':
456           verbose = 1;
457           break;
458         case 'S':
459           make_backups = 1;
460           backup_suffix_string = optarg;
461           break;
462         case_GETOPT_HELP_CHAR;
463         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
464         default:
465           usage (1);
466           break;
467         }
468     }
469
470   n_files = argc - optind;
471   file = argv + optind;
472
473   if (n_files == 0)
474     {
475       error (0, 0, _("missing file argument"));
476       usage (1);
477     }
478
479   target_directory_specified = (target_directory != NULL);
480   if (!target_directory)
481     target_directory = file[n_files - 1];
482
483   /* If there's only one file argument, then pretend `.' was given
484      as the second argument.  */
485   if (n_files == 1)
486     {
487       static char *dummy[2];
488       dummy[0] = file[0];
489       dummy[1] = ".";
490       file = dummy;
491       n_files = 2;
492       dest_is_dir = 1;
493     }
494   else
495     {
496       dest_is_dir = isdir (target_directory);
497     }
498
499   if (symbolic_link)
500     linkfunc = symlink;
501   else
502     linkfunc = link;
503
504   if (target_directory_specified && !dest_is_dir)
505     {
506       error (0, 0, _("specified target directory, `%s' is not a directory"),
507              target_directory);
508       usage (1);
509     }
510
511   backup_type = (make_backups
512                  ? xget_version (_("backup type"), version_control_string)
513                  : none);
514
515   if (target_directory_specified || n_files > 2)
516     {
517       int i;
518       unsigned int last_file_idx = (target_directory_specified
519                                     ? n_files - 1
520                                     : n_files - 2);
521
522       if (!target_directory_specified && !dest_is_dir)
523         error (1, 0,
524            _("when making multiple links, last argument must be a directory"));
525       for (i = 0; i <= last_file_idx; ++i)
526         errors += do_link (file[i], target_directory);
527     }
528   else
529     {
530       struct stat source_stats;
531       const char *source;
532       char *dest;
533       char *new_dest;
534
535       source = file[0];
536       dest = file[1];
537
538       /* When the destination is specified with a trailing slash and the
539          source exists but is not a directory, convert the user's command
540          `ln source dest/' to `ln source dest/basename(source)'.  */
541
542       if (dest[strlen (dest) - 1] == '/'
543           && lstat (source, &source_stats) == 0
544           && !S_ISDIR (source_stats.st_mode))
545         {
546           PATH_BASENAME_CONCAT (new_dest, dest, source);
547         }
548       else
549         {
550           new_dest = dest;
551         }
552
553       errors = do_link (source, new_dest);
554     }
555
556   exit (errors != 0);
557 }