* apt-pkg/acquire-item.{cc,h}:
[ntk/apt.git] / apt-pkg / acquire-item.cc
index 6831abd..7cae6c8 100644 (file)
@@ -13,9 +13,6 @@
    ##################################################################### */
                                                                        /*}}}*/
 // Include Files                                                       /*{{{*/
-#ifdef __GNUG__
-#pragma implementation "apt-pkg/acquire-item.h"
-#endif
 #include <apt-pkg/acquire-item.h>
 #include <apt-pkg/configuration.h>
 #include <apt-pkg/sourcelist.h>
@@ -98,7 +95,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,
+void pkgAcquire::Item::Done(string Message,unsigned long Size,string Hash,
                            pkgAcquire::MethodConfig *Cnf)
 {
    // We just downloaded something..
@@ -145,8 +142,9 @@ void pkgAcquire::Item::Rename(string From,string To)
  */
 pkgAcqDiffIndex::pkgAcqDiffIndex(pkgAcquire *Owner,
                                 string URI,string URIDesc,string ShortDesc,
-                                string ExpectedMD5)
-   : Item(Owner), RealURI(URI), ExpectedMD5(ExpectedMD5), Description(URIDesc)
+                                HashString ExpectedHash)
+   : Item(Owner), RealURI(URI), ExpectedHash(ExpectedHash),
+     Description(URIDesc)
 {
    
    Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
@@ -274,15 +272,18 @@ bool pkgAcqDiffIndex::ParseDiffIndex(string IndexDiffFile)
       if(found) 
       {
         // queue the diffs
+        string::size_type last_space = Description.rfind(" ");
+        if(last_space != string::npos)
+           Description.erase(last_space, Description.size()-last_space);
         new pkgAcqIndexDiffs(Owner, RealURI, Description, Desc.ShortDesc,
-                             ExpectedMD5, available_patches);
+                             ExpectedHash, available_patches);
         Complete = false;
         Status = StatDone;
         Dequeue();
         return true;
       }
    }
-
+   
    // Nothing found, report and return false
    // Failing here is ok, if we return false later, the full
    // IndexFile is queued
@@ -298,7 +299,7 @@ void pkgAcqDiffIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
                << "Falling back to normal index file aquire" << std::endl;
 
    new pkgAcqIndex(Owner, RealURI, Description, Desc.ShortDesc, 
-                  ExpectedMD5);
+                  ExpectedHash);
 
    Complete = false;
    Status = StatDone;
@@ -344,8 +345,9 @@ void pkgAcqDiffIndex::Done(string Message,unsigned long Size,string Md5Hash,
  */
 pkgAcqIndexDiffs::pkgAcqIndexDiffs(pkgAcquire *Owner,
                                   string URI,string URIDesc,string ShortDesc,
-                                  string ExpectedMD5, vector<DiffInfo> diffs)
-   : Item(Owner), RealURI(URI), ExpectedMD5(ExpectedMD5), 
+                                  HashString ExpectedHash, 
+                                  vector<DiffInfo> diffs)
+   : Item(Owner), RealURI(URI), ExpectedHash(ExpectedHash), 
      available_patches(diffs)
 {
    
@@ -354,7 +356,7 @@ pkgAcqIndexDiffs::pkgAcqIndexDiffs(pkgAcquire *Owner,
 
    Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
 
-   Desc.Description = URIDesc;
+   Description = URIDesc;
    Desc.Owner = this;
    Desc.ShortDesc = ShortDesc;
 
@@ -378,7 +380,7 @@ void pkgAcqIndexDiffs::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
       std::clog << "pkgAcqIndexDiffs failed: " << Desc.URI << std::endl
                << "Falling back to normal index file aquire" << std::endl;
    new pkgAcqIndex(Owner, RealURI, Description,Desc.ShortDesc, 
-                  ExpectedMD5);
+                  ExpectedHash);
    Finish();
 }
 
@@ -393,14 +395,7 @@ void pkgAcqIndexDiffs::Finish(bool allDone)
       DestFile = _config->FindDir("Dir::State::lists");
       DestFile += URItoFileName(RealURI);
 
