]> git.saurik.com Git - apt.git/blobdiff - apt-pkg/contrib/fileutl.cc
- add a ReadLine method
[apt.git] / apt-pkg / contrib / fileutl.cc
index 95058cbdee77b036c42aaabfb6cbe0222259fd7a..58cd6dceb3637bccde9958156a40900b11b53fce 100644 (file)
@@ -24,6 +24,7 @@
 #include <apt-pkg/strutl.h>
 #include <apt-pkg/error.h>
 #include <apt-pkg/sptr.h>
+#include <apt-pkg/aptconfiguration.h>
 #include <apt-pkg/configuration.h>
 
 #include <cstdlib>
@@ -43,6 +44,8 @@
 #include <set>
 #include <algorithm>
 
+#include <zlib.h>
+
 #ifdef WORDS_BIGENDIAN
 #include <inttypes.h>
 #endif
 
 using namespace std;
 
+class FileFdPrivate {
+       public:
+       gzFile gz;
+       FileFdPrivate() : gz(NULL) {};
+};
+
 // RunScripts - Run a set of scripts from a configuration subtree      /*{{{*/
 // ---------------------------------------------------------------------
 /* */
@@ -718,84 +727,184 @@ bool ExecWait(pid_t Pid,const char *Name,bool Reap)
 // FileFd::Open - Open a file                                          /*{{{*/
 // ---------------------------------------------------------------------
 /* The most commonly used open mode combinations are given with Mode */
