]> git.saurik.com Git - apt.git/blobdiff - apt-pkg/contrib/fileutl.cc
try to avoid direct usage of .Fd() if possible and do read()s and co
[apt.git] / apt-pkg / contrib / fileutl.cc
index c2b6840890eeeed2840a667edcbabf9ff82d3ba9..bb836e93be46e602c0e93c94a0ac19ffe1e4de51 100644 (file)
@@ -50,6 +50,8 @@
 #define APT_USE_ZLIB 1
 #if APT_USE_ZLIB
 #include <zlib.h>
+#else
+#pragma message "Usage of zlib is DISABLED!"
 #endif
 
 #ifdef WORDS_BIGENDIAN
@@ -68,11 +70,14 @@ class FileFdPrivate {
 #else
        void* gz;
 #endif
+       int compressed_fd;
        pid_t compressor_pid;
        bool pipe;
        APT::Configuration::Compressor compressor;
-       FileFd::OpenMode openmode;
-       FileFdPrivate() : gz(NULL), compressor_pid(-1), pipe(false) {};
+       unsigned int openmode;
+       unsigned long long seekpos;
+       FileFdPrivate() : gz(NULL), compressed_fd(-1), compressor_pid(-1), pipe(false),
+                         openmode(0), seekpos(0) {};
 };
 
 // RunScripts - Run a set of scripts from a configuration subtree      /*{{{*/
@@ -738,179 +743,10 @@ bool ExecWait(pid_t Pid,const char *Name,bool Reap)
 }
                                                                        /*}}}*/
 
