id: fix infinite loop on some systems
[coreutils/ericb.git] / src / mv.c
blob061323632ea8398b12ad4a4b098dd99a3eec809e
1 /* mv -- move or rename files
2 Copyright (C) 86, 89, 90, 91, 1995-2009 Free Software Foundation, Inc.
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 3 of the License, or
7 (at your option) any later version.
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.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 /* Written by Mike Parker, David MacKenzie, and Jim Meyering */
19 #include <config.h>
20 #include <stdio.h>
21 #include <getopt.h>
22 #include <sys/types.h>
23 #include <assert.h>
24 #include <selinux/selinux.h>
26 #include "system.h"
27 #include "backupfile.h"
28 #include "copy.h"
29 #include "cp-hash.h"
30 #include "error.h"
31 #include "filenamecat.h"
32 #include "quote.h"
33 #include "remove.h"
34 #include "root-dev-ino.h"
36 /* The official name of this program (e.g., no `g' prefix). */
37 #define PROGRAM_NAME "mv"
39 #define AUTHORS \
40 proper_name ("Mike Parker"), \
41 proper_name ("David MacKenzie"), \
42 proper_name ("Jim Meyering")
44 /* For long options that have no equivalent short option, use a
45 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
46 enum
48 STRIP_TRAILING_SLASHES_OPTION = CHAR_MAX + 1
51 /* Remove any trailing slashes from each SOURCE argument. */
52 static bool remove_trailing_slashes;
54 static struct option const long_options[] =
56 {"backup", optional_argument, NULL, 'b'},
57 {"force", no_argument, NULL, 'f'},
58 {"interactive", no_argument, NULL, 'i'},
59 {"no-clobber", no_argument, NULL, 'n'},
60 {"no-target-directory", no_argument, NULL, 'T'},
61 {"strip-trailing-slashes", no_argument, NULL, STRIP_TRAILING_SLASHES_OPTION},
62 {"suffix", required_argument, NULL, 'S'},
63 {"target-directory", required_argument, NULL, 't'},
64 {"update", no_argument, NULL, 'u'},
65 {"verbose", no_argument, NULL, 'v'},
66 {GETOPT_HELP_OPTION_DECL},
67 {GETOPT_VERSION_OPTION_DECL},
68 {NULL, 0, NULL, 0}
71 static void
72 rm_option_init (struct rm_options *x)
74 x->ignore_missing_files = false;
75 x->recursive = true;
76 x->one_file_system = false;
78 /* Should we prompt for removal, too? No. Prompting for the `move'
79 part is enough. It implies removal. */
80 x->interactive = RMI_NEVER;
81 x->stdin_tty = false;
83 x->verbose = false;
85 /* Since this program may well have to process additional command
86 line arguments after any call to `rm', that function must preserve
87 the initial working directory, in case one of those is a
88 `.'-relative name. */
89 x->require_restore_cwd = true;
92 static struct dev_ino dev_ino_buf;
93 x->root_dev_ino = get_root_dev_ino (&dev_ino_buf);
94 if (x->root_dev_ino == NULL)
95 error (EXIT_FAILURE, errno, _("failed to get attributes of %s"),
96 quote ("/"));
100 static void
101 cp_option_init (struct cp_options *x)
103 bool selinux_enabled = (0 < is_selinux_enabled ());
105 cp_options_default (x);
106 x->copy_as_regular = false; /* FIXME: maybe make this an option */
107 x->dereference = DEREF_NEVER;
108 x->unlink_dest_before_opening = false;
109 x->unlink_dest_after_failed_open = false;
110 x->hard_link = false;
111 x->interactive = I_UNSPECIFIED;
112 x->move_mode = true;
113 x->one_file_system = false;
114 x->preserve_ownership = true;
115 x->preserve_links = true;
116 x->preserve_mode = true;
117 x->preserve_timestamps = true;
118 x->preserve_security_context = selinux_enabled;
119 x->reduce_diagnostics = false;
120 x->require_preserve = false; /* FIXME: maybe make this an option */
121 x->require_preserve_context = false;
122 x->preserve_xattr = true;
123 x->require_preserve_xattr = false;
124 x->recursive = true;
125 x->sparse_mode = SPARSE_AUTO; /* FIXME: maybe make this an option */
126 x->symbolic_link = false;
127 x->set_mode = false;
128 x->mode = 0;
129 x->stdin_tty = isatty (STDIN_FILENO);
131 x->open_dangling_dest_symlink = false;
132 x->update = false;
133 x->verbose = false;
134 x->dest_info = NULL;
135 x->src_info = NULL;
138 /* FILE is the last operand of this command. Return true if FILE is a
139 directory. But report an error if there is a problem accessing FILE, other
140 than nonexistence (errno == ENOENT). */
142 static bool
143 target_directory_operand (char const *file)
145 struct stat st;
146 int err = (stat (file, &st) == 0 ? 0 : errno);
147 bool is_a_dir = !err && S_ISDIR (st.st_mode);
148 if (err && err != ENOENT)
149 error (EXIT_FAILURE, err, _("accessing %s"), quote (file));
150 return is_a_dir;
153 /* Move SOURCE onto DEST. Handles cross-file-system moves.
154 If SOURCE is a directory, DEST must not exist.
155 Return true if successful. */
157 static bool
158 do_move (const char *source, const char *dest, const struct cp_options *x)
160 bool copy_into_self;
161 bool rename_succeeded;
162 bool ok = copy (source, dest, false, x, &copy_into_self, &rename_succeeded);
164 if (ok)
166 char const *dir_to_remove;
167 if (copy_into_self)
169 /* In general, when copy returns with copy_into_self set, SOURCE is
170 the same as, or a parent of DEST. In this case we know it's a
171 parent. It doesn't make sense to move a directory into itself, and
172 besides in some situations doing so would give highly nonintuitive
173 results. Run this `mkdir b; touch a c; mv * b' in an empty
174 directory. Here's the result of running echo `find b -print`:
175 b b/a b/b b/b/a b/c. Notice that only file `a' was copied
176 into b/b. Handle this by giving a diagnostic, removing the
177 copied-into-self directory, DEST (`b/b' in the example),
178 and failing. */
180 dir_to_remove = NULL;
181 ok = false;
183 else if (rename_succeeded)
185 /* No need to remove anything. SOURCE was successfully
186 renamed to DEST. Or the user declined to rename a file. */
187 dir_to_remove = NULL;
189 else
191 /* This may mean SOURCE and DEST referred to different devices.
192 It may also conceivably mean that even though they referred
193 to the same device, rename wasn't implemented for that device.
195 E.g., (from Joel N. Weber),
196 [...] there might someday be cases where you can't rename
197 but you can copy where the device name is the same, especially
198 on Hurd. Consider an ftpfs with a primitive ftp server that
199 supports uploading, downloading and deleting, but not renaming.
201 Also, note that comparing device numbers is not a reliable
202 check for `can-rename'. Some systems can be set up so that
203 files from many different physical devices all have the same
204 st_dev field. This is a feature of some NFS mounting
205 configurations.
207 We reach this point if SOURCE has been successfully copied
208 to DEST. Now we have to remove SOURCE.
210 This function used to resort to copying only when rename
211 failed and set errno to EXDEV. */
213 dir_to_remove = source;
216 if (dir_to_remove != NULL)
218 struct rm_options rm_options;
219 enum RM_status status;
221 rm_option_init (&rm_options);
222 rm_options.verbose = x->verbose;
224 status = rm (1, &dir_to_remove, &rm_options);
225 assert (VALID_STATUS (status));
226 if (status == RM_ERROR)
227 ok = false;
231 return ok;
234 /* Move file SOURCE onto DEST. Handles the case when DEST is a directory.
235 Treat DEST as a directory if DEST_IS_DIR.
236 Return true if successful. */
238 static bool
239 movefile (char *source, char *dest, bool dest_is_dir,
240 const struct cp_options *x)
242 bool ok;
244 /* This code was introduced to handle the ambiguity in the semantics
245 of mv that is induced by the varying semantics of the rename function.
246 Some systems (e.g., GNU/Linux) have a rename function that honors a
247 trailing slash, while others (like Solaris 5,6,7) have a rename
248 function that ignores a trailing slash. I believe the GNU/Linux
249 rename semantics are POSIX and susv2 compliant. */
251 if (remove_trailing_slashes)
252 strip_trailing_slashes (source);
254 if (dest_is_dir)
256 /* Treat DEST as a directory; build the full filename. */
257 char const *src_basename = last_component (source);
258 char *new_dest = file_name_concat (dest, src_basename, NULL);
259 strip_trailing_slashes (new_dest);
260 ok = do_move (source, new_dest, x);
261 free (new_dest);
263 else
265 ok = do_move (source, dest, x);
268 return ok;
271 void
272 usage (int status)
274 if (status != EXIT_SUCCESS)
275 fprintf (stderr, _("Try `%s --help' for more information.\n"),
276 program_name);
277 else
279 printf (_("\
280 Usage: %s [OPTION]... [-T] SOURCE DEST\n\
281 or: %s [OPTION]... SOURCE... DIRECTORY\n\
282 or: %s [OPTION]... -t DIRECTORY SOURCE...\n\
284 program_name, program_name, program_name);
285 fputs (_("\
286 Rename SOURCE to DEST, or move SOURCE(s) to DIRECTORY.\n\
288 "), stdout);
289 fputs (_("\
290 Mandatory arguments to long options are mandatory for short options too.\n\
291 "), stdout);
292 fputs (_("\
293 --backup[=CONTROL] make a backup of each existing destination file\n\
294 -b like --backup but does not accept an argument\n\
295 -f, --force do not prompt before overwriting\n\
296 -i, --interactive prompt before overwrite\n\
297 -n, --no-clobber do not overwrite an existing file\n\
298 If you specify more than one of -i, -f, -n, only the final one takes effect.\n\
299 "), stdout);
300 fputs (_("\
301 --strip-trailing-slashes remove any trailing slashes from each SOURCE\n\
302 argument\n\
303 -S, --suffix=SUFFIX override the usual backup suffix\n\
304 "), stdout);
305 fputs (_("\
306 -t, --target-directory=DIRECTORY move all SOURCE arguments into DIRECTORY\n\
307 -T, --no-target-directory treat DEST as a normal file\n\
308 -u, --update move only when the SOURCE file is newer\n\
309 than the destination file or when the\n\
310 destination file is missing\n\
311 -v, --verbose explain what is being done\n\
312 "), stdout);
313 fputs (HELP_OPTION_DESCRIPTION, stdout);
314 fputs (VERSION_OPTION_DESCRIPTION, stdout);
315 fputs (_("\
317 The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
318 The version control method may be selected via the --backup option or through\n\
319 the VERSION_CONTROL environment variable. Here are the values:\n\
321 "), stdout);
322 fputs (_("\
323 none, off never make backups (even if --backup is given)\n\
324 numbered, t make numbered backups\n\
325 existing, nil numbered if numbered backups exist, simple otherwise\n\
326 simple, never always make simple backups\n\
327 "), stdout);
328 emit_bug_reporting_address ();
330 exit (status);
334 main (int argc, char **argv)
336 int c;
337 bool ok;
338 bool make_backups = false;
339 char *backup_suffix_string;
340 char *version_control_string = NULL;
341 struct cp_options x;
342 char *target_directory = NULL;
343 bool no_target_directory = false;
344 int n_files;
345 char **file;
347 initialize_main (&argc, &argv);
348 set_program_name (argv[0]);
349 setlocale (LC_ALL, "");
350 bindtextdomain (PACKAGE, LOCALEDIR);
351 textdomain (PACKAGE);
353 atexit (close_stdin);
355 cp_option_init (&x);
357 /* FIXME: consider not calling getenv for SIMPLE_BACKUP_SUFFIX unless
358 we'll actually use backup_suffix_string. */
359 backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
361 while ((c = getopt_long (argc, argv, "bfint:uvS:T", long_options, NULL))
362 != -1)
364 switch (c)
366 case 'b':
367 make_backups = true;
368 if (optarg)
369 version_control_string = optarg;
370 break;
371 case 'f':
372 x.interactive = I_ALWAYS_YES;
373 break;
374 case 'i':
375 x.interactive = I_ASK_USER;
376 break;
377 case 'n':
378 x.interactive = I_ALWAYS_NO;
379 break;
380 case STRIP_TRAILING_SLASHES_OPTION:
381 remove_trailing_slashes = true;
382 break;
383 case 't':
384 if (target_directory)
385 error (EXIT_FAILURE, 0, _("multiple target directories specified"));
386 else
388 struct stat st;
389 if (stat (optarg, &st) != 0)
390 error (EXIT_FAILURE, errno, _("accessing %s"), quote (optarg));
391 if (! S_ISDIR (st.st_mode))
392 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
393 quote (optarg));
395 target_directory = optarg;
396 break;
397 case 'T':
398 no_target_directory = true;
399 break;
400 case 'u':
401 x.update = true;
402 break;
403 case 'v':
404 x.verbose = true;
405 break;
406 case 'S':
407 make_backups = true;
408 backup_suffix_string = optarg;
409 break;
410 case_GETOPT_HELP_CHAR;
411 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
412 default:
413 usage (EXIT_FAILURE);
417 n_files = argc - optind;
418 file = argv + optind;
420 if (n_files <= !target_directory)
422 if (n_files <= 0)
423 error (0, 0, _("missing file operand"));
424 else
425 error (0, 0, _("missing destination file operand after %s"),
426 quote (file[0]));
427 usage (EXIT_FAILURE);
430 if (no_target_directory)
432 if (target_directory)
433 error (EXIT_FAILURE, 0,
434 _("cannot combine --target-directory (-t) "
435 "and --no-target-directory (-T)"));
436 if (2 < n_files)
438 error (0, 0, _("extra operand %s"), quote (file[2]));
439 usage (EXIT_FAILURE);
442 else if (!target_directory)
444 assert (2 <= n_files);
445 if (target_directory_operand (file[n_files - 1]))
446 target_directory = file[--n_files];
447 else if (2 < n_files)
448 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
449 quote (file[n_files - 1]));
452 if (make_backups && x.interactive == I_ALWAYS_NO)
454 error (0, 0,
455 _("options --backup and --no-clobber are mutually exclusive"));
456 usage (EXIT_FAILURE);
459 if (backup_suffix_string)
460 simple_backup_suffix = xstrdup (backup_suffix_string);
462 x.backup_type = (make_backups
463 ? xget_version (_("backup type"),
464 version_control_string)
465 : no_backups);
467 hash_init ();
469 if (target_directory)
471 int i;
473 /* Initialize the hash table only if we'll need it.
474 The problem it is used to detect can arise only if there are
475 two or more files to move. */
476 if (2 <= n_files)
477 dest_info_init (&x);
479 ok = true;
480 for (i = 0; i < n_files; ++i)
481 ok &= movefile (file[i], target_directory, true, &x);
483 else
484 ok = movefile (file[0], file[1], false, &x);
486 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);