some more coverity fixes
[ntk/apt.git] / apt-pkg / acquire-item.cc
index 9433e5c..f70cabe 100644 (file)
@@ -25,6 +25,8 @@
 #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 <sys/stat.h>
 #include <unistd.h>
@@ -187,14 +189,14 @@ void pkgAcquire::Item::ReportMirrorFailure(string FailCode)
                                                                        /*}}}*/
 // AcqSubIndex::AcqSubIndex - Constructor                              /*{{{*/
 // ---------------------------------------------------------------------
-/* Get the Index file first and see if there are languages available
- * If so, create a pkgAcqIndexTrans for the found language(s).
- */
+/* Get a sub-index file based on checksums from a 'master' file and
+   possibly query additional files */
 pkgAcqSubIndex::pkgAcqSubIndex(pkgAcquire *Owner, string const &URI,
                                 string const &URIDesc, string const &ShortDesc,
                                 HashString const &ExpectedHash)
    : Item(Owner), ExpectedHash(ExpectedHash)
 {
+   /* XXX: Beware: Currently this class does nothing (of value) anymore ! */
    Debug = _config->FindB("Debug::pkgAcquire::SubIndex",false);
 
    DestFile = _config->FindDir("Dir::State::lists") + "partial/";
@@ -234,17 +236,7 @@ void pkgAcqSubIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf)  /*{{{*
    Status = StatDone;
    Dequeue();
 
-   // No good Index is provided, so try guessing
-   std::vector<std::string> langs = APT::Configuration::getLanguages(true);
-   for (std::vector<std::string>::const_iterator l = langs.begin();
-       l != langs.end(); ++l)
-   {
-      if (*l == "none") continue;
-      string const file = "Translation-" + *l;
-      new pkgAcqIndexTrans(Owner, Desc.URI.substr(0, Desc.URI.rfind('/')+1).append(file),
-               Desc.Description.erase(Desc.Description.rfind(' ')+1).append(file),
-               file);
-   }
+   // No good Index is provided
 }
                                                                        /*}}}*/
 void pkgAcqSubIndex::Done(string Message,unsigned long long Size,string Md5Hash,       /*{{{*/
@@ -303,38 +295,7 @@ bool pkgAcqSubIndex::ParseIndex(string const &IndexFile)           /*{{{*/
    indexRecords SubIndexParser;
    if (FileExists(IndexFile) == false || SubIndexParser.Load(IndexFile) == false)
       return false;
-
-   std::vector<std::string> lang = APT::Configuration::getLanguages(true);
-   for (std::vector<std::string>::const_iterator l = lang.begin();
-       l != lang.end(); ++l)
-   {
-      if (*l == "none")
-        continue;
-
-      string file = "Translation-" + *l;
-      indexRecords::checkSum const *Record = SubIndexParser.Lookup(file);
-      HashString expected;
-      if (Record == NULL)
-      {
-        // FIXME: the Index file provided by debian currently only includes bz2 records
-        Record = SubIndexParser.Lookup(file + ".bz2");
-        if (Record == NULL)
-           continue;
-      }
-      else
-      {
-        expected = Record->Hash;
-        if (expected.empty() == true)
-           continue;
-      }
-
-      IndexTarget target;
-      target.Description = Desc.Description.erase(Desc.Description.rfind(' ')+1).append(file);
-      target.MetaKey = file;
-      target.ShortDesc = file;
-      target.URI = Desc.URI.substr(0, Desc.URI.rfind('/')+1).append(file);
-      new pkgAcqIndexTrans(Owner, &target, expected, &SubIndexParser);
-   }
+   // so something with the downloaded index
    return true;
 }
                                                                        /*}}}*/
@@ -436,7 +397,7 @@ bool pkgAcqDiffIndex::ParseDiffIndex(string IndexDiffFile)          /*{{{*/
 
       FileFd fd(CurrentPackagesFile, FileFd::ReadOnly);
       SHA1Summation SHA1;
-      SHA1.AddFD(fd.Fd(), fd.Size());
+      SHA1.AddFD(fd);
       string const local_sha1 = SHA1.Result();
 
       if(local_sha1 == ServerSha1) 