-      // do the final md5sum checking
-      MD5Summation sum;
-      FileFd Fd(DestFile, FileFd::ReadOnly);
-      sum.AddFD(Fd.Fd(), Fd.Size());
-      Fd.Close();
-      string MD5 = (string)sum.Result();
-
-      if (!ExpectedMD5.empty() && MD5 != ExpectedMD5)
+      if(!ExpectedHash.empty() && !ExpectedHash.VerifyFile(DestFile))
       {
         Status = StatAuthError;
         ErrorText = _("MD5Sum mismatch");
@@ -463,8 +458,7 @@ bool pkgAcqIndexDiffs::QueueNextDiff()
 
    // queue the right diff
    Desc.URI = string(RealURI) + ".diff/" + available_patches[0].file + ".gz";
-   Desc.Description = available_patches[0].file + string(".pdiff");
-
+   Desc.Description = Description + " " + available_patches[0].file + string(".pdiff");
    DestFile = _config->FindDir("Dir::State::lists") + "partial/";
    DestFile += URItoFileName(RealURI + ".diff/" + available_patches[0].file);
 
@@ -543,7 +537,7 @@ void pkgAcqIndexDiffs::Done(string Message,unsigned long Size,string Md5Hash,
       // see if there is more to download
       if(available_patches.size() > 0) {
         new pkgAcqIndexDiffs(Owner, RealURI, Description, Desc.ShortDesc,
-                             ExpectedMD5, available_patches);
+                             ExpectedHash, available_patches);
         return Finish();
       } else 
         return Finish(true);
@@ -557,8 +551,8 @@ void pkgAcqIndexDiffs::Done(string Message,unsigned long Size,string Md5Hash,
    instantiated to fetch the revision file */   
 pkgAcqIndex::pkgAcqIndex(pkgAcquire *Owner,
                         string URI,string URIDesc,string ShortDesc,
-                        string ExpectedMD5, string comprExt)
-   : Item(Owner), RealURI(URI), ExpectedMD5(ExpectedMD5)
+                        HashString ExpectedHash, string comprExt)
+   : Item(Owner), RealURI(URI), ExpectedHash(ExpectedHash)
 {
    Decompression = false;
    Erase = false;
@@ -569,7 +563,7 @@ pkgAcqIndex::pkgAcqIndex(pkgAcquire *Owner,
    if(comprExt.empty()) 
    {
       // autoselect the compression method
-      if(FileExists("/usr/bin/bzip2")) 
+      if(FileExists("/bin/bzip2")) 
         CompressionExtension = ".bz2";
       else 
         CompressionExtension = ".gz";
@@ -604,19 +598,25 @@ string pkgAcqIndex::Custom600Headers()
 void pkgAcqIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
 {
    // no .bz2 found, retry with .gz
-   if(Desc.URI.substr(Desc.URI.size()-3,Desc.URI.size()-1) == "bz2") {
+   if(Desc.URI.substr(Desc.URI.size()-3) == "bz2") {
       Desc.URI = Desc.URI.substr(0,Desc.URI.size()-3) + "gz"; 
 
       // retry with a gzip one 
       new pkgAcqIndex(Owner, RealURI, Desc.Description,Desc.ShortDesc, 
-                     ExpectedMD5, string(".gz"));
+                     ExpectedHash, string(".gz"));
       Status = StatDone;
       Complete = false;
       Dequeue();
       return;
+   } 
+   
+   // on decompression failure, remove bad versions in partial/
+   if(Decompression && Erase) {
+      string s = _config->FindDir("Dir::State::lists") + "partial/";
+      s += URItoFileName(RealURI);
+      unlink(s.c_str());
    }
 
-   
    Item::Failed(Message,Cnf);
 }
 
@@ -628,32 +628,23 @@ 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 MD5,
+void pkgAcqIndex::Done(string Message,unsigned long Size,string Hash,
                       pkgAcquire::MethodConfig *Cfg)
 {
-   Item::Done(Message,Size,MD5,Cfg);
+   Item::Done(Message,Size,Hash,Cfg);
 
    if (Decompression == true)
    {
       if (_config->FindB("Debug::pkgAcquire::Auth", false))
       {
-         std::cerr << std::endl << RealURI << ": Computed MD5: " << MD5;
-         std::cerr << "  Expected MD5: " << ExpectedMD5 << std::endl;
-      }
-
-      if (MD5.empty())
-      {
-         MD5Summation sum;
-         FileFd Fd(DestFile, FileFd::ReadOnly);
-         sum.AddFD(Fd.Fd(), Fd.Size());
-         Fd.Close();
-         MD5 = (string)sum.Result();
+         std::cerr << std::endl << RealURI << ": Computed Hash: " << Hash;
+         std::cerr << "  Expected Hash: " << ExpectedHash.toStr() << std::endl;
       }
 
-      if (!ExpectedMD5.empty() && MD5 != ExpectedMD5)
+      if (!ExpectedHash.empty() && ExpectedHash.toStr() != Hash)
       {
          Status = StatAuthError;
-         ErrorText = _("MD5Sum mismatch");
+         ErrorText = _("Hash Sum mismatch");
          Rename(DestFile,DestFile + ".FAILED");
          return;
       }
@@ -684,7 +675,6 @@ void pkgAcqIndex::Done(string Message,unsigned long Size,string MD5,
       // The files timestamp matches
       if (StringToBool(LookupTag(Message,"Alt-IMS-Hit"),false) == true)
         return;
-
       Decompression = true;
       Local = true;
       DestFile += ".decomp";
@@ -710,8 +700,8 @@ void pkgAcqIndex::Done(string Message,unsigned long Size,string MD5,
    else
       Local = true;
    
-   string compExt = Desc.URI.substr(Desc.URI.size()-3,Desc.URI.size()-1);
-   char *decompProg;
+   string compExt = Desc.URI.substr(Desc.URI.size()-3);
+   const char *decompProg;
    if(compExt == "bz2") 
       decompProg = "bzip2";
    else if(compExt == ".gz") 
@@ -728,6 +718,35 @@ void pkgAcqIndex::Done(string Message,unsigned long Size,string MD5,
    Mode = decompProg;
 }
 
+// AcqIndexTrans::pkgAcqIndexTrans - Constructor                       /*{{{*/
+// ---------------------------------------------------------------------
+/* The Translation file is added to the queue */
+pkgAcqIndexTrans::pkgAcqIndexTrans(pkgAcquire *Owner,
+                           string URI,string URIDesc,string ShortDesc) 
+  : pkgAcqIndex(Owner, URI, URIDesc, ShortDesc, HashString(), "")
+{
+}
+
+                                                                       /*}}}*/
+// AcqIndexTrans::Failed - Silence failure messages for missing files  /*{{{*/
+// ---------------------------------------------------------------------
+/* */
+void pkgAcqIndexTrans::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
+{
+   if (Cnf->LocalOnly == true || 
+       StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
+   {      
+      // Ignore this
+      Status = StatDone;
+      Complete = false;
+      Dequeue();
+      return;
+   }
+   
+   Item::Failed(Message,Cnf);
+}
+                                                                       /*}}}*/
+
 pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire *Owner,
                             string URI,string URIDesc,string ShortDesc,
                             string MetaIndexURI, string MetaIndexURIDesc,
@@ -735,15 +754,15 @@ pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire *Owner,
                             const vector<IndexTarget*>* IndexTargets,
                             indexRecords* MetaIndexParser) :
    Item(Owner), RealURI(URI), MetaIndexURI(MetaIndexURI),
-   MetaIndexURIDesc(MetaIndexURIDesc), MetaIndexShortDesc(MetaIndexShortDesc)
+   MetaIndexURIDesc(MetaIndexURIDesc), MetaIndexShortDesc(MetaIndexShortDesc),
+   MetaIndexParser(MetaIndexParser), IndexTargets(IndexTargets)
 {
-   this->MetaIndexParser = MetaIndexParser;
-   this->IndexTargets = IndexTargets;
    DestFile = _config->FindDir("Dir::State::lists") + "partial/";
    DestFile += URItoFileName(URI);
 
-   // remove any partial downloaded sig-file. it may confuse proxies
-   // and is too small to warrant a partial download anyway
+   // remove any partial downloaded sig-file in partial/. 
+   // it may confuse proxies and is too small to warrant a 
+   // partial download anyway
    unlink(DestFile.c_str());
 
    // Create the item
@@ -751,22 +770,19 @@ pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire *Owner,
    Desc.Owner = this;
    Desc.ShortDesc = ShortDesc;
    Desc.URI = URI;
-   
       
    string Final = _config->FindDir("Dir::State::lists");
    Final += URItoFileName(RealURI);
    struct stat Buf;
    if (stat(Final.c_str(),&Buf) == 0)
    {
-      // File was already in place.  It needs to be re-verified
-      // because Release might have changed, so Move it into partial
-      Rename(Final,DestFile);
-      // unlink the file and do not try to use I-M-S and Last-Modified
-      // if the users proxy is broken
-      if(_config->FindB("Acquire::BrokenProxy", false) == true) {
-        std::cerr << "forcing re-get of the signature file as requested" << std::endl;
-        unlink(DestFile.c_str());
-      }
+      // File was already in place.  It needs to be re-downloaded/verified
+      // because Release might have changed, we do give it a differnt
+      // name than DestFile because otherwise the http method will
+      // send If-Range requests and there are too many broken servers
+      // out there that do not understand them
+      LastGoodSig = DestFile+".reverify";
+      Rename(Final,LastGoodSig);
    }
 
    QueueURI(Desc);
@@ -778,7 +794,7 @@ pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire *Owner,
 string pkgAcqMetaSig::Custom600Headers()
 {
    struct stat Buf;
-   if (stat(DestFile.c_str(),&Buf) != 0)
+   if (stat(LastGoodSig.c_str(),&Buf) != 0)
       return "\nIndex-File: true";
 
    return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
@@ -808,6 +824,12 @@ void pkgAcqMetaSig::Done(string Message,unsigned long Size,string MD5,
 
    Complete = true;
 
+   // put the last known good file back on i-m-s hit (it will
+   // be re-verified again)
+   // Else do nothing, we have the new file in DestFile then
+   if(StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
+      Rename(LastGoodSig, DestFile);
+
    // queue a pkgAcqMetaIndex to be verified against the sig we just retrieved
    new pkgAcqMetaIndex(Owner, MetaIndexURI, MetaIndexURIDesc, MetaIndexShortDesc,
                       DestFile, IndexTargets, MetaIndexParser);
@@ -816,18 +838,24 @@ void pkgAcqMetaSig::Done(string Message,unsigned long Size,string MD5,
                                                                        /*}}}*/
 void pkgAcqMetaSig::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
 {
-   // Delete any existing sigfile, so that this source isn't
-   // mistakenly trusted
    string Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
-   unlink(Final.c_str());
 
-   // if we get a timeout if fail
-   if(LookupTag(Message,"FailReason") == "Timeout" || 
-      LookupTag(Message,"FailReason") == "TmpResolveFailure") {
+   // if we get a network error we fail gracefully
+   if(Status == StatTransientNetworkError)
+   {
       Item::Failed(Message,Cnf);
+      // move the sigfile back on transient network failures 
+      if(FileExists(DestFile))
+        Rename(LastGoodSig,Final);
+
+      // set the status back to , Item::Failed likes to reset it
+      Status = pkgAcquire::Item::StatTransientNetworkError;
       return;
    }
 
+   // Delete any existing sigfile when the acquire failed
+   unlink(Final.c_str());
+
    // queue a pkgAcqMetaIndex with no sigfile
    new pkgAcqMetaIndex(Owner, MetaIndexURI, MetaIndexURIDesc, MetaIndexShortDesc,
                       "", IndexTargets, MetaIndexParser);
@@ -850,11 +878,9 @@ pkgAcqMetaIndex::pkgAcqMetaIndex(pkgAcquire *Owner,
                                 string SigFile,
                                 const vector<struct IndexTarget*>* IndexTargets,
                                 indexRecords* MetaIndexParser) :
-  Item(Owner), RealURI(URI), SigFile(SigFile)
+   Item(Owner), RealURI(URI), SigFile(SigFile), IndexTargets(IndexTargets),
+   MetaIndexParser(MetaIndexParser), AuthPass(false), IMSHit(false)
 {
-   this->AuthPass = false;
-   this->MetaIndexParser = MetaIndexParser;
-   this->IndexTargets = IndexTargets;
    DestFile = _config->FindDir("Dir::State::lists") + "partial/";
    DestFile += URItoFileName(URI);
 
@@ -883,10 +909,10 @@ string pkgAcqMetaIndex::Custom600Headers()
    return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
 }
 
-void pkgAcqMetaIndex::Done(string Message,unsigned long Size,string MD5,
+void pkgAcqMetaIndex::Done(string Message,unsigned long Size,string Hash,
                           pkgAcquire::MethodConfig *Cfg)
 {
-   Item::Done(Message,Size,MD5,Cfg);
+   Item::Done(Message,Size,Hash,Cfg);
 
    // MetaIndexes are done in two passes: one to download the
    // metaindex with an appropriate method, and a second to verify it
@@ -946,17 +972,20 @@ void pkgAcqMetaIndex::RetrievalDone(string Message)
       return;
    }
 
+   // see if the download was a IMSHit
+   IMSHit = StringToBool(LookupTag(Message,"IMS-Hit"),false);
    Complete = true;
 
    string FinalFile = _config->FindDir("Dir::State::lists");
    FinalFile += URItoFileName(RealURI);
 
-   // The files timestamp matches
-   if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == false)
-   {
-      // Move it into position
+   // If we get a IMS hit we can remove the empty file in partial
+   // othersie we move the file in place
+   if (IMSHit)
+      unlink(DestFile.c_str());
+   else
       Rename(DestFile,FinalFile);
-   }
+
    chmod(FinalFile.c_str(),0644);
    DestFile = FinalFile;
 }
@@ -975,7 +1004,7 @@ void pkgAcqMetaIndex::AuthDone(string Message)
       return;
    }
 
-   if (!VerifyVendor())
+   if (!VerifyVendor(Message))
    {
       return;
    }
@@ -1001,7 +1030,7 @@ void pkgAcqMetaIndex::QueueIndexes(bool verify)
         Target != IndexTargets->end();
         Target++)
    {
-      string ExpectedIndexMD5;
+      HashString ExpectedIndexHash;
       if (verify)
       {
          const indexRecords::checkSum *Record = MetaIndexParser->Lookup((*Target)->MetaKey);
@@ -1012,16 +1041,16 @@ void pkgAcqMetaIndex::QueueIndexes(bool verify)
                + (*Target)->MetaKey + " in Meta-index file (malformed Release file?)";
             return;
          }
-         ExpectedIndexMD5 = Record->MD5Hash;
+         ExpectedIndexHash = Record->Hash;
          if (_config->FindB("Debug::pkgAcquire::Auth", false))
          {
             std::cerr << "Queueing: " << (*Target)->URI << std::endl;
-            std::cerr << "Expected MD5: " << ExpectedIndexMD5 << std::endl;
+            std::cerr << "Expected Hash: " << ExpectedIndexHash.toStr() << std::endl;
          }
-         if (ExpectedIndexMD5.empty())
+         if (ExpectedIndexHash.empty())
          {
             Status = StatAuthError;
-            ErrorText = "Unable to find MD5 sum for "
+            ErrorText = "Unable to find hash sum for "
                + (*Target)->MetaKey + " in Meta-index file";
             return;
          }
@@ -1031,14 +1060,14 @@ void pkgAcqMetaIndex::QueueIndexes(bool verify)
       // on the users option)
       if(_config->FindB("Acquire::PDiffs",true) == true) 
         new pkgAcqDiffIndex(Owner, (*Target)->URI, (*Target)->Description,
-                            (*Target)->ShortDesc, ExpectedIndexMD5);
+                            (*Target)->ShortDesc, ExpectedIndexHash);
       else 
         new pkgAcqIndex(Owner, (*Target)->URI, (*Target)->Description,
-                           (*Target)->ShortDesc, ExpectedIndexMD5);
+                           (*Target)->ShortDesc, ExpectedIndexHash);
    }
 }
 
-bool pkgAcqMetaIndex::VerifyVendor()
+bool pkgAcqMetaIndex::VerifyVendor(string Message)
 {
 //    // Maybe this should be made available from above so we don't have
 //    // to read and parse it every time?
@@ -1063,6 +1092,22 @@ bool pkgAcqMetaIndex::VerifyVendor()
 //          break;
 //       }
 //    }
+   string::size_type pos;
+
+   // check for missing sigs (that where not fatal because otherwise we had
+   // bombed earlier)
+   string missingkeys;
+   string msg = _("There is no public key available for the "
+                 "following key IDs:\n");
+   pos = Message.find("NO_PUBKEY ");
+   if (pos != std::string::npos)
+   {
+      string::size_type start = pos+strlen("NO_PUBKEY ");
+      string Fingerprint = Message.substr(start, Message.find("\n")-start);
+      missingkeys += (Fingerprint);
+   }
+   if(!missingkeys.empty())
+      _error->Warning("%s", string(msg+missingkeys).c_str());
 
    string Transformed = MetaIndexParser->GetExpectedDist();
 
@@ -1071,7 +1116,7 @@ bool pkgAcqMetaIndex::VerifyVendor()
       Transformed = "experimental";
    }
 
-   string::size_type pos = Transformed.rfind('/');
+   pos = Transformed.rfind('/');
    if (pos != string::npos)
    {
       Transformed = Transformed.substr(0, pos);
@@ -1117,10 +1162,30 @@ void pkgAcqMetaIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
 {
    if (AuthPass == true)
    {
-      // gpgv method failed
+      // if we fail the authentication but got the file via a IMS-Hit 
+      // this means that the file wasn't downloaded and that it might be
+      // just stale (server problem, proxy etc). we delete what we have
+      // queue it again without i-m-s 
+      // alternatively we could just unlink the file and let the user try again
+      if (IMSHit)
+      {
+        Complete = false;
+        Local = false;
+        AuthPass = false;
+        unlink(DestFile.c_str());
+
+        DestFile = _config->FindDir("Dir::State::lists") + "partial/";
+        DestFile += URItoFileName(RealURI);
+        Desc.URI = RealURI;
+        QueueURI(Desc);
+        return;
+      }
+
+      // gpgv method failed 
       _error->Warning("GPG error: %s: %s",
                       Desc.Description.c_str(),
                       LookupTag(Message,"Message").c_str());
+
    }
 
    // No Release file was present, or verification failed, so fall
@@ -1196,6 +1261,12 @@ pkgAcqArchive::pkgAcqArchive(pkgAcquire *Owner,pkgSourceList *Sources,
       }
    }
 
+   // "allow-unauthenticated" restores apts old fetching behaviour
+   // that means that e.g. unauthenticated file:// uris are higher
+   // priority than authenticated http:// uris
+   if (_config->FindB("APT::Get::AllowUnauthenticated",false) == true)
+      Trusted = false;
+
    // Select a source
    if (QueueNext() == false && _error->PendingError() == false)
       _error->Error(_("I wasn't able to locate file for the %s package. "
@@ -1232,7 +1303,12 @@ bool pkgAcqArchive::QueueNext()
         return false;
       
       string PkgFile = Parse.FileName();
-      MD5 = Parse.MD5Hash();
+      if(Parse.SHA256Hash() != "")
+        ExpectedHash = HashString("SHA256", Parse.SHA256Hash());
+      else if (Parse.SHA1Hash() != "")
+        ExpectedHash = HashString("SHA1", Parse.SHA1Hash());
+      else 
+        ExpectedHash = HashString("MD5Sum", Parse.MD5Hash());
       if (PkgFile.empty() == true)
         return _error->Error(_("The package index files are corrupted. No Filename: "
                              "field for package %s."),
@@ -1312,10 +1388,10 @@ bool pkgAcqArchive::QueueNext()
 // AcqArchive::Done - Finished fetching                                        /*{{{*/
 // ---------------------------------------------------------------------
 /* */
-void pkgAcqArchive::Done(string Message,unsigned long Size,string Md5Hash,
+void pkgAcqArchive::Done(string Message,unsigned long Size,string CalcHash,
                         pkgAcquire::MethodConfig *Cfg)
 {
-   Item::Done(Message,Size,Md5Hash,Cfg);
+   Item::Done(Message,Size,CalcHash,Cfg);
    
    // Check the size
    if (Size != Version->Size)
@@ -1325,17 +1401,14 @@ void pkgAcqArchive::Done(string Message,unsigned long Size,string Md5Hash,
       return;
    }
    
-   // Check the md5
-   if (Md5Hash.empty() == false && MD5.empty() == false)
+   // Check the hash
+   if(ExpectedHash.toStr() != CalcHash)
    {
-      if (Md5Hash != MD5)
-      {
-        Status = StatError;
-        ErrorText = _("MD5Sum mismatch");
-        if(FileExists(DestFile))
-           Rename(DestFile,DestFile + ".FAILED");
-        return;
-      }
+      Status = StatError;
+      ErrorText = _("Hash Sum mismatch");
+      if(FileExists(DestFile))
+        Rename(DestFile,DestFile + ".FAILED");
+      return;
    }
 
    // Grab the output filename
@@ -1427,14 +1500,20 @@ void pkgAcqArchive::Finished()
 // AcqFile::pkgAcqFile - Constructor                                   /*{{{*/
 // ---------------------------------------------------------------------
 /* The file is added to the queue */
-pkgAcqFile::pkgAcqFile(pkgAcquire *Owner,string URI,string MD5,
-                      unsigned long Size,string Dsc,string ShortDesc) :
-                       Item(Owner), Md5Hash(MD5)
+pkgAcqFile::pkgAcqFile(pkgAcquire *Owner,string URI,string Hash,
+                      unsigned long Size,string Dsc,string ShortDesc,
+                      const string &DestDir, const string &DestFilename) :
+                       Item(Owner), ExpectedHash(Hash)
 {
    Retries = _config->FindI("Acquire::Retries",0);
    
-   DestFile = flNotDir(URI);
-   
+   if(!DestFilename.empty())
+      DestFile = DestFilename;
+   else if(!DestDir.empty())
+      DestFile = DestDir + "/" + flNotDir(URI);
+   else
+      DestFile = flNotDir(URI);
+
    // Create the item
    Desc.URI = URI;
    Desc.Description = Dsc;
@@ -1454,30 +1533,27 @@ pkgAcqFile::pkgAcqFile(pkgAcquire *Owner,string URI,string MD5,
       else
         PartialSize = Buf.st_size;
    }
-   
+
    QueueURI(Desc);
 }
                                                                        /*}}}*/
 // AcqFile::Done - Item downloaded OK                                  /*{{{*/
 // ---------------------------------------------------------------------
 /* */
-void pkgAcqFile::Done(string Message,unsigned long Size,string MD5,
+void pkgAcqFile::Done(string Message,unsigned long Size,string CalcHash,
                      pkgAcquire::MethodConfig *Cnf)
 {
-   // Check the md5
-   if (Md5Hash.empty() == false && MD5.empty() == false)
+   Item::Done(Message,Size,CalcHash,Cnf);
+
+   // Check the hash
+   if(!ExpectedHash.empty() && ExpectedHash.toStr() != CalcHash)
    {
-      if (Md5Hash != MD5)
-      {
-        Status = StatError;
-        ErrorText = "MD5Sum mismatch";
-        Rename(DestFile,DestFile + ".FAILED");
-        return;
-      }
+      Status = StatError;
+      ErrorText = "Hash Sum mismatch";
+      Rename(DestFile,DestFile + ".FAILED");
+      return;
    }
    
-   Item::Done(Message,Size,MD5,Cnf);
-
    string FileName = LookupTag(Message,"Filename");
    if (FileName.empty() == true)
    {