-// ExecCompressor - Open a de/compressor pipe                          /*{{{*/
-// ---------------------------------------------------------------------
-/* This opens the compressor, either in compress mode or decompress
-   mode. FileFd is always the compressor input/output file,
-   OutFd is the created pipe, Input for Compress, Output for Decompress. */
-bool ExecCompressor(APT::Configuration::Compressor const &Prog,
-                   pid_t *Pid, int const FileFd, int &OutFd, bool const Comp)
-{
-   if (Pid != NULL)
-      *Pid = -1;
-
-   // No compression
-   if (Prog.Binary.empty() == true)
-   {
-      OutFd = dup(FileFd);
-      return true;
-   }
-
-   // Handle 'decompression' of empty files
-   if (Comp == false)
-   {
-      struct stat Buf;
-      fstat(FileFd, &Buf);
-      if (Buf.st_size == 0 && S_ISFIFO(Buf.st_mode) == false)
-      {
-        OutFd = FileFd;
-        return true;
-      }
-   }
-
-   // Create a data pipe
-   int Pipe[2] = {-1,-1};
-   if (pipe(Pipe) != 0)
-      return _error->Errno("pipe",_("Failed to create subprocess IPC"));
-   for (int J = 0; J != 2; J++)
-      SetCloseExec(Pipe[J],true);
-
-   if (Comp == true)
-      OutFd = Pipe[1];
-   else
-      OutFd = Pipe[0];
-
-   // The child..
-   pid_t child = ExecFork();
-   if (Pid != NULL)
-      *Pid = child;
-   if (child == 0)
-   {
-      if (Comp == true)
-      {
-        dup2(FileFd,STDOUT_FILENO);
-        dup2(Pipe[0],STDIN_FILENO);
-      }
-      else
-      {
-        dup2(FileFd,STDIN_FILENO);
-        dup2(Pipe[1],STDOUT_FILENO);
-      }
-
-      SetCloseExec(STDOUT_FILENO,false);
-      SetCloseExec(STDIN_FILENO,false);
-
-      std::vector<char const*> Args;
-      Args.push_back(Prog.Binary.c_str());
-      std::vector<std::string> const * const addArgs =
-               (Comp == true) ? &(Prog.CompressArgs) : &(Prog.UncompressArgs);
-      for (std::vector<std::string>::const_iterator a = addArgs->begin();
-          a != addArgs->end(); ++a)
-        Args.push_back(a->c_str());
-      Args.push_back(NULL);
-
-      execvp(Args[0],(char **)&Args[0]);
-      cerr << _("Failed to exec compressor ") << Args[0] << endl;
-      _exit(100);
-   }
-   if (Comp == true)
-      close(Pipe[0]);
-   else
-      close(Pipe[1]);
-
-   if (Pid == NULL)
-      ExecWait(child, Prog.Binary.c_str(), true);
-
-   return true;
-}
-bool ExecCompressor(APT::Configuration::Compressor const &Prog,
-                   pid_t *Pid, std::string const &FileName, int &OutFd, bool const Comp)
-{
-   if (Pid != NULL)
-      *Pid = -1;
-
-   // No compression
-   if (Prog.Binary.empty() == true)
-   {
-      if (Comp == true)
-        OutFd = open(FileName.c_str(), O_WRONLY, 0666);
-      else
-        OutFd = open(FileName.c_str(), O_RDONLY);
-      return true;
-   }
-
-   // Handle 'decompression' of empty files
-   if (Comp == false)
-   {
-      struct stat Buf;
-      stat(FileName.c_str(), &Buf);
-      if (Buf.st_size == 0)
-      {
-        OutFd = open(FileName.c_str(), O_RDONLY);
-        return true;
-      }
-   }
-
-   // Create a data pipe
-   int Pipe[2] = {-1,-1};
-   if (pipe(Pipe) != 0)
-      return _error->Errno("pipe",_("Failed to create subprocess IPC"));
-   for (int J = 0; J != 2; J++)
-      SetCloseExec(Pipe[J],true);
-
-   if (Comp == true)
-      OutFd = Pipe[1];
-   else
-      OutFd = Pipe[0];
-
-   // The child..
-   pid_t child = ExecFork();
-   if (Pid != NULL)
-      *Pid = child;
-   if (child == 0)
-   {
-      if (Comp == true)
-      {
-        dup2(Pipe[0],STDIN_FILENO);
-        SetCloseExec(STDIN_FILENO,false);
-      }
-      else
-      {
-        dup2(Pipe[1],STDOUT_FILENO);
-        SetCloseExec(STDOUT_FILENO,false);
-      }
-
-      std::vector<char const*> Args;
-      Args.push_back(Prog.Binary.c_str());
-      std::vector<std::string> const * const addArgs =
-               (Comp == true) ? &(Prog.CompressArgs) : &(Prog.UncompressArgs);
-      for (std::vector<std::string>::const_iterator a = addArgs->begin();
-          a != addArgs->end(); ++a)
-        Args.push_back(a->c_str());
-      Args.push_back("--stdout");
-      Args.push_back(FileName.c_str());
-      Args.push_back(NULL);
-
-      execvp(Args[0],(char **)&Args[0]);
-      cerr << _("Failed to exec compressor ") << Args[0] << endl;
-      _exit(100);
-   }
-   if (Comp == true)
-      close(Pipe[0]);
-   else
-      close(Pipe[1]);
-
-   if (Pid == NULL)
-      ExecWait(child, Prog.Binary.c_str(), false);
-
-   return true;
-}
-                                                                       /*}}}*/
-
 // FileFd::Open - Open a file                                          /*{{{*/
 // ---------------------------------------------------------------------
 /* The most commonly used open mode combinations are given with Mode */
