(main): Test for `missing argument' before computing n_files.
[platform/upstream/coreutils.git] / src / ln.c
1 /* `ln' program to create links between files.
2    Copyright (C) 86, 89, 90, 91, 1995-2003 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 "dirname.h"
33 #include "error.h"
34 #include "quote.h"
35
36 /* The official name of this program (e.g., no `g' prefix).  */
37 #define PROGRAM_NAME "ln"
38
39 #define AUTHORS N_ ("Mike Parker and David MacKenzie")
40
41 /* For long options that have no equivalent short option, use a
42    non-character as a pseudo short option, starting with CHAR_MAX + 1.  */
43 enum
44 {
45   TARGET_DIRECTORY_OPTION = CHAR_MAX + 1
46 };
47
48 int link ();                    /* Some systems don't declare this anywhere. */
49
50 #ifdef S_ISLNK
51 int symlink ();
52 #endif
53
54 /* In being careful not even to try to make hard links to directories,
55    we have to know whether link(2) follows symlinks.  If it does, then
56    we have to *stat* the `source' to see if the resulting link would be
57    to a directory.  Otherwise, we have to use *lstat* so that we allow
58    users to make hard links to symlinks-that-point-to-directories.  */
59
60 #if LINK_FOLLOWS_SYMLINKS
61 # define STAT_LIKE_LINK(File, Stat_buf) \
62   stat (File, Stat_buf)
63 #else
64 # define STAT_LIKE_LINK(File, Stat_buf) \
65   lstat (File, Stat_buf)
66 #endif
67
68 /* Construct a string NEW_DEST by concatenating DEST, a slash, and
69    basename(SOURCE) in alloca'd memory.  Don't modify DEST or SOURCE.  */
70
71 #define PATH_BASENAME_CONCAT(new_dest, dest, source)                    \
72     do                                                                  \
73       {                                                                 \
74         const char *source_base;                                        \
75         char *tmp_source;                                               \
76                                                                         \
77         tmp_source = (char *) alloca (strlen ((source)) + 1);           \
78         strcpy (tmp_source, (source));                                  \
79         strip_trailing_slashes (tmp_source);                            \
80         source_base = base_name (tmp_source);                           \
81                                                                         \
82         (new_dest) = (char *) alloca (strlen ((dest)) + 1               \
83                                       + strlen (source_base) + 1);      \
84         stpcpy (stpcpy (stpcpy ((new_dest), (dest)), "/"), source_base);\
85       }                                                                 \
86     while (0)
87
88 int isdir ();
89 int yesno ();
90
91 /* The name by which the program was run, for error messages.  */
92 char *program_name;
93
94 /* FIXME: document */
95 enum backup_type backup_type;
96
97 /* A pointer to the function used to make links.  This will point to either
98    `link' or `symlink'. */
99 static int (*linkfunc) ();
100
101 /* If nonzero, make symbolic links; otherwise, make hard links.  */
102 static int symbolic_link;
103
104 /* If nonzero, ask the user before removing existing files.  */
105 static int interactive;
106
107 /* If nonzero, remove existing files unconditionally.  */
108 static int remove_existing_files;
109
110 /* If nonzero, list each file as it is moved. */
111 static int verbose;
112
113 /* If nonzero, allow the superuser to make hard links to directories. */
114 static int hard_dir_link;
115
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;
121
122 static struct option const long_options[] =
123 {
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}
137 };
138
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.  */
143
144 static int
145 do_link (const char *source, const char *dest)
146 {
147   struct stat source_stats;
148   struct stat dest_stats;
149   char *dest_backup = NULL;
150   int lstat_status;
151   int backup_succeeded = 0;
152
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)
158     {
159       if (STAT_LIKE_LINK (source, &source_stats) != 0)
160         {
161           error (0, errno, _("accessing %s"), quote (source));
162           return 1;
163         }
164
165       if (S_ISLNK (source_stats.st_mode))
166         {
167           error (0, 0, _("%s: warning: making a hard link to a symbolic link\
168  is not portable"),
169                  quote (source));
170         }
171
172       if (!hard_dir_link && S_ISDIR (source_stats.st_mode))
173         {
174           error (0, 0, _("%s: hard link not allowed for directory"),
175                  quote (source));
176           return 1;
177         }
178     }
179
180   lstat_status = lstat (dest, &dest_stats);
181   if (lstat_status != 0 && errno != ENOENT)
182     {
183       error (0, errno, _("accessing %s"), quote (dest));
184       return 1;
185     }
186
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
199      )
200     {
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;
205
206       /* Get stats for new DEST.  */
207       lstat_status = lstat (dest, &dest_stats);
208       if (lstat_status != 0 && errno != ENOENT)
209         {
210           error (0, errno, _("accessing %s"), quote (dest));
211           return 1;
212         }
213     }
214
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 || !symbolic_link)
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)))
236     {
237       error (0, 0, _("%s and %s are the same file"),
238              quote_n (0, source), quote_n (1, dest));
239       return 1;
240     }
241
242   if (lstat_status == 0 || lstat (dest, &dest_stats) == 0)
243     {
244       if (S_ISDIR (dest_stats.st_mode))
245         {
246           error (0, 0, _("%s: cannot overwrite directory"), quote (dest));
247           return 1;
248         }
249       if (interactive)
250         {
251           fprintf (stderr, _("%s: replace %s? "), program_name, quote (dest));
252           if (!yesno ())
253             return 0;
254         }
255       else if (!remove_existing_files && backup_type == none)
256         {
257           error (0, 0, _("%s: File exists"), quote (dest));
258           return 1;
259         }
260
261       if (backup_type != none)
262         {
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))
270             {
271               if (errno != ENOENT)
272                 {
273                   error (0, errno, _("cannot backup %s"), quote (dest));
274                   return 1;
275                 }
276               else
277                 dest_backup = NULL;
278             }
279           else
280             {
281               backup_succeeded = 1;
282             }
283         }
284
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)
290         {
291           error (0, errno, _("cannot remove %s"), quote (dest));
292           return 1;
293         }
294     }
295   else if (errno != ENOENT)
296     {
297       error (0, errno, _("accessing %s"), quote (dest));
298       return 1;
299     }
300
301   if (verbose)
302     {
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');
310     }
311
312   if ((*linkfunc) (source, dest) == 0)
313     {
314       return 0;
315     }
316
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));
322
323   if (dest_backup)
324     {
325       if (rename (dest_backup, dest))
326         error (0, errno, _("cannot un-backup %s"), quote (dest));
327     }
328   return 1;
329 }
330
331 void
332 usage (int status)
333 {
334   if (status != 0)
335     fprintf (stderr, _("Try `%s --help' for more information.\n"),
336              program_name);
337   else
338     {
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\
343 "),
344               program_name, program_name, program_name);
345       fputs (_("\
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\
352 \n\
353 "), stdout);
354       fputs (_("\
355 Mandatory arguments to long options are mandatory for short options too.\n\
356 "), stdout);
357       fputs (_("\
358       --backup[=CONTROL]      make a backup of each existing destination file\n\
359   -b                          like --backup but does not accept an argument\n\
360   -d, -F, --directory         hard link directories (super-user only)\n\
361   -f, --force                 remove existing destination files\n\
362 "), stdout);
363       fputs (_("\
364   -n, --no-dereference        treat destination that is a symlink to a\n\
365                                 directory as if it were a normal file\n\
366   -i, --interactive           prompt whether to remove destinations\n\
367   -s, --symbolic              make symbolic links instead of hard links\n\
368 "), stdout);
369       fputs (_("\
370   -S, --suffix=SUFFIX         override the usual backup suffix\n\
371       --target-directory=DIRECTORY  specify the DIRECTORY in which to create\n\
372                                 the links\n\
373   -v, --verbose               print name of each file before linking\n\
374 "), stdout);
375       fputs (HELP_OPTION_DESCRIPTION, stdout);
376       fputs (VERSION_OPTION_DESCRIPTION, stdout);
377       fputs (_("\
378 \n\
379 The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
380 The version control method may be selected via the --backup option or through\n\
381 the VERSION_CONTROL environment variable.  Here are the values:\n\
382 \n\
383 "), stdout);
384       fputs (_("\
385   none, off       never make backups (even if --backup is given)\n\
386   numbered, t     make numbered backups\n\
387   existing, nil   numbered if numbered backups exist, simple otherwise\n\
388   simple, never   always make simple backups\n\
389 "), stdout);
390       printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
391     }
392   exit (status);
393 }
394
395 int
396 main (int argc, char **argv)
397 {
398   int c;
399   int errors;
400   int make_backups = 0;
401   char *backup_suffix_string;
402   char *version_control_string = NULL;
403   char *target_directory = NULL;
404   int target_directory_specified;
405   unsigned int n_files;
406   char **file;
407   int dest_is_dir;
408
409   program_name = argv[0];
410   setlocale (LC_ALL, "");
411   bindtextdomain (PACKAGE, LOCALEDIR);
412   textdomain (PACKAGE);
413
414   atexit (close_stdout);
415
416   /* FIXME: consider not calling getenv for SIMPLE_BACKUP_SUFFIX unless
417      we'll actually use backup_suffix_string.  */
418   backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
419
420   symbolic_link = remove_existing_files = interactive = verbose
421     = hard_dir_link = 0;
422   errors = 0;
423
424   while ((c = getopt_long (argc, argv, "bdfinsvFS:V:", long_options, NULL))
425          != -1)
426     {
427       switch (c)
428         {
429         case 0:                 /* Long-named option. */
430           break;
431
432         case 'V':  /* FIXME: this is deprecated.  Remove it in 2001.  */
433           error (0, 0,
434                  _("warning: --version-control (-V) is obsolete;  support for\
435  it\nwill be removed in some future release.  Use --backup=%s instead."
436                    ), optarg);
437           /* Fall through.  */
438
439         case 'b':
440           make_backups = 1;
441           if (optarg)
442             version_control_string = optarg;
443           break;
444         case 'd':
445         case 'F':
446           hard_dir_link = 1;
447           break;
448         case 'f':
449           remove_existing_files = 1;
450           interactive = 0;
451           break;
452         case 'i':
453           remove_existing_files = 0;
454           interactive = 1;
455           break;
456         case 'n':
457           dereference_dest_dir_symlinks = 0;
458           break;
459         case 's':
460 #ifdef S_ISLNK
461           symbolic_link = 1;
462 #else
463           error (EXIT_FAILURE, 0,
464                  _("symbolic links are not supported on this system"));
465 #endif
466           break;
467         case TARGET_DIRECTORY_OPTION:
468           target_directory = optarg;
469           break;
470         case 'v':
471           verbose = 1;
472           break;
473         case 'S':
474           make_backups = 1;
475           backup_suffix_string = optarg;
476           break;
477         case_GETOPT_HELP_CHAR;
478         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
479         default:
480           usage (EXIT_FAILURE);
481           break;
482         }
483     }
484
485   if (argc <= optind)
486     {
487       error (0, 0, _("missing file argument"));
488       usage (EXIT_FAILURE);
489     }
490
491   n_files = argc - optind;
492   file = argv + optind;
493
494   target_directory_specified = (target_directory != NULL);
495   if (!target_directory)
496     target_directory = file[n_files - 1];
497
498   /* If target directory is not specified, and there's only one
499      file argument, then pretend `.' was given as the second argument.  */
500   if (!target_directory_specified && n_files == 1)
501     {
502       static char *dummy[2];
503       dummy[0] = file[0];
504       dummy[1] = ".";
505       file = dummy;
506       n_files = 2;
507       dest_is_dir = 1;
508     }
509   else
510     {
511       dest_is_dir = isdir (target_directory);
512     }
513
514   if (symbolic_link)
515     linkfunc = symlink;
516   else
517     linkfunc = link;
518
519   if (target_directory_specified && !dest_is_dir)
520     {
521       error (0, 0, _("%s: specified target directory is not a directory"),
522              quote (target_directory));
523       usage (EXIT_FAILURE);
524     }
525
526   if (backup_suffix_string)
527     simple_backup_suffix = xstrdup (backup_suffix_string);
528
529   backup_type = (make_backups
530                  ? xget_version (_("backup type"), version_control_string)
531                  : none);
532
533   if (target_directory_specified || n_files > 2)
534     {
535       unsigned int i;
536       unsigned int last_file_idx = (target_directory_specified
537                                     ? n_files - 1
538                                     : n_files - 2);
539
540       if (!target_directory_specified && !dest_is_dir)
541         error (EXIT_FAILURE, 0,
542            _("when making multiple links, last argument must be a directory"));
543       for (i = 0; i <= last_file_idx; ++i)
544         errors += do_link (file[i], target_directory);
545     }
546   else
547     {
548       struct stat source_stats;
549       const char *source;
550       char *dest;
551       char *new_dest;
552
553       source = file[0];
554       dest = file[1];
555
556       /* When the destination is specified with a trailing slash and the
557          source exists but is not a directory, convert the user's command
558          `ln source dest/' to `ln source dest/basename(source)'.  */
559
560       if (dest[strlen (dest) - 1] == '/'
561           && lstat (source, &source_stats) == 0
562           && !S_ISDIR (source_stats.st_mode))
563         {
564           PATH_BASENAME_CONCAT (new_dest, dest, source);
565         }
566       else
567         {
568           new_dest = dest;
569         }
570
571       errors = do_link (source, new_dest);
572     }
573
574   exit (errors != 0);
575 }