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