keep track of where we are in a filedescriptor so we can use it as Tell()
[ntk/apt.git] / apt-pkg / acquire-item.cc
index 39b9fef..453fce1 100644 (file)
@@ -13,6 +13,8 @@
    ##################################################################### */
                                                                        /*}}}*/
 // Include Files                                                       /*{{{*/
+#include <config.h>
+
 #include <apt-pkg/acquire-item.h>
 #include <apt-pkg/configuration.h>
 #include <apt-pkg/aptconfiguration.h>
@@ -23,9 +25,9 @@
 #include <apt-pkg/md5.h>
 #include <apt-pkg/sha1.h>
 #include <apt-pkg/tagfile.h>
+#include <apt-pkg/indexrecords.h>
+#include <apt-pkg/metaindex.h>
 
-#include <apti18n.h>
-    
 #include <sys/stat.h>
 #include <unistd.h>
 #include <errno.h>
@@ -33,6 +35,8 @@
 #include <sstream>
 #include <stdio.h>
 #include <ctime>
+
+#include <apti18n.h>
                                                                        /*}}}*/
 
 using namespace std;
@@ -94,7 +98,7 @@ void pkgAcquire::Item::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
 // ---------------------------------------------------------------------
 /* Stash status and the file size. Note that setting Complete means 
    sub-phases of the acquire process such as decompresion are operating */
