making note of my changes.
[oweals/busybox.git] / tar.c
diff --git a/tar.c b/tar.c
index b404ab0256afd9a7447c5cf2bc45252622fbdb1b..a53370e85d1f364b00829cf5ac8c1b6a6e4b14ac 100644 (file)
--- a/tar.c
+++ b/tar.c
@@ -1,13 +1,32 @@
 /*
+ * Mini tar implementation for busybox based on code taken from sash.
+ *
  * Copyright (c) 1999 by David I. Bell
  * Permission is granted to use, distribute, or modify this source,
  * provided that this copyright notice remains intact.
  *
- * The "tar" command, taken from sash.
- * This allows creation, extraction, and listing of tar files.
- *
  * Permission to distribute this code under the GPL has been granted.
+ *
  * Modified for busybox by Erik Andersen <andersee@debian.org>
+ * Adjusted to grok stdin/stdout options.
+ *
+ * Modified to handle device special files by Matt Porter
+ * <porter@debian.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
  */
 
 
 #include <fcntl.h>
 #include <signal.h>
 #include <time.h>
+#include <utime.h>
+#include <sys/types.h>
+#include <sys/sysmacros.h>
 
 
 static const char tar_usage[] =
-    "Create, extract, or list files from a TAR file\n\n"
-    "usage: tar -[cxtvOf] [tarFileName] [FILE] ...\n"
-    "\tc=create, x=extract, t=list contents, v=verbose,\n"
-    "\tO=extract to stdout, f=tarfile or \"-\" for stdin\n";
+"tar -[cxtvOf] [tarFileName] [FILE] ...\n\n"
+"Create, extract, or list files from a tar file\n\n"
+"Options:\n"
+"\tc=create, x=extract, t=list contents, v=verbose,\n"
+"\tO=extract to stdout, f=tarfile or \"-\" for stdin\n";
 
 
 
@@ -76,7 +99,7 @@ static int createFlag;
 static int verboseFlag;
 static int tostdoutFlag;
 
-static int inHeader;
+static int inHeader; // <- check me
 static int badHeader;
 static int errorFlag;
 static int skipFileFlag;
@@ -84,8 +107,12 @@ static int warnedRoot;
 static int eofFlag;
 static long dataCc;
 static int outFd;
-static char outName[TAR_NAME_SIZE];
+static const char *outName;
 
+static int mode;
+static int uid;
+static int gid;
+static time_t mtime;
 
 /*
  * Static data associated with the tar file.
@@ -135,10 +162,8 @@ extern int tar_main (int argc, char **argv)
     argc--;
     argv++;
 
-    if (argc < 1) {
-       fprintf (stderr, "%s", tar_usage);
-       exit (FALSE);
-    }
+    if (argc < 1)
+       usage( tar_usage);
 
 
     errorFlag = FALSE;
@@ -155,10 +180,9 @@ extern int tar_main (int argc, char **argv)
     /* 
      * Parse the options.
      */
