(add_tabstop): Give correct size when reallocating tab_list buffer.
[platform/upstream/coreutils.git] / src / mv.c
1 /* mv -- move or rename 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
18 /* Options:
19    -f, --force          Assume a 'y' answer to all questions it would
20                         normally ask, and not ask the questions.
21
22    -i, --interactive    Require confirmation from the user before
23                         performing any move that would destroy an
24                         existing file.
25
26    -u, --update         Do not move a nondirectory that has an
27                         existing destination with the same or newer
28                         modification time.
29
30    -v, --verbose                List the name of each file as it is moved, and
31                         the name it is moved to.
32
33    -b, --backup
34    -S, --suffix
35    -V, --version-control
36                         Backup file creation.
37
38    Written by Mike Parker and David MacKenzie */
39
40 #ifdef _AIX
41  #pragma alloca
42 #endif
43
44 #include <config.h>
45 #include <stdio.h>
46 #include <getopt.h>
47 #include <sys/types.h>
48
49 #include "system.h"
50 #include "backupfile.h"
51 #include "version.h"
52 #include "safe-lstat.h"
53 #include "error.h"
54
55 #ifndef _POSIX_VERSION
56 uid_t geteuid ();
57 #endif
58
59 char *basename ();
60 enum backup_type get_version ();
61 int isdir ();
62 int yesno ();
63 int safe_read ();
64 int full_write ();
65 void strip_trailing_slashes ();
66 int eaccess_stat ();
67 char *stpcpy ();
68
69 static int copy_reg ();
70 static int do_move ();
71 static int movefile ();
72 static void usage ();
73
74 /* The name this program was run with. */
75 char *program_name;
76
77 /* If nonzero, query the user before overwriting files. */
78 static int interactive;
79
80 /* If nonzero, do not query the user before overwriting unwritable
81    files. */
82 static int override_mode;
83
84 /* If nonzero, do not move a nondirectory that has an existing destination
85    with the same or newer modification time. */
86 static int update = 0;
87
88 /* If nonzero, list each file as it is moved. */
89 static int verbose;
90
91 /* If nonzero, stdin is a tty. */
92 static int stdin_tty;
93
94 /* This process's effective user ID.  */
95 static uid_t myeuid;
96
97 /* If non-zero, display usage information and exit.  */
98 static int show_help;
99
100 /* If non-zero, print the version on standard output and exit.  */
101 static int show_version;
102
103 static struct option const long_options[] =
104 {
105   {"backup", no_argument, NULL, 'b'},
106   {"force", no_argument, NULL, 'f'},
107   {"interactive", no_argument, NULL, 'i'},
108   {"suffix", required_argument, NULL, 'S'},
109   {"update", no_argument, &update, 1},
110   {"verbose", no_argument, &verbose, 1},
111   {"version-control", required_argument, NULL, 'V'},
112   {"help", no_argument, &show_help, 1},
113   {"version", no_argument, &show_version, 1},
114   {NULL, 0, NULL, 0}
115 };
116
117 void
118 main (argc, argv)
119      int argc;
120      char **argv;
121 {
122   int c;
123   int errors;
124   int make_backups = 0;
125   char *version;
126
127   version = getenv ("SIMPLE_BACKUP_SUFFIX");
128   if (version)
129     simple_backup_suffix = version;
130   version = getenv ("VERSION_CONTROL");
131   program_name = argv[0];
132   myeuid = geteuid ();
133   interactive = override_mode = verbose = update = 0;
134   errors = 0;
135
136   while ((c = getopt_long (argc, argv, "bfiuvS:V:", long_options, (int *) 0))
137          != EOF)
138     {
139       switch (c)
140         {
141         case 0:
142           break;
143         case 'b':
144           make_backups = 1;
145           break;
146         case 'f':
147           interactive = 0;
148           override_mode = 1;
149           break;
150         case 'i':
151           interactive = 1;
152           override_mode = 0;
153           break;
154         case 'u':
155           update = 1;
156           break;
157         case 'v':
158           verbose = 1;
159           break;
160         case 'S':
161           simple_backup_suffix = optarg;
162           break;
163         case 'V':
164           version = optarg;
165           break;
166         default:
167           usage (1);
168         }
169     }
170
171   if (show_version)
172     {
173       printf ("%s\n", version_string);
174       exit (0);
175     }
176
177   if (show_help)
178     usage (0);
179
180   if (argc < optind + 2)
181     {
182       error (0, 0, "missing file argument%s", argc == optind ? "s" : "");
183       usage (1);
184     }
185
186   if (make_backups)
187     backup_type = get_version (version);
188
189   stdin_tty = isatty (STDIN_FILENO);
190
191   if (argc > optind + 2 && !isdir (argv[argc - 1]))
192     error (1, 0, "when moving multiple files, last argument must be a directory");
193
194   /* Move each arg but the last onto the last. */
195   for (; optind < argc - 1; ++optind)
196     errors |= movefile (argv[optind], argv[argc - 1]);
197
198   exit (errors);
199 }
200
201 /* If PATH is an existing directory, return nonzero, else 0.  */
202
203 static int
204 is_real_dir (path)
205      char *path;
206 {
207   struct stat stats;
208
209   return safe_lstat (path, &stats) == 0 && S_ISDIR (stats.st_mode);
210 }
211
212 /* Move file SOURCE onto DEST.  Handles the case when DEST is a directory.
213    Return 0 if successful, 1 if an error occurred.  */
214
215 static int
216 movefile (source, dest)
217      char *source;
218      char *dest;
219 {
220   strip_trailing_slashes (source);
221
222   if ((dest[strlen (dest) - 1] == '/' && !is_real_dir (source))
223       || isdir (dest))
224     {
225       /* Target is a directory; build full target filename. */
226       char *base;
227       char *new_dest;
228
229       base = basename (source);
230       new_dest = (char *) alloca (strlen (dest) + 1 + strlen (base) + 1);
231       stpcpy (stpcpy (stpcpy (new_dest, dest), "/"), base);
232       return do_move (source, new_dest);
233     }
234   else
235     return do_move (source, dest);
236 }
237
238 static struct stat dest_stats, source_stats;
239
240 /* Move SOURCE onto DEST.  Handles cross-filesystem moves.
241    If DEST is a directory, SOURCE must be also.
242    Return 0 if successful, 1 if an error occurred.  */
243
244 static int
245 do_move (source, dest)
246      char *source;
247      char *dest;
248 {
249   char *dest_backup = NULL;
250
251   if (safe_lstat (source, &source_stats) != 0)
252     {
253       error (0, errno, "%s", source);
254       return 1;
255     }
256
257   if (safe_lstat (dest, &dest_stats) == 0)
258     {
259       if (source_stats.st_dev == dest_stats.st_dev
260           && source_stats.st_ino == dest_stats.st_ino)
261         {
262           error (0, 0, "`%s' and `%s' are the same file", source, dest);
263           return 1;
264         }
265
266       if (S_ISDIR (dest_stats.st_mode))
267         {
268           error (0, 0, "%s: cannot overwrite directory", dest);
269           return 1;
270         }
271
272       if (!S_ISDIR (source_stats.st_mode) && update
273           && source_stats.st_mtime <= dest_stats.st_mtime)
274         return 0;
275
276       if (!override_mode && (interactive || stdin_tty)
277           && eaccess_stat (&dest_stats, W_OK, dest))
278         {
279           fprintf (stderr, "%s: replace `%s', overriding mode %04o? ",
280                    program_name, dest,
281                    (unsigned int) (dest_stats.st_mode & 07777));
282           if (!yesno ())
283             return 0;
284         }
285       else if (interactive)
286         {
287           fprintf (stderr, "%s: replace `%s'? ", program_name, dest);
288           if (!yesno ())
289             return 0;
290         }
291
292       if (backup_type != none)
293         {
294           char *tmp_backup = find_backup_file_name (dest);
295           if (tmp_backup == NULL)
296             error (1, 0, "virtual memory exhausted");
297           dest_backup = (char *) alloca (strlen (tmp_backup) + 1);
298           strcpy (dest_backup, tmp_backup);
299           free (tmp_backup);
300           if (rename (dest, dest_backup))
301             {
302               if (errno != ENOENT)
303                 {
304                   error (0, errno, "cannot backup `%s'", dest);
305                   return 1;
306                 }
307               else
308                 dest_backup = NULL;
309             }
310         }
311     }
312   else if (errno != ENOENT)
313     {
314       error (0, errno, "%s", dest);
315       return 1;
316     }
317
318   if (verbose)
319     printf ("%s -> %s\n", source, dest);
320
321   if (rename (source, dest) == 0)
322     {
323       return 0;
324     }
325
326   if (errno != EXDEV)
327     {
328       error (0, errno, "cannot move `%s' to `%s'", source, dest);
329       goto un_backup;
330     }
331
332   /* rename failed on cross-filesystem link.  Copy the file instead. */
333
334   if (copy_reg (source, dest))
335     goto un_backup;
336
337   if (unlink (source))
338     {
339       error (0, errno, "cannot remove `%s'", source);
340       return 1;
341     }
342
343   return 0;
344
345  un_backup:
346   if (dest_backup)
347     {
348       if (rename (dest_backup, dest))
349         error (0, errno, "cannot un-backup `%s'", dest);
350     }
351   return 1;
352 }
353
354 /* Copy regular file SOURCE onto file DEST.
355    Return 1 if an error occurred, 0 if successful. */
356
357 static int
358 copy_reg (source, dest)
359      char *source, *dest;
360 {
361   int ifd;
362   int ofd;
363   char buf[1024 * 8];
364   int len;                      /* Number of bytes read into `buf'. */
365
366   if (!S_ISREG (source_stats.st_mode))
367     {
368       error (0, 0, "cannot move `%s' across filesystems: Not a regular file",
369              source);
370       return 1;
371     }
372
373   if (unlink (dest) && errno != ENOENT)
374     {
375       error (0, errno, "cannot remove `%s'", dest);
376       return 1;
377     }
378
379   ifd = open (source, O_RDONLY, 0);
380   if (ifd < 0)
381     {
382       error (0, errno, "%s", source);
383       return 1;
384     }
385   ofd = open (dest, O_WRONLY | O_CREAT | O_TRUNC, 0600);
386   if (ofd < 0)
387     {
388       error (0, errno, "%s", dest);
389       close (ifd);
390       return 1;
391     }
392
393   while ((len = safe_read (ifd, buf, sizeof (buf))) > 0)
394     {
395       if (full_write (ofd, buf, len) < 0)
396         {
397           error (0, errno, "%s", dest);
398           close (ifd);
399           close (ofd);
400           unlink (dest);
401           return 1;
402         }
403     }
404   if (len < 0)
405     {
406       error (0, errno, "%s", source);
407       close (ifd);
408       close (ofd);
409       unlink (dest);
410       return 1;
411     }
412
413   if (close (ifd) < 0)
414     {
415       error (0, errno, "%s", source);
416       close (ofd);
417       return 1;
418     }
419   if (close (ofd) < 0)
420     {
421       error (0, errno, "%s", dest);
422       return 1;
423     }
424
425   /* chown turns off set[ug]id bits for non-root,
426      so do the chmod last.  */
427
428   /* Try to copy the old file's modtime and access time.  */
429   {
430     struct utimbuf tv;
431
432     tv.actime = source_stats.st_atime;
433     tv.modtime = source_stats.st_mtime;
434     if (utime (dest, &tv))
435       {
436         error (0, errno, "%s", dest);
437         return 1;
438       }
439   }
440
441   /* Try to preserve ownership.  For non-root it might fail, but that's ok.
442      But root probably wants to know, e.g. if NFS disallows it.  */
443   if (chown (dest, source_stats.st_uid, source_stats.st_gid)
444       && (errno != EPERM || myeuid == 0))
445     {
446       error (0, errno, "%s", dest);
447       return 1;
448     }
449
450   if (chmod (dest, source_stats.st_mode & 07777))
451     {
452       error (0, errno, "%s", dest);
453       return 1;
454     }
455
456   return 0;
457 }
458
459 static void
460 usage (status)
461      int status;
462 {
463   if (status != 0)
464     fprintf (stderr, "Try `%s --help' for more information.\n",
465              program_name);
466   else
467     {
468       printf ("\
469 Usage: %s [OPTION]... SOURCE DEST\n\
470   or:  %s [OPTION]... SOURCE... DIRECTORY\n\
471 ",
472               program_name, program_name);
473       printf ("\
474 \n\
475   -b, --backup                 make backup before removal\n\
476   -f, --force                  remove existing destinations, never prompt\n\
477   -i, --interactive            prompt before overwrite\n\
478   -u, --update                 move only older or brand new files\n\
479   -v, --verbose                explain what is being done\n\
480   -S, --suffix=SUFFIX          override the usual backup suffix\n\
481   -V, --version-control=WORD   override the usual version control\n\
482       --help                   display this help and exit\n\
483       --version                output version information and exit\n\
484 \n\
485 The backup suffix is ~, unless set with SIMPLE_BACKUP_SUFFIX.  The\n\
486 version control may be set with VERSION_CONTROL, values are:\n\
487 \n\
488   t, numbered     make numbered backups\n\
489   nil, existing   numbered if numbered backups exist, simple otherwise\n\
490   never, simple   always make simple backups  \n");
491     }
492   exit (status);
493 }