-void pkgAcquire::Item::Start(string /*Message*/,unsigned long Size)
+void pkgAcquire::Item::Start(string /*Message*/,unsigned long long Size)
 {
    Status = StatFetching;
    if (FileSize == 0 && Complete == false)
@@ -104,7 +108,7 @@ void pkgAcquire::Item::Start(string /*Message*/,unsigned long Size)
 // Acquire::Item::Done - Item downloaded OK                            /*{{{*/
 // ---------------------------------------------------------------------
 /* */
-void pkgAcquire::Item::Done(string Message,unsigned long Size,string Hash,
+void pkgAcquire::Item::Done(string Message,unsigned long long Size,string Hash,
                            pkgAcquire::MethodConfig *Cnf)
 {
    // We just downloaded something..
@@ -245,7 +249,7 @@ void pkgAcqSubIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf)   /*{{{*
    }
 }
                                                                        /*}}}*/
-void pkgAcqSubIndex::Done(string Message,unsigned long Size,string Md5Hash,    /*{{{*/
+void pkgAcqSubIndex::Done(string Message,unsigned long long Size,string Md5Hash,       /*{{{*/
                           pkgAcquire::MethodConfig *Cnf)
 {
    if(Debug)
@@ -271,6 +275,14 @@ void pkgAcqSubIndex::Done(string Message,unsigned long Size,string Md5Hash,        /*{{
 
    string FinalFile = _config->FindDir("Dir::State::lists")+URItoFileName(Desc.URI);
 
+   /* Downloaded invalid transindex => Error (LP: #346386) (Closes: #627642) */
+   indexRecords SubIndexParser;
+   if (FileExists(DestFile) == true && !SubIndexParser.Load(DestFile)) {
+      Status = StatError;
+      ErrorText = SubIndexParser.ErrorText;
+      return;
+   }
+
    // sucess in downloading the index
    // rename the index
    if(Debug)
@@ -536,7 +548,7 @@ void pkgAcqDiffIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf)  /*{{{
    Dequeue();
 }
                                                                        /*}}}*/
-void pkgAcqDiffIndex::Done(string Message,unsigned long Size,string Md5Hash,   /*{{{*/
+void pkgAcqDiffIndex::Done(string Message,unsigned long long Size,string Md5Hash,      /*{{{*/
                           pkgAcquire::MethodConfig *Cnf)
 {
    if(Debug)
@@ -673,17 +685,17 @@ bool pkgAcqIndexDiffs::QueueNextDiff()                                    /*{{{*/
    // remove all patches until the next matching patch is found
    // this requires the Index file to be ordered
    for(vector<DiffInfo>::iterator I=available_patches.begin();
-       available_patches.size() > 0 && 
+       available_patches.empty() == false &&
          I != available_patches.end() &&
-         (*I).sha1 != local_sha1; 
-       I++) 
+         I->sha1 != local_sha1;
+       ++I)
    {
       available_patches.erase(I);
    }
 
    // error checking and falling back if no patch was found
-   if(available_patches.size() == 0) 
-   { 
+   if(available_patches.empty() == true)
+   {
       Failed("", NULL);
       return false;
    }
@@ -702,7 +714,7 @@ bool pkgAcqIndexDiffs::QueueNextDiff()                                      /*{{{*/
    return true;
 }
                                                                        /*}}}*/
-void pkgAcqIndexDiffs::Done(string Message,unsigned long Size,string Md5Hash,  /*{{{*/
+void pkgAcqIndexDiffs::Done(string Message,unsigned long long Size,string Md5Hash,     /*{{{*/
                            pkgAcquire::MethodConfig *Cnf)
 {
    if(Debug)
@@ -748,7 +760,7 @@ void pkgAcqIndexDiffs::Done(string Message,unsigned long Size,string Md5Hash,       /*
       chmod(FinalFile.c_str(),0644);
 
       // see if there is more to download
-      if(available_patches.size() > 0) {
+      if(available_patches.empty() == false) {
         new pkgAcqIndexDiffs(Owner, RealURI, Description, Desc.ShortDesc,
                              ExpectedHash, ServerSha1, available_patches);
         return Finish();
@@ -800,6 +812,13 @@ pkgAcqIndex::pkgAcqIndex(pkgAcquire *Owner, IndexTarget const *Target,
    if (CompressionExtension.empty() == false)
       CompressionExtension.erase(CompressionExtension.end()-1);
 
+   // only verify non-optional targets, see acquire-item.h for a FIXME
+   // to make this more flexible
+   if (Target->IsOptional())
+     Verify = false;
+   else
+     Verify = true;
+
    Init(Target->URI, Target->Description, Target->ShortDesc);
 }
                                                                        /*}}}*/
@@ -873,7 +892,7 @@ void pkgAcqIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf)      /*{{{*/
    to the uncompressed version of the file. If this is so the file
    is copied into the partial directory. In all other cases the file
    is decompressed with a gzip uri. */
-void pkgAcqIndex::Done(string Message,unsigned long Size,string Hash,
+void pkgAcqIndex::Done(string Message,unsigned long long Size,string Hash,
                       pkgAcquire::MethodConfig *Cfg)
 {
    Item::Done(Message,Size,Hash,Cfg);
@@ -894,6 +913,31 @@ void pkgAcqIndex::Done(string Message,unsigned long Size,string Hash,
         ReportMirrorFailure("HashChecksumFailure");
          return;
       }
+
+      /* Verify the index file for correctness (all indexes must
+       * have a Package field) (LP: #346386) (Closes: #627642) */
+      if (Verify == true)
+      {
+        FileFd fd(DestFile, FileFd::ReadOnly);
+        pkgTagSection sec;
+        pkgTagFile tag(&fd);
+
+         // Only test for correctness if the file is not empty (empty is ok)
+         if (fd.Size() > 0) {
+            if (_error->PendingError() || !tag.Step(sec)) {
+               Status = StatError;
+               _error->DumpErrors();
+               Rename(DestFile,DestFile + ".FAILED");
+               return;
+            } else if (!sec.Exists("Package")) {
+               Status = StatError;
+               ErrorText = ("Encountered a section with no Package: header");
+               Rename(DestFile,DestFile + ".FAILED");
+               return;
+            }
+         }
+      }
+       
       // Done, move it into position
       string FinalFile = _config->FindDir("Dir::State::lists");
       FinalFile += URItoFileName(RealURI);
@@ -1091,7 +1135,7 @@ string pkgAcqMetaSig::Custom600Headers()
    return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
 }
 
-void pkgAcqMetaSig::Done(string Message,unsigned long Size,string MD5,
+void pkgAcqMetaSig::Done(string Message,unsigned long long Size,string MD5,
                         pkgAcquire::MethodConfig *Cfg)
 {
    Item::Done(Message,Size,MD5,Cfg);
@@ -1200,7 +1244,7 @@ string pkgAcqMetaIndex::Custom600Headers()
    return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
 }
                                                                        /*}}}*/
-void pkgAcqMetaIndex::Done(string Message,unsigned long Size,string Hash,      /*{{{*/
+void pkgAcqMetaIndex::Done(string Message,unsigned long long Size,string Hash, /*{{{*/
                           pkgAcquire::MethodConfig *Cfg)
 {
    Item::Done(Message,Size,Hash,Cfg);
@@ -1226,7 +1270,8 @@ void pkgAcqMetaIndex::Done(string Message,unsigned long Size,string Hash, /*{{{*
       if (SigFile == "")
       {
          // There was no signature file, so we are finished.  Download
-         // the indexes without verification.
+         // the indexes and do only hashsum verification if possible
+         MetaIndexParser->Load(DestFile);
          QueueIndexes(false);
       }
       else
@@ -1330,37 +1375,45 @@ void pkgAcqMetaIndex::AuthDone(string Message)                          /*{{{*/
                                                                        /*}}}*/
 void pkgAcqMetaIndex::QueueIndexes(bool verify)                                /*{{{*/
 {
+#if 0
+   /* Reject invalid, existing Release files (LP: #346386) (Closes: #627642)
+    * FIXME: Disabled; it breaks unsigned repositories without hashes */
+   if (!verify && FileExists(DestFile) && !MetaIndexParser->Load(DestFile))
+   {
+      Status = StatError;
+      ErrorText = MetaIndexParser->ErrorText;
+      return;
+   }
+#endif
    for (vector <struct IndexTarget*>::const_iterator Target = IndexTargets->begin();
         Target != IndexTargets->end();
-        Target++)
+        ++Target)
    {
       HashString ExpectedIndexHash;
-      if (verify)
+      const indexRecords::checkSum *Record = MetaIndexParser->Lookup((*Target)->MetaKey);
+      if (Record == NULL)
       {
-        const indexRecords::checkSum *Record = MetaIndexParser->Lookup((*Target)->MetaKey);
-        if (Record == NULL)
+        if (verify == true && (*Target)->IsOptional() == false)
         {
-           if ((*Target)->IsOptional() == false)
-           {
-              Status = StatAuthError;
-              strprintf(ErrorText, _("Unable to find expected entry '%s' in Release file (Wrong sources.list entry or malformed file)"), (*Target)->MetaKey.c_str());
-              return;
-           }
+           Status = StatAuthError;
+           strprintf(ErrorText, _("Unable to find expected entry '%s' in Release file (Wrong sources.list entry or malformed file)"), (*Target)->MetaKey.c_str());
+           return;
         }
-        else
+      }
+      else
+      {
+        ExpectedIndexHash = Record->Hash;
+        if (_config->FindB("Debug::pkgAcquire::Auth", false))
         {
-           ExpectedIndexHash = Record->Hash;
-           if (_config->FindB("Debug::pkgAcquire::Auth", false))
-           {
-              std::cerr << "Queueing: " << (*Target)->URI << std::endl;
-              std::cerr << "Expected Hash: " << ExpectedIndexHash.toStr() << std::endl;
-           }
-           if (ExpectedIndexHash.empty() == true && (*Target)->IsOptional() == false)
-           {
-              Status = StatAuthError;
-              strprintf(ErrorText, _("Unable to find hash sum for '%s' in Release file"), (*Target)->MetaKey.c_str());
-              return;
-           }
+           std::cerr << "Queueing: " << (*Target)->URI << std::endl;
+           std::cerr << "Expected Hash: " << ExpectedIndexHash.toStr() << std::endl;
+           std::cerr << "For: " << Record->MetaKeyFilename << std::endl;
+        }
+        if (verify == true && ExpectedIndexHash.empty() == true && (*Target)->IsOptional() == false)
+        {
+           Status = StatAuthError;
+           strprintf(ErrorText, _("Unable to find hash sum for '%s' in Release file"), (*Target)->MetaKey.c_str());
+           return;
         }
       }
 
@@ -1431,8 +1484,10 @@ bool pkgAcqMetaIndex::VerifyVendor(string Message)                       /*{{{*/
         // TRANSLATOR: The first %s is the URL of the bad Release file, the second is
         // the time since then the file is invalid - formated in the same way as in
         // the download progress display (e.g. 7d 3h 42min 1s)
-        return _error->Error(_("Release file expired, ignoring %s (invalid since %s)"),
-                             RealURI.c_str(), TimeToStr(invalid_since).c_str());
+        return _error->Error(
+            _("Release file for %s is expired (invalid since %s). "
+              "Updates for this repository will not be applied."),
+            RealURI.c_str(), TimeToStr(invalid_since).c_str());
    }
 
    if (_config->FindB("Debug::pkgAcquire::Auth", false)) 
@@ -1493,6 +1548,12 @@ void pkgAcqMetaIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
                         LookupTag(Message,"Message").c_str());
         RunScripts("APT::Update::Auth-Failure");
         return;
+      } else if (LookupTag(Message,"Message").find("NODATA") != string::npos) {
+        /* Invalid signature file, reject (LP: #346386) (Closes: #627642) */
+        _error->Error(_("GPG error: %s: %s"),
+                        Desc.Description.c_str(),
+                        LookupTag(Message,"Message").c_str());
+        return;
       } else {
         _error->Warning(_("GPG error: %s: %s"),
                         Desc.Description.c_str(),
@@ -1502,6 +1563,26 @@ void pkgAcqMetaIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
       ReportMirrorFailure("GPGFailure");
    }
 
+   /* Always move the meta index, even if gpgv failed. This ensures
+    * that PackageFile objects are correctly filled in */
+   if (FileExists(DestFile)) {
+      string FinalFile = _config->FindDir("Dir::State::lists");
+      FinalFile += URItoFileName(RealURI);
+      /* InRelease files become Release files, otherwise
+       * they would be considered as trusted later on */
+      if (SigFile == DestFile) {
+        RealURI = RealURI.replace(RealURI.rfind("InRelease"), 9,
+                                      "Release");
+        FinalFile = FinalFile.replace(FinalFile.rfind("InRelease"), 9,
+                                      "Release");
+        SigFile = FinalFile;
+      }
+      Rename(DestFile,FinalFile);
+      chmod(FinalFile.c_str(),0644);
+
+      DestFile = FinalFile;
+   }
+
    // No Release file was present, or verification failed, so fall
    // back to queueing Packages files without verification
    QueueIndexes(false);
@@ -1601,7 +1682,7 @@ pkgAcqArchive::pkgAcqArchive(pkgAcquire *Owner,pkgSourceList *Sources,
 
    // check if we have one trusted source for the package. if so, switch
    // to "TrustedOnly" mode
-   for (pkgCache::VerFileIterator i = Version.FileList(); i.end() == false; i++)
+   for (pkgCache::VerFileIterator i = Version.FileList(); i.end() == false; ++i)
    {
       pkgIndexFile *Index;
       if (Sources->FindIndex(i.File(),Index) == false)
@@ -1625,7 +1706,7 @@ pkgAcqArchive::pkgAcqArchive(pkgAcquire *Owner,pkgSourceList *Sources,
 
    // Select a source
    if (QueueNext() == false && _error->PendingError() == false)
-      _error->Error(_("I wasn't able to locate file for the %s package. "
+      _error->Error(_("I wasn't able to locate file for the %s package. "
                    "This might mean you need to manually fix this package."),
                    Version.ParentPkg().Name());
 }
@@ -1638,7 +1719,7 @@ pkgAcqArchive::pkgAcqArchive(pkgAcquire *Owner,pkgSourceList *Sources,
 bool pkgAcqArchive::QueueNext()
 {
    string const ForceHash = _config->Find("Acquire::ForceHash");
-   for (; Vf.end() == false; Vf++)
+   for (; Vf.end() == false; ++Vf)
    {
       // Ignore not source sources
       if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
@@ -1662,6 +1743,8 @@ bool pkgAcqArchive::QueueNext()
       string PkgFile = Parse.FileName();
       if (ForceHash.empty() == false)
       {
+        if(stringcasecmp(ForceHash, "sha512") == 0)
+           ExpectedHash = HashString("SHA512", Parse.SHA512Hash());
         if(stringcasecmp(ForceHash, "sha256") == 0)
            ExpectedHash = HashString("SHA256", Parse.SHA256Hash());
         else if (stringcasecmp(ForceHash, "sha1") == 0)
@@ -1672,7 +1755,9 @@ bool pkgAcqArchive::QueueNext()
       else
       {
         string Hash;
-        if ((Hash = Parse.SHA256Hash()).empty() == false)
+        if ((Hash = Parse.SHA512Hash()).empty() == false)
+           ExpectedHash = HashString("SHA512", Hash);
+        else if ((Hash = Parse.SHA256Hash()).empty() == false)
            ExpectedHash = HashString("SHA256", Hash);
         else if ((Hash = Parse.SHA1Hash()).empty() == false)
            ExpectedHash = HashString("SHA1", Hash);
@@ -1696,7 +1781,7 @@ bool pkgAcqArchive::QueueNext()
       if (stat(FinalFile.c_str(),&Buf) == 0)
       {
         // Make sure the size matches
-        if ((unsigned)Buf.st_size == Version->Size)
+        if ((unsigned long long)Buf.st_size == Version->Size)
         {
            Complete = true;
            Local = true;
@@ -1715,7 +1800,7 @@ bool pkgAcqArchive::QueueNext()
       if (stat(FinalFile.c_str(),&Buf) == 0)
       {
         // Make sure the size matches
-        if ((unsigned)Buf.st_size == Version->Size)
+        if ((unsigned long long)Buf.st_size == Version->Size)
         {
            Complete = true;
            Local = true;
@@ -1735,7 +1820,7 @@ bool pkgAcqArchive::QueueNext()
       if (stat(DestFile.c_str(),&Buf) == 0)
       {
         // Hmm, the partial file is too big, erase it
-        if ((unsigned)Buf.st_size > Version->Size)
+        if ((unsigned long long)Buf.st_size > Version->Size)
            unlink(DestFile.c_str());
         else
            PartialSize = Buf.st_size;
@@ -1749,7 +1834,7 @@ bool pkgAcqArchive::QueueNext()
       Desc.ShortDesc = Version.ParentPkg().Name();
       QueueURI(Desc);
 
-      Vf++;
+      ++Vf;
       return true;
    }
    return false;
@@ -1758,7 +1843,7 @@ bool pkgAcqArchive::QueueNext()
 // AcqArchive::Done - Finished fetching                                        /*{{{*/
 // ---------------------------------------------------------------------
 /* */
-void pkgAcqArchive::Done(string Message,unsigned long Size,string CalcHash,
+void pkgAcqArchive::Done(string Message,unsigned long long Size,string CalcHash,
                         pkgAcquire::MethodConfig *Cfg)
 {
    Item::Done(Message,Size,CalcHash,Cfg);
@@ -1823,7 +1908,7 @@ void pkgAcqArchive::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
        StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
    {
       // Vf = Version.FileList();
-      while (Vf.end() == false) Vf++;
+      while (Vf.end() == false) ++Vf;
       StoreFilename = string();
       Item::Failed(Message,Cnf);
       return;
@@ -1869,7 +1954,7 @@ void pkgAcqArchive::Finished()
 // ---------------------------------------------------------------------
 /* The file is added to the queue */
 pkgAcqFile::pkgAcqFile(pkgAcquire *Owner,string URI,string Hash,
-                      unsigned long Size,string Dsc,string ShortDesc,
+                      unsigned long long Size,string Dsc,string ShortDesc,
                       const string &DestDir, const string &DestFilename,
                        bool IsIndexFile) :
                        Item(Owner), ExpectedHash(Hash), IsIndexFile(IsIndexFile)
@@ -1897,7 +1982,7 @@ pkgAcqFile::pkgAcqFile(pkgAcquire *Owner,string URI,string Hash,
    if (stat(DestFile.c_str(),&Buf) == 0)
    {
       // Hmm, the partial file is too big, erase it
-      if ((unsigned)Buf.st_size > Size)
+      if ((unsigned long long)Buf.st_size > Size)
         unlink(DestFile.c_str());
       else
         PartialSize = Buf.st_size;
@@ -1909,7 +1994,7 @@ pkgAcqFile::pkgAcqFile(pkgAcquire *Owner,string URI,string Hash,
 // AcqFile::Done - Item downloaded OK                                  /*{{{*/
 // ---------------------------------------------------------------------
 /* */
-void pkgAcqFile::Done(string Message,unsigned long Size,string CalcHash,
+void pkgAcqFile::Done(string Message,unsigned long long Size,string CalcHash,
                      pkgAcquire::MethodConfig *Cnf)
 {
    Item::Done(Message,Size,CalcHash,Cnf);
@@ -1997,13 +2082,3 @@ string pkgAcqFile::Custom600Headers()
    return "";
 }
                                                                        /*}}}*/
-bool IndexTarget::IsOptional() const {
-   if (strncmp(ShortDesc.c_str(), "Translation", 11) != 0)
-      return false;
-   return true;
-}
-bool IndexTarget::IsSubIndex() const {
-   if (ShortDesc != "TranslationIndex")
-      return false;
-   return true;
-}