Declare new global, backup_type.
[platform/upstream/coreutils.git] / src / ln.c
1 /* `ln' program to create links between files.
2    Copyright (C) 86, 89, 90, 91, 95, 96, 97, 1998 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 "backupfile.h"
31 #include "closeout.h"
32 #include "error.h"
33
34 int link ();                    /* Some systems don't declare this anywhere. */
35
36 #ifdef S_ISLNK
37 int symlink ();
38 #endif
39
40 /* Construct a string NEW_DEST by concatenating DEST, a slash, and
41    basename(SOURCE) in alloca'd memory.  Don't modify DEST or SOURCE.  */
42
43 #define PATH_BASENAME_CONCAT(new_dest, dest, source)                    \
44     do                                                                  \
45       {                                                                 \
46         char *source_base;                                              \
47         char *tmp_source;                                               \
48                                                                         \
49         tmp_source = (char *) alloca (strlen ((source)) + 1);           \
50         strcpy (tmp_source, (source));                                  \
51         strip_trailing_slashes (tmp_source);                            \
52         source_base = base_name (tmp_source);                           \
53                                                                         \
54         (new_dest) = (char *) alloca (strlen ((dest)) + 1               \
55                                       + strlen (source_base) + 1);      \
56         stpcpy (stpcpy (stpcpy ((new_dest), (dest)), "/"), source_base);\
57       }                                                                 \
58     while (0)
59
60 char *base_name ();
61 char *dirname ();
62 enum backup_type get_version ();
63 int isdir ();
64 int yesno ();
65 void strip_trailing_slashes ();
66
67 /* The name by which the program was run, for error messages.  */
68 char *program_name;
69
70 /* FIXME: document */
71 enum backup_type backup_type;
72
73 /* A pointer to the function used to make links.  This will point to either
74    `link' or `symlink'. */
75 static int (*linkfunc) ();
76
77 /* If nonzero, make symbolic links; otherwise, make hard links.  */
78 static int symbolic_link;
79
80 /* A string describing type of link to make.  For use in verbose
81    diagnostics and in error messages.  */
82 static const char *link_type_string;
83
84 /* If nonzero, ask the user before removing existing files.  */
85 static int interactive;
86
87 /* If nonzero, remove existing files unconditionally.  */
88 static int remove_existing_files;
89
90 /* If nonzero, list each file as it is moved. */
91 static int verbose;
92
93 /* If nonzero, allow the superuser to make hard links to directories. */
94 static int hard_dir_link;
95
96 /* If nonzero, and the specified destination is a symbolic link to a
97    directory, treat it just as if it were a directory.  Otherwise, the
98    command `ln --force --no-dereference file symlink-to-dir' deletes
99    symlink-to-dir before creating the new link.  */
100 static int dereference_dest_dir_symlinks = 1;
101
102 /* If nonzero, display usage information and exit.  */
103 static int show_help;
104
105 /* If nonzero, print the version on standard output and exit.  */
106 static int show_version;
107
108 static struct option const long_options[] =
109 {
110   {"backup", no_argument, NULL, 'b'},
111   {"directory", no_argument, &hard_dir_link, 1},
112   {"no-dereference", no_argument, NULL, 'n'},
113   {"force", no_argument, NULL, 'f'},
114   {"interactive", no_argument, NULL, 'i'},
115   {"suffix", required_argument, NULL, 'S'},
116   {"symbolic", no_argument, &symbolic_link, 1},
117   {"verbose", no_argument, &verbose, 1},
118   {"version-control", required_argument, NULL, 'V'},
119   {"help", no_argument, &show_help, 1},
120   {"version", no_argument, &show_version, 1},
121   {NULL, 0, NULL, 0}
122 };
123
124 /* Return nonzero if SOURCE and DEST point to the same name in the same
125    directory.  */
126
127 static int
128 same_name (const char *source, const char *dest)
129 {
130   struct stat source_dir_stats;
131   struct stat dest_dir_stats;
132   char *source_dirname, *dest_dirname;
133
134   source_dirname = dirname (source);
135   dest_dirname = dirname (dest);
136   if (source_dirname == NULL || dest_dirname == NULL)
137     error (1, 0, _("virtual memory exhausted"));
138
139   if (stat (source_dirname, &source_dir_stats))
140     {
141       /* Shouldn't happen.  */
142       error (1, errno, "%s", source_dirname);
143     }
144
145   if (stat (dest_dirname, &dest_dir_stats))
146     {
147       /* Shouldn't happen.  */
148       error (1, errno, "%s", dest_dirname);
149     }
150
151   free (source_dirname);
152   free (dest_dirname);
153
154   return (source_dir_stats.st_dev == dest_dir_stats.st_dev
155           && source_dir_stats.st_ino == dest_dir_stats.st_ino
156           && STREQ (base_name (source), base_name (dest)));
157 }
158
159 /* Make a link DEST to the (usually) existing file SOURCE.
160    Symbolic links to nonexistent files are allowed.
161    If DEST is a directory, put the link to SOURCE in that directory.
162    Return 1 if there is an error, otherwise 0.  */
163
164 static int
165 do_link (const char *source, const char *dest)
166 {
167   struct stat source_stats;
168   struct stat dest_stats;
169   char *dest_backup = NULL;
170   int lstat_status;
171
172   /* Use stat here instead of lstat.
173      On SVR4, link does not follow symlinks, so this check disallows
174      making hard links to symlinks that point to directories.  Big deal.
175      On other systems, link follows symlinks, so this check is right.  */
176   if (!symbolic_link)
177     {
178       if (stat (source, &source_stats) != 0)
179         {
180           error (0, errno, "%s", source);
181           return 1;
182         }
183       if (!hard_dir_link && S_ISDIR (source_stats.st_mode))
184         {
185           error (0, 0, _("%s: hard link not allowed for directory"), source);
186           return 1;
187         }
188     }
189
190   lstat_status = lstat (dest, &dest_stats);
191   if (lstat_status != 0 && errno != ENOENT)
192     {
193       error (0, errno, "%s", dest);
194       return 1;
195     }
196
197   /* If the destination is a directory or (it is a symlink to a directory
198      and the user has not specified --no-dereference), then form the
199      actual destination name by appending base_name (source) to the
200      specified destination directory.  */
201   if ((lstat_status == 0
202        && S_ISDIR (dest_stats.st_mode))
203 #ifdef S_ISLNK
204       || (dereference_dest_dir_symlinks
205           && (lstat_status == 0
206               && S_ISLNK (dest_stats.st_mode)
207               && isdir (dest)))
208 #endif
209      )
210     {
211       /* Target is a directory; build the full filename. */
212       char *new_dest;
213       PATH_BASENAME_CONCAT (new_dest, dest, source);
214       dest = new_dest;
215
216       /* Get stats for new DEST.  */
217       lstat_status = lstat (dest, &dest_stats);
218       if (lstat_status != 0 && errno != ENOENT)
219         {
220           error (0, errno, "%s", dest);
221           return 1;
222         }
223     }
224
225   /* If --force (-f) has been specified without --backup, then before
226      making a link ln must remove the destination file if it exists.
227      (with --backup, it just renames any existing destination file)
228      But if the source and destination are the same, don't remove
229      anything and fail right here.  */
230   if (remove_existing_files
231       && lstat_status == 0
232       /* Allow `ln -sf --backup k k' to succeed in creating the
233          self-referential symlink, but don't allow the hard-linking
234          equivalent: `ln -f k k' (with or without --backup) to get
235          beyond this point, because the error message you'd get is
236          misleading.  */
237       && (backup_type == none || !symlink)
238       && (!symlink || stat (source, &source_stats) == 0)
239       && source_stats.st_dev == dest_stats.st_dev
240       && source_stats.st_ino == dest_stats.st_ino
241       /* The following detects whether removing DEST will also remove
242          SOURCE.  If the file has only one link then both are surely
243          the same link.  Otherwise check whether they point to the same
244          name in the same directory.  */
245       && (source_stats.st_nlink == 1 || same_name (source, dest)))
246     {
247       error (0, 0, _("`%s' and `%s' are the same file"), source, dest);
248       return 1;
249     }
250
251   if (lstat_status == 0 || lstat (dest, &dest_stats) == 0)
252     {
253       if (S_ISDIR (dest_stats.st_mode))
254         {
255           error (0, 0, _("%s: cannot overwrite directory"), dest);
256           return 1;
257         }
258       if (interactive)
259         {
260           fprintf (stderr, _("%s: replace `%s'? "), program_name, dest);
261           if (!yesno ())
262             return 0;
263         }
264       else if (!remove_existing_files && backup_type == none)
265         {
266           error (0, 0, _("%s: File exists"), dest);
267           return 1;
268         }
269
270       if (backup_type != none)
271         {
272           char *tmp_backup = find_backup_file_name (dest, backup_type);
273           if (tmp_backup == NULL)
274             error (1, 0, _("virtual memory exhausted"));
275           dest_backup = (char *) alloca (strlen (tmp_backup) + 1);
276           strcpy (dest_backup, tmp_backup);
277           free (tmp_backup);
278           if (rename (dest, dest_backup))
279             {
280               if (errno != ENOENT)
281                 {
282                   error (0, errno, _("cannot backup `%s'"), dest);
283                   return 1;
284                 }
285               else
286                 dest_backup = NULL;
287             }
288         }
289       else if (unlink (dest) && errno != ENOENT)
290         {
291           error (0, errno, _("cannot remove `%s'"), dest);
292           return 1;
293         }
294     }
295   else if (errno != ENOENT)
296     {
297       error (0, errno, "%s", dest);
298       return 1;
299     }
300
301   if (verbose)
302     printf (_("create %s %s to %s\n"), link_type_string, dest, source);
303
304   if ((*linkfunc) (source, dest) == 0)
305     {
306       return 0;
307     }
308
309   error (0, errno, _("cannot create %s `%s' to `%s'"), link_type_string,
310          dest, source);
311
312   if (dest_backup)
313     {
314       if (rename (dest_backup, dest))
315         error (0, errno, _("cannot un-backup `%s'"), dest);
316     }
317   return 1;
318 }
319
320 static void
321 usage (int status)
322 {
323   if (status != 0)
324     fprintf (stderr, _("Try `%s --help' for more information.\n"),
325              program_name);
326   else
327     {
328       printf (_("\
329 Usage: %s [OPTION]... SOURCE [DEST]\n\
330   or:  %s [OPTION]... SOURCE... DIRECTORY\n\
331 "),
332               program_name, program_name);
333       printf (_("\
334 Link SOURCE to DEST (. by default), or multiple SOURCE(s) to DIRECTORY.\n\
335 Makes hard links by default, symbolic links with -s.\n\
336 \n\
337   -b, --backup                 make backups for removed files\n\
338   -d, -F, --directory          hard link directories (super-user only)\n\
339   -f, --force                  remove existing destinations\n\
340   -n, --no-dereference         treat destination that is a symlink to a\n\
341                                  directory as if it were a normal file\n\
342   -i, --interactive            prompt whether to remove destinations\n\
343   -s, --symbolic               make symbolic links instead of hard links\n\
344   -S, --suffix=SUFFIX          override the usual backup suffix\n\
345   -v, --verbose                print name of each file before linking\n\
346   -V, --version-control=WORD   override the usual version control\n\
347       --help                   display this help and exit\n\
348       --version                output version information and exit\n\
349 \n\
350 "));
351       printf (_("\
352 The backup suffix is ~, unless set with SIMPLE_BACKUP_SUFFIX.  The\n\
353 version control may be set with VERSION_CONTROL, values are:\n\
354 \n\
355   t, numbered     make numbered backups\n\
356   nil, existing   numbered if numbered backups exist, simple otherwise\n\
357   never, simple   always make simple backups\n\
358 "));
359       puts (_("\nReport bugs to <fileutils-bugs@gnu.org>."));
360       close_stdout ();
361     }
362   exit (status);
363 }
364
365 int
366 main (int argc, char **argv)
367 {
368   int c;
369   int errors;
370   int make_backups = 0;
371   char *version;
372
373   program_name = argv[0];
374   setlocale (LC_ALL, "");
375   bindtextdomain (PACKAGE, LOCALEDIR);
376   textdomain (PACKAGE);
377
378   version = getenv ("SIMPLE_BACKUP_SUFFIX");
379   if (version)
380     simple_backup_suffix = version;
381   version = getenv ("VERSION_CONTROL");
382
383   symbolic_link = remove_existing_files = interactive = verbose
384     = hard_dir_link = 0;
385   errors = 0;
386
387   while ((c = getopt_long (argc, argv, "bdfinsvFS:V:", long_options, NULL))
388          != -1)
389     {
390       switch (c)
391         {
392         case 0:                 /* Long-named option. */
393           break;
394         case 'b':
395           make_backups = 1;
396           break;
397         case 'd':
398         case 'F':
399           hard_dir_link = 1;
400           break;
401         case 'f':
402           remove_existing_files = 1;
403           interactive = 0;
404           break;
405         case 'i':
406           remove_existing_files = 0;
407           interactive = 1;
408           break;
409         case 'n':
410           dereference_dest_dir_symlinks = 0;
411           break;
412         case 's':
413 #ifdef S_ISLNK
414           symbolic_link = 1;
415 #else
416           error (1, 0, _("symbolic links are not supported on this system"));
417 #endif
418           break;
419         case 'v':
420           verbose = 1;
421           break;
422         case 'S':
423           simple_backup_suffix = optarg;
424           break;
425         case 'V':
426           version = optarg;
427           break;
428         default:
429           usage (1);
430           break;
431         }
432     }
433
434   if (show_version)
435     {
436       printf ("ln (%s) %s\n", GNU_PACKAGE, VERSION);
437       close_stdout ();
438       exit (0);
439     }
440
441   if (show_help)
442     usage (0);
443
444   if (optind == argc)
445     {
446       error (0, 0, _("missing file argument"));
447       usage (1);
448     }
449
450   backup_type = (make_backups ? get_version (version) : none);
451
452 #ifdef S_ISLNK
453   if (symbolic_link)
454     {
455       linkfunc = symlink;
456       link_type_string = _("symbolic link");
457     }
458   else
459     {
460       linkfunc = link;
461       link_type_string = _("hard link");
462     }
463 #else
464   link_type_string = _("link");
465 #endif
466
467   if (optind == argc - 1)
468     errors = do_link (argv[optind], ".");
469   else if (optind == argc - 2)
470     {
471       struct stat source_stats;
472       char *source;
473       char *dest;
474       char *new_dest;
475
476       source = argv[optind];
477       dest = argv[optind + 1];
478
479       /* When the destination is specified with a trailing slash and the
480          source exists but is not a directory, convert the user's command
481          `ln source dest/' to `ln source dest/basename(source)'.  */
482
483       if (dest[strlen (dest) - 1] == '/'
484           && lstat (source, &source_stats) == 0
485           && !S_ISDIR (source_stats.st_mode))
486         {
487           PATH_BASENAME_CONCAT (new_dest, dest, source);
488         }
489       else
490         {
491           new_dest = dest;
492         }
493
494       errors = do_link (source, new_dest);
495     }
496   else
497     {
498       char *to;
499
500       to = argv[argc - 1];
501       if (!isdir (to))
502         error (1, 0, _("when making multiple links, last argument must be a directory"));
503       for (; optind < argc - 1; ++optind)
504         errors += do_link (argv[optind], to);
505     }
506
507   if (verbose)
508     close_stdout ();
509   exit (errors != 0);
510 }