-bool FileFd::Open(string FileName,OpenMode Mode,CompressMode Compress, unsigned long const Perms)
+bool FileFd::Open(string FileName,unsigned int const Mode,CompressMode Compress, unsigned long const Perms)
 {
    if (Mode == ReadOnlyGzip)
       return Open(FileName, ReadOnly, Gzip, Perms);
@@ -934,11 +770,20 @@ bool FileFd::Open(string FileName,OpenMode Mode,CompressMode Compress, unsigned
    }
    else if (Compress == Extension)
    {
-      std::string ext = flExtension(FileName);
-      if (ext == FileName)
-        ext.clear();
-      else
-        ext = "." + ext;
+      std::string::size_type const found = FileName.find_last_of('.');
+      std::string ext;
+      if (found != std::string::npos)
+      {
+        ext = FileName.substr(found);
+        if (ext == ".new" || ext == ".bak")
+        {
+           std::string::size_type const found2 = FileName.find_last_of('.', found - 1);
+           if (found2 != std::string::npos)
+              ext = FileName.substr(found2, found - found2);
+           else
+              ext.clear();
+        }
+      }
       for (; compressor != compressors.end(); ++compressor)
         if (ext == compressor->Extension)
            break;
@@ -960,8 +805,8 @@ bool FileFd::Open(string FileName,OpenMode Mode,CompressMode Compress, unsigned
       case Xz: name = "xz"; break;
       case Auto:
       case Extension:
-         // Unreachable
-         return _error->Error("Opening File %s in None, Auto or Extension should be already handled?!?", FileName.c_str());
+        // Unreachable
+        return _error->Error("Opening File %s in None, Auto or Extension should be already handled?!?", FileName.c_str());
       }
       for (; compressor != compressors.end(); ++compressor)
         if (compressor->Name == name)
@@ -974,7 +819,7 @@ bool FileFd::Open(string FileName,OpenMode Mode,CompressMode Compress, unsigned
       return _error->Error("Can't find a match for specified compressor mode for file %s", FileName.c_str());
    return Open(FileName, Mode, *compressor, Perms);
 }
-bool FileFd::Open(string FileName,OpenMode Mode,APT::Configuration::Compressor const &compressor, unsigned long const Perms)
+bool FileFd::Open(string FileName,unsigned int const Mode,APT::Configuration::Compressor const &compressor, unsigned long const Perms)
 {
    Close();
    d = new FileFdPrivate;
@@ -1005,53 +850,33 @@ bool FileFd::Open(string FileName,OpenMode Mode,APT::Configuration::Compressor c
         unlink(FileName.c_str());
    }
 
-   // if we have them, use inbuilt compressors instead of forking
-   if (compressor.Name != "."
-#if APT_USE_ZLIB
-       && compressor.Name != "gzip"
-#endif
-      )
-   {
-      if ((Mode & ReadWrite) == ReadWrite)
-        return _error->Error("External compressors like %s do not support readwrite mode for file %s", compressor.Name.c_str(), FileName.c_str());
+   int fileflags = 0;
+   #define if_FLAGGED_SET(FLAG, MODE) if ((Mode & FLAG) == FLAG) fileflags |= MODE
+   if_FLAGGED_SET(ReadWrite, O_RDWR);
+   else if_FLAGGED_SET(ReadOnly, O_RDONLY);
+   else if_FLAGGED_SET(WriteOnly, O_WRONLY);
 
-      if (ExecCompressor(compressor, NULL /*d->compressor_pid*/, FileName, iFd, ((Mode & ReadOnly) != ReadOnly)) == false)
-         return _error->Error("Forking external compressor %s is not implemented for %s", compressor.Name.c_str(), FileName.c_str());
-      d->pipe = true;
-      d->compressor = compressor;
-   }
-   else
-   {
-      int fileflags = 0;
-      #define if_FLAGGED_SET(FLAG, MODE) if ((Mode & FLAG) == FLAG) fileflags |= MODE
-      if_FLAGGED_SET(ReadWrite, O_RDWR);
-      else if_FLAGGED_SET(ReadOnly, O_RDONLY);
-      else if_FLAGGED_SET(WriteOnly, O_WRONLY);
-
-      if_FLAGGED_SET(Create, O_CREAT);
-      if_FLAGGED_SET(Exclusive, O_EXCL);
-      else if_FLAGGED_SET(Atomic, O_EXCL);
-      if_FLAGGED_SET(Empty, O_TRUNC);
-      #undef if_FLAGGED_SET
+   if_FLAGGED_SET(Create, O_CREAT);
+   if_FLAGGED_SET(Empty, O_TRUNC);
+   if_FLAGGED_SET(Exclusive, O_EXCL);
+   else if_FLAGGED_SET(Atomic, O_EXCL);
+   #undef if_FLAGGED_SET
 
-      if (TemporaryFileName.empty() == false)
-        iFd = open(TemporaryFileName.c_str(), fileflags, Perms);
-      else
-        iFd = open(FileName.c_str(), fileflags, Perms);
+   if (TemporaryFileName.empty() == false)
+      iFd = open(TemporaryFileName.c_str(), fileflags, Perms);
+   else
+      iFd = open(FileName.c_str(), fileflags, Perms);
 
+   if (iFd == -1 || OpenInternDescriptor(Mode, compressor) == false)
+   {
       if (iFd != -1)
       {
-        if (OpenInternDescriptor(Mode, compressor) == false)
-        {
-           close (iFd);
-           iFd = -1;
-        }
+        close (iFd);
+        iFd = -1;
       }
+      return _error->Errno("open",_("Could not open file %s"), FileName.c_str());
    }
 
-   if (iFd == -1)
-      return _error->Errno("open",_("Could not open file %s"),FileName.c_str());
-
    this->FileName = FileName;
    SetCloseExec(iFd,true);
    return true;
@@ -1060,7 +885,7 @@ bool FileFd::Open(string FileName,OpenMode Mode,APT::Configuration::Compressor c
 // FileFd::OpenDescriptor - Open a filedescriptor                      /*{{{*/
 // ---------------------------------------------------------------------
 /* */
-bool FileFd::OpenDescriptor(int Fd, OpenMode Mode, CompressMode Compress, bool AutoClose)
+bool FileFd::OpenDescriptor(int Fd, unsigned int const Mode, CompressMode Compress, bool AutoClose)
 {
    std::vector<APT::Configuration::Compressor> const compressors = APT::Configuration::getCompressors();
    std::vector<APT::Configuration::Compressor>::const_iterator compressor = compressors.begin();
@@ -1084,7 +909,7 @@ bool FileFd::OpenDescriptor(int Fd, OpenMode Mode, CompressMode Compress, bool A
 
    return OpenDescriptor(Fd, Mode, *compressor, AutoClose);
 }
-bool FileFd::OpenDescriptor(int Fd, OpenMode Mode, APT::Configuration::Compressor const &compressor, bool AutoClose)
+bool FileFd::OpenDescriptor(int Fd, unsigned int const Mode, APT::Configuration::Compressor const &compressor, bool AutoClose)
 {
    Close();
    d = new FileFdPrivate;
@@ -1100,9 +925,10 @@ bool FileFd::OpenDescriptor(int Fd, OpenMode Mode, APT::Configuration::Compresso
    this->FileName = "";
    return true;
 }
-bool FileFd::OpenInternDescriptor(OpenMode Mode, APT::Configuration::Compressor const &compressor)
+bool FileFd::OpenInternDescriptor(unsigned int const Mode, APT::Configuration::Compressor const &compressor)
 {
-   if (compressor.Name == ".")
+   d->compressor = compressor;
+   if (compressor.Name == "." || compressor.Binary.empty() == true)
       return true;
 #if APT_USE_ZLIB
    else if (compressor.Name == "gzip")
@@ -1116,10 +942,90 @@ bool FileFd::OpenInternDescriptor(OpenMode Mode, APT::Configuration::Compressor
       if (d->gz == NULL)
         return false;
       Flags |= Compressed;
+      return true;
    }
 #endif
+
+   if ((Mode & ReadWrite) == ReadWrite)
+      return _error->Error("ReadWrite mode is not supported for file %s", FileName.c_str());
+
+   bool const Comp = (Mode & WriteOnly) == WriteOnly;
+   // Handle 'decompression' of empty files
+   if (Comp == false)
+   {
+      struct stat Buf;
+      fstat(iFd, &Buf);
+      if (Buf.st_size == 0 && S_ISFIFO(Buf.st_mode) == false)
+        return true;
+
+      // We don't need the file open - instead let the compressor open it
+      // as he properly knows better how to efficiently read from 'his' file
+      if (FileName.empty() == false)
+        close(iFd);
+   }
+
+   // Create a data pipe
+   int Pipe[2] = {-1,-1};
+   if (pipe(Pipe) != 0)
+      return _error->Errno("pipe",_("Failed to create subprocess IPC"));
+   for (int J = 0; J != 2; J++)
+      SetCloseExec(Pipe[J],true);
+
+   d->compressed_fd = iFd;
+   d->pipe = true;
+
+   if (Comp == true)
+      iFd = Pipe[1];
    else
-      return _error->Error("Can't find a match for specified compressor %s for file %s", compressor.Name.c_str(), FileName.c_str());
+      iFd = Pipe[0];
+
+   // The child..
+   d->compressor_pid = ExecFork();
+   if (d->compressor_pid == 0)
+   {
+      if (Comp == true)
+      {
+        dup2(d->compressed_fd,STDOUT_FILENO);
+        dup2(Pipe[0],STDIN_FILENO);
+      }
+      else
+      {
+        if (FileName.empty() == true)
+           dup2(d->compressed_fd,STDIN_FILENO);
+        dup2(Pipe[1],STDOUT_FILENO);
+      }
+
+      SetCloseExec(STDOUT_FILENO,false);
+      SetCloseExec(STDIN_FILENO,false);
+
+      std::vector<char const*> Args;
+      Args.push_back(compressor.Binary.c_str());
+      std::vector<std::string> const * const addArgs =
+               (Comp == true) ? &(compressor.CompressArgs) : &(compressor.UncompressArgs);
+      for (std::vector<std::string>::const_iterator a = addArgs->begin();
+          a != addArgs->end(); ++a)
+        Args.push_back(a->c_str());
+      if (Comp == false && FileName.empty() == false)
+      {
+        Args.push_back("--stdout");
+        if (TemporaryFileName.empty() == false)
+           Args.push_back(TemporaryFileName.c_str());
+        else
+           Args.push_back(FileName.c_str());
+      }
+      Args.push_back(NULL);
+
+      execvp(Args[0],(char **)&Args[0]);
+      cerr << _("Failed to exec compressor ") << Args[0] << endl;
+      _exit(100);
+   }
+   if (Comp == true)
+      close(Pipe[0]);
+   else
+      close(Pipe[1]);
+   if (Comp == true || FileName.empty() == true)
+      close(d->compressed_fd);
+
    return true;
 }
                                                                        /*}}}*/
@@ -1161,6 +1067,7 @@ bool FileFd::Read(void *To,unsigned long long Size,unsigned long long *Actual)
       
       To = (char *)To + Res;
       Size -= Res;
+      d->seekpos += Res;
       if (Actual != 0)
         *Actual += Res;
    }
@@ -1230,6 +1137,7 @@ bool FileFd::Write(const void *From,unsigned long long Size)
       
       From = (char *)From + Res;
       Size -= Res;
+      d->seekpos += Res;
    }
    while (Res > 0 && Size > 0);
    
@@ -1247,12 +1155,38 @@ bool FileFd::Seek(unsigned long long To)
 {
    if (d->pipe == true)
    {
-      // FIXME: What about OpenDescriptor() stuff here?
+      // Our poor man seeking in pipes is costly, so try to avoid it
+      unsigned long long seekpos = Tell();
+      if (seekpos == To)
+        return true;
+      else if (seekpos < To)
+        return Skip(To - seekpos);
+
+      if ((d->openmode & ReadOnly) != ReadOnly)
+        return _error->Error("Reopen is only implemented for read-only files!");
       close(iFd);
-      bool result = ExecCompressor(d->compressor, NULL, FileName, iFd, (d->openmode & ReadOnly) != ReadOnly);
-      if (result == true && To != 0)
-        result &= Skip(To);
-      return result;
+      iFd = 0;
+      if (TemporaryFileName.empty() == false)
+        iFd = open(TemporaryFileName.c_str(), O_RDONLY);
+      else if (FileName.empty() == false)
+        iFd = open(FileName.c_str(), O_RDONLY);
+      else
+      {
+        if (d->compressed_fd > 0)
+           if (lseek(d->compressed_fd, 0, SEEK_SET) != 0)
+              iFd = d->compressed_fd;
+        if (iFd <= 0)
+           return _error->Error("Reopen is not implemented for pipes opened with FileFd::OpenDescriptor()!");
+      }
+
+      if (OpenInternDescriptor(d->openmode, d->compressor) == false)
+        return _error->Error("Seek on file %s because it couldn't be reopened", FileName.c_str());
+
+      if (To != 0)
+        return Skip(To);
+
+      d->seekpos = To;
+      return true;
    }
    int res;
 #if APT_USE_ZLIB
@@ -1266,7 +1200,8 @@ bool FileFd::Seek(unsigned long long To)
       Flags |= Fail;
       return _error->Error("Unable to seek to %llu", To);
    }
-   
+
+   d->seekpos = To;
    return true;
 }
                                                                        /*}}}*/
@@ -1287,7 +1222,8 @@ bool FileFd::Skip(unsigned long long Over)
       Flags |= Fail;
       return _error->Error("Unable to seek ahead %llu",Over);
    }
-   
+   d->seekpos = res;
+
    return true;
 }
                                                                        /*}}}*/
@@ -1315,6 +1251,13 @@ bool FileFd::Truncate(unsigned long long To)
 /* */
 unsigned long long FileFd::Tell()
 {
+   // In theory, we could just return seekpos here always instead of
+   // seeking around, but not all users of FileFd use always Seek() and co
+   // so d->seekpos isn't always true and we can just use it as a hint if
+   // we have nothing else, but not always as an authority…
+   if (d->pipe == true)
+      return d->seekpos;
+
    off_t Res;
 #if APT_USE_ZLIB
    if (d->gz != NULL)
@@ -1324,6 +1267,7 @@ unsigned long long FileFd::Tell()
      Res = lseek(iFd,0,SEEK_CUR);
    if (Res == (off_t)-1)
       _error->Errno("lseek","Failed to determine the current file position");
+   d->seekpos = Res;
    return Res;
 }
                                                                        /*}}}*/
@@ -1360,15 +1304,14 @@ unsigned long long FileFd::Size()
    // so we 'read' the content and 'seek' back - see there
    if (d->pipe == true)
    {
-      // FIXME: If we have read first and then FileSize() the report is wrong
-      size = 0;
+      unsigned long long const oldSeek = Tell();
       char ignore[1000];
       unsigned long long read = 0;
       do {
         Read(ignore, sizeof(ignore), &read);
-        size += read;
       } while(read != 0);
-      Seek(0);
+      size = Tell();
+      Seek(oldSeek);
    }
 #if APT_USE_ZLIB
    // only check gzsize if we are actually a gzip file, just checking for
@@ -1380,7 +1323,6 @@ unsigned long long FileFd::Size()
        * this ourselves; the original (uncompressed) file size is the last 32
        * bits of the file */
        // FIXME: Size for gz-files is limited by 32bit… no largefile support
-       off_t orig_pos = lseek(iFd, 0, SEEK_CUR);
        if (lseek(iFd, -4, SEEK_END) < 0)
           return _error->Errno("lseek","Unable to seek to end of gzipped file");
        size = 0L;
@@ -1394,7 +1336,7 @@ unsigned long long FileFd::Size()
        size = tmp_size;
 #endif
 
-       if (lseek(iFd, orig_pos, SEEK_SET) < 0)
+       if (lseek(iFd, d->seekpos, SEEK_SET) < 0)
           return _error->Errno("lseek","Unable to seek in gzipped file");
        return size;
    }
@@ -1471,8 +1413,8 @@ bool FileFd::Close()
 
    if (d != NULL)
    {
-//      if (d->compressor_pid != -1)
-//      ExecWait(d->compressor_pid, "FileFdCompressor", true);
+      if (d->compressor_pid > 0)
+        ExecWait(d->compressor_pid, "FileFdCompressor", true);
       delete d;
       d = NULL;
    }