Don't include dirname.h, since system.h does it now.
[platform/upstream/coreutils.git] / src / ln.c
1 /* `ln' program to create links between files.
2    Copyright (C) 1986, 1989-1991, 1995-2006 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
17 \f
18 /* Written by Mike Parker and David MacKenzie. */
19
20 #include <config.h>
21 #include <stdio.h>
22 #include <sys/types.h>
23 #include <getopt.h>
24
25 #include "system.h"
26 #include "same.h"
27 #include "backupfile.h"
28 #include "error.h"
29 #include "filenamecat.h"
30 #include "quote.h"
31 #include "yesno.h"
32
33 /* The official name of this program (e.g., no `g' prefix).  */
34 #define PROGRAM_NAME "ln"
35
36 #define AUTHORS "Mike Parker", "David MacKenzie"
37
38 #ifndef ENABLE_HARD_LINK_TO_SYMLINK_WARNING
39 # define ENABLE_HARD_LINK_TO_SYMLINK_WARNING 0
40 #endif
41
42 /* In being careful not even to try to make hard links to directories,
43    we have to know whether link(2) follows symlinks.  If it does, then
44    we have to *stat* the `source' to see if the resulting link would be
45    to a directory.  Otherwise, we have to use *lstat* so that we allow
46    users to make hard links to symlinks-that-point-to-directories.  */
47
48 #if LINK_FOLLOWS_SYMLINKS
49 # define STAT_LIKE_LINK(File, Stat_buf) \
50   stat (File, Stat_buf)
51 #else
52 # define STAT_LIKE_LINK(File, Stat_buf) \
53   lstat (File, Stat_buf)
54 #endif
55
56 /* The name by which the program was run, for error messages.  */
57 char *program_name;
58
59 /* FIXME: document */
60 static enum backup_type backup_type;
61
62 /* If true, make symbolic links; otherwise, make hard links.  */
63 static bool symbolic_link;
64
65 /* If true, ask the user before removing existing files.  */
66 static bool interactive;
67
68 /* If true, remove existing files unconditionally.  */
69 static bool remove_existing_files;
70
71 /* If true, list each file as it is moved. */
72 static bool verbose;
73
74 /* If true, allow the superuser to *attempt* to make hard links
75    to directories.  However, it appears that this option is not useful
76    in practice, since even the superuser is prohibited from hard-linking
77    directories on most (all?) existing systems.  */
78 static bool hard_dir_link;
79
80 /* If nonzero, and the specified destination is a symbolic link to a
81    directory, treat it just as if it were a directory.  Otherwise, the
82    command `ln --force --no-dereference file symlink-to-dir' deletes
83    symlink-to-dir before creating the new link.  */
84 static bool dereference_dest_dir_symlinks = true;
85
86 static struct option const long_options[] =
87 {
88   {"backup", optional_argument, NULL, 'b'},
89   {"directory", no_argument, NULL, 'F'},
90   {"no-dereference", no_argument, NULL, 'n'},
91   {"no-target-directory", no_argument, NULL, 'T'},
92   {"force", no_argument, NULL, 'f'},
93   {"interactive", no_argument, NULL, 'i'},
94   {"suffix", required_argument, NULL, 'S'},
95   {"target-directory", required_argument, NULL, 't'},
96   {"symbolic", no_argument, NULL, 's'},
97   {"verbose", no_argument, NULL, 'v'},
98   {GETOPT_HELP_OPTION_DECL},
99   {GETOPT_VERSION_OPTION_DECL},
100   {NULL, 0, NULL, 0}
101 };
102
103 /* FILE is the last operand of this command.  Return true if FILE is a
104    directory.  But report an error there is a problem accessing FILE,
105    or if FILE does not exist but would have to refer to an existing
106    directory if it referred to anything at all.  */
107
108 static bool
109 target_directory_operand (char const *file)
110 {
111   char const *b = last_component (file);
112   size_t blen = strlen (b);
113   bool looks_like_a_dir = (blen == 0 || ISSLASH (b[blen - 1]));
114   struct stat st;
115   int err = ((dereference_dest_dir_symlinks ? stat : lstat) (file, &st) == 0
116              ? 0 : errno);
117   bool is_a_dir = !err && S_ISDIR (st.st_mode);
118   if (err && err != ENOENT)
119     error (EXIT_FAILURE, err, _("accessing %s"), quote (file));
120   if (is_a_dir < looks_like_a_dir)
121     error (EXIT_FAILURE, err, _("target %s is not a directory"), quote (file));
122   return is_a_dir;
123 }
124
125 /* Make a link DEST to the (usually) existing file SOURCE.
126    Symbolic links to nonexistent files are allowed.
127    Return true if successful.  */
128
129 static bool
130 do_link (const char *source, const char *dest)
131 {
132   struct stat source_stats;
133   struct stat dest_stats;
134   char *dest_backup = NULL;
135   bool lstat_ok = false;
136   bool source_is_dir = false;
137   bool ok;
138
139   /* Use stat here instead of lstat.
140      On SVR4, link does not follow symlinks, so this check disallows
141      making hard links to symlinks that point to directories.  Big deal.
142      On other systems, link follows symlinks, so this check is right.  */
143   if (!symbolic_link)
144     {
145       if (STAT_LIKE_LINK (source, &source_stats) != 0)
146         {
147           error (0, errno, _("accessing %s"), quote (source));
148           return false;
149         }
150
151       if (ENABLE_HARD_LINK_TO_SYMLINK_WARNING
152           && S_ISLNK (source_stats.st_mode))
153         {
154           error (0, 0, _("%s: warning: making a hard link to a symbolic link\
155  is not portable"),
156                  quote (source));
157         }
158
159       if (S_ISDIR (source_stats.st_mode))
160         {
161           source_is_dir = true;
162           if (! hard_dir_link)
163             {
164               error (0, 0, _("%s: hard link not allowed for directory"),
165                      quote (source));
166               return false;
167             }
168         }
169     }
170
171   if (remove_existing_files || interactive || backup_type != no_backups)
172     {
173       lstat_ok = (lstat (dest, &dest_stats) == 0);
174       if (!lstat_ok && errno != ENOENT)
175         {
176           error (0, errno, _("accessing %s"), quote (dest));
177           return false;
178         }
179     }
180
181   /* If --force (-f) has been specified without --backup, then before
182      making a link ln must remove the destination file if it exists.
183      (with --backup, it just renames any existing destination file)
184      But if the source and destination are the same, don't remove
185      anything and fail right here.  */
186   if (remove_existing_files
187       && lstat_ok
188       /* Allow `ln -sf --backup k k' to succeed in creating the
189          self-referential symlink, but don't allow the hard-linking
190          equivalent: `ln -f k k' (with or without --backup) to get
191          beyond this point, because the error message you'd get is
192          misleading.  */
193       && (backup_type == no_backups || !symbolic_link)
194       && (!symbolic_link || stat (source, &source_stats) == 0)
195       && SAME_INODE (source_stats, dest_stats)
196       /* The following detects whether removing DEST will also remove
197          SOURCE.  If the file has only one link then both are surely
198          the same link.  Otherwise check whether they point to the same
199          name in the same directory.  */
200       && (source_stats.st_nlink == 1 || same_name (source, dest)))
201     {
202       error (0, 0, _("%s and %s are the same file"),
203              quote_n (0, source), quote_n (1, dest));
204       return false;
205     }
206
207   if (lstat_ok)
208     {
209       if (S_ISDIR (dest_stats.st_mode))
210         {
211           error (0, 0, _("%s: cannot overwrite directory"), quote (dest));
212           return false;
213         }
214       if (interactive)
215         {
216           fprintf (stderr, _("%s: replace %s? "), program_name, quote (dest));
217           if (!yesno ())
218             return true;
219           remove_existing_files = true;
220         }
221
222       if (backup_type != no_backups)
223         {
224           dest_backup = find_backup_file_name (dest, backup_type);
225           if (rename (dest, dest_backup) != 0)
226             {
227               int rename_errno = errno;
228               free (dest_backup);
229               dest_backup = NULL;
230               if (rename_errno != ENOENT)
231                 {
232                   error (0, rename_errno, _("cannot backup %s"), quote (dest));
233                   return false;
234                 }
235             }
236         }
237     }
238
239   ok = ((symbolic_link ? symlink (source, dest) : link (source, dest))
240         == 0);
241
242   /* If the attempt to create a link failed and we are removing or
243      backing up destinations, unlink the destination and try again.
244
245      POSIX 1003.1-2004 requires that ln -f A B must unlink B even on
246      failure (e.g., when A does not exist).  This is counterintuitive,
247      and we submitted a defect report
248      <http://www.opengroup.org/austin/mailarchives/ag-review/msg01794.html>
249      (2004-06-24).  If the committee does not fix the standard we'll
250      have to change the behavior of ln -f, at least if POSIXLY_CORRECT
251      is set.  In the meantime ln -f A B will not unlink B unless the
252      attempt to link A to B failed because B already existed.
253
254      Try to unlink DEST even if we may have backed it up successfully.
255      In some unusual cases (when DEST and DEST_BACKUP are hard-links
256      that refer to the same file), rename succeeds and DEST remains.
257      If we didn't remove DEST in that case, the subsequent LINKFUNC
258      call would fail.  */
259
260   if (!ok && errno == EEXIST && (remove_existing_files || dest_backup))
261     {
262       if (unlink (dest) != 0)
263         {
264           error (0, errno, _("cannot remove %s"), quote (dest));
265           free (dest_backup);
266           return false;
267         }
268
269       ok = ((symbolic_link ? symlink (source, dest) : link (source, dest))
270             == 0);
271     }
272
273   if (ok)
274     {
275       if (verbose)
276         {
277           if (dest_backup)
278             printf ("%s ~ ", quote (dest_backup));
279           printf ("%s %c> %s\n", quote_n (0, dest), (symbolic_link ? '-' : '='),
280                   quote_n (1, source));
281         }
282     }
283   else
284     {
285       error (0, errno,
286              (symbolic_link
287               ? (errno != ENAMETOOLONG && *source
288                  ? _("creating symbolic link %s")
289                  : _("creating symbolic link %s -> %s"))
290               : (errno == EMLINK && !source_is_dir
291                  ? _("creating hard link to %.0s%s")
292                  : (errno == EDQUOT || errno == EEXIST || errno == ENOSPC
293                     || errno == EROFS)
294                  ? _("creating hard link %s")
295                  : _("creating hard link %s => %s"))),
296              quote_n (0, dest), quote_n (1, source));
297
298       if (dest_backup)
299         {
300           if (rename (dest_backup, dest) != 0)
301             error (0, errno, _("cannot un-backup %s"), quote (dest));
302         }
303     }
304
305   free (dest_backup);
306   return ok;
307 }
308
309 void
310 usage (int status)
311 {
312   if (status != EXIT_SUCCESS)
313     fprintf (stderr, _("Try `%s --help' for more information.\n"),
314              program_name);
315   else
316     {
317       printf (_("\
318 Usage: %s [OPTION]... [-T] TARGET LINK_NAME   (1st form)\n\
319   or:  %s [OPTION]... TARGET                  (2nd form)\n\
320   or:  %s [OPTION]... TARGET... DIRECTORY     (3rd form)\n\
321   or:  %s [OPTION]... -t DIRECTORY TARGET...  (4th form)\n\
322 "),
323               program_name, program_name, program_name, program_name);
324       fputs (_("\
325 In the 1st form, create a link to TARGET with the name LINK_NAME.\n\
326 In the 2nd form, create a link to TARGET in the current directory.\n\
327 In the 3rd and 4th forms, create links to each TARGET in DIRECTORY.\n\
328 Create hard links by default, symbolic links with --symbolic.\n\
329 When creating hard links, each TARGET must exist.\n\
330 \n\
331 "), stdout);
332       fputs (_("\
333 Mandatory arguments to long options are mandatory for short options too.\n\
334 "), stdout);
335       fputs (_("\
336       --backup[=CONTROL]      make a backup of each existing destination file\n\
337   -b                          like --backup but does not accept an argument\n\
338   -d, -F, --directory         allow the superuser to attempt to hard link\n\
339                                 directories (note: will probably fail due to\n\
340                                 system restrictions, even for the superuser)\n\
341   -f, --force                 remove existing destination files\n\
342 "), stdout);
343       fputs (_("\
344   -n, --no-dereference        treat destination that is a symlink to a\n\
345                                 directory as if it were a normal file\n\
346   -i, --interactive           prompt whether to remove destinations\n\
347   -s, --symbolic              make symbolic links instead of hard links\n\
348 "), stdout);
349       fputs (_("\
350   -S, --suffix=SUFFIX         override the usual backup suffix\n\
351   -t, --target-directory=DIRECTORY  specify the DIRECTORY in which to create\n\
352                                 the links\n\
353   -T, --no-target-directory   treat LINK_NAME as a normal file\n\
354   -v, --verbose               print name of each linked file\n\
355 "), stdout);
356       fputs (HELP_OPTION_DESCRIPTION, stdout);
357       fputs (VERSION_OPTION_DESCRIPTION, stdout);
358       fputs (_("\
359 \n\
360 The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
361 The version control method may be selected via the --backup option or through\n\
362 the VERSION_CONTROL environment variable.  Here are the values:\n\
363 \n\
364 "), stdout);
365       fputs (_("\
366   none, off       never make backups (even if --backup is given)\n\
367   numbered, t     make numbered backups\n\
368   existing, nil   numbered if numbered backups exist, simple otherwise\n\
369   simple, never   always make simple backups\n\
370 "), stdout);
371       printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
372     }
373   exit (status);
374 }
375
376 int
377 main (int argc, char **argv)
378 {
379   int c;
380   bool ok;
381   bool make_backups = false;
382   char *backup_suffix_string;
383   char *version_control_string = NULL;
384   char const *target_directory = NULL;
385   bool no_target_directory = false;
386   int n_files;
387   char **file;
388
389   initialize_main (&argc, &argv);
390   program_name = argv[0];
391   setlocale (LC_ALL, "");
392   bindtextdomain (PACKAGE, LOCALEDIR);
393   textdomain (PACKAGE);
394
395   atexit (close_stdout);
396
397   /* FIXME: consider not calling getenv for SIMPLE_BACKUP_SUFFIX unless
398      we'll actually use backup_suffix_string.  */
399   backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
400
401   symbolic_link = remove_existing_files = interactive = verbose
402     = hard_dir_link = false;
403
404   while ((c = getopt_long (argc, argv, "bdfinst:vFS:T", long_options, NULL))
405          != -1)
406     {
407       switch (c)
408         {
409         case 'b':
410           make_backups = true;
411           if (optarg)
412             version_control_string = optarg;
413           break;
414         case 'd':
415         case 'F':
416           hard_dir_link = true;
417           break;
418         case 'f':
419           remove_existing_files = true;
420           interactive = false;
421           break;
422         case 'i':
423           remove_existing_files = false;
424           interactive = true;
425           break;
426         case 'n':
427           dereference_dest_dir_symlinks = false;
428           break;
429         case 's':
430           symbolic_link = true;
431           break;
432         case 't':
433           if (target_directory)
434             error (EXIT_FAILURE, 0, _("multiple target directories specified"));
435           else
436             {
437               struct stat st;
438               if (stat (optarg, &st) != 0)
439                 error (EXIT_FAILURE, errno, _("accessing %s"), quote (optarg));
440               if (! S_ISDIR (st.st_mode))
441                 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
442                        quote (optarg));
443             }
444           target_directory = optarg;
445           break;
446         case 'T':
447           no_target_directory = true;
448           break;
449         case 'v':
450           verbose = true;
451           break;
452         case 'S':
453           make_backups = true;
454           backup_suffix_string = optarg;
455           break;
456         case_GETOPT_HELP_CHAR;
457         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
458         default:
459           usage (EXIT_FAILURE);
460           break;
461         }
462     }
463
464   n_files = argc - optind;
465   file = argv + optind;
466
467   if (n_files <= 0)
468     {
469       error (0, 0, _("missing file operand"));
470       usage (EXIT_FAILURE);
471     }
472
473   if (no_target_directory)
474     {
475       if (target_directory)
476         error (EXIT_FAILURE, 0,
477                _("Cannot combine --target-directory "
478                  "and --no-target-directory"));
479       if (n_files != 2)
480         {
481           if (n_files < 2)
482             error (0, 0,
483                    _("missing destination file operand after %s"),
484                    quote (file[0]));
485           else
486             error (0, 0, _("extra operand %s"), quote (file[2]));
487           usage (EXIT_FAILURE);
488         }
489     }
490   else if (!target_directory)
491     {
492       if (n_files < 2)
493         target_directory = ".";
494       else if (2 <= n_files && target_directory_operand (file[n_files - 1]))
495         target_directory = file[--n_files];
496       else if (2 < n_files)
497         error (EXIT_FAILURE, 0, _("target %s is not a directory"),
498                quote (file[n_files - 1]));
499     }
500
501   if (backup_suffix_string)
502     simple_backup_suffix = xstrdup (backup_suffix_string);
503
504   backup_type = (make_backups
505                  ? xget_version (_("backup type"), version_control_string)
506                  : no_backups);
507
508   if (target_directory)
509     {
510       int i;
511       ok = true;
512       for (i = 0; i < n_files; ++i)
513         {
514           char *dest_base;
515           char *dest = file_name_concat (target_directory,
516                                          last_component (file[i]),
517                                          &dest_base);
518           strip_trailing_slashes (dest_base);
519           ok &= do_link (file[i], dest);
520           free (dest);
521         }
522     }
523   else
524     ok = do_link (file[0], file[1]);
525
526   exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);
527 }