-    options = *argv++;
-    argc--;
-
     if (**argv == '-') {
+       options = (*argv++) + 1;
+       argc--;
        for (; *options; options++) {
            switch (*options) {
            case 'f':
@@ -194,10 +218,13 @@ extern int tar_main (int argc, char **argv)
                break;
 
            case '-':
+               usage( tar_usage);
                break;
 
            default:
-               fprintf (stderr, "Unknown tar flag '%c'\n", *options);
+               fprintf (stderr, "Unknown tar flag '%c'\n"
+                       "Try `tar --help' for more information\n", 
+                       *options);
 
                exit (FALSE);
            }
@@ -207,7 +234,7 @@ extern int tar_main (int argc, char **argv)
     /* 
      * Validate the options.
      */
-    if (extractFlag + listFlag + createFlag != 1) {
+    if (extractFlag + listFlag + createFlag != (TRUE+FALSE+FALSE)) {
        fprintf (stderr,
                 "Exactly one of 'c', 'x' or 't' must be specified\n");
 
@@ -218,13 +245,13 @@ extern int tar_main (int argc, char **argv)
      * Do the correct type of action supplying the rest of the
      * command line arguments as the list of files to process.
      */
-    if (createFlag)
+    if (createFlag==TRUE)
        writeTarFile (argc, argv);
     else
        readTarFile (argc, argv);
-    if (errorFlag)
+    if (errorFlag==TRUE)
        fprintf (stderr, "\n");
-    exit (errorFlag);
+    exit (!errorFlag);
 }
 
 
@@ -255,7 +282,7 @@ static void readTarFile (int fileCount, char **fileTable)
      * Open the tar file for reading.
      */
     if ((tarName == NULL) || !strcmp (tarName, "-")) {
-       tarFd = STDIN;
+       tarFd = fileno(stdin);
     } else
        tarFd = open (tarName, O_RDONLY);
 
@@ -269,7 +296,7 @@ static void readTarFile (int fileCount, char **fileTable)
      * Read blocks from the file until an end of file header block
      * has been seen.  (A real end of file from a read is an error.)
      */
-    while (!eofFlag) {
+    while (eofFlag==FALSE) {
        /* 
         * Read the next block of data if necessary.
         * This will be a large block if possible, which we will
@@ -296,7 +323,7 @@ static void readTarFile (int fileCount, char **fileTable)
        /* 
         * If we are expecting a header block then examine it.
         */
-       if (inHeader) {
+       if (inHeader==TRUE) {
            readHeader ((const TarHeader *) cp, fileCount, fileTable);
 
            cp += TAR_BLOCK_SIZE;
@@ -342,8 +369,9 @@ static void readTarFile (int fileCount, char **fileTable)
      * message is required on errors.
      */
     if (tostdoutFlag == FALSE) {
-       if (outFd >= 0)
-           (void) close (outFd);
+       if (outFd >= 0) {
+           close (outFd);
+       }
     }
 }
 
@@ -356,26 +384,25 @@ static void readTarFile (int fileCount, char **fileTable)
 static void
 readHeader (const TarHeader * hp, int fileCount, char **fileTable)
 {
-    int mode;
-    int uid;
-    int gid;
     int checkSum;
-    long size;
-    time_t mtime;
-    const char *name;
     int cc;
     int hardLink;
     int softLink;
+    int devFileFlag;
+    unsigned int major;
+    unsigned int minor;
+    long size;
+    struct utimbuf utb;
 
     /* 
      * If the block is completely empty, then this is the end of the
      * archive file.  If the name is null, then just skip this header.
      */
-    name = hp->name;
+    outName = hp->name;
 
-    if (*name == '\0') {
+    if (*outName == '\0') {
        for (cc = TAR_BLOCK_SIZE; cc > 0; cc--) {
-           if (*name++)
+           if (*outName++)
                return;
        }
 
@@ -394,9 +421,11 @@ readHeader (const TarHeader * hp, int fileCount, char **fileTable)
     size = getOctal (hp->size, sizeof (hp->size));
     mtime = getOctal (hp->mtime, sizeof (hp->mtime));
     checkSum = getOctal (hp->checkSum, sizeof (hp->checkSum));
+    major = getOctal (hp->devMajor, sizeof (hp->devMajor));
+    minor = getOctal (hp->devMinor, sizeof (hp->devMinor));
 
     if ((mode < 0) || (uid < 0) || (gid < 0) || (size < 0)) {
-       if (!badHeader)
+       if (badHeader==FALSE)
            fprintf (stderr, "Bad tar header, skipping\n");
 
        badHeader = TRUE;
@@ -406,6 +435,7 @@ readHeader (const TarHeader * hp, int fileCount, char **fileTable)
 
     badHeader = FALSE;
     skipFileFlag = FALSE;
+    devFileFlag = FALSE;
 
     /* 
      * Check for the file modes.
@@ -417,22 +447,20 @@ readHeader (const TarHeader * hp, int fileCount, char **fileTable)
                (hp->typeFlag == TAR_TYPE_SOFT_LINK - '0'));
 
     /* 
-     * Check for a directory or a regular file.
+     * Check for a directory.
      */
-    if (name[strlen (name) - 1] == '/')
+    if (outName[strlen (outName) - 1] == '/')
        mode |= S_IFDIR;
-    else if ((mode & S_IFMT) == 0)
-       mode |= S_IFREG;
 
     /* 
      * Check for absolute paths in the file.
      * If we find any, then warn the user and make them relative.
      */
-    if (*name == '/') {
-       while (*name == '/')
-           name++;
+    if (*outName == '/') {
+       while (*outName == '/')
+           outName++;
 
-       if (!warnedRoot) {
+       if (warnedRoot==FALSE) {
            fprintf (stderr,
                     "Absolute path detected, removing leading slashes\n");
        }
@@ -444,9 +472,10 @@ readHeader (const TarHeader * hp, int fileCount, char **fileTable)
      * See if we want this file to be restored.
      * If not, then set up to skip it.
      */
-    if (!wantFileName (name, fileCount, fileTable)) {
-       if (!hardLink && !softLink && S_ISREG (mode)) {
-           inHeader = (size == 0);
+    if (wantFileName (outName, fileCount, fileTable) == FALSE) {
+       if ( !hardLink && !softLink && (S_ISREG (mode) || S_ISCHR (mode)
+                   || S_ISBLK (mode) || S_ISSOCK(mode) || S_ISFIFO(mode) ) ) {
+           inHeader = (size == 0)? TRUE : FALSE;
            dataCc = size;
        }
 
@@ -459,19 +488,23 @@ readHeader (const TarHeader * hp, int fileCount, char **fileTable)
      * This file is to be handled.
      * If we aren't extracting then just list information about the file.
      */
-    if (!extractFlag) {
-       if (verboseFlag) {
-           printf ("%s %3d/%-d %9ld %s %s", modeString (mode),
-                   uid, gid, size, timeString (mtime), name);
-       } else
-           printf ("%s", name);
+    if (extractFlag==FALSE) {
+       if (verboseFlag==TRUE) {
+           printf ("%s %3d/%-d ", modeString (mode), uid, gid);
+           if( S_ISCHR (mode) || S_ISBLK (mode) )
+               printf ("%4d,%4d %s ", major,minor, timeString (mtime));
+           else
+               printf ("%9ld %s ", size, timeString (mtime));
+       }
+       printf ("%s", outName);
 
        if (hardLink)
            printf (" (link to \"%s\")", hp->linkName);
        else if (softLink)
            printf (" (symlink to \"%s\")", hp->linkName);
-       else if (S_ISREG (mode)) {
-           inHeader = (size == 0);
+       else if (S_ISREG (mode) || S_ISCHR (mode) || S_ISBLK (mode) || 
+               S_ISSOCK(mode) || S_ISFIFO(mode) ) {
+           inHeader = (size == 0)? TRUE : FALSE;
            dataCc = size;
        }
 
@@ -483,63 +516,106 @@ readHeader (const TarHeader * hp, int fileCount, char **fileTable)
     /* 
      * We really want to extract the file.
      */
-    if (verboseFlag)
-       printf ("x %s\n", name);
+    if (verboseFlag==TRUE)
+       printf ("x %s\n", outName);
 
     if (hardLink) {
-       if (link (hp->linkName, name) < 0)
-           perror (name);
-
+       if (link (hp->linkName, outName) < 0)
+           perror (outName);
+       /* Set the file time */
+       utb.actime = mtime;
+       utb.modtime = mtime;
+       utime (outName, &utb);
+       /* Set the file permissions */
+       chown(outName, uid, gid);
+       chmod(outName, mode);
        return;
     }
 
     if (softLink) {
 #ifdef S_ISLNK
-       if (symlink (hp->linkName, name) < 0)
-           perror (name);
+       if (symlink (hp->linkName, outName) < 0)
+           perror (outName);
+       /* Try to change ownership of the symlink.
+        * If libs doesn't support that, don't bother.
+        * Changing the pointed-to file is the Wrong Thing(tm).
+        */
+#if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
+       lchown(outName, uid, gid);
+#endif
+
+       /* Do not change permissions or date on symlink,
+        * since it changes the pointed to file instead.  duh. */
 #else
        fprintf (stderr, "Cannot create symbolic links\n");
 #endif
        return;
     }
 
+    /* Set the umask for this process so it doesn't 
+     * screw things up. */
+    umask(0);
+
     /* 
      * If the file is a directory, then just create the path.
      */
     if (S_ISDIR (mode)) {
-       createPath (name, mode);
-
+       createPath (outName, mode);
+       /* Set the file time */
+       utb.actime = mtime;
+       utb.modtime = mtime;
+       utime (outName, &utb);
+       /* Set the file permissions */
+       chown(outName, uid, gid);
+       chmod(outName, mode);
        return;
     }
 
     /* 
      * There is a file to write.
-     * First create the path to it if necessary with a default permission.
+     * First create the path to it if necessary with default permissions.
      */
-    createPath (name, 0777);
+    createPath (outName, 0777);
 
-    inHeader = (size == 0);
+    inHeader = (size == 0)? TRUE : FALSE;
     dataCc = size;
 
     /* 
      * Start the output file.
      */
     if (tostdoutFlag == TRUE)
-       outFd = STDOUT;
-    else
-       outFd = open (name, O_WRONLY | O_CREAT | O_TRUNC, mode);
-
-    if (outFd < 0) {
-       perror (name);
-       skipFileFlag = TRUE;
-       return;
+       outFd = fileno(stdout);
+    else {
+       if ( S_ISCHR(mode) || S_ISBLK(mode) || S_ISSOCK(mode) ) {
+           devFileFlag = TRUE;
+           outFd = mknod (outName, mode, makedev(major, minor) );
+       }
+       else if (S_ISFIFO(mode) ) {
+           devFileFlag = TRUE;
+           outFd = mkfifo(outName, mode);
+       } else {
+           outFd = open (outName, O_WRONLY | O_CREAT | O_TRUNC, mode);
+       }
+       if (outFd < 0) {
+           perror (outName);
+           skipFileFlag = TRUE;
+           return;
+       }
+       /* Set the file time */
+       utb.actime = mtime;
+       utb.modtime = mtime;
+       utime (outName, &utb);
+       /* Set the file permissions */
+       chown(outName, uid, gid);
+       chmod(outName, mode);
     }
 
+
     /* 
      * If the file is empty, then that's all we need to do.
      */
-    if (size == 0 && tostdoutFlag == FALSE) {
-       (void) close (outFd);
+    if (size == 0 && (tostdoutFlag == FALSE) && (devFileFlag == FALSE)) {
+       close (outFd);
        outFd = -1;
     }
 }
@@ -564,7 +640,7 @@ static void readData (const char *cp, int count)
      * If we aren't extracting files or this file is being
      * skipped then do nothing more.
      */
-    if (!extractFlag || skipFileFlag)
+    if (extractFlag==FALSE || skipFileFlag==TRUE)
        return;
 
     /* 
@@ -573,7 +649,7 @@ static void readData (const char *cp, int count)
     if (fullWrite (outFd, cp, count) < 0) {
        perror (outName);
        if (tostdoutFlag == FALSE) {
-           (void) close (outFd);
+           close (outFd);
            outFd = -1;
        }
        skipFileFlag = TRUE;
@@ -581,13 +657,21 @@ static void readData (const char *cp, int count)
     }
 
     /* 
-     * If the write failed, close the file and disable further
-     * writes to this file.
+     * Check if we are done writing to the file now.
      */
     if (dataCc <= 0 && tostdoutFlag == FALSE) {
+       struct utimbuf utb;
        if (close (outFd))
            perror (outName);
 
+       /* Set the file time */
+       utb.actime = mtime;
+       utb.modtime = mtime;
+       utime (outName, &utb);
+       /* Set the file permissions */
+       chown(outName, uid, gid);
+       chmod(outName, mode);
+
        outFd = -1;
     }
 }
@@ -613,7 +697,7 @@ static void writeTarFile (int fileCount, char **fileTable)
      */
     if ((tarName == NULL) || !strcmp (tarName, "-")) {
        tostdoutFlag = TRUE;
-       tarFd = STDOUT;
+       tarFd = fileno(stdout);
     } else
        tarFd = open (tarName, O_WRONLY | O_CREAT | O_TRUNC, 0666);
 
@@ -634,12 +718,12 @@ static void writeTarFile (int fileCount, char **fileTable)
 
     tarDev = statbuf.st_dev;
     tarInode = statbuf.st_ino;
-
+               
     /* 
      * Append each file name into the archive file.
      * Follow symbolic links for these top level file names.
      */
-    while (!errorFlag && (fileCount-- > 0)) {
+    while (errorFlag==FALSE && (fileCount-- > 0)) {
        saveFile (*fileTable++, FALSE);
     }
 
@@ -668,10 +752,9 @@ static void writeTarFile (int fileCount, char **fileTable)
 static void saveFile (const char *fileName, int seeLinks)
 {
     int status;
-    int mode;
     struct stat statbuf;
 
-    if (verboseFlag)
+    if (verboseFlag==TRUE)
        printf ("a %s\n", fileName);
 
     /* 
@@ -687,7 +770,7 @@ static void saveFile (const char *fileName, int seeLinks)
      * Find out about the file.
      */
 #ifdef S_ISLNK
-    if (seeLinks)
+    if (seeLinks==TRUE)
        status = lstat (fileName, &statbuf);
     else
 #endif
@@ -718,12 +801,16 @@ static void saveFile (const char *fileName, int seeLinks)
 
        return;
     }
-
     if (S_ISREG (mode)) {
        saveRegularFile (fileName, &statbuf);
 
        return;
     }
+    
+    /* Some day add support for tarring these up... but not today. :) */
+//  if (S_ISLNK(mode) || S_ISFIFO(mode) || S_ISBLK(mode) || S_ISCHR (mode) ) {
+//     fprintf (stderr, "%s: This version of tar can't store this type of file\n", fileName);
+//  }
 
     /* 
      * The file is a strange type of file, ignore it.
@@ -787,7 +874,7 @@ saveRegularFile (const char *fileName, const struct stat *statbuf)
         */
        cc = 0;
 
-       if (!sawEof) {
+       if (sawEof==FALSE) {
            cc = fullRead (fileFd, data, dataCount);
 
            if (cc < 0) {
@@ -876,7 +963,7 @@ static void saveDirectory (const char *dirName, const struct stat *statbuf)
      * Read all of the directory entries and check them,
      * except for the current and parent directory entries.
      */
-    while (!errorFlag && ((entry = readdir (dir)) != NULL)) {
+    while (errorFlag==FALSE && ((entry = readdir (dir)) != NULL)) {
        if ((strcmp (entry->d_name, ".") == 0) ||
            (strcmp (entry->d_name, "..") == 0)) {
            continue;
@@ -975,7 +1062,7 @@ static void writeTarBlock (const char *buf, int len)
     /* 
      * If we had a write error before, then do nothing more.
      */
-    if (errorFlag)
+    if (errorFlag==TRUE)
        return;
 
     /*