home *** CD-ROM | disk | FTP | other *** search
/ Fresh Fish 8 / FreshFishVol8-CD2.bin / bbs / gnu / fileutils-3.12-src.lha / fileutils-3.12 / src / mv.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-11-12  |  11.2 KB  |  492 lines

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