-bool FileFd::Open(string FileName,OpenMode Mode, unsigned long Perms)
+bool FileFd::Open(string FileName,OpenMode Mode,CompressMode Compress, unsigned long const Perms)
 {
+   if (Mode == ReadOnlyGzip)
+      return Open(FileName, ReadOnly, Gzip, Perms);
    Close();
+   d = new FileFdPrivate;
    Flags = AutoClose;
-   switch (Mode)
+
+   if (Compress == Auto && (Mode & WriteOnly) == WriteOnly)
+      return _error->Error("Autodetection on %s only works in ReadOnly openmode!", FileName.c_str());
+   if ((Mode & WriteOnly) != WriteOnly && (Mode & (Atomic | Create | Empty | Exclusive)) != 0)
+      return _error->Error("ReadOnly mode for %s doesn't accept additional flags!", 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);
+   else return _error->Error("No openmode provided in FileFd::Open for %s", FileName.c_str());
+
+   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
+
+   // FIXME: Denote inbuilt compressors somehow - as we don't need to have the binaries for them
+   std::vector<APT::Configuration::Compressor> const compressors = APT::Configuration::getCompressors();
+   std::vector<APT::Configuration::Compressor>::const_iterator compressor = compressors.begin();
+   if (Compress == Auto)
    {
-      case ReadOnly:
-      iFd = open(FileName.c_str(),O_RDONLY);
-      break;
-
-      case ReadOnlyGzip:
-      iFd = open(FileName.c_str(),O_RDONLY);
-      if (iFd > 0) {
-        gz = gzdopen (iFd, "r");
-        if (gz == NULL) {
-            close (iFd);
-            iFd = -1;
-        }
-      }
-      break;
-      
-      case WriteAtomic:
+      Compress = None;
+      for (; compressor != compressors.end(); ++compressor)
       {
-        Flags |= Replace;
-        char *name = strdup((FileName + ".XXXXXX").c_str());
-        TemporaryFileName = string(mktemp(name));
-        iFd = open(TemporaryFileName.c_str(),O_RDWR | O_CREAT | O_EXCL,Perms);
-        free(name);
+        std::string file = std::string(FileName).append(compressor->Extension);
+        if (FileExists(file) == false)
+           continue;
+        FileName = file;
+        if (compressor->Binary == ".")
+           Compress = None;
+        else
+           Compress = Extension;
         break;
       }
-
-      case WriteEmpty:
+   }
+   else if (Compress == Extension)
+   {
+      Compress = None;
+      std::string ext = flExtension(FileName);
+      if (ext != FileName)
       {
-        struct stat Buf;
-        if (lstat(FileName.c_str(),&Buf) == 0 && S_ISLNK(Buf.st_mode))
-           unlink(FileName.c_str());
-        iFd = open(FileName.c_str(),O_RDWR | O_CREAT | O_TRUNC,Perms);
-        break;
+        ext = "." + ext;
+        for (; compressor != compressors.end(); ++compressor)
+           if (ext == compressor->Extension)
+              break;
       }
-      
-      case WriteExists:
-      iFd = open(FileName.c_str(),O_RDWR);
-      break;
+   }
+   else if (Compress != None)
+   {
+      std::string name;
+      switch (Compress)
+      {
+      case Gzip: name = "gzip"; break;
+      case Bzip2: name = "bzip2"; break;
+      case Lzma: name = "lzma"; break;
+      case Xz: name = "xz"; break;
+      default: return _error->Error("Can't find a match for specified compressor mode for file %s", FileName.c_str());
+      }
+      for (; compressor != compressors.end(); ++compressor)
+        if (compressor->Name == name)
+           break;
+      if (compressor == compressors.end() && name != "gzip")
+        return _error->Error("Can't find a configured compressor %s for file %s", name.c_str(), FileName.c_str());
+   }
 
-      case WriteAny:
-      iFd = open(FileName.c_str(),O_RDWR | O_CREAT,Perms);
-      break;      
+   // if we have them, use inbuilt compressors instead of forking
+   if (compressor != compressors.end())
+   {
+      if (compressor->Name == "gzip")
+      {
+        Compress = Gzip;
+        compressor = compressors.end();
+      }
+      else if (compressor->Name == "." || Compress == None)
+      {
+        Compress = None;
+        compressor = compressors.end();
+      }
+   }
 
-      case WriteTemp:
+   if ((Mode & Atomic) == Atomic)
+   {
+      Flags |= Replace;
+      char *name = strdup((FileName + ".XXXXXX").c_str());
+      TemporaryFileName = string(mktemp(name));
+      free(name);
+   }
+   else if ((Mode & (Exclusive | Create)) == (Exclusive | Create))
+   {
+      // for atomic, this will be done by rename in Close()
       unlink(FileName.c_str());
-      iFd = open(FileName.c_str(),O_RDWR | O_CREAT | O_EXCL,Perms);
-      break;
-   }  
+   }
+   if ((Mode & Empty) == Empty)
+   {
+      struct stat Buf;
+      if (lstat(FileName.c_str(),&Buf) == 0 && S_ISLNK(Buf.st_mode))
+        unlink(FileName.c_str());
+   }
+
+   if (compressor != compressors.end())
+   {
+      if ((Mode & ReadWrite) == ReadWrite)
+        _error->Error("External compressors like %s do not support readwrite mode for file %s", compressor->Name.c_str(), FileName.c_str());
+
+      _error->Error("Forking external compressor %s is not implemented for %s", compressor->Name.c_str(), FileName.c_str());
+   }
+   else
+   {
+      if (TemporaryFileName.empty() == false)
+        iFd = open(TemporaryFileName.c_str(), fileflags, Perms);
+      else
+        iFd = open(FileName.c_str(), fileflags, Perms);
+
+      if (iFd != -1)
+      {
+        if (OpenInternDescriptor(Mode, Compress) == false)
+        {
+           close (iFd);
+           iFd = -1;
+        }
+      }
+   }
 
-   if (iFd < 0)
+   if (iFd == -1)
       return _error->Errno("open",_("Could not open file %s"),FileName.c_str());
-   
+
    this->FileName = FileName;
    SetCloseExec(iFd,true);
    return true;
 }