@@ -599,7 +560,7 @@ pkgAcqIndexDiffs::pkgAcqIndexDiffs(pkgAcquire *Owner,
    Desc.Owner = this;
    Desc.ShortDesc = ShortDesc;
 
-   if(available_patches.size() == 0) 
+   if(available_patches.empty() == true)
    {
       // we are done (yeah!)
       Finish(true);
@@ -667,7 +628,7 @@ bool pkgAcqIndexDiffs::QueueNextDiff()                                      /*{{{*/
 
    FileFd fd(FinalFile, FileFd::ReadOnly);
    SHA1Summation SHA1;
-   SHA1.AddFD(fd.Fd(), fd.Size());
+   SHA1.AddFD(fd);
    string local_sha1 = string(SHA1.Result());
    if(Debug)
       std::clog << "QueueNextDiff: " 
@@ -1023,6 +984,8 @@ void pkgAcqIndex::Done(string Message,unsigned long long Size,string Hash,
    DestFile += ".decomp";
    Desc.URI = decompProg + ":" + FileName;
    QueueURI(Desc);
+
+   // FIXME: this points to a c++ string that goes out of scope
    Mode = decompProg.c_str();
 }
                                                                        /*}}}*/
@@ -1268,9 +1231,9 @@ void pkgAcqMetaIndex::Done(string Message,unsigned long long Size,string Hash,    /
       if (SigFile == "")
       {
          // There was no signature file, so we are finished.  Download
-         // the indexes and do only hashsum verification
+         // the indexes and do only hashsum verification if possible
          MetaIndexParser->Load(DestFile);
-         QueueIndexes(true);
+         QueueIndexes(false);
       }
       else
       {
@@ -1328,7 +1291,14 @@ void pkgAcqMetaIndex::RetrievalDone(string Message)                      /*{{{*/
       string FinalFile = _config->FindDir("Dir::State::lists");
       FinalFile += URItoFileName(RealURI);
       if (SigFile == DestFile)
+      {
         SigFile = FinalFile;
+        // constructor of pkgAcqMetaClearSig moved it out of the way,
+        // now move it back in on IMS hit for the 'old' file
+        string const OldClearSig = DestFile + ".reverify";
+        if (RealFileExists(OldClearSig) == true)
+           Rename(OldClearSig, FinalFile);
+      }
       DestFile = FinalFile;
    }
    Complete = true;
@@ -1383,38 +1353,58 @@ void pkgAcqMetaIndex::QueueIndexes(bool verify)                         /*{{{*/
       return;
    }
 #endif
+   bool transInRelease = false;
+   {
+      std::vector<std::string> const keys = MetaIndexParser->MetaKeys();
+      for (std::vector<std::string>::const_iterator k = keys.begin(); k != keys.end(); ++k)
+        // FIXME: Feels wrong to check for hardcoded string here, but what should we do elseā€¦
+        if (k->find("Translation-") != std::string::npos)
+        {
+           transInRelease = true;
+           break;
+        }
+   }
+
    for (vector <struct IndexTarget*>::const_iterator Target = IndexTargets->begin();
         Target != IndexTargets->end();
         ++Target)
    {
       HashString ExpectedIndexHash;
-      if (verify)
+      const indexRecords::checkSum *Record = MetaIndexParser->Lookup((*Target)->MetaKey);
+      bool compressedAvailable = false;
+      if (Record == NULL)
       {
-        const indexRecords::checkSum *Record = MetaIndexParser->Lookup((*Target)->MetaKey);
-        if (Record == NULL)
+        if ((*Target)->IsOptional() == true)
         {
-           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;
-           }
+           std::vector<std::string> types = APT::Configuration::getCompressionTypes();
+           for (std::vector<std::string>::const_iterator t = types.begin(); t != types.end(); ++t)
+              if (MetaIndexParser->Exists(string((*Target)->MetaKey).append(".").append(*t)) == true)
+              {
+                 compressedAvailable = true;
+                 break;
+              }
         }
-        else
+        else if (verify == true)
         {
-           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;
-              std::cerr << "For: " << Record->MetaKeyFilename << 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;
-           }
+           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
+      {
+        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;
+           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;
         }
       }
 
@@ -1423,8 +1413,15 @@ void pkgAcqMetaIndex::QueueIndexes(bool verify)                          /*{{{*/
         if ((*Target)->IsSubIndex() == true)
            new pkgAcqSubIndex(Owner, (*Target)->URI, (*Target)->Description,
                                (*Target)->ShortDesc, ExpectedIndexHash);
-        else
-           new pkgAcqIndexTrans(Owner, *Target, ExpectedIndexHash, MetaIndexParser);
+        else if (transInRelease == false || Record != NULL || compressedAvailable == true)
+        {
+           if (_config->FindB("Acquire::PDiffs",true) == true && transInRelease == true &&
+               MetaIndexParser->Exists(string((*Target)->MetaKey).append(".diff/Index")) == true)
+              new pkgAcqDiffIndex(Owner, (*Target)->URI, (*Target)->Description,
+                                  (*Target)->ShortDesc, ExpectedIndexHash);
+           else
+              new pkgAcqIndexTrans(Owner, *Target, ExpectedIndexHash, MetaIndexParser);
+        }
         continue;
       }
 
@@ -1526,22 +1523,19 @@ void pkgAcqMetaIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
    if (AuthPass == true)
    {
       // gpgv method failed, if we have a good signature 
-      string LastGoodSigFile = _config->FindDir("Dir::State::lists");
-      if (DestFile == SigFile)
-        LastGoodSigFile.append(URItoFileName(RealURI));
-      else
-        LastGoodSigFile.append("partial/").append(URItoFileName(RealURI)).append(".gpg.reverify");
+      string LastGoodSigFile = _config->FindDir("Dir::State::lists").append("partial/").append(URItoFileName(RealURI));
+      if (DestFile != SigFile)
+        LastGoodSigFile.append(".gpg");
+      LastGoodSigFile.append(".reverify");
 
       if(FileExists(LastGoodSigFile))
       {
+        string VerifiedSigFile = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
         if (DestFile != SigFile)
-        {
-           string VerifiedSigFile = _config->FindDir("Dir::State::lists") +
-                                       URItoFileName(RealURI) + ".gpg";
-           Rename(LastGoodSigFile,VerifiedSigFile);
-        }
+           VerifiedSigFile.append(".gpg");
+        Rename(LastGoodSigFile, VerifiedSigFile);
         Status = StatTransientNetworkError;
-        _error->Warning(_("A error occurred during the signature "
+        _error->Warning(_("An error occurred during the signature "
                           "verification. The repository is not updated "
                           "and the previous index files will be used. "
                           "GPG error: %s: %s\n"),
@@ -1600,6 +1594,15 @@ pkgAcqMetaClearSig::pkgAcqMetaClearSig(pkgAcquire *Owner,                /*{{{*/
        MetaSigURI(MetaSigURI), MetaSigURIDesc(MetaSigURIDesc), MetaSigShortDesc(MetaSigShortDesc)
 {
    SigFile = DestFile;
+
+   // keep the old InRelease around in case of transistent network errors
+   string const Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
+   struct stat Buf;
+   if (stat(Final.c_str(),&Buf) == 0)
+   {
+      string const LastGoodSig = DestFile + ".reverify";
+      Rename(Final,LastGoodSig);
+   }
 }
                                                                        /*}}}*/
 // pkgAcqMetaClearSig::Custom600Headers - Insert custom request headers        /*{{{*/
@@ -1612,7 +1615,11 @@ string pkgAcqMetaClearSig::Custom600Headers()
 
    struct stat Buf;
    if (stat(Final.c_str(),&Buf) != 0)
-      return "\nIndex-File: true\nFail-Ignore: true\n";
+   {
+      Final = DestFile + ".reverify";
+      if (stat(Final.c_str(),&Buf) != 0)
+        return "\nIndex-File: true\nFail-Ignore: true\n";
+   }
 
    return "\nIndex-File: true\nFail-Ignore: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
 }
@@ -1621,6 +1628,13 @@ void pkgAcqMetaClearSig::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*
 {
    if (AuthPass == false)
    {
+      // Remove the 'old' InRelease file if we try Release.gpg now as otherwise
+      // the file will stay around and gives a false-auth impression (CVE-2012-0214)
+      string FinalFile = _config->FindDir("Dir::State::lists");
+      FinalFile.append(URItoFileName(RealURI));
+      if (FileExists(FinalFile))
+        unlink(FinalFile.c_str());
+
       new pkgAcqMetaSig(Owner,
                        MetaSigURI, MetaSigURIDesc, MetaSigShortDesc,
                        MetaIndexURI, MetaIndexURIDesc, MetaIndexShortDesc,
@@ -1659,7 +1673,7 @@ pkgAcqArchive::pkgAcqArchive(pkgAcquire *Owner,pkgSourceList *Sources,
       assumption here that all the available sources for this version share
       the same extension.. */
    // Skip not source sources, they do not have file fields.
-   for (; Vf.end() == false; Vf++)
+   for (; Vf.end() == false; ++Vf)
    {
       if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
         continue;
@@ -1746,7 +1760,7 @@ bool pkgAcqArchive::QueueNext()
       {
         if(stringcasecmp(ForceHash, "sha512") == 0)
            ExpectedHash = HashString("SHA512", Parse.SHA512Hash());
-        if(stringcasecmp(ForceHash, "sha256") == 0)
+        else if(stringcasecmp(ForceHash, "sha256") == 0)
            ExpectedHash = HashString("SHA256", Parse.SHA256Hash());
         else if (stringcasecmp(ForceHash, "sha1") == 0)
            ExpectedHash = HashString("SHA1", Parse.SHA1Hash());
@@ -1826,7 +1840,18 @@ bool pkgAcqArchive::QueueNext()
         else
            PartialSize = Buf.st_size;
       }
-      
+
+      // Disables download of archives - useful if no real installation follows,
+      // e.g. if we are just interested in proposed installation order
+      if (_config->FindB("Debug::pkgAcqArchive::NoQueue", false) == true)
+      {
+        Complete = true;
+        Local = true;
+        Status = StatDone;
+        StoreFilename = DestFile = FinalFile;
+        return true;
+      }
+
       // Create the item
       Local = false;
       Desc.URI = Index->ArchiveURI(PkgFile);