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