-
-bool FileFd::OpenDescriptor(int Fd, OpenMode Mode, bool AutoClose)
+                                                                       /*}}}*/
+// FileFd::OpenDescriptor - Open a filedescriptor                      /*{{{*/
+// ---------------------------------------------------------------------
+/* */
+bool FileFd::OpenDescriptor(int Fd, OpenMode Mode, CompressMode Compress, bool AutoClose)
 {
    Close();
+   d = new FileFdPrivate;
    Flags = (AutoClose) ? FileFd::AutoClose : 0;
    iFd = Fd;
-   if (Mode == ReadOnlyGzip) {
-      gz = gzdopen (iFd, "r");
-      if (gz == NULL) {
-        if (AutoClose)
-           close (iFd);
-        return _error->Errno("gzdopen",_("Could not open file descriptor %d"),
-                             Fd);
-      }
+   if (OpenInternDescriptor(Mode, Compress) == false)
+   {
+      if (AutoClose)
+        close (iFd);
+      return _error->Errno("gzdopen",_("Could not open file descriptor %d"), Fd);
    }
    this->FileName = "";
    return true;
+}
+bool FileFd::OpenInternDescriptor(OpenMode Mode, CompressMode Compress)
+{
+   if (Compress == None)
+      return true;
+   else if (Compress == Gzip)
+   {
+      if ((Mode & ReadWrite) == ReadWrite)
+        d->gz = gzdopen(iFd, "r+");
+      else if ((Mode & WriteOnly) == WriteOnly)
+        d->gz = gzdopen(iFd, "w");
+      else
+        d->gz = gzdopen (iFd, "r");
+      if (d->gz == NULL)
+        return false;
+      Flags |= Compressed;
+   }
+   else
+      return false;
+   return true;
 }
                                                                        /*}}}*/
 // FileFd::~File - Closes the file                                     /*{{{*/
@@ -820,8 +929,8 @@ bool FileFd::Read(void *To,unsigned long long Size,unsigned long long *Actual)
    
    do
    {
-      if (gz != NULL)
-         Res = gzread(gz,To,Size);
+      if (d->gz != NULL)
+         Res = gzread(d->gz,To,Size);
       else
          Res = read(iFd,To,Size);
       if (Res < 0 && errno == EINTR)
@@ -853,6 +962,28 @@ bool FileFd::Read(void *To,unsigned long long Size,unsigned long long *Actual)
    return _error->Error(_("read, still have %llu to read but none left"), Size);
 }
                                                                        /*}}}*/
+// FileFd::ReadLine - Read a complete line from the file               /*{{{*/
+// ---------------------------------------------------------------------
+/* Beware: This method can be quiet slow for big buffers on UNcompressed
+   files because of the naive implementation! */
+char* FileFd::ReadLine(char *To, unsigned long long const Size)
+{
+   if (d->gz != NULL)
+      return gzgets(d->gz, To, Size);
+
+   unsigned long long read = 0;
+   if (Read(To, Size, &read) == false)
+      return NULL;
+   char* c = To;
+   for (; *c != '\n' && *c != '\0' && read != 0; --read, ++c)
+      ; // find the end of the line
+   if (*c != '\0')
+      *c = '\0';
+   if (read != 0)
+      Seek(Tell() - read);
+   return To;
+}
+                                                                       /*}}}*/
 // FileFd::Write - Write to the file                                   /*{{{*/
 // ---------------------------------------------------------------------
 /* */
@@ -862,8 +993,8 @@ bool FileFd::Write(const void *From,unsigned long long Size)
    errno = 0;
    do
    {
-      if (gz != NULL)
-         Res = gzwrite(gz,From,Size);
+      if (d->gz != NULL)
+         Res = gzwrite(d->gz,From,Size);
       else
          Res = write(iFd,From,Size);
       if (Res < 0 && errno == EINTR)
@@ -892,8 +1023,8 @@ bool FileFd::Write(const void *From,unsigned long long Size)
 bool FileFd::Seek(unsigned long long To)
 {
    int res;
-   if (gz)
-      res = gzseek(gz,To,SEEK_SET);
+   if (d->gz)
+      res = gzseek(d->gz,To,SEEK_SET);
    else
       res = lseek(iFd,To,SEEK_SET);
    if (res != (signed)To)
@@ -911,8 +1042,8 @@ bool FileFd::Seek(unsigned long long To)
 bool FileFd::Skip(unsigned long long Over)
 {
    int res;
-   if (gz)
-      res = gzseek(gz,Over,SEEK_CUR);
+   if (d->gz != NULL)
+      res = gzseek(d->gz,Over,SEEK_CUR);
    else
       res = lseek(iFd,Over,SEEK_CUR);
    if (res < 0)
@@ -929,7 +1060,7 @@ bool FileFd::Skip(unsigned long long Over)
 /* */
 bool FileFd::Truncate(unsigned long long To)
 {
-   if (gz)
+   if (d->gz != NULL)
    {
       Flags |= Fail;
       return _error->Error("Truncating gzipped files is not implemented (%s)", FileName.c_str());
@@ -949,8 +1080,8 @@ bool FileFd::Truncate(unsigned long long To)
 unsigned long long FileFd::Tell()
 {
    off_t Res;
-   if (gz)
-     Res = gztell(gz);
+   if (d->gz != NULL)
+     Res = gztell(d->gz);
    else
      Res = lseek(iFd,0,SEEK_CUR);
    if (Res == (off_t)-1)
@@ -978,9 +1109,9 @@ unsigned long long FileFd::Size()
    unsigned long long size = FileSize();
 
    // only check gzsize if we are actually a gzip file, just checking for
-   // "gz" is not sufficient as uncompressed files will be opened with
+   // "gz" is not sufficient as uncompressed files could be opened with
    // gzopen in "direct" mode as well
-   if (gz && !gzdirect(gz) && size > 0)
+   if (d->gz && !gzdirect(d->gz) && size > 0)
    {
        /* unfortunately zlib.h doesn't provide a gzsize(), so we have to do
        * this ourselves; the original (uncompressed) file size is the last 32
@@ -1008,16 +1139,33 @@ unsigned long long FileFd::Size()
    return size;
 }
                                                                        /*}}}*/
+// FileFd::ModificationTime - Return the time of last touch            /*{{{*/
+// ---------------------------------------------------------------------
+/* */
+time_t FileFd::ModificationTime()
+{
+   struct stat Buf;
+   if (fstat(iFd,&Buf) != 0)
+   {
+      _error->Errno("fstat","Unable to determine the modification time of file %s", FileName.c_str());
+      return 0;
+   }
+   return Buf.st_mtime;
+}
+                                                                       /*}}}*/
 // FileFd::Close - Close the file if the close flag is set             /*{{{*/
 // ---------------------------------------------------------------------
 /* */
 bool FileFd::Close()
 {
+   if (iFd == -1)
+      return true;
+
    bool Res = true;
    if ((Flags & AutoClose) == AutoClose)
    {
-      if (gz != NULL) {
-        int const e = gzclose(gz);
+      if (d != NULL && d->gz != NULL) {
+        int const e = gzclose(d->gz);
         // gzdopen() on empty files always fails with "buffer error" here, ignore that
         if (e != 0 && e != Z_BUF_ERROR)
            Res &= _error->Errno("close",_("Problem closing the gzip file %s"), FileName.c_str());
@@ -1031,16 +1179,21 @@ bool FileFd::Close()
         Res &= _error->Errno("rename",_("Problem renaming the file %s to %s"), TemporaryFileName.c_str(), FileName.c_str());
 
       FileName = TemporaryFileName; // for the unlink() below.
+      TemporaryFileName.clear();
    }
 
    iFd = -1;
-   gz = NULL;
 
    if ((Flags & Fail) == Fail && (Flags & DelOnFail) == DelOnFail &&
        FileName.empty() == false)
       if (unlink(FileName.c_str()) != 0)
         Res &= _error->WarningE("unlnk",_("Problem unlinking the file %s"), FileName.c_str());
 
+   if (d != NULL)
+   {
+      delete d;
+      d = NULL;
+   }
 
    return Res;
 }
@@ -1057,3 +1210,4 @@ bool FileFd::Sync()
    return true;
 }
                                                                        /*}}}*/
+gzFile FileFd::gzFd() {return d->gz;};