summaryrefslogtreecommitdiff
path: root/apt-pkg
diff options
context:
space:
mode:
Diffstat (limited to 'apt-pkg')
-rw-r--r--apt-pkg/acquire-item.cc2224
-rw-r--r--apt-pkg/acquire-item.h855
-rw-r--r--apt-pkg/acquire-method.cc69
-rw-r--r--apt-pkg/acquire-method.h18
-rw-r--r--apt-pkg/acquire-worker.cc49
-rw-r--r--apt-pkg/acquire.cc137
-rw-r--r--apt-pkg/acquire.h29
-rw-r--r--apt-pkg/algorithms.cc16
-rw-r--r--apt-pkg/algorithms.h28
-rw-r--r--apt-pkg/aptconfiguration.cc60
-rw-r--r--apt-pkg/aptconfiguration.h3
-rw-r--r--apt-pkg/cachefilter.cc144
-rw-r--r--apt-pkg/cachefilter.h158
-rw-r--r--apt-pkg/cacheiterators.h16
-rw-r--r--apt-pkg/cacheset.cc374
-rw-r--r--apt-pkg/cacheset.h582
-rw-r--r--apt-pkg/cdrom.cc10
-rw-r--r--apt-pkg/clean.cc2
-rw-r--r--apt-pkg/clean.h8
-rw-r--r--apt-pkg/contrib/cmndline.cc19
-rw-r--r--apt-pkg/contrib/configuration.cc3
-rw-r--r--apt-pkg/contrib/configuration.h16
-rw-r--r--apt-pkg/contrib/fileutl.cc235
-rw-r--r--apt-pkg/contrib/fileutl.h35
-rw-r--r--apt-pkg/contrib/gpgv.cc63
-rw-r--r--apt-pkg/contrib/hashes.cc213
-rw-r--r--apt-pkg/contrib/hashes.h165
-rw-r--r--apt-pkg/contrib/macros.h2
-rw-r--r--apt-pkg/contrib/netrc.cc12
-rw-r--r--apt-pkg/contrib/netrc.h4
-rw-r--r--apt-pkg/contrib/strutl.cc26
-rw-r--r--apt-pkg/contrib/strutl.h6
-rw-r--r--apt-pkg/deb/debindexfile.cc191
-rw-r--r--apt-pkg/deb/debindexfile.h86
-rw-r--r--apt-pkg/deb/deblistparser.cc161
-rw-r--r--apt-pkg/deb/deblistparser.h28
-rw-r--r--apt-pkg/deb/debmetaindex.cc73
-rw-r--r--apt-pkg/deb/debmetaindex.h29
-rw-r--r--apt-pkg/deb/debrecords.cc103
-rw-r--r--apt-pkg/deb/debrecords.h32
-rw-r--r--apt-pkg/deb/debsrcrecords.cc161
-rw-r--r--apt-pkg/deb/debsrcrecords.h7
-rw-r--r--apt-pkg/deb/debsystem.h2
-rw-r--r--apt-pkg/deb/dpkgpm.cc17
-rw-r--r--apt-pkg/deb/dpkgpm.h15
-rw-r--r--apt-pkg/depcache.cc16
-rw-r--r--apt-pkg/depcache.h25
-rw-r--r--apt-pkg/edsp.cc6
-rw-r--r--apt-pkg/edsp/edspindexfile.cc2
-rw-r--r--apt-pkg/indexcopy.cc10
-rw-r--r--apt-pkg/indexcopy.h6
-rw-r--r--apt-pkg/indexfile.h1
-rw-r--r--apt-pkg/indexrecords.cc65
-rw-r--r--apt-pkg/indexrecords.h47
-rw-r--r--apt-pkg/init.cc10
-rw-r--r--apt-pkg/install-progress.cc2
-rw-r--r--apt-pkg/install-progress.h7
-rw-r--r--apt-pkg/metaindex.h2
-rw-r--r--apt-pkg/packagemanager.cc3
-rw-r--r--apt-pkg/packagemanager.h6
-rw-r--r--apt-pkg/pkgcache.cc95
-rw-r--r--apt-pkg/pkgcache.h238
-rw-r--r--apt-pkg/pkgcachegen.cc342
-rw-r--r--apt-pkg/pkgcachegen.h59
-rw-r--r--apt-pkg/pkgrecords.cc2
-rw-r--r--apt-pkg/pkgrecords.h44
-rw-r--r--apt-pkg/pkgsystem.h6
-rw-r--r--apt-pkg/sourcelist.cc8
-rw-r--r--apt-pkg/sourcelist.h16
-rw-r--r--apt-pkg/srcrecords.h16
-rw-r--r--apt-pkg/tagfile.cc233
-rw-r--r--apt-pkg/tagfile.h70
-rw-r--r--apt-pkg/update.cc4
-rw-r--r--apt-pkg/update.h3
-rw-r--r--apt-pkg/upgrade.cc113
-rw-r--r--apt-pkg/upgrade.h14
76 files changed, 5166 insertions, 2791 deletions
diff --git a/apt-pkg/acquire-item.cc b/apt-pkg/acquire-item.cc
index 253cbdaf7..5187738e9 100644
--- a/apt-pkg/acquire-item.cc
+++ b/apt-pkg/acquire-item.cc
@@ -44,22 +44,72 @@
#include <sstream>
#include <stdio.h>
#include <ctime>
+#include <sys/types.h>
+#include <pwd.h>
+#include <grp.h>
#include <apti18n.h>
/*}}}*/
using namespace std;
+static void printHashSumComparision(std::string const &URI, HashStringList const &Expected, HashStringList const &Actual) /*{{{*/
+{
+ if (_config->FindB("Debug::Acquire::HashSumMismatch", false) == false)
+ return;
+ std::cerr << std::endl << URI << ":" << std::endl << " Expected Hash: " << std::endl;
+ for (HashStringList::const_iterator hs = Expected.begin(); hs != Expected.end(); ++hs)
+ std::cerr << "\t- " << hs->toStr() << std::endl;
+ std::cerr << " Actual Hash: " << std::endl;
+ for (HashStringList::const_iterator hs = Actual.begin(); hs != Actual.end(); ++hs)
+ std::cerr << "\t- " << hs->toStr() << std::endl;
+}
+ /*}}}*/
+static void ChangeOwnerAndPermissionOfFile(char const * const requester, char const * const file, char const * const user, char const * const group, mode_t const mode)
+{
+ // ensure the file is owned by root and has good permissions
+ struct passwd const * const pw = getpwnam(user);
+ struct group const * const gr = getgrnam(group);
+ if (getuid() == 0) // if we aren't root, we can't chown, so don't try it
+ {
+ if (pw != NULL && gr != NULL && chown(file, pw->pw_uid, gr->gr_gid) != 0)
+ _error->WarningE(requester, "chown to %s:%s of file %s failed", user, group, file);
+ }
+ if (chmod(file, mode) != 0)
+ _error->WarningE(requester, "chmod 0%o of file %s failed", mode, file);
+}
+static std::string GetPartialFileName(std::string const &file)
+{
+ std::string DestFile = _config->FindDir("Dir::State::lists") + "partial/";
+ DestFile += file;
+ return DestFile;
+}
+static std::string GetPartialFileNameFromURI(std::string const &uri)
+{
+ return GetPartialFileName(URItoFileName(uri));
+}
+
+
// Acquire::Item::Item - Constructor /*{{{*/
-// ---------------------------------------------------------------------
-/* */
-pkgAcquire::Item::Item(pkgAcquire *Owner) : Owner(Owner), FileSize(0),
- PartialSize(0), Mode(0), ID(0), Complete(false),
- Local(false), QueueCounter(0)
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+pkgAcquire::Item::Item(pkgAcquire *Owner,
+ HashStringList const &ExpectedHashes,
+ pkgAcqMetaBase *TransactionManager)
+ : Owner(Owner), FileSize(0), PartialSize(0), Mode(0), ID(0), Complete(false),
+ Local(false), QueueCounter(0), TransactionManager(TransactionManager),
+ ExpectedAdditionalItems(0), ExpectedHashes(ExpectedHashes)
{
Owner->Add(this);
Status = StatIdle;
+ if(TransactionManager != NULL)
+ TransactionManager->Add(this);
}
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic pop
+#endif
/*}}}*/
// Acquire::Item::~Item - Destructor /*{{{*/
// ---------------------------------------------------------------------
@@ -75,15 +125,15 @@ pkgAcquire::Item::~Item()
fetch this object */
void pkgAcquire::Item::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
{
- Status = StatIdle;
- ErrorText = LookupTag(Message,"Message");
+ if(ErrorText == "")
+ ErrorText = LookupTag(Message,"Message");
UsedMirror = LookupTag(Message,"UsedMirror");
if (QueueCounter <= 1)
{
/* This indicates that the file is not available right now but might
be sometime later. If we do a retry cycle then this should be
retried [CDROMs] */
- if (Cnf->LocalOnly == true &&
+ if (Cnf != NULL && Cnf->LocalOnly == true &&
StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
{
Status = StatIdle;
@@ -92,11 +142,18 @@ void pkgAcquire::Item::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
}
Status = StatError;
+ Complete = false;
Dequeue();
- }
+ }
+ else
+ Status = StatIdle;
- // report mirror failure back to LP if we actually use a mirror
+ // check fail reason
string FailReason = LookupTag(Message, "FailReason");
+ if(FailReason == "MaximumSizeExceeded")
+ Rename(DestFile, DestFile+".FAILED");
+
+ // report mirror failure back to LP if we actually use a mirror
if(FailReason.size() != 0)
ReportMirrorFailure(FailReason);
else
@@ -117,12 +174,12 @@ void pkgAcquire::Item::Start(string /*Message*/,unsigned long long Size)
// Acquire::Item::Done - Item downloaded OK /*{{{*/
// ---------------------------------------------------------------------
/* */
-void pkgAcquire::Item::Done(string Message,unsigned long long Size,string /*Hash*/,
+void pkgAcquire::Item::Done(string Message,unsigned long long Size,HashStringList const &/*Hash*/,
pkgAcquire::MethodConfig * /*Cnf*/)
{
// We just downloaded something..
string FileName = LookupTag(Message,"Filename");
- UsedMirror = LookupTag(Message,"UsedMirror");
+ UsedMirror = LookupTag(Message,"UsedMirror");
if (Complete == false && !Local && FileName == DestFile)
{
if (Owner->Log != 0)
@@ -140,7 +197,7 @@ void pkgAcquire::Item::Done(string Message,unsigned long long Size,string /*Hash
// ---------------------------------------------------------------------
/* This helper function is used by a lot of item methods as their final
step */
-void pkgAcquire::Item::Rename(string From,string To)
+bool pkgAcquire::Item::Rename(string From,string To)
{
if (rename(From.c_str(),To.c_str()) != 0)
{
@@ -148,10 +205,28 @@ void pkgAcquire::Item::Rename(string From,string To)
snprintf(S,sizeof(S),_("rename failed, %s (%s -> %s)."),strerror(errno),
From.c_str(),To.c_str());
Status = StatError;
- ErrorText = S;
+ ErrorText += S;
+ return false;
}
+ return true;
}
/*}}}*/
+
+void pkgAcquire::Item::QueueURI(ItemDesc &Item)
+{
+ if (RealFileExists(DestFile))
+ {
+ std::string SandboxUser = _config->Find("APT::Sandbox::User");
+ ChangeOwnerAndPermissionOfFile("GetPartialFileName", DestFile.c_str(),
+ SandboxUser.c_str(), "root", 0600);
+ }
+ Owner->Enqueue(Item);
+}
+void pkgAcquire::Item::Dequeue()
+{
+ Owner->Dequeue(this);
+}
+
bool pkgAcquire::Item::RenameOnError(pkgAcquire::Item::RenameOnErrorState const error)/*{{{*/
{
if(FileExists(DestFile))
@@ -174,10 +249,31 @@ bool pkgAcquire::Item::RenameOnError(pkgAcquire::Item::RenameOnErrorState const
Status = StatError;
// do not report as usually its not the mirrors fault, but Portal/Proxy
break;
+ case SignatureError:
+ ErrorText = _("Signature error");
+ Status = StatError;
+ break;
+ case NotClearsigned:
+ ErrorText = _("Does not start with a cleartext signature");
+ Status = StatError;
+ break;
}
return false;
}
/*}}}*/
+void pkgAcquire::Item::SetActiveSubprocess(const std::string &subprocess)/*{{{*/
+{
+ ActiveSubprocess = subprocess;
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+ Mode = ActiveSubprocess.c_str();
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic pop
+#endif
+}
+ /*}}}*/
// Acquire::Item::ReportMirrorFailure /*{{{*/
// ---------------------------------------------------------------------
void pkgAcquire::Item::ReportMirrorFailure(string FailCode)
@@ -222,118 +318,6 @@ void pkgAcquire::Item::ReportMirrorFailure(string FailCode)
}
}
/*}}}*/
-// AcqSubIndex::AcqSubIndex - Constructor /*{{{*/
-// ---------------------------------------------------------------------
-/* 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/";
- DestFile += URItoFileName(URI);
-
- Desc.URI = URI;
- Desc.Description = URIDesc;
- Desc.Owner = this;
- Desc.ShortDesc = ShortDesc;
-
- QueueURI(Desc);
-
- if(Debug)
- std::clog << "pkgAcqSubIndex: " << Desc.URI << std::endl;
-}
- /*}}}*/
-// AcqSubIndex::Custom600Headers - Insert custom request headers /*{{{*/
-// ---------------------------------------------------------------------
-/* The only header we use is the last-modified header. */
-string pkgAcqSubIndex::Custom600Headers()
-{
- string Final = _config->FindDir("Dir::State::lists");
- Final += URItoFileName(Desc.URI);
-
- struct stat Buf;
- 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);
-}
- /*}}}*/
-void pkgAcqSubIndex::Failed(string Message,pkgAcquire::MethodConfig * /*Cnf*/)/*{{{*/
-{
- if(Debug)
- std::clog << "pkgAcqSubIndex failed: " << Desc.URI << " with " << Message << std::endl;
-
- Complete = false;
- Status = StatDone;
- Dequeue();
-
- // No good Index is provided
-}
- /*}}}*/
-void pkgAcqSubIndex::Done(string Message,unsigned long long Size,string Md5Hash, /*{{{*/
- pkgAcquire::MethodConfig *Cnf)
-{
- if(Debug)
- std::clog << "pkgAcqSubIndex::Done(): " << Desc.URI << std::endl;
-
- string FileName = LookupTag(Message,"Filename");
- if (FileName.empty() == true)
- {
- Status = StatError;
- ErrorText = "Method gave a blank filename";
- return;
- }
-
- if (FileName != DestFile)
- {
- Local = true;
- Desc.URI = "copy:" + FileName;
- QueueURI(Desc);
- return;
- }
-
- Item::Done(Message,Size,Md5Hash,Cnf);
-
- 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;
- }
-
- // success in downloading the index
- // rename the index
- if(Debug)
- std::clog << "Renaming: " << DestFile << " -> " << FinalFile << std::endl;
- Rename(DestFile,FinalFile);
- chmod(FinalFile.c_str(),0644);
- DestFile = FinalFile;
-
- if(ParseIndex(DestFile) == false)
- return Failed("", NULL);
-
- Complete = true;
- Status = StatDone;
- Dequeue();
- return;
-}
- /*}}}*/
-bool pkgAcqSubIndex::ParseIndex(string const &IndexFile) /*{{{*/
-{
- indexRecords SubIndexParser;
- if (FileExists(IndexFile) == false || SubIndexParser.Load(IndexFile) == false)
- return false;
- // so something with the downloaded index
- return true;
-}
- /*}}}*/
// AcqDiffIndex::AcqDiffIndex - Constructor /*{{{*/
// ---------------------------------------------------------------------
/* Get the DiffIndex file first and see if there are patches available
@@ -342,21 +326,23 @@ bool pkgAcqSubIndex::ParseIndex(string const &IndexFile) /*{{{*/
* the original packages file
*/
pkgAcqDiffIndex::pkgAcqDiffIndex(pkgAcquire *Owner,
- string URI,string URIDesc,string ShortDesc,
- HashString ExpectedHash)
- : Item(Owner), RealURI(URI), ExpectedHash(ExpectedHash),
- Description(URIDesc)
+ pkgAcqMetaBase *TransactionManager,
+ IndexTarget const * const Target,
+ HashStringList const &ExpectedHashes,
+ indexRecords *MetaIndexParser)
+ : pkgAcqBaseIndex(Owner, TransactionManager, Target, ExpectedHashes,
+ MetaIndexParser), PackagesFileReadyInPartial(false)
{
Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
- Desc.Description = URIDesc + "/DiffIndex";
+ RealURI = Target->URI;
Desc.Owner = this;
- Desc.ShortDesc = ShortDesc;
- Desc.URI = URI + ".diff/Index";
+ Desc.Description = Target->Description + ".diff/Index";
+ Desc.ShortDesc = Target->ShortDesc;
+ Desc.URI = Target->URI + ".diff/Index";
- DestFile = _config->FindDir("Dir::State::lists") + "partial/";
- DestFile += URItoFileName(Desc.URI);
+ DestFile = GetPartialFileNameFromURI(Desc.URI);
if(Debug)
std::clog << "pkgAcqDiffIndex: " << Desc.URI << std::endl;
@@ -372,9 +358,7 @@ pkgAcqDiffIndex::pkgAcqDiffIndex(pkgAcquire *Owner,
Desc.URI.substr(0,strlen("file:/")) == "file:/")
{
// we don't have a pkg file or we don't want to queue
- if(Debug)
- std::clog << "No index file, local or canceld by user" << std::endl;
- Failed("", NULL);
+ Failed("No index file, local or canceld by user", NULL);
return;
}
@@ -389,11 +373,11 @@ pkgAcqDiffIndex::pkgAcqDiffIndex(pkgAcquire *Owner,
// AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
// ---------------------------------------------------------------------
/* The only header we use is the last-modified header. */
-string pkgAcqDiffIndex::Custom600Headers()
+string pkgAcqDiffIndex::Custom600Headers() const
{
string Final = _config->FindDir("Dir::State::lists");
Final += URItoFileName(Desc.URI);
-
+
if(Debug)
std::clog << "Custom600Header-IMS: " << Final << std::endl;
@@ -406,190 +390,333 @@ string pkgAcqDiffIndex::Custom600Headers()
/*}}}*/
bool pkgAcqDiffIndex::ParseDiffIndex(string IndexDiffFile) /*{{{*/
{
+ // failing here is fine: our caller will take care of trying to
+ // get the complete file if patching fails
if(Debug)
std::clog << "pkgAcqDiffIndex::ParseIndexDiff() " << IndexDiffFile
<< std::endl;
- pkgTagSection Tags;
- string ServerSha1;
- vector<DiffInfo> available_patches;
-
FileFd Fd(IndexDiffFile,FileFd::ReadOnly);
pkgTagFile TF(&Fd);
if (_error->PendingError() == true)
return false;
- if(TF.Step(Tags) == true)
+ pkgTagSection Tags;
+ if(unlikely(TF.Step(Tags) == false))
+ return false;
+
+ HashStringList ServerHashes;
+ unsigned long long ServerSize = 0;
+
+ for (char const * const * type = HashString::SupportedHashes(); *type != NULL; ++type)
{
- bool found = false;
- DiffInfo d;
- string size;
+ std::string tagname = *type;
+ tagname.append("-Current");
+ std::string const tmp = Tags.FindS(tagname.c_str());
+ if (tmp.empty() == true)
+ continue;
- string const tmp = Tags.FindS("SHA1-Current");
+ string hash;
+ unsigned long long size;
std::stringstream ss(tmp);
- ss >> ServerSha1 >> size;
- unsigned long const ServerSize = atol(size.c_str());
+ ss >> hash >> size;
+ if (unlikely(hash.empty() == true))
+ continue;
+ if (unlikely(ServerSize != 0 && ServerSize != size))
+ continue;
+ ServerHashes.push_back(HashString(*type, hash));
+ ServerSize = size;
+ }
- FileFd fd(CurrentPackagesFile, FileFd::ReadOnly);
- SHA1Summation SHA1;
- SHA1.AddFD(fd);
- string const local_sha1 = SHA1.Result();
+ if (ServerHashes.usable() == false)
+ {
+ if (Debug == true)
+ std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": Did not find a good hashsum in the index" << std::endl;
+ return false;
+ }
- if(local_sha1 == ServerSha1)
+ if (ServerHashes != HashSums())
+ {
+ if (Debug == true)
{
- // we have the same sha1 as the server so we are done here
- if(Debug)
- std::clog << "Package file is up-to-date" << std::endl;
- // list cleanup needs to know that this file as well as the already
- // present index is ours, so we create an empty diff to save it for us
- new pkgAcqIndexDiffs(Owner, RealURI, Description, Desc.ShortDesc,
- ExpectedHash, ServerSha1, available_patches);
- return true;
+ std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": Index has different hashes than parser, probably older, so fail pdiffing" << std::endl;
+ printHashSumComparision(CurrentPackagesFile, ServerHashes, HashSums());
}
- else
+ return false;
+ }
+
+ if (ServerHashes.VerifyFile(CurrentPackagesFile) == true)
+ {
+ // we have the same sha1 as the server so we are done here
+ if(Debug)
+ std::clog << "pkgAcqDiffIndex: Package file " << CurrentPackagesFile << " is up-to-date" << std::endl;
+
+ // list cleanup needs to know that this file as well as the already
+ // present index is ours, so we create an empty diff to save it for us
+ new pkgAcqIndexDiffs(Owner, TransactionManager, Target,
+ ExpectedHashes, MetaIndexParser);
+ return true;
+ }
+
+ FileFd fd(CurrentPackagesFile, FileFd::ReadOnly);
+ Hashes LocalHashesCalc;
+ LocalHashesCalc.AddFD(fd);
+ HashStringList const LocalHashes = LocalHashesCalc.GetHashStringList();
+
+ if(Debug)
+ std::clog << "Server-Current: " << ServerHashes.find(NULL)->toStr() << " and we start at "
+ << fd.Name() << " " << fd.FileSize() << " " << LocalHashes.find(NULL)->toStr() << std::endl;
+
+ // parse all of (provided) history
+ vector<DiffInfo> available_patches;
+ bool firstAcceptedHashes = true;
+ for (char const * const * type = HashString::SupportedHashes(); *type != NULL; ++type)
+ {
+ if (LocalHashes.find(*type) == NULL)
+ continue;
+
+ std::string tagname = *type;
+ tagname.append("-History");
+ std::string const tmp = Tags.FindS(tagname.c_str());
+ if (tmp.empty() == true)
+ continue;
+
+ string hash, filename;
+ unsigned long long size;
+ std::stringstream ss(tmp);
+
+ while (ss >> hash >> size >> filename)
{
- if(Debug)
- std::clog << "SHA1-Current: " << ServerSha1 << " and we start at "<< fd.Name() << " " << fd.Size() << " " << local_sha1 << std::endl;
+ if (unlikely(hash.empty() == true || filename.empty() == true))
+ continue;
- // check the historie and see what patches we need
- string const history = Tags.FindS("SHA1-History");
- std::stringstream hist(history);
- while(hist >> d.sha1 >> size >> d.file)
+ // see if we have a record for this file already
+ std::vector<DiffInfo>::iterator cur = available_patches.begin();
+ for (; cur != available_patches.end(); ++cur)
{
- // read until the first match is found
- // from that point on, we probably need all diffs
- if(d.sha1 == local_sha1)
- found=true;
- else if (found == false)
+ if (cur->file != filename || unlikely(cur->result_size != size))
continue;
-
- if(Debug)
- std::clog << "Need to get diff: " << d.file << std::endl;
- available_patches.push_back(d);
+ cur->result_hashes.push_back(HashString(*type, hash));
+ break;
}
-
- if (available_patches.empty() == false)
+ if (cur != available_patches.end())
+ continue;
+ if (firstAcceptedHashes == true)
{
- // patching with too many files is rather slow compared to a fast download
- unsigned long const fileLimit = _config->FindI("Acquire::PDiffs::FileLimit", 0);
- if (fileLimit != 0 && fileLimit < available_patches.size())
- {
- if (Debug)
- std::clog << "Need " << available_patches.size() << " diffs (Limit is " << fileLimit
- << ") so fallback to complete download" << std::endl;
- return false;
- }
-
- // see if the patches are too big
- found = false; // it was true and it will be true again at the end
- d = *available_patches.begin();
- string const firstPatch = d.file;
- unsigned long patchesSize = 0;
- std::stringstream patches(Tags.FindS("SHA1-Patches"));
- while(patches >> d.sha1 >> size >> d.file)
- {
- if (firstPatch == d.file)
- found = true;
- else if (found == false)
- continue;
-
- patchesSize += atol(size.c_str());
- }
- unsigned long const sizeLimit = ServerSize * _config->FindI("Acquire::PDiffs::SizeLimit", 100);
- if (sizeLimit > 0 && (sizeLimit/100) < patchesSize)
- {
- if (Debug)
- std::clog << "Need " << patchesSize << " bytes (Limit is " << sizeLimit/100
- << ") so fallback to complete download" << std::endl;
- return false;
- }
+ DiffInfo next;
+ next.file = filename;
+ next.result_hashes.push_back(HashString(*type, hash));
+ next.result_size = size;
+ next.patch_size = 0;
+ available_patches.push_back(next);
+ }
+ else
+ {
+ if (Debug == true)
+ std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": File " << filename
+ << " wasn't in the list for the first parsed hash! (history)" << std::endl;
+ break;
}
}
+ firstAcceptedHashes = false;
+ }
+
+ if (unlikely(available_patches.empty() == true))
+ {
+ if (Debug)
+ std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": "
+ << "Couldn't find any patches for the patch series." << std::endl;
+ return false;
+ }
+
+ for (char const * const * type = HashString::SupportedHashes(); *type != NULL; ++type)
+ {
+ if (LocalHashes.find(*type) == NULL)
+ continue;
+
+ std::string tagname = *type;
+ tagname.append("-Patches");
+ std::string const tmp = Tags.FindS(tagname.c_str());
+ if (tmp.empty() == true)
+ continue;
+
+ string hash, filename;
+ unsigned long long size;
+ std::stringstream ss(tmp);
- // we have something, queue the next diff
- if(found)
+ while (ss >> hash >> size >> filename)
{
- // queue the diffs
- string::size_type const last_space = Description.rfind(" ");
- if(last_space != string::npos)
- Description.erase(last_space, Description.size()-last_space);
-
- /* decide if we should download patches one by one or in one go:
- The first is good if the server merges patches, but many don't so client
- based merging can be attempt in which case the second is better.
- "bad things" will happen if patches are merged on the server,
- but client side merging is attempt as well */
- bool pdiff_merge = _config->FindB("Acquire::PDiffs::Merge", true);
- if (pdiff_merge == true)
- {
- // reprepro adds this flag if it has merged patches on the server
- std::string const precedence = Tags.FindS("X-Patch-Precedence");
- pdiff_merge = (precedence != "merged");
- }
+ if (unlikely(hash.empty() == true || filename.empty() == true))
+ continue;
- if (pdiff_merge == false)
- new pkgAcqIndexDiffs(Owner, RealURI, Description, Desc.ShortDesc,
- ExpectedHash, ServerSha1, available_patches);
- else
+ // see if we have a record for this file already
+ std::vector<DiffInfo>::iterator cur = available_patches.begin();
+ for (; cur != available_patches.end(); ++cur)
{
- std::vector<pkgAcqIndexMergeDiffs*> *diffs = new std::vector<pkgAcqIndexMergeDiffs*>(available_patches.size());
- for(size_t i = 0; i < available_patches.size(); ++i)
- (*diffs)[i] = new pkgAcqIndexMergeDiffs(Owner, RealURI, Description, Desc.ShortDesc, ExpectedHash,
- available_patches[i], diffs);
+ if (cur->file != filename)
+ continue;
+ if (unlikely(cur->patch_size != 0 && cur->patch_size != size))
+ continue;
+ cur->patch_hashes.push_back(HashString(*type, hash));
+ cur->patch_size = size;
+ break;
}
-
- Complete = false;
- Status = StatDone;
- Dequeue();
- return true;
+ if (cur != available_patches.end())
+ continue;
+ if (Debug == true)
+ std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": File " << filename
+ << " wasn't in the list for the first parsed hash! (patches)" << std::endl;
+ break;
}
}
+
+ bool foundStart = false;
+ for (std::vector<DiffInfo>::iterator cur = available_patches.begin();
+ cur != available_patches.end(); ++cur)
+ {
+ if (LocalHashes != cur->result_hashes)
+ continue;
+
+ available_patches.erase(available_patches.begin(), cur);
+ foundStart = true;
+ break;
+ }
+
+ if (foundStart == false || unlikely(available_patches.empty() == true))
+ {
+ if (Debug)
+ std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": "
+ << "Couldn't find the start of the patch series." << std::endl;
+ return false;
+ }
+
+ // patching with too many files is rather slow compared to a fast download
+ unsigned long const fileLimit = _config->FindI("Acquire::PDiffs::FileLimit", 0);
+ if (fileLimit != 0 && fileLimit < available_patches.size())
+ {
+ if (Debug)
+ std::clog << "Need " << available_patches.size() << " diffs (Limit is " << fileLimit
+ << ") so fallback to complete download" << std::endl;
+ return false;
+ }
+
+ // calculate the size of all patches we have to get
+ // note that all sizes are uncompressed, while we download compressed files
+ unsigned long long patchesSize = 0;
+ for (std::vector<DiffInfo>::const_iterator cur = available_patches.begin();
+ cur != available_patches.end(); ++cur)
+ patchesSize += cur->patch_size;
+ unsigned long long const sizeLimit = ServerSize * _config->FindI("Acquire::PDiffs::SizeLimit", 100);
+ if (false && sizeLimit > 0 && (sizeLimit/100) < patchesSize)
+ {
+ if (Debug)
+ std::clog << "Need " << patchesSize << " bytes (Limit is " << sizeLimit/100
+ << ") so fallback to complete download" << std::endl;
+ return false;
+ }
+
+ // FIXME: make this use the method
+ PackagesFileReadyInPartial = true;
+ std::string const Partial = GetPartialFileNameFromURI(RealURI);
+
+ FileFd From(CurrentPackagesFile, FileFd::ReadOnly);
+ FileFd To(Partial, FileFd::WriteEmpty);
+ if(CopyFile(From, To) == false)
+ return _error->Errno("CopyFile", "failed to copy");
- // Nothing found, report and return false
- // Failing here is ok, if we return false later, the full
- // IndexFile is queued
if(Debug)
- std::clog << "Can't find a patch in the index file" << std::endl;
- return false;
+ std::cerr << "Done copying " << CurrentPackagesFile
+ << " -> " << Partial
+ << std::endl;
+
+ // we have something, queue the diffs
+ string::size_type const last_space = Description.rfind(" ");
+ if(last_space != string::npos)
+ Description.erase(last_space, Description.size()-last_space);
+
+ /* decide if we should download patches one by one or in one go:
+ The first is good if the server merges patches, but many don't so client
+ based merging can be attempt in which case the second is better.
+ "bad things" will happen if patches are merged on the server,
+ but client side merging is attempt as well */
+ bool pdiff_merge = _config->FindB("Acquire::PDiffs::Merge", true);
+ if (pdiff_merge == true)
+ {
+ // reprepro adds this flag if it has merged patches on the server
+ std::string const precedence = Tags.FindS("X-Patch-Precedence");
+ pdiff_merge = (precedence != "merged");
+ }
+
+ if (pdiff_merge == false)
+ {
+ new pkgAcqIndexDiffs(Owner, TransactionManager, Target, ExpectedHashes,
+ MetaIndexParser, available_patches);
+ }
+ else
+ {
+ std::vector<pkgAcqIndexMergeDiffs*> *diffs = new std::vector<pkgAcqIndexMergeDiffs*>(available_patches.size());
+ for(size_t i = 0; i < available_patches.size(); ++i)
+ (*diffs)[i] = new pkgAcqIndexMergeDiffs(Owner, TransactionManager,
+ Target,
+ ExpectedHashes,
+ MetaIndexParser,
+ available_patches[i],
+ diffs);
+ }
+
+ Complete = false;
+ Status = StatDone;
+ Dequeue();
+ return true;
}
/*}}}*/
-void pkgAcqDiffIndex::Failed(string Message,pkgAcquire::MethodConfig * /*Cnf*/)/*{{{*/
+void pkgAcqDiffIndex::Failed(string Message,pkgAcquire::MethodConfig * Cnf)/*{{{*/
{
if(Debug)
std::clog << "pkgAcqDiffIndex failed: " << Desc.URI << " with " << Message << std::endl
<< "Falling back to normal index file acquire" << std::endl;
- new pkgAcqIndex(Owner, RealURI, Description, Desc.ShortDesc,
- ExpectedHash);
+ new pkgAcqIndex(Owner, TransactionManager, Target, ExpectedHashes, MetaIndexParser);
- Complete = false;
+ Item::Failed(Message,Cnf);
Status = StatDone;
- Dequeue();
}
/*}}}*/
-void pkgAcqDiffIndex::Done(string Message,unsigned long long Size,string Md5Hash, /*{{{*/
+void pkgAcqDiffIndex::Done(string Message,unsigned long long Size,HashStringList const &Hashes, /*{{{*/
pkgAcquire::MethodConfig *Cnf)
{
if(Debug)
std::clog << "pkgAcqDiffIndex::Done(): " << Desc.URI << std::endl;
- Item::Done(Message,Size,Md5Hash,Cnf);
+ Item::Done(Message, Size, Hashes, Cnf);
+
+ // verify the index target
+ if(Target && Target->MetaKey != "" && MetaIndexParser && Hashes.usable())
+ {
+ std::string IndexMetaKey = Target->MetaKey + ".diff/Index";
+ indexRecords::checkSum *Record = MetaIndexParser->Lookup(IndexMetaKey);
+ if(Record && Record->Hashes.usable() && Hashes != Record->Hashes)
+ {
+ RenameOnError(HashSumMismatch);
+ printHashSumComparision(RealURI, Record->Hashes, Hashes);
+ Failed(Message, Cnf);
+ return;
+ }
+
+ }
string FinalFile;
- FinalFile = _config->FindDir("Dir::State::lists")+URItoFileName(RealURI);
+ FinalFile = _config->FindDir("Dir::State::lists");
+ FinalFile += URItoFileName(Desc.URI);
- // success in downloading the index
- // rename the index
- FinalFile += string(".IndexDiff");
- if(Debug)
- std::clog << "Renaming: " << DestFile << " -> " << FinalFile
- << std::endl;
- Rename(DestFile,FinalFile);
- chmod(FinalFile.c_str(),0644);
- DestFile = FinalFile;
+ if(StringToBool(LookupTag(Message,"IMS-Hit"),false))
+ DestFile = FinalFile;
if(!ParseDiffIndex(DestFile))
- return Failed("", NULL);
+ return Failed("Message: Couldn't parse pdiff index", Cnf);
+
+ // queue for final move
+ TransactionManager->TransactionStageCopy(this, DestFile, FinalFile);
Complete = true;
Status = StatDone;
@@ -603,26 +730,28 @@ void pkgAcqDiffIndex::Done(string Message,unsigned long long Size,string Md5Hash
* for each diff and the index
*/
pkgAcqIndexDiffs::pkgAcqIndexDiffs(pkgAcquire *Owner,
- string URI,string URIDesc,string ShortDesc,
- HashString ExpectedHash,
- string ServerSha1,
+ pkgAcqMetaBase *TransactionManager,
+ struct IndexTarget const * const Target,
+ HashStringList const &ExpectedHashes,
+ indexRecords *MetaIndexParser,
vector<DiffInfo> diffs)
- : Item(Owner), RealURI(URI), ExpectedHash(ExpectedHash),
- available_patches(diffs), ServerSha1(ServerSha1)
+ : pkgAcqBaseIndex(Owner, TransactionManager, Target, ExpectedHashes, MetaIndexParser),
+ available_patches(diffs)
{
-
- DestFile = _config->FindDir("Dir::State::lists") + "partial/";
- DestFile += URItoFileName(URI);
+ DestFile = GetPartialFileNameFromURI(Target->URI);
Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
- Description = URIDesc;
+ RealURI = Target->URI;
Desc.Owner = this;
- Desc.ShortDesc = ShortDesc;
+ Description = Target->Description;
+ Desc.ShortDesc = Target->ShortDesc;
if(available_patches.empty() == true)
{
- // we are done (yeah!)
+ // we are done (yeah!), check hashes against the final file
+ DestFile = _config->FindDir("Dir::State::lists");
+ DestFile += URItoFileName(Target->URI);
Finish(true);
}
else
@@ -638,28 +767,34 @@ void pkgAcqIndexDiffs::Failed(string Message,pkgAcquire::MethodConfig * /*Cnf*/)
if(Debug)
std::clog << "pkgAcqIndexDiffs failed: " << Desc.URI << " with " << Message << std::endl
<< "Falling back to normal index file acquire" << std::endl;
- new pkgAcqIndex(Owner, RealURI, Description,Desc.ShortDesc,
- ExpectedHash);
+ new pkgAcqIndex(Owner, TransactionManager, Target, ExpectedHashes, MetaIndexParser);
Finish();
}
/*}}}*/
// Finish - helper that cleans the item out of the fetcher queue /*{{{*/
void pkgAcqIndexDiffs::Finish(bool allDone)
{
+ if(Debug)
+ std::clog << "pkgAcqIndexDiffs::Finish(): "
+ << allDone << " "
+ << Desc.URI << std::endl;
+
// we restore the original name, this is required, otherwise
// the file will be cleaned
if(allDone)
{
- DestFile = _config->FindDir("Dir::State::lists");
- DestFile += URItoFileName(RealURI);
-
- if(!ExpectedHash.empty() && !ExpectedHash.VerifyFile(DestFile))
+ if(HashSums().usable() && !HashSums().VerifyFile(DestFile))
{
RenameOnError(HashSumMismatch);
Dequeue();
return;
}
+ // queue for copy
+ std::string FinalFile = _config->FindDir("Dir::State::lists");
+ FinalFile += URItoFileName(RealURI);
+ TransactionManager->TransactionStageCopy(this, DestFile, FinalFile);
+
// this is for the "real" finish
Complete = true;
Status = StatDone;
@@ -679,21 +814,32 @@ void pkgAcqIndexDiffs::Finish(bool allDone)
/*}}}*/
bool pkgAcqIndexDiffs::QueueNextDiff() /*{{{*/
{
-
// calc sha1 of the just patched file
- string FinalFile = _config->FindDir("Dir::State::lists");
- FinalFile += URItoFileName(RealURI);
+ std::string const FinalFile = GetPartialFileNameFromURI(RealURI);
+
+ if(!FileExists(FinalFile))
+ {
+ Failed("Message: No FinalFile " + FinalFile + " available", NULL);
+ return false;
+ }
FileFd fd(FinalFile, FileFd::ReadOnly);
- SHA1Summation SHA1;
- SHA1.AddFD(fd);
- string local_sha1 = string(SHA1.Result());
+ Hashes LocalHashesCalc;
+ LocalHashesCalc.AddFD(fd);
+ HashStringList const LocalHashes = LocalHashesCalc.GetHashStringList();
+
if(Debug)
- std::clog << "QueueNextDiff: "
- << FinalFile << " (" << local_sha1 << ")"<<std::endl;
+ std::clog << "QueueNextDiff: " << FinalFile << " (" << LocalHashes.find(NULL)->toStr() << ")" << std::endl;
+
+ if (unlikely(LocalHashes.usable() == false || ExpectedHashes.usable() == false))
+ {
+ Failed("Local/Expected hashes are not usable", NULL);
+ return false;
+ }
+
// final file reached before all patches are applied
- if(local_sha1 == ServerSha1)
+ if(LocalHashes == ExpectedHashes)
{
Finish(true);
return true;
@@ -701,10 +847,10 @@ 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();
+ for(vector<DiffInfo>::iterator I = available_patches.begin();
available_patches.empty() == false &&
I != available_patches.end() &&
- I->sha1 != local_sha1;
+ I->result_hashes != LocalHashes;
++I)
{
available_patches.erase(I);
@@ -713,38 +859,48 @@ bool pkgAcqIndexDiffs::QueueNextDiff() /*{{{*/
// error checking and falling back if no patch was found
if(available_patches.empty() == true)
{
- Failed("", NULL);
+ Failed("No patches left to reach target", NULL);
return false;
}
// queue the right diff
Desc.URI = RealURI + ".diff/" + available_patches[0].file + ".gz";
Desc.Description = Description + " " + available_patches[0].file + string(".pdiff");
- DestFile = _config->FindDir("Dir::State::lists") + "partial/";
- DestFile += URItoFileName(RealURI + ".diff/" + available_patches[0].file);
+ DestFile = GetPartialFileNameFromURI(RealURI + ".diff/" + available_patches[0].file);
if(Debug)
std::clog << "pkgAcqIndexDiffs::QueueNextDiff(): " << Desc.URI << std::endl;
-
+
QueueURI(Desc);
return true;
}
/*}}}*/
-void pkgAcqIndexDiffs::Done(string Message,unsigned long long Size,string Md5Hash, /*{{{*/
+void pkgAcqIndexDiffs::Done(string Message,unsigned long long Size, HashStringList const &Hashes, /*{{{*/
pkgAcquire::MethodConfig *Cnf)
{
if(Debug)
std::clog << "pkgAcqIndexDiffs::Done(): " << Desc.URI << std::endl;
- Item::Done(Message,Size,Md5Hash,Cnf);
+ Item::Done(Message, Size, Hashes, Cnf);
- string FinalFile;
- FinalFile = _config->FindDir("Dir::State::lists")+URItoFileName(RealURI);
+ // FIXME: verify this download too before feeding it to rred
+ std::string const FinalFile = GetPartialFileNameFromURI(RealURI);
// success in downloading a diff, enter ApplyDiff state
if(State == StateFetchDiff)
{
+ FileFd fd(DestFile, FileFd::ReadOnly, FileFd::Gzip);
+ class Hashes LocalHashesCalc;
+ LocalHashesCalc.AddFD(fd);
+ HashStringList const LocalHashes = LocalHashesCalc.GetHashStringList();
+
+ if (fd.Size() != available_patches[0].patch_size ||
+ available_patches[0].patch_hashes != LocalHashes)
+ {
+ Failed("Patch has Size/Hashsum mismatch", NULL);
+ return;
+ }
// rred excepts the patch as $FinalFile.ed
Rename(DestFile,FinalFile+".ed");
@@ -756,7 +912,7 @@ void pkgAcqIndexDiffs::Done(string Message,unsigned long long Size,string Md5Has
Local = true;
Desc.URI = "rred:" + FinalFile;
QueueURI(Desc);
- Mode = "rred";
+ SetActiveSubprocess("rred");
return;
}
@@ -779,37 +935,39 @@ void pkgAcqIndexDiffs::Done(string Message,unsigned long long Size,string Md5Has
// see if there is more to download
if(available_patches.empty() == false) {
- new pkgAcqIndexDiffs(Owner, RealURI, Description, Desc.ShortDesc,
- ExpectedHash, ServerSha1, available_patches);
+ new pkgAcqIndexDiffs(Owner, TransactionManager, Target,
+ ExpectedHashes, MetaIndexParser,
+ available_patches);
return Finish();
} else
+ // update
+ DestFile = FinalFile;
return Finish(true);
}
}
/*}}}*/
// AcqIndexMergeDiffs::AcqIndexMergeDiffs - Constructor /*{{{*/
pkgAcqIndexMergeDiffs::pkgAcqIndexMergeDiffs(pkgAcquire *Owner,
- string const &URI, string const &URIDesc,
- string const &ShortDesc, HashString const &ExpectedHash,
- DiffInfo const &patch,
- std::vector<pkgAcqIndexMergeDiffs*> const * const allPatches)
- : Item(Owner), RealURI(URI), ExpectedHash(ExpectedHash),
- patch(patch),allPatches(allPatches), State(StateFetchDiff)
+ pkgAcqMetaBase *TransactionManager,
+ struct IndexTarget const * const Target,
+ HashStringList const &ExpectedHashes,
+ indexRecords *MetaIndexParser,
+ DiffInfo const &patch,
+ std::vector<pkgAcqIndexMergeDiffs*> const * const allPatches)
+ : pkgAcqBaseIndex(Owner, TransactionManager, Target, ExpectedHashes, MetaIndexParser),
+ patch(patch), allPatches(allPatches), State(StateFetchDiff)
{
-
- DestFile = _config->FindDir("Dir::State::lists") + "partial/";
- DestFile += URItoFileName(URI);
-
Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
- Description = URIDesc;
+ RealURI = Target->URI;
Desc.Owner = this;
- Desc.ShortDesc = ShortDesc;
+ Description = Target->Description;
+ Desc.ShortDesc = Target->ShortDesc;
Desc.URI = RealURI + ".diff/" + patch.file + ".gz";
Desc.Description = Description + " " + patch.file + string(".pdiff");
- DestFile = _config->FindDir("Dir::State::lists") + "partial/";
- DestFile += URItoFileName(RealURI + ".diff/" + patch.file);
+
+ DestFile = GetPartialFileNameFromURI(RealURI + ".diff/" + patch.file);
if(Debug)
std::clog << "pkgAcqIndexMergeDiffs: " << Desc.URI << std::endl;
@@ -817,13 +975,13 @@ pkgAcqIndexMergeDiffs::pkgAcqIndexMergeDiffs(pkgAcquire *Owner,
QueueURI(Desc);
}
/*}}}*/
-void pkgAcqIndexMergeDiffs::Failed(string Message,pkgAcquire::MethodConfig * /*Cnf*/)/*{{{*/
+void pkgAcqIndexMergeDiffs::Failed(string Message,pkgAcquire::MethodConfig * Cnf)/*{{{*/
{
if(Debug)
std::clog << "pkgAcqIndexMergeDiffs failed: " << Desc.URI << " with " << Message << std::endl;
- Complete = false;
+
+ Item::Failed(Message,Cnf);
Status = StatDone;
- Dequeue();
// check if we are the first to fail, otherwise we are done here
State = StateDoneDiff;
@@ -835,22 +993,33 @@ void pkgAcqIndexMergeDiffs::Failed(string Message,pkgAcquire::MethodConfig * /*C
// first failure means we should fallback
State = StateErrorDiff;
std::clog << "Falling back to normal index file acquire" << std::endl;
- new pkgAcqIndex(Owner, RealURI, Description,Desc.ShortDesc,
- ExpectedHash);
+ new pkgAcqIndex(Owner, TransactionManager, Target, ExpectedHashes, MetaIndexParser);
}
/*}}}*/
-void pkgAcqIndexMergeDiffs::Done(string Message,unsigned long long Size,string Md5Hash, /*{{{*/
+void pkgAcqIndexMergeDiffs::Done(string Message,unsigned long long Size,HashStringList const &Hashes, /*{{{*/
pkgAcquire::MethodConfig *Cnf)
{
if(Debug)
std::clog << "pkgAcqIndexMergeDiffs::Done(): " << Desc.URI << std::endl;
- Item::Done(Message,Size,Md5Hash,Cnf);
+ Item::Done(Message,Size,Hashes,Cnf);
- string const FinalFile = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
+ // FIXME: verify download before feeding it to rred
+ string const FinalFile = GetPartialFileNameFromURI(RealURI);
if (State == StateFetchDiff)
{
+ FileFd fd(DestFile, FileFd::ReadOnly, FileFd::Gzip);
+ class Hashes LocalHashesCalc;
+ LocalHashesCalc.AddFD(fd);
+ HashStringList const LocalHashes = LocalHashesCalc.GetHashStringList();
+
+ if (fd.Size() != patch.patch_size || patch.patch_hashes != LocalHashes)
+ {
+ Failed("Patch has Size/Hashsum mismatch", NULL);
+ return;
+ }
+
// rred expects the patch as $FinalFile.ed.$patchname.gz
Rename(DestFile, FinalFile + ".ed." + patch.file + ".gz");
@@ -874,35 +1043,38 @@ void pkgAcqIndexMergeDiffs::Done(string Message,unsigned long long Size,string M
Local = true;
Desc.URI = "rred:" + FinalFile;
QueueURI(Desc);
- Mode = "rred";
+ SetActiveSubprocess("rred");
return;
}
// success in download/apply all diffs, clean up
else if (State == StateApplyDiff)
{
// see if we really got the expected file
- if(!ExpectedHash.empty() && !ExpectedHash.VerifyFile(DestFile))
+ if(ExpectedHashes.usable() && !ExpectedHashes.VerifyFile(DestFile))
{
RenameOnError(HashSumMismatch);
return;
}
+
+ std::string FinalFile = _config->FindDir("Dir::State::lists");
+ FinalFile += URItoFileName(RealURI);
+
// move the result into place
if(Debug)
- std::clog << "Moving patched file in place: " << std::endl
+ std::clog << "Queue patched file in place: " << std::endl
<< DestFile << " -> " << FinalFile << std::endl;
- Rename(DestFile, FinalFile);
- chmod(FinalFile.c_str(), 0644);
- // otherwise lists cleanup will eat the file
- DestFile = FinalFile;
+ // queue for copy by the transaction manager
+ TransactionManager->TransactionStageCopy(this, DestFile, FinalFile);
// ensure the ed's are gone regardless of list-cleanup
for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
I != allPatches->end(); ++I)
{
- std::string patch = FinalFile + ".ed." + (*I)->patch.file + ".gz";
- unlink(patch.c_str());
+ std::string const PartialFile = GetPartialFileNameFromURI(RealURI);
+ std::string patch = PartialFile + ".ed." + (*I)->patch.file + ".gz";
+ unlink(patch.c_str());
}
// all set and done
@@ -912,66 +1084,116 @@ void pkgAcqIndexMergeDiffs::Done(string Message,unsigned long long Size,string M
}
}
/*}}}*/
+// AcqBaseIndex::VerifyHashByMetaKey - verify hash for the given metakey /*{{{*/
+bool pkgAcqBaseIndex::VerifyHashByMetaKey(HashStringList const &Hashes)
+{
+ if(MetaKey != "" && Hashes.usable())
+ {
+ indexRecords::checkSum *Record = MetaIndexParser->Lookup(MetaKey);
+ if(Record && Record->Hashes.usable() && Hashes != Record->Hashes)
+ {
+ printHashSumComparision(RealURI, Record->Hashes, Hashes);
+ return false;
+ }
+ }
+ return true;
+}
+ /*}}}*/
// AcqIndex::AcqIndex - Constructor /*{{{*/
// ---------------------------------------------------------------------
-/* The package file is added to the queue and a second class is
- instantiated to fetch the revision file */
+/* The package file is added to the queue and a second class is
+ instantiated to fetch the revision file */
pkgAcqIndex::pkgAcqIndex(pkgAcquire *Owner,
string URI,string URIDesc,string ShortDesc,
- HashString ExpectedHash, string comprExt)
- : Item(Owner), RealURI(URI), ExpectedHash(ExpectedHash)
+ HashStringList const &ExpectedHash)
+ : pkgAcqBaseIndex(Owner, 0, NULL, ExpectedHash, NULL)
{
- if(comprExt.empty() == true)
- {
- // autoselect the compression method
- std::vector<std::string> types = APT::Configuration::getCompressionTypes();
- for (std::vector<std::string>::const_iterator t = types.begin(); t != types.end(); ++t)
- comprExt.append(*t).append(" ");
- if (comprExt.empty() == false)
- comprExt.erase(comprExt.end()-1);
- }
- CompressionExtension = comprExt;
+ RealURI = URI;
+ AutoSelectCompression();
Init(URI, URIDesc, ShortDesc);
+
+ if(_config->FindB("Debug::Acquire::Transaction", false) == true)
+ std::clog << "New pkgIndex with TransactionManager "
+ << TransactionManager << std::endl;
}
-pkgAcqIndex::pkgAcqIndex(pkgAcquire *Owner, IndexTarget const *Target,
- HashString const &ExpectedHash, indexRecords const *MetaIndexParser)
- : Item(Owner), RealURI(Target->URI), ExpectedHash(ExpectedHash)
+ /*}}}*/
+// AcqIndex::AcqIndex - Constructor /*{{{*/
+pkgAcqIndex::pkgAcqIndex(pkgAcquire *Owner,
+ pkgAcqMetaBase *TransactionManager,
+ IndexTarget const *Target,
+ HashStringList const &ExpectedHash,
+ indexRecords *MetaIndexParser)
+ : pkgAcqBaseIndex(Owner, TransactionManager, Target, ExpectedHash,
+ MetaIndexParser)
{
+ RealURI = Target->URI;
+
// autoselect the compression method
+ AutoSelectCompression();
+ Init(Target->URI, Target->Description, Target->ShortDesc);
+
+ if(_config->FindB("Debug::Acquire::Transaction", false) == true)
+ std::clog << "New pkgIndex with TransactionManager "
+ << TransactionManager << std::endl;
+}
+ /*}}}*/
+// AcqIndex::AutoSelectCompression - Select compression /*{{{*/
+void pkgAcqIndex::AutoSelectCompression()
+{
std::vector<std::string> types = APT::Configuration::getCompressionTypes();
- CompressionExtension = "";
- if (ExpectedHash.empty() == false)
+ CompressionExtensions = "";
+ if (ExpectedHashes.usable())
{
- for (std::vector<std::string>::const_iterator t = types.begin(); t != types.end(); ++t)
- if (*t == "uncompressed" || MetaIndexParser->Exists(string(Target->MetaKey).append(".").append(*t)) == true)
- CompressionExtension.append(*t).append(" ");
+ for (std::vector<std::string>::const_iterator t = types.begin();
+ t != types.end(); ++t)
+ {
+ std::string CompressedMetaKey = string(Target->MetaKey).append(".").append(*t);
+ if (*t == "uncompressed" ||
+ MetaIndexParser->Exists(CompressedMetaKey) == true)
+ CompressionExtensions.append(*t).append(" ");
+ }
}
else
{
for (std::vector<std::string>::const_iterator t = types.begin(); t != types.end(); ++t)
- CompressionExtension.append(*t).append(" ");
+ CompressionExtensions.append(*t).append(" ");
}
- if (CompressionExtension.empty() == false)
- CompressionExtension.erase(CompressionExtension.end()-1);
-
- Init(Target->URI, Target->Description, Target->ShortDesc);
+ if (CompressionExtensions.empty() == false)
+ CompressionExtensions.erase(CompressionExtensions.end()-1);
}
/*}}}*/
// AcqIndex::Init - defered Constructor /*{{{*/
-void pkgAcqIndex::Init(string const &URI, string const &URIDesc, string const &ShortDesc) {
- Decompression = false;
- Erase = false;
+void pkgAcqIndex::Init(string const &URI, string const &URIDesc,
+ string const &ShortDesc)
+{
+ Stage = STAGE_DOWNLOAD;
- DestFile = _config->FindDir("Dir::State::lists") + "partial/";
- DestFile += URItoFileName(URI);
+ DestFile = GetPartialFileNameFromURI(URI);
- std::string const comprExt = CompressionExtension.substr(0, CompressionExtension.find(' '));
- if (comprExt == "uncompressed")
+ CurrentCompressionExtension = CompressionExtensions.substr(0, CompressionExtensions.find(' '));
+ if (CurrentCompressionExtension == "uncompressed")
+ {
Desc.URI = URI;
- else {
- Desc.URI = URI + '.' + comprExt;
- DestFile = DestFile + '.' + comprExt;
+ if(Target)
+ MetaKey = string(Target->MetaKey);
+ }
+ else
+ {
+ Desc.URI = URI + '.' + CurrentCompressionExtension;
+ DestFile = DestFile + '.' + CurrentCompressionExtension;
+ if(Target)
+ MetaKey = string(Target->MetaKey) + '.' + CurrentCompressionExtension;
+ }
+
+ // load the filesize
+ if(MetaIndexParser)
+ {
+ indexRecords::checkSum *Record = MetaIndexParser->Lookup(MetaKey);
+ if(Record)
+ FileSize = Record->Size;
+
+ InitByHashIfNeeded(MetaKey);
}
Desc.Description = URIDesc;
@@ -981,22 +1203,44 @@ void pkgAcqIndex::Init(string const &URI, string const &URIDesc, string const &S
QueueURI(Desc);
}
/*}}}*/
+// AcqIndex::AdjustForByHash - modify URI for by-hash support /*{{{*/
+void pkgAcqIndex::InitByHashIfNeeded(const std::string MetaKey)
+{
+ // TODO:
+ // - (maybe?) add support for by-hash into the sources.list as flag
+ // - make apt-ftparchive generate the hashes (and expire?)
+ std::string HostKnob = "APT::Acquire::" + ::URI(Desc.URI).Host + "::By-Hash";
+ if(_config->FindB("APT::Acquire::By-Hash", false) == true ||
+ _config->FindB(HostKnob, false) == true ||
+ MetaIndexParser->GetSupportsAcquireByHash())
+ {
+ indexRecords::checkSum *Record = MetaIndexParser->Lookup(MetaKey);
+ if(Record)
+ {
+ // FIXME: should we really use the best hash here? or a fixed one?
+ const HashString *TargetHash = Record->Hashes.find("");
+ std::string ByHash = "/by-hash/" + TargetHash->HashType() + "/" + TargetHash->HashValue();
+ size_t trailing_slash = Desc.URI.find_last_of("/");
+ Desc.URI = Desc.URI.replace(
+ trailing_slash,
+ Desc.URI.substr(trailing_slash+1).size()+1,
+ ByHash);
+ } else {
+ _error->Warning(
+ "Fetching ByHash requested but can not find record for %s",
+ MetaKey.c_str());
+ }
+ }
+}
+ /*}}}*/
// AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
// ---------------------------------------------------------------------
/* The only header we use is the last-modified header. */
-string pkgAcqIndex::Custom600Headers()
+string pkgAcqIndex::Custom600Headers() const
{
- std::string const compExt = CompressionExtension.substr(0, CompressionExtension.find(' '));
- string Final = _config->FindDir("Dir::State::lists");
- Final += URItoFileName(RealURI);
- if (_config->FindB("Acquire::GzipIndexes",false))
- Final += compExt;
-
+ string Final = GetFinalFilename();
+
string msg = "\nIndex-File: true";
- // FIXME: this really should use "IndexTarget::IsOptional()" but that
- // seems to be difficult without breaking ABI
- if (ShortDesc().find("Translation") != 0)
- msg += "\nFail-Ignore: true";
struct stat Buf;
if (stat(Final.c_str(),&Buf) == 0)
msg += "\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
@@ -1004,131 +1248,140 @@ string pkgAcqIndex::Custom600Headers()
return msg;
}
/*}}}*/
-void pkgAcqIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
+// pkgAcqIndex::Failed - getting the indexfile failed /*{{{*/
+void pkgAcqIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
{
- size_t const nextExt = CompressionExtension.find(' ');
+ size_t const nextExt = CompressionExtensions.find(' ');
if (nextExt != std::string::npos)
{
- CompressionExtension = CompressionExtension.substr(nextExt+1);
+ CompressionExtensions = CompressionExtensions.substr(nextExt+1);
Init(RealURI, Desc.Description, Desc.ShortDesc);
return;
}
// on decompression failure, remove bad versions in partial/
- if (Decompression && Erase) {
- string s = _config->FindDir("Dir::State::lists") + "partial/";
- s.append(URItoFileName(RealURI));
- unlink(s.c_str());
+ if (Stage == STAGE_DECOMPRESS_AND_VERIFY)
+ {
+ unlink(EraseFileName.c_str());
}
Item::Failed(Message,Cnf);
+
+ /// cancel the entire transaction
+ TransactionManager->AbortTransaction();
}
/*}}}*/
-// pkgAcqIndex::GetFinalFilename - Return the full final file path /*{{{*/
-std::string pkgAcqIndex::GetFinalFilename(std::string const &URI,
- std::string const &compExt)
+// pkgAcqIndex::GetFinalFilename - Return the full final file path /*{{{*/
+std::string pkgAcqIndex::GetFinalFilename() const
{
std::string FinalFile = _config->FindDir("Dir::State::lists");
- FinalFile += URItoFileName(URI);
+ FinalFile += URItoFileName(RealURI);
if (_config->FindB("Acquire::GzipIndexes",false) == true)
- FinalFile += '.' + compExt;
+ FinalFile += '.' + CurrentCompressionExtension;
return FinalFile;
}
/*}}}*/
// AcqIndex::ReverifyAfterIMS - Reverify index after an ims-hit /*{{{*/
-void pkgAcqIndex::ReverifyAfterIMS(std::string const &FileName)
+void pkgAcqIndex::ReverifyAfterIMS()
{
- std::string const compExt = CompressionExtension.substr(0, CompressionExtension.find(' '));
+ // update destfile to *not* include the compression extension when doing
+ // a reverify (as its uncompressed on disk already)
+ DestFile = GetPartialFileNameFromURI(RealURI);
+
+ // do not reverify cdrom sources as apt-cdrom may rewrite the Packages
+ // file when its doing the indexcopy
+ if (RealURI.substr(0,6) == "cdrom:")
+ return;
+
+ // adjust DestFile if its compressed on disk
if (_config->FindB("Acquire::GzipIndexes",false) == true)
- DestFile += compExt;
+ DestFile += '.' + CurrentCompressionExtension;
- string FinalFile = GetFinalFilename(RealURI, compExt);
- Rename(FinalFile, FileName);
- Decompression = true;
- Desc.URI = "copy:" + FileName;
+ // copy FinalFile into partial/ so that we check the hash again
+ string FinalFile = GetFinalFilename();
+ Stage = STAGE_DECOMPRESS_AND_VERIFY;
+ Desc.URI = "copy:" + FinalFile;
QueueURI(Desc);
}
/*}}}*/
+// AcqIndex::ValidateFile - Validate the content of the downloaded file /*{{{*/
+bool pkgAcqIndex::ValidateFile(const std::string &FileName)
+{
+ // FIXME: this can go away once we only ever download stuff that
+ // has a valid hash and we never do GET based probing
+ // FIXME2: this also leaks debian-isms into the code and should go therefore
+
+ /* Always validate the index file for correctness (all indexes must
+ * have a Package field) (LP: #346386) (Closes: #627642)
+ */
+ FileFd fd(FileName, FileFd::ReadOnly, FileFd::Extension);
+ // Only test for correctness if the content of the file is not empty
+ // (empty is ok)
+ if (fd.Size() > 0)
+ {
+ pkgTagSection sec;
+ pkgTagFile tag(&fd);
+
+ // all our current indexes have a field 'Package' in each section
+ if (_error->PendingError() == true ||
+ tag.Step(sec) == false ||
+ sec.Exists("Package") == false)
+ return false;
+ }
+ return true;
+}
+ /*}}}*/
// AcqIndex::Done - Finished a fetch /*{{{*/
// ---------------------------------------------------------------------
/* This goes through a number of states.. On the initial fetch the
method could possibly return an alternate filename which points
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 long Size,string Hash,
+ is decompressed with a compressed uri. */
+void pkgAcqIndex::Done(string Message,
+ unsigned long long Size,
+ HashStringList const &Hashes,
pkgAcquire::MethodConfig *Cfg)
{
- Item::Done(Message,Size,Hash,Cfg);
- std::string const compExt = CompressionExtension.substr(0, CompressionExtension.find(' '));
+ Item::Done(Message,Size,Hashes,Cfg);
- if (Decompression == true)
+ switch(Stage)
{
- if (_config->FindB("Debug::pkgAcquire::Auth", false))
- {
- std::cerr << std::endl << RealURI << ": Computed Hash: " << Hash;
- std::cerr << " Expected Hash: " << ExpectedHash.toStr() << std::endl;
- }
-
- if (!ExpectedHash.empty() && ExpectedHash.toStr() != Hash)
- {
- Desc.URI = RealURI;
- RenameOnError(HashSumMismatch);
- return;
- }
-
- // FIXME: this can go away once we only ever download stuff that
- // has a valid hash and we never do GET based probing
- //
- /* Always verify the index file for correctness (all indexes must
- * have a Package field) (LP: #346386) (Closes: #627642)
- */
- FileFd fd(DestFile, FileFd::ReadOnly, FileFd::Extension);
- // Only test for correctness if the file is not empty (empty is ok)
- if (fd.Size() > 0)
- {
- pkgTagSection sec;
- pkgTagFile tag(&fd);
-
- // all our current indexes have a field 'Package' in each section
- if (_error->PendingError() == true || tag.Step(sec) == false || sec.Exists("Package") == false)
- {
- RenameOnError(InvalidFormat);
- return;
- }
- }
-
- // Done, move it into position
- string FinalFile = GetFinalFilename(RealURI, compExt);
- Rename(DestFile,FinalFile);
- chmod(FinalFile.c_str(),0644);
-
- /* We restore the original name to DestFile so that the clean operation
- will work OK */
- DestFile = _config->FindDir("Dir::State::lists") + "partial/";
- DestFile += URItoFileName(RealURI);
- if (_config->FindB("Acquire::GzipIndexes",false))
- DestFile += '.' + compExt;
-
- // Remove the compressed version.
- if (Erase == true)
- unlink(DestFile.c_str());
+ case STAGE_DOWNLOAD:
+ StageDownloadDone(Message, Hashes, Cfg);
+ break;
+ case STAGE_DECOMPRESS_AND_VERIFY:
+ StageDecompressDone(Message, Hashes, Cfg);
+ break;
+ }
+}
+ /*}}}*/
+// AcqIndex::StageDownloadDone - Queue for decompress and verify /*{{{*/
+void pkgAcqIndex::StageDownloadDone(string Message,
+ HashStringList const &Hashes,
+ pkgAcquire::MethodConfig *Cfg)
+{
+ // First check if the calculcated Hash of the (compressed) downloaded
+ // file matches the hash we have in the MetaIndexRecords for this file
+ if(VerifyHashByMetaKey(Hashes) == false)
+ {
+ RenameOnError(HashSumMismatch);
+ Failed(Message, Cfg);
return;
}
- Erase = false;
Complete = true;
-
+
// Handle the unzipd case
string FileName = LookupTag(Message,"Alt-Filename");
if (FileName.empty() == false)
{
- Decompression = true;
+ Stage = STAGE_DECOMPRESS_AND_VERIFY;
Local = true;
DestFile += ".decomp";
Desc.URI = "copy:" + FileName;
QueueURI(Desc);
- Mode = "copy";
+ SetActiveSubprocess("copy");
return;
}
@@ -1139,88 +1392,106 @@ void pkgAcqIndex::Done(string Message,unsigned long long Size,string Hash,
ErrorText = "Method gave a blank filename";
}
- if (FileName == DestFile)
- Erase = true;
- else
+ // Methods like e.g. "file:" will give us a (compressed) FileName that is
+ // not the "DestFile" we set, in this case we uncompress from the local file
+ if (FileName != DestFile)
Local = true;
+ else
+ EraseFileName = FileName;
- // The files timestamp matches, for non-local URLs reverify the local
- // file, for local file, uncompress again to ensure the hashsum is still
- // matching the Release file
- bool const IsCDROM = RealURI.substr(0,6) == "cdrom:";
- if ((Local == false || IsCDROM == true) &&
- StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
+ // we need to verify the file against the current Release file again
+ // on if-modfied-since hit to avoid a stale attack against us
+ if(StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
{
- // set destfile to the final destfile
- if(_config->FindB("Acquire::GzipIndexes",false) == false)
- {
- DestFile = _config->FindDir("Dir::State::lists") + "partial/";
- DestFile += URItoFileName(RealURI);
- }
-
- // do not reverify cdrom sources as apt-cdrom may rewrite the Packages
- // file when its doing the indexcopy
- if (IsCDROM == false)
- ReverifyAfterIMS(FileName);
+ // The files timestamp matches, reverify by copy into partial/
+ EraseFileName = "";
+ ReverifyAfterIMS();
return;
}
- string decompProg;
- // If we enable compressed indexes, queue for hash verification
+ // If we have compressed indexes enabled, queue for hash verification
if (_config->FindB("Acquire::GzipIndexes",false))
{
- DestFile = _config->FindDir("Dir::State::lists");
- DestFile += URItoFileName(RealURI) + '.' + compExt;
-
- Decompression = true;
+ DestFile = GetPartialFileNameFromURI(RealURI + '.' + CurrentCompressionExtension);
+ EraseFileName = "";
+ Stage = STAGE_DECOMPRESS_AND_VERIFY;
Desc.URI = "copy:" + FileName;
QueueURI(Desc);
-
+ SetActiveSubprocess("copy");
return;
}
// get the binary name for your used compression type
- decompProg = _config->Find(string("Acquire::CompressionTypes::").append(compExt),"");
- if(decompProg.empty() == false);
- else if(compExt == "uncompressed")
+ string decompProg;
+ if(CurrentCompressionExtension == "uncompressed")
decompProg = "copy";
- else {
- _error->Error("Unsupported extension: %s", compExt.c_str());
+ else
+ decompProg = _config->Find(string("Acquire::CompressionTypes::").append(CurrentCompressionExtension),"");
+ if(decompProg.empty() == true)
+ {
+ _error->Error("Unsupported extension: %s", CurrentCompressionExtension.c_str());
return;
}
- Decompression = true;
+ // queue uri for the next stage
+ Stage = STAGE_DECOMPRESS_AND_VERIFY;
DestFile += ".decomp";
Desc.URI = decompProg + ":" + FileName;
QueueURI(Desc);
+ SetActiveSubprocess(decompProg);
+}
+ /*}}}*/
+// pkgAcqIndex::StageDecompressDone - Final verification /*{{{*/
+void pkgAcqIndex::StageDecompressDone(string Message,
+ HashStringList const &Hashes,
+ pkgAcquire::MethodConfig *Cfg)
+{
+ if (ExpectedHashes.usable() && ExpectedHashes != Hashes)
+ {
+ Desc.URI = RealURI;
+ RenameOnError(HashSumMismatch);
+ printHashSumComparision(RealURI, ExpectedHashes, Hashes);
+ Failed(Message, Cfg);
+ return;
+ }
- // FIXME: this points to a c++ string that goes out of scope
- Mode = decompProg.c_str();
+ if(!ValidateFile(DestFile))
+ {
+ RenameOnError(InvalidFormat);
+ Failed(Message, Cfg);
+ return;
+ }
+
+ // remove the compressed version of the file
+ unlink(EraseFileName.c_str());
+
+ // Done, queue for rename on transaction finished
+ TransactionManager->TransactionStageCopy(this, DestFile, GetFinalFilename());
+
+ return;
}
/*}}}*/
// 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(), "")
+ string URI,string URIDesc,string ShortDesc)
+ : pkgAcqIndex(Owner, URI, URIDesc, ShortDesc, HashStringList())
{
}
-pkgAcqIndexTrans::pkgAcqIndexTrans(pkgAcquire *Owner, IndexTarget const *Target,
- HashString const &ExpectedHash, indexRecords const *MetaIndexParser)
- : pkgAcqIndex(Owner, Target, ExpectedHash, MetaIndexParser)
+pkgAcqIndexTrans::pkgAcqIndexTrans(pkgAcquire *Owner,
+ pkgAcqMetaBase *TransactionManager,
+ IndexTarget const * const Target,
+ HashStringList const &ExpectedHashes,
+ indexRecords *MetaIndexParser)
+ : pkgAcqIndex(Owner, TransactionManager, Target, ExpectedHashes, MetaIndexParser)
{
}
/*}}}*/
// AcqIndexTrans::Custom600Headers - Insert custom request headers /*{{{*/
-// ---------------------------------------------------------------------
-string pkgAcqIndexTrans::Custom600Headers()
+string pkgAcqIndexTrans::Custom600Headers() const
{
- std::string const compExt = CompressionExtension.substr(0, CompressionExtension.find(' '));
- string Final = _config->FindDir("Dir::State::lists");
- Final += URItoFileName(RealURI);
- if (_config->FindB("Acquire::GzipIndexes",false))
- Final += compExt;
+ string Final = GetFinalFilename();
struct stat Buf;
if (stat(Final.c_str(),&Buf) != 0)
@@ -1229,265 +1500,447 @@ string pkgAcqIndexTrans::Custom600Headers()
}
/*}}}*/
// AcqIndexTrans::Failed - Silence failure messages for missing files /*{{{*/
-// ---------------------------------------------------------------------
-/* */
void pkgAcqIndexTrans::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
{
- size_t const nextExt = CompressionExtension.find(' ');
+ size_t const nextExt = CompressionExtensions.find(' ');
if (nextExt != std::string::npos)
{
- CompressionExtension = CompressionExtension.substr(nextExt+1);
+ CompressionExtensions = CompressionExtensions.substr(nextExt+1);
Init(RealURI, Desc.Description, Desc.ShortDesc);
Status = StatIdle;
return;
}
- if (Cnf->LocalOnly == true ||
+ Item::Failed(Message,Cnf);
+
+ // FIXME: this is used often (e.g. in pkgAcqIndexTrans) so refactor
+ if (Cnf->LocalOnly == true ||
StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
- {
+ {
// Ignore this
Status = StatDone;
- Complete = false;
- Dequeue();
- return;
}
+}
+ /*}}}*/
+// AcqMetaBase::Add - Add a item to the current Transaction /*{{{*/
+void pkgAcqMetaBase::Add(Item *I)
+{
+ Transaction.push_back(I);
+}
+ /*}}}*/
+// AcqMetaBase::AbortTransaction - Abort the current Transaction /*{{{*/
+void pkgAcqMetaBase::AbortTransaction()
+{
+ if(_config->FindB("Debug::Acquire::Transaction", false) == true)
+ std::clog << "AbortTransaction: " << TransactionManager << std::endl;
- Item::Failed(Message,Cnf);
+ // ensure the toplevel is in error state too
+ for (std::vector<Item*>::iterator I = Transaction.begin();
+ I != Transaction.end(); ++I)
+ {
+ if(_config->FindB("Debug::Acquire::Transaction", false) == true)
+ std::clog << " Cancel: " << (*I)->DestFile << std::endl;
+ // the transaction will abort, so stop anything that is idle
+ if ((*I)->Status == pkgAcquire::Item::StatIdle)
+ (*I)->Status = pkgAcquire::Item::StatDone;
+
+ // kill failed files in partial
+ if ((*I)->Status == pkgAcquire::Item::StatError)
+ {
+ std::string const PartialFile = GetPartialFileName(flNotDir((*I)->DestFile));
+ if(FileExists(PartialFile))
+ Rename(PartialFile, PartialFile + ".FAILED");
+ }
+ }
+}
+ /*}}}*/
+// AcqMetaBase::TransactionHasError - Check for errors in Transaction /*{{{*/
+bool pkgAcqMetaBase::TransactionHasError()
+{
+ for (pkgAcquire::ItemIterator I = Transaction.begin();
+ I != Transaction.end(); ++I)
+ if((*I)->Status != pkgAcquire::Item::StatDone &&
+ (*I)->Status != pkgAcquire::Item::StatIdle)
+ return true;
+
+ return false;
+}
+ /*}}}*/
+// AcqMetaBase::CommitTransaction - Commit a transaction /*{{{*/
+void pkgAcqMetaBase::CommitTransaction()
+{
+ if(_config->FindB("Debug::Acquire::Transaction", false) == true)
+ std::clog << "CommitTransaction: " << this << std::endl;
+
+ // move new files into place *and* remove files that are not
+ // part of the transaction but are still on disk
+ for (std::vector<Item*>::iterator I = Transaction.begin();
+ I != Transaction.end(); ++I)
+ {
+ if((*I)->PartialFile != "")
+ {
+ if(_config->FindB("Debug::Acquire::Transaction", false) == true)
+ std::clog << "mv " << (*I)->PartialFile << " -> "<< (*I)->DestFile << " "
+ << (*I)->DescURI() << std::endl;
+
+ Rename((*I)->PartialFile, (*I)->DestFile);
+ ChangeOwnerAndPermissionOfFile("CommitTransaction", (*I)->DestFile.c_str(), "root", "root", 0644);
+
+ } else {
+ if(_config->FindB("Debug::Acquire::Transaction", false) == true)
+ std::clog << "rm "
+ << (*I)->DestFile
+ << " "
+ << (*I)->DescURI()
+ << std::endl;
+ unlink((*I)->DestFile.c_str());
+ }
+ // mark that this transaction is finished
+ (*I)->TransactionManager = 0;
+ }
+}
+ /*}}}*/
+// AcqMetaBase::TransactionStageCopy - Stage a file for copying /*{{{*/
+void pkgAcqMetaBase::TransactionStageCopy(Item *I,
+ const std::string &From,
+ const std::string &To)
+{
+ I->PartialFile = From;
+ I->DestFile = To;
+}
+ /*}}}*/
+// AcqMetaBase::TransactionStageRemoval - Sage a file for removal /*{{{*/
+void pkgAcqMetaBase::TransactionStageRemoval(Item *I,
+ const std::string &FinalFile)
+{
+ I->PartialFile = "";
+ I->DestFile = FinalFile;
}
/*}}}*/
-pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire *Owner, /*{{{*/
+// AcqMetaBase::GenerateAuthWarning - Check gpg authentication error /*{{{*/
+bool pkgAcqMetaBase::CheckStopAuthentication(const std::string &RealURI,
+ const std::string &Message)
+{
+ // FIXME: this entire function can do now that we disallow going to
+ // a unauthenticated state and can cleanly rollback
+
+ string Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
+
+ if(FileExists(Final))
+ {
+ Status = StatTransientNetworkError;
+ _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"),
+ Desc.Description.c_str(),
+ LookupTag(Message,"Message").c_str());
+ RunScripts("APT::Update::Auth-Failure");
+ return true;
+ } 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());
+ Status = StatError;
+ return true;
+ } else {
+ _error->Warning(_("GPG error: %s: %s"),
+ Desc.Description.c_str(),
+ LookupTag(Message,"Message").c_str());
+ }
+ // gpgv method failed
+ ReportMirrorFailure("GPGFailure");
+ return false;
+}
+ /*}}}*/
+// AcqMetaSig::AcqMetaSig - Constructor /*{{{*/
+pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire *Owner,
+ pkgAcqMetaBase *TransactionManager,
string URI,string URIDesc,string ShortDesc,
- string MetaIndexURI, string MetaIndexURIDesc,
- string MetaIndexShortDesc,
+ string MetaIndexFile,
const vector<IndexTarget*>* IndexTargets,
indexRecords* MetaIndexParser) :
- Item(Owner), RealURI(URI), MetaIndexURI(MetaIndexURI),
- MetaIndexURIDesc(MetaIndexURIDesc), MetaIndexShortDesc(MetaIndexShortDesc),
- MetaIndexParser(MetaIndexParser), IndexTargets(IndexTargets)
+ pkgAcqMetaBase(Owner, IndexTargets, MetaIndexParser,
+ HashStringList(), TransactionManager),
+ RealURI(URI), MetaIndexFile(MetaIndexFile), URIDesc(URIDesc),
+ ShortDesc(ShortDesc)
{
DestFile = _config->FindDir("Dir::State::lists") + "partial/";
- DestFile += URItoFileName(URI);
+ DestFile += URItoFileName(RealURI);
- // remove any partial downloaded sig-file in partial/.
- // it may confuse proxies and is too small to warrant a
+ // 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());
+ // set the TransactionManager
+ if(_config->FindB("Debug::Acquire::Transaction", false) == true)
+ std::clog << "New pkgAcqMetaSig with TransactionManager "
+ << TransactionManager << std::endl;
+
// Create the item
Desc.Description = URIDesc;
Desc.Owner = this;
Desc.ShortDesc = ShortDesc;
Desc.URI = URI;
-
- string Final = _config->FindDir("Dir::State::lists");
- Final += URItoFileName(RealURI);
- if (RealFileExists(Final) == true)
- {
- // File was already in place. It needs to be re-downloaded/verified
- // because Release might have changed, we do give it a different
- // 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);
}
/*}}}*/
pkgAcqMetaSig::~pkgAcqMetaSig() /*{{{*/
{
- // if the file was never queued undo file-changes done in the constructor
- if (QueueCounter == 1 && Status == StatIdle && FileSize == 0 && Complete == false &&
- LastGoodSig.empty() == false)
- {
- string const Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
- if (RealFileExists(Final) == false && RealFileExists(LastGoodSig) == true)
- Rename(LastGoodSig, Final);
- }
-
}
/*}}}*/
// pkgAcqMetaSig::Custom600Headers - Insert custom request headers /*{{{*/
// ---------------------------------------------------------------------
-/* The only header we use is the last-modified header. */
-string pkgAcqMetaSig::Custom600Headers()
+string pkgAcqMetaSig::Custom600Headers() const
{
- struct stat Buf;
- if (stat(LastGoodSig.c_str(),&Buf) != 0)
- return "\nIndex-File: true";
-
- return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
+ std::string Header = GetCustom600Headers(RealURI);
+ return Header;
}
-
-void pkgAcqMetaSig::Done(string Message,unsigned long long Size,string MD5,
+ /*}}}*/
+// pkgAcqMetaSig::Done - The signature was downloaded/verified /*{{{*/
+// ---------------------------------------------------------------------
+/* The only header we use is the last-modified header. */
+void pkgAcqMetaSig::Done(string Message,unsigned long long Size,
+ HashStringList const &Hashes,
pkgAcquire::MethodConfig *Cfg)
{
- Item::Done(Message,Size,MD5,Cfg);
+ Item::Done(Message, Size, Hashes, Cfg);
- string FileName = LookupTag(Message,"Filename");
- if (FileName.empty() == true)
+ if(AuthPass == false)
{
- Status = StatError;
- ErrorText = "Method gave a blank filename";
+ if(CheckDownloadDone(Message, RealURI) == true)
+ {
+ // destfile will be modified to point to MetaIndexFile for the
+ // gpgv method, so we need to save it here
+ MetaIndexFileSignature = DestFile;
+ QueueForSignatureVerify(MetaIndexFile, MetaIndexFileSignature);
+ }
return;
}
-
- if (FileName != DestFile)
+ else
{
- // We have to copy it into place
- Local = true;
- Desc.URI = "copy:" + FileName;
- QueueURI(Desc);
- return;
+ if(CheckAuthDone(Message, RealURI) == true)
+ {
+ std::string FinalFile = _config->FindDir("Dir::State::lists");
+ FinalFile += URItoFileName(RealURI);
+ TransactionManager->TransactionStageCopy(this, MetaIndexFileSignature, FinalFile);
+ }
}
-
- 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);
-
}
/*}}}*/
void pkgAcqMetaSig::Failed(string Message,pkgAcquire::MethodConfig *Cnf)/*{{{*/
{
string Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
- // 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(LastGoodSig))
- Rename(LastGoodSig,Final);
+ // check if we need to fail at this point
+ if (AuthPass == true && CheckStopAuthentication(RealURI, Message))
+ return;
- // set the status back to , Item::Failed likes to reset it
- Status = pkgAcquire::Item::StatTransientNetworkError;
- return;
- }
+ // FIXME: meh, this is not really elegant
+ string InReleaseURI = RealURI.replace(RealURI.rfind("Release.gpg"), 12,
+ "InRelease");
+ string FinalInRelease = _config->FindDir("Dir::State::lists") + URItoFileName(InReleaseURI);
- // Delete any existing sigfile when the acquire failed
- unlink(Final.c_str());
+ if (RealFileExists(Final) || RealFileExists(FinalInRelease))
+ {
+ std::string downgrade_msg;
+ strprintf(downgrade_msg, _("The repository '%s' is no longer signed."),
+ URIDesc.c_str());
+ if(_config->FindB("Acquire::AllowDowngradeToInsecureRepositories"))
+ {
+ // meh, the users wants to take risks (we still mark the packages
+ // from this repository as unauthenticated)
+ _error->Warning("%s", downgrade_msg.c_str());
+ _error->Warning(_("This is normally not allowed, but the option "
+ "Acquire::AllowDowngradeToInsecureRepositories was "
+ "given to override it."));
+
+ } else {
+ _error->Error("%s", downgrade_msg.c_str());
+ Rename(MetaIndexFile, MetaIndexFile+".FAILED");
+ Item::Failed("Message: " + downgrade_msg, Cnf);
+ TransactionManager->AbortTransaction();
+ return;
+ }
+ }
+ else
+ _error->Warning(_("The data from '%s' is not signed. Packages "
+ "from that repository can not be authenticated."),
+ URIDesc.c_str());
+
+ // this ensures that any file in the lists/ dir is removed by the
+ // transaction
+ DestFile = GetPartialFileNameFromURI(RealURI);
+ TransactionManager->TransactionStageRemoval(this, DestFile);
+
+ // only allow going further if the users explicitely wants it
+ if(MetaIndexParser->IsAlwaysTrusted() || _config->FindB("Acquire::AllowInsecureRepositories") == true)
+ {
+ // we parse the indexes here because at this point the user wanted
+ // a repository that may potentially harm him
+ MetaIndexParser->Load(MetaIndexFile);
+ QueueIndexes(true);
+ }
+ else
+ {
+ _error->Error("Use --allow-insecure-repositories to force the update");
+ }
- // queue a pkgAcqMetaIndex with no sigfile
- new pkgAcqMetaIndex(Owner, MetaIndexURI, MetaIndexURIDesc, MetaIndexShortDesc,
- "", IndexTargets, MetaIndexParser);
+ Item::Failed(Message,Cnf);
- if (Cnf->LocalOnly == true ||
+ // FIXME: this is used often (e.g. in pkgAcqIndexTrans) so refactor
+ if (Cnf->LocalOnly == true ||
StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
- {
+ {
// Ignore this
Status = StatDone;
- Complete = false;
- Dequeue();
- return;
}
-
- Item::Failed(Message,Cnf);
}
/*}}}*/
pkgAcqMetaIndex::pkgAcqMetaIndex(pkgAcquire *Owner, /*{{{*/
+ pkgAcqMetaBase *TransactionManager,
string URI,string URIDesc,string ShortDesc,
- string SigFile,
- const vector<struct IndexTarget*>* IndexTargets,
+ string MetaIndexSigURI,string MetaIndexSigURIDesc, string MetaIndexSigShortDesc,
+ const vector<IndexTarget*>* IndexTargets,
indexRecords* MetaIndexParser) :
- Item(Owner), RealURI(URI), SigFile(SigFile), IndexTargets(IndexTargets),
- MetaIndexParser(MetaIndexParser), AuthPass(false), IMSHit(false)
+ pkgAcqMetaBase(Owner, IndexTargets, MetaIndexParser, HashStringList(),
+ TransactionManager),
+ RealURI(URI), URIDesc(URIDesc), ShortDesc(ShortDesc),
+ MetaIndexSigURI(MetaIndexSigURI), MetaIndexSigURIDesc(MetaIndexSigURIDesc),
+ MetaIndexSigShortDesc(MetaIndexSigShortDesc)
{
- DestFile = _config->FindDir("Dir::State::lists") + "partial/";
- DestFile += URItoFileName(URI);
+ if(TransactionManager == NULL)
+ {
+ this->TransactionManager = this;
+ this->TransactionManager->Add(this);
+ }
+
+ if(_config->FindB("Debug::Acquire::Transaction", false) == true)
+ std::clog << "New pkgAcqMetaIndex with TransactionManager "
+ << this->TransactionManager << std::endl;
+
+
+ Init(URIDesc, ShortDesc);
+}
+ /*}}}*/
+// pkgAcqMetaIndex::Init - Delayed constructor /*{{{*/
+void pkgAcqMetaIndex::Init(std::string URIDesc, std::string ShortDesc)
+{
+ DestFile = GetPartialFileNameFromURI(RealURI);
// Create the item
Desc.Description = URIDesc;
Desc.Owner = this;
Desc.ShortDesc = ShortDesc;
- Desc.URI = URI;
+ Desc.URI = RealURI;
+ // we expect more item
+ ExpectedAdditionalItems = IndexTargets->size();
QueueURI(Desc);
}
/*}}}*/
// pkgAcqMetaIndex::Custom600Headers - Insert custom request headers /*{{{*/
// ---------------------------------------------------------------------
-/* The only header we use is the last-modified header. */
-string pkgAcqMetaIndex::Custom600Headers()
+string pkgAcqMetaIndex::Custom600Headers() const
{
- string Final = _config->FindDir("Dir::State::lists");
- Final += URItoFileName(RealURI);
-
- struct stat Buf;
- if (stat(Final.c_str(),&Buf) != 0)
- return "\nIndex-File: true";
-
- return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
+ return GetCustom600Headers(RealURI);
}
/*}}}*/
-void pkgAcqMetaIndex::Done(string Message,unsigned long long Size,string Hash, /*{{{*/
+void pkgAcqMetaIndex::Done(string Message,unsigned long long Size, /*{{{*/
+ HashStringList const &Hashes,
pkgAcquire::MethodConfig *Cfg)
{
- Item::Done(Message,Size,Hash,Cfg);
+ Item::Done(Message,Size,Hashes,Cfg);
- // MetaIndexes are done in two passes: one to download the
- // metaindex with an appropriate method, and a second to verify it
- // with the gpgv method
-
- if (AuthPass == true)
+ if(CheckDownloadDone(Message, RealURI))
{
- AuthDone(Message);
+ // we have a Release file, now download the Signature, all further
+ // verify/queue for additional downloads will be done in the
+ // pkgAcqMetaSig::Done() code
+ std::string MetaIndexFile = DestFile;
+ new pkgAcqMetaSig(Owner, TransactionManager,
+ MetaIndexSigURI, MetaIndexSigURIDesc,
+ MetaIndexSigShortDesc, MetaIndexFile, IndexTargets,
+ MetaIndexParser);
- // all cool, move Release file into place
- Complete = true;
+ string FinalFile = _config->FindDir("Dir::State::lists");
+ FinalFile += URItoFileName(RealURI);
+ TransactionManager->TransactionStageCopy(this, DestFile, FinalFile);
}
- else
- {
- RetrievalDone(Message);
- if (!Complete)
- // Still more retrieving to do
- return;
+}
+ /*}}}*/
+bool pkgAcqMetaBase::CheckAuthDone(string Message, const string &RealURI) /*{{{*/
+{
+ // At this point, the gpgv method has succeeded, so there is a
+ // valid signature from a key in the trusted keyring. We
+ // perform additional verification of its contents, and use them
+ // to verify the indexes we are about to download
- if (SigFile == "")
- {
- // There was no signature file, so we are finished. Download
- // the indexes and do only hashsum verification if possible
- MetaIndexParser->Load(DestFile);
- QueueIndexes(false);
- }
- else
- {
- // There was a signature file, so pass it to gpgv for
- // verification
-
- if (_config->FindB("Debug::pkgAcquire::Auth", false))
- std::cerr << "Metaindex acquired, queueing gpg verification ("
- << SigFile << "," << DestFile << ")\n";
- AuthPass = true;
- Desc.URI = "gpgv:" + SigFile;
- QueueURI(Desc);
- Mode = "gpgv";
- return;
- }
+ if (!MetaIndexParser->Load(DestFile))
+ {
+ Status = StatAuthError;
+ ErrorText = MetaIndexParser->ErrorText;
+ return false;
}
- if (Complete == true)
+ if (!VerifyVendor(Message, RealURI))
{
- string FinalFile = _config->FindDir("Dir::State::lists");
- FinalFile += URItoFileName(RealURI);
- if (SigFile == DestFile)
- SigFile = FinalFile;
- Rename(DestFile,FinalFile);
- chmod(FinalFile.c_str(),0644);
- DestFile = FinalFile;
+ return false;
}
+
+ if (_config->FindB("Debug::pkgAcquire::Auth", false))
+ std::cerr << "Signature verification succeeded: "
+ << DestFile << std::endl;
+
+ // Download further indexes with verification
+ //
+ // it would be really nice if we could simply do
+ // if (IMSHit == false) QueueIndexes(true)
+ // and skip the download if the Release file has not changed
+ // - but right now the list cleaner will needs to be tricked
+ // to not delete all our packages/source indexes in this case
+ QueueIndexes(true);
+
+ return true;
}
/*}}}*/
-void pkgAcqMetaIndex::RetrievalDone(string Message) /*{{{*/
+// pkgAcqMetaBase::GetCustom600Headers - Get header for AcqMetaBase /*{{{*/
+// ---------------------------------------------------------------------
+string pkgAcqMetaBase::GetCustom600Headers(const string &RealURI) const
+{
+ std::string Header = "\nIndex-File: true";
+ std::string MaximumSize;
+ strprintf(MaximumSize, "\nMaximum-Size: %i",
+ _config->FindI("Acquire::MaxReleaseFileSize", 10*1000*1000));
+ Header += MaximumSize;
+
+ string FinalFile = _config->FindDir("Dir::State::lists");
+ FinalFile += URItoFileName(RealURI);
+
+ struct stat Buf;
+ if (stat(FinalFile.c_str(),&Buf) == 0)
+ Header += "\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
+
+ return Header;
+}
+ /*}}}*/
+// pkgAcqMetaBase::QueueForSignatureVerify /*{{{*/
+void pkgAcqMetaBase::QueueForSignatureVerify(const std::string &MetaIndexFile,
+ const std::string &MetaIndexFileSignature)
+{
+ AuthPass = true;
+ Desc.URI = "gpgv:" + MetaIndexFileSignature;
+ DestFile = MetaIndexFile;
+ QueueURI(Desc);
+ SetActiveSubprocess("gpgv");
+}
+ /*}}}*/
+// pkgAcqMetaBase::CheckDownloadDone /*{{{*/
+bool pkgAcqMetaBase::CheckDownloadDone(const std::string &Message,
+ const std::string &RealURI)
{
// We have just finished downloading a Release file (it is not
// verified yet)
@@ -1497,7 +1950,7 @@ void pkgAcqMetaIndex::RetrievalDone(string Message) /*{{{*/
{
Status = StatError;
ErrorText = "Method gave a blank filename";
- return;
+ return false;
}
if (FileName != DestFile)
@@ -1505,7 +1958,7 @@ void pkgAcqMetaIndex::RetrievalDone(string Message) /*{{{*/
Local = true;
Desc.URI = "copy:" + FileName;
QueueURI(Desc);
- return;
+ return false;
}
// make sure to verify against the right file on I-M-S hit
@@ -1514,95 +1967,17 @@ 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;
-}
- /*}}}*/
-void pkgAcqMetaIndex::AuthDone(string Message) /*{{{*/
-{
- // At this point, the gpgv method has succeeded, so there is a
- // valid signature from a key in the trusted keyring. We
- // perform additional verification of its contents, and use them
- // to verify the indexes we are about to download
-
- if (!MetaIndexParser->Load(DestFile))
- {
- Status = StatAuthError;
- ErrorText = MetaIndexParser->ErrorText;
- return;
- }
-
- if (!VerifyVendor(Message))
- {
- return;
- }
-
- if (_config->FindB("Debug::pkgAcquire::Auth", false))
- std::cerr << "Signature verification succeeded: "
- << DestFile << std::endl;
- // do not trust any previously unverified content that we may have
- string LastGoodSigFile = _config->FindDir("Dir::State::lists").append("partial/").append(URItoFileName(RealURI));
- if (DestFile != SigFile)
- LastGoodSigFile.append(".gpg");
- LastGoodSigFile.append(".reverify");
- if(IMSHit == false && RealFileExists(LastGoodSigFile) == false)
- {
- for (vector <struct IndexTarget*>::const_iterator Target = IndexTargets->begin();
- Target != IndexTargets->end();
- ++Target)
- {
- // remove old indexes
- std::string index = _config->FindDir("Dir::State::lists") +
- URItoFileName((*Target)->URI);
- unlink(index.c_str());
- // and also old gzipindexes
- std::vector<std::string> types = APT::Configuration::getCompressionTypes();
- for (std::vector<std::string>::const_iterator t = types.begin(); t != types.end(); ++t)
- {
- index += '.' + (*t);
- unlink(index.c_str());
- }
- }
- }
-
-
- // Download further indexes with verification
- QueueIndexes(true);
-
- // is it a clearsigned MetaIndex file?
- if (DestFile == SigFile)
- return;
+ // set Item to complete as the remaining work is all local (verify etc)
+ Complete = true;
- // Done, move signature file into position
- string VerifiedSigFile = _config->FindDir("Dir::State::lists") +
- URItoFileName(RealURI) + ".gpg";
- Rename(SigFile,VerifiedSigFile);
- chmod(VerifiedSigFile.c_str(),0644);
+ return true;
}
/*}}}*/
-void pkgAcqMetaIndex::QueueIndexes(bool verify) /*{{{*/
+void pkgAcqMetaBase::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
bool transInRelease = false;
{
std::vector<std::string> const keys = MetaIndexParser->MetaKeys();
@@ -1615,11 +1990,13 @@ void pkgAcqMetaIndex::QueueIndexes(bool verify) /*{{{*/
}
}
- for (vector <struct IndexTarget*>::const_iterator Target = IndexTargets->begin();
+ // at this point the real Items are loaded in the fetcher
+ ExpectedAdditionalItems = 0;
+ for (vector <IndexTarget*>::const_iterator Target = IndexTargets->begin();
Target != IndexTargets->end();
++Target)
{
- HashString ExpectedIndexHash;
+ HashStringList ExpectedIndexHashes;
const indexRecords::checkSum *Record = MetaIndexParser->Lookup((*Target)->MetaKey);
bool compressedAvailable = false;
if (Record == NULL)
@@ -1643,14 +2020,16 @@ void pkgAcqMetaIndex::QueueIndexes(bool verify) /*{{{*/
}
else
{
- ExpectedIndexHash = Record->Hash;
+ ExpectedIndexHashes = Record->Hashes;
if (_config->FindB("Debug::pkgAcquire::Auth", false))
{
- std::cerr << "Queueing: " << (*Target)->URI << std::endl;
- std::cerr << "Expected Hash: " << ExpectedIndexHash.toStr() << std::endl;
+ std::cerr << "Queueing: " << (*Target)->URI << std::endl
+ << "Expected Hash:" << std::endl;
+ for (HashStringList::const_iterator hs = ExpectedIndexHashes.begin(); hs != ExpectedIndexHashes.end(); ++hs)
+ std::cerr << "\t- " << hs->toStr() << std::endl;
std::cerr << "For: " << Record->MetaKeyFilename << std::endl;
}
- if (verify == true && ExpectedIndexHash.empty() == true && (*Target)->IsOptional() == false)
+ if (verify == true && ExpectedIndexHashes.empty() == true && (*Target)->IsOptional() == false)
{
Status = StatAuthError;
strprintf(ErrorText, _("Unable to find hash sum for '%s' in Release file"), (*Target)->MetaKey.c_str());
@@ -1660,17 +2039,13 @@ void pkgAcqMetaIndex::QueueIndexes(bool verify) /*{{{*/
if ((*Target)->IsOptional() == true)
{
- if ((*Target)->IsSubIndex() == true)
- new pkgAcqSubIndex(Owner, (*Target)->URI, (*Target)->Description,
- (*Target)->ShortDesc, ExpectedIndexHash);
- else if (transInRelease == false || Record != NULL || compressedAvailable == true)
+ if (transInRelease == false || Record != NULL || compressedAvailable == true)
{
if (_config->FindB("Acquire::PDiffs",true) == true && transInRelease == true &&
MetaIndexParser->Exists((*Target)->MetaKey + ".diff/Index") == true)
- new pkgAcqDiffIndex(Owner, (*Target)->URI, (*Target)->Description,
- (*Target)->ShortDesc, ExpectedIndexHash);
+ new pkgAcqDiffIndex(Owner, TransactionManager, *Target, ExpectedIndexHashes, MetaIndexParser);
else
- new pkgAcqIndexTrans(Owner, *Target, ExpectedIndexHash, MetaIndexParser);
+ new pkgAcqIndexTrans(Owner, TransactionManager, *Target, ExpectedIndexHashes, MetaIndexParser);
}
continue;
}
@@ -1681,14 +2056,13 @@ void pkgAcqMetaIndex::QueueIndexes(bool verify) /*{{{*/
instead, but passing the required info to it is to much hassle */
if(_config->FindB("Acquire::PDiffs",true) == true && (verify == false ||
MetaIndexParser->Exists((*Target)->MetaKey + ".diff/Index") == true))
- new pkgAcqDiffIndex(Owner, (*Target)->URI, (*Target)->Description,
- (*Target)->ShortDesc, ExpectedIndexHash);
+ new pkgAcqDiffIndex(Owner, TransactionManager, *Target, ExpectedIndexHashes, MetaIndexParser);
else
- new pkgAcqIndex(Owner, *Target, ExpectedIndexHash, MetaIndexParser);
+ new pkgAcqIndex(Owner, TransactionManager, *Target, ExpectedIndexHashes, MetaIndexParser);
}
}
/*}}}*/
-bool pkgAcqMetaIndex::VerifyVendor(string Message) /*{{{*/
+bool pkgAcqMetaBase::VerifyVendor(string Message, const string &RealURI)/*{{{*/
{
string::size_type pos;
@@ -1765,147 +2139,174 @@ bool pkgAcqMetaIndex::VerifyVendor(string Message) /*{{{*/
return true;
}
/*}}}*/
-// pkgAcqMetaIndex::Failed - no Release file present or no signature file present /*{{{*/
-// ---------------------------------------------------------------------
-/* */
-void pkgAcqMetaIndex::Failed(string Message,pkgAcquire::MethodConfig * /*Cnf*/)
+// pkgAcqMetaIndex::Failed - no Release file present /*{{{*/
+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").append("partial/").append(URItoFileName(RealURI));
- if (DestFile != SigFile)
- LastGoodSigFile.append(".gpg");
- LastGoodSigFile.append(".reverify");
+ pkgAcquire::Item::Failed(Message, Cnf);
+ Status = StatDone;
- if(FileExists(LastGoodSigFile))
- {
- string VerifiedSigFile = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
- if (DestFile != SigFile)
- VerifiedSigFile.append(".gpg");
- Rename(LastGoodSigFile, VerifiedSigFile);
- Status = StatTransientNetworkError;
- _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"),
- Desc.Description.c_str(),
- 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(),
- LookupTag(Message,"Message").c_str());
- }
- // gpgv method failed
- ReportMirrorFailure("GPGFailure");
- }
+ string FinalFile = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
- /* 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);
+ _error->Warning(_("The repository '%s' does not have a Release file. "
+ "This is deprecated, please contact the owner of the "
+ "repository."), URIDesc.c_str());
- DestFile = FinalFile;
- }
-
- // No Release file was present, or verification failed, so fall
+ // No Release file was present so fall
// back to queueing Packages files without verification
- QueueIndexes(false);
+ // only allow going further if the users explicitely wants it
+ if(MetaIndexParser->IsAlwaysTrusted() || _config->FindB("Acquire::AllowInsecureRepositories") == true)
+ {
+ // Done, queue for rename on transaction finished
+ if (FileExists(DestFile))
+ TransactionManager->TransactionStageCopy(this, DestFile, FinalFile);
+
+ // queue without any kind of hashsum support
+ QueueIndexes(false);
+ } else {
+ // warn if the repository is unsinged
+ _error->Error("Use --allow-insecure-repositories to force the update");
+ TransactionManager->AbortTransaction();
+ Status = StatError;
+ return;
+ }
+}
+ /*}}}*/
+void pkgAcqMetaIndex::Finished() /*{{{*/
+{
+ if(_config->FindB("Debug::Acquire::Transaction", false) == true)
+ std::clog << "Finished: " << DestFile <<std::endl;
+ if(TransactionManager != NULL &&
+ TransactionManager->TransactionHasError() == false)
+ TransactionManager->CommitTransaction();
}
/*}}}*/
pkgAcqMetaClearSig::pkgAcqMetaClearSig(pkgAcquire *Owner, /*{{{*/
string const &URI, string const &URIDesc, string const &ShortDesc,
string const &MetaIndexURI, string const &MetaIndexURIDesc, string const &MetaIndexShortDesc,
string const &MetaSigURI, string const &MetaSigURIDesc, string const &MetaSigShortDesc,
- const vector<struct IndexTarget*>* IndexTargets,
+ const vector<IndexTarget*>* IndexTargets,
indexRecords* MetaIndexParser) :
- pkgAcqMetaIndex(Owner, URI, URIDesc, ShortDesc, "", IndexTargets, MetaIndexParser),
- MetaIndexURI(MetaIndexURI), MetaIndexURIDesc(MetaIndexURIDesc), MetaIndexShortDesc(MetaIndexShortDesc),
- MetaSigURI(MetaSigURI), MetaSigURIDesc(MetaSigURIDesc), MetaSigShortDesc(MetaSigShortDesc)
+ pkgAcqMetaIndex(Owner, NULL, URI, URIDesc, ShortDesc, MetaSigURI, MetaSigURIDesc,MetaSigShortDesc, IndexTargets, MetaIndexParser),
+ MetaIndexURI(MetaIndexURI), MetaIndexURIDesc(MetaIndexURIDesc), MetaIndexShortDesc(MetaIndexShortDesc),
+ MetaSigURI(MetaSigURI), MetaSigURIDesc(MetaSigURIDesc), MetaSigShortDesc(MetaSigShortDesc)
{
- SigFile = DestFile;
+ // index targets + (worst case:) Release/Release.gpg
+ ExpectedAdditionalItems = IndexTargets->size() + 2;
- // keep the old InRelease around in case of transistent network errors
- string const Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
- if (RealFileExists(Final) == true)
- {
- string const LastGoodSig = DestFile + ".reverify";
- Rename(Final,LastGoodSig);
- }
}
/*}}}*/
pkgAcqMetaClearSig::~pkgAcqMetaClearSig() /*{{{*/
{
- // if the file was never queued undo file-changes done in the constructor
- if (QueueCounter == 1 && Status == StatIdle && FileSize == 0 && Complete == false)
- {
- string const Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
- string const LastGoodSig = DestFile + ".reverify";
- if (RealFileExists(Final) == false && RealFileExists(LastGoodSig) == true)
- Rename(LastGoodSig, Final);
- }
}
/*}}}*/
// pkgAcqMetaClearSig::Custom600Headers - Insert custom request headers /*{{{*/
// ---------------------------------------------------------------------
-// FIXME: this can go away once the InRelease file is used widely
-string pkgAcqMetaClearSig::Custom600Headers()
+string pkgAcqMetaClearSig::Custom600Headers() const
{
- string Final = _config->FindDir("Dir::State::lists");
- Final += URItoFileName(RealURI);
+ string Header = GetCustom600Headers(RealURI);
+ Header += "\nFail-Ignore: true";
+ return Header;
+}
+ /*}}}*/
+// pkgAcqMetaClearSig::Done - We got a file /*{{{*/
+// ---------------------------------------------------------------------
+void pkgAcqMetaClearSig::Done(std::string Message,unsigned long long /*Size*/,
+ HashStringList const &/*Hashes*/,
+ pkgAcquire::MethodConfig *Cnf)
+{
+ // if we expect a ClearTextSignature (InRelase), ensure that
+ // this is what we get and if not fail to queue a
+ // Release/Release.gpg, see #346386
+ if (FileExists(DestFile) && !StartsWithGPGClearTextSignature(DestFile))
+ {
+ pkgAcquire::Item::Failed(Message, Cnf);
+ RenameOnError(NotClearsigned);
+ TransactionManager->AbortTransaction();
+ return;
+ }
- struct stat Buf;
- if (stat(Final.c_str(),&Buf) != 0)
+ if(AuthPass == false)
{
- Final = DestFile + ".reverify";
- if (stat(Final.c_str(),&Buf) != 0)
- return "\nIndex-File: true\nFail-Ignore: true\n";
+ if(CheckDownloadDone(Message, RealURI) == true)
+ QueueForSignatureVerify(DestFile, DestFile);
+ return;
}
+ else
+ {
+ if(CheckAuthDone(Message, RealURI) == true)
+ {
+ string FinalFile = _config->FindDir("Dir::State::lists");
+ FinalFile += URItoFileName(RealURI);
- return "\nIndex-File: true\nFail-Ignore: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
+ // queue for copy in place
+ TransactionManager->TransactionStageCopy(this, DestFile, FinalFile);
+ }
+ }
}
/*}}}*/
void pkgAcqMetaClearSig::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
{
+ Item::Failed(Message, Cnf);
+
+ // we failed, we will not get additional items from this method
+ ExpectedAdditionalItems = 0;
+
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)
+ // Queue the 'old' InRelease file for removal if we try Release.gpg
+ // 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());
+ TransactionManager->TransactionStageRemoval(this, FinalFile);
+ Status = StatDone;
- new pkgAcqMetaSig(Owner,
- MetaSigURI, MetaSigURIDesc, MetaSigShortDesc,
+ new pkgAcqMetaIndex(Owner, TransactionManager,
MetaIndexURI, MetaIndexURIDesc, MetaIndexShortDesc,
+ MetaSigURI, MetaSigURIDesc, MetaSigShortDesc,
IndexTargets, MetaIndexParser);
- if (Cnf->LocalOnly == true ||
- StringToBool(LookupTag(Message, "Transient-Failure"), false) == false)
- Dequeue();
}
else
- pkgAcqMetaIndex::Failed(Message, Cnf);
+ {
+ if(CheckStopAuthentication(RealURI, Message))
+ return;
+
+ _error->Warning(_("The data from '%s' is not signed. Packages "
+ "from that repository can not be authenticated."),
+ URIDesc.c_str());
+
+ // No Release file was present, or verification failed, so fall
+ // back to queueing Packages files without verification
+ // only allow going further if the users explicitely wants it
+ if(MetaIndexParser->IsAlwaysTrusted() || _config->FindB("Acquire::AllowInsecureRepositories") == true)
+ {
+ Status = StatDone;
+
+ /* 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 */
+ RealURI = RealURI.replace(RealURI.rfind("InRelease"), 9,
+ "Release");
+ FinalFile = FinalFile.replace(FinalFile.rfind("InRelease"), 9,
+ "Release");
+
+ // Done, queue for rename on transaction finished
+ TransactionManager->TransactionStageCopy(this, DestFile, FinalFile);
+ }
+ QueueIndexes(false);
+ } else {
+ // warn if the repository is unsigned
+ _error->Error("Use --allow-insecure-repositories to force the update");
+ TransactionManager->AbortTransaction();
+ Status = StatError;
+ }
+ }
}
/*}}}*/
// AcqArchive::AcqArchive - Constructor /*{{{*/
@@ -1915,7 +2316,7 @@ void pkgAcqMetaClearSig::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*
pkgAcqArchive::pkgAcqArchive(pkgAcquire *Owner,pkgSourceList *Sources,
pkgRecords *Recs,pkgCache::VerIterator const &Version,
string &StoreFilename) :
- Item(Owner), Version(Version), Sources(Sources), Recs(Recs),
+ Item(Owner, HashStringList()), Version(Version), Sources(Sources), Recs(Recs),
StoreFilename(StoreFilename), Vf(Version.FileList()),
Trusted(false)
{
@@ -2000,7 +2401,6 @@ pkgAcqArchive::pkgAcqArchive(pkgAcquire *Owner,pkgSourceList *Sources,
checking later. */
bool pkgAcqArchive::QueueNext()
{
- string const ForceHash = _config->Find("Acquire::ForceHash");
for (; Vf.end() == false; ++Vf)
{
// Ignore not source sources
@@ -2021,31 +2421,10 @@ bool pkgAcqArchive::QueueNext()
pkgRecords::Parser &Parse = Recs->Lookup(Vf);
if (_error->PendingError() == true)
return false;
-
+
string PkgFile = Parse.FileName();
- if (ForceHash.empty() == false)
- {
- if(stringcasecmp(ForceHash, "sha512") == 0)
- ExpectedHash = HashString("SHA512", Parse.SHA512Hash());
- else if(stringcasecmp(ForceHash, "sha256") == 0)
- ExpectedHash = HashString("SHA256", Parse.SHA256Hash());
- else if (stringcasecmp(ForceHash, "sha1") == 0)
- ExpectedHash = HashString("SHA1", Parse.SHA1Hash());
- else
- ExpectedHash = HashString("MD5Sum", Parse.MD5Hash());
- }
- else
- {
- string Hash;
- 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);
- else
- ExpectedHash = HashString("MD5Sum", Parse.MD5Hash());
- }
+ ExpectedHashes = Parse.Hashes();
+
if (PkgFile.empty() == true)
return _error->Error(_("The package index files are corrupted. No Filename: "
"field for package %s."),
@@ -2105,7 +2484,11 @@ bool pkgAcqArchive::QueueNext()
if ((unsigned long long)Buf.st_size > Version->Size)
unlink(DestFile.c_str());
else
+ {
PartialSize = Buf.st_size;
+ std::string SandboxUser = _config->Find("APT::Sandbox::User");
+ ChangeOwnerAndPermissionOfFile("pkgAcqArchive::QueueNext",DestFile.c_str(), SandboxUser.c_str(), "root", 0600);
+ }
}
// Disables download of archives - useful if no real installation follows,
@@ -2132,10 +2515,10 @@ bool pkgAcqArchive::QueueNext()
// AcqArchive::Done - Finished fetching /*{{{*/
// ---------------------------------------------------------------------
/* */
-void pkgAcqArchive::Done(string Message,unsigned long long Size,string CalcHash,
+void pkgAcqArchive::Done(string Message,unsigned long long Size, HashStringList const &CalcHashes,
pkgAcquire::MethodConfig *Cfg)
{
- Item::Done(Message,Size,CalcHash,Cfg);
+ Item::Done(Message, Size, CalcHashes, Cfg);
// Check the size
if (Size != Version->Size)
@@ -2143,11 +2526,12 @@ void pkgAcqArchive::Done(string Message,unsigned long long Size,string CalcHash,
RenameOnError(SizeMismatch);
return;
}
-
- // Check the hash
- if(ExpectedHash.toStr() != CalcHash)
+
+ // FIXME: could this empty() check impose *any* sort of security issue?
+ if(ExpectedHashes.usable() && ExpectedHashes != CalcHashes)
{
RenameOnError(HashSumMismatch);
+ printHashSumComparision(DestFile, ExpectedHashes, CalcHashes);
return;
}
@@ -2160,21 +2544,20 @@ void pkgAcqArchive::Done(string Message,unsigned long long Size,string CalcHash,
return;
}
- Complete = true;
-
// Reference filename
if (FileName != DestFile)
{
StoreFilename = DestFile = FileName;
Local = true;
+ Complete = true;
return;
}
-
+
// Done, move it into position
string FinalFile = _config->FindDir("Dir::Cache::Archives");
FinalFile += flNotDir(StoreFilename);
Rename(DestFile,FinalFile);
-
+ ChangeOwnerAndPermissionOfFile("pkgAcqArchive::Done", FinalFile.c_str(), "root", "root", 0644);
StoreFilename = DestFile = FinalFile;
Complete = true;
}
@@ -2219,7 +2602,7 @@ void pkgAcqArchive::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
/*}}}*/
// AcqArchive::IsTrusted - Determine whether this archive comes from a trusted source /*{{{*/
// ---------------------------------------------------------------------
-APT_PURE bool pkgAcqArchive::IsTrusted()
+APT_PURE bool pkgAcqArchive::IsTrusted() const
{
return Trusted;
}
@@ -2238,11 +2621,11 @@ void pkgAcqArchive::Finished()
// AcqFile::pkgAcqFile - Constructor /*{{{*/
// ---------------------------------------------------------------------
/* The file is added to the queue */
-pkgAcqFile::pkgAcqFile(pkgAcquire *Owner,string URI,string Hash,
+pkgAcqFile::pkgAcqFile(pkgAcquire *Owner,string URI, HashStringList const &Hashes,
unsigned long long Size,string Dsc,string ShortDesc,
const string &DestDir, const string &DestFilename,
bool IsIndexFile) :
- Item(Owner), ExpectedHash(Hash), IsIndexFile(IsIndexFile)
+ Item(Owner, Hashes), IsIndexFile(IsIndexFile)
{
Retries = _config->FindI("Acquire::Retries",0);
@@ -2270,7 +2653,11 @@ pkgAcqFile::pkgAcqFile(pkgAcquire *Owner,string URI,string Hash,
if ((Size > 0) && (unsigned long long)Buf.st_size > Size)
unlink(DestFile.c_str());
else
+ {
PartialSize = Buf.st_size;
+ std::string SandboxUser = _config->Find("APT::Sandbox::User");
+ ChangeOwnerAndPermissionOfFile("pkgAcqFile", DestFile.c_str(), SandboxUser.c_str(), "root", 0600);
+ }
}
QueueURI(Desc);
@@ -2279,15 +2666,16 @@ pkgAcqFile::pkgAcqFile(pkgAcquire *Owner,string URI,string Hash,
// AcqFile::Done - Item downloaded OK /*{{{*/
// ---------------------------------------------------------------------
/* */
-void pkgAcqFile::Done(string Message,unsigned long long Size,string CalcHash,
+void pkgAcqFile::Done(string Message,unsigned long long Size,HashStringList const &CalcHashes,
pkgAcquire::MethodConfig *Cnf)
{
- Item::Done(Message,Size,CalcHash,Cnf);
+ Item::Done(Message,Size,CalcHashes,Cnf);
// Check the hash
- if(!ExpectedHash.empty() && ExpectedHash.toStr() != CalcHash)
+ if(ExpectedHashes.usable() && ExpectedHashes != CalcHashes)
{
RenameOnError(HashSumMismatch);
+ printHashSumComparision(DestFile, ExpectedHashes, CalcHashes);
return;
}
@@ -2358,7 +2746,7 @@ void pkgAcqFile::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
// AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
// ---------------------------------------------------------------------
/* The only header we use is the last-modified header. */
-string pkgAcqFile::Custom600Headers()
+string pkgAcqFile::Custom600Headers() const
{
if (IsIndexFile)
return "\nIndex-File: true";
diff --git a/apt-pkg/acquire-item.h b/apt-pkg/acquire-item.h
index 384c5ee2b..68d5a01ce 100644
--- a/apt-pkg/acquire-item.h
+++ b/apt-pkg/acquire-item.h
@@ -46,6 +46,8 @@
class indexRecords;
class pkgRecords;
class pkgSourceList;
+class IndexTarget;
+class pkgAcqMetaBase;
/** \brief Represents the process by which a pkgAcquire object should {{{
* retrieve a file or a collection of files.
@@ -61,6 +63,8 @@ class pkgSourceList;
*/
class pkgAcquire::Item : public WeakPointable
{
+ void *d;
+
protected:
/** \brief The acquire object with which this item is associated. */
@@ -71,12 +75,11 @@ class pkgAcquire::Item : public WeakPointable
* \param Item Metadata about this item (its URI and
* description).
*/
- inline void QueueURI(ItemDesc &Item)
- {Owner->Enqueue(Item);};
+ void QueueURI(ItemDesc &Item);
/** \brief Remove this item from its owner's queue. */
- inline void Dequeue() {Owner->Dequeue(this);};
-
+ void Dequeue();
+
/** \brief Rename a file without modifying its timestamp.
*
* Many item methods call this as their final action.
@@ -86,7 +89,7 @@ class pkgAcquire::Item : public WeakPointable
* \param To The new name of \a From. If \a To exists it will be
* overwritten.
*/
- void Rename(std::string From,std::string To);
+ bool Rename(std::string From,std::string To);
public:
@@ -115,7 +118,7 @@ class pkgAcquire::Item : public WeakPointable
/** \brief The item was could not be downloaded because of
* a transient network error (e.g. network down)
*/
- StatTransientNetworkError
+ StatTransientNetworkError,
} Status;
/** \brief Contains a textual description of the error encountered
@@ -132,7 +135,12 @@ class pkgAcquire::Item : public WeakPointable
/** \brief If not \b NULL, contains the name of a subprocess that
* is operating on this object (for instance, "gzip" or "gpgv").
*/
- const char *Mode;
+ APT_DEPRECATED const char *Mode;
+
+ /** \brief contains the name of the subprocess that is operating on this object
+ * (for instance, "gzip", "rred" or "gpgv"). This is obsoleting #Mode from above
+ * as it can manage the lifetime of included string properly. */
+ std::string ActiveSubprocess;
/** \brief A client-supplied unique identifier.
*
@@ -166,12 +174,28 @@ class pkgAcquire::Item : public WeakPointable
* \sa pkgAcquire
*/
unsigned int QueueCounter;
+
+ /** \brief TransactionManager */
+ pkgAcqMetaBase *TransactionManager;
+
+ /** \brief The number of additional fetch items that are expected
+ * once this item is done.
+ *
+ * Some items like pkgAcqMeta{Index,Sig} will queue additional
+ * items. This variable can be set by the methods if it knows
+ * in advance how many items to expect to get a more accurate
+ * progress.
+ */
+ unsigned int ExpectedAdditionalItems;
/** \brief The name of the file into which the retrieved object
* will be written.
*/
std::string DestFile;
+ /** \brief storge name until a transaction is finished */
+ std::string PartialFile;
+
/** \brief Invoked by the acquire worker when the object couldn't
* be fetched.
*
@@ -201,12 +225,12 @@ class pkgAcquire::Item : public WeakPointable
* \param Message Data from the acquire method. Use LookupTag()
* to parse it.
* \param Size The size of the object that was fetched.
- * \param Hash The HashSum of the object that was fetched.
+ * \param Hashes The HashSums of the object that was fetched.
* \param Cnf The method via which the object was fetched.
*
* \sa pkgAcqMethod
*/
- virtual void Done(std::string Message,unsigned long long Size,std::string Hash,
+ virtual void Done(std::string Message, unsigned long long Size, HashStringList const &Hashes,
pkgAcquire::MethodConfig *Cnf);
/** \brief Invoked when the worker starts to fetch this object.
@@ -228,7 +252,7 @@ class pkgAcquire::Item : public WeakPointable
* line, so they should (if nonempty) have a leading newline and
* no trailing newline.
*/
- virtual std::string Custom600Headers() {return std::string();};
+ virtual std::string Custom600Headers() const {return std::string();};
/** \brief A "descriptive" URI-like string.
*
@@ -244,20 +268,20 @@ class pkgAcquire::Item : public WeakPointable
/** \brief Invoked by the worker when the download is completely done. */
virtual void Finished() {};
- /** \brief HashSum
+ /** \brief HashSums
*
- * \return the HashSum of this object, if applicable; otherwise, an
- * empty string.
+ * \return the HashSums of this object, if applicable; otherwise, an
+ * empty list.
*/
- virtual std::string HashSum() {return std::string();};
+ HashStringList HashSums() const {return ExpectedHashes;};
+ std::string HashSum() const {HashStringList const hashes = HashSums(); HashString const * const hs = hashes.find(NULL); return hs != NULL ? hs->toStr() : ""; };
/** \return the acquire process with which this item is associated. */
- pkgAcquire *GetOwner() {return Owner;};
+ pkgAcquire *GetOwner() const {return Owner;};
/** \return \b true if this object is being fetched from a trusted source. */
- virtual bool IsTrusted() {return false;};
+ virtual bool IsTrusted() const {return false;};
- // report mirror problems
/** \brief Report mirror problem
*
* This allows reporting mirror failures back to a centralized
@@ -267,6 +291,11 @@ class pkgAcquire::Item : public WeakPointable
*/
void ReportMirrorFailure(std::string FailCode);
+ /** \brief Set the name of the current active subprocess
+ *
+ * See also #ActiveSubprocess
+ */
+ void SetActiveSubprocess(const std::string &subprocess);
/** \brief Initialize an item.
*
@@ -274,12 +303,12 @@ class pkgAcquire::Item : public WeakPointable
* process, but does not place it into any fetch queues (you must
* manually invoke QueueURI() to do so).
*
- * Initializes all fields of the item other than Owner to 0,
- * false, or the empty string.
- *
* \param Owner The new owner of this item.
+ * \param ExpectedHashes of the file represented by this item
*/
- Item(pkgAcquire *Owner);
+ Item(pkgAcquire *Owner,
+ HashStringList const &ExpectedHashes=HashStringList(),
+ pkgAcqMetaBase *TransactionManager=NULL);
/** \brief Remove this item from its owner's queue by invoking
* pkgAcquire::Remove.
@@ -291,7 +320,9 @@ class pkgAcquire::Item : public WeakPointable
enum RenameOnErrorState {
HashSumMismatch,
SizeMismatch,
- InvalidFormat
+ InvalidFormat,
+ SignatureError,
+ NotClearsigned,
};
/** \brief Rename failed file and set error
@@ -299,6 +330,12 @@ class pkgAcquire::Item : public WeakPointable
* \param state respresenting the error we encountered
*/
bool RenameOnError(RenameOnErrorState const state);
+
+ /** \brief The HashSums of the item is supposed to have than done */
+ HashStringList ExpectedHashes;
+
+ /** \brief The item that is currently being downloaded. */
+ pkgAcquire::ItemDesc Desc;
};
/*}}}*/
/** \brief Information about an index patch (aka diff). */ /*{{{*/
@@ -306,55 +343,301 @@ struct DiffInfo {
/** The filename of the diff. */
std::string file;
- /** The sha1 hash of the diff. */
- std::string sha1;
+ /** The hashes of the diff */
+ HashStringList result_hashes;
+
+ /** The hashes of the file after the diff is applied */
+ HashStringList patch_hashes;
+
+ /** The size of the file after the diff is applied */
+ unsigned long long result_size;
- /** The size of the diff. */
- unsigned long size;
+ /** The size of the diff itself */
+ unsigned long long patch_size;
};
/*}}}*/
-/** \brief An item that is responsible for fetching a SubIndex {{{
- *
- * The MetaIndex file includes only records for important indexes
- * and records for these SubIndex files so these can carry records
- * for addition files like PDiffs and Translations
- */
-class pkgAcqSubIndex : public pkgAcquire::Item
+ /*}}}*/
+
+class pkgAcqMetaBase : public pkgAcquire::Item
{
+ void *d;
+
protected:
- /** \brief If \b true, debugging information will be written to std::clog. */
- bool Debug;
+ std::vector<Item*> Transaction;
- /** \brief The item that is currently being downloaded. */
- pkgAcquire::ItemDesc Desc;
+ /** \brief A package-system-specific parser for the meta-index file. */
+ indexRecords *MetaIndexParser;
- /** \brief The Hash that this file should have after download
+ /** \brief The index files which should be looked up in the meta-index
+ * and then downloaded.
*/
- HashString ExpectedHash;
+ const std::vector<IndexTarget*>* IndexTargets;
- public:
- // Specialized action members
- virtual void Failed(std::string Message,pkgAcquire::MethodConfig *Cnf);
- virtual void Done(std::string Message,unsigned long long Size,std::string Md5Hash,
- pkgAcquire::MethodConfig *Cnf);
- virtual std::string DescURI() {return Desc.URI;};
- virtual std::string Custom600Headers();
- virtual bool ParseIndex(std::string const &IndexFile);
+ /** \brief If \b true, the index's signature is currently being verified.
+ */
+ bool AuthPass;
- /** \brief Create a new pkgAcqSubIndex.
+ // required to deal gracefully with problems caused by incorrect ims hits
+ bool IMSHit;
+
+ /** \brief Starts downloading the individual index files.
*
- * \param Owner The Acquire object that owns this item.
+ * \param verify If \b true, only indices whose expected hashsum
+ * can be determined from the meta-index will be downloaded, and
+ * the hashsums of indices will be checked (reporting
+ * #StatAuthError if there is a mismatch). If verify is \b false,
+ * no hashsum checking will be performed.
+ */
+ void QueueIndexes(bool verify);
+
+ /** \brief Called when a file is finished being retrieved.
*
- * \param URI The URI of the list file to download.
+ * If the file was not downloaded to DestFile, a copy process is
+ * set up to copy it to DestFile; otherwise, Complete is set to \b
+ * true and the file is moved to its final location.
*
- * \param URIDesc A long description of the list file to download.
+ * \param Message The message block received from the fetch
+ * subprocess.
+ */
+ bool CheckDownloadDone(const std::string &Message,
+ const std::string &RealURI);
+
+ /** \brief Queue the downloaded Signature for verification */
+ void QueueForSignatureVerify(const std::string &MetaIndexFile,
+ const std::string &MetaIndexFileSignature);
+
+ /** \brief get the custom600 header for all pkgAcqMeta */
+ std::string GetCustom600Headers(const std::string &RealURI) const;
+
+ /** \brief Called when authentication succeeded.
*
- * \param ShortDesc A short description of the list file to download.
+ * Sanity-checks the authenticated file, queues up the individual
+ * index files for download, and saves the signature in the lists
+ * directory next to the authenticated list file.
+ *
+ * \param Message The message block received from the fetch
+ * subprocess.
+ */
+ bool CheckAuthDone(std::string Message, const std::string &RealURI);
+
+ /** Check if the current item should fail at this point */
+ bool CheckStopAuthentication(const std::string &RealURI,
+ const std::string &Message);
+
+ /** \brief Check that the release file is a release file for the
+ * correct distribution.
*
- * \param ExpectedHash The list file's MD5 signature.
+ * \return \b true if no fatal errors were encountered.
+ */
+ bool VerifyVendor(std::string Message, const std::string &RealURI);
+
+ public:
+ // transaction code
+ void Add(Item *I);
+ void AbortTransaction();
+ bool TransactionHasError() APT_PURE;
+ void CommitTransaction();
+
+ /** \brief Stage (queue) a copy action when the transaction is commited
+ */
+ void TransactionStageCopy(Item *I,
+ const std::string &From,
+ const std::string &To);
+ /** \brief Stage (queue) a removal action when the transaction is commited
+ */
+ void TransactionStageRemoval(Item *I, const std::string &FinalFile);
+
+ pkgAcqMetaBase(pkgAcquire *Owner,
+ const std::vector<IndexTarget*>* IndexTargets,
+ indexRecords* MetaIndexParser,
+ HashStringList const &ExpectedHashes=HashStringList(),
+ pkgAcqMetaBase *TransactionManager=NULL)
+ : Item(Owner, ExpectedHashes, TransactionManager),
+ MetaIndexParser(MetaIndexParser), IndexTargets(IndexTargets),
+ AuthPass(false), IMSHit(false) {};
+};
+
+/** \brief An acquire item that downloads the detached signature {{{
+ * of a meta-index (Release) file, then queues up the release
+ * file itself.
+ *
+ * \todo Why protected members?
+ *
+ * \sa pkgAcqMetaIndex
+ */
+class pkgAcqMetaSig : public pkgAcqMetaBase
+{
+ void *d;
+
+ protected:
+
+ /** \brief The URI of the signature file. Unlike Desc.URI, this is
+ * never modified; it is used to determine the file that is being
+ * downloaded.
+ */
+ std::string RealURI;
+
+ /** \brief The file we need to verify */
+ std::string MetaIndexFile;
+
+ /** \brief The file we use to verify the MetaIndexFile with */
+ std::string MetaIndexFileSignature;
+
+ /** \brief Long URI description used in the acquire system */
+ std::string URIDesc;
+
+ /** \brief Short URI description used in the acquire system */
+ std::string ShortDesc;
+
+ public:
+
+ // Specialized action members
+ virtual void Failed(std::string Message,pkgAcquire::MethodConfig *Cnf);
+ virtual void Done(std::string Message,unsigned long long Size,
+ HashStringList const &Hashes,
+ pkgAcquire::MethodConfig *Cnf);
+ virtual std::string Custom600Headers() const;
+ virtual std::string DescURI() {return RealURI; };
+
+ /** \brief Create a new pkgAcqMetaSig. */
+ pkgAcqMetaSig(pkgAcquire *Owner,
+ pkgAcqMetaBase *TransactionManager,
+ std::string URI,std::string URIDesc, std::string ShortDesc,
+ std::string MetaIndexFile,
+ const std::vector<IndexTarget*>* IndexTargets,
+ indexRecords* MetaIndexParser);
+ virtual ~pkgAcqMetaSig();
+};
+ /*}}}*/
+
+/** \brief An item that is responsible for downloading the meta-index {{{
+ * file (i.e., Release) itself and verifying its signature.
+ *
+ * Once the download and verification are complete, the downloads of
+ * the individual index files are queued up using pkgAcqDiffIndex.
+ * If the meta-index file had a valid signature, the expected hashsums
+ * of the index files will be the md5sums listed in the meta-index;
+ * otherwise, the expected hashsums will be "" (causing the
+ * authentication of the index files to be bypassed).
+ */
+class pkgAcqMetaIndex : public pkgAcqMetaBase
+{
+ void *d;
+
+ protected:
+ /** \brief The URI that is actually being downloaded; never
+ * modified by pkgAcqMetaIndex.
*/
- pkgAcqSubIndex(pkgAcquire *Owner, std::string const &URI,std::string const &URIDesc,
- std::string const &ShortDesc, HashString const &ExpectedHash);
+ std::string RealURI;
+
+ std::string URIDesc;
+ std::string ShortDesc;
+
+ /** \brief The URI of the meta-index file for the detached signature */
+ std::string MetaIndexSigURI;
+
+ /** \brief A "URI-style" description of the meta-index file */
+ std::string MetaIndexSigURIDesc;
+
+ /** \brief A brief description of the meta-index file */
+ std::string MetaIndexSigShortDesc;
+
+ /** \brief delayed constructor */
+ void Init(std::string URIDesc, std::string ShortDesc);
+
+ public:
+
+ // Specialized action members
+ virtual void Failed(std::string Message,pkgAcquire::MethodConfig *Cnf);
+ virtual void Done(std::string Message,unsigned long long Size, HashStringList const &Hashes,
+ pkgAcquire::MethodConfig *Cnf);
+ virtual std::string Custom600Headers() const;
+ virtual std::string DescURI() {return RealURI; };
+ virtual void Finished();
+
+ /** \brief Create a new pkgAcqMetaIndex. */
+ pkgAcqMetaIndex(pkgAcquire *Owner,
+ pkgAcqMetaBase *TransactionManager,
+ std::string URI,std::string URIDesc, std::string ShortDesc,
+ std::string MetaIndexSigURI, std::string MetaIndexSigURIDesc, std::string MetaIndexSigShortDesc,
+ const std::vector<IndexTarget*>* IndexTargets,
+ indexRecords* MetaIndexParser);
+};
+ /*}}}*/
+/** \brief An item repsonsible for downloading clearsigned metaindexes {{{*/
+class pkgAcqMetaClearSig : public pkgAcqMetaIndex
+{
+ void *d;
+
+ /** \brief The URI of the meta-index file for the detached signature */
+ std::string MetaIndexURI;
+
+ /** \brief A "URI-style" description of the meta-index file */
+ std::string MetaIndexURIDesc;
+
+ /** \brief A brief description of the meta-index file */
+ std::string MetaIndexShortDesc;
+
+ /** \brief The URI of the detached meta-signature file if the clearsigned one failed. */
+ std::string MetaSigURI;
+
+ /** \brief A "URI-style" description of the meta-signature file */
+ std::string MetaSigURIDesc;
+
+ /** \brief A brief description of the meta-signature file */
+ std::string MetaSigShortDesc;
+
+public:
+ virtual void Failed(std::string Message,pkgAcquire::MethodConfig *Cnf);
+ virtual std::string Custom600Headers() const;
+ virtual void Done(std::string Message,unsigned long long Size,
+ HashStringList const &Hashes,
+ pkgAcquire::MethodConfig *Cnf);
+
+ /** \brief Create a new pkgAcqMetaClearSig. */
+ pkgAcqMetaClearSig(pkgAcquire *Owner,
+ std::string const &URI, std::string const &URIDesc, std::string const &ShortDesc,
+ std::string const &MetaIndexURI, std::string const &MetaIndexURIDesc, std::string const &MetaIndexShortDesc,
+ std::string const &MetaSigURI, std::string const &MetaSigURIDesc, std::string const &MetaSigShortDesc,
+ const std::vector<IndexTarget*>* IndexTargets,
+ indexRecords* MetaIndexParser);
+ virtual ~pkgAcqMetaClearSig();
+};
+ /*}}}*/
+
+
+/** \brief Common base class for all classes that deal with fetching {{{
+ indexes
+ */
+class pkgAcqBaseIndex : public pkgAcquire::Item
+{
+ void *d;
+
+ protected:
+ /** \brief Pointer to the IndexTarget data
+ */
+ const struct IndexTarget * Target;
+
+ /** \brief Pointer to the indexRecords parser */
+ indexRecords *MetaIndexParser;
+
+ /** \brief The MetaIndex Key */
+ std::string MetaKey;
+
+ /** \brief The URI of the index file to recreate at our end (either
+ * by downloading it or by applying partial patches).
+ */
+ std::string RealURI;
+
+ bool VerifyHashByMetaKey(HashStringList const &Hashes);
+
+ pkgAcqBaseIndex(pkgAcquire *Owner,
+ pkgAcqMetaBase *TransactionManager,
+ struct IndexTarget const * const Target,
+ HashStringList const &ExpectedHashes,
+ indexRecords *MetaIndexParser)
+ : Item(Owner, ExpectedHashes, TransactionManager), Target(Target),
+ MetaIndexParser(MetaIndexParser) {};
};
/*}}}*/
/** \brief An item that is responsible for fetching an index file of {{{
@@ -366,25 +649,14 @@ class pkgAcqSubIndex : public pkgAcquire::Item
*
* \sa pkgAcqIndexDiffs, pkgAcqIndex
*/
-class pkgAcqDiffIndex : public pkgAcquire::Item
+class pkgAcqDiffIndex : public pkgAcqBaseIndex
{
+ void *d;
+
protected:
/** \brief If \b true, debugging information will be written to std::clog. */
bool Debug;
- /** \brief The item that is currently being downloaded. */
- pkgAcquire::ItemDesc Desc;
-
- /** \brief The URI of the index file to recreate at our end (either
- * by downloading it or by applying partial patches).
- */
- std::string RealURI;
-
- /** \brief The Hash that the real index file should have after
- * all patches have been applied.
- */
- HashString ExpectedHash;
-
/** \brief The index file which will be patched to generate the new
* file.
*/
@@ -395,13 +667,17 @@ class pkgAcqDiffIndex : public pkgAcquire::Item
*/
std::string Description;
+ /** \brief If the copy step of the packages file is done
+ */
+ bool PackagesFileReadyInPartial;
+
public:
// Specialized action members
virtual void Failed(std::string Message,pkgAcquire::MethodConfig *Cnf);
- virtual void Done(std::string Message,unsigned long long Size,std::string Md5Hash,
+ virtual void Done(std::string Message,unsigned long long Size, HashStringList const &Hashes,
pkgAcquire::MethodConfig *Cnf);
virtual std::string DescURI() {return RealURI + "Index";};
- virtual std::string Custom600Headers();
+ virtual std::string Custom600Headers() const;
/** \brief Parse the Index file for a set of Packages diffs.
*
@@ -426,10 +702,13 @@ class pkgAcqDiffIndex : public pkgAcquire::Item
*
* \param ShortDesc A short description of the list file to download.
*
- * \param ExpectedHash The list file's MD5 signature.
+ * \param ExpectedHashes The list file's hashsums which are expected.
*/
- pkgAcqDiffIndex(pkgAcquire *Owner,std::string URI,std::string URIDesc,
- std::string ShortDesc, HashString ExpectedHash);
+ pkgAcqDiffIndex(pkgAcquire *Owner,
+ pkgAcqMetaBase *TransactionManager,
+ struct IndexTarget const * const Target,
+ HashStringList const &ExpectedHashes,
+ indexRecords *MetaIndexParser);
};
/*}}}*/
/** \brief An item that is responsible for fetching client-merge patches {{{
@@ -443,8 +722,10 @@ class pkgAcqDiffIndex : public pkgAcquire::Item
*
* \sa pkgAcqDiffIndex, pkgAcqIndex
*/
-class pkgAcqIndexMergeDiffs : public pkgAcquire::Item
+class pkgAcqIndexMergeDiffs : public pkgAcqBaseIndex
{
+ void *d;
+
protected:
/** \brief If \b true, debugging output will be written to
@@ -452,21 +733,6 @@ class pkgAcqIndexMergeDiffs : public pkgAcquire::Item
*/
bool Debug;
- /** \brief description of the item that is currently being
- * downloaded.
- */
- pkgAcquire::ItemDesc Desc;
-
- /** \brief URI of the package index file that is being
- * reconstructed.
- */
- std::string RealURI;
-
- /** \brief HashSum of the package index file that is being
- * reconstructed.
- */
- HashString ExpectedHash;
-
/** \brief description of the file being downloaded. */
std::string Description;
@@ -499,9 +765,8 @@ class pkgAcqIndexMergeDiffs : public pkgAcquire::Item
* outright; its arguments are ignored.
*/
virtual void Failed(std::string Message,pkgAcquire::MethodConfig *Cnf);
-
- virtual void Done(std::string Message,unsigned long long Size,std::string Md5Hash,
- pkgAcquire::MethodConfig *Cnf);
+ virtual void Done(std::string Message,unsigned long long Size, HashStringList const &Hashes,
+ pkgAcquire::MethodConfig *Cnf);
virtual std::string DescURI() {return RealURI + "Index";};
/** \brief Create an index merge-diff item.
@@ -515,7 +780,7 @@ class pkgAcqIndexMergeDiffs : public pkgAcquire::Item
*
* \param ShortDesc A brief description of this item.
*
- * \param ExpectedHash The expected md5sum of the completely
+ * \param ExpectedHashes The expected md5sum of the completely
* reconstructed package index file; the index file will be tested
* against this value when it is entirely reconstructed.
*
@@ -525,9 +790,13 @@ class pkgAcqIndexMergeDiffs : public pkgAcquire::Item
* \param allPatches contains all related items so that each item can
* check if it was the last one to complete the download step
*/
- pkgAcqIndexMergeDiffs(pkgAcquire *Owner,std::string const &URI,std::string const &URIDesc,
- std::string const &ShortDesc, HashString const &ExpectedHash,
- DiffInfo const &patch, std::vector<pkgAcqIndexMergeDiffs*> const * const allPatches);
+ pkgAcqIndexMergeDiffs(pkgAcquire *Owner,
+ pkgAcqMetaBase *TransactionManager,
+ struct IndexTarget const * const Target,
+ HashStringList const &ExpectedHash,
+ indexRecords *MetaIndexParser,
+ DiffInfo const &patch,
+ std::vector<pkgAcqIndexMergeDiffs*> const * const allPatches);
};
/*}}}*/
/** \brief An item that is responsible for fetching server-merge patches {{{
@@ -541,8 +810,10 @@ class pkgAcqIndexMergeDiffs : public pkgAcquire::Item
*
* \sa pkgAcqDiffIndex, pkgAcqIndex
*/
-class pkgAcqIndexDiffs : public pkgAcquire::Item
+class pkgAcqIndexDiffs : public pkgAcqBaseIndex
{
+ void *d;
+
private:
/** \brief Queue up the next diff download.
@@ -554,20 +825,20 @@ class pkgAcqIndexDiffs : public pkgAcquire::Item
* \return \b true if an applicable diff was found, \b false
* otherwise.
*/
- bool QueueNextDiff();
+ APT_HIDDEN bool QueueNextDiff();
/** \brief Handle tasks that must be performed after the item
* finishes downloading.
*
- * Dequeues the item and checks the resulting file's md5sum
- * against ExpectedHash after the last patch was applied.
+ * Dequeues the item and checks the resulting file's hashsums
+ * against ExpectedHashes after the last patch was applied.
* There is no need to check the md5/sha1 after a "normal"
* patch because QueueNextDiff() will check the sha1 later.
*
* \param allDone If \b true, the file was entirely reconstructed,
* and its md5sum is verified.
*/
- void Finish(bool allDone=false);
+ APT_HIDDEN void Finish(bool allDone=false);
protected:
@@ -576,21 +847,6 @@ class pkgAcqIndexDiffs : public pkgAcquire::Item
*/
bool Debug;
- /** \brief A description of the item that is currently being
- * downloaded.
- */
- pkgAcquire::ItemDesc Desc;
-
- /** \brief The URI of the package index file that is being
- * reconstructed.
- */
- std::string RealURI;
-
- /** \brief The HashSum of the package index file that is being
- * reconstructed.
- */
- HashString ExpectedHash;
-
/** A description of the file being downloaded. */
std::string Description;
@@ -604,9 +860,6 @@ class pkgAcqIndexDiffs : public pkgAcquire::Item
*/
std::vector<DiffInfo> available_patches;
- /** Stop applying patches when reaching that sha1 */
- std::string ServerSha1;
-
/** The current status of this patch. */
enum DiffState
{
@@ -632,9 +885,9 @@ class pkgAcqIndexDiffs : public pkgAcquire::Item
*/
virtual void Failed(std::string Message,pkgAcquire::MethodConfig *Cnf);
- virtual void Done(std::string Message,unsigned long long Size,std::string Md5Hash,
+ virtual void Done(std::string Message,unsigned long long Size, HashStringList const &Hashes,
pkgAcquire::MethodConfig *Cnf);
- virtual std::string DescURI() {return RealURI + "Index";};
+ virtual std::string DescURI() {return RealURI + "IndexDiffs";};
/** \brief Create an index diff item.
*
@@ -650,19 +903,19 @@ class pkgAcqIndexDiffs : public pkgAcquire::Item
*
* \param ShortDesc A brief description of this item.
*
- * \param ExpectedHash The expected md5sum of the completely
+ * \param ExpectedHashes The expected hashsums of the completely
* reconstructed package index file; the index file will be tested
* against this value when it is entirely reconstructed.
*
- * \param ServerSha1 is the sha1sum of the current file on the server
- *
* \param diffs The remaining diffs from the index of diffs. They
* should be ordered so that each diff appears before any diff
* that depends on it.
*/
- pkgAcqIndexDiffs(pkgAcquire *Owner,std::string URI,std::string URIDesc,
- std::string ShortDesc, HashString ExpectedHash,
- std::string ServerSha1,
+ pkgAcqIndexDiffs(pkgAcquire *Owner,
+ pkgAcqMetaBase *TransactionManager,
+ struct IndexTarget const * const Target,
+ HashStringList const &ExpectedHash,
+ indexRecords *MetaIndexParser,
std::vector<DiffInfo> diffs=std::vector<DiffInfo>());
};
/*}}}*/
@@ -673,56 +926,73 @@ class pkgAcqIndexDiffs : public pkgAcquire::Item
*
* \todo Why does pkgAcqIndex have protected members?
*/
-class pkgAcqIndex : public pkgAcquire::Item
+class pkgAcqIndex : public pkgAcqBaseIndex
{
- protected:
+ void *d;
- /** \brief If \b true, the index file has been decompressed. */
- bool Decompression;
+ protected:
- /** \brief If \b true, the partially downloaded file will be
- * removed when the download completes.
+ /** \brief The stages the method goes through
+ *
+ * The method first downloads the indexfile, then its decompressed (or
+ * copied) and verified
*/
- bool Erase;
+ enum AllStages {
+ STAGE_DOWNLOAD,
+ STAGE_DECOMPRESS_AND_VERIFY,
+ };
+ AllStages Stage;
- // Unused, used to be used to verify that "Packages: " header was there
- bool __DELME_ON_NEXT_ABI_BREAK_Verify;
+ /** \brief Handle what needs to be done when the download is done */
+ void StageDownloadDone(std::string Message,
+ HashStringList const &Hashes,
+ pkgAcquire::MethodConfig *Cfg);
- /** \brief The download request that is currently being
- * processed.
+ /** \brief Handle what needs to be done when the decompression/copy is
+ * done
*/
- pkgAcquire::ItemDesc Desc;
+ void StageDecompressDone(std::string Message,
+ HashStringList const &Hashes,
+ pkgAcquire::MethodConfig *Cfg);
- /** \brief The object that is actually being fetched (minus any
- * compression-related extensions).
+ /** \brief If \b set, this partially downloaded file will be
+ * removed when the download completes.
*/
- std::string RealURI;
-
- /** \brief The expected hashsum of the decompressed index file. */
- HashString ExpectedHash;
+ std::string EraseFileName;
/** \brief The compression-related file extensions that are being
* added to the downloaded file one by one if first fails (e.g., "gz bz2").
*/
- std::string CompressionExtension;
+ std::string CompressionExtensions;
+
+ /** \brief The actual compression extension currently used */
+ std::string CurrentCompressionExtension;
+
+ /** \brief Do the changes needed to fetch via AptByHash (if needed) */
+ void InitByHashIfNeeded(const std::string MetaKey);
+
+ /** \brief Auto select the right compression to use */
+ void AutoSelectCompression();
- /** \brief Get the full pathname of the final file for the given URI
+ /** \brief Get the full pathname of the final file for the current URI
*/
- std::string GetFinalFilename(std::string const &URI,
- std::string const &compExt);
+ std::string GetFinalFilename() const;
/** \brief Schedule file for verification after a IMS hit */
- void ReverifyAfterIMS(std::string const &FileName);
+ void ReverifyAfterIMS();
+
+ /** \brief Validate the downloaded index file */
+ bool ValidateFile(const std::string &FileName);
public:
// Specialized action members
virtual void Failed(std::string Message,pkgAcquire::MethodConfig *Cnf);
- virtual void Done(std::string Message,unsigned long long Size,std::string Md5Hash,
+ virtual void Done(std::string Message,unsigned long long Size,
+ HashStringList const &Hashes,
pkgAcquire::MethodConfig *Cnf);
- virtual std::string Custom600Headers();
+ virtual std::string Custom600Headers() const;
virtual std::string DescURI() {return Desc.URI;};
- virtual std::string HashSum() {return ExpectedHash.toStr(); };
/** \brief Create a pkgAcqIndex.
*
@@ -735,7 +1005,7 @@ class pkgAcqIndex : public pkgAcquire::Item
*
* \param ShortDesc A brief description of this index file.
*
- * \param ExpectedHash The expected hashsum of this index file.
+ * \param ExpectedHashes The expected hashsum of this index file.
*
* \param compressExt The compression-related extension with which
* this index file should be downloaded, or "" to autodetect
@@ -744,11 +1014,14 @@ class pkgAcqIndex : public pkgAcquire::Item
* fallback is ".gz" or none.
*/
pkgAcqIndex(pkgAcquire *Owner,std::string URI,std::string URIDesc,
- std::string ShortDesc, HashString ExpectedHash,
- std::string compressExt="");
- pkgAcqIndex(pkgAcquire *Owner, struct IndexTarget const * const Target,
- HashString const &ExpectedHash, indexRecords const *MetaIndexParser);
- void Init(std::string const &URI, std::string const &URIDesc, std::string const &ShortDesc);
+ std::string ShortDesc, HashStringList const &ExpectedHashes);
+ pkgAcqIndex(pkgAcquire *Owner, pkgAcqMetaBase *TransactionManager,
+ IndexTarget const * const Target,
+ HashStringList const &ExpectedHash,
+ indexRecords *MetaIndexParser);
+
+ void Init(std::string const &URI, std::string const &URIDesc,
+ std::string const &ShortDesc);
};
/*}}}*/
/** \brief An acquire item that is responsible for fetching a {{{
@@ -760,10 +1033,12 @@ class pkgAcqIndex : public pkgAcquire::Item
*/
class pkgAcqIndexTrans : public pkgAcqIndex
{
+ void *d;
+
public:
virtual void Failed(std::string Message,pkgAcquire::MethodConfig *Cnf);
- virtual std::string Custom600Headers();
+ virtual std::string Custom600Headers() const;
/** \brief Create a pkgAcqIndexTrans.
*
@@ -776,15 +1051,21 @@ class pkgAcqIndexTrans : public pkgAcqIndex
*
* \param ShortDesc A brief description of this index file.
*/
- pkgAcqIndexTrans(pkgAcquire *Owner,std::string URI,std::string URIDesc,
+ pkgAcqIndexTrans(pkgAcquire *Owner,
+ std::string URI,std::string URIDesc,
std::string ShortDesc);
- pkgAcqIndexTrans(pkgAcquire *Owner, struct IndexTarget const * const Target,
- HashString const &ExpectedHash, indexRecords const *MetaIndexParser);
+ pkgAcqIndexTrans(pkgAcquire *Owner,
+ pkgAcqMetaBase *TransactionManager,
+ IndexTarget const * const Target,
+ HashStringList const &ExpectedHashes,
+ indexRecords *MetaIndexParser);
};
/*}}}*/
/** \brief Information about an index file. */ /*{{{*/
class IndexTarget
{
+ void *d;
+
public:
/** \brief A URI from which the index file can be downloaded. */
std::string URI;
@@ -803,230 +1084,18 @@ class IndexTarget
virtual bool IsOptional() const {
return false;
}
- virtual bool IsSubIndex() const {
- return false;
- }
};
/*}}}*/
/** \brief Information about an optional index file. */ /*{{{*/
class OptionalIndexTarget : public IndexTarget
{
+ void *d;
+
virtual bool IsOptional() const {
return true;
}
};
/*}}}*/
-/** \brief Information about an subindex index file. */ /*{{{*/
-class SubIndexTarget : public IndexTarget
-{
- virtual bool IsSubIndex() const {
- return true;
- }
-};
- /*}}}*/
-/** \brief Information about an subindex index file. */ /*{{{*/
-class OptionalSubIndexTarget : public OptionalIndexTarget
-{
- virtual bool IsSubIndex() const {
- return true;
- }
-};
- /*}}}*/
-
-/** \brief An acquire item that downloads the detached signature {{{
- * of a meta-index (Release) file, then queues up the release
- * file itself.
- *
- * \todo Why protected members?
- *
- * \sa pkgAcqMetaIndex
- */
-class pkgAcqMetaSig : public pkgAcquire::Item
-{
- protected:
- /** \brief The last good signature file */
- std::string LastGoodSig;
-
- /** \brief The fetch request that is currently being processed. */
- pkgAcquire::ItemDesc Desc;
-
- /** \brief The URI of the signature file. Unlike Desc.URI, this is
- * never modified; it is used to determine the file that is being
- * downloaded.
- */
- std::string RealURI;
-
- /** \brief The URI of the meta-index file to be fetched after the signature. */
- std::string MetaIndexURI;
-
- /** \brief A "URI-style" description of the meta-index file to be
- * fetched after the signature.
- */
- std::string MetaIndexURIDesc;
-
- /** \brief A brief description of the meta-index file to be fetched
- * after the signature.
- */
- std::string MetaIndexShortDesc;
-
- /** \brief A package-system-specific parser for the meta-index file. */
- indexRecords* MetaIndexParser;
-
- /** \brief The index files which should be looked up in the meta-index
- * and then downloaded.
- *
- * \todo Why a list of pointers instead of a list of structs?
- */
- const std::vector<struct IndexTarget*>* IndexTargets;
-
- public:
-
- // Specialized action members
- virtual void Failed(std::string Message,pkgAcquire::MethodConfig *Cnf);
- virtual void Done(std::string Message,unsigned long long Size,std::string Md5Hash,
- pkgAcquire::MethodConfig *Cnf);
- virtual std::string Custom600Headers();
- virtual std::string DescURI() {return RealURI; };
-
- /** \brief Create a new pkgAcqMetaSig. */
- pkgAcqMetaSig(pkgAcquire *Owner,std::string URI,std::string URIDesc, std::string ShortDesc,
- std::string MetaIndexURI, std::string MetaIndexURIDesc, std::string MetaIndexShortDesc,
- const std::vector<struct IndexTarget*>* IndexTargets,
- indexRecords* MetaIndexParser);
- virtual ~pkgAcqMetaSig();
-};
- /*}}}*/
-/** \brief An item that is responsible for downloading the meta-index {{{
- * file (i.e., Release) itself and verifying its signature.
- *
- * Once the download and verification are complete, the downloads of
- * the individual index files are queued up using pkgAcqDiffIndex.
- * If the meta-index file had a valid signature, the expected hashsums
- * of the index files will be the md5sums listed in the meta-index;
- * otherwise, the expected hashsums will be "" (causing the
- * authentication of the index files to be bypassed).
- */
-class pkgAcqMetaIndex : public pkgAcquire::Item
-{
- protected:
- /** \brief The fetch command that is currently being processed. */
- pkgAcquire::ItemDesc Desc;
-
- /** \brief The URI that is actually being downloaded; never
- * modified by pkgAcqMetaIndex.
- */
- std::string RealURI;
-
- /** \brief The file in which the signature for this index was stored.
- *
- * If empty, the signature and the md5sums of the individual
- * indices will not be checked.
- */
- std::string SigFile;
-
- /** \brief The index files to download. */
- const std::vector<struct IndexTarget*>* IndexTargets;
-
- /** \brief The parser for the meta-index file. */
- indexRecords* MetaIndexParser;
-
- /** \brief If \b true, the index's signature is currently being verified.
- */
- bool AuthPass;
- // required to deal gracefully with problems caused by incorrect ims hits
- bool IMSHit;
-
- /** \brief Check that the release file is a release file for the
- * correct distribution.
- *
- * \return \b true if no fatal errors were encountered.
- */
- bool VerifyVendor(std::string Message);
-
- /** \brief Called when a file is finished being retrieved.
- *
- * If the file was not downloaded to DestFile, a copy process is
- * set up to copy it to DestFile; otherwise, Complete is set to \b
- * true and the file is moved to its final location.
- *
- * \param Message The message block received from the fetch
- * subprocess.
- */
- void RetrievalDone(std::string Message);
-
- /** \brief Called when authentication succeeded.
- *
- * Sanity-checks the authenticated file, queues up the individual
- * index files for download, and saves the signature in the lists
- * directory next to the authenticated list file.
- *
- * \param Message The message block received from the fetch
- * subprocess.
- */
- void AuthDone(std::string Message);
-
- /** \brief Starts downloading the individual index files.
- *
- * \param verify If \b true, only indices whose expected hashsum
- * can be determined from the meta-index will be downloaded, and
- * the hashsums of indices will be checked (reporting
- * #StatAuthError if there is a mismatch). If verify is \b false,
- * no hashsum checking will be performed.
- */
- void QueueIndexes(bool verify);
-
- public:
-
- // Specialized action members
- virtual void Failed(std::string Message,pkgAcquire::MethodConfig *Cnf);
- virtual void Done(std::string Message,unsigned long long Size, std::string Hash,
- pkgAcquire::MethodConfig *Cnf);
- virtual std::string Custom600Headers();
- virtual std::string DescURI() {return RealURI; };
-
- /** \brief Create a new pkgAcqMetaIndex. */
- pkgAcqMetaIndex(pkgAcquire *Owner,
- std::string URI,std::string URIDesc, std::string ShortDesc,
- std::string SigFile,
- const std::vector<struct IndexTarget*>* IndexTargets,
- indexRecords* MetaIndexParser);
-};
- /*}}}*/
-/** \brief An item repsonsible for downloading clearsigned metaindexes {{{*/
-class pkgAcqMetaClearSig : public pkgAcqMetaIndex
-{
- /** \brief The URI of the meta-index file for the detached signature */
- std::string MetaIndexURI;
-
- /** \brief A "URI-style" description of the meta-index file */
- std::string MetaIndexURIDesc;
-
- /** \brief A brief description of the meta-index file */
- std::string MetaIndexShortDesc;
-
- /** \brief The URI of the detached meta-signature file if the clearsigned one failed. */
- std::string MetaSigURI;
-
- /** \brief A "URI-style" description of the meta-signature file */
- std::string MetaSigURIDesc;
-
- /** \brief A brief description of the meta-signature file */
- std::string MetaSigShortDesc;
-
-public:
- void Failed(std::string Message,pkgAcquire::MethodConfig *Cnf);
- virtual std::string Custom600Headers();
-
- /** \brief Create a new pkgAcqMetaClearSig. */
- pkgAcqMetaClearSig(pkgAcquire *Owner,
- std::string const &URI, std::string const &URIDesc, std::string const &ShortDesc,
- std::string const &MetaIndexURI, std::string const &MetaIndexURIDesc, std::string const &MetaIndexShortDesc,
- std::string const &MetaSigURI, std::string const &MetaSigURIDesc, std::string const &MetaSigShortDesc,
- const std::vector<struct IndexTarget*>* IndexTargets,
- indexRecords* MetaIndexParser);
- virtual ~pkgAcqMetaClearSig();
-};
- /*}}}*/
/** \brief An item that is responsible for fetching a package file. {{{
*
* If the package file already exists in the cache, nothing will be
@@ -1034,13 +1103,12 @@ public:
*/
class pkgAcqArchive : public pkgAcquire::Item
{
+ void *d;
+
protected:
/** \brief The package version being fetched. */
pkgCache::VerIterator Version;
- /** \brief The fetch command that is currently being processed. */
- pkgAcquire::ItemDesc Desc;
-
/** \brief The list of sources from which to pick archives to
* download this package from.
*/
@@ -1051,9 +1119,6 @@ class pkgAcqArchive : public pkgAcquire::Item
*/
pkgRecords *Recs;
- /** \brief The hashsum of this package. */
- HashString ExpectedHash;
-
/** \brief A location in which the actual filename of the package
* should be stored.
*/
@@ -1080,13 +1145,12 @@ class pkgAcqArchive : public pkgAcquire::Item
public:
virtual void Failed(std::string Message,pkgAcquire::MethodConfig *Cnf);
- virtual void Done(std::string Message,unsigned long long Size,std::string Hash,
+ virtual void Done(std::string Message,unsigned long long Size, HashStringList const &Hashes,
pkgAcquire::MethodConfig *Cnf);
virtual std::string DescURI() {return Desc.URI;};
virtual std::string ShortDesc() {return Desc.ShortDesc;};
virtual void Finished();
- virtual std::string HashSum() {return ExpectedHash.toStr(); };
- virtual bool IsTrusted();
+ virtual bool IsTrusted() const;
/** \brief Create a new pkgAcqArchive.
*
@@ -1119,11 +1183,7 @@ class pkgAcqArchive : public pkgAcquire::Item
*/
class pkgAcqFile : public pkgAcquire::Item
{
- /** \brief The currently active download process. */
- pkgAcquire::ItemDesc Desc;
-
- /** \brief The hashsum of the file to download, if it is known. */
- HashString ExpectedHash;
+ void *d;
/** \brief How many times to retry the download, set from
* Acquire::Retries.
@@ -1137,11 +1197,10 @@ class pkgAcqFile : public pkgAcquire::Item
// Specialized action members
virtual void Failed(std::string Message,pkgAcquire::MethodConfig *Cnf);
- virtual void Done(std::string Message,unsigned long long Size,std::string CalcHash,
+ virtual void Done(std::string Message,unsigned long long Size, HashStringList const &CalcHashes,
pkgAcquire::MethodConfig *Cnf);
virtual std::string DescURI() {return Desc.URI;};
- virtual std::string HashSum() {return ExpectedHash.toStr(); };
- virtual std::string Custom600Headers();
+ virtual std::string Custom600Headers() const;
/** \brief Create a new pkgAcqFile object.
*
@@ -1150,8 +1209,8 @@ class pkgAcqFile : public pkgAcquire::Item
*
* \param URI The URI to download.
*
- * \param Hash The hashsum of the file to download, if it is known;
- * otherwise "".
+ * \param Hashes The hashsums of the file to download, if they are known;
+ * otherwise empty list.
*
* \param Size The size of the file to download, if it is known;
* otherwise 0.
@@ -1174,7 +1233,7 @@ class pkgAcqFile : public pkgAcquire::Item
* is the absolute name to which the file should be downloaded.
*/
- pkgAcqFile(pkgAcquire *Owner, std::string URI, std::string Hash, unsigned long long Size,
+ pkgAcqFile(pkgAcquire *Owner, std::string URI, HashStringList const &Hashes, unsigned long long Size,
std::string Desc, std::string ShortDesc,
const std::string &DestDir="", const std::string &DestFilename="",
bool IsIndexFile=false);
diff --git a/apt-pkg/acquire-method.cc b/apt-pkg/acquire-method.cc
index 746c553f1..c29ef469e 100644
--- a/apt-pkg/acquire-method.cc
+++ b/apt-pkg/acquire-method.cc
@@ -102,7 +102,10 @@ void pkgAcqMethod::Fail(string Err,bool Transient)
if (Queue != 0)
{
std::cout << "400 URI Failure\nURI: " << Queue->Uri << "\n"
- << "Message: " << Err << " " << IP << "\n";
+ << "Message: " << Err;
+ if (IP.empty() == false && _config->FindB("Acquire::Failure::ShowIP", true) == true)
+ std::cout << " " << IP;
+ std::cout << "\n";
Dequeue();
}
else
@@ -119,6 +122,18 @@ void pkgAcqMethod::Fail(string Err,bool Transient)
std::cout << "\n" << std::flush;
}
/*}}}*/
+// AcqMethod::DropPrivsOrDie - Drop privileges or die /*{{{*/
+// ---------------------------------------------------------------------
+/* */
+void pkgAcqMethod::DropPrivsOrDie()
+{
+ if (!DropPrivileges()) {
+ Fail(false);
+ exit(112); /* call the european emergency number */
+ }
+}
+
+ /*}}}*/
// AcqMethod::URIStart - Indicate a download is starting /*{{{*/
// ---------------------------------------------------------------------
/* */
@@ -147,6 +162,16 @@ void pkgAcqMethod::URIStart(FetchResult &Res)
// AcqMethod::URIDone - A URI is finished /*{{{*/
// ---------------------------------------------------------------------
/* */
+static void printHashStringList(HashStringList const * const list)
+{
+ for (HashStringList::const_iterator hash = list->begin(); hash != list->end(); ++hash)
+ {
+ // very old compatibility name for MD5Sum
+ if (hash->HashType() == "MD5Sum")
+ std::cout << "MD5-Hash: " << hash->HashValue() << "\n";
+ std::cout << hash->HashType() << "-Hash: " << hash->HashValue() << "\n";
+ }
+}
void pkgAcqMethod::URIDone(FetchResult &Res, FetchResult *Alt)
{
if (Queue == 0)
@@ -164,15 +189,8 @@ void pkgAcqMethod::URIDone(FetchResult &Res, FetchResult *Alt)
if (Res.LastModified != 0)
std::cout << "Last-Modified: " << TimeRFC1123(Res.LastModified) << "\n";
- if (Res.MD5Sum.empty() == false)
- std::cout << "MD5-Hash: " << Res.MD5Sum << "\n"
- << "MD5Sum-Hash: " << Res.MD5Sum << "\n";
- if (Res.SHA1Sum.empty() == false)
- std::cout << "SHA1-Hash: " << Res.SHA1Sum << "\n";
- if (Res.SHA256Sum.empty() == false)
- std::cout << "SHA256-Hash: " << Res.SHA256Sum << "\n";
- if (Res.SHA512Sum.empty() == false)
- std::cout << "SHA512-Hash: " << Res.SHA512Sum << "\n";
+ printHashStringList(&Res.Hashes);
+
if (UsedMirror.empty() == false)
std::cout << "UsedMirror: " << UsedMirror << "\n";
if (Res.GPGVOutput.empty() == false)
@@ -200,15 +218,8 @@ void pkgAcqMethod::URIDone(FetchResult &Res, FetchResult *Alt)
if (Alt->LastModified != 0)
std::cout << "Alt-Last-Modified: " << TimeRFC1123(Alt->LastModified) << "\n";
- if (Alt->MD5Sum.empty() == false)
- std::cout << "Alt-MD5-Hash: " << Alt->MD5Sum << "\n";
- if (Alt->SHA1Sum.empty() == false)
- std::cout << "Alt-SHA1-Hash: " << Alt->SHA1Sum << "\n";
- if (Alt->SHA256Sum.empty() == false)
- std::cout << "Alt-SHA256-Hash: " << Alt->SHA256Sum << "\n";
- if (Alt->SHA512Sum.empty() == false)
- std::cout << "Alt-SHA512-Hash: " << Alt->SHA512Sum << "\n";
-
+ printHashStringList(&Alt->Hashes);
+
if (Alt->IMSHit == true)
std::cout << "Alt-IMS-Hit: true\n";
}
@@ -355,6 +366,17 @@ int pkgAcqMethod::Run(bool Single)
Tmp->LastModified = 0;
Tmp->IndexFile = StringToBool(LookupTag(Message,"Index-File"),false);
Tmp->FailIgnore = StringToBool(LookupTag(Message,"Fail-Ignore"),false);
+ Tmp->ExpectedHashes = HashStringList();
+ for (char const * const * t = HashString::SupportedHashes(); *t != NULL; ++t)
+ {
+ std::string tag = "Expected-";
+ tag.append(*t);
+ std::string const hash = LookupTag(Message, tag.c_str());
+ if (hash.empty() == false)
+ Tmp->ExpectedHashes.push_back(HashString(*t, hash));
+ }
+ char *End;
+ Tmp->MaximumSize = strtoll(LookupTag(Message, "Maximum-Size", "0").c_str(), &End, 10);
Tmp->Next = 0;
// Append it to the list
@@ -442,12 +464,9 @@ pkgAcqMethod::FetchResult::FetchResult() : LastModified(0),
// ---------------------------------------------------------------------
/* This hides the number of hashes we are supporting from the caller.
It just deals with the hash class. */
-void pkgAcqMethod::FetchResult::TakeHashes(Hashes &Hash)
+void pkgAcqMethod::FetchResult::TakeHashes(class Hashes &Hash)
{
- MD5Sum = Hash.MD5.Result();
- SHA1Sum = Hash.SHA1.Result();
- SHA256Sum = Hash.SHA256.Result();
- SHA512Sum = Hash.SHA512.Result();
+ Hashes = Hash.GetHashStringList();
}
/*}}}*/
void pkgAcqMethod::Dequeue() { /*{{{*/
@@ -458,3 +477,5 @@ void pkgAcqMethod::Dequeue() { /*{{{*/
delete Tmp;
}
/*}}}*/
+
+pkgAcqMethod::~pkgAcqMethod() {}
diff --git a/apt-pkg/acquire-method.h b/apt-pkg/acquire-method.h
index 221ccf273..48bd95672 100644
--- a/apt-pkg/acquire-method.h
+++ b/apt-pkg/acquire-method.h
@@ -20,6 +20,7 @@
#ifndef PKGLIB_ACQUIRE_METHOD_H
#define PKGLIB_ACQUIRE_METHOD_H
+#include <apt-pkg/hashes.h>
#include <apt-pkg/macros.h>
#include <stdarg.h>
@@ -33,7 +34,6 @@
#include <apt-pkg/strutl.h>
#endif
-class Hashes;
class pkgAcqMethod
{
protected:
@@ -47,14 +47,16 @@ class pkgAcqMethod
time_t LastModified;
bool IndexFile;
bool FailIgnore;
+ HashStringList ExpectedHashes;
+ // a maximum size we will download, this can be the exact filesize
+ // for when we know it or a arbitrary limit when we don't know the
+ // filesize (like a InRelease file)
+ unsigned long long MaximumSize;
};
struct FetchResult
{
- std::string MD5Sum;
- std::string SHA1Sum;
- std::string SHA256Sum;
- std::string SHA512Sum;
+ HashStringList Hashes;
std::vector<std::string> GPGVOutput;
time_t LastModified;
bool IMSHit;
@@ -62,7 +64,7 @@ class pkgAcqMethod
unsigned long long Size;
unsigned long long ResumePoint;
- void TakeHashes(Hashes &Hash);
+ void TakeHashes(class Hashes &Hash);
FetchResult();
};
@@ -106,8 +108,8 @@ class pkgAcqMethod
inline void SetIP(std::string aIP) {IP = aIP;};
pkgAcqMethod(const char *Ver,unsigned long Flags = 0);
- virtual ~pkgAcqMethod() {};
-
+ virtual ~pkgAcqMethod();
+ void DropPrivsOrDie();
private:
APT_HIDDEN void Dequeue();
};
diff --git a/apt-pkg/acquire-worker.cc b/apt-pkg/acquire-worker.cc
index 047a655ce..64df3c80f 100644
--- a/apt-pkg/acquire-worker.cc
+++ b/apt-pkg/acquire-worker.cc
@@ -326,25 +326,30 @@ bool pkgAcquire::Worker::RunMessages()
Owner->DestFile.c_str(), LookupTag(Message,"Size","0").c_str(),TotalSize);
// see if there is a hash to verify
- string RecivedHash;
- HashString expectedHash(Owner->HashSum());
- if(!expectedHash.empty())
+ HashStringList RecivedHashes;
+ HashStringList expectedHashes = Owner->HashSums();
+ for (HashStringList::const_iterator hs = expectedHashes.begin(); hs != expectedHashes.end(); ++hs)
{
- string hashTag = expectedHash.HashType()+"-Hash";
- string hashSum = LookupTag(Message, hashTag.c_str());
- if(!hashSum.empty())
- RecivedHash = expectedHash.HashType() + ":" + hashSum;
- if(_config->FindB("Debug::pkgAcquire::Auth", false) == true)
- {
- clog << "201 URI Done: " << Owner->DescURI() << endl
- << "RecivedHash: " << RecivedHash << endl
- << "ExpectedHash: " << expectedHash.toStr()
- << endl << endl;
- }
+ std::string const tagname = hs->HashType() + "-Hash";
+ std::string const hashsum = LookupTag(Message, tagname.c_str());
+ if (hashsum.empty() == false)
+ RecivedHashes.push_back(HashString(hs->HashType(), hashsum));
+ }
+
+ if(_config->FindB("Debug::pkgAcquire::Auth", false) == true)
+ {
+ std::clog << "201 URI Done: " << Owner->DescURI() << endl
+ << "RecivedHash:" << endl;
+ for (HashStringList::const_iterator hs = RecivedHashes.begin(); hs != RecivedHashes.end(); ++hs)
+ std::clog << "\t- " << hs->toStr() << std::endl;
+ std::clog << "ExpectedHash:" << endl;
+ for (HashStringList::const_iterator hs = expectedHashes.begin(); hs != expectedHashes.end(); ++hs)
+ std::clog << "\t- " << hs->toStr() << std::endl;
+ std::clog << endl;
}
- Owner->Done(Message, ServerSize, RecivedHash.c_str(), Config);
+ Owner->Done(Message, ServerSize, RecivedHashes, Config);
ItemDone();
-
+
// Log that we are done
if (Log != 0)
{
@@ -366,7 +371,8 @@ bool pkgAcquire::Worker::RunMessages()
{
if (Itm == 0)
{
- _error->Error("Method gave invalid 400 URI Failure message");
+ std::string const msg = LookupTag(Message,"Message");
+ _error->Error("Method gave invalid 400 URI Failure message: %s", msg.c_str());
break;
}
@@ -525,6 +531,15 @@ bool pkgAcquire::Worker::QueueItem(pkgAcquire::Queue::QItem *Item)
Message.reserve(300);
Message += "URI: " + Item->URI;
Message += "\nFilename: " + Item->Owner->DestFile;
+ HashStringList const hsl = Item->Owner->HashSums();
+ for (HashStringList::const_iterator hs = hsl.begin(); hs != hsl.end(); ++hs)
+ Message += "\nExpected-" + hs->HashType() + ": " + hs->HashValue();
+ if(Item->Owner->FileSize > 0)
+ {
+ string MaximumSize;
+ strprintf(MaximumSize, "%llu", Item->Owner->FileSize);
+ Message += "\nMaximum-Size: " + MaximumSize;
+ }
Message += Item->Owner->Custom600Headers();
Message += "\n\n";
diff --git a/apt-pkg/acquire.cc b/apt-pkg/acquire.cc
index 057bc24cd..1aa709381 100644
--- a/apt-pkg/acquire.cc
+++ b/apt-pkg/acquire.cc
@@ -27,15 +27,20 @@
#include <vector>
#include <iostream>
#include <sstream>
+#include <iomanip>
+
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
-
+#include <pwd.h>
+#include <grp.h>
#include <dirent.h>
#include <sys/time.h>
#include <sys/select.h>
#include <errno.h>
+#include <sys/stat.h>
+#include <sys/types.h>
#include <apti18n.h>
/*}}}*/
@@ -55,8 +60,8 @@ pkgAcquire::pkgAcquire() : LockFD(-1), Queues(0), Workers(0), Configs(0), Log(NU
if (strcasecmp(Mode.c_str(),"access") == 0)
QueueMode = QueueAccess;
}
-pkgAcquire::pkgAcquire(pkgAcquireStatus *Progress) : LockFD(-1), Queues(0), Workers(0),
- Configs(0), Log(Progress), ToFetch(0),
+pkgAcquire::pkgAcquire(pkgAcquireStatus *Progress) : LockFD(-1), Queues(0), Workers(0),
+ Configs(0), Log(NULL), ToFetch(0),
Debug(_config->FindB("Debug::pkgAcquire",false)),
Running(false)
{
@@ -65,36 +70,70 @@ pkgAcquire::pkgAcquire(pkgAcquireStatus *Progress) : LockFD(-1), Queues(0), Wor
QueueMode = QueueHost;
if (strcasecmp(Mode.c_str(),"access") == 0)
QueueMode = QueueAccess;
- Setup(Progress, "");
+ SetLog(Progress);
}
/*}}}*/
-// Acquire::Setup - Delayed Constructor /*{{{*/
-// ---------------------------------------------------------------------
-/* Do everything needed to be a complete Acquire object and report the
- success (or failure) back so the user knows that something is wrong… */
+// Acquire::GetLock - lock directory and prepare for action /*{{{*/
+static bool SetupAPTPartialDirectory(std::string const &grand, std::string const &parent)
+{
+ std::string const partial = parent + "partial";
+ if (CreateAPTDirectoryIfNeeded(grand, partial) == false &&
+ CreateAPTDirectoryIfNeeded(parent, partial) == false)
+ return false;
+
+ if (getuid() == 0) // if we aren't root, we can't chown, so don't try it
+ {
+ std::string SandboxUser = _config->Find("APT::Sandbox::User");
+ struct passwd *pw = getpwnam(SandboxUser.c_str());
+ struct group *gr = getgrnam("root");
+ if (pw != NULL && gr != NULL && chown(partial.c_str(), pw->pw_uid, gr->gr_gid) != 0)
+ _error->WarningE("SetupAPTPartialDirectory", "chown to %s:root of directory %s failed", SandboxUser.c_str(), partial.c_str());
+ }
+ if (chmod(partial.c_str(), 0700) != 0)
+ _error->WarningE("SetupAPTPartialDirectory", "chmod 0700 of directory %s failed", partial.c_str());
+
+ return true;
+}
bool pkgAcquire::Setup(pkgAcquireStatus *Progress, string const &Lock)
{
Log = Progress;
+ if (Lock.empty())
+ {
+ string const listDir = _config->FindDir("Dir::State::lists");
+ if (SetupAPTPartialDirectory(_config->FindDir("Dir::State"), listDir) == false)
+ return _error->Errno("Acquire", _("List directory %spartial is missing."), listDir.c_str());
+ string const archivesDir = _config->FindDir("Dir::Cache::Archives");
+ if (SetupAPTPartialDirectory(_config->FindDir("Dir::Cache"), archivesDir) == false)
+ return _error->Errno("Acquire", _("Archives directory %spartial is missing."), archivesDir.c_str());
+ return true;
+ }
+ return GetLock(Lock);
+}
+bool pkgAcquire::GetLock(std::string const &Lock)
+{
+ if (Lock.empty() == true)
+ return false;
// check for existence and possibly create auxiliary directories
string const listDir = _config->FindDir("Dir::State::lists");
- string const partialListDir = listDir + "partial/";
string const archivesDir = _config->FindDir("Dir::Cache::Archives");
- string const partialArchivesDir = archivesDir + "partial/";
- if (CreateAPTDirectoryIfNeeded(_config->FindDir("Dir::State"), partialListDir) == false &&
- CreateAPTDirectoryIfNeeded(listDir, partialListDir) == false)
- return _error->Errno("Acquire", _("List directory %spartial is missing."), listDir.c_str());
-
- if (CreateAPTDirectoryIfNeeded(_config->FindDir("Dir::Cache"), partialArchivesDir) == false &&
- CreateAPTDirectoryIfNeeded(archivesDir, partialArchivesDir) == false)
- return _error->Errno("Acquire", _("Archives directory %spartial is missing."), archivesDir.c_str());
+ if (Lock == listDir)
+ {
+ if (SetupAPTPartialDirectory(_config->FindDir("Dir::State"), listDir) == false)
+ return _error->Errno("Acquire", _("List directory %spartial is missing."), listDir.c_str());
+ }
+ if (Lock == archivesDir)
+ {
+ if (SetupAPTPartialDirectory(_config->FindDir("Dir::Cache"), archivesDir) == false)
+ return _error->Errno("Acquire", _("Archives directory %spartial is missing."), archivesDir.c_str());
+ }
- if (Lock.empty() == true || _config->FindB("Debug::NoLocking", false) == true)
+ if (_config->FindB("Debug::NoLocking", false) == true)
return true;
// Lock the directory this acquire object will work in
- LockFD = GetLock(flCombine(Lock, "lock"));
+ LockFD = ::GetLock(flCombine(Lock, "lock"));
if (LockFD == -1)
return _error->Error(_("Unable to lock directory %s"), Lock.c_str());
@@ -580,27 +619,18 @@ pkgAcquire::UriIterator pkgAcquire::UriEnd()
// Acquire::MethodConfig::MethodConfig - Constructor /*{{{*/
// ---------------------------------------------------------------------
/* */
-pkgAcquire::MethodConfig::MethodConfig()
+pkgAcquire::MethodConfig::MethodConfig() : d(NULL), Next(0), SingleInstance(false),
+ Pipeline(false), SendConfig(false), LocalOnly(false), NeedsCleanup(false),
+ Removable(false)
{
- SingleInstance = false;
- Pipeline = false;
- SendConfig = false;
- LocalOnly = false;
- Removable = false;
- Next = 0;
}
/*}}}*/
// Queue::Queue - Constructor /*{{{*/
// ---------------------------------------------------------------------
/* */
-pkgAcquire::Queue::Queue(string Name,pkgAcquire *Owner) : Name(Name),
- Owner(Owner)
+pkgAcquire::Queue::Queue(string Name,pkgAcquire *Owner) : d(NULL), Next(0),
+ Name(Name), Items(0), Workers(0), Owner(Owner), PipeDepth(0), MaxPipeDepth(1)
{
- Items = 0;
- Next = 0;
- Workers = 0;
- MaxPipeDepth = 1;
- PipeDepth = 0;
}
/*}}}*/
// Queue::~Queue - Destructor /*{{{*/
@@ -804,7 +834,7 @@ void pkgAcquire::Queue::Bump()
// AcquireStatus::pkgAcquireStatus - Constructor /*{{{*/
// ---------------------------------------------------------------------
/* */
-pkgAcquireStatus::pkgAcquireStatus() : d(NULL), Update(true), MorePulses(false)
+pkgAcquireStatus::pkgAcquireStatus() : d(NULL), Percent(0), Update(true), MorePulses(false)
{
Start();
}
@@ -824,7 +854,9 @@ bool pkgAcquireStatus::Pulse(pkgAcquire *Owner)
// Compute the total number of bytes to fetch
unsigned int Unknown = 0;
unsigned int Count = 0;
- for (pkgAcquire::ItemCIterator I = Owner->ItemsBegin(); I != Owner->ItemsEnd();
+ bool UnfetchedReleaseFiles = false;
+ for (pkgAcquire::ItemCIterator I = Owner->ItemsBegin();
+ I != Owner->ItemsEnd();
++I, ++Count)
{
TotalItems++;
@@ -835,6 +867,13 @@ bool pkgAcquireStatus::Pulse(pkgAcquire *Owner)
if ((*I)->Local == true)
continue;
+ // see if the method tells us to expect more
+ TotalItems += (*I)->ExpectedAdditionalItems;
+
+ // check if there are unfetched Release files
+ if ((*I)->Complete == false && (*I)->ExpectedAdditionalItems > 0)
+ UnfetchedReleaseFiles = true;
+
TotalBytes += (*I)->FileSize;
if ((*I)->Complete == true)
CurrentBytes += (*I)->FileSize;
@@ -846,6 +885,7 @@ bool pkgAcquireStatus::Pulse(pkgAcquire *Owner)
unsigned long long ResumeSize = 0;
for (pkgAcquire::Worker *I = Owner->WorkersBegin(); I != 0;
I = Owner->WorkerStep(I))
+ {
if (I->CurrentItem != 0 && I->CurrentItem->Owner->Complete == false)
{
CurrentBytes += I->CurrentSize;
@@ -856,6 +896,7 @@ bool pkgAcquireStatus::Pulse(pkgAcquire *Owner)
I->CurrentItem->Owner->Complete == false)
TotalBytes += I->CurrentSize;
}
+ }
// Normalize the figures and account for unknown size downloads
if (TotalBytes <= 0)
@@ -866,6 +907,12 @@ bool pkgAcquireStatus::Pulse(pkgAcquire *Owner)
// Wha?! Is not supposed to happen.
if (CurrentBytes > TotalBytes)
CurrentBytes = TotalBytes;
+
+ // debug
+ if (_config->FindB("Debug::acquire::progress", false) == true)
+ std::clog << " Bytes: "
+ << SizeToStr(CurrentBytes) << " / " << SizeToStr(TotalBytes)
+ << std::endl;
// Compute the CPS
struct timeval NewTime;
@@ -886,6 +933,14 @@ bool pkgAcquireStatus::Pulse(pkgAcquire *Owner)
Time = NewTime;
}
+ // calculate the percentage, if we have too little data assume 1%
+ if (TotalBytes > 0 && UnfetchedReleaseFiles)
+ Percent = 0;
+ else
+ // use both files and bytes because bytes can be unreliable
+ Percent = (0.8 * (CurrentBytes/float(TotalBytes)*100.0) +
+ 0.2 * (CurrentItems/float(TotalItems)*100.0));
+
int fd = _config->FindI("APT::Status-Fd",-1);
if(fd > 0)
{
@@ -903,13 +958,11 @@ bool pkgAcquireStatus::Pulse(pkgAcquire *Owner)
else
snprintf(msg,sizeof(msg), _("Retrieving file %li of %li"), i, TotalItems);
-
-
// build the status str
status << "dlstatus:" << i
- << ":" << (CurrentBytes/float(TotalBytes)*100.0)
- << ":" << msg
- << endl;
+ << ":" << std::setprecision(3) << Percent
+ << ":" << msg
+ << endl;
std::string const dlstatus = status.str();
FileFd::Write(fd, dlstatus.c_str(), dlstatus.size());
@@ -964,3 +1017,7 @@ void pkgAcquireStatus::Fetched(unsigned long long Size,unsigned long long Resume
FetchedBytes += Size - Resume;
}
/*}}}*/
+
+APT_CONST pkgAcquire::UriIterator::~UriIterator() {}
+APT_CONST pkgAcquire::MethodConfig::~MethodConfig() {}
+APT_CONST pkgAcquireStatus::~pkgAcquireStatus() {}
diff --git a/apt-pkg/acquire.h b/apt-pkg/acquire.h
index ef16d8556..a1a192d5f 100644
--- a/apt-pkg/acquire.h
+++ b/apt-pkg/acquire.h
@@ -351,14 +351,24 @@ class pkgAcquire
* long as the pkgAcquire object does.
* \param Lock defines a lock file that should be acquired to ensure
* only one Acquire class is in action at the time or an empty string
- * if no lock file should be used.
+ * if no lock file should be used. If set also all needed directories
+ * will be created.
*/
- bool Setup(pkgAcquireStatus *Progress = NULL, std::string const &Lock = "");
+ APT_DEPRECATED bool Setup(pkgAcquireStatus *Progress = NULL, std::string const &Lock = "");
void SetLog(pkgAcquireStatus *Progress) { Log = Progress; }
+ /** \brief acquire lock and perform directory setup
+ *
+ * \param Lock defines a lock file that should be acquired to ensure
+ * only one Acquire class is in action at the time or an empty string
+ * if no lock file should be used. If set also all needed directories
+ * will be created and setup.
+ */
+ bool GetLock(std::string const &Lock);
+
/** \brief Construct a new pkgAcquire. */
- pkgAcquire(pkgAcquireStatus *Log) APT_DEPRECATED;
+ pkgAcquire(pkgAcquireStatus *Log);
pkgAcquire();
/** \brief Destroy this pkgAcquire object.
@@ -585,7 +595,7 @@ class pkgAcquire::UriIterator
*
* \param Q The queue over which this UriIterator should iterate.
*/
- UriIterator(pkgAcquire::Queue *Q) : CurQ(Q), CurItem(0)
+ UriIterator(pkgAcquire::Queue *Q) : d(NULL), CurQ(Q), CurItem(0)
{
while (CurItem == 0 && CurQ != 0)
{
@@ -593,7 +603,7 @@ class pkgAcquire::UriIterator
CurQ = CurQ->Next;
}
}
- virtual ~UriIterator() {};
+ virtual ~UriIterator();
};
/*}}}*/
/** \brief Information about the properties of a single acquire method. {{{*/
@@ -651,8 +661,7 @@ struct pkgAcquire::MethodConfig
*/
MethodConfig();
- /* \brief Destructor, empty currently */
- virtual ~MethodConfig() {};
+ virtual ~MethodConfig();
};
/*}}}*/
/** \brief A monitor object for downloads controlled by the pkgAcquire class. {{{
@@ -714,6 +723,10 @@ class pkgAcquireStatus
/** \brief The number of items that have been successfully downloaded. */
unsigned long CurrentItems;
+ /** \brief The estimated percentage of the download (0-100)
+ */
+ double Percent;
+
public:
/** \brief If \b true, the download scheduler should call Pulse()
@@ -794,7 +807,7 @@ class pkgAcquireStatus
/** \brief Initialize all counters to 0 and the time to the current time. */
pkgAcquireStatus();
- virtual ~pkgAcquireStatus() {};
+ virtual ~pkgAcquireStatus();
};
/*}}}*/
/** @} */
diff --git a/apt-pkg/algorithms.cc b/apt-pkg/algorithms.cc
index 608ec7fce..71b5ac2c1 100644
--- a/apt-pkg/algorithms.cc
+++ b/apt-pkg/algorithms.cc
@@ -640,13 +640,11 @@ bool pkgProblemResolver::DoUpgrade(pkgCache::PkgIterator Pkg)
// ProblemResolver::Resolve - calls a resolver to fix the situation /*{{{*/
// ---------------------------------------------------------------------
/* */
-bool pkgProblemResolver::Resolve(bool BrokenFix)
+bool pkgProblemResolver::Resolve(bool BrokenFix, OpProgress * const Progress)
{
std::string const solver = _config->Find("APT::Solver", "internal");
- if (solver != "internal") {
- OpTextProgress Prog(*_config);
- return EDSP::ResolveExternal(solver.c_str(), Cache, false, false, false, &Prog);
- }
+ if (solver != "internal")
+ return EDSP::ResolveExternal(solver.c_str(), Cache, false, false, false, Progress);
return ResolveInternal(BrokenFix);
}
/*}}}*/
@@ -1140,13 +1138,11 @@ bool pkgProblemResolver::InstOrNewPolicyBroken(pkgCache::PkgIterator I)
/* This is the work horse of the soft upgrade routine. It is very gental
in that it does not install or remove any packages. It is assumed that the
system was non-broken previously. */
-bool pkgProblemResolver::ResolveByKeep()
+bool pkgProblemResolver::ResolveByKeep(OpProgress * const Progress)
{
std::string const solver = _config->Find("APT::Solver", "internal");
- if (solver != "internal") {
- OpTextProgress Prog(*_config);
- return EDSP::ResolveExternal(solver.c_str(), Cache, true, false, false, &Prog);
- }
+ if (solver != "internal")
+ return EDSP::ResolveExternal(solver.c_str(), Cache, true, false, false, Progress);
return ResolveByKeepInternal();
}
/*}}}*/
diff --git a/apt-pkg/algorithms.h b/apt-pkg/algorithms.h
index f35bd9a13..b6da1f2bf 100644
--- a/apt-pkg/algorithms.h
+++ b/apt-pkg/algorithms.h
@@ -82,9 +82,9 @@ class pkgSimulate : public pkgPackageManager /*{{{*/
virtual bool Remove(PkgIterator Pkg,bool Purge);
private:
- void ShortBreaks();
- void Describe(PkgIterator iPkg,std::ostream &out,bool Current,bool Candidate);
-
+ APT_HIDDEN void ShortBreaks();
+ APT_HIDDEN void Describe(PkgIterator iPkg,std::ostream &out,bool Current,bool Candidate);
+
public:
pkgSimulate(pkgDepCache *Cache);
@@ -114,7 +114,7 @@ class pkgProblemResolver /*{{{*/
// Sort stuff
static pkgProblemResolver *This;
- static int ScoreSort(const void *a,const void *b) APT_PURE;
+ APT_HIDDEN static int ScoreSort(const void *a,const void *b) APT_PURE;
struct PackageKill
{
@@ -122,12 +122,12 @@ class pkgProblemResolver /*{{{*/
DepIterator Dep;
};
- void MakeScores();
- bool DoUpgrade(pkgCache::PkgIterator Pkg);
+ APT_HIDDEN void MakeScores();
+ APT_HIDDEN bool DoUpgrade(pkgCache::PkgIterator Pkg);
+
+ APT_HIDDEN bool ResolveInternal(bool const BrokenFix = false);
+ APT_HIDDEN bool ResolveByKeepInternal();
- bool ResolveInternal(bool const BrokenFix = false);
- bool ResolveByKeepInternal();
-
protected:
bool InstOrNewPolicyBroken(pkgCache::PkgIterator Pkg);
@@ -136,12 +136,12 @@ class pkgProblemResolver /*{{{*/
inline void Protect(pkgCache::PkgIterator Pkg) {Flags[Pkg->ID] |= Protected; Cache.MarkProtected(Pkg);};
inline void Remove(pkgCache::PkgIterator Pkg) {Flags[Pkg->ID] |= ToRemove;};
inline void Clear(pkgCache::PkgIterator Pkg) {Flags[Pkg->ID] &= ~(Protected | ToRemove);};
-
- // Try to intelligently resolve problems by installing and removing packages
- bool Resolve(bool BrokenFix = false);
-
+
+ // Try to intelligently resolve problems by installing and removing packages
+ bool Resolve(bool BrokenFix = false, OpProgress * const Progress = NULL);
+
// Try to resolve problems only by using keep
- bool ResolveByKeep();
+ bool ResolveByKeep(OpProgress * const Progress = NULL);
APT_DEPRECATED void InstallProtect();
diff --git a/apt-pkg/aptconfiguration.cc b/apt-pkg/aptconfiguration.cc
index 9982759c6..01b85a74e 100644
--- a/apt-pkg/aptconfiguration.cc
+++ b/apt-pkg/aptconfiguration.cc
@@ -32,6 +32,35 @@
#include <apti18n.h>
/*}}}*/
namespace APT {
+// setDefaultConfigurationForCompressors /*{{{*/
+static void setDefaultConfigurationForCompressors() {
+ // Set default application paths to check for optional compression types
+ _config->CndSet("Dir::Bin::bzip2", "/bin/bzip2");
+ _config->CndSet("Dir::Bin::xz", "/usr/bin/xz");
+ if (FileExists(_config->FindFile("Dir::Bin::xz")) == true) {
+ _config->Set("Dir::Bin::lzma", _config->FindFile("Dir::Bin::xz"));
+ _config->Set("APT::Compressor::lzma::Binary", "xz");
+ if (_config->Exists("APT::Compressor::lzma::CompressArg") == false) {
+ _config->Set("APT::Compressor::lzma::CompressArg::", "--format=lzma");
+ _config->Set("APT::Compressor::lzma::CompressArg::", "-9");
+ }
+ if (_config->Exists("APT::Compressor::lzma::UncompressArg") == false) {
+ _config->Set("APT::Compressor::lzma::UncompressArg::", "--format=lzma");
+ _config->Set("APT::Compressor::lzma::UncompressArg::", "-d");
+ }
+ } else {
+ _config->CndSet("Dir::Bin::lzma", "/usr/bin/lzma");
+ if (_config->Exists("APT::Compressor::lzma::CompressArg") == false) {
+ _config->Set("APT::Compressor::lzma::CompressArg::", "--suffix=");
+ _config->Set("APT::Compressor::lzma::CompressArg::", "-9");
+ }
+ if (_config->Exists("APT::Compressor::lzma::UncompressArg") == false) {
+ _config->Set("APT::Compressor::lzma::UncompressArg::", "--suffix=");
+ _config->Set("APT::Compressor::lzma::UncompressArg::", "-d");
+ }
+ }
+}
+ /*}}}*/
// getCompressionTypes - Return Vector of usable compressiontypes /*{{{*/
// ---------------------------------------------------------------------
/* return a vector of compression types in the preferred order. */
@@ -402,35 +431,6 @@ bool Configuration::checkArchitecture(std::string const &Arch) {
return (std::find(archs.begin(), archs.end(), Arch) != archs.end());
}
/*}}}*/
-// setDefaultConfigurationForCompressors /*{{{*/
-void Configuration::setDefaultConfigurationForCompressors() {
- // Set default application paths to check for optional compression types
- _config->CndSet("Dir::Bin::bzip2", "/bin/bzip2");
- _config->CndSet("Dir::Bin::xz", "/usr/bin/xz");
- if (FileExists(_config->FindFile("Dir::Bin::xz")) == true) {
- _config->Set("Dir::Bin::lzma", _config->FindFile("Dir::Bin::xz"));
- _config->Set("APT::Compressor::lzma::Binary", "xz");
- if (_config->Exists("APT::Compressor::lzma::CompressArg") == false) {
- _config->Set("APT::Compressor::lzma::CompressArg::", "--format=lzma");
- _config->Set("APT::Compressor::lzma::CompressArg::", "-9");
- }
- if (_config->Exists("APT::Compressor::lzma::UncompressArg") == false) {
- _config->Set("APT::Compressor::lzma::UncompressArg::", "--format=lzma");
- _config->Set("APT::Compressor::lzma::UncompressArg::", "-d");
- }
- } else {
- _config->CndSet("Dir::Bin::lzma", "/usr/bin/lzma");
- if (_config->Exists("APT::Compressor::lzma::CompressArg") == false) {
- _config->Set("APT::Compressor::lzma::CompressArg::", "--suffix=");
- _config->Set("APT::Compressor::lzma::CompressArg::", "-9");
- }
- if (_config->Exists("APT::Compressor::lzma::UncompressArg") == false) {
- _config->Set("APT::Compressor::lzma::UncompressArg::", "--suffix=");
- _config->Set("APT::Compressor::lzma::UncompressArg::", "-d");
- }
- }
-}
- /*}}}*/
// getCompressors - Return Vector of usealbe compressors /*{{{*/
// ---------------------------------------------------------------------
/* return a vector of compressors used by apt-ftparchive in the
@@ -540,7 +540,7 @@ std::string const Configuration::getBuildProfilesString() {
return "";
std::vector<std::string>::const_iterator p = profiles.begin();
std::string list = *p;
- for (; p != profiles.end(); ++p)
+ for (++p; p != profiles.end(); ++p)
list.append(",").append(*p);
return list;
}
diff --git a/apt-pkg/aptconfiguration.h b/apt-pkg/aptconfiguration.h
index dfed194ae..c7b8d2d73 100644
--- a/apt-pkg/aptconfiguration.h
+++ b/apt-pkg/aptconfiguration.h
@@ -123,9 +123,6 @@ public: /*{{{*/
/** \return Return a comma-separated list of enabled build profile specifications */
std::string static const getBuildProfilesString();
/*}}}*/
- private: /*{{{*/
- void static setDefaultConfigurationForCompressors();
- /*}}}*/
};
/*}}}*/
}
diff --git a/apt-pkg/cachefilter.cc b/apt-pkg/cachefilter.cc
index e388f2450..4362f43e3 100644
--- a/apt-pkg/cachefilter.cc
+++ b/apt-pkg/cachefilter.cc
@@ -6,6 +6,7 @@
// Include Files /*{{{*/
#include <config.h>
+#include <apt-pkg/cachefile.h>
#include <apt-pkg/cachefilter.h>
#include <apt-pkg/error.h>
#include <apt-pkg/pkgcache.h>
@@ -22,7 +23,11 @@
/*}}}*/
namespace APT {
namespace CacheFilter {
-PackageNameMatchesRegEx::PackageNameMatchesRegEx(std::string const &Pattern) : d(NULL) {/*{{{*/
+APT_CONST Matcher::~Matcher() {}
+APT_CONST PackageMatcher::~PackageMatcher() {}
+
+// Name matches RegEx /*{{{*/
+PackageNameMatchesRegEx::PackageNameMatchesRegEx(std::string const &Pattern) {
pattern = new regex_t;
int const Res = regcomp(pattern, Pattern.c_str(), REG_EXTENDED | REG_ICASE | REG_NOSUB);
if (Res == 0)
@@ -34,41 +39,36 @@ PackageNameMatchesRegEx::PackageNameMatchesRegEx(std::string const &Pattern) : d
regerror(Res, pattern, Error, sizeof(Error));
_error->Error(_("Regex compilation error - %s"), Error);
}
- /*}}}*/
-bool PackageNameMatchesRegEx::operator() (pkgCache::PkgIterator const &Pkg) {/*{{{*/
+bool PackageNameMatchesRegEx::operator() (pkgCache::PkgIterator const &Pkg) {
if (unlikely(pattern == NULL))
return false;
else
return regexec(pattern, Pkg.Name(), 0, 0, 0) == 0;
}
- /*}}}*/
-bool PackageNameMatchesRegEx::operator() (pkgCache::GrpIterator const &Grp) {/*{{{*/
+bool PackageNameMatchesRegEx::operator() (pkgCache::GrpIterator const &Grp) {
if (unlikely(pattern == NULL))
return false;
else
return regexec(pattern, Grp.Name(), 0, 0, 0) == 0;
}
- /*}}}*/
-PackageNameMatchesRegEx::~PackageNameMatchesRegEx() { /*{{{*/
+PackageNameMatchesRegEx::~PackageNameMatchesRegEx() {
if (pattern == NULL)
return;
regfree(pattern);
delete pattern;
}
/*}}}*/
-
-// Fnmatch support /*{{{*/
-//----------------------------------------------------------------------
-bool PackageNameMatchesFnmatch::operator() (pkgCache::PkgIterator const &Pkg) {/*{{{*/
+// Name matches Fnmatch /*{{{*/
+PackageNameMatchesFnmatch::PackageNameMatchesFnmatch(std::string const &Pattern) :
+ Pattern(Pattern) {}
+bool PackageNameMatchesFnmatch::operator() (pkgCache::PkgIterator const &Pkg) {
return fnmatch(Pattern.c_str(), Pkg.Name(), FNM_CASEFOLD) == 0;
}
- /*}}}*/
-bool PackageNameMatchesFnmatch::operator() (pkgCache::GrpIterator const &Grp) {/*{{{*/
+bool PackageNameMatchesFnmatch::operator() (pkgCache::GrpIterator const &Grp) {
return fnmatch(Pattern.c_str(), Grp.Name(), FNM_CASEFOLD) == 0;
}
/*}}}*/
-
-// CompleteArch to <kernel>-<cpu> tuple /*{{{*/
+// Architecture matches <kernel>-<cpu> specification /*{{{*/
//----------------------------------------------------------------------
/* The complete architecture, consisting of <kernel>-<cpu>. */
static std::string CompleteArch(std::string const &arch) {
@@ -82,12 +82,10 @@ static std::string CompleteArch(std::string const &arch) {
else if (arch == "any") return "*-*";
else return "linux-" + arch;
}
- /*}}}*/
-PackageArchitectureMatchesSpecification::PackageArchitectureMatchesSpecification(std::string const &pattern, bool const isPattern) :/*{{{*/
- literal(pattern), complete(CompleteArch(pattern)), isPattern(isPattern), d(NULL) {
+PackageArchitectureMatchesSpecification::PackageArchitectureMatchesSpecification(std::string const &pattern, bool const isPattern) :
+ literal(pattern), complete(CompleteArch(pattern)), isPattern(isPattern) {
}
- /*}}}*/
-bool PackageArchitectureMatchesSpecification::operator() (char const * const &arch) {/*{{{*/
+bool PackageArchitectureMatchesSpecification::operator() (char const * const &arch) {
if (strcmp(literal.c_str(), arch) == 0 ||
strcmp(complete.c_str(), arch) == 0)
return true;
@@ -96,16 +94,112 @@ bool PackageArchitectureMatchesSpecification::operator() (char const * const &ar
return fnmatch(complete.c_str(), pkgarch.c_str(), 0) == 0;
return fnmatch(pkgarch.c_str(), complete.c_str(), 0) == 0;
}
- /*}}}*/
-bool PackageArchitectureMatchesSpecification::operator() (pkgCache::PkgIterator const &Pkg) {/*{{{*/
+bool PackageArchitectureMatchesSpecification::operator() (pkgCache::PkgIterator const &Pkg) {
return (*this)(Pkg.Arch());
}
+PackageArchitectureMatchesSpecification::~PackageArchitectureMatchesSpecification() {
+}
/*}}}*/
-bool PackageArchitectureMatchesSpecification::operator() (pkgCache::VerIterator const &Ver) {/*{{{*/
- return (*this)(Ver.ParentPkg());
+// Package is new install /*{{{*/
+PackageIsNewInstall::PackageIsNewInstall(pkgCacheFile * const Cache) : Cache(Cache) {}
+APT_PURE bool PackageIsNewInstall::operator() (pkgCache::PkgIterator const &Pkg) {
+ return (*Cache)[Pkg].NewInstall();
}
+PackageIsNewInstall::~PackageIsNewInstall() {}
/*}}}*/
-PackageArchitectureMatchesSpecification::~PackageArchitectureMatchesSpecification() { /*{{{*/
+// Generica like True, False, NOT, AND, OR /*{{{*/
+APT_CONST bool TrueMatcher::operator() (pkgCache::PkgIterator const &) { return true; }
+APT_CONST bool TrueMatcher::operator() (pkgCache::GrpIterator const &) { return true; }
+APT_CONST bool TrueMatcher::operator() (pkgCache::VerIterator const &) { return true; }
+
+APT_CONST bool FalseMatcher::operator() (pkgCache::PkgIterator const &) { return false; }
+APT_CONST bool FalseMatcher::operator() (pkgCache::GrpIterator const &) { return false; }
+APT_CONST bool FalseMatcher::operator() (pkgCache::VerIterator const &) { return false; }
+
+NOTMatcher::NOTMatcher(Matcher * const matcher) : matcher(matcher) {}
+bool NOTMatcher::operator() (pkgCache::PkgIterator const &Pkg) { return ! (*matcher)(Pkg); }
+bool NOTMatcher::operator() (pkgCache::GrpIterator const &Grp) { return ! (*matcher)(Grp); }
+bool NOTMatcher::operator() (pkgCache::VerIterator const &Ver) { return ! (*matcher)(Ver); }
+NOTMatcher::~NOTMatcher() { delete matcher; }
+
+ANDMatcher::ANDMatcher() {}
+ANDMatcher::ANDMatcher(Matcher * const matcher1) {
+ AND(matcher1);
+}
+ANDMatcher::ANDMatcher(Matcher * const matcher1, Matcher * const matcher2) {
+ AND(matcher1).AND(matcher2);
+}
+ANDMatcher::ANDMatcher(Matcher * const matcher1, Matcher * const matcher2, Matcher * const matcher3) {
+ AND(matcher1).AND(matcher2).AND(matcher3);
+}
+ANDMatcher::ANDMatcher(Matcher * const matcher1, Matcher * const matcher2, Matcher * const matcher3, Matcher * const matcher4) {
+ AND(matcher1).AND(matcher2).AND(matcher3).AND(matcher4);
+}
+ANDMatcher::ANDMatcher(Matcher * const matcher1, Matcher * const matcher2, Matcher * const matcher3, Matcher * const matcher4, Matcher * const matcher5) {
+ AND(matcher1).AND(matcher2).AND(matcher3).AND(matcher4).AND(matcher5);
+}
+ANDMatcher& ANDMatcher::AND(Matcher * const matcher) { matchers.push_back(matcher); return *this; }
+bool ANDMatcher::operator() (pkgCache::PkgIterator const &Pkg) {
+ for (std::vector<Matcher *>::const_iterator M = matchers.begin(); M != matchers.end(); ++M)
+ if ((**M)(Pkg) == false)
+ return false;
+ return true;
+}
+bool ANDMatcher::operator() (pkgCache::GrpIterator const &Grp) {
+ for (std::vector<Matcher *>::const_iterator M = matchers.begin(); M != matchers.end(); ++M)
+ if ((**M)(Grp) == false)
+ return false;
+ return true;
+}
+bool ANDMatcher::operator() (pkgCache::VerIterator const &Ver) {
+ for (std::vector<Matcher *>::const_iterator M = matchers.begin(); M != matchers.end(); ++M)
+ if ((**M)(Ver) == false)
+ return false;
+ return true;
+}
+ANDMatcher::~ANDMatcher() {
+ for (std::vector<Matcher *>::iterator M = matchers.begin(); M != matchers.end(); ++M)
+ delete *M;
+}
+
+ORMatcher::ORMatcher() {}
+ORMatcher::ORMatcher(Matcher * const matcher1) {
+ OR(matcher1);
+}
+ORMatcher::ORMatcher(Matcher * const matcher1, Matcher * const matcher2) {
+ OR(matcher1).OR(matcher2);
+}
+ORMatcher::ORMatcher(Matcher * const matcher1, Matcher * const matcher2, Matcher * const matcher3) {
+ OR(matcher1).OR(matcher2).OR(matcher3);
+}
+ORMatcher::ORMatcher(Matcher * const matcher1, Matcher * const matcher2, Matcher * const matcher3, Matcher * const matcher4) {
+ OR(matcher1).OR(matcher2).OR(matcher3).OR(matcher4);
+}
+ORMatcher::ORMatcher(Matcher * const matcher1, Matcher * const matcher2, Matcher * const matcher3, Matcher * const matcher4, Matcher * const matcher5) {
+ OR(matcher1).OR(matcher2).OR(matcher3).OR(matcher4).OR(matcher5);
+}
+ORMatcher& ORMatcher::OR(Matcher * const matcher) { matchers.push_back(matcher); return *this; }
+bool ORMatcher::operator() (pkgCache::PkgIterator const &Pkg) {
+ for (std::vector<Matcher *>::const_iterator M = matchers.begin(); M != matchers.end(); ++M)
+ if ((**M)(Pkg) == true)
+ return true;
+ return false;
+}
+bool ORMatcher::operator() (pkgCache::GrpIterator const &Grp) {
+ for (std::vector<Matcher *>::const_iterator M = matchers.begin(); M != matchers.end(); ++M)
+ if ((**M)(Grp) == true)
+ return true;
+ return false;
+}
+bool ORMatcher::operator() (pkgCache::VerIterator const &Ver) {
+ for (std::vector<Matcher *>::const_iterator M = matchers.begin(); M != matchers.end(); ++M)
+ if ((**M)(Ver) == true)
+ return true;
+ return false;
+}
+ORMatcher::~ORMatcher() {
+ for (std::vector<Matcher *>::iterator M = matchers.begin(); M != matchers.end(); ++M)
+ delete *M;
}
/*}}}*/
diff --git a/apt-pkg/cachefilter.h b/apt-pkg/cachefilter.h
index 6d10d1163..b4697b773 100644
--- a/apt-pkg/cachefilter.h
+++ b/apt-pkg/cachefilter.h
@@ -10,86 +10,90 @@
#include <apt-pkg/cacheiterators.h>
#include <string>
+#include <vector>
#include <regex.h>
+
+class pkgCacheFile;
/*}}}*/
namespace APT {
namespace CacheFilter {
-#define PACKAGE_MATCHER_ABI_COMPAT 1
-#ifdef PACKAGE_MATCHER_ABI_COMPAT
-
-// PackageNameMatchesRegEx /*{{{*/
-class PackageNameMatchesRegEx {
- /** \brief dpointer placeholder (for later in case we need it) */
- void *d;
- regex_t* pattern;
+class Matcher {
public:
- PackageNameMatchesRegEx(std::string const &Pattern);
- bool operator() (pkgCache::PkgIterator const &Pkg);
- bool operator() (pkgCache::GrpIterator const &Grp);
- ~PackageNameMatchesRegEx();
+ virtual bool operator() (pkgCache::PkgIterator const &/*Pkg*/) = 0;
+ virtual bool operator() (pkgCache::GrpIterator const &/*Grp*/) = 0;
+ virtual bool operator() (pkgCache::VerIterator const &/*Ver*/) = 0;
+ virtual ~Matcher();
};
- /*}}}*/
-// PackageNameMatchesFnmatch /*{{{*/
- class PackageNameMatchesFnmatch {
- /** \brief dpointer placeholder (for later in case we need it) */
- void *d;
- const std::string Pattern;
+
+class PackageMatcher : public Matcher {
public:
- PackageNameMatchesFnmatch(std::string const &Pattern)
- : Pattern(Pattern) {};
- bool operator() (pkgCache::PkgIterator const &Pkg);
- bool operator() (pkgCache::GrpIterator const &Grp);
- ~PackageNameMatchesFnmatch() {};
+ virtual bool operator() (pkgCache::PkgIterator const &Pkg) = 0;
+ virtual bool operator() (pkgCache::VerIterator const &Ver) { return (*this)(Ver.ParentPkg()); }
+ virtual bool operator() (pkgCache::GrpIterator const &/*Grp*/) { return false; }
+ virtual ~PackageMatcher();
};
- /*}}}*/
-// PackageArchitectureMatchesSpecification /*{{{*/
-/** \class PackageArchitectureMatchesSpecification
- \brief matching against architecture specification strings
- The strings are of the format \<kernel\>-\<cpu\> where either component,
- or the whole string, can be the wildcard "any" as defined in
- debian-policy §11.1 "Architecture specification strings".
-
- Examples: i386, mipsel, linux-any, any-amd64, any */
-class PackageArchitectureMatchesSpecification {
- std::string literal;
- std::string complete;
- bool isPattern;
- /** \brief dpointer placeholder (for later in case we need it) */
- void *d;
+// Generica like True, False, NOT, AND, OR /*{{{*/
+class TrueMatcher : public Matcher {
public:
- /** \brief matching against architecture specification strings
- *
- * @param pattern is the architecture specification string
- * @param isPattern defines if the given \b pattern is a
- * architecture specification pattern to match others against
- * or if it is the fixed string and matched against patterns
- */
- PackageArchitectureMatchesSpecification(std::string const &pattern, bool const isPattern = true);
- bool operator() (char const * const &arch);
- bool operator() (pkgCache::PkgIterator const &Pkg);
- bool operator() (pkgCache::VerIterator const &Ver);
- ~PackageArchitectureMatchesSpecification();
+ virtual bool operator() (pkgCache::PkgIterator const &Pkg);
+ virtual bool operator() (pkgCache::GrpIterator const &Grp);
+ virtual bool operator() (pkgCache::VerIterator const &Ver);
};
- /*}}}*/
-#else
+class FalseMatcher : public Matcher {
+public:
+ virtual bool operator() (pkgCache::PkgIterator const &Pkg);
+ virtual bool operator() (pkgCache::GrpIterator const &Grp);
+ virtual bool operator() (pkgCache::VerIterator const &Ver);
+};
-class PackageMatcher {
- public:
- virtual bool operator() (pkgCache::PkgIterator const &Pkg) { return false; };
- virtual bool operator() (pkgCache::GrpIterator const &Grp) { return false; };
- virtual bool operator() (pkgCache::VerIterator const &Ver) { return false; };
-
- virtual ~PackageMatcher() {};
+class NOTMatcher : public Matcher {
+ Matcher * const matcher;
+public:
+ NOTMatcher(Matcher * const matcher);
+ virtual bool operator() (pkgCache::PkgIterator const &Pkg);
+ virtual bool operator() (pkgCache::GrpIterator const &Grp);
+ virtual bool operator() (pkgCache::VerIterator const &Ver);
+ virtual ~NOTMatcher();
};
-// PackageNameMatchesRegEx /*{{{*/
-class PackageNameMatchesRegEx : public PackageMatcher {
- /** \brief dpointer placeholder (for later in case we need it) */
- void *d;
+class ANDMatcher : public Matcher {
+ std::vector<Matcher *> matchers;
+public:
+ // 5 ought to be enough for everybody… c++11 variadic templates would be nice
+ ANDMatcher();
+ ANDMatcher(Matcher * const matcher1);
+ ANDMatcher(Matcher * const matcher1, Matcher * const matcher2);
+ ANDMatcher(Matcher * const matcher1, Matcher * const matcher2, Matcher * const matcher3);
+ ANDMatcher(Matcher * const matcher1, Matcher * const matcher2, Matcher * const matcher3, Matcher * const matcher4);
+ ANDMatcher(Matcher * const matcher1, Matcher * const matcher2, Matcher * const matcher3, Matcher * const matcher4, Matcher * const matcher5);
+ ANDMatcher& AND(Matcher * const matcher);
+ virtual bool operator() (pkgCache::PkgIterator const &Pkg);
+ virtual bool operator() (pkgCache::GrpIterator const &Grp);
+ virtual bool operator() (pkgCache::VerIterator const &Ver);
+ virtual ~ANDMatcher();
+};
+class ORMatcher : public Matcher {
+ std::vector<Matcher *> matchers;
+public:
+ // 5 ought to be enough for everybody… c++11 variadic templates would be nice
+ ORMatcher();
+ ORMatcher(Matcher * const matcher1);
+ ORMatcher(Matcher * const matcher1, Matcher * const matcher2);
+ ORMatcher(Matcher * const matcher1, Matcher * const matcher2, Matcher * const matcher3);
+ ORMatcher(Matcher * const matcher1, Matcher * const matcher2, Matcher * const matcher3, Matcher * const matcher4);
+ ORMatcher(Matcher * const matcher1, Matcher * const matcher2, Matcher * const matcher3, Matcher * const matcher4, Matcher * const matcher5);
+ ORMatcher& OR(Matcher * const matcher);
+ virtual bool operator() (pkgCache::PkgIterator const &Pkg);
+ virtual bool operator() (pkgCache::GrpIterator const &Grp);
+ virtual bool operator() (pkgCache::VerIterator const &Ver);
+ virtual ~ORMatcher();
+};
+ /*}}}*/
+class PackageNameMatchesRegEx : public PackageMatcher { /*{{{*/
regex_t* pattern;
public:
PackageNameMatchesRegEx(std::string const &Pattern);
@@ -98,20 +102,16 @@ public:
virtual ~PackageNameMatchesRegEx();
};
/*}}}*/
-// PackageNameMatchesFnmatch /*{{{*/
- class PackageNameMatchesFnmatch : public PackageMatcher{
- /** \brief dpointer placeholder (for later in case we need it) */
- void *d;
- const std::string Pattern;
+class PackageNameMatchesFnmatch : public PackageMatcher { /*{{{*/
+ const std::string Pattern;
public:
- PackageNameMatchesFnmatch(std::string const &Pattern)
- : Pattern(Pattern) {};
- virtual bool operator() (pkgCache::PkgIterator const &Pkg);
+ PackageNameMatchesFnmatch(std::string const &Pattern);
+ virtual bool operator() (pkgCache::PkgIterator const &Pkg);
virtual bool operator() (pkgCache::GrpIterator const &Grp);
virtual ~PackageNameMatchesFnmatch() {};
};
/*}}}*/
-// PackageArchitectureMatchesSpecification /*{{{*/
+class PackageArchitectureMatchesSpecification : public PackageMatcher { /*{{{*/
/** \class PackageArchitectureMatchesSpecification
\brief matching against architecture specification strings
@@ -120,12 +120,9 @@ public:
debian-policy §11.1 "Architecture specification strings".
Examples: i386, mipsel, linux-any, any-amd64, any */
-class PackageArchitectureMatchesSpecification : public PackageMatcher {
std::string literal;
std::string complete;
bool isPattern;
- /** \brief dpointer placeholder (for later in case we need it) */
- void *d;
public:
/** \brief matching against architecture specification strings
*
@@ -137,11 +134,18 @@ public:
PackageArchitectureMatchesSpecification(std::string const &pattern, bool const isPattern = true);
bool operator() (char const * const &arch);
virtual bool operator() (pkgCache::PkgIterator const &Pkg);
- virtual bool operator() (pkgCache::VerIterator const &Ver);
virtual ~PackageArchitectureMatchesSpecification();
};
-#endif
/*}}}*/
+class PackageIsNewInstall : public PackageMatcher { /*{{{*/
+ pkgCacheFile * const Cache;
+public:
+ PackageIsNewInstall(pkgCacheFile * const Cache);
+ virtual bool operator() (pkgCache::PkgIterator const &Pkg);
+ virtual ~PackageIsNewInstall();
+};
+ /*}}}*/
+
}
}
#endif
diff --git a/apt-pkg/cacheiterators.h b/apt-pkg/cacheiterators.h
index 2fdf8404d..b0c02d4a2 100644
--- a/apt-pkg/cacheiterators.h
+++ b/apt-pkg/cacheiterators.h
@@ -159,8 +159,12 @@ class pkgCache::PkgIterator: public Iterator<Package, PkgIterator> {
enum OkState {NeedsNothing,NeedsUnpack,NeedsConfigure};
// Accessors
- inline const char *Name() const {return S->Name == 0?0:Owner->StrP + S->Name;}
- inline const char *Section() const {return S->Section == 0?0:Owner->StrP + S->Section;}
+ inline const char *Name() const { return Group().Name(); }
+ // Versions have sections - and packages can have different versions with different sections
+ // so this interface is broken by design. It used to return the section of the "first parsed
+ // package stanza", but as this can potentially be anything it now returns the section of the
+ // newest version instead (if any). aka: Run as fast as you can to Version.Section().
+ APT_DEPRECATED const char *Section() const;
inline bool Purge() const {return S->CurrentState == pkgCache::State::Purge ||
(S->CurrentVer == 0 && S->CurrentState == pkgCache::State::NotInstalled);}
inline const char *Arch() const {return S->Arch == 0?0:Owner->StrP + S->Arch;}
@@ -211,6 +215,12 @@ class pkgCache::VerIterator : public Iterator<Version, VerIterator> {
// Accessors
inline const char *VerStr() const {return S->VerStr == 0?0:Owner->StrP + S->VerStr;}
inline const char *Section() const {return S->Section == 0?0:Owner->StrP + S->Section;}
+ /** \brief source package name this version comes from
+ Always contains the name, even if it is the same as the binary name */
+ inline const char *SourcePkgName() const {return Owner->StrP + S->SourcePkgName;}
+ /** \brief source version this version comes from
+ Always contains the version string, even if it is the same as the binary version */
+ inline const char *SourceVerStr() const {return Owner->StrP + S->SourceVerStr;}
inline const char *Arch() const {
if ((S->MultiArch & pkgCache::Version::All) == pkgCache::Version::All)
return "all";
@@ -332,7 +342,7 @@ class pkgCache::PrvIterator : public Iterator<Provides, PrvIterator> {
inline void operator ++() {operator ++(0);}
// Accessors
- inline const char *Name() const {return Owner->StrP + Owner->PkgP[S->ParentPkg].Name;}
+ inline const char *Name() const {return ParentPkg().Name();}
inline const char *ProvideVersion() const {return S->ProvideVersion == 0?0:Owner->StrP + S->ProvideVersion;}
inline PkgIterator ParentPkg() const {return PkgIterator(*Owner,Owner->PkgP + S->ParentPkg);}
inline VerIterator OwnerVer() const {return VerIterator(*Owner,Owner->VerP + S->Version);}
diff --git a/apt-pkg/cacheset.cc b/apt-pkg/cacheset.cc
index 2ed6a96da..76a7e717e 100644
--- a/apt-pkg/cacheset.cc
+++ b/apt-pkg/cacheset.cc
@@ -24,6 +24,7 @@
#include <apt-pkg/depcache.h>
#include <apt-pkg/macros.h>
#include <apt-pkg/pkgcache.h>
+#include <apt-pkg/fileutl.h>
#include <stddef.h>
#include <stdio.h>
@@ -36,8 +37,23 @@
#include <apti18n.h>
/*}}}*/
namespace APT {
-// FromTask - Return all packages in the cache from a specific task /*{{{*/
-bool PackageContainerInterface::FromTask(PackageContainerInterface * const pci, pkgCacheFile &Cache, std::string pattern, CacheSetHelper &helper) {
+
+// PackageFrom - selecting the appropriate method for package selection /*{{{*/
+bool CacheSetHelper::PackageFrom(enum PkgSelector const select, PackageContainerInterface * const pci,
+ pkgCacheFile &Cache, std::string const &pattern) {
+ switch (select) {
+ case UNKNOWN: return false;
+ case REGEX: return PackageFromRegEx(pci, Cache, pattern);
+ case TASK: return PackageFromTask(pci, Cache, pattern);
+ case FNMATCH: return PackageFromFnmatch(pci, Cache, pattern);
+ case PACKAGENAME: return PackageFromPackageName(pci, Cache, pattern);
+ case STRING: return PackageFromString(pci, Cache, pattern);
+ }
+ return false;
+}
+ /*}}}*/
+// PackageFromTask - Return all packages in the cache from a specific task /*{{{*/
+bool CacheSetHelper::PackageFromTask(PackageContainerInterface * const pci, pkgCacheFile &Cache, std::string pattern) {
size_t const archfound = pattern.find_last_of(':');
std::string arch = "native";
if (archfound != std::string::npos) {
@@ -54,7 +70,7 @@ bool PackageContainerInterface::FromTask(PackageContainerInterface * const pci,
bool const wasEmpty = pci->empty();
if (wasEmpty == true)
- pci->setConstructor(TASK);
+ pci->setConstructor(CacheSetHelper::TASK);
// get the records
pkgRecords Recs(Cache);
@@ -90,32 +106,32 @@ bool PackageContainerInterface::FromTask(PackageContainerInterface * const pci,
continue;
pci->insert(Pkg);
- helper.showTaskSelection(Pkg, pattern);
+ showPackageSelection(Pkg, CacheSetHelper::TASK, pattern);
found = true;
}
regfree(&Pattern);
if (found == false) {
- helper.canNotFindTask(pci, Cache, pattern);
- pci->setConstructor(UNKNOWN);
+ canNotFindPackage(CacheSetHelper::TASK, pci, Cache, pattern);
+ pci->setConstructor(CacheSetHelper::UNKNOWN);
return false;
}
- if (wasEmpty == false && pci->getConstructor() != UNKNOWN)
- pci->setConstructor(UNKNOWN);
+ if (wasEmpty == false && pci->getConstructor() != CacheSetHelper::UNKNOWN)
+ pci->setConstructor(CacheSetHelper::UNKNOWN);
return true;
}
/*}}}*/
-// FromRegEx - Return all packages in the cache matching a pattern /*{{{*/
-bool PackageContainerInterface::FromRegEx(PackageContainerInterface * const pci, pkgCacheFile &Cache, std::string pattern, CacheSetHelper &helper) {
+// PackageFromRegEx - Return all packages in the cache matching a pattern /*{{{*/
+bool CacheSetHelper::PackageFromRegEx(PackageContainerInterface * const pci, pkgCacheFile &Cache, std::string pattern) {
static const char * const isregex = ".?+*|[^$";
if (pattern.find_first_of(isregex) == std::string::npos)
return false;
bool const wasEmpty = pci->empty();
if (wasEmpty == true)
- pci->setConstructor(REGEX);
+ pci->setConstructor(CacheSetHelper::REGEX);
size_t archfound = pattern.find_last_of(':');
std::string arch = "native";
@@ -149,28 +165,25 @@ bool PackageContainerInterface::FromRegEx(PackageContainerInterface * const pci,
}
pci->insert(Pkg);
- helper.showRegExSelection(Pkg, pattern);
+ showPackageSelection(Pkg, CacheSetHelper::REGEX, pattern);
found = true;
}
if (found == false) {
- helper.canNotFindRegEx(pci, Cache, pattern);
- pci->setConstructor(UNKNOWN);
+ canNotFindPackage(CacheSetHelper::REGEX, pci, Cache, pattern);
+ pci->setConstructor(CacheSetHelper::UNKNOWN);
return false;
}
- if (wasEmpty == false && pci->getConstructor() != UNKNOWN)
- pci->setConstructor(UNKNOWN);
+ if (wasEmpty == false && pci->getConstructor() != CacheSetHelper::UNKNOWN)
+ pci->setConstructor(CacheSetHelper::UNKNOWN);
return true;
}
/*}}}*/
-// FromFnmatch - Returns the package defined by this fnmatch /*{{{*/
-bool
-PackageContainerInterface::FromFnmatch(PackageContainerInterface * const pci,
- pkgCacheFile &Cache,
- std::string pattern,
- CacheSetHelper &helper)
+// PackageFromFnmatch - Returns the package defined by this fnmatch /*{{{*/
+bool CacheSetHelper::PackageFromFnmatch(PackageContainerInterface * const pci,
+ pkgCacheFile &Cache, std::string pattern)
{
static const char * const isfnmatch = ".?*[]!";
if (pattern.find_first_of(isfnmatch) == std::string::npos)
@@ -178,7 +191,7 @@ PackageContainerInterface::FromFnmatch(PackageContainerInterface * const pci,
bool const wasEmpty = pci->empty();
if (wasEmpty == true)
- pci->setConstructor(FNMATCH);
+ pci->setConstructor(CacheSetHelper::FNMATCH);
size_t archfound = pattern.find_last_of(':');
std::string arch = "native";
@@ -212,33 +225,25 @@ PackageContainerInterface::FromFnmatch(PackageContainerInterface * const pci,
}
pci->insert(Pkg);
-#if (APT_PKG_MAJOR >= 4 && APT_PKG_MINOR >= 13)
- helper.showFnmatchSelection(Pkg, pattern);
-#else
- helper.showRegExSelection(Pkg, pattern);
-#endif
+ showPackageSelection(Pkg, CacheSetHelper::FNMATCH, pattern);
found = true;
}
if (found == false) {
-#if (APT_PKG_MAJOR >= 4 && APT_PKG_MINOR >= 13)
- helper.canNotFindFnmatch(pci, Cache, pattern);
-#else
- helper.canNotFindRegEx(pci, Cache, pattern);
-#endif
- pci->setConstructor(UNKNOWN);
+ canNotFindPackage(CacheSetHelper::FNMATCH, pci, Cache, pattern);
+ pci->setConstructor(CacheSetHelper::UNKNOWN);
return false;
}
- if (wasEmpty == false && pci->getConstructor() != UNKNOWN)
- pci->setConstructor(UNKNOWN);
+ if (wasEmpty == false && pci->getConstructor() != CacheSetHelper::UNKNOWN)
+ pci->setConstructor(CacheSetHelper::UNKNOWN);
return true;
}
/*}}}*/
-// FromName - Returns the package defined by this string /*{{{*/
-pkgCache::PkgIterator PackageContainerInterface::FromName(pkgCacheFile &Cache,
- std::string const &str, CacheSetHelper &helper) {
+// PackageFromName - Returns the package defined by this string /*{{{*/
+pkgCache::PkgIterator CacheSetHelper::PackageFromName(pkgCacheFile &Cache,
+ std::string const &str) {
std::string pkg = str;
size_t archfound = pkg.find_last_of(':');
std::string arch;
@@ -259,13 +264,13 @@ pkgCache::PkgIterator PackageContainerInterface::FromName(pkgCacheFile &Cache,
Pkg = Cache.GetPkgCache()->FindPkg(pkg, arch);
if (Pkg.end() == true)
- return helper.canNotFindPkgName(Cache, str);
+ return canNotFindPkgName(Cache, str);
return Pkg;
}
/*}}}*/
-// FromGroup - Returns the package defined by this string /*{{{*/
-bool PackageContainerInterface::FromGroup(PackageContainerInterface * const pci, pkgCacheFile &Cache,
- std::string pkg, CacheSetHelper &helper) {
+// PackageFromPackageName - Returns the package defined by this string /*{{{*/
+bool CacheSetHelper::PackageFromPackageName(PackageContainerInterface * const pci, pkgCacheFile &Cache,
+ std::string pkg) {
if (unlikely(Cache.GetPkgCache() == 0))
return false;
@@ -305,7 +310,7 @@ bool PackageContainerInterface::FromGroup(PackageContainerInterface * const pci,
}
}
- pkgCache::PkgIterator Pkg = helper.canNotFindPkgName(Cache, pkg);
+ pkgCache::PkgIterator Pkg = canNotFindPkgName(Cache, pkg);
if (Pkg.end() == true)
return false;
@@ -313,19 +318,18 @@ bool PackageContainerInterface::FromGroup(PackageContainerInterface * const pci,
return true;
}
/*}}}*/
-// FromString - Return all packages matching a specific string /*{{{*/
-bool PackageContainerInterface::FromString(PackageContainerInterface * const pci, pkgCacheFile &Cache, std::string const &str, CacheSetHelper &helper) {
+// PackageFromString - Return all packages matching a specific string /*{{{*/
+bool CacheSetHelper::PackageFromString(PackageContainerInterface * const pci, pkgCacheFile &Cache, std::string const &str) {
bool found = true;
_error->PushToStack();
- if (FromGroup(pci, Cache, str, helper) == false &&
- FromTask(pci, Cache, str, helper) == false &&
-#if (APT_PKG_MAJOR >= 4 && APT_PKG_MINOR >= 13)
- FromFnmatch(pci, Cache, str, helper) == false)
-#endif
- FromRegEx(pci, Cache, str, helper) == false)
+ if (PackageFrom(CacheSetHelper::PACKAGENAME, pci, Cache, str) == false &&
+ PackageFrom(CacheSetHelper::TASK, pci, Cache, str) == false &&
+ // FIXME: hm, hm, regexp/fnmatch incompatible?
+ PackageFrom(CacheSetHelper::FNMATCH, pci, Cache, str) == false &&
+ PackageFrom(CacheSetHelper::REGEX, pci, Cache, str) == false)
{
- helper.canNotFindPackage(pci, Cache, str);
+ canNotFindPackage(CacheSetHelper::PACKAGENAME, pci, Cache, str);
found = false;
}
@@ -336,51 +340,50 @@ bool PackageContainerInterface::FromString(PackageContainerInterface * const pci
return found;
}
/*}}}*/
-// FromCommandLine - Return all packages specified on commandline /*{{{*/
-bool PackageContainerInterface::FromCommandLine(PackageContainerInterface * const pci, pkgCacheFile &Cache, const char **cmdline, CacheSetHelper &helper) {
+// PackageFromCommandLine - Return all packages specified on commandline /*{{{*/
+bool CacheSetHelper::PackageFromCommandLine(PackageContainerInterface * const pci, pkgCacheFile &Cache, const char **cmdline) {
bool found = false;
for (const char **I = cmdline; *I != 0; ++I)
- found |= PackageContainerInterface::FromString(pci, Cache, *I, helper);
+ found |= PackageFrom(CacheSetHelper::PACKAGENAME, pci, Cache, *I);
return found;
}
/*}}}*/
// FromModifierCommandLine - helper doing the work for PKG:GroupedFromCommandLine /*{{{*/
-bool PackageContainerInterface::FromModifierCommandLine(unsigned short &modID, PackageContainerInterface * const pci,
+bool CacheSetHelper::PackageFromModifierCommandLine(unsigned short &modID, PackageContainerInterface * const pci,
pkgCacheFile &Cache, const char * cmdline,
- std::list<Modifier> const &mods, CacheSetHelper &helper) {
+ std::list<PkgModifier> const &mods) {
std::string str = cmdline;
unsigned short fallback = modID;
bool modifierPresent = false;
- for (std::list<Modifier>::const_iterator mod = mods.begin();
+ for (std::list<PkgModifier>::const_iterator mod = mods.begin();
mod != mods.end(); ++mod) {
size_t const alength = strlen(mod->Alias);
switch(mod->Pos) {
- case Modifier::POSTFIX:
+ case PkgModifier::POSTFIX:
if (str.compare(str.length() - alength, alength,
mod->Alias, 0, alength) != 0)
continue;
str.erase(str.length() - alength);
modID = mod->ID;
break;
- case Modifier::PREFIX:
+ case PkgModifier::PREFIX:
continue;
- case Modifier::NONE:
+ case PkgModifier::NONE:
continue;
}
modifierPresent = true;
break;
}
if (modifierPresent == true) {
- bool const errors = helper.showErrors(false);
- pkgCache::PkgIterator Pkg = FromName(Cache, cmdline, helper);
- helper.showErrors(errors);
- if (Pkg.end() == false) {
- pci->insert(Pkg);
+ bool const errors = showErrors(false);
+ bool const found = PackageFrom(PACKAGENAME, pci, Cache, cmdline);
+ showErrors(errors);
+ if (found == true) {
modID = fallback;
return true;
}
}
- return FromString(pci, Cache, str, helper);
+ return PackageFrom(CacheSetHelper::PACKAGENAME, pci, Cache, str);
}
/*}}}*/
// FromModifierCommandLine - helper doing the work for VER:GroupedFromCommandLine /*{{{*/
@@ -389,7 +392,7 @@ bool VersionContainerInterface::FromModifierCommandLine(unsigned short &modID,
pkgCacheFile &Cache, const char * cmdline,
std::list<Modifier> const &mods,
CacheSetHelper &helper) {
- Version select = NEWEST;
+ CacheSetHelper::VerSelector select = CacheSetHelper::NEWEST;
std::string str = cmdline;
if (unlikely(str.empty() == true))
return false;
@@ -432,7 +435,8 @@ bool VersionContainerInterface::FromModifierCommandLine(unsigned short &modID,
// FromCommandLine - Return all versions specified on commandline /*{{{*/
bool VersionContainerInterface::FromCommandLine(VersionContainerInterface * const vci,
pkgCacheFile &Cache, const char **cmdline,
- Version const &fallback, CacheSetHelper &helper) {
+ CacheSetHelper::VerSelector const fallback,
+ CacheSetHelper &helper) {
bool found = false;
for (const char **I = cmdline; *I != 0; ++I)
found |= VersionContainerInterface::FromString(vci, Cache, *I, fallback, helper);
@@ -442,8 +446,17 @@ bool VersionContainerInterface::FromCommandLine(VersionContainerInterface * cons
// FromString - Returns all versions spedcified by a string /*{{{*/
bool VersionContainerInterface::FromString(VersionContainerInterface * const vci,
pkgCacheFile &Cache, std::string pkg,
- Version const &fallback, CacheSetHelper &helper,
+ CacheSetHelper::VerSelector const fallback,
+ CacheSetHelper &helper,
bool const onlyFromName) {
+ PackageSet pkgset;
+ if(FileExists(pkg)) {
+ helper.PackageFrom(CacheSetHelper::STRING, &pkgset, Cache, pkg);
+ if(pkgset.empty() == true)
+ return false;
+ return VersionContainerInterface::FromPackage(vci, Cache, pkgset.begin(), fallback, helper);
+ }
+
std::string ver;
bool verIsRel = false;
size_t const vertag = pkg.find_last_of("/=");
@@ -452,15 +465,14 @@ bool VersionContainerInterface::FromString(VersionContainerInterface * const vci
verIsRel = (pkg[vertag] == '/');
pkg.erase(vertag);
}
- PackageSet pkgset;
if (onlyFromName == false)
- PackageContainerInterface::FromString(&pkgset, Cache, pkg, helper);
+ helper.PackageFrom(CacheSetHelper::STRING, &pkgset, Cache, pkg);
else {
- pkgset.insert(PackageContainerInterface::FromName(Cache, pkg, helper));
+ helper.PackageFrom(CacheSetHelper::PACKAGENAME, &pkgset, Cache, pkg);
}
bool errors = true;
- if (pkgset.getConstructor() != PackageSet::UNKNOWN)
+ if (pkgset.getConstructor() != CacheSetHelper::UNKNOWN)
errors = helper.showErrors(false);
bool found = false;
@@ -479,7 +491,7 @@ bool VersionContainerInterface::FromString(VersionContainerInterface * const vci
if (P->VersionList != 0)
V = P.VersionList();
else
- V = helper.canNotFindNewestVer(Cache, P);
+ V = helper.canNotGetVersion(CacheSetHelper::NEWEST, Cache, P);
} else {
pkgVersionMatch Match(ver, (verIsRel == true ? pkgVersionMatch::Release :
pkgVersionMatch::Version));
@@ -496,11 +508,14 @@ bool VersionContainerInterface::FromString(VersionContainerInterface * const vci
}
if (V.end() == true)
continue;
- helper.showSelectedVersion(P, V, ver, verIsRel);
+ if (verIsRel == true)
+ helper.showVersionSelection(P, V, CacheSetHelper::RELEASE, ver);
+ else
+ helper.showVersionSelection(P, V, CacheSetHelper::VERSIONNUMBER, ver);
vci->insert(V);
found = true;
}
- if (pkgset.getConstructor() != PackageSet::UNKNOWN)
+ if (pkgset.getConstructor() != CacheSetHelper::UNKNOWN)
helper.showErrors(errors);
return found;
}
@@ -509,30 +524,30 @@ bool VersionContainerInterface::FromString(VersionContainerInterface * const vci
bool VersionContainerInterface::FromPackage(VersionContainerInterface * const vci,
pkgCacheFile &Cache,
pkgCache::PkgIterator const &P,
- Version const &fallback,
+ CacheSetHelper::VerSelector const fallback,
CacheSetHelper &helper) {
pkgCache::VerIterator V;
bool showErrors;
bool found = false;
switch(fallback) {
- case ALL:
+ case CacheSetHelper::ALL:
if (P->VersionList != 0)
for (V = P.VersionList(); V.end() != true; ++V)
found |= vci->insert(V);
else
- helper.canNotFindAllVer(vci, Cache, P);
+ helper.canNotFindVersion(CacheSetHelper::ALL, vci, Cache, P);
break;
- case CANDANDINST:
+ case CacheSetHelper::CANDANDINST:
found |= vci->insert(getInstalledVer(Cache, P, helper));
found |= vci->insert(getCandidateVer(Cache, P, helper));
break;
- case CANDIDATE:
+ case CacheSetHelper::CANDIDATE:
found |= vci->insert(getCandidateVer(Cache, P, helper));
break;
- case INSTALLED:
+ case CacheSetHelper::INSTALLED:
found |= vci->insert(getInstalledVer(Cache, P, helper));
break;
- case CANDINST:
+ case CacheSetHelper::CANDINST:
showErrors = helper.showErrors(false);
V = getCandidateVer(Cache, P, helper);
if (V.end() == true)
@@ -541,9 +556,9 @@ bool VersionContainerInterface::FromPackage(VersionContainerInterface * const vc
if (V.end() == false)
found |= vci->insert(V);
else
- helper.canNotFindInstCandVer(vci, Cache, P);
+ helper.canNotFindVersion(CacheSetHelper::CANDINST, vci, Cache, P);
break;
- case INSTCAND:
+ case CacheSetHelper::INSTCAND:
showErrors = helper.showErrors(false);
V = getInstalledVer(Cache, P, helper);
if (V.end() == true)
@@ -552,14 +567,18 @@ bool VersionContainerInterface::FromPackage(VersionContainerInterface * const vc
if (V.end() == false)
found |= vci->insert(V);
else
- helper.canNotFindInstCandVer(vci, Cache, P);
+ helper.canNotFindVersion(CacheSetHelper::INSTCAND, vci, Cache, P);
break;
- case NEWEST:
+ case CacheSetHelper::NEWEST:
if (P->VersionList != 0)
found |= vci->insert(P.VersionList());
else
- helper.canNotFindNewestVer(Cache, P);
+ helper.canNotFindVersion(CacheSetHelper::NEWEST, vci, Cache, P);
break;
+ case CacheSetHelper::RELEASE:
+ case CacheSetHelper::VERSIONNUMBER:
+ // both make no sense here, so always false
+ return false;
}
return found;
}
@@ -576,7 +595,7 @@ pkgCache::VerIterator VersionContainerInterface::getCandidateVer(pkgCacheFile &C
Cand = Cache[Pkg].CandidateVerIter(Cache);
}
if (Cand.end() == true)
- return helper.canNotFindCandidateVer(Cache, Pkg);
+ return helper.canNotGetVersion(CacheSetHelper::CANDIDATE, Cache, Pkg);
return Cand;
}
/*}}}*/
@@ -584,19 +603,31 @@ pkgCache::VerIterator VersionContainerInterface::getCandidateVer(pkgCacheFile &C
pkgCache::VerIterator VersionContainerInterface::getInstalledVer(pkgCacheFile &Cache,
pkgCache::PkgIterator const &Pkg, CacheSetHelper &helper) {
if (Pkg->CurrentVer == 0)
- return helper.canNotFindInstalledVer(Cache, Pkg);
+ return helper.canNotGetVersion(CacheSetHelper::INSTALLED, Cache, Pkg);
return Pkg.CurrentVer();
}
/*}}}*/
-// canNotFindPkgName - handle the case no package has this name /*{{{*/
-pkgCache::PkgIterator CacheSetHelper::canNotFindPkgName(pkgCacheFile &Cache,
- std::string const &str) {
- if (ShowError == true)
- _error->Insert(ErrorType, _("Unable to locate package %s"), str.c_str());
- return pkgCache::PkgIterator(Cache, 0);
+// canNotFindPackage - with the given selector and pattern /*{{{*/
+void CacheSetHelper::canNotFindPackage(enum PkgSelector const select,
+ PackageContainerInterface * const pci, pkgCacheFile &Cache,
+ std::string const &pattern) {
+ switch (select) {
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+ case REGEX: canNotFindRegEx(pci, Cache, pattern); break;
+ case TASK: canNotFindTask(pci, Cache, pattern); break;
+ case FNMATCH: canNotFindFnmatch(pci, Cache, pattern); break;
+ case PACKAGENAME: canNotFindPackage(pci, Cache, pattern); break;
+ case STRING: canNotFindPackage(pci, Cache, pattern); break;
+ case UNKNOWN: break;
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic pop
+#endif
+ }
}
- /*}}}*/
// canNotFindTask - handle the case no package is found for a task /*{{{*/
void CacheSetHelper::canNotFindTask(PackageContainerInterface * const /*pci*/, pkgCacheFile &/*Cache*/, std::string pattern) {
if (ShowError == true)
@@ -608,17 +639,50 @@ void CacheSetHelper::canNotFindRegEx(PackageContainerInterface * const /*pci*/,
if (ShowError == true)
_error->Insert(ErrorType, _("Couldn't find any package by regex '%s'"), pattern.c_str());
}
-#if (APT_PKG_MAJOR >= 4 && APT_PKG_MINOR >= 13)
+ /*}}}*/
// canNotFindFnmatch - handle the case no package is found by a fnmatch /*{{{*/
-void CacheSetHelper::canNotFindFnmatch(PackageContainerInterface * const pci, pkgCacheFile &Cache, std::string pattern) {
+ void CacheSetHelper::canNotFindFnmatch(PackageContainerInterface * const /*pci*/, pkgCacheFile &/*Cache*/, std::string pattern) {
if (ShowError == true)
_error->Insert(ErrorType, _("Couldn't find any package by glob '%s'"), pattern.c_str());
}
-#endif /*}}}*/
+ /*}}}*/
// canNotFindPackage - handle the case no package is found from a string/*{{{*/
APT_CONST void CacheSetHelper::canNotFindPackage(PackageContainerInterface * const /*pci*/, pkgCacheFile &/*Cache*/, std::string const &/*str*/) {
}
/*}}}*/
+ /*}}}*/
+// canNotFindPkgName - handle the case no package has this name /*{{{*/
+pkgCache::PkgIterator CacheSetHelper::canNotFindPkgName(pkgCacheFile &Cache,
+ std::string const &str) {
+ if (ShowError == true)
+ _error->Insert(ErrorType, _("Unable to locate package %s"), str.c_str());
+ return pkgCache::PkgIterator(Cache, 0);
+}
+ /*}}}*/
+// canNotFindVersion - for package by selector /*{{{*/
+void CacheSetHelper::canNotFindVersion(enum VerSelector const select, VersionContainerInterface * const vci, pkgCacheFile &Cache, pkgCache::PkgIterator const &Pkg)
+{
+ switch (select) {
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+ case ALL: canNotFindAllVer(vci, Cache, Pkg); break;
+ case INSTCAND: canNotFindInstCandVer(vci, Cache, Pkg); break;
+ case CANDINST: canNotFindCandInstVer(vci, Cache, Pkg); break;
+ case NEWEST: canNotFindNewestVer(Cache, Pkg); break;
+ case CANDIDATE: canNotFindCandidateVer(Cache, Pkg); break;
+ case INSTALLED: canNotFindInstalledVer(Cache, Pkg); break;
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic pop
+#endif
+ case CANDANDINST: canNotGetCandInstVer(Cache, Pkg); break;
+ case RELEASE:
+ case VERSIONNUMBER:
+ // invalid in this branch
+ break;
+ }
+}
// canNotFindAllVer /*{{{*/
void CacheSetHelper::canNotFindAllVer(VersionContainerInterface * const /*vci*/, pkgCacheFile &/*Cache*/,
pkgCache::PkgIterator const &Pkg) {
@@ -627,19 +691,42 @@ void CacheSetHelper::canNotFindAllVer(VersionContainerInterface * const /*vci*/,
}
/*}}}*/
// canNotFindInstCandVer /*{{{*/
-void CacheSetHelper::canNotFindInstCandVer(VersionContainerInterface * const /*vci*/, pkgCacheFile &/*Cache*/,
+void CacheSetHelper::canNotFindInstCandVer(VersionContainerInterface * const /*vci*/, pkgCacheFile &Cache,
pkgCache::PkgIterator const &Pkg) {
- if (ShowError == true)
- _error->Insert(ErrorType, _("Can't select installed nor candidate version from package '%s' as it has neither of them"), Pkg.FullName(true).c_str());
+ canNotGetInstCandVer(Cache, Pkg);
}
/*}}}*/
// canNotFindInstCandVer /*{{{*/
-void CacheSetHelper::canNotFindCandInstVer(VersionContainerInterface * const /*vci*/, pkgCacheFile &/*Cache*/,
+void CacheSetHelper::canNotFindCandInstVer(VersionContainerInterface * const /*vci*/, pkgCacheFile &Cache,
pkgCache::PkgIterator const &Pkg) {
- if (ShowError == true)
- _error->Insert(ErrorType, _("Can't select installed nor candidate version from package '%s' as it has neither of them"), Pkg.FullName(true).c_str());
+ canNotGetCandInstVer(Cache, Pkg);
}
/*}}}*/
+ /*}}}*/
+// canNotGetVersion - for package by selector /*{{{*/
+pkgCache::VerIterator CacheSetHelper::canNotGetVersion(enum VerSelector const select, pkgCacheFile &Cache, pkgCache::PkgIterator const &Pkg) {
+ switch (select) {
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+ case NEWEST: return canNotFindNewestVer(Cache, Pkg);
+ case CANDIDATE: return canNotFindCandidateVer(Cache, Pkg);
+ case INSTALLED: return canNotFindInstalledVer(Cache, Pkg);
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic pop
+#endif
+ case CANDINST: return canNotGetCandInstVer(Cache, Pkg);
+ case INSTCAND: return canNotGetInstCandVer(Cache, Pkg);
+ case ALL:
+ case CANDANDINST:
+ case RELEASE:
+ case VERSIONNUMBER:
+ // invalid in this branch
+ return pkgCache::VerIterator(Cache, 0);
+ }
+ return pkgCache::VerIterator(Cache, 0);
+}
// canNotFindNewestVer /*{{{*/
pkgCache::VerIterator CacheSetHelper::canNotFindNewestVer(pkgCacheFile &Cache,
pkgCache::PkgIterator const &Pkg) {
@@ -664,6 +751,42 @@ pkgCache::VerIterator CacheSetHelper::canNotFindInstalledVer(pkgCacheFile &Cache
return pkgCache::VerIterator(Cache, 0);
}
/*}}}*/
+// canNotFindInstCandVer /*{{{*/
+pkgCache::VerIterator CacheSetHelper::canNotGetInstCandVer(pkgCacheFile &Cache,
+ pkgCache::PkgIterator const &Pkg) {
+ if (ShowError == true)
+ _error->Insert(ErrorType, _("Can't select installed nor candidate version from package '%s' as it has neither of them"), Pkg.FullName(true).c_str());
+ return pkgCache::VerIterator(Cache, 0);
+}
+ /*}}}*/
+// canNotFindInstCandVer /*{{{*/
+pkgCache::VerIterator CacheSetHelper::canNotGetCandInstVer(pkgCacheFile &Cache,
+ pkgCache::PkgIterator const &Pkg) {
+ if (ShowError == true)
+ _error->Insert(ErrorType, _("Can't select installed nor candidate version from package '%s' as it has neither of them"), Pkg.FullName(true).c_str());
+ return pkgCache::VerIterator(Cache, 0);
+}
+ /*}}}*/
+ /*}}}*/
+// showPackageSelection - by selector and given pattern /*{{{*/
+APT_CONST void CacheSetHelper::showPackageSelection(pkgCache::PkgIterator const &pkg, enum PkgSelector const select,
+ std::string const &pattern) {
+ switch (select) {
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+ case REGEX: showRegExSelection(pkg, pattern); break;
+ case TASK: showTaskSelection(pkg, pattern); break;
+ case FNMATCH: showFnmatchSelection(pkg, pattern); break;
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic pop
+#endif
+ case PACKAGENAME: /* no suprises here */ break;
+ case STRING: /* handled by the special cases */ break;
+ case UNKNOWN: break;
+ }
+}
// showTaskSelection /*{{{*/
APT_CONST void CacheSetHelper::showTaskSelection(pkgCache::PkgIterator const &/*pkg*/,
std::string const &/*pattern*/) {
@@ -674,14 +797,41 @@ APT_CONST void CacheSetHelper::showRegExSelection(pkgCache::PkgIterator const &/
std::string const &/*pattern*/) {
}
/*}}}*/
-#if (APT_PKG_MAJOR >= 4 && APT_PKG_MINOR >= 13)
// showFnmatchSelection /*{{{*/
-APT_CONST void CacheSetHelper::showFnmatchSelection(pkgCache::PkgIterator const &pkg,
- std::string const &pattern) {
+APT_CONST void CacheSetHelper::showFnmatchSelection(pkgCache::PkgIterator const &/*pkg*/,
+ std::string const &/*pattern*/) {
}
/*}}}*/
+ /*}}}*/
+// showVersionSelection /*{{{*/
+APT_CONST void CacheSetHelper::showVersionSelection(pkgCache::PkgIterator const &Pkg,
+ pkgCache::VerIterator const &Ver, enum VerSelector const select, std::string const &pattern) {
+ switch (select) {
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
-// showSelectedVersion /*{{{*/
+ case RELEASE:
+ showSelectedVersion(Pkg, Ver, pattern, true);
+ break;
+ case VERSIONNUMBER:
+ showSelectedVersion(Pkg, Ver, pattern, false);
+ break;
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic pop
+ #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+ case NEWEST:
+ case CANDIDATE:
+ case INSTALLED:
+ case CANDINST:
+ case INSTCAND:
+ case ALL:
+ case CANDANDINST:
+ // not really suprises, but in fact: just not implemented
+ break;
+ }
+}
APT_CONST void CacheSetHelper::showSelectedVersion(pkgCache::PkgIterator const &/*Pkg*/,
pkgCache::VerIterator const /*Ver*/,
std::string const &/*ver*/,
diff --git a/apt-pkg/cacheset.h b/apt-pkg/cacheset.h
index 16a3daa42..f3f1d1fc6 100644
--- a/apt-pkg/cacheset.h
+++ b/apt-pkg/cacheset.h
@@ -13,8 +13,10 @@
#include <map>
#include <set>
#include <list>
+#include <vector>
#include <string>
#include <iterator>
+#include <algorithm>
#include <stddef.h>
@@ -51,36 +53,127 @@ public: /*{{{*/
ShowError(ShowError), ErrorType(ErrorType) {}
virtual ~CacheSetHelper() {}
- virtual void showTaskSelection(pkgCache::PkgIterator const &pkg, std::string const &pattern);
- virtual void showRegExSelection(pkgCache::PkgIterator const &pkg, std::string const &pattern);
-#if (APT_PKG_MAJOR >= 4 && APT_PKG_MINOR >= 13)
- virtual void showFnmatchSelection(pkgCache::PkgIterator const &pkg, std::string const &pattern);
-#endif
- virtual void showSelectedVersion(pkgCache::PkgIterator const &Pkg, pkgCache::VerIterator const Ver,
- std::string const &ver, bool const verIsRel);
+ enum PkgSelector { UNKNOWN, REGEX, TASK, FNMATCH, PACKAGENAME, STRING };
- virtual void canNotFindTask(PackageContainerInterface * const pci, pkgCacheFile &Cache, std::string pattern);
- virtual void canNotFindRegEx(PackageContainerInterface * const pci, pkgCacheFile &Cache, std::string pattern);
-#if (APT_PKG_MAJOR >= 4 && APT_PKG_MINOR >= 13)
- virtual void canNotFindFnmatch(PackageContainerInterface * const pci, pkgCacheFile &Cache, std::string pattern);
-#endif
- virtual void canNotFindPackage(PackageContainerInterface * const pci, pkgCacheFile &Cache, std::string const &str);
+ virtual bool PackageFrom(enum PkgSelector const select, PackageContainerInterface * const pci, pkgCacheFile &Cache, std::string const &pattern);
+
+ virtual bool PackageFromCommandLine(PackageContainerInterface * const pci, pkgCacheFile &Cache, const char **cmdline);
+
+ struct PkgModifier {
+ enum Position { NONE, PREFIX, POSTFIX };
+ unsigned short ID;
+ const char * const Alias;
+ Position Pos;
+ PkgModifier (unsigned short const &id, const char * const alias, Position const &pos) : ID(id), Alias(alias), Pos(pos) {}
+ };
+ virtual bool PackageFromModifierCommandLine(unsigned short &modID, PackageContainerInterface * const pci,
+ pkgCacheFile &Cache, const char * cmdline,
+ std::list<PkgModifier> const &mods);
+
+ // use PackageFrom(PACKAGENAME, …) instead
+ APT_DEPRECATED pkgCache::PkgIterator PackageFromName(pkgCacheFile &Cache, std::string const &pattern);
+
+ /** \brief be notified about the package being selected via pattern
+ *
+ * Main use is probably to show a message to the user what happened
+ *
+ * \param pkg is the package which was selected
+ * \param select is the selection method which choose the package
+ * \param pattern is the string used by the selection method to pick the package
+ */
+ virtual void showPackageSelection(pkgCache::PkgIterator const &pkg, PkgSelector const select, std::string const &pattern);
+ // use the method above instead, react only on the type you need and let the base handle the rest if need be
+ // this allows use to add new selection methods without breaking the ABI constantly with new virtual methods
+ APT_DEPRECATED virtual void showTaskSelection(pkgCache::PkgIterator const &pkg, std::string const &pattern);
+ APT_DEPRECATED virtual void showRegExSelection(pkgCache::PkgIterator const &pkg, std::string const &pattern);
+ APT_DEPRECATED virtual void showFnmatchSelection(pkgCache::PkgIterator const &pkg, std::string const &pattern);
+
+ /** \brief be notified if a package can't be found via pattern
+ *
+ * Can be used to show a message as well as to try something else to make it match
+ *
+ * \param select is the method tried for selection
+ * \param pci is the container the package should be inserted in
+ * \param Cache is the package universe available
+ * \param pattern is the string not matching anything
+ */
+ virtual void canNotFindPackage(enum PkgSelector const select, PackageContainerInterface * const pci, pkgCacheFile &Cache, std::string const &pattern);
+ // same as above for showPackageSelection
+ APT_DEPRECATED virtual void canNotFindTask(PackageContainerInterface * const pci, pkgCacheFile &Cache, std::string pattern);
+ APT_DEPRECATED virtual void canNotFindRegEx(PackageContainerInterface * const pci, pkgCacheFile &Cache, std::string pattern);
+ APT_DEPRECATED virtual void canNotFindFnmatch(PackageContainerInterface * const pci, pkgCacheFile &Cache, std::string pattern);
+ APT_DEPRECATED virtual void canNotFindPackage(PackageContainerInterface * const pci, pkgCacheFile &Cache, std::string const &str);
+
+ /** \brief specifies which version(s) we want to refer to */
+ enum VerSelector {
+ /** by release string */
+ RELEASE,
+ /** by version number string */
+ VERSIONNUMBER,
+ /** All versions */
+ ALL,
+ /** Candidate and installed version */
+ CANDANDINST,
+ /** Candidate version */
+ CANDIDATE,
+ /** Installed version */
+ INSTALLED,
+ /** Candidate or if non installed version */
+ CANDINST,
+ /** Installed or if non candidate version */
+ INSTCAND,
+ /** Newest version */
+ NEWEST
+ };
+
+ /** \brief be notified about the version being selected via pattern
+ *
+ * Main use is probably to show a message to the user what happened
+ * Note that at the moment this method is only called for RELEASE
+ * and VERSION selections, not for the others.
+ *
+ * \param Pkg is the package which was selected for
+ * \param Ver is the version selected
+ * \param select is the selection method which choose the version
+ * \param pattern is the string used by the selection method to pick the version
+ */
+ virtual void showVersionSelection(pkgCache::PkgIterator const &Pkg, pkgCache::VerIterator const &Ver,
+ enum VerSelector const select, std::string const &pattern);
+ // renamed to have a similar interface to showPackageSelection
+ APT_DEPRECATED virtual void showSelectedVersion(pkgCache::PkgIterator const &Pkg, pkgCache::VerIterator const Ver,
+ std::string const &ver, bool const verIsRel);
- virtual void canNotFindAllVer(VersionContainerInterface * const vci, pkgCacheFile &Cache, pkgCache::PkgIterator const &Pkg);
- virtual void canNotFindInstCandVer(VersionContainerInterface * const vci, pkgCacheFile &Cache,
+ /** \brief be notified if a version can't be found for a package
+ *
+ * Main use is probably to show a message to the user what happened
+ *
+ * \param select is the method tried for selection
+ * \param vci is the container the version should be inserted in
+ * \param Cache is the package universe available
+ * \param Pkg is the package we wanted a version from
+ */
+ virtual void canNotFindVersion(enum VerSelector const select, VersionContainerInterface * const vci, pkgCacheFile &Cache, pkgCache::PkgIterator const &Pkg);
+ // same as above for showPackageSelection
+ APT_DEPRECATED virtual void canNotFindAllVer(VersionContainerInterface * const vci, pkgCacheFile &Cache, pkgCache::PkgIterator const &Pkg);
+ APT_DEPRECATED virtual void canNotFindInstCandVer(VersionContainerInterface * const vci, pkgCacheFile &Cache,
pkgCache::PkgIterator const &Pkg);
- virtual void canNotFindCandInstVer(VersionContainerInterface * const vci,
+ APT_DEPRECATED virtual void canNotFindCandInstVer(VersionContainerInterface * const vci,
pkgCacheFile &Cache,
pkgCache::PkgIterator const &Pkg);
- virtual pkgCache::PkgIterator canNotFindPkgName(pkgCacheFile &Cache, std::string const &str);
- virtual pkgCache::VerIterator canNotFindNewestVer(pkgCacheFile &Cache,
+ // the difference between canNotFind and canNotGet is that the later is more low-level
+ // and called from other places: In this case looking into the code is the only real answer…
+ virtual pkgCache::VerIterator canNotGetVersion(enum VerSelector const select, pkgCacheFile &Cache, pkgCache::PkgIterator const &Pkg);
+ // same as above for showPackageSelection
+ APT_DEPRECATED virtual pkgCache::VerIterator canNotFindNewestVer(pkgCacheFile &Cache,
pkgCache::PkgIterator const &Pkg);
- virtual pkgCache::VerIterator canNotFindCandidateVer(pkgCacheFile &Cache,
+ APT_DEPRECATED virtual pkgCache::VerIterator canNotFindCandidateVer(pkgCacheFile &Cache,
pkgCache::PkgIterator const &Pkg);
- virtual pkgCache::VerIterator canNotFindInstalledVer(pkgCacheFile &Cache,
+ APT_DEPRECATED virtual pkgCache::VerIterator canNotFindInstalledVer(pkgCacheFile &Cache,
pkgCache::PkgIterator const &Pkg);
+ virtual pkgCache::PkgIterator canNotFindPkgName(pkgCacheFile &Cache, std::string const &str);
+
bool showErrors() const { return ShowError; }
bool showErrors(bool const newValue) { if (ShowError == newValue) return ShowError; else return ((ShowError = newValue) == false); }
GlobalError::MsgType errorType() const { return ErrorType; }
@@ -98,7 +191,19 @@ public: /*{{{*/
protected:
bool ShowError;
GlobalError::MsgType ErrorType;
+
+ pkgCache::VerIterator canNotGetInstCandVer(pkgCacheFile &Cache,
+ pkgCache::PkgIterator const &Pkg);
+ pkgCache::VerIterator canNotGetCandInstVer(pkgCacheFile &Cache,
+ pkgCache::PkgIterator const &Pkg);
+
+ bool PackageFromTask(PackageContainerInterface * const pci, pkgCacheFile &Cache, std::string pattern);
+ bool PackageFromRegEx(PackageContainerInterface * const pci, pkgCacheFile &Cache, std::string pattern);
+ bool PackageFromFnmatch(PackageContainerInterface * const pci, pkgCacheFile &Cache, std::string pattern);
+ bool PackageFromPackageName(PackageContainerInterface * const pci, pkgCacheFile &Cache, std::string pattern);
+ bool PackageFromString(PackageContainerInterface * const pci, pkgCacheFile &Cache, std::string const &pattern);
}; /*}}}*/
+
class PackageContainerInterface { /*{{{*/
/** \class PackageContainerInterface
@@ -118,7 +223,16 @@ public:
inline const char *Name() const {return getPkg().Name(); }
inline std::string FullName(bool const Pretty) const { return getPkg().FullName(Pretty); }
inline std::string FullName() const { return getPkg().FullName(); }
- inline const char *Section() const {return getPkg().Section(); }
+ APT_DEPRECATED inline const char *Section() const {
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+ return getPkg().Section();
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic pop
+#endif
+ }
inline bool Purge() const {return getPkg().Purge(); }
inline const char *Arch() const {return getPkg().Arch(); }
inline pkgCache::GrpIterator Group() const { return getPkg().Group(); }
@@ -142,29 +256,56 @@ public:
virtual bool empty() const = 0;
virtual void clear() = 0;
- enum Constructor { UNKNOWN, REGEX, TASK, FNMATCH };
- virtual void setConstructor(Constructor const &con) = 0;
- virtual Constructor getConstructor() const = 0;
-
- static bool FromTask(PackageContainerInterface * const pci, pkgCacheFile &Cache, std::string pattern, CacheSetHelper &helper);
- static bool FromRegEx(PackageContainerInterface * const pci, pkgCacheFile &Cache, std::string pattern, CacheSetHelper &helper);
- static pkgCache::PkgIterator FromName(pkgCacheFile &Cache, std::string const &pattern, CacheSetHelper &helper);
- static bool FromFnmatch(PackageContainerInterface * const pci, pkgCacheFile &Cache, std::string pattern, CacheSetHelper &helper);
- static bool FromGroup(PackageContainerInterface * const pci, pkgCacheFile &Cache, std::string pattern, CacheSetHelper &helper);
- static bool FromString(PackageContainerInterface * const pci, pkgCacheFile &Cache, std::string const &pattern, CacheSetHelper &helper);
- static bool FromCommandLine(PackageContainerInterface * const pci, pkgCacheFile &Cache, const char **cmdline, CacheSetHelper &helper);
+ // FIXME: This is a bloody hack removed soon. Use CacheSetHelper::PkgSelector !
+ enum APT_DEPRECATED Constructor { UNKNOWN = CacheSetHelper::UNKNOWN,
+ REGEX = CacheSetHelper::REGEX,
+ TASK = CacheSetHelper::TASK,
+ FNMATCH = CacheSetHelper::FNMATCH };
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+ void setConstructor(Constructor const by) { ConstructedBy = (CacheSetHelper::PkgSelector)by; }
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic pop
+#endif
- struct Modifier {
- enum Position { NONE, PREFIX, POSTFIX };
- unsigned short ID;
- const char * const Alias;
- Position Pos;
- Modifier (unsigned short const &id, const char * const alias, Position const &pos) : ID(id), Alias(alias), Pos(pos) {}
- };
+ void setConstructor(CacheSetHelper::PkgSelector const by) { ConstructedBy = by; }
+ CacheSetHelper::PkgSelector getConstructor() const { return ConstructedBy; }
+ PackageContainerInterface() : ConstructedBy(CacheSetHelper::UNKNOWN) {}
+ PackageContainerInterface(CacheSetHelper::PkgSelector const by) : ConstructedBy(by) {}
+
+ APT_DEPRECATED static bool FromTask(PackageContainerInterface * const pci, pkgCacheFile &Cache, std::string pattern, CacheSetHelper &helper) {
+ return helper.PackageFrom(CacheSetHelper::TASK, pci, Cache, pattern); }
+ APT_DEPRECATED static bool FromRegEx(PackageContainerInterface * const pci, pkgCacheFile &Cache, std::string pattern, CacheSetHelper &helper) {
+ return helper.PackageFrom(CacheSetHelper::REGEX, pci, Cache, pattern); }
+ APT_DEPRECATED static bool FromFnmatch(PackageContainerInterface * const pci, pkgCacheFile &Cache, std::string pattern, CacheSetHelper &helper) {
+ return helper.PackageFrom(CacheSetHelper::FNMATCH, pci, Cache, pattern); }
+ APT_DEPRECATED static bool FromGroup(PackageContainerInterface * const pci, pkgCacheFile &Cache, std::string pattern, CacheSetHelper &helper) {
+ return helper.PackageFrom(CacheSetHelper::PACKAGENAME, pci, Cache, pattern); }
+ APT_DEPRECATED static bool FromString(PackageContainerInterface * const pci, pkgCacheFile &Cache, std::string const &pattern, CacheSetHelper &helper) {
+ return helper.PackageFrom(CacheSetHelper::STRING, pci, Cache, pattern); }
+ APT_DEPRECATED static bool FromCommandLine(PackageContainerInterface * const pci, pkgCacheFile &Cache, const char **cmdline, CacheSetHelper &helper) {
+ return helper.PackageFromCommandLine(pci, Cache, cmdline); }
+
+ APT_DEPRECATED typedef CacheSetHelper::PkgModifier Modifier;
+
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+ APT_DEPRECATED static pkgCache::PkgIterator FromName(pkgCacheFile &Cache, std::string const &pattern, CacheSetHelper &helper) {
+ return helper.PackageFromName(Cache, pattern); }
+ APT_DEPRECATED static bool FromModifierCommandLine(unsigned short &modID, PackageContainerInterface * const pci,
+ pkgCacheFile &Cache, const char * cmdline,
+ std::list<Modifier> const &mods, CacheSetHelper &helper) {
+ return helper.PackageFromModifierCommandLine(modID, pci, Cache, cmdline, mods); }
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic pop
+#endif
- static bool FromModifierCommandLine(unsigned short &modID, PackageContainerInterface * const pci,
- pkgCacheFile &Cache, const char * cmdline,
- std::list<Modifier> const &mods, CacheSetHelper &helper);
+private:
+ CacheSetHelper::PkgSelector ConstructedBy;
};
/*}}}*/
template<class Container> class PackageContainer : public PackageContainerInterface {/*{{{*/
@@ -228,11 +369,28 @@ public: /*{{{*/
iterator end() { return iterator(_cont.end()); }
const_iterator find(pkgCache::PkgIterator const &P) const { return const_iterator(_cont.find(P)); }
- void setConstructor(Constructor const &by) { ConstructedBy = by; }
- Constructor getConstructor() const { return ConstructedBy; }
+ PackageContainer() : PackageContainerInterface() {}
+ PackageContainer(CacheSetHelper::PkgSelector const &by) : PackageContainerInterface(by) {}
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+ APT_DEPRECATED PackageContainer(Constructor const &by) : PackageContainerInterface((CacheSetHelper::PkgSelector)by) {}
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic pop
+#endif
+
+ /** \brief sort all included versions with given comparer
- PackageContainer() : ConstructedBy(UNKNOWN) {}
- PackageContainer(Constructor const &by) : ConstructedBy(by) {}
+ Some containers are sorted by default, some are not and can't be,
+ but a few like std::vector can be sorted if need be, so this can be
+ specialized in later on. The default is that this will fail though.
+ Specifically, already sorted containers like std::set will return
+ false as well as there is no easy way to check that the given comparer
+ would sort in the same way the set is currently sorted
+
+ \return \b true if the set was sorted, \b false if not. */
+ template<class Compare> bool sort(Compare /*Comp*/) { return false; }
/** \brief returns all packages in the cache who belong to the given task
@@ -243,8 +401,8 @@ public: /*{{{*/
\param pattern name of the task
\param helper responsible for error and message handling */
static PackageContainer FromTask(pkgCacheFile &Cache, std::string const &pattern, CacheSetHelper &helper) {
- PackageContainer cont(TASK);
- PackageContainerInterface::FromTask(&cont, Cache, pattern, helper);
+ PackageContainer cont(CacheSetHelper::TASK);
+ helper.PackageFrom(CacheSetHelper::TASK, &cont, Cache, pattern);
return cont;
}
static PackageContainer FromTask(pkgCacheFile &Cache, std::string const &pattern) {
@@ -260,9 +418,9 @@ public: /*{{{*/
\param Cache the packages are in
\param pattern regular expression for package names
\param helper responsible for error and message handling */
- static PackageContainer FromRegEx(pkgCacheFile &Cache, std::string pattern, CacheSetHelper &helper) {
- PackageContainer cont(REGEX);
- PackageContainerInterface::FromRegEx(&cont, Cache, pattern, helper);
+ static PackageContainer FromRegEx(pkgCacheFile &Cache, std::string const &pattern, CacheSetHelper &helper) {
+ PackageContainer cont(CacheSetHelper::REGEX);
+ helper.PackageFrom(CacheSetHelper::REGEX, &cont, Cache, pattern);
return cont;
}
@@ -271,9 +429,9 @@ public: /*{{{*/
return FromRegEx(Cache, pattern, helper);
}
- static PackageContainer FromFnmatch(pkgCacheFile &Cache, std::string pattern, CacheSetHelper &helper) {
- PackageContainer cont(FNMATCH);
- PackageContainerInterface::FromFnmatch(&cont, Cache, pattern, helper);
+ static PackageContainer FromFnmatch(pkgCacheFile &Cache, std::string const &pattern, CacheSetHelper &helper) {
+ PackageContainer cont(CacheSetHelper::FNMATCH);
+ helper.PackageFrom(CacheSetHelper::FNMATCH, &cont, Cache, pattern);
return cont;
}
static PackageContainer FromFnMatch(pkgCacheFile &Cache, std::string const &pattern) {
@@ -281,18 +439,25 @@ public: /*{{{*/
return FromFnmatch(Cache, pattern, helper);
}
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
/** \brief returns a package specified by a string
\param Cache the package is in
\param pattern String the package name should be extracted from
\param helper responsible for error and message handling */
- static pkgCache::PkgIterator FromName(pkgCacheFile &Cache, std::string const &pattern, CacheSetHelper &helper) {
- return PackageContainerInterface::FromName(Cache, pattern, helper);
+ APT_DEPRECATED static pkgCache::PkgIterator FromName(pkgCacheFile &Cache, std::string const &pattern, CacheSetHelper &helper) {
+ return helper.PackageFromName(Cache, pattern);
}
- static pkgCache::PkgIterator FromName(pkgCacheFile &Cache, std::string const &pattern) {
+ APT_DEPRECATED static pkgCache::PkgIterator FromName(pkgCacheFile &Cache, std::string const &pattern) {
CacheSetHelper helper;
- return PackageContainerInterface::FromName(Cache, pattern, helper);
+ return FromName(Cache, pattern, helper);
}
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic pop
+#endif
/** \brief returns all packages specified by a string
@@ -301,7 +466,7 @@ public: /*{{{*/
\param helper responsible for error and message handling */
static PackageContainer FromString(pkgCacheFile &Cache, std::string const &pattern, CacheSetHelper &helper) {
PackageContainer cont;
- PackageContainerInterface::FromString(&cont, Cache, pattern, helper);
+ helper.PackageFrom(CacheSetHelper::PACKAGENAME, &cont, Cache, pattern);
return cont;
}
static PackageContainer FromString(pkgCacheFile &Cache, std::string const &pattern) {
@@ -318,7 +483,7 @@ public: /*{{{*/
\param helper responsible for error and message handling */
static PackageContainer FromCommandLine(pkgCacheFile &Cache, const char **cmdline, CacheSetHelper &helper) {
PackageContainer cont;
- PackageContainerInterface::FromCommandLine(&cont, Cache, cmdline, helper);
+ helper.PackageFromCommandLine(&cont, Cache, cmdline);
return cont;
}
static PackageContainer FromCommandLine(pkgCacheFile &Cache, const char **cmdline) {
@@ -340,14 +505,14 @@ public: /*{{{*/
static std::map<unsigned short, PackageContainer> GroupedFromCommandLine(
pkgCacheFile &Cache,
const char **cmdline,
- std::list<Modifier> const &mods,
+ std::list<CacheSetHelper::PkgModifier> const &mods,
unsigned short const &fallback,
CacheSetHelper &helper) {
std::map<unsigned short, PackageContainer> pkgsets;
for (const char **I = cmdline; *I != 0; ++I) {
unsigned short modID = fallback;
PackageContainer pkgset;
- PackageContainerInterface::FromModifierCommandLine(modID, &pkgset, Cache, *I, mods, helper);
+ helper.PackageFromModifierCommandLine(modID, &pkgset, Cache, *I, mods);
pkgsets[modID].insert(pkgset);
}
return pkgsets;
@@ -355,22 +520,23 @@ public: /*{{{*/
static std::map<unsigned short, PackageContainer> GroupedFromCommandLine(
pkgCacheFile &Cache,
const char **cmdline,
- std::list<Modifier> const &mods,
+ std::list<CacheSetHelper::PkgModifier> const &mods,
unsigned short const &fallback) {
CacheSetHelper helper;
return GroupedFromCommandLine(Cache, cmdline,
mods, fallback, helper);
}
/*}}}*/
-private: /*{{{*/
- Constructor ConstructedBy;
- /*}}}*/
}; /*}}}*/
-
+// specialisations for push_back containers: std::list & std::vector /*{{{*/
template<> template<class Cont> void PackageContainer<std::list<pkgCache::PkgIterator> >::insert(PackageContainer<Cont> const &pkgcont) {
for (typename PackageContainer<Cont>::const_iterator p = pkgcont.begin(); p != pkgcont.end(); ++p)
_cont.push_back(*p);
}
+template<> template<class Cont> void PackageContainer<std::vector<pkgCache::PkgIterator> >::insert(PackageContainer<Cont> const &pkgcont) {
+ for (typename PackageContainer<Cont>::const_iterator p = pkgcont.begin(); p != pkgcont.end(); ++p)
+ _cont.push_back(*p);
+}
// these two are 'inline' as otherwise the linker has problems with seeing these untemplated
// specializations again and again - but we need to see them, so that library users can use them
template<> inline bool PackageContainer<std::list<pkgCache::PkgIterator> >::insert(pkgCache::PkgIterator const &P) {
@@ -379,12 +545,65 @@ template<> inline bool PackageContainer<std::list<pkgCache::PkgIterator> >::inse
_cont.push_back(P);
return true;
}
+template<> inline bool PackageContainer<std::vector<pkgCache::PkgIterator> >::insert(pkgCache::PkgIterator const &P) {
+ if (P.end() == true)
+ return false;
+ _cont.push_back(P);
+ return true;
+}
template<> inline void PackageContainer<std::list<pkgCache::PkgIterator> >::insert(const_iterator begin, const_iterator end) {
for (const_iterator p = begin; p != end; ++p)
_cont.push_back(*p);
}
+template<> inline void PackageContainer<std::vector<pkgCache::PkgIterator> >::insert(const_iterator begin, const_iterator end) {
+ for (const_iterator p = begin; p != end; ++p)
+ _cont.push_back(*p);
+}
+ /*}}}*/
+
+template<> template<class Compare> inline bool PackageContainer<std::vector<pkgCache::PkgIterator> >::sort(Compare Comp) {
+ std::sort(_cont.begin(), _cont.end(), Comp);
+ return true;
+}
+
+// class PackageUniverse - pkgCache as PackageContainerInterface /*{{{*/
+/** \class PackageUniverse
+
+ Wraps around our usual pkgCache, so that it can be stuffed into methods
+ expecting a PackageContainer.
+
+ The wrapping is read-only in practice modeled by making erase and co
+ private methods. */
+class APT_HIDDEN PackageUniverse : public PackageContainerInterface {
+ pkgCache * const _cont;
+public:
+ typedef pkgCache::PkgIterator iterator;
+ typedef pkgCache::PkgIterator const_iterator;
+
+ APT_PUBLIC bool empty() const { return false; }
+ APT_PUBLIC size_t size() const { return _cont->Head().PackageCount; }
+
+ APT_PUBLIC const_iterator begin() const { return _cont->PkgBegin(); }
+ APT_PUBLIC const_iterator end() const { return _cont->PkgEnd(); }
+ APT_PUBLIC iterator begin() { return _cont->PkgBegin(); }
+ APT_PUBLIC iterator end() { return _cont->PkgEnd(); }
+
+ APT_PUBLIC PackageUniverse(pkgCache * const Owner) : _cont(Owner) { }
+
+private:
+ bool insert(pkgCache::PkgIterator const &) { return true; }
+ template<class Cont> void insert(PackageContainer<Cont> const &) { }
+ void insert(const_iterator, const_iterator) { }
+
+ void clear() { }
+ iterator& erase(iterator &iter) { return iter; }
+ size_t erase(const pkgCache::PkgIterator) { return 0; }
+ void erase(iterator, iterator) { }
+};
+ /*}}}*/
typedef PackageContainer<std::set<pkgCache::PkgIterator> > PackageSet;
typedef PackageContainer<std::list<pkgCache::PkgIterator> > PackageList;
+typedef PackageContainer<std::vector<pkgCache::PkgIterator> > PackageVector;
class VersionContainerInterface { /*{{{*/
/** \class APT::VersionContainerInterface
@@ -426,45 +645,83 @@ public:
virtual void clear() = 0;
/** \brief specifies which version(s) will be returned if non is given */
- enum Version {
- /** All versions */
- ALL,
- /** Candidate and installed version */
- CANDANDINST,
- /** Candidate version */
- CANDIDATE,
- /** Installed version */
- INSTALLED,
- /** Candidate or if non installed version */
- CANDINST,
- /** Installed or if non candidate version */
- INSTCAND,
- /** Newest version */
- NEWEST
+ enum APT_DEPRECATED Version {
+ ALL = CacheSetHelper::ALL,
+ CANDANDINST = CacheSetHelper::CANDANDINST,
+ CANDIDATE = CacheSetHelper::CANDIDATE,
+ INSTALLED = CacheSetHelper::INSTALLED,
+ CANDINST = CacheSetHelper::CANDINST,
+ INSTCAND = CacheSetHelper::INSTCAND,
+ NEWEST = CacheSetHelper::NEWEST
};
struct Modifier {
- enum Position { NONE, PREFIX, POSTFIX };
- unsigned short ID;
+ unsigned short const ID;
const char * const Alias;
- Position Pos;
- Version SelectVersion;
+ enum Position { NONE, PREFIX, POSTFIX } const Pos;
+ enum CacheSetHelper::VerSelector const SelectVersion;
Modifier (unsigned short const &id, const char * const alias, Position const &pos,
- Version const &select) : ID(id), Alias(alias), Pos(pos),
+ enum CacheSetHelper::VerSelector const select) : ID(id), Alias(alias), Pos(pos),
SelectVersion(select) {}
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+ APT_DEPRECATED Modifier(unsigned short const &id, const char * const alias, Position const &pos,
+ Version const &select) : ID(id), Alias(alias), Pos(pos),
+ SelectVersion((CacheSetHelper::VerSelector)select) {}
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic pop
+#endif
};
static bool FromCommandLine(VersionContainerInterface * const vci, pkgCacheFile &Cache,
- const char **cmdline, Version const &fallback,
+ const char **cmdline, CacheSetHelper::VerSelector const fallback,
CacheSetHelper &helper);
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+ APT_DEPRECATED static bool FromCommandLine(VersionContainerInterface * const vci, pkgCacheFile &Cache,
+ const char **cmdline, Version const &fallback,
+ CacheSetHelper &helper) {
+ return FromCommandLine(vci, Cache, cmdline, (CacheSetHelper::VerSelector)fallback, helper);
+ }
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic pop
+#endif
static bool FromString(VersionContainerInterface * const vci, pkgCacheFile &Cache,
- std::string pkg, Version const &fallback, CacheSetHelper &helper,
+ std::string pkg, CacheSetHelper::VerSelector const fallback, CacheSetHelper &helper,
bool const onlyFromName = false);
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+ APT_DEPRECATED static bool FromString(VersionContainerInterface * const vci, pkgCacheFile &Cache,
+ std::string pkg, Version const &fallback, CacheSetHelper &helper,
+ bool const onlyFromName = false) {
+ return FromString(vci, Cache, pkg, (CacheSetHelper::VerSelector)fallback, helper, onlyFromName);
+ }
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic pop
+#endif
static bool FromPackage(VersionContainerInterface * const vci, pkgCacheFile &Cache,
- pkgCache::PkgIterator const &P, Version const &fallback,
+ pkgCache::PkgIterator const &P, CacheSetHelper::VerSelector const fallback,
CacheSetHelper &helper);
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+ APT_DEPRECATED static bool FromPackage(VersionContainerInterface * const vci, pkgCacheFile &Cache,
+ pkgCache::PkgIterator const &P, Version const &fallback,
+ CacheSetHelper &helper) {
+ return FromPackage(vci, Cache, P, (CacheSetHelper::VerSelector)fallback, helper);
+ }
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic pop
+#endif
static bool FromModifierCommandLine(unsigned short &modID,
VersionContainerInterface * const vci,
@@ -476,8 +733,22 @@ public:
static bool FromDependency(VersionContainerInterface * const vci,
pkgCacheFile &Cache,
pkgCache::DepIterator const &D,
- Version const &selector,
+ CacheSetHelper::VerSelector const selector,
CacheSetHelper &helper);
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+ APT_DEPRECATED static bool FromDependency(VersionContainerInterface * const vci,
+ pkgCacheFile &Cache,
+ pkgCache::DepIterator const &D,
+ Version const &selector,
+ CacheSetHelper &helper) {
+ return FromDependency(vci, Cache, D, (CacheSetHelper::VerSelector)selector, helper);
+ }
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic pop
+#endif
protected: /*{{{*/
@@ -559,6 +830,18 @@ public: /*{{{*/
iterator end() { return iterator(_cont.end()); }
const_iterator find(pkgCache::VerIterator const &V) const { return const_iterator(_cont.find(V)); }
+ /** \brief sort all included versions with given comparer
+
+ Some containers are sorted by default, some are not and can't be,
+ but a few like std::vector can be sorted if need be, so this can be
+ specialized in later on. The default is that this will fail though.
+ Specifically, already sorted containers like std::set will return
+ false as well as there is no easy way to check that the given comparer
+ would sort in the same way the set is currently sorted
+
+ \return \b true if the set was sorted, \b false if not. */
+ template<class Compare> bool sort(Compare /*Comp*/) { return false; }
+
/** \brief returns all versions specified on the commandline
Get all versions from the commandline, uses given default version if
@@ -568,35 +851,64 @@ public: /*{{{*/
\param fallback version specification
\param helper responsible for error and message handling */
static VersionContainer FromCommandLine(pkgCacheFile &Cache, const char **cmdline,
- Version const &fallback, CacheSetHelper &helper) {
+ CacheSetHelper::VerSelector const fallback, CacheSetHelper &helper) {
VersionContainer vercon;
VersionContainerInterface::FromCommandLine(&vercon, Cache, cmdline, fallback, helper);
return vercon;
}
static VersionContainer FromCommandLine(pkgCacheFile &Cache, const char **cmdline,
- Version const &fallback) {
+ CacheSetHelper::VerSelector const fallback) {
CacheSetHelper helper;
return FromCommandLine(Cache, cmdline, fallback, helper);
}
static VersionContainer FromCommandLine(pkgCacheFile &Cache, const char **cmdline) {
- return FromCommandLine(Cache, cmdline, CANDINST);
+ return FromCommandLine(Cache, cmdline, CacheSetHelper::CANDINST);
}
-
static VersionContainer FromString(pkgCacheFile &Cache, std::string const &pkg,
- Version const &fallback, CacheSetHelper &helper,
- bool const onlyFromName = false) {
+ CacheSetHelper::VerSelector const fallback, CacheSetHelper &helper,
+ bool const /*onlyFromName = false*/) {
VersionContainer vercon;
VersionContainerInterface::FromString(&vercon, Cache, pkg, fallback, helper);
return vercon;
}
static VersionContainer FromString(pkgCacheFile &Cache, std::string pkg,
- Version const &fallback) {
+ CacheSetHelper::VerSelector const fallback) {
CacheSetHelper helper;
return FromString(Cache, pkg, fallback, helper);
}
static VersionContainer FromString(pkgCacheFile &Cache, std::string pkg) {
- return FromString(Cache, pkg, CANDINST);
+ return FromString(Cache, pkg, CacheSetHelper::CANDINST);
}
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+ static VersionContainer FromCommandLine(pkgCacheFile &Cache, const char **cmdline,
+ Version const &fallback, CacheSetHelper &helper) {
+ VersionContainer vercon;
+ VersionContainerInterface::FromCommandLine(&vercon, Cache, cmdline, (CacheSetHelper::VerSelector)fallback, helper);
+ return vercon;
+ }
+ static VersionContainer FromCommandLine(pkgCacheFile &Cache, const char **cmdline,
+ Version const &fallback) {
+ CacheSetHelper helper;
+ return FromCommandLine(Cache, cmdline, (CacheSetHelper::VerSelector)fallback, helper);
+ }
+ static VersionContainer FromString(pkgCacheFile &Cache, std::string const &pkg,
+ Version const &fallback, CacheSetHelper &helper,
+ bool const /*onlyFromName = false*/) {
+ VersionContainer vercon;
+ VersionContainerInterface::FromString(&vercon, Cache, pkg, (CacheSetHelper::VerSelector)fallback, helper);
+ return vercon;
+ }
+ static VersionContainer FromString(pkgCacheFile &Cache, std::string pkg,
+ Version const &fallback) {
+ CacheSetHelper helper;
+ return FromString(Cache, pkg, (CacheSetHelper::VerSelector)fallback, helper);
+ }
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic pop
+#endif
/** \brief returns all versions specified for the package
@@ -605,18 +917,36 @@ public: /*{{{*/
\param fallback the version(s) you want to get
\param helper the helper used for display and error handling */
static VersionContainer FromPackage(pkgCacheFile &Cache, pkgCache::PkgIterator const &P,
- Version const &fallback, CacheSetHelper &helper) {
+ CacheSetHelper::VerSelector const fallback, CacheSetHelper &helper) {
VersionContainer vercon;
VersionContainerInterface::FromPackage(&vercon, Cache, P, fallback, helper);
return vercon;
}
static VersionContainer FromPackage(pkgCacheFile &Cache, pkgCache::PkgIterator const &P,
- Version const &fallback) {
+ CacheSetHelper::VerSelector const fallback) {
CacheSetHelper helper;
return FromPackage(Cache, P, fallback, helper);
}
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+ static VersionContainer FromPackage(pkgCacheFile &Cache, pkgCache::PkgIterator const &P,
+ Version const &fallback, CacheSetHelper &helper) {
+ VersionContainer vercon;
+ VersionContainerInterface::FromPackage(&vercon, Cache, P, (CacheSetHelper::VerSelector)fallback, helper);
+ return vercon;
+ }
+ static VersionContainer FromPackage(pkgCacheFile &Cache, pkgCache::PkgIterator const &P,
+ Version const &fallback) {
+ CacheSetHelper helper;
+ return FromPackage(Cache, P, (CacheSetHelper::VerSelector)fallback, helper);
+ }
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic pop
+#endif
static VersionContainer FromPackage(pkgCacheFile &Cache, pkgCache::PkgIterator const &P) {
- return FromPackage(Cache, P, CANDIDATE);
+ return FromPackage(Cache, P, CacheSetHelper::CANDIDATE);
}
static std::map<unsigned short, VersionContainer> GroupedFromCommandLine(
@@ -645,26 +975,48 @@ public: /*{{{*/
}
static VersionContainer FromDependency(pkgCacheFile &Cache, pkgCache::DepIterator const &D,
- Version const &selector, CacheSetHelper &helper) {
+ CacheSetHelper::VerSelector const selector, CacheSetHelper &helper) {
VersionContainer vercon;
VersionContainerInterface::FromDependency(&vercon, Cache, D, selector, helper);
return vercon;
}
static VersionContainer FromDependency(pkgCacheFile &Cache, pkgCache::DepIterator const &D,
- Version const &selector) {
+ CacheSetHelper::VerSelector const selector) {
CacheSetHelper helper;
return FromPackage(Cache, D, selector, helper);
}
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+ static VersionContainer FromDependency(pkgCacheFile &Cache, pkgCache::DepIterator const &D,
+ Version const &selector, CacheSetHelper &helper) {
+ VersionContainer vercon;
+ VersionContainerInterface::FromDependency(&vercon, Cache, D, (CacheSetHelper::VerSelector)selector, helper);
+ return vercon;
+ }
+ static VersionContainer FromDependency(pkgCacheFile &Cache, pkgCache::DepIterator const &D,
+ Version const &selector) {
+ CacheSetHelper helper;
+ return FromPackage(Cache, D, (CacheSetHelper::VerSelector)selector, helper);
+ }
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic pop
+#endif
static VersionContainer FromDependency(pkgCacheFile &Cache, pkgCache::DepIterator const &D) {
- return FromPackage(Cache, D, CANDIDATE);
+ return FromPackage(Cache, D, CacheSetHelper::CANDIDATE);
}
/*}}}*/
}; /*}}}*/
-
+// specialisations for push_back containers: std::list & std::vector /*{{{*/
template<> template<class Cont> void VersionContainer<std::list<pkgCache::VerIterator> >::insert(VersionContainer<Cont> const &vercont) {
for (typename VersionContainer<Cont>::const_iterator v = vercont.begin(); v != vercont.end(); ++v)
_cont.push_back(*v);
}
+template<> template<class Cont> void VersionContainer<std::vector<pkgCache::VerIterator> >::insert(VersionContainer<Cont> const &vercont) {
+ for (typename VersionContainer<Cont>::const_iterator v = vercont.begin(); v != vercont.end(); ++v)
+ _cont.push_back(*v);
+}
// these two are 'inline' as otherwise the linker has problems with seeing these untemplated
// specializations again and again - but we need to see them, so that library users can use them
template<> inline bool VersionContainer<std::list<pkgCache::VerIterator> >::insert(pkgCache::VerIterator const &V) {
@@ -673,11 +1025,29 @@ template<> inline bool VersionContainer<std::list<pkgCache::VerIterator> >::inse
_cont.push_back(V);
return true;
}
+template<> inline bool VersionContainer<std::vector<pkgCache::VerIterator> >::insert(pkgCache::VerIterator const &V) {
+ if (V.end() == true)
+ return false;
+ _cont.push_back(V);
+ return true;
+}
template<> inline void VersionContainer<std::list<pkgCache::VerIterator> >::insert(const_iterator begin, const_iterator end) {
for (const_iterator v = begin; v != end; ++v)
_cont.push_back(*v);
}
+template<> inline void VersionContainer<std::vector<pkgCache::VerIterator> >::insert(const_iterator begin, const_iterator end) {
+ for (const_iterator v = begin; v != end; ++v)
+ _cont.push_back(*v);
+}
+ /*}}}*/
+
+template<> template<class Compare> inline bool VersionContainer<std::vector<pkgCache::VerIterator> >::sort(Compare Comp) {
+ std::sort(_cont.begin(), _cont.end(), Comp);
+ return true;
+}
+
typedef VersionContainer<std::set<pkgCache::VerIterator> > VersionSet;
typedef VersionContainer<std::list<pkgCache::VerIterator> > VersionList;
+typedef VersionContainer<std::vector<pkgCache::VerIterator> > VersionVector;
}
#endif
diff --git a/apt-pkg/cdrom.cc b/apt-pkg/cdrom.cc
index a5ad6a9ff..b97f7b036 100644
--- a/apt-pkg/cdrom.cc
+++ b/apt-pkg/cdrom.cc
@@ -913,10 +913,14 @@ bool pkgCdrom::Add(pkgCdromStatus *log) /*{{{*/
return true;
}
/*}}}*/
-pkgUdevCdromDevices::pkgUdevCdromDevices() /*{{{*/
- : libudev_handle(NULL)
+pkgUdevCdromDevices::pkgUdevCdromDevices() /*{{{*/
+: libudev_handle(NULL), udev_new(NULL), udev_enumerate_add_match_property(NULL),
+ udev_enumerate_scan_devices(NULL), udev_enumerate_get_list_entry(NULL),
+ udev_device_new_from_syspath(NULL), udev_enumerate_get_udev(NULL),
+ udev_list_entry_get_name(NULL), udev_device_get_devnode(NULL),
+ udev_enumerate_new(NULL), udev_list_entry_get_next(NULL),
+ udev_device_get_property_value(NULL), udev_enumerate_add_match_sysattr(NULL)
{
-
}
/*}}}*/
diff --git a/apt-pkg/clean.cc b/apt-pkg/clean.cc
index 37128e9aa..6edce5b6d 100644
--- a/apt-pkg/clean.cc
+++ b/apt-pkg/clean.cc
@@ -131,3 +131,5 @@ bool pkgArchiveCleaner::Go(std::string Dir,pkgCache &Cache)
return true;
}
/*}}}*/
+
+APT_CONST pkgArchiveCleaner::~pkgArchiveCleaner() {}
diff --git a/apt-pkg/clean.h b/apt-pkg/clean.h
index 930d54a7f..466cb67a9 100644
--- a/apt-pkg/clean.h
+++ b/apt-pkg/clean.h
@@ -24,13 +24,13 @@ class pkgArchiveCleaner
void *d;
protected:
-
+
virtual void Erase(const char * /*File*/,std::string /*Pkg*/,std::string /*Ver*/,struct stat & /*St*/) {};
- public:
-
+ public:
+
bool Go(std::string Dir,pkgCache &Cache);
- virtual ~pkgArchiveCleaner() {};
+ virtual ~pkgArchiveCleaner();
};
#endif
diff --git a/apt-pkg/contrib/cmndline.cc b/apt-pkg/contrib/cmndline.cc
index 3799c822d..93c1f4664 100644
--- a/apt-pkg/contrib/cmndline.cc
+++ b/apt-pkg/contrib/cmndline.cc
@@ -47,23 +47,26 @@ CommandLine::~CommandLine()
char const * CommandLine::GetCommand(Dispatch const * const Map,
unsigned int const argc, char const * const * const argv)
{
- // if there is a -- on the line there must be the word we search for around it
- // as -- marks the end of the options, just not sure if the command can be
- // considered an option or not, so accept both
+ // if there is a -- on the line there must be the word we search for either
+ // before it (as -- marks the end of the options) or right after it (as we can't
+ // decide if the command is actually an option, given that in theory, you could
+ // have parameters named like commands)
for (size_t i = 1; i < argc; ++i)
{
if (strcmp(argv[i], "--") != 0)
continue;
- ++i;
- if (i < argc)
+ // check if command is before --
+ for (size_t k = 1; k < i; ++k)
for (size_t j = 0; Map[j].Match != NULL; ++j)
- if (strcmp(argv[i], Map[j].Match) == 0)
+ if (strcmp(argv[k], Map[j].Match) == 0)
return Map[j].Match;
- i -= 2;
- if (i != 0)
+ // see if the next token after -- is the command
+ ++i;
+ if (i < argc)
for (size_t j = 0; Map[j].Match != NULL; ++j)
if (strcmp(argv[i], Map[j].Match) == 0)
return Map[j].Match;
+ // we found a --, but not a command
return NULL;
}
// no --, so search for the first word matching a command
diff --git a/apt-pkg/contrib/configuration.cc b/apt-pkg/contrib/configuration.cc
index 00f6ad0f9..4380d64b9 100644
--- a/apt-pkg/contrib/configuration.cc
+++ b/apt-pkg/contrib/configuration.cc
@@ -253,9 +253,6 @@ string Configuration::FindDir(const char *Name,const char *Default) const
// Configuration::FindVector - Find a vector of values /*{{{*/
// ---------------------------------------------------------------------
/* Returns a vector of config values under the given item */
-#if (APT_PKG_MAJOR >= 4 && APT_PKG_MINOR < 13)
-vector<string> Configuration::FindVector(const char *Name) const { return FindVector(Name, ""); }
-#endif
vector<string> Configuration::FindVector(const char *Name, std::string const &Default) const
{
vector<string> Vec;
diff --git a/apt-pkg/contrib/configuration.h b/apt-pkg/contrib/configuration.h
index c256139f4..2ecea8bee 100644
--- a/apt-pkg/contrib/configuration.h
+++ b/apt-pkg/contrib/configuration.h
@@ -34,6 +34,8 @@
#include <vector>
#include <iostream>
+#include <apt-pkg/macros.h>
+
#ifndef APT_8_CLEANER_HEADERS
using std::string;
#endif
@@ -59,7 +61,7 @@ class Configuration
Item *Root;
bool ToFree;
-
+
Item *Lookup(Item *Head,const char *S,unsigned long const &Len,bool const &Create);
Item *Lookup(const char *Name,const bool &Create);
inline const Item *Lookup(const char *Name) const
@@ -82,14 +84,8 @@ class Configuration
*
* \param Name of the parent node
* \param Default list of values separated by commas */
- std::vector<std::string> FindVector(const char *Name, std::string const &Default) const;
- std::vector<std::string> FindVector(std::string const &Name, std::string const &Default) const { return FindVector(Name.c_str(), Default); };
-#if (APT_PKG_MAJOR >= 4 && APT_PKG_MINOR >= 13)
- std::vector<std::string> FindVector(const char *Name) const { return FindVector(Name, ""); };
-#else
- std::vector<std::string> FindVector(const char *Name) const;
-#endif
- std::vector<std::string> FindVector(std::string const &Name) const { return FindVector(Name.c_str(), ""); };
+ std::vector<std::string> FindVector(const char *Name, std::string const &Default = "") const;
+ std::vector<std::string> FindVector(std::string const &Name, std::string const &Default = "") const { return FindVector(Name.c_str(), Default); };
int FindI(const char *Name,int const &Default = 0) const;
int FindI(std::string const &Name,int const &Default = 0) const {return FindI(Name.c_str(),Default);};
bool FindB(const char *Name,bool const &Default = false) const;
@@ -129,7 +125,7 @@ class Configuration
class MatchAgainstConfig
{
std::vector<regex_t *> patterns;
- void clearPatterns();
+ APT_HIDDEN void clearPatterns();
public:
MatchAgainstConfig(char const * Config);
diff --git a/apt-pkg/contrib/fileutl.cc b/apt-pkg/contrib/fileutl.cc
index 1ba4674e5..c51eee737 100644
--- a/apt-pkg/contrib/fileutl.cc
+++ b/apt-pkg/contrib/fileutl.cc
@@ -47,6 +47,8 @@
#include <signal.h>
#include <errno.h>
#include <glob.h>
+#include <pwd.h>
+#include <grp.h>
#include <set>
#include <algorithm>
@@ -63,6 +65,10 @@
#include <endian.h>
#include <stdint.h>
+#if __gnu_linux__
+#include <sys/prctl.h>
+#endif
+
#include <apti18n.h>
/*}}}*/
@@ -656,6 +662,22 @@ string flCombine(string Dir,string File)
return Dir + '/' + File;
}
/*}}}*/
+// flAbsPath - Return the absolute path of the filename /*{{{*/
+// ---------------------------------------------------------------------
+/* */
+string flAbsPath(string File)
+{
+ char *p = realpath(File.c_str(), NULL);
+ if (p == NULL)
+ {
+ _error->Errno("realpath", "flAbsPath failed");
+ return "";
+ }
+ std::string AbsPath(p);
+ free(p);
+ return AbsPath;
+}
+ /*}}}*/
// SetCloseExec - Set the close on exec flag /*{{{*/
// ---------------------------------------------------------------------
/* */
@@ -835,6 +857,23 @@ bool ExecWait(pid_t Pid,const char *Name,bool Reap)
return true;
}
/*}}}*/
+// StartsWithGPGClearTextSignature - Check if a file is Pgp/GPG clearsigned /*{{{*/
+bool StartsWithGPGClearTextSignature(string const &FileName)
+{
+ static const char* SIGMSG = "-----BEGIN PGP SIGNED MESSAGE-----\n";
+ char buffer[strlen(SIGMSG)+1];
+ FILE* gpg = fopen(FileName.c_str(), "r");
+ if (gpg == NULL)
+ return false;
+
+ char const * const test = fgets(buffer, sizeof(buffer), gpg);
+ fclose(gpg);
+ if (test == NULL || strcmp(buffer, SIGMSG) != 0)
+ return false;
+
+ return true;
+}
+ /*}}}*/
class FileFdPrivate { /*{{{*/
public:
@@ -853,7 +892,7 @@ class FileFdPrivate { /*{{{*/
bool eof;
bool compressing;
- LZMAFILE() : file(NULL), eof(false), compressing(false) {}
+ LZMAFILE() : file(NULL), eof(false), compressing(false) { buffer[0] = '\0'; }
~LZMAFILE() {
if (compressing == true)
{
@@ -1482,7 +1521,7 @@ bool FileFd::Read(void *To,unsigned long long Size,unsigned long long *Actual)
int err;
char const * const errmsg = BZ2_bzerror(d->bz2, &err);
if (err != BZ_IO_ERROR)
- return FileFdError("BZ2_bzread: %s (%d: %s)", _("Read error"), err, errmsg);
+ return FileFdError("BZ2_bzread: %s %s (%d: %s)", FileName.c_str(), _("Read error"), err, errmsg);
}
#endif
#ifdef HAVE_LZMA
@@ -1913,7 +1952,6 @@ bool FileFd::Close()
{
if ((Flags & Compressed) != Compressed && iFd > 0 && close(iFd) != 0)
Res &= _error->Errno("close",_("Problem closing the file %s"), FileName.c_str());
-
if (d != NULL)
{
Res &= d->CloseDown(FileName);
@@ -1993,10 +2031,7 @@ APT_DEPRECATED gzFile FileFd::gzFd() {
#endif
}
-
-// Glob - wrapper around "glob()" /*{{{*/
-// ---------------------------------------------------------------------
-/* */
+// Glob - wrapper around "glob()" /*{{{*/
std::vector<std::string> Glob(std::string const &pattern, int flags)
{
std::vector<std::string> result;
@@ -2022,8 +2057,7 @@ std::vector<std::string> Glob(std::string const &pattern, int flags)
return result;
}
/*}}}*/
-
-std::string GetTempDir()
+std::string GetTempDir() /*{{{*/
{
const char *tmpdir = getenv("TMPDIR");
@@ -2039,14 +2073,193 @@ std::string GetTempDir()
return string(tmpdir);
}
+ /*}}}*/
+FileFd* GetTempFile(std::string const &Prefix, bool ImmediateUnlink) /*{{{*/
+{
+ char fn[512];
+ FileFd *Fd = new FileFd();
+
+ std::string tempdir = GetTempDir();
+ snprintf(fn, sizeof(fn), "%s/%s.XXXXXX",
+ tempdir.c_str(), Prefix.c_str());
+ int fd = mkstemp(fn);
+ if(ImmediateUnlink)
+ unlink(fn);
+ if (fd < 0)
+ {
+ _error->Errno("GetTempFile",_("Unable to mkstemp %s"), fn);
+ return NULL;
+ }
+ if (!Fd->OpenDescriptor(fd, FileFd::WriteOnly, FileFd::None, true))
+ {
+ _error->Errno("GetTempFile",_("Unable to write to %s"),fn);
+ return NULL;
+ }
-bool Rename(std::string From, std::string To)
+ return Fd;
+}
+ /*}}}*/
+bool Rename(std::string From, std::string To) /*{{{*/
{
if (rename(From.c_str(),To.c_str()) != 0)
{
_error->Error(_("rename failed, %s (%s -> %s)."),strerror(errno),
From.c_str(),To.c_str());
return false;
- }
+ }
return true;
}
+ /*}}}*/
+bool Popen(const char* Args[], FileFd &Fd, pid_t &Child, FileFd::OpenMode Mode)/*{{{*/
+{
+ int fd;
+ if (Mode != FileFd::ReadOnly && Mode != FileFd::WriteOnly)
+ return _error->Error("Popen supports ReadOnly (x)or WriteOnly mode only");
+
+ int Pipe[2] = {-1, -1};
+ if(pipe(Pipe) != 0)
+ return _error->Errno("pipe", _("Failed to create subprocess IPC"));
+
+ std::set<int> keep_fds;
+ keep_fds.insert(Pipe[0]);
+ keep_fds.insert(Pipe[1]);
+ Child = ExecFork(keep_fds);
+ if(Child < 0)
+ return _error->Errno("fork", "Failed to fork");
+ if(Child == 0)
+ {
+ if(Mode == FileFd::ReadOnly)
+ {
+ close(Pipe[0]);
+ fd = Pipe[1];
+ }
+ else if(Mode == FileFd::WriteOnly)
+ {
+ close(Pipe[1]);
+ fd = Pipe[0];
+ }
+
+ if(Mode == FileFd::ReadOnly)
+ {
+ dup2(fd, 1);
+ dup2(fd, 2);
+ } else if(Mode == FileFd::WriteOnly)
+ dup2(fd, 0);
+
+ execv(Args[0], (char**)Args);
+ _exit(100);
+ }
+ if(Mode == FileFd::ReadOnly)
+ {
+ close(Pipe[1]);
+ fd = Pipe[0];
+ } else if(Mode == FileFd::WriteOnly)
+ {
+ close(Pipe[0]);
+ fd = Pipe[1];
+ }
+ Fd.OpenDescriptor(fd, Mode, FileFd::None, true);
+
+ return true;
+}
+ /*}}}*/
+bool DropPrivileges() /*{{{*/
+{
+ if(_config->FindB("Debug::NoDropPrivs", false) == true)
+ return true;
+
+#if __gnu_linux__
+#if defined(PR_SET_NO_NEW_PRIVS) && ( PR_SET_NO_NEW_PRIVS != 38 )
+#error "PR_SET_NO_NEW_PRIVS is defined, but with a different value than expected!"
+#endif
+ // see prctl(2), needs linux3.5 at runtime - magic constant to avoid it at buildtime
+ int ret = prctl(38, 1, 0, 0, 0);
+ // ignore EINVAL - kernel is too old to understand the option
+ if(ret < 0 && errno != EINVAL)
+ _error->Warning("PR_SET_NO_NEW_PRIVS failed with %i", ret);
+#endif
+
+ // empty setting disables privilege dropping - this also ensures
+ // backward compatibility, see bug #764506
+ const std::string toUser = _config->Find("APT::Sandbox::User");
+ if (toUser.empty())
+ return true;
+
+ // uid will be 0 in the end, but gid might be different anyway
+ uid_t const old_uid = getuid();
+ gid_t const old_gid = getgid();
+
+ if (old_uid != 0)
+ return true;
+
+ struct passwd *pw = getpwnam(toUser.c_str());
+ if (pw == NULL)
+ return _error->Error("No user %s, can not drop rights", toUser.c_str());
+
+ // Do not change the order here, it might break things
+ if (setgroups(1, &pw->pw_gid))
+ return _error->Errno("setgroups", "Failed to setgroups");
+
+ if (setegid(pw->pw_gid) != 0)
+ return _error->Errno("setegid", "Failed to setegid");
+
+ if (setgid(pw->pw_gid) != 0)
+ return _error->Errno("setgid", "Failed to setgid");
+
+ if (setuid(pw->pw_uid) != 0)
+ return _error->Errno("setuid", "Failed to setuid");
+
+ // the seteuid() is probably uneeded (at least thats what the linux
+ // man-page says about setuid(2)) but we cargo culted it anyway
+ if (seteuid(pw->pw_uid) != 0)
+ return _error->Errno("seteuid", "Failed to seteuid");
+
+ // Verify that the user has only a single group, and the correct one
+ gid_t groups[1];
+ if (getgroups(1, groups) != 1)
+ return _error->Errno("getgroups", "Could not get new groups");
+ if (groups[0] != pw->pw_gid)
+ return _error->Error("Could not switch group");
+
+ // Verify that gid, egid, uid, and euid changed
+ if (getgid() != pw->pw_gid)
+ return _error->Error("Could not switch group");
+ if (getegid() != pw->pw_gid)
+ return _error->Error("Could not switch effective group");
+ if (getuid() != pw->pw_uid)
+ return _error->Error("Could not switch user");
+ if (geteuid() != pw->pw_uid)
+ return _error->Error("Could not switch effective user");
+
+#ifdef HAVE_GETRESUID
+ // verify that the saved set-user-id was changed as well
+ uid_t ruid = 0;
+ uid_t euid = 0;
+ uid_t suid = 0;
+ if (getresuid(&ruid, &euid, &suid))
+ return _error->Errno("getresuid", "Could not get saved set-user-ID");
+ if (suid != pw->pw_uid)
+ return _error->Error("Could not switch saved set-user-ID");
+#endif
+
+#ifdef HAVE_GETRESGID
+ // verify that the saved set-group-id was changed as well
+ gid_t rgid = 0;
+ gid_t egid = 0;
+ gid_t sgid = 0;
+ if (getresgid(&rgid, &egid, &sgid))
+ return _error->Errno("getresuid", "Could not get saved set-group-ID");
+ if (sgid != pw->pw_gid)
+ return _error->Error("Could not switch saved set-group-ID");
+#endif
+
+ // Check that uid and gid changes do not work anymore
+ if (pw->pw_gid != old_gid && (setgid(old_gid) != -1 || setegid(old_gid) != -1))
+ return _error->Error("Could restore a gid to root, privilege dropping did not work");
+
+ if (pw->pw_uid != old_uid && (setuid(old_uid) != -1 || seteuid(old_uid) != -1))
+ return _error->Error("Could restore a uid to root, privilege dropping did not work");
+
+ return true;
+}
+ /*}}}*/
diff --git a/apt-pkg/contrib/fileutl.h b/apt-pkg/contrib/fileutl.h
index 667057067..a64d6cb98 100644
--- a/apt-pkg/contrib/fileutl.h
+++ b/apt-pkg/contrib/fileutl.h
@@ -170,6 +170,8 @@ time_t GetModificationTime(std::string const &Path);
bool Rename(std::string From, std::string To);
std::string GetTempDir();
+FileFd* GetTempFile(std::string const &Prefix = "",
+ bool ImmediateUnlink = true);
/** \brief Ensure the existence of the given Path
*
@@ -193,6 +195,23 @@ pid_t ExecFork(std::set<int> keep_fds);
void MergeKeepFdsFromConfiguration(std::set<int> &keep_fds);
bool ExecWait(pid_t Pid,const char *Name,bool Reap = false);
+
+// check if the given file starts with a PGP cleartext signature
+bool StartsWithGPGClearTextSignature(std::string const &FileName);
+
+/**
+ * \brief Drop privileges
+ *
+ * Drop the privileges to the user _apt (or the one specified in
+ * APT::Sandbox::User). This does not set the supplementary group
+ * ids up correctly, it only uses the default group. Also prevent
+ * the process from gaining any new privileges afterwards, at least
+ * on Linux.
+ *
+ * \return true on success, false on failure with _error set
+ */
+bool DropPrivileges();
+
// File string manipulators
std::string flNotDir(std::string File);
std::string flNotFile(std::string File);
@@ -200,7 +219,23 @@ std::string flNoLink(std::string File);
std::string flExtension(std::string File);
std::string flCombine(std::string Dir,std::string File);
+/** \brief Takes a file path and returns the absolute path
+ */
+std::string flAbsPath(std::string File);
+
// simple c++ glob
std::vector<std::string> Glob(std::string const &pattern, int flags=0);
+/** \brief Popen() implementation that execv() instead of using a shell
+ *
+ * \param Args the execv style command to run
+ * \param FileFd is a referenz to the FileFd to use for input or output
+ * \param Child a reference to the integer that stores the child pid
+ * Note that you must call ExecWait() or similar to cleanup
+ * \param Mode is either FileFd::ReadOnly or FileFd::WriteOnly
+ * \return true on success, false on failure with _error set
+ */
+bool Popen(const char* Args[], FileFd &Fd, pid_t &Child, FileFd::OpenMode Mode);
+
+
#endif
diff --git a/apt-pkg/contrib/gpgv.cc b/apt-pkg/contrib/gpgv.cc
index f24dd9640..9d798cca9 100644
--- a/apt-pkg/contrib/gpgv.cc
+++ b/apt-pkg/contrib/gpgv.cc
@@ -32,50 +32,30 @@ static char * GenerateTemporaryFileTemplate(const char *basename) /*{{{*/
/*}}}*/
// ExecGPGV - returns the command needed for verify /*{{{*/
// ---------------------------------------------------------------------
-/* Generating the commandline for calling gpgv is somehow complicated as
+/* Generating the commandline for calling gpg is somehow complicated as
we need to add multiple keyrings and user supplied options.
- Also, as gpgv has no options to enforce a certain reduced style of
+ Also, as gpg has no options to enforce a certain reduced style of
clear-signed files (=the complete content of the file is signed and
the content isn't encoded) we do a divide and conquer approach here
- and split up the clear-signed file in message and signature for gpgv
+ and split up the clear-signed file in message and signature for gpg.
+ And as a cherry on the cake, we use our apt-key wrapper to do part
+ of the lifting in regards to merging keyrings. Fun for the whole family.
*/
void ExecGPGV(std::string const &File, std::string const &FileGPG,
int const &statusfd, int fd[2])
{
#define EINTERNAL 111
- std::string const gpgvpath = _config->Find("Dir::Bin::gpg", "/usr/bin/gpgv");
- // FIXME: remove support for deprecated APT::GPGV setting
- std::string const trustedFile = _config->Find("APT::GPGV::TrustedKeyring", _config->FindFile("Dir::Etc::Trusted"));
- std::string const trustedPath = _config->FindDir("Dir::Etc::TrustedParts");
+ std::string const aptkey = _config->FindFile("Dir::Bin::apt-key", "/usr/bin/apt-key");
bool const Debug = _config->FindB("Debug::Acquire::gpgv", false);
- if (Debug == true)
- {
- std::clog << "gpgv path: " << gpgvpath << std::endl;
- std::clog << "Keyring file: " << trustedFile << std::endl;
- std::clog << "Keyring path: " << trustedPath << std::endl;
- }
-
- std::vector<std::string> keyrings;
- if (DirectoryExists(trustedPath))
- keyrings = GetListOfFilesInDir(trustedPath, "gpg", false, true);
- if (RealFileExists(trustedFile) == true)
- keyrings.push_back(trustedFile);
-
std::vector<const char *> Args;
- Args.reserve(30);
-
- if (keyrings.empty() == true)
- {
- // TRANSLATOR: %s is the trusted keyring parts directory
- ioprintf(std::cerr, _("No keyring installed in %s."),
- _config->FindDir("Dir::Etc::TrustedParts").c_str());
- exit(EINTERNAL);
- }
+ Args.reserve(10);
- Args.push_back(gpgvpath.c_str());
- Args.push_back("--ignore-time-conflict");
+ Args.push_back(aptkey.c_str());
+ Args.push_back("--quiet");
+ Args.push_back("--readonly");
+ Args.push_back("verify");
char statusfdstr[10];
if (statusfd != -1)
@@ -85,13 +65,6 @@ void ExecGPGV(std::string const &File, std::string const &FileGPG,
Args.push_back(statusfdstr);
}
- for (std::vector<std::string>::const_iterator K = keyrings.begin();
- K != keyrings.end(); ++K)
- {
- Args.push_back("--keyring");
- Args.push_back(K->c_str());
- }
-
Configuration::Item const *Opts;
Opts = _config->Tree("Acquire::gpgv::Options");
if (Opts != 0)
@@ -160,7 +133,7 @@ void ExecGPGV(std::string const &File, std::string const &FileGPG,
if (Debug == true)
{
- std::clog << "Preparing to exec: " << gpgvpath;
+ std::clog << "Preparing to exec: ";
for (std::vector<const char *>::const_iterator a = Args.begin(); *a != NULL; ++a)
std::clog << " " << *a;
std::clog << std::endl;
@@ -168,7 +141,7 @@ void ExecGPGV(std::string const &File, std::string const &FileGPG,
if (statusfd != -1)
{
- int const nullfd = open("/dev/null", O_RDONLY);
+ int const nullfd = open("/dev/null", O_WRONLY);
close(fd[0]);
// Redirect output to /dev/null; we read from the status fd
if (statusfd != STDOUT_FILENO)
@@ -185,7 +158,7 @@ void ExecGPGV(std::string const &File, std::string const &FileGPG,
if (releaseSignature == DETACHED)
{
- execvp(gpgvpath.c_str(), (char **) &Args[0]);
+ execvp(Args[0], (char **) &Args[0]);
ioprintf(std::cerr, "Couldn't execute %s to check %s", Args[0], File.c_str());
exit(EINTERNAL);
}
@@ -205,7 +178,7 @@ void ExecGPGV(std::string const &File, std::string const &FileGPG,
{
if (statusfd != -1)
dup2(fd[1], statusfd);
- execvp(gpgvpath.c_str(), (char **) &Args[0]);
+ execvp(Args[0], (char **) &Args[0]);
ioprintf(std::cerr, "Couldn't execute %s to check %s", Args[0], File.c_str());
UNLINK_EXIT(EINTERNAL);
}
@@ -216,7 +189,7 @@ void ExecGPGV(std::string const &File, std::string const &FileGPG,
{
if (errno == EINTR)
continue;
- ioprintf(std::cerr, _("Waited for %s but it wasn't there"), "gpgv");
+ ioprintf(std::cerr, _("Waited for %s but it wasn't there"), "apt-key");
UNLINK_EXIT(EINTERNAL);
}
#undef UNLINK_EXIT
@@ -229,14 +202,14 @@ void ExecGPGV(std::string const &File, std::string const &FileGPG,
// check if it exit'ed normally …
if (WIFEXITED(Status) == false)
{
- ioprintf(std::cerr, _("Sub-process %s exited unexpectedly"), "gpgv");
+ ioprintf(std::cerr, _("Sub-process %s exited unexpectedly"), "apt-key");
exit(EINTERNAL);
}
// … and with a good exit code
if (WEXITSTATUS(Status) != 0)
{
- ioprintf(std::cerr, _("Sub-process %s returned an error code (%u)"), "gpgv", WEXITSTATUS(Status));
+ ioprintf(std::cerr, _("Sub-process %s returned an error code (%u)"), "apt-key", WEXITSTATUS(Status));
exit(WEXITSTATUS(Status));
}
diff --git a/apt-pkg/contrib/hashes.cc b/apt-pkg/contrib/hashes.cc
index 15f83615d..417982343 100644
--- a/apt-pkg/contrib/hashes.cc
+++ b/apt-pkg/contrib/hashes.cc
@@ -27,7 +27,7 @@
#include <iostream>
/*}}}*/
-const char* HashString::_SupportedHashes[] =
+const char * HashString::_SupportedHashes[] =
{
"SHA512", "SHA256", "SHA1", "MD5Sum", NULL
};
@@ -42,11 +42,16 @@ HashString::HashString(std::string Type, std::string Hash) : Type(Type), Hash(Ha
HashString::HashString(std::string StringedHash) /*{{{*/
{
- // legacy: md5sum without "MD5Sum:" prefix
- if (StringedHash.find(":") == std::string::npos && StringedHash.size() == 32)
+ if (StringedHash.find(":") == std::string::npos)
{
- Type = "MD5Sum";
- Hash = StringedHash;
+ // legacy: md5sum without "MD5Sum:" prefix
+ if (StringedHash.size() == 32)
+ {
+ Type = "MD5Sum";
+ Hash = StringedHash;
+ }
+ if(_config->FindB("Debug::Hashes",false) == true)
+ std::clog << "HashString(string): invalid StringedHash " << StringedHash << std::endl;
return;
}
std::string::size_type pos = StringedHash.find(":");
@@ -82,25 +87,25 @@ std::string HashString::GetHashForFile(std::string filename) const /*{{{*/
std::string fileHash;
FileFd Fd(filename, FileFd::ReadOnly);
- if(Type == "MD5Sum")
+ if(strcasecmp(Type.c_str(), "MD5Sum") == 0)
{
MD5Summation MD5;
MD5.AddFD(Fd);
fileHash = (std::string)MD5.Result();
}
- else if (Type == "SHA1")
+ else if (strcasecmp(Type.c_str(), "SHA1") == 0)
{
SHA1Summation SHA1;
SHA1.AddFD(Fd);
fileHash = (std::string)SHA1.Result();
}
- else if (Type == "SHA256")
+ else if (strcasecmp(Type.c_str(), "SHA256") == 0)
{
SHA256Summation SHA256;
SHA256.AddFD(Fd);
fileHash = (std::string)SHA256.Result();
}
- else if (Type == "SHA512")
+ else if (strcasecmp(Type.c_str(), "SHA512") == 0)
{
SHA512Summation SHA512;
SHA512.AddFD(Fd);
@@ -111,26 +116,147 @@ std::string HashString::GetHashForFile(std::string filename) const /*{{{*/
return fileHash;
}
/*}}}*/
-const char** HashString::SupportedHashes()
+const char** HashString::SupportedHashes() /*{{{*/
{
return _SupportedHashes;
}
-
-APT_PURE bool HashString::empty() const
+ /*}}}*/
+APT_PURE bool HashString::empty() const /*{{{*/
{
return (Type.empty() || Hash.empty());
}
+ /*}}}*/
+std::string HashString::toStr() const /*{{{*/
+{
+ return Type + ":" + Hash;
+}
+ /*}}}*/
+APT_PURE bool HashString::operator==(HashString const &other) const /*{{{*/
+{
+ return (strcasecmp(Type.c_str(), other.Type.c_str()) == 0 && Hash == other.Hash);
+}
+APT_PURE bool HashString::operator!=(HashString const &other) const
+{
+ return !(*this == other);
+}
+ /*}}}*/
+
+bool HashStringList::usable() const /*{{{*/
+{
+ if (empty() == true)
+ return false;
+ std::string const forcedType = _config->Find("Acquire::ForceHash", "");
+ if (forcedType.empty() == true)
+ return true;
+ return find(forcedType) != NULL;
+}
+ /*}}}*/
+HashString const * HashStringList::find(char const * const type) const /*{{{*/
+{
+ if (type == NULL || type[0] == '\0')
+ {
+ std::string const forcedType = _config->Find("Acquire::ForceHash", "");
+ if (forcedType.empty() == false)
+ return find(forcedType.c_str());
+ for (char const * const * t = HashString::SupportedHashes(); *t != NULL; ++t)
+ for (std::vector<HashString>::const_iterator hs = list.begin(); hs != list.end(); ++hs)
+ if (strcasecmp(hs->HashType().c_str(), *t) == 0)
+ return &*hs;
+ return NULL;
+ }
+ for (std::vector<HashString>::const_iterator hs = list.begin(); hs != list.end(); ++hs)
+ if (strcasecmp(hs->HashType().c_str(), type) == 0)
+ return &*hs;
+ return NULL;
+}
+ /*}}}*/
+bool HashStringList::supported(char const * const type) /*{{{*/
+{
+ for (char const * const * t = HashString::SupportedHashes(); *t != NULL; ++t)
+ if (strcasecmp(*t, type) == 0)
+ return true;
+ return false;
+}
+ /*}}}*/
+bool HashStringList::push_back(const HashString &hashString) /*{{{*/
+{
+ if (hashString.HashType().empty() == true ||
+ hashString.HashValue().empty() == true ||
+ supported(hashString.HashType().c_str()) == false)
+ return false;
+
+ // ensure that each type is added only once
+ HashString const * const hs = find(hashString.HashType().c_str());
+ if (hs != NULL)
+ return *hs == hashString;
-std::string HashString::toStr() const
+ list.push_back(hashString);
+ return true;
+}
+ /*}}}*/
+bool HashStringList::VerifyFile(std::string filename) const /*{{{*/
{
- return Type + std::string(":") + Hash;
+ if (list.empty() == true)
+ return false;
+ HashString const * const hs = find(NULL);
+ if (hs == NULL || hs->VerifyFile(filename) == false)
+ return false;
+ return true;
}
+ /*}}}*/
+bool HashStringList::operator==(HashStringList const &other) const /*{{{*/
+{
+ std::string const forcedType = _config->Find("Acquire::ForceHash", "");
+ if (forcedType.empty() == false)
+ {
+ HashString const * const hs = find(forcedType);
+ HashString const * const ohs = other.find(forcedType);
+ if (hs == NULL || ohs == NULL)
+ return false;
+ return *hs == *ohs;
+ }
+ short matches = 0;
+ for (const_iterator hs = begin(); hs != end(); ++hs)
+ {
+ HashString const * const ohs = other.find(hs->HashType());
+ if (ohs == NULL)
+ continue;
+ if (*hs != *ohs)
+ return false;
+ ++matches;
+ }
+ if (matches == 0)
+ return false;
+ return true;
+}
+bool HashStringList::operator!=(HashStringList const &other) const
+{
+ return !(*this == other);
+}
+ /*}}}*/
-// Hashes::AddFD - Add the contents of the FD /*{{{*/
-// ---------------------------------------------------------------------
-/* */
-bool Hashes::AddFD(int const Fd,unsigned long long Size, bool const addMD5,
- bool const addSHA1, bool const addSHA256, bool const addSHA512)
+// Hashes::Add* - Add the contents of data or FD /*{{{*/
+bool Hashes::Add(const unsigned char * const Data,unsigned long long const Size, unsigned int const Hashes)
+{
+ bool Res = true;
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+ if ((Hashes & MD5SUM) == MD5SUM)
+ Res &= MD5.Add(Data, Size);
+ if ((Hashes & SHA1SUM) == SHA1SUM)
+ Res &= SHA1.Add(Data, Size);
+ if ((Hashes & SHA256SUM) == SHA256SUM)
+ Res &= SHA256.Add(Data, Size);
+ if ((Hashes & SHA512SUM) == SHA512SUM)
+ Res &= SHA512.Add(Data, Size);
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic pop
+#endif
+ return Res;
+}
+bool Hashes::AddFD(int const Fd,unsigned long long Size, unsigned int const Hashes)
{
unsigned char Buf[64*64];
bool const ToEOF = (Size == UntilEOF);
@@ -144,19 +270,12 @@ bool Hashes::AddFD(int const Fd,unsigned long long Size, bool const addMD5,
if (ToEOF && Res == 0) // EOF
break;
Size -= Res;
- if (addMD5 == true)
- MD5.Add(Buf,Res);
- if (addSHA1 == true)
- SHA1.Add(Buf,Res);
- if (addSHA256 == true)
- SHA256.Add(Buf,Res);
- if (addSHA512 == true)
- SHA512.Add(Buf,Res);
+ if (Add(Buf, Res, Hashes) == false)
+ return false;
}
return true;
}
-bool Hashes::AddFD(FileFd &Fd,unsigned long long Size, bool const addMD5,
- bool const addSHA1, bool const addSHA256, bool const addSHA512)
+bool Hashes::AddFD(FileFd &Fd,unsigned long long Size, unsigned int const Hashes)
{
unsigned char Buf[64*64];
bool const ToEOF = (Size == 0);
@@ -175,15 +294,35 @@ bool Hashes::AddFD(FileFd &Fd,unsigned long long Size, bool const addMD5,
else if (a == 0) // EOF
break;
Size -= a;
- if (addMD5 == true)
- MD5.Add(Buf, a);
- if (addSHA1 == true)
- SHA1.Add(Buf, a);
- if (addSHA256 == true)
- SHA256.Add(Buf, a);
- if (addSHA512 == true)
- SHA512.Add(Buf, a);
+ if (Add(Buf, a, Hashes) == false)
+ return false;
}
return true;
}
/*}}}*/
+HashStringList Hashes::GetHashStringList()
+{
+ HashStringList hashes;
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+ hashes.push_back(HashString("MD5Sum", MD5.Result().Value()));
+ hashes.push_back(HashString("SHA1", SHA1.Result().Value()));
+ hashes.push_back(HashString("SHA256", SHA256.Result().Value()));
+ hashes.push_back(HashString("SHA512", SHA512.Result().Value()));
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic pop
+#endif
+ return hashes;
+}
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+ #pragma GCC diagnostic ignored "-Wsuggest-attribute=const"
+#endif
+Hashes::Hashes() {}
+Hashes::~Hashes() {}
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic pop
+#endif
diff --git a/apt-pkg/contrib/hashes.h b/apt-pkg/contrib/hashes.h
index 7a62f8a8f..caeba006d 100644
--- a/apt-pkg/contrib/hashes.h
+++ b/apt-pkg/contrib/hashes.h
@@ -17,6 +17,7 @@
#include <apt-pkg/md5.h>
#include <apt-pkg/sha1.h>
#include <apt-pkg/sha2.h>
+#include <apt-pkg/macros.h>
#include <cstring>
#include <string>
@@ -41,7 +42,7 @@ class HashString
protected:
std::string Type;
std::string Hash;
- static const char* _SupportedHashes[10];
+ static const char * _SupportedHashes[10];
// internal helper
std::string GetHashForFile(std::string filename) const;
@@ -52,7 +53,8 @@ class HashString
HashString();
// get hash type used
- std::string HashType() { return Type; };
+ std::string HashType() const { return Type; };
+ std::string HashValue() const { return Hash; };
// verify the given filename against the currently loaded hash
bool VerifyFile(std::string filename) const;
@@ -64,37 +66,160 @@ class HashString
// helper
std::string toStr() const; // convert to str as "type:hash"
bool empty() const;
+ bool operator==(HashString const &other) const;
+ bool operator!=(HashString const &other) const;
// return the list of hashes we support
static APT_CONST const char** SupportedHashes();
};
+class HashStringList
+{
+ public:
+ /** find best hash if no specific one is requested
+ *
+ * @param type of the checksum to return, can be \b NULL
+ * @return If type is \b NULL (or the empty string) it will
+ * return the 'best' hash; otherwise the hash which was
+ * specifically requested. If no hash is found \b NULL will be returned.
+ */
+ HashString const * find(char const * const type) const;
+ HashString const * find(std::string const &type) const { return find(type.c_str()); }
+ /** check if the given hash type is supported
+ *
+ * @param type to check
+ * @return true if supported, otherwise false
+ */
+ static APT_PURE bool supported(char const * const type);
+ /** add the given #HashString to the list
+ *
+ * @param hashString to add
+ * @return true if the hash is added because it is supported and
+ * not already a different hash of the same type included, otherwise false
+ */
+ bool push_back(const HashString &hashString);
+ /** @return size of the list of HashStrings */
+ size_t size() const { return list.size(); }
+
+ /** take the 'best' hash and verify file with it
+ *
+ * @param filename to verify
+ * @return true if the file matches the hashsum, otherwise false
+ */
+ bool VerifyFile(std::string filename) const;
+
+ /** is the list empty ?
+ *
+ * @return \b true if the list is empty, otherwise \b false
+ */
+ bool empty() const { return list.empty(); }
+
+ /** has the list at least one good entry
+ *
+ * similar to #empty, but handles forced hashes.
+ *
+ * @return if no hash is forced, same result as #empty,
+ * if one is forced \b true if this has is available, \b false otherwise
+ */
+ bool usable() const;
+
+ typedef std::vector<HashString>::const_iterator const_iterator;
+
+ /** iterator to the first element */
+ const_iterator begin() const { return list.begin(); }
+
+ /** iterator to the end element */
+ const_iterator end() const { return list.end(); }
+
+ /** start fresh with a clear list */
+ void clear() { list.clear(); }
+
+ /** compare two HashStringList for similarity.
+ *
+ * Two lists are similar if at least one hashtype is in both lists
+ * and the hashsum matches. All hashes are checked by default,
+ * if one doesn't match false is returned regardless of how many
+ * matched before. If a hash is forced, only this hash is compared,
+ * all others are ignored.
+ */
+ bool operator==(HashStringList const &other) const;
+ bool operator!=(HashStringList const &other) const;
+
+ HashStringList() {}
+
+ // simplifying API-compatibility constructors
+ HashStringList(std::string const &hash) {
+ if (hash.empty() == false)
+ list.push_back(HashString(hash));
+ }
+ HashStringList(char const * const hash) {
+ if (hash != NULL && hash[0] != '\0')
+ list.push_back(HashString(hash));
+ }
+
+ private:
+ std::vector<HashString> list;
+};
+
class Hashes
{
+ /** \brief dpointer placeholder */
+ void *d;
+
public:
+ /* those will disappear in the future as it is hard to add new ones this way.
+ * Use Add* to build the results and get them via GetHashStringList() instead */
+ APT_DEPRECATED MD5Summation MD5;
+ APT_DEPRECATED SHA1Summation SHA1;
+ APT_DEPRECATED SHA256Summation SHA256;
+ APT_DEPRECATED SHA512Summation SHA512;
- MD5Summation MD5;
- SHA1Summation SHA1;
- SHA256Summation SHA256;
- SHA512Summation SHA512;
-
static const int UntilEOF = 0;
- inline bool Add(const unsigned char *Data,unsigned long long Size)
+ bool Add(const unsigned char * const Data, unsigned long long const Size, unsigned int const Hashes = ~0);
+ inline bool Add(const char * const Data)
+ {return Add((unsigned char const * const)Data,strlen(Data));};
+ inline bool Add(const unsigned char * const Beg,const unsigned char * const End)
+ {return Add(Beg,End-Beg);};
+
+ enum SupportedHashes { MD5SUM = (1 << 0), SHA1SUM = (1 << 1), SHA256SUM = (1 << 2),
+ SHA512SUM = (1 << 3) };
+ bool AddFD(int const Fd,unsigned long long Size = 0, unsigned int const Hashes = ~0);
+ bool AddFD(FileFd &Fd,unsigned long long Size = 0, unsigned int const Hashes = ~0);
+
+ HashStringList GetHashStringList();
+
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+ Hashes();
+ virtual ~Hashes();
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic pop
+#endif
+
+ private:
+ APT_HIDDEN APT_CONST inline unsigned int boolsToFlag(bool const addMD5, bool const addSHA1, bool const addSHA256, bool const addSHA512)
{
- return MD5.Add(Data,Size) && SHA1.Add(Data,Size) && SHA256.Add(Data,Size) && SHA512.Add(Data,Size);
+ unsigned int Hashes = ~0;
+ if (addMD5 == false) Hashes &= ~MD5SUM;
+ if (addSHA1 == false) Hashes &= ~SHA1SUM;
+ if (addSHA256 == false) Hashes &= ~SHA256SUM;
+ if (addSHA512 == false) Hashes &= ~SHA512SUM;
+ return Hashes;
+ }
+
+ public:
+ APT_DEPRECATED bool AddFD(int const Fd, unsigned long long Size, bool const addMD5,
+ bool const addSHA1, bool const addSHA256, bool const addSHA512) {
+ return AddFD(Fd, Size, boolsToFlag(addMD5, addSHA1, addSHA256, addSHA512));
+ };
+
+ APT_DEPRECATED bool AddFD(FileFd &Fd, unsigned long long Size, bool const addMD5,
+ bool const addSHA1, bool const addSHA256, bool const addSHA512) {
+ return AddFD(Fd, Size, boolsToFlag(addMD5, addSHA1, addSHA256, addSHA512));
};
- inline bool Add(const char *Data) {return Add((unsigned char const *)Data,strlen(Data));};
- inline bool AddFD(int const Fd,unsigned long long Size = 0)
- { return AddFD(Fd, Size, true, true, true, true); };
- bool AddFD(int const Fd, unsigned long long Size, bool const addMD5,
- bool const addSHA1, bool const addSHA256, bool const addSHA512);
- inline bool AddFD(FileFd &Fd,unsigned long long Size = 0)
- { return AddFD(Fd, Size, true, true, true, true); };
- bool AddFD(FileFd &Fd, unsigned long long Size, bool const addMD5,
- bool const addSHA1, bool const addSHA256, bool const addSHA512);
- inline bool Add(const unsigned char *Beg,const unsigned char *End)
- {return Add(Beg,End-Beg);};
};
#endif
diff --git a/apt-pkg/contrib/macros.h b/apt-pkg/contrib/macros.h
index 2d6448e5e..a0573398d 100644
--- a/apt-pkg/contrib/macros.h
+++ b/apt-pkg/contrib/macros.h
@@ -138,7 +138,7 @@
// Non-ABI-Breaks should only increase RELEASE number.
// See also buildlib/libversion.mak
#define APT_PKG_MAJOR 4
-#define APT_PKG_MINOR 12
+#define APT_PKG_MINOR 14
#define APT_PKG_RELEASE 0
#endif
diff --git a/apt-pkg/contrib/netrc.cc b/apt-pkg/contrib/netrc.cc
index feaed67c8..1e3778f45 100644
--- a/apt-pkg/contrib/netrc.cc
+++ b/apt-pkg/contrib/netrc.cc
@@ -152,18 +152,6 @@ static int parsenetrc_string (char *host, std::string &login, std::string &passw
return retcode;
}
-// for some unknown reason this method is exported so keep a compatible interface for now …
-int parsenetrc (char *host, char *login, char *password, char *netrcfile = NULL)
-{
- std::string login_string, password_string;
- int const ret = parsenetrc_string(host, login_string, password_string, netrcfile);
- if (ret < 0)
- return ret;
- strncpy(login, login_string.c_str(), LOGINSIZE - 1);
- strncpy(password, password_string.c_str(), PASSWORDSIZE - 1);
- return ret;
-}
-
void maybe_add_auth (URI &Uri, string NetRCFile)
{
diff --git a/apt-pkg/contrib/netrc.h b/apt-pkg/contrib/netrc.h
index dbeb45386..b5b56f5d4 100644
--- a/apt-pkg/contrib/netrc.h
+++ b/apt-pkg/contrib/netrc.h
@@ -27,9 +27,5 @@
class URI;
-// FIXME: kill this export on the next ABI break - strongly doubt its in use anyway
-// outside of the apt itself, its really a internal interface
-APT_DEPRECATED int parsenetrc (char *host, char *login, char *password, char *filename);
-
void maybe_add_auth (URI &Uri, std::string NetRCFile);
#endif
diff --git a/apt-pkg/contrib/strutl.cc b/apt-pkg/contrib/strutl.cc
index 87f57a30e..aad358a55 100644
--- a/apt-pkg/contrib/strutl.cc
+++ b/apt-pkg/contrib/strutl.cc
@@ -74,6 +74,13 @@ bool Endswith(const std::string &s, const std::string &end)
return (s.substr(s.size() - end.size(), s.size()) == end);
}
+bool Startswith(const std::string &s, const std::string &start)
+{
+ if (start.size() > s.size())
+ return false;
+ return (s.substr(0, start.size()) == start);
+}
+
}
}
/*}}}*/
@@ -1061,7 +1068,7 @@ bool StrToNum(const char *Str,unsigned long long &Res,unsigned Len,unsigned Base
// ---------------------------------------------------------------------
/* This is used in decoding the 256bit encoded fixed length fields in
tar files */
-bool Base256ToNum(const char *Str,unsigned long &Res,unsigned int Len)
+bool Base256ToNum(const char *Str,unsigned long long &Res,unsigned int Len)
{
if ((Str[0] & 0x80) == 0)
return false;
@@ -1074,6 +1081,23 @@ bool Base256ToNum(const char *Str,unsigned long &Res,unsigned int Len)
}
}
/*}}}*/
+// Base256ToNum - Convert a fixed length binary to a number /*{{{*/
+// ---------------------------------------------------------------------
+/* This is used in decoding the 256bit encoded fixed length fields in
+ tar files */
+bool Base256ToNum(const char *Str,unsigned long &Res,unsigned int Len)
+{
+ unsigned long long Num;
+ bool rc;
+
+ rc = Base256ToNum(Str, Num, Len);
+ Res = Num;
+ if (Res != Num)
+ return false;
+
+ return rc;
+}
+ /*}}}*/
// HexDigit - Convert a hex character into an integer /*{{{*/
// ---------------------------------------------------------------------
/* Helper for Hex2Num */
diff --git a/apt-pkg/contrib/strutl.h b/apt-pkg/contrib/strutl.h
index 185cdc3fc..e20ddca9c 100644
--- a/apt-pkg/contrib/strutl.h
+++ b/apt-pkg/contrib/strutl.h
@@ -40,6 +40,7 @@ namespace APT {
namespace String {
std::string Strip(const std::string &s);
bool Endswith(const std::string &s, const std::string &ending);
+ bool Startswith(const std::string &s, const std::string &starting);
}
}
@@ -72,6 +73,7 @@ bool ReadMessages(int Fd, std::vector<std::string> &List);
bool StrToNum(const char *Str,unsigned long &Res,unsigned Len,unsigned Base = 0);
bool StrToNum(const char *Str,unsigned long long &Res,unsigned Len,unsigned Base = 0);
bool Base256ToNum(const char *Str,unsigned long &Res,unsigned int Len);
+bool Base256ToNum(const char *Str,unsigned long long &Res,unsigned int Len);
bool Hex2Num(const std::string &Str,unsigned char *Num,unsigned int Length);
// input changing string split
@@ -151,9 +153,9 @@ inline const char *DeNull(const char *s) {return (s == 0?"(null)":s);}
class URI
{
void CopyFrom(const std::string &From);
-
+
public:
-
+
std::string Access;
std::string User;
std::string Password;
diff --git a/apt-pkg/deb/debindexfile.cc b/apt-pkg/deb/debindexfile.cc
index 5b4289e92..cc1d94d81 100644
--- a/apt-pkg/deb/debindexfile.cc
+++ b/apt-pkg/deb/debindexfile.cc
@@ -30,6 +30,7 @@
#include <apt-pkg/pkgcachegen.h>
#include <apt-pkg/pkgrecords.h>
#include <apt-pkg/srcrecords.h>
+#include <apt-pkg/sptr.h>
#include <stdio.h>
#include <iostream>
@@ -130,7 +131,7 @@ string debSourcesIndex::Info(const char *Type) const
// SourcesIndex::Index* - Return the URI to the index files /*{{{*/
// ---------------------------------------------------------------------
/* */
-inline string debSourcesIndex::IndexFile(const char *Type) const
+string debSourcesIndex::IndexFile(const char *Type) const
{
string s = URItoFileName(IndexURI(Type));
@@ -264,7 +265,7 @@ string debPackagesIndex::Info(const char *Type) const
// PackagesIndex::Index* - Return the URI to the index files /*{{{*/
// ---------------------------------------------------------------------
/* */
-inline string debPackagesIndex::IndexFile(const char *Type) const
+string debPackagesIndex::IndexFile(const char *Type) const
{
string s =_config->FindDir("Dir::State::lists") + URItoFileName(IndexURI(Type));
@@ -420,7 +421,7 @@ debTranslationsIndex::debTranslationsIndex(string URI,string Dist,string Section
// TranslationIndex::Trans* - Return the URI to the translation files /*{{{*/
// ---------------------------------------------------------------------
/* */
-inline string debTranslationsIndex::IndexFile(const char *Type) const
+string debTranslationsIndex::IndexFile(const char *Type) const
{
string s =_config->FindDir("Dir::State::lists") + URItoFileName(IndexURI(Type));
@@ -634,7 +635,7 @@ bool debStatusIndex::Merge(pkgCacheGenerator &Gen,OpProgress *Prog) const
pkgCache::PkgFileIterator CFile = Gen.GetCurFile();
CFile->Size = Pkg.FileSize();
CFile->mtime = Pkg.ModificationTime();
- map_ptrloc const storage = Gen.WriteUniqString("now");
+ map_stringitem_t const storage = Gen.StoreString(pkgCacheGenerator::MIXED, "now");
CFile->Archive = storage;
if (Gen.MergeList(Parser) == false)
@@ -683,6 +684,136 @@ APT_CONST bool debStatusIndex::Exists() const
}
/*}}}*/
+// debDebPkgFile - Single .deb file /*{{{*/
+// ---------------------------------------------------------------------
+debDebPkgFileIndex::debDebPkgFileIndex(std::string DebFile)
+ : pkgIndexFile(true), DebFile(DebFile)
+{
+ DebFileFullPath = flAbsPath(DebFile);
+}
+
+std::string debDebPkgFileIndex::ArchiveURI(std::string /*File*/) const
+{
+ return "file:" + DebFileFullPath;
+}
+
+bool debDebPkgFileIndex::Exists() const
+{
+ return FileExists(DebFile);
+}
+bool debDebPkgFileIndex::Merge(pkgCacheGenerator& Gen, OpProgress* Prog) const
+{
+ if(Prog)
+ Prog->SubProgress(0, "Reading deb file");
+
+ // get the control data out of the deb file vid dpkg -I
+ // ... can I haz libdpkg?
+ Configuration::Item const *Opts = _config->Tree("DPkg::Options");
+ std::string dpkg = _config->Find("Dir::Bin::dpkg","dpkg");
+ std::vector<const char *> Args;
+ Args.push_back(dpkg.c_str());
+ if (Opts != 0)
+ {
+ Opts = Opts->Child;
+ for (; Opts != 0; Opts = Opts->Next)
+ {
+ if (Opts->Value.empty() == true)
+ continue;
+ Args.push_back(Opts->Value.c_str());
+ }
+ }
+ Args.push_back("-I");
+ Args.push_back(DebFile.c_str());
+ Args.push_back("control");
+ Args.push_back(NULL);
+ FileFd PipeFd;
+ pid_t Child;
+ if(Popen((const char**)&Args[0], PipeFd, Child, FileFd::ReadOnly) == false)
+ return _error->Error("Popen failed");
+ // FIXME: static buffer
+ char buf[8*1024];
+ unsigned long long n = 0;
+ if(PipeFd.Read(buf, sizeof(buf)-1, &n) == false)
+ return _error->Errno("read", "Failed to read dpkg pipe");
+ ExecWait(Child, "Popen");
+
+ // now write the control data to a tempfile
+ SPtr<FileFd> DebControl = GetTempFile("deb-file-" + flNotDir(DebFile));
+ if(DebControl == NULL)
+ return false;
+ DebControl->Write(buf, n);
+ // append size of the file
+ FileFd Fd(DebFile, FileFd::ReadOnly);
+ string Size;
+ strprintf(Size, "Size: %llu\n", Fd.Size());
+ DebControl->Write(Size.c_str(), Size.size());
+ // and rewind for the listparser
+ DebControl->Seek(0);
+
+ // and give it to the list parser
+ debDebFileParser Parser(DebControl, DebFile);
+ if(Gen.SelectFile(DebFile, "local", *this) == false)
+ return _error->Error("Problem with SelectFile %s", DebFile.c_str());
+
+ pkgCache::PkgFileIterator File = Gen.GetCurFile();
+ File->Size = DebControl->Size();
+ File->mtime = DebControl->ModificationTime();
+
+ if (Gen.MergeList(Parser) == false)
+ return _error->Error("Problem with MergeLister for %s", DebFile.c_str());
+
+ return true;
+}
+pkgCache::PkgFileIterator debDebPkgFileIndex::FindInCache(pkgCache &Cache) const
+{
+ pkgCache::PkgFileIterator File = Cache.FileBegin();
+ for (; File.end() == false; ++File)
+ {
+ if (File.FileName() == NULL || DebFile != File.FileName())
+ continue;
+
+ return File;
+ }
+
+ return File;
+}
+unsigned long debDebPkgFileIndex::Size() const
+{
+ struct stat buf;
+ if(stat(DebFile.c_str(), &buf) != 0)
+ return 0;
+ return buf.st_size;
+}
+ /*}}}*/
+
+// debDscFileIndex stuff
+debDscFileIndex::debDscFileIndex(std::string &DscFile)
+ : pkgIndexFile(true), DscFile(DscFile)
+{
+}
+
+bool debDscFileIndex::Exists() const
+{
+ return FileExists(DscFile);
+}
+
+unsigned long debDscFileIndex::Size() const
+{
+ struct stat buf;
+ if(stat(DscFile.c_str(), &buf) == 0)
+ return buf.st_size;
+ return 0;
+}
+
+// DscFileIndex::CreateSrcParser - Get a parser for the .dsc file /*{{{*/
+pkgSrcRecords::Parser *debDscFileIndex::CreateSrcParser() const
+{
+ if (!FileExists(DscFile))
+ return NULL;
+
+ return new debDscRecordParser(DscFile,this);
+}
+ /*}}}*/
// Index File types for Debian /*{{{*/
class debIFTypeSrc : public pkgIndexFile::Type
{
@@ -715,10 +846,42 @@ class debIFTypeStatus : public pkgIndexFile::Type
};
debIFTypeStatus() {Label = "Debian dpkg status file";};
};
+class debIFTypeDebPkgFile : public pkgIndexFile::Type
+{
+ public:
+ virtual pkgRecords::Parser *CreatePkgParser(pkgCache::PkgFileIterator File) const
+ {
+ return new debDebFileRecordParser(File.FileName(),*File.Cache());
+ };
+ debIFTypeDebPkgFile() {Label = "deb Package file";};
+};
+class debIFTypeDscFile : public pkgIndexFile::Type
+{
+ public:
+ virtual pkgSrcRecords::Parser *CreateSrcPkgParser(std::string DscFile) const
+ {
+ return new debDscRecordParser(DscFile, NULL);
+ };
+ debIFTypeDscFile() {Label = "dsc File Source Index";};
+};
+class debIFTypeDebianSourceDir : public pkgIndexFile::Type
+{
+ public:
+ virtual pkgSrcRecords::Parser *CreateSrcPkgParser(std::string SourceDir) const
+ {
+ return new debDscRecordParser(SourceDir + string("/debian/control"), NULL);
+ };
+ debIFTypeDebianSourceDir() {Label = "debian/control File Source Index";};
+};
+
static debIFTypeSrc _apt_Src;
static debIFTypePkg _apt_Pkg;
static debIFTypeTrans _apt_Trans;
static debIFTypeStatus _apt_Status;
+static debIFTypeDebPkgFile _apt_DebPkgFile;
+// file based pseudo indexes
+static debIFTypeDscFile _apt_DscFile;
+static debIFTypeDebianSourceDir _apt_DebianSourceDir;
const pkgIndexFile::Type *debSourcesIndex::GetType() const
{
@@ -736,5 +899,23 @@ const pkgIndexFile::Type *debStatusIndex::GetType() const
{
return &_apt_Status;
}
-
+const pkgIndexFile::Type *debDebPkgFileIndex::GetType() const
+{
+ return &_apt_DebPkgFile;
+}
+const pkgIndexFile::Type *debDscFileIndex::GetType() const
+{
+ return &_apt_DscFile;
+}
+const pkgIndexFile::Type *debDebianSourceDirIndex::GetType() const
+{
+ return &_apt_DebianSourceDir;
+}
/*}}}*/
+
+debStatusIndex::~debStatusIndex() {}
+debPackagesIndex::~debPackagesIndex() {}
+debTranslationsIndex::~debTranslationsIndex() {}
+debSourcesIndex::~debSourcesIndex() {}
+
+debDebPkgFileIndex::~debDebPkgFileIndex() {}
diff --git a/apt-pkg/deb/debindexfile.h b/apt-pkg/deb/debindexfile.h
index 017c69a0a..e5a1a7873 100644
--- a/apt-pkg/deb/debindexfile.h
+++ b/apt-pkg/deb/debindexfile.h
@@ -52,7 +52,7 @@ class debStatusIndex : public pkgIndexFile
virtual pkgCache::PkgFileIterator FindInCache(pkgCache &Cache) const;
debStatusIndex(std::string File);
- virtual ~debStatusIndex() {};
+ virtual ~debStatusIndex();
};
class debPackagesIndex : public pkgIndexFile
@@ -65,10 +65,10 @@ class debPackagesIndex : public pkgIndexFile
std::string Section;
std::string Architecture;
- std::string Info(const char *Type) const;
- std::string IndexFile(const char *Type) const;
- std::string IndexURI(const char *Type) const;
-
+ APT_HIDDEN std::string Info(const char *Type) const;
+ APT_HIDDEN std::string IndexFile(const char *Type) const;
+ APT_HIDDEN std::string IndexURI(const char *Type) const;
+
public:
virtual const Type *GetType() const APT_CONST;
@@ -89,7 +89,7 @@ class debPackagesIndex : public pkgIndexFile
debPackagesIndex(std::string const &URI, std::string const &Dist, std::string const &Section,
bool const &Trusted, std::string const &Arch = "native");
- virtual ~debPackagesIndex() {};
+ virtual ~debPackagesIndex();
};
class debTranslationsIndex : public pkgIndexFile
@@ -102,11 +102,11 @@ class debTranslationsIndex : public pkgIndexFile
std::string Section;
const char * const Language;
- std::string Info(const char *Type) const;
- std::string IndexFile(const char *Type) const;
- std::string IndexURI(const char *Type) const;
+ APT_HIDDEN std::string Info(const char *Type) const;
+ APT_HIDDEN std::string IndexFile(const char *Type) const;
+ APT_HIDDEN std::string IndexURI(const char *Type) const;
- inline std::string TranslationFile() const {return std::string("Translation-").append(Language);};
+ APT_HIDDEN std::string TranslationFile() const {return std::string("Translation-").append(Language);};
public:
@@ -124,7 +124,7 @@ class debTranslationsIndex : public pkgIndexFile
virtual pkgCache::PkgFileIterator FindInCache(pkgCache &Cache) const;
debTranslationsIndex(std::string URI,std::string Dist,std::string Section, char const * const Language);
- virtual ~debTranslationsIndex() {};
+ virtual ~debTranslationsIndex();
};
class debSourcesIndex : public pkgIndexFile
@@ -136,10 +136,10 @@ class debSourcesIndex : public pkgIndexFile
std::string Dist;
std::string Section;
- std::string Info(const char *Type) const;
- std::string IndexFile(const char *Type) const;
- std::string IndexURI(const char *Type) const;
-
+ APT_HIDDEN std::string Info(const char *Type) const;
+ APT_HIDDEN std::string IndexFile(const char *Type) const;
+ APT_HIDDEN std::string IndexURI(const char *Type) const;
+
public:
virtual const Type *GetType() const APT_CONST;
@@ -161,7 +161,61 @@ class debSourcesIndex : public pkgIndexFile
virtual unsigned long Size() const;
debSourcesIndex(std::string URI,std::string Dist,std::string Section,bool Trusted);
- virtual ~debSourcesIndex() {};
+ virtual ~debSourcesIndex();
+};
+
+class debDebPkgFileIndex : public pkgIndexFile
+{
+ private:
+ void *d;
+ std::string DebFile;
+ std::string DebFileFullPath;
+
+ public:
+ virtual const Type *GetType() const APT_CONST;
+
+ virtual std::string Describe(bool /*Short*/) const {
+ return DebFile;
+ }
+
+ // Interface for the Cache Generator
+ virtual bool Exists() const;
+ virtual bool HasPackages() const {
+ return true;
+ };
+ virtual unsigned long Size() const;
+ virtual bool Merge(pkgCacheGenerator &Gen,OpProgress *Prog) const;
+ virtual pkgCache::PkgFileIterator FindInCache(pkgCache &Cache) const;
+
+ // Interface for acquire
+ virtual std::string ArchiveURI(std::string /*File*/) const;
+
+ debDebPkgFileIndex(std::string DebFile);
+ virtual ~debDebPkgFileIndex();
+};
+
+class debDscFileIndex : public pkgIndexFile
+{
+ private:
+ std::string DscFile;
+ public:
+ virtual const Type *GetType() const APT_CONST;
+ virtual pkgSrcRecords::Parser *CreateSrcParser() const;
+ virtual bool Exists() const;
+ virtual bool HasPackages() const {return false;};
+ virtual unsigned long Size() const;
+ virtual std::string Describe(bool /*Short*/) const {
+ return DscFile;
+ };
+
+ debDscFileIndex(std::string &DscFile);
+ virtual ~debDscFileIndex() {};
+};
+
+class debDebianSourceDirIndex : public debDscFileIndex
+{
+ public:
+ virtual const Type *GetType() const APT_CONST;
};
#endif
diff --git a/apt-pkg/deb/deblistparser.cc b/apt-pkg/deb/deblistparser.cc
index 4eef66c2b..616d8296d 100644
--- a/apt-pkg/deb/deblistparser.cc
+++ b/apt-pkg/deb/deblistparser.cc
@@ -58,18 +58,6 @@ debListParser::debListParser(FileFd *File, string const &Arch) : Tags(File),
MultiArchEnabled = Architectures.size() > 1;
}
/*}}}*/
-// ListParser::UniqFindTagWrite - Find the tag and write a unq string /*{{{*/
-// ---------------------------------------------------------------------
-/* */
-unsigned long debListParser::UniqFindTagWrite(const char *Tag)
-{
- const char *Start;
- const char *Stop;
- if (Section.Find(Tag,Start,Stop) == false)
- return 0;
- return WriteUniqString(Start,Stop - Start);
-}
- /*}}}*/
// ListParser::Package - Return the package name /*{{{*/
// ---------------------------------------------------------------------
/* This is to return the name of the package this section describes */
@@ -144,9 +132,67 @@ unsigned char debListParser::ParseMultiArch(bool const showErrors) /*{{{*/
/* */
bool debListParser::NewVersion(pkgCache::VerIterator &Ver)
{
+ const char *Start;
+ const char *Stop;
+
// Parse the section
- unsigned long const idxSection = UniqFindTagWrite("Section");
- Ver->Section = idxSection;
+ if (Section.Find("Section",Start,Stop) == true)
+ {
+ map_stringitem_t const idx = StoreString(pkgCacheGenerator::SECTION, Start, Stop - Start);
+ Ver->Section = idx;
+ }
+ // Parse the source package name
+ pkgCache::GrpIterator const G = Ver.ParentPkg().Group();
+ Ver->SourcePkgName = G->Name;
+ Ver->SourceVerStr = Ver->VerStr;
+ if (Section.Find("Source",Start,Stop) == true)
+ {
+ const char * const Space = (const char * const) memchr(Start, ' ', Stop - Start);
+ pkgCache::VerIterator V;
+
+ if (Space != NULL)
+ {
+ Stop = Space;
+ const char * const Open = (const char * const) memchr(Space, '(', Stop - Space);
+ if (likely(Open != NULL))
+ {
+ const char * const Close = (const char * const) memchr(Open, ')', Stop - Open);
+ if (likely(Close != NULL))
+ {
+ std::string const version(Open + 1, (Close - Open) - 1);
+ if (version != Ver.VerStr())
+ {
+ map_stringitem_t const idx = StoreString(pkgCacheGenerator::VERSIONNUMBER, version);
+ Ver->SourceVerStr = idx;
+ }
+ }
+ }
+ }
+
+ std::string const pkgname(Start, Stop - Start);
+ if (pkgname != G.Name())
+ {
+ for (pkgCache::PkgIterator P = G.PackageList(); P.end() == false; P = G.NextPkg(P))
+ {
+ for (V = P.VersionList(); V.end() == false; ++V)
+ {
+ if (pkgname == V.SourcePkgName())
+ {
+ Ver->SourcePkgName = V->SourcePkgName;
+ break;
+ }
+ }
+ if (V.end() == false)
+ break;
+ }
+ if (V.end() == true)
+ {
+ map_stringitem_t const idx = StoreString(pkgCacheGenerator::PKGNAME, pkgname);
+ Ver->SourcePkgName = idx;
+ }
+ }
+ }
+
Ver->MultiArch = ParseMultiArch(true);
// Archive Size
Ver->Size = Section.FindULL("Size");
@@ -155,10 +201,8 @@ bool debListParser::NewVersion(pkgCache::VerIterator &Ver)
Ver->InstalledSize *= 1024;
// Priority
- const char *Start;
- const char *Stop;
if (Section.Find("Priority",Start,Stop) == true)
- {
+ {
if (GrabWord(string(Start,Stop-Start),PrioList,Ver->Priority) == false)
Ver->Priority = pkgCache::State::Extra;
}
@@ -195,35 +239,31 @@ bool debListParser::NewVersion(pkgCache::VerIterator &Ver)
/* This is to return the string describing the package in debian
form. If this returns the blank string then the entry is assumed to
only describe package properties */
-string debListParser::Description()
+string debListParser::Description(std::string const &lang)
{
- string const lang = DescriptionLanguage();
if (lang.empty())
return Section.FindS("Description");
else
return Section.FindS(string("Description-").append(lang).c_str());
}
- /*}}}*/
-// ListParser::DescriptionLanguage - Return the description lang string /*{{{*/
-// ---------------------------------------------------------------------
-/* This is to return the string describing the language of
- description. If this returns the blank string then the entry is
- assumed to describe original description. */
-string debListParser::DescriptionLanguage()
+ /*}}}*/
+// ListParser::AvailableDescriptionLanguages /*{{{*/
+std::vector<std::string> debListParser::AvailableDescriptionLanguages()
{
- if (Section.FindS("Description").empty() == false)
- return "";
-
- std::vector<string> const lang = APT::Configuration::getLanguages(true);
- for (std::vector<string>::const_iterator l = lang.begin();
- l != lang.end(); ++l)
- if (Section.FindS(string("Description-").append(*l).c_str()).empty() == false)
- return *l;
-
- return "";
+ std::vector<std::string> const understood = APT::Configuration::getLanguages();
+ std::vector<std::string> avail;
+ if (Section.Exists("Description") == true)
+ avail.push_back("");
+ for (std::vector<std::string>::const_iterator lang = understood.begin(); lang != understood.end(); ++lang)
+ {
+ std::string const tagname = "Description-" + *lang;
+ if (Section.Exists(tagname.c_str()) == true)
+ avail.push_back(*lang);
+ }
+ return avail;
}
- /*}}}*/
-// ListParser::Description - Return the description_md5 MD5SumValue /*{{{*/
+ /*}}}*/
+// ListParser::Description_md5 - Return the description_md5 MD5SumValue /*{{{*/
// ---------------------------------------------------------------------
/* This is to return the md5 string to allow the check if it is the right
description. If no Description-md5 is found in the section it will be
@@ -234,7 +274,7 @@ MD5SumValue debListParser::Description_md5()
string const value = Section.FindS("Description-md5");
if (value.empty() == true)
{
- std::string const desc = Description() + "\n";
+ std::string const desc = Description("") + "\n";
if (desc == "\n")
return MD5SumValue();
@@ -260,12 +300,6 @@ MD5SumValue debListParser::Description_md5()
bool debListParser::UsePackage(pkgCache::PkgIterator &Pkg,
pkgCache::VerIterator &Ver)
{
- if (Pkg->Section == 0)
- {
- unsigned long const idxSection = UniqFindTagWrite("Section");
- Pkg->Section = idxSection;
- }
-
string const static myArch = _config->Find("APT::Architecture");
// Possible values are: "all", "native", "installed" and "none"
// The "installed" mode is handled by ParseStatus(), See #544481 and friends.
@@ -917,7 +951,7 @@ bool debListParser::LoadReleaseInfo(pkgCache::PkgFileIterator &FileI,
{
// apt-secure does no longer download individual (per-section) Release
// file. to provide Component pinning we use the section name now
- map_ptrloc const storage = WriteUniqString(component);
+ map_stringitem_t const storage = StoreString(pkgCacheGenerator::MIXED, component);
FileI->Component = storage;
pkgTagFile TagFile(&File, File.Size());
@@ -926,19 +960,19 @@ bool debListParser::LoadReleaseInfo(pkgCache::PkgFileIterator &FileI,
return false;
std::string data;
- #define APT_INRELEASE(TAG, STORE) \
+ #define APT_INRELEASE(TYPE, TAG, STORE) \
data = Section.FindS(TAG); \
if (data.empty() == false) \
{ \
- map_ptrloc const storage = WriteUniqString(data); \
+ map_stringitem_t const storage = StoreString(pkgCacheGenerator::TYPE, data); \
STORE = storage; \
}
- APT_INRELEASE("Suite", FileI->Archive)
- APT_INRELEASE("Component", FileI->Component)
- APT_INRELEASE("Version", FileI->Version)
- APT_INRELEASE("Origin", FileI->Origin)
- APT_INRELEASE("Codename", FileI->Codename)
- APT_INRELEASE("Label", FileI->Label)
+ APT_INRELEASE(MIXED, "Suite", FileI->Archive)
+ APT_INRELEASE(MIXED, "Component", FileI->Component)
+ APT_INRELEASE(VERSIONNUMBER, "Version", FileI->Version)
+ APT_INRELEASE(MIXED, "Origin", FileI->Origin)
+ APT_INRELEASE(MIXED, "Codename", FileI->Codename)
+ APT_INRELEASE(MIXED, "Label", FileI->Label)
#undef APT_INRELEASE
Section.FindFlag("NotAutomatic", FileI->Flags, pkgCache::Flag::NotAutomatic);
Section.FindFlag("ButAutomaticUpgrades", FileI->Flags, pkgCache::Flag::ButAutomaticUpgrades);
@@ -979,3 +1013,22 @@ bool debListParser::SameVersion(unsigned short const Hash, /*{{{*/
}
/*}}}*/
#endif
+
+
+debDebFileParser::debDebFileParser(FileFd *File, std::string const &DebFile)
+ : debListParser(File, ""), DebFile(DebFile)
+{
+}
+
+bool debDebFileParser::UsePackage(pkgCache::PkgIterator &Pkg,
+ pkgCache::VerIterator &Ver)
+{
+ bool res = debListParser::UsePackage(Pkg, Ver);
+ // we use the full file path as a provides so that the file is found
+ // by its name
+ if(NewProvidesAllArch(Ver, DebFile, Ver.VerStr()) == false)
+ return false;
+ return res;
+}
+
+debListParser::~debListParser() {}
diff --git a/apt-pkg/deb/deblistparser.h b/apt-pkg/deb/deblistparser.h
index 3b6963211..f20f7f33e 100644
--- a/apt-pkg/deb/deblistparser.h
+++ b/apt-pkg/deb/deblistparser.h
@@ -44,19 +44,19 @@ class debListParser : public pkgCacheGenerator::ListParser
protected:
pkgTagFile Tags;
pkgTagSection Section;
- unsigned long iOffset;
+ map_filesize_t iOffset;
std::string Arch;
std::vector<std::string> Architectures;
bool MultiArchEnabled;
- unsigned long UniqFindTagWrite(const char *Tag);
virtual bool ParseStatus(pkgCache::PkgIterator &Pkg,pkgCache::VerIterator &Ver);
bool ParseDepends(pkgCache::VerIterator &Ver,const char *Tag,
unsigned int Type);
bool ParseProvides(pkgCache::VerIterator &Ver);
bool NewProvidesAllArch(pkgCache::VerIterator &Ver, std::string const &Package, std::string const &Version);
static bool GrabWord(std::string Word,WordList *List,unsigned char &Out);
-
+ APT_HIDDEN unsigned char ParseMultiArch(bool const showErrors);
+
public:
static unsigned char GetPrio(std::string Str);
@@ -67,8 +67,8 @@ class debListParser : public pkgCacheGenerator::ListParser
virtual bool ArchitectureAll();
virtual std::string Version();
virtual bool NewVersion(pkgCache::VerIterator &Ver);
- virtual std::string Description();
- virtual std::string DescriptionLanguage();
+ virtual std::string Description(std::string const &lang);
+ virtual std::vector<std::string> AvailableDescriptionLanguages();
virtual MD5SumValue Description_md5();
virtual unsigned short VersionHash();
#if (APT_PKG_MAJOR >= 4 && APT_PKG_MINOR >= 13)
@@ -76,8 +76,8 @@ class debListParser : public pkgCacheGenerator::ListParser
#endif
virtual bool UsePackage(pkgCache::PkgIterator &Pkg,
pkgCache::VerIterator &Ver);
- virtual unsigned long Offset() {return iOffset;};
- virtual unsigned long Size() {return Section.size();};
+ virtual map_filesize_t Offset() {return iOffset;};
+ virtual map_filesize_t Size() {return Section.size();};
virtual bool Step();
@@ -100,10 +100,18 @@ class debListParser : public pkgCacheGenerator::ListParser
static const char *ConvertRelation(const char *I,unsigned int &Op);
debListParser(FileFd *File, std::string const &Arch = "");
- virtual ~debListParser() {};
+ virtual ~debListParser();
+};
- private:
- APT_HIDDEN unsigned char ParseMultiArch(bool const showErrors);
+class debDebFileParser : public debListParser
+{
+ private:
+ std::string DebFile;
+
+ public:
+ debDebFileParser(FileFd *File, std::string const &DebFile);
+ virtual bool UsePackage(pkgCache::PkgIterator &Pkg,
+ pkgCache::VerIterator &Ver);
};
class debTranslationsParser : public debListParser
diff --git a/apt-pkg/deb/debmetaindex.cc b/apt-pkg/deb/debmetaindex.cc
index 6fd12add8..c103da8f7 100644
--- a/apt-pkg/deb/debmetaindex.cc
+++ b/apt-pkg/deb/debmetaindex.cc
@@ -186,8 +186,8 @@ debReleaseIndex::~debReleaseIndex() {
delete *S;
}
-vector <struct IndexTarget *>* debReleaseIndex::ComputeIndexTargets() const {
- vector <struct IndexTarget *>* IndexTargets = new vector <IndexTarget *>;
+vector <IndexTarget *>* debReleaseIndex::ComputeIndexTargets() const {
+ vector <IndexTarget *>* IndexTargets = new vector <IndexTarget *>;
map<string, vector<debSectionEntry const*> >::const_iterator const src = ArchEntries.find("source");
if (src != ArchEntries.end()) {
@@ -253,38 +253,44 @@ bool debReleaseIndex::GetIndexes(pkgAcquire *Owner, bool const &GetAll) const
{
bool const tryInRelease = _config->FindB("Acquire::TryInRelease", true);
+ indexRecords * const iR = new indexRecords(Dist);
+ if (Trusted == ALWAYS_TRUSTED)
+ iR->SetTrusted(true);
+ else if (Trusted == NEVER_TRUSTED)
+ iR->SetTrusted(false);
+
// special case for --print-uris
if (GetAll) {
- vector <struct IndexTarget *> *targets = ComputeIndexTargets();
- for (vector <struct IndexTarget*>::const_iterator Target = targets->begin(); Target != targets->end(); ++Target) {
+ vector <IndexTarget *> *targets = ComputeIndexTargets();
+ for (vector <IndexTarget*>::const_iterator Target = targets->begin(); Target != targets->end(); ++Target) {
new pkgAcqIndex(Owner, (*Target)->URI, (*Target)->Description,
- (*Target)->ShortDesc, HashString());
+ (*Target)->ShortDesc, HashStringList());
}
delete targets;
// this is normally created in pkgAcqMetaSig, but if we run
// in --print-uris mode, we add it here
if (tryInRelease == false)
- new pkgAcqMetaIndex(Owner, MetaIndexURI("Release"),
- MetaIndexInfo("Release"), "Release",
- MetaIndexURI("Release.gpg"),
- ComputeIndexTargets(),
- new indexRecords (Dist));
+ new pkgAcqMetaIndex(Owner, NULL,
+ MetaIndexURI("Release"),
+ MetaIndexInfo("Release"), "Release",
+ MetaIndexURI("Release.gpg"), MetaIndexInfo("Release.gpg"), "Release.gpg",
+ ComputeIndexTargets(),
+ iR);
}
-
if (tryInRelease == true)
- new pkgAcqMetaClearSig(Owner, MetaIndexURI("InRelease"),
- MetaIndexInfo("InRelease"), "InRelease",
+ new pkgAcqMetaClearSig(Owner,
+ MetaIndexURI("InRelease"), MetaIndexInfo("InRelease"), "InRelease",
MetaIndexURI("Release"), MetaIndexInfo("Release"), "Release",
MetaIndexURI("Release.gpg"), MetaIndexInfo("Release.gpg"), "Release.gpg",
ComputeIndexTargets(),
- new indexRecords (Dist));
+ iR);
else
- new pkgAcqMetaSig(Owner, MetaIndexURI("Release.gpg"),
- MetaIndexInfo("Release.gpg"), "Release.gpg",
- MetaIndexURI("Release"), MetaIndexInfo("Release"), "Release",
- ComputeIndexTargets(),
- new indexRecords (Dist));
+ new pkgAcqMetaIndex(Owner, NULL,
+ MetaIndexURI("Release"), MetaIndexInfo("Release"), "Release",
+ MetaIndexURI("Release.gpg"), MetaIndexInfo("Release.gpg"), "Release.gpg",
+ ComputeIndexTargets(),
+ iR);
return true;
}
@@ -471,6 +477,15 @@ class debSLTypeDebian : public pkgSourceList::Type
}
};
+debDebFileMetaIndex::debDebFileMetaIndex(std::string const &DebFile)
+ : metaIndex(DebFile, "local-uri", "deb-dist"), DebFile(DebFile)
+{
+ DebIndex = new debDebPkgFileIndex(DebFile);
+ Indexes = new vector<pkgIndexFile *>();
+ Indexes->push_back(DebIndex);
+}
+
+
class debSLTypeDeb : public debSLTypeDebian
{
public:
@@ -507,5 +522,25 @@ class debSLTypeDebSrc : public debSLTypeDebian
}
};
+class debSLTypeDebFile : public pkgSourceList::Type
+{
+ public:
+
+ bool CreateItem(vector<metaIndex *> &List, string const &URI,
+ string const &/*Dist*/, string const &/*Section*/,
+ std::map<string, string> const &/*Options*/) const
+ {
+ metaIndex *mi = new debDebFileMetaIndex(URI);
+ List.push_back(mi);
+ return true;
+ }
+
+ debSLTypeDebFile()
+ {
+ Name = "deb-file";
+ Label = "Debian Deb File";
+ }
+};
debSLTypeDeb _apt_DebType;
debSLTypeDebSrc _apt_DebSrcType;
+debSLTypeDebFile _apt_DebFileType;
diff --git a/apt-pkg/deb/debmetaindex.h b/apt-pkg/deb/debmetaindex.h
index 2286fa8b2..399543953 100644
--- a/apt-pkg/deb/debmetaindex.h
+++ b/apt-pkg/deb/debmetaindex.h
@@ -18,6 +18,8 @@
class pkgAcquire;
class pkgIndexFile;
+class debDebPkgFileIndex;
+class IndexTarget;
class debReleaseIndex : public metaIndex {
public:
@@ -34,7 +36,7 @@ class debReleaseIndex : public metaIndex {
/** \brief dpointer placeholder (for later in case we need it) */
void *d;
std::map<std::string, std::vector<debSectionEntry const*> > ArchEntries;
- enum { ALWAYS_TRUSTED, NEVER_TRUSTED, CHECK_TRUST } Trusted;
+ enum APT_HIDDEN { ALWAYS_TRUSTED, NEVER_TRUSTED, CHECK_TRUST } Trusted;
public:
@@ -44,7 +46,7 @@ class debReleaseIndex : public metaIndex {
virtual std::string ArchiveURI(std::string const &File) const {return URI + File;};
virtual bool GetIndexes(pkgAcquire *Owner, bool const &GetAll=false) const;
- std::vector <struct IndexTarget *>* ComputeIndexTargets() const;
+ std::vector <IndexTarget *>* ComputeIndexTargets() const;
std::string Info(const char *Type, std::string const &Section, std::string const &Arch="") const;
std::string MetaIndexInfo(const char *Type) const;
@@ -71,4 +73,27 @@ class debReleaseIndex : public metaIndex {
void PushSectionEntry(const debSectionEntry *Entry);
};
+class debDebFileMetaIndex : public metaIndex
+{
+ private:
+ std::string DebFile;
+ debDebPkgFileIndex *DebIndex;
+ public:
+ virtual std::string ArchiveURI(std::string const& /*File*/) const {
+ return DebFile;
+ }
+ virtual bool GetIndexes(pkgAcquire* /*Owner*/, const bool& /*GetAll=false*/) const {
+ return true;
+ }
+ virtual std::vector<pkgIndexFile *> *GetIndexFiles() {
+ return Indexes;
+ }
+ virtual bool IsTrusted() const {
+ return true;
+ }
+ debDebFileMetaIndex(std::string const &DebFile);
+ virtual ~debDebFileMetaIndex() {};
+
+};
+
#endif
diff --git a/apt-pkg/deb/debrecords.cc b/apt-pkg/deb/debrecords.cc
index 6063db5a8..b41aa5584 100644
--- a/apt-pkg/deb/debrecords.cc
+++ b/apt-pkg/deb/debrecords.cc
@@ -73,36 +73,17 @@ string debRecordParser::Homepage()
return Section.FindS("Homepage");
}
/*}}}*/
-// RecordParser::MD5Hash - Return the archive hash /*{{{*/
-// ---------------------------------------------------------------------
-/* */
-string debRecordParser::MD5Hash()
+// RecordParser::Hashes - return the available archive hashes /*{{{*/
+HashStringList debRecordParser::Hashes() const
{
- return Section.FindS("MD5Sum");
-}
- /*}}}*/
-// RecordParser::SHA1Hash - Return the archive hash /*{{{*/
-// ---------------------------------------------------------------------
-/* */
-string debRecordParser::SHA1Hash()
-{
- return Section.FindS("SHA1");
-}
- /*}}}*/
-// RecordParser::SHA256Hash - Return the archive hash /*{{{*/
-// ---------------------------------------------------------------------
-/* */
-string debRecordParser::SHA256Hash()
-{
- return Section.FindS("SHA256");
-}
- /*}}}*/
-// RecordParser::SHA512Hash - Return the archive hash /*{{{*/
-// ---------------------------------------------------------------------
-/* */
-string debRecordParser::SHA512Hash()
-{
- return Section.FindS("SHA512");
+ HashStringList hashes;
+ for (char const * const * type = HashString::SupportedHashes(); *type != NULL; ++type)
+ {
+ std::string const hash = Section.FindS(*type);
+ if (hash.empty() == false)
+ hashes.push_back(HashString(*type, hash));
+ }
+ return hashes;
}
/*}}}*/
// RecordParser::Maintainer - Return the maintainer email /*{{{*/
@@ -125,10 +106,12 @@ string debRecordParser::RecordField(const char *fieldName)
// RecordParser::ShortDesc - Return a 1 line description /*{{{*/
// ---------------------------------------------------------------------
/* */
-string debRecordParser::ShortDesc()
+string debRecordParser::ShortDesc(std::string const &lang)
{
- string Res = LongDesc();
- string::size_type Pos = Res.find('\n');
+ string const Res = LongDesc(lang);
+ if (Res.empty() == true)
+ return "";
+ string::size_type const Pos = Res.find('\n');
if (Pos == string::npos)
return Res;
return string(Res,0,Pos);
@@ -137,26 +120,44 @@ string debRecordParser::ShortDesc()
// RecordParser::LongDesc - Return a longer description /*{{{*/
// ---------------------------------------------------------------------
/* */
-string debRecordParser::LongDesc()
-{
- string orig, dest;
+string debRecordParser::LongDesc(std::string const &lang)
+{
+ string orig;
+ if (lang.empty() == true)
+ {
+ std::vector<string> const lang = APT::Configuration::getLanguages();
+ for (std::vector<string>::const_iterator l = lang.begin();
+ l != lang.end(); ++l)
+ {
+ std::string const tagname = "Description-" + *l;
+ orig = Section.FindS(tagname.c_str());
+ if (orig.empty() == false)
+ break;
+ else if (*l == "en")
+ {
+ orig = Section.FindS("Description");
+ if (orig.empty() == false)
+ break;
+ }
+ }
+ if (orig.empty() == true)
+ orig = Section.FindS("Description");
+ }
+ else
+ {
+ std::string const tagname = "Description-" + lang;
+ orig = Section.FindS(tagname.c_str());
+ if (orig.empty() == true && lang == "en")
+ orig = Section.FindS("Description");
+ }
- if (!Section.FindS("Description").empty())
- orig = Section.FindS("Description").c_str();
- else
- {
- std::vector<string> const lang = APT::Configuration::getLanguages();
- for (std::vector<string>::const_iterator l = lang.begin();
- orig.empty() && l != lang.end(); ++l)
- orig = Section.FindS(string("Description-").append(*l).c_str());
- }
+ char const * const codeset = nl_langinfo(CODESET);
+ if (strcmp(codeset,"UTF-8") != 0) {
+ string dest;
+ UTF8ToCodeset(codeset, orig, &dest);
+ return dest;
+ }
- char const * const codeset = nl_langinfo(CODESET);
- if (strcmp(codeset,"UTF-8") != 0) {
- UTF8ToCodeset(codeset, orig, &dest);
- orig = dest;
- }
-
return orig;
}
/*}}}*/
@@ -206,3 +207,5 @@ void debRecordParser::GetRec(const char *&Start,const char *&Stop)
Section.GetSection(Start,Stop);
}
/*}}}*/
+
+debRecordParser::~debRecordParser() {}
diff --git a/apt-pkg/deb/debrecords.h b/apt-pkg/deb/debrecords.h
index bdac6c90b..6b5f94334 100644
--- a/apt-pkg/deb/debrecords.h
+++ b/apt-pkg/deb/debrecords.h
@@ -29,31 +29,28 @@ class debRecordParser : public pkgRecords::Parser
{
/** \brief dpointer placeholder (for later in case we need it) */
void *d;
-
+
+ protected:
FileFd File;
pkgTagFile Tags;
pkgTagSection Section;
- protected:
-
virtual bool Jump(pkgCache::VerFileIterator const &Ver);
virtual bool Jump(pkgCache::DescFileIterator const &Desc);
- public:
+ public:
// These refer to the archive file for the Version
virtual std::string FileName();
- virtual std::string MD5Hash();
- virtual std::string SHA1Hash();
- virtual std::string SHA256Hash();
- virtual std::string SHA512Hash();
virtual std::string SourcePkg();
virtual std::string SourceVer();
-
+
+ virtual HashStringList Hashes() const;
+
// These are some general stats about the package
virtual std::string Maintainer();
- virtual std::string ShortDesc();
- virtual std::string LongDesc();
+ virtual std::string ShortDesc(std::string const &lang);
+ virtual std::string LongDesc(std::string const &lang);
virtual std::string Name();
virtual std::string Homepage();
@@ -63,7 +60,18 @@ class debRecordParser : public pkgRecords::Parser
virtual void GetRec(const char *&Start,const char *&Stop);
debRecordParser(std::string FileName,pkgCache &Cache);
- virtual ~debRecordParser() {};
+ virtual ~debRecordParser();
+};
+
+// custom record parser that reads deb files directly
+class debDebFileRecordParser : public debRecordParser
+{
+ public:
+ virtual std::string FileName() {
+ return File.Name();
+ }
+ debDebFileRecordParser(std::string FileName,pkgCache &Cache)
+ : debRecordParser(FileName, Cache) {};
};
#endif
diff --git a/apt-pkg/deb/debsrcrecords.cc b/apt-pkg/deb/debsrcrecords.cc
index a444cbe4d..97f43aca2 100644
--- a/apt-pkg/deb/debsrcrecords.cc
+++ b/apt-pkg/deb/debsrcrecords.cc
@@ -18,6 +18,8 @@
#include <apt-pkg/aptconfiguration.h>
#include <apt-pkg/srcrecords.h>
#include <apt-pkg/tagfile.h>
+#include <apt-pkg/hashes.h>
+#include <apt-pkg/gpgv.h>
#include <ctype.h>
#include <stdlib.h>
@@ -55,12 +57,13 @@ const char **debSrcRecordParser::Binaries()
char* binStartNext = strchrnul(bin, ',');
char* binEnd = binStartNext - 1;
for (; isspace(*binEnd) != 0; --binEnd)
- binEnd = '\0';
+ binEnd = 0;
StaticBinList.push_back(bin);
if (*binStartNext != ',')
break;
*binStartNext = '\0';
- for (bin = binStartNext + 1; isspace(*bin) != 0; ++bin);
+ for (bin = binStartNext + 1; isspace(*bin) != 0; ++bin)
+ ;
} while (*bin != '\0');
StaticBinList.push_back(NULL);
@@ -121,10 +124,6 @@ bool debSrcRecordParser::BuildDepends(std::vector<pkgSrcRecords::Parser::BuildDe
bool debSrcRecordParser::Files(std::vector<pkgSrcRecords::File> &List)
{
List.erase(List.begin(),List.end());
-
- string Files = Sect.FindS("Files");
- if (Files.empty() == true)
- return false;
// Stash the / terminated directory prefix
string Base = Sect.FindS("Directory");
@@ -133,51 +132,105 @@ bool debSrcRecordParser::Files(std::vector<pkgSrcRecords::File> &List)
std::vector<std::string> const compExts = APT::Configuration::getCompressorExtensions();
- // Iterate over the entire list grabbing each triplet
- const char *C = Files.c_str();
- while (*C != 0)
- {
- pkgSrcRecords::File F;
- string Size;
-
- // Parse each of the elements
- if (ParseQuoteWord(C,F.MD5Hash) == false ||
- ParseQuoteWord(C,Size) == false ||
- ParseQuoteWord(C,F.Path) == false)
- return _error->Error("Error parsing file record");
-
- // Parse the size and append the directory
- F.Size = atoi(Size.c_str());
- F.Path = Base + F.Path;
-
- // Try to guess what sort of file it is we are getting.
- string::size_type Pos = F.Path.length()-1;
- while (1)
+ for (char const * const * type = HashString::SupportedHashes(); *type != NULL; ++type)
+ {
+ // derive field from checksum type
+ std::string checksumField("Checksums-");
+ if (strcmp(*type, "MD5Sum") == 0)
+ checksumField = "Files"; // historic name for MD5 checksums
+ else
+ checksumField.append(*type);
+
+ string const Files = Sect.FindS(checksumField.c_str());
+ if (Files.empty() == true)
+ continue;
+
+ // Iterate over the entire list grabbing each triplet
+ const char *C = Files.c_str();
+ while (*C != 0)
{
- string::size_type Tmp = F.Path.rfind('.',Pos);
- if (Tmp == string::npos)
- break;
- if (F.Type == "tar") {
- // source v3 has extension 'debian.tar.*' instead of 'diff.*'
- if (string(F.Path, Tmp+1, Pos-Tmp) == "debian")
- F.Type = "diff";
- break;
- }
- F.Type = string(F.Path,Tmp+1,Pos-Tmp);
-
- if (std::find(compExts.begin(), compExts.end(), std::string(".").append(F.Type)) != compExts.end() ||
- F.Type == "tar")
+ string hash, size, path;
+
+ // Parse each of the elements
+ if (ParseQuoteWord(C, hash) == false ||
+ ParseQuoteWord(C, size) == false ||
+ ParseQuoteWord(C, path) == false)
+ return _error->Error("Error parsing file record in %s of source package %s", checksumField.c_str(), Package().c_str());
+
+ HashString const hashString(*type, hash);
+ if (Base.empty() == false)
+ path = Base + path;
+
+ // look if we have a record for this file already
+ std::vector<pkgSrcRecords::File>::iterator file = List.begin();
+ for (; file != List.end(); ++file)
+ if (file->Path == path)
+ break;
+
+ // we have it already, store the new hash and be done
+ if (file != List.end())
{
- Pos = Tmp-1;
+#if __GNUC__ >= 4
+ // set for compatibility only, so warn users not us
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+ if (checksumField == "Files")
+ file->MD5Hash = hash;
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic pop
+#endif
+ // an error here indicates that we have two different hashes for the same file
+ if (file->Hashes.push_back(hashString) == false)
+ return _error->Error("Error parsing checksum in %s of source package %s", checksumField.c_str(), Package().c_str());
continue;
}
-
- break;
+
+ // we haven't seen this file yet
+ pkgSrcRecords::File F;
+ F.Path = path;
+ F.Size = strtoull(size.c_str(), NULL, 10);
+ F.Hashes.push_back(hashString);
+
+#if __GNUC__ >= 4
+ // set for compatibility only, so warn users not us
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+ if (checksumField == "Files")
+ F.MD5Hash = hash;
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic pop
+#endif
+
+ // Try to guess what sort of file it is we are getting.
+ string::size_type Pos = F.Path.length()-1;
+ while (1)
+ {
+ string::size_type Tmp = F.Path.rfind('.',Pos);
+ if (Tmp == string::npos)
+ break;
+ if (F.Type == "tar") {
+ // source v3 has extension 'debian.tar.*' instead of 'diff.*'
+ if (string(F.Path, Tmp+1, Pos-Tmp) == "debian")
+ F.Type = "diff";
+ break;
+ }
+ F.Type = string(F.Path,Tmp+1,Pos-Tmp);
+
+ if (std::find(compExts.begin(), compExts.end(), std::string(".").append(F.Type)) != compExts.end() ||
+ F.Type == "tar")
+ {
+ Pos = Tmp-1;
+ continue;
+ }
+
+ break;
+ }
+ List.push_back(F);
}
-
- List.push_back(F);
}
-
+
return true;
}
/*}}}*/
@@ -190,3 +243,21 @@ debSrcRecordParser::~debSrcRecordParser()
free(Buffer);
}
/*}}}*/
+
+
+debDscRecordParser::debDscRecordParser(std::string const &DscFile, pkgIndexFile const *Index)
+ : debSrcRecordParser(DscFile, Index)
+{
+ // support clear signed files
+ if (OpenMaybeClearSignedFile(DscFile, Fd) == false)
+ {
+ _error->Error("Failed to open %s", DscFile.c_str());
+ return;
+ }
+
+ // re-init to ensure the updated Fd is used
+ Tags.Init(&Fd);
+ // read the first (and only) record
+ Step();
+
+}
diff --git a/apt-pkg/deb/debsrcrecords.h b/apt-pkg/deb/debsrcrecords.h
index b65d1480b..a0a151875 100644
--- a/apt-pkg/deb/debsrcrecords.h
+++ b/apt-pkg/deb/debsrcrecords.h
@@ -26,6 +26,7 @@ class debSrcRecordParser : public pkgSrcRecords::Parser
/** \brief dpointer placeholder (for later in case we need it) */
void *d;
+ protected:
FileFd Fd;
pkgTagFile Tags;
pkgTagSection Sect;
@@ -60,4 +61,10 @@ class debSrcRecordParser : public pkgSrcRecords::Parser
virtual ~debSrcRecordParser();
};
+class debDscRecordParser : public debSrcRecordParser
+{
+ public:
+ debDscRecordParser(std::string const &DscFile, pkgIndexFile const *Index);
+};
+
#endif
diff --git a/apt-pkg/deb/debsystem.h b/apt-pkg/deb/debsystem.h
index a945f68fb..226cd60bf 100644
--- a/apt-pkg/deb/debsystem.h
+++ b/apt-pkg/deb/debsystem.h
@@ -29,7 +29,7 @@ class debSystem : public pkgSystem
{
// private d-pointer
debSystemPrivate *d;
- bool CheckUpdates();
+ APT_HIDDEN bool CheckUpdates();
public:
diff --git a/apt-pkg/deb/dpkgpm.cc b/apt-pkg/deb/dpkgpm.cc
index 04a13a86c..95fae9a28 100644
--- a/apt-pkg/deb/dpkgpm.cc
+++ b/apt-pkg/deb/dpkgpm.cc
@@ -517,7 +517,7 @@ bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf)
void pkgDPkgPM::DoStdin(int master)
{
unsigned char input_buf[256] = {0,};
- ssize_t len = read(0, input_buf, sizeof(input_buf));
+ ssize_t len = read(STDIN_FILENO, input_buf, sizeof(input_buf));
if (len)
FileFd::Write(master, input_buf, len);
else
@@ -1034,7 +1034,6 @@ void pkgDPkgPM::BuildPackagesProgressMap()
}
}
/*}}}*/
-#if (APT_PKG_MAJOR >= 4 && APT_PKG_MINOR < 13)
bool pkgDPkgPM::Go(int StatusFd)
{
APT::Progress::PackageManager *progress = NULL;
@@ -1043,9 +1042,8 @@ bool pkgDPkgPM::Go(int StatusFd)
else
progress = new APT::Progress::PackageManagerProgressFd(StatusFd);
- return GoNoABIBreak(progress);
+ return Go(progress);
}
-#endif
void pkgDPkgPM::StartPtyMagic()
{
@@ -1184,11 +1182,7 @@ void pkgDPkgPM::StopPtyMagic()
* through to human readable (and i10n-able)
* names and calculates a percentage for each step.
*/
-#if (APT_PKG_MAJOR >= 4 && APT_PKG_MINOR >= 13)
bool pkgDPkgPM::Go(APT::Progress::PackageManager *progress)
-#else
-bool pkgDPkgPM::GoNoABIBreak(APT::Progress::PackageManager *progress)
-#endif
{
pkgPackageManager::SigINTStop = false;
d->progress = progress;
@@ -1760,11 +1754,6 @@ void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
if (Ver.end() == true)
return;
pkgver = Ver.VerStr() == NULL ? "unknown" : Ver.VerStr();
- pkgRecords Recs(Cache);
- pkgRecords::Parser &Parse = Recs.Lookup(Ver.FileList());
- srcpkgname = Parse.SourcePkg();
- if(srcpkgname.empty())
- srcpkgname = pkgname;
// if the file exists already, we check:
// - if it was reported already (touched by apport).
@@ -1815,7 +1804,7 @@ void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
time_t now = time(NULL);
fprintf(report, "Date: %s" , ctime(&now));
fprintf(report, "Package: %s %s\n", pkgname.c_str(), pkgver.c_str());
- fprintf(report, "SourcePackage: %s\n", srcpkgname.c_str());
+ fprintf(report, "SourcePackage: %s\n", Ver.SourcePkgName());
fprintf(report, "ErrorMessage:\n %s\n", errormsg);
// ensure that the log is flushed
diff --git a/apt-pkg/deb/dpkgpm.h b/apt-pkg/deb/dpkgpm.h
index 2c1805015..2a6e7e004 100644
--- a/apt-pkg/deb/dpkgpm.h
+++ b/apt-pkg/deb/dpkgpm.h
@@ -52,7 +52,7 @@ class pkgDPkgPM : public pkgPackageManager
needs to declare a Replaces on the disappeared package.
\param pkgname Name of the package that disappeared
*/
- void handleDisappearAction(std::string const &pkgname);
+ APT_HIDDEN void handleDisappearAction(std::string const &pkgname);
protected:
int pkgFailures;
@@ -118,27 +118,14 @@ class pkgDPkgPM : public pkgPackageManager
void DoTerminalPty(int master);
void DoDpkgStatusFd(int statusfd);
void ProcessDpkgStatusLine(char *line);
-#if (APT_PKG_MAJOR >= 4 && APT_PKG_MINOR < 13)
- void DoDpkgStatusFd(int statusfd, int /*unused*/) {
- DoDpkgStatusFd(statusfd);
- }
- void ProcessDpkgStatusLine(int /*unused*/, char *line) {
- ProcessDpkgStatusLine(line);
- }
-#endif
-
// The Actuall installation implementation
virtual bool Install(PkgIterator Pkg,std::string File);
virtual bool Configure(PkgIterator Pkg);
virtual bool Remove(PkgIterator Pkg,bool Purge = false);
-#if (APT_PKG_MAJOR >= 4 && APT_PKG_MINOR >= 13)
virtual bool Go(APT::Progress::PackageManager *progress);
-#else
virtual bool Go(int StatusFd=-1);
- bool GoNoABIBreak(APT::Progress::PackageManager *progress);
-#endif
virtual void Reset();
diff --git a/apt-pkg/depcache.cc b/apt-pkg/depcache.cc
index 42e31396b..1332f3ee2 100644
--- a/apt-pkg/depcache.cc
+++ b/apt-pkg/depcache.cc
@@ -1226,7 +1226,7 @@ bool pkgDepCache::MarkInstall(PkgIterator const &Pkg,bool AutoInst,
continue;
}
// now check if we should consider it a automatic dependency or not
- if(InstPkg->CurrentVer == 0 && Pkg->Section != 0 && ConfigValueInSubTree("APT::Never-MarkAuto-Sections", Pkg.Section()))
+ if(InstPkg->CurrentVer == 0 && InstVer->Section != 0 && ConfigValueInSubTree("APT::Never-MarkAuto-Sections", InstVer.Section()))
{
if(DebugAutoInstall == true)
std::clog << OutputInDepth(Depth) << "Setting NOT as auto-installed (direct "
@@ -1961,3 +1961,17 @@ bool pkgDepCache::Sweep() /*{{{*/
return true;
}
/*}}}*/
+// DepCache::MarkAndSweep /*{{{*/
+bool pkgDepCache::MarkAndSweep(InRootSetFunc &rootFunc)
+{
+ return MarkRequired(rootFunc) && Sweep();
+}
+bool pkgDepCache::MarkAndSweep()
+{
+ std::auto_ptr<InRootSetFunc> f(GetRootSetFunc());
+ if(f.get() != NULL)
+ return MarkAndSweep(*f.get());
+ else
+ return false;
+}
+ /*}}}*/
diff --git a/apt-pkg/depcache.h b/apt-pkg/depcache.h
index bec651279..5554e1a69 100644
--- a/apt-pkg/depcache.h
+++ b/apt-pkg/depcache.h
@@ -91,7 +91,7 @@ class pkgDepCache : protected pkgCache::Namespace
* \param follow_suggests If \b true, suggestions of the package
* will be recursively marked.
*/
- void MarkPackage(const pkgCache::PkgIterator &pkg,
+ APT_HIDDEN void MarkPackage(const pkgCache::PkgIterator &pkg,
const pkgCache::VerIterator &ver,
bool const &follow_recommends,
bool const &follow_suggests);
@@ -109,7 +109,7 @@ class pkgDepCache : protected pkgCache::Namespace
*
* \return \b false if an error occurred.
*/
- bool MarkRequired(InRootSetFunc &rootFunc);
+ APT_HIDDEN bool MarkRequired(InRootSetFunc &rootFunc);
/** \brief Set the StateCache::Garbage flag on all packages that
* should be removed.
@@ -120,7 +120,7 @@ class pkgDepCache : protected pkgCache::Namespace
*
* \return \b false if an error occurred.
*/
- bool Sweep();
+ APT_HIDDEN bool Sweep();
public:
@@ -169,7 +169,7 @@ class pkgDepCache : protected pkgCache::Namespace
bool released;
/** Action groups are noncopyable. */
- ActionGroup(const ActionGroup &other);
+ APT_HIDDEN ActionGroup(const ActionGroup &other);
public:
/** \brief Create a new ActionGroup.
*
@@ -396,19 +396,8 @@ class pkgDepCache : protected pkgCache::Namespace
* \param rootFunc A predicate that returns \b true for packages
* that should be added to the root set.
*/
- bool MarkAndSweep(InRootSetFunc &rootFunc)
- {
- return MarkRequired(rootFunc) && Sweep();
- }
-
- bool MarkAndSweep()
- {
- std::auto_ptr<InRootSetFunc> f(GetRootSetFunc());
- if(f.get() != NULL)
- return MarkAndSweep(*f.get());
- else
- return false;
- }
+ bool MarkAndSweep(InRootSetFunc &rootFunc);
+ bool MarkAndSweep();
/** \name State Manipulators
*/
@@ -514,7 +503,7 @@ class pkgDepCache : protected pkgCache::Namespace
bool const rPurge, unsigned long const Depth, bool const FromUser);
private:
- bool IsModeChangeOk(ModeList const mode, PkgIterator const &Pkg,
+ APT_HIDDEN bool IsModeChangeOk(ModeList const mode, PkgIterator const &Pkg,
unsigned long const Depth, bool const FromUser);
};
diff --git a/apt-pkg/edsp.cc b/apt-pkg/edsp.cc
index 0d0418e06..2ba914b16 100644
--- a/apt-pkg/edsp.cc
+++ b/apt-pkg/edsp.cc
@@ -95,12 +95,8 @@ bool EDSP::WriteLimitedScenario(pkgDepCache &Cache, FILE* output,
void EDSP::WriteScenarioVersion(pkgDepCache &Cache, FILE* output, pkgCache::PkgIterator const &Pkg,
pkgCache::VerIterator const &Ver)
{
- pkgRecords Recs(Cache);
- pkgRecords::Parser &rec = Recs.Lookup(Ver.FileList());
- string srcpkg = rec.SourcePkg().empty() ? Pkg.Name() : rec.SourcePkg();
-
fprintf(output, "Package: %s\n", Pkg.Name());
- fprintf(output, "Source: %s\n", srcpkg.c_str());
+ fprintf(output, "Source: %s\n", Ver.SourcePkgName());
fprintf(output, "Architecture: %s\n", Ver.Arch());
fprintf(output, "Version: %s\n", Ver.VerStr());
if (Pkg.CurrentVer() == Ver)
diff --git a/apt-pkg/edsp/edspindexfile.cc b/apt-pkg/edsp/edspindexfile.cc
index 10313fd61..c38f24567 100644
--- a/apt-pkg/edsp/edspindexfile.cc
+++ b/apt-pkg/edsp/edspindexfile.cc
@@ -56,7 +56,7 @@ bool edspIndex::Merge(pkgCacheGenerator &Gen,OpProgress *Prog) const
pkgCache::PkgFileIterator CFile = Gen.GetCurFile();
CFile->Size = Pkg.FileSize();
CFile->mtime = Pkg.ModificationTime();
- map_ptrloc const storage = Gen.WriteUniqString("edsp::scenario");
+ map_stringitem_t const storage = Gen.StoreString(pkgCacheGenerator::MIXED, "edsp::scenario");
CFile->Archive = storage;
if (Gen.MergeList(Parser) == false)
diff --git a/apt-pkg/indexcopy.cc b/apt-pkg/indexcopy.cc
index 854ba1bd7..5fa57fd8b 100644
--- a/apt-pkg/indexcopy.cc
+++ b/apt-pkg/indexcopy.cc
@@ -516,7 +516,7 @@ bool SigVerify::Verify(string prefix, string file, indexRecords *MetaIndex)
return false;
}
- if (!Record->Hash.VerifyFile(prefix+file))
+ if (!Record->Hashes.VerifyFile(prefix+file))
{
_error->Warning(_("Hash mismatch for: %s"),file.c_str());
return false;
@@ -524,8 +524,10 @@ bool SigVerify::Verify(string prefix, string file, indexRecords *MetaIndex)
if(Debug == true)
{
- cout << "File: " << prefix+file << endl;
- cout << "Expected Hash " << Record->Hash.toStr() << endl;
+ cout << "File: " << prefix+file << endl
+ << "Expected Hash " << endl;
+ for (HashStringList::const_iterator hs = Record->Hashes.begin(); hs != Record->Hashes.end(); ++hs)
+ std::cout << "\t- " << hs->toStr() << std::endl;
}
return true;
@@ -791,3 +793,5 @@ bool TranslationsCopy::CopyTranslations(string CDROM,string Name, /*{{{*/
return true;
}
/*}}}*/
+
+APT_CONST IndexCopy::~IndexCopy() {}
diff --git a/apt-pkg/indexcopy.h b/apt-pkg/indexcopy.h
index 43cdb3f0a..701beb075 100644
--- a/apt-pkg/indexcopy.h
+++ b/apt-pkg/indexcopy.h
@@ -53,7 +53,7 @@ class IndexCopy /*{{{*/
bool CopyPackages(std::string CDROM,std::string Name,std::vector<std::string> &List,
pkgCdromStatus *log);
- virtual ~IndexCopy() {};
+ virtual ~IndexCopy();
};
/*}}}*/
class PackageCopy : public IndexCopy /*{{{*/
@@ -93,8 +93,8 @@ class SigVerify /*{{{*/
/** \brief dpointer placeholder (for later in case we need it) */
void *d;
- bool Verify(std::string prefix,std::string file, indexRecords *records);
- bool CopyMetaIndex(std::string CDROM, std::string CDName,
+ APT_HIDDEN bool Verify(std::string prefix,std::string file, indexRecords *records);
+ APT_HIDDEN bool CopyMetaIndex(std::string CDROM, std::string CDName,
std::string prefix, std::string file);
public:
diff --git a/apt-pkg/indexfile.h b/apt-pkg/indexfile.h
index b5c9ac77e..817165f08 100644
--- a/apt-pkg/indexfile.h
+++ b/apt-pkg/indexfile.h
@@ -59,6 +59,7 @@ class pkgIndexFile
const char *Label;
virtual pkgRecords::Parser *CreatePkgParser(pkgCache::PkgFileIterator /*File*/) const {return 0;};
+ virtual pkgSrcRecords::Parser *CreateSrcPkgParser(std::string /*File*/) const {return 0;};
Type();
virtual ~Type() {};
};
diff --git a/apt-pkg/indexrecords.cc b/apt-pkg/indexrecords.cc
index 5353d1098..bf1901e11 100644
--- a/apt-pkg/indexrecords.cc
+++ b/apt-pkg/indexrecords.cc
@@ -37,6 +37,11 @@ APT_PURE string indexRecords::GetSuite() const
return this->Suite;
}
+APT_PURE bool indexRecords::GetSupportsAcquireByHash() const
+{
+ return this->SupportsAcquireByHash;
+}
+
APT_PURE bool indexRecords::CheckDist(const string MaybeDist) const
{
return (this->Dist == MaybeDist
@@ -53,7 +58,7 @@ APT_PURE time_t indexRecords::GetValidUntil() const
return this->ValidUntil;
}
-APT_PURE const indexRecords::checkSum *indexRecords::Lookup(const string MetaKey)
+APT_PURE indexRecords::checkSum *indexRecords::Lookup(const string MetaKey)
{
std::map<std::string, indexRecords::checkSum* >::const_iterator sum = Entries.find(MetaKey);
if (sum == Entries.end())
@@ -86,12 +91,14 @@ bool indexRecords::Load(const string Filename) /*{{{*/
strprintf(ErrorText, _("No sections in Release file %s"), Filename.c_str());
return false;
}
+ // FIXME: find better tag name
+ SupportsAcquireByHash = Section.FindB("Acquire-By-Hash", false);
Suite = Section.FindS("Suite");
Dist = Section.FindS("Codename");
- int i;
- for (i=0;HashString::SupportedHashes()[i] != NULL; i++)
+ bool FoundHashSum = false;
+ for (int i=0;HashString::SupportedHashes()[i] != NULL; i++)
{
if (!Section.Find(HashString::SupportedHashes()[i], Start, End))
continue;
@@ -103,16 +110,28 @@ bool indexRecords::Load(const string Filename) /*{{{*/
{
if (!parseSumData(Start, End, Name, Hash, Size))
return false;
- indexRecords::checkSum *Sum = new indexRecords::checkSum;
- Sum->MetaKeyFilename = Name;
- Sum->Hash = HashString(HashString::SupportedHashes()[i],Hash);
- Sum->Size = Size;
- Entries[Name] = Sum;
+
+ if (Entries.find(Name) == Entries.end())
+ {
+ indexRecords::checkSum *Sum = new indexRecords::checkSum;
+ Sum->MetaKeyFilename = Name;
+ Sum->Size = Size;
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+ Sum->Hash = HashString(HashString::SupportedHashes()[i],Hash);
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic pop
+#endif
+ Entries[Name] = Sum;
+ }
+ Entries[Name]->Hashes.push_back(HashString(HashString::SupportedHashes()[i],Hash));
+ FoundHashSum = true;
}
- break;
}
- if(HashString::SupportedHashes()[i] == NULL)
+ if(FoundHashSum == false)
{
strprintf(ErrorText, _("No Hash entry in Release file %s"), Filename.c_str());
return false;
@@ -234,11 +253,31 @@ bool indexRecords::parseSumData(const char *&Start, const char *End, /*{{{*/
return true;
}
/*}}}*/
-indexRecords::indexRecords()
+
+APT_PURE bool indexRecords::IsAlwaysTrusted() const
+{
+ if (Trusted == ALWAYS_TRUSTED)
+ return true;
+ return false;
+}
+APT_PURE bool indexRecords::IsNeverTrusted() const
+{
+ if (Trusted == NEVER_TRUSTED)
+ return true;
+ return false;
+}
+void indexRecords::SetTrusted(bool const Trusted)
{
+ if (Trusted == true)
+ this->Trusted = ALWAYS_TRUSTED;
+ else
+ this->Trusted = NEVER_TRUSTED;
}
-indexRecords::indexRecords(const string ExpectedDist) :
- ExpectedDist(ExpectedDist), ValidUntil(0)
+indexRecords::indexRecords(const string &ExpectedDist) :
+ Trusted(CHECK_TRUST), d(NULL), ExpectedDist(ExpectedDist), ValidUntil(0),
+ SupportsAcquireByHash(false)
{
}
+
+indexRecords::~indexRecords() {}
diff --git a/apt-pkg/indexrecords.h b/apt-pkg/indexrecords.h
index e31f889ad..88a06779c 100644
--- a/apt-pkg/indexrecords.h
+++ b/apt-pkg/indexrecords.h
@@ -21,45 +21,76 @@
class indexRecords
{
- bool parseSumData(const char *&Start, const char *End, std::string &Name,
+ APT_HIDDEN bool parseSumData(const char *&Start, const char *End, std::string &Name,
std::string &Hash, unsigned long long &Size);
public:
struct checkSum;
std::string ErrorText;
-
+
+ private:
+ enum APT_HIDDEN { ALWAYS_TRUSTED, NEVER_TRUSTED, CHECK_TRUST } Trusted;
+ // dpointer (for later)
+ void * d;
+
protected:
std::string Dist;
std::string Suite;
std::string ExpectedDist;
time_t ValidUntil;
+ bool SupportsAcquireByHash;
std::map<std::string,checkSum *> Entries;
public:
- indexRecords();
- indexRecords(const std::string ExpectedDist);
+ indexRecords(const std::string &ExpectedDist = "");
// Lookup function
- virtual const checkSum *Lookup(const std::string MetaKey);
+ virtual checkSum *Lookup(const std::string MetaKey);
/** \brief tests if a checksum for this file is available */
bool Exists(std::string const &MetaKey) const;
std::vector<std::string> MetaKeys();
virtual bool Load(std::string Filename);
+ virtual bool CheckDist(const std::string MaybeDist) const;
+
std::string GetDist() const;
std::string GetSuite() const;
+ bool GetSupportsAcquireByHash() const;
time_t GetValidUntil() const;
- virtual bool CheckDist(const std::string MaybeDist) const;
std::string GetExpectedDist() const;
- virtual ~indexRecords(){};
+
+ /** \brief check if source is marked as always trusted */
+ bool IsAlwaysTrusted() const;
+ /** \brief check if source is marked as never trusted */
+ bool IsNeverTrusted() const;
+
+ /** \brief sets an explicit trust value
+ *
+ * \b true means that the source should always be considered trusted,
+ * while \b false marks a source as always untrusted, even if we have
+ * a valid signature and everything.
+ */
+ void SetTrusted(bool const Trusted);
+
+ virtual ~indexRecords();
};
+#if __GNUC__ >= 4
+ // ensure that con- & de-structor don't trigger this warning
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
struct indexRecords::checkSum
{
std::string MetaKeyFilename;
- HashString Hash;
+ HashStringList Hashes;
unsigned long long Size;
+
+ APT_DEPRECATED HashString Hash;
};
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic pop
+#endif
#endif
diff --git a/apt-pkg/init.cc b/apt-pkg/init.cc
index 241628632..d04c51621 100644
--- a/apt-pkg/init.cc
+++ b/apt-pkg/init.cc
@@ -88,9 +88,19 @@ bool pkgInitConfig(Configuration &Cnf)
Cnf.Set("Dir::Ignore-Files-Silently::", "\\.orig$");
Cnf.Set("Dir::Ignore-Files-Silently::", "\\.distUpgrade$");
+ // Repository security
+ // FIXME: this is set to "true" for backward compatiblity, once
+ // jessie is out we want to change this to "false" to
+ // improve security
+ Cnf.CndSet("Acquire::AllowInsecureRepositories", true);
+ Cnf.CndSet("Acquire::AllowDowngradeToInsecureRepositories", false);
+
// Default cdrom mount point
Cnf.CndSet("Acquire::cdrom::mount", "/media/cdrom/");
+ // The default user we drop to in the methods
+ Cnf.CndSet("APT::Sandbox::User", "_apt");
+
bool Res = true;
// Read an alternate config file
diff --git a/apt-pkg/install-progress.cc b/apt-pkg/install-progress.cc
index cf6c85912..5ea8bf4d0 100644
--- a/apt-pkg/install-progress.cc
+++ b/apt-pkg/install-progress.cc
@@ -21,6 +21,8 @@
namespace APT {
namespace Progress {
+PackageManager::PackageManager() : d(NULL), percentage(0.0), last_reported_progress(-1) {}
+PackageManager::~PackageManager() {}
/* Return a APT::Progress::PackageManager based on the global
* apt configuration (i.e. APT::Status-Fd and APT::Status-deb822-Fd)
diff --git a/apt-pkg/install-progress.h b/apt-pkg/install-progress.h
index 5d1a20e9b..d8b4a5c82 100644
--- a/apt-pkg/install-progress.h
+++ b/apt-pkg/install-progress.h
@@ -26,9 +26,8 @@ namespace Progress {
int last_reported_progress;
public:
- PackageManager()
- : percentage(0.0), last_reported_progress(-1) {};
- virtual ~PackageManager() {};
+ PackageManager();
+ virtual ~PackageManager();
/* Global Start/Stop */
virtual void Start(int /*child_pty*/=-1) {};
@@ -120,7 +119,7 @@ namespace Progress {
class PackageManagerFancy : public PackageManager
{
private:
- static void staticSIGWINCH(int);
+ APT_HIDDEN static void staticSIGWINCH(int);
static std::vector<PackageManagerFancy*> instances;
APT_HIDDEN bool DrawStatusLine();
diff --git a/apt-pkg/metaindex.h b/apt-pkg/metaindex.h
index ffabaadbf..7c4d0c1aa 100644
--- a/apt-pkg/metaindex.h
+++ b/apt-pkg/metaindex.h
@@ -53,7 +53,7 @@ class metaIndex
metaIndex(std::string const &URI, std::string const &Dist,
char const * const Type)
- : Indexes(NULL), Type(Type), URI(URI), Dist(Dist)
+ : Indexes(NULL), Type(Type), URI(URI), Dist(Dist), Trusted(false)
{
/* nothing */
}
diff --git a/apt-pkg/packagemanager.cc b/apt-pkg/packagemanager.cc
index 249542c68..101912f9d 100644
--- a/apt-pkg/packagemanager.cc
+++ b/apt-pkg/packagemanager.cc
@@ -28,6 +28,7 @@
#include <apt-pkg/pkgcache.h>
#include <apt-pkg/cacheiterators.h>
#include <apt-pkg/strutl.h>
+#include <apt-pkg/install-progress.h>
#include <stddef.h>
#include <list>
@@ -1079,7 +1080,7 @@ pkgPackageManager::DoInstallPostFork(APT::Progress::PackageManager *progress)
return Failed;
return Res;
-};
+}
#else
pkgPackageManager::OrderResult
pkgPackageManager::DoInstallPostFork(int statusFd)
diff --git a/apt-pkg/packagemanager.h b/apt-pkg/packagemanager.h
index d72790b6e..5bcd2045d 100644
--- a/apt-pkg/packagemanager.h
+++ b/apt-pkg/packagemanager.h
@@ -44,6 +44,11 @@ class pkgDepCache;
class pkgSourceList;
class pkgOrderList;
class pkgRecords;
+namespace APT {
+ namespace Progress {
+ class PackageManager;
+ }
+}
class pkgPackageManager : protected pkgCache::Namespace
@@ -93,6 +98,7 @@ class pkgPackageManager : protected pkgCache::Namespace
virtual bool Remove(PkgIterator /*Pkg*/,bool /*Purge*/=false) {return false;};
#if (APT_PKG_MAJOR >= 4 && APT_PKG_MINOR >= 13)
virtual bool Go(APT::Progress::PackageManager * /*progress*/) {return true;};
+ virtual bool Go(int /*statusFd*/=-1) {return true;};
#else
virtual bool Go(int /*statusFd*/=-1) {return true;};
#endif
diff --git a/apt-pkg/pkgcache.cc b/apt-pkg/pkgcache.cc
index 58a63459f..572685ba5 100644
--- a/apt-pkg/pkgcache.cc
+++ b/apt-pkg/pkgcache.cc
@@ -54,12 +54,8 @@ pkgCache::Header::Header()
/* Whenever the structures change the major version should be bumped,
whenever the generator changes the minor version should be bumped. */
- MajorVersion = 8;
-#if (APT_PKG_MAJOR >= 4 && APT_PKG_MINOR >= 13)
- MinorVersion = 2;
-#else
- MinorVersion = 1;
-#endif
+ MajorVersion = 10;
+ MinorVersion = 0;
Dirty = false;
HeaderSz = sizeof(pkgCache::Header);
@@ -86,11 +82,10 @@ pkgCache::Header::Header()
MaxDescFileSize = 0;
FileList = 0;
- StringList = 0;
VerSysName = 0;
Architecture = 0;
- memset(PkgHashTable,0,sizeof(PkgHashTable));
- memset(GrpHashTable,0,sizeof(GrpHashTable));
+ Architectures = 0;
+ HashTableSize = _config->FindI("APT::Cache-HashTableSize", 10 * 1048);
memset(Pools,0,sizeof(Pools));
CacheFileSize = 0;
@@ -145,7 +140,6 @@ bool pkgCache::ReMap(bool const &Errorchecks)
DescP = (Description *)Map.Data();
ProvideP = (Provides *)Map.Data();
DepP = (Dependency *)Map.Data();
- StringItemP = (StringItem *)Map.Data();
StrP = (char *)Map.Data();
if (Errorchecks == false)
@@ -168,15 +162,23 @@ bool pkgCache::ReMap(bool const &Errorchecks)
if (Map.Size() < HeaderP->CacheFileSize)
return _error->Error(_("The package cache file is corrupted, it is too small"));
+ if (HeaderP->VerSysName == 0 || HeaderP->Architecture == 0 || HeaderP->Architectures == 0)
+ return _error->Error(_("The package cache file is corrupted"));
+
// Locate our VS..
- if (HeaderP->VerSysName == 0 ||
- (VS = pkgVersioningSystem::GetVS(StrP + HeaderP->VerSysName)) == 0)
+ if ((VS = pkgVersioningSystem::GetVS(StrP + HeaderP->VerSysName)) == 0)
return _error->Error(_("This APT does not support the versioning system '%s'"),StrP + HeaderP->VerSysName);
- // Chcek the arhcitecture
- if (HeaderP->Architecture == 0 ||
- _config->Find("APT::Architecture") != StrP + HeaderP->Architecture)
- return _error->Error(_("The package cache was built for a different architecture"));
+ // Check the architecture
+ std::vector<std::string> archs = APT::Configuration::getArchitectures();
+ std::vector<std::string>::const_iterator a = archs.begin();
+ std::string list = *a;
+ for (++a; a != archs.end(); ++a)
+ list.append(",").append(*a);
+ if (_config->Find("APT::Architecture") != StrP + HeaderP->Architecture ||
+ list != StrP + HeaderP->Architectures)
+ return _error->Error(_("The package cache was built for different architectures: %s vs %s"), StrP + HeaderP->Architectures, list.c_str());
+
return true;
}
/*}}}*/
@@ -185,20 +187,20 @@ bool pkgCache::ReMap(bool const &Errorchecks)
/* This is used to generate the hash entries for the HashTable. With my
package list from bo this function gets 94% table usage on a 512 item
table (480 used items) */
-unsigned long pkgCache::sHash(const string &Str) const
+map_id_t pkgCache::sHash(const string &Str) const
{
unsigned long Hash = 0;
for (string::const_iterator I = Str.begin(); I != Str.end(); ++I)
Hash = 41 * Hash + tolower_ascii(*I);
- return Hash % _count(HeaderP->PkgHashTable);
+ return Hash % HeaderP->HashTableSize;
}
-unsigned long pkgCache::sHash(const char *Str) const
+map_id_t pkgCache::sHash(const char *Str) const
{
unsigned long Hash = tolower_ascii(*Str);
for (const char *I = Str + 1; *I != 0; ++I)
Hash = 41 * Hash + tolower_ascii(*I);
- return Hash % _count(HeaderP->PkgHashTable);
+ return Hash % HeaderP->HashTableSize;
}
/*}}}*/
// Cache::SingleArchFindPkg - Locate a package by name /*{{{*/
@@ -209,13 +211,10 @@ unsigned long pkgCache::sHash(const char *Str) const
pkgCache::PkgIterator pkgCache::SingleArchFindPkg(const string &Name)
{
// Look at the hash bucket
- Package *Pkg = PkgP + HeaderP->PkgHashTable[Hash(Name)];
- for (; Pkg != PkgP; Pkg = PkgP + Pkg->NextPackage)
+ Package *Pkg = PkgP + HeaderP->PkgHashTable()[Hash(Name)];
+ for (; Pkg != PkgP; Pkg = PkgP + Pkg->Next)
{
- if (unlikely(Pkg->Name == 0))
- continue;
-
- int const cmp = strcasecmp(Name.c_str(), StrP + Pkg->Name);
+ int const cmp = strcmp(Name.c_str(), StrP + (GrpP + Pkg->Group)->Name);
if (cmp == 0)
return PkgIterator(*this, Pkg);
else if (cmp < 0)
@@ -274,12 +273,9 @@ pkgCache::GrpIterator pkgCache::FindGrp(const string &Name) {
return GrpIterator(*this,0);
// Look at the hash bucket for the group
- Group *Grp = GrpP + HeaderP->GrpHashTable[sHash(Name)];
+ Group *Grp = GrpP + HeaderP->GrpHashTable()[sHash(Name)];
for (; Grp != GrpP; Grp = GrpP + Grp->Next) {
- if (unlikely(Grp->Name == 0))
- continue;
-
- int const cmp = strcasecmp(Name.c_str(), StrP + Grp->Name);
+ int const cmp = strcmp(Name.c_str(), StrP + Grp->Name);
if (cmp == 0)
return GrpIterator(*this, Grp);
else if (cmp < 0)
@@ -356,19 +352,15 @@ pkgCache::PkgIterator pkgCache::GrpIterator::FindPkg(string Arch) const {
last one we check, so we do it now. */
if (Arch == "native" || Arch == myArch || Arch == "all") {
pkgCache::Package *Pkg = Owner->PkgP + S->LastPackage;
- if (strcasecmp(myArch, Owner->StrP + Pkg->Arch) == 0)
+ if (strcmp(myArch, Owner->StrP + Pkg->Arch) == 0)
return PkgIterator(*Owner, Pkg);
Arch = myArch;
}
- /* Iterate over the list to find the matching arch
- unfortunately this list includes "package noise"
- (= different packages with same calculated hash),
- so we need to check the name also */
+ // Iterate over the list to find the matching arch
for (pkgCache::Package *Pkg = PackageList(); Pkg != Owner->PkgP;
- Pkg = Owner->PkgP + Pkg->NextPackage) {
- if (S->Name == Pkg->Name &&
- stringcasecmp(Arch, Owner->StrP + Pkg->Arch) == 0)
+ Pkg = Owner->PkgP + Pkg->Next) {
+ if (stringcmp(Arch, Owner->StrP + Pkg->Arch) == 0)
return PkgIterator(*Owner, Pkg);
if ((Owner->PkgP + S->LastPackage) == Pkg)
break;
@@ -415,7 +407,7 @@ pkgCache::PkgIterator pkgCache::GrpIterator::NextPkg(pkgCache::PkgIterator const
if (S->LastPackage == LastPkg.Index())
return PkgIterator(*Owner, 0);
- return PkgIterator(*Owner, Owner->PkgP + LastPkg->NextPackage);
+ return PkgIterator(*Owner, Owner->PkgP + LastPkg->Next);
}
/*}}}*/
// GrpIterator::operator ++ - Postfix incr /*{{{*/
@@ -428,10 +420,10 @@ void pkgCache::GrpIterator::operator ++(int)
S = Owner->GrpP + S->Next;
// Follow the hash table
- while (S == Owner->GrpP && (HashIndex+1) < (signed)_count(Owner->HeaderP->GrpHashTable))
+ while (S == Owner->GrpP && (HashIndex+1) < (signed)Owner->HeaderP->HashTableSize)
{
HashIndex++;
- S = Owner->GrpP + Owner->HeaderP->GrpHashTable[HashIndex];
+ S = Owner->GrpP + Owner->HeaderP->GrpHashTable()[HashIndex];
}
}
/*}}}*/
@@ -442,13 +434,13 @@ void pkgCache::PkgIterator::operator ++(int)
{
// Follow the current links
if (S != Owner->PkgP)
- S = Owner->PkgP + S->NextPackage;
+ S = Owner->PkgP + S->Next;
// Follow the hash table
- while (S == Owner->PkgP && (HashIndex+1) < (signed)_count(Owner->HeaderP->PkgHashTable))
+ while (S == Owner->PkgP && (HashIndex+1) < (signed)Owner->HeaderP->HashTableSize)
{
HashIndex++;
- S = Owner->PkgP + Owner->HeaderP->PkgHashTable[HashIndex];
+ S = Owner->PkgP + Owner->HeaderP->PkgHashTable()[HashIndex];
}
}
/*}}}*/
@@ -524,7 +516,10 @@ operator<<(std::ostream& out, pkgCache::PkgIterator Pkg)
out << " -> " << candidate;
if ( newest != "none" && candidate != newest)
out << " | " << newest;
- out << " > ( " << string(Pkg.Section()==0?"none":Pkg.Section()) << " )";
+ if (Pkg->VersionList == 0)
+ out << " > ( none )";
+ else
+ out << " > ( " << string(Pkg.VersionList().Section()==0?"unknown":Pkg.VersionList().Section()) << " )";
return out;
}
/*}}}*/
@@ -1031,8 +1026,14 @@ bool pkgCache::PrvIterator::IsMultiArchImplicit() const
{
pkgCache::PkgIterator const Owner = OwnerPkg();
pkgCache::PkgIterator const Parent = ParentPkg();
- if (strcmp(Owner.Arch(), Parent.Arch()) != 0 || Owner->Name == Parent->Name)
+ if (strcmp(Owner.Arch(), Parent.Arch()) != 0 || Owner.Group()->Name == Parent.Group()->Name)
return true;
return false;
}
/*}}}*/
+APT_DEPRECATED APT_PURE const char * pkgCache::PkgIterator::Section() const {/*{{{*/
+ if (S->VersionList == 0)
+ return 0;
+ return VersionList().Section();
+}
+ /*}}}*/
diff --git a/apt-pkg/pkgcache.h b/apt-pkg/pkgcache.h
index 5e8a9630a..4f8568205 100644
--- a/apt-pkg/pkgcache.h
+++ b/apt-pkg/pkgcache.h
@@ -79,11 +79,23 @@
#include <string>
#include <time.h>
+#include <stdint.h>
#ifndef APT_8_CLEANER_HEADERS
using std::string;
#endif
+// storing file sizes of indexes, which are way below 4 GB for now
+typedef uint32_t map_filesize_t;
+// each package/group/dependency gets an id
+typedef uint32_t map_id_t;
+// some files get an id, too, but in far less absolute numbers
+typedef uint16_t map_fileid_t;
+// relative pointer from cache start
+typedef uint32_t map_pointer_t;
+// same as the previous, but documented to be to a string item
+typedef map_pointer_t map_stringitem_t;
+
class pkgVersioningSystem;
class pkgCache /*{{{*/
{
@@ -97,7 +109,6 @@ class pkgCache /*{{{*/
struct Description;
struct Provides;
struct Dependency;
- struct StringItem;
struct VerFile;
struct DescFile;
@@ -138,7 +149,7 @@ class pkgCache /*{{{*/
/** \brief priority of a package version
Zero is used for unparsable or absent Priority fields. */
- enum VerPriority {Important=1,Required=2,Standard=3,Optional=4,Extra=5};
+ enum VerPriority {Required=1,Important=2,Standard=3,Optional=4,Extra=5};
enum PkgSelectedState {Unknown=0,Install=1,Hold=2,DeInstall=3,Purge=4};
enum PkgInstState {Ok=0,ReInstReq=1,HoldInst=2,HoldReInstReq=3};
enum PkgCurrentState {NotInstalled=0,UnPacked=1,HalfConfigured=2,
@@ -158,8 +169,8 @@ class pkgCache /*{{{*/
std::string CacheFile;
MMap &Map;
- unsigned long sHash(const std::string &S) const APT_PURE;
- unsigned long sHash(const char *S) const APT_PURE;
+ map_id_t sHash(const std::string &S) const APT_PURE;
+ map_id_t sHash(const char *S) const APT_PURE;
public:
@@ -174,7 +185,6 @@ class pkgCache /*{{{*/
Description *DescP;
Provides *ProvideP;
Dependency *DepP;
- StringItem *StringItemP;
char *StrP;
virtual bool ReMap(bool const &Errorchecks = true);
@@ -183,8 +193,8 @@ class pkgCache /*{{{*/
inline void *DataEnd() {return ((unsigned char *)Map.Data()) + Map.Size();}
// String hashing function (512 range)
- inline unsigned long Hash(const std::string &S) const {return sHash(S);}
- inline unsigned long Hash(const char *S) const {return sHash(S);}
+ inline map_id_t Hash(const std::string &S) const {return sHash(S);}
+ inline map_id_t Hash(const char *S) const {return sHash(S);}
// Useful transformation things
const char *Priority(unsigned char Priority);
@@ -218,7 +228,7 @@ class pkgCache /*{{{*/
private:
bool MultiArchEnabled;
- PkgIterator SingleArchFindPkg(const std::string &Name);
+ APT_HIDDEN PkgIterator SingleArchFindPkg(const std::string &Name);
};
/*}}}*/
// Header structure /*{{{*/
@@ -263,35 +273,31 @@ struct pkgCache::Header
These indicate the number of each structure contained in the cache.
PackageCount is especially useful for generating user state structures.
See Package::Id for more info. */
- unsigned long GroupCount;
- unsigned long PackageCount;
- unsigned long VersionCount;
- unsigned long DescriptionCount;
- unsigned long DependsCount;
- unsigned long PackageFileCount;
- unsigned long VerFileCount;
- unsigned long DescFileCount;
- unsigned long ProvidesCount;
+ map_id_t GroupCount;
+ map_id_t PackageCount;
+ map_id_t VersionCount;
+ map_id_t DescriptionCount;
+ map_id_t DependsCount;
+ map_fileid_t PackageFileCount;
+ map_fileid_t VerFileCount;
+ map_fileid_t DescFileCount;
+ map_id_t ProvidesCount;
/** \brief index of the first PackageFile structure
The PackageFile structures are singly linked lists that represent
all package files that have been merged into the cache. */
- map_ptrloc FileList;
- /** \brief index of the first StringItem structure
-
- The cache contains a list of all the unique strings (StringItems).
- The parser reads this list into memory so it can match strings
- against it.*/
- map_ptrloc StringList;
+ map_pointer_t FileList;
/** \brief String representing the version system used */
- map_ptrloc VerSysName;
- /** \brief Architecture(s) the cache was built against */
- map_ptrloc Architecture;
+ map_pointer_t VerSysName;
+ /** \brief native architecture the cache was built against */
+ map_pointer_t Architecture;
+ /** \brief all architectures the cache was built against */
+ map_pointer_t Architectures;
/** \brief The maximum size of a raw entry from the original Package file */
- unsigned long MaxVerFileSize;
+ map_filesize_t MaxVerFileSize;
/** \brief The maximum size of a raw entry from the original Translation file */
- unsigned long MaxDescFileSize;
+ map_filesize_t MaxDescFileSize;
/** \brief The Pool structures manage the allocation pools that the generator uses
@@ -302,23 +308,23 @@ struct pkgCache::Header
stores this information so future additions can make use of any unused pool
blocks. */
DynamicMMap::Pool Pools[9];
-
+
/** \brief hash tables providing rapid group/package name lookup
- Each group/package name is inserted into the hash table using pkgCache::Hash(const &string)
+ Each group/package name is inserted into a hash table using pkgCache::Hash(const &string)
By iterating over each entry in the hash table it is possible to iterate over
the entire list of packages. Hash Collisions are handled with a singly linked
list of packages based at the hash item. The linked list contains only
packages that match the hashing function.
In the PkgHashTable is it possible that multiple packages have the same name -
these packages are stored as a sequence in the list.
-
- Beware: The Hashmethod assumes that the hash table sizes are equal */
- map_ptrloc PkgHashTable[2*1048];
- map_ptrloc GrpHashTable[2*1048];
+ The size of both tables is the same. */
+ unsigned int HashTableSize;
+ map_pointer_t * PkgHashTable() const { return (map_pointer_t*) (this + 1); }
+ map_pointer_t * GrpHashTable() const { return PkgHashTable() + HashTableSize; }
/** \brief Size of the complete cache file */
- unsigned long CacheFileSize;
+ unsigned long long CacheFileSize;
bool CheckSizes(Header &Against) const APT_PURE;
Header();
@@ -334,17 +340,17 @@ struct pkgCache::Header
struct pkgCache::Group
{
/** \brief Name of the group */
- map_ptrloc Name; // StringItem
+ map_stringitem_t Name;
// Linked List
/** \brief Link to the first package which belongs to the group */
- map_ptrloc FirstPackage; // Package
+ map_pointer_t FirstPackage; // Package
/** \brief Link to the last package which belongs to the group */
- map_ptrloc LastPackage; // Package
+ map_pointer_t LastPackage; // Package
/** \brief Link to the next Group */
- map_ptrloc Next; // Group
+ map_pointer_t Next; // Group
/** \brief unique sequel ID */
- unsigned int ID;
+ map_id_t ID;
};
/*}}}*/
@@ -362,10 +368,13 @@ struct pkgCache::Group
*/
struct pkgCache::Package
{
- /** \brief Name of the package */
- map_ptrloc Name; // StringItem
+ /** \brief Name of the package
+ * Note that the access method Name() will remain. It is just this data member
+ * deprecated as this information is already stored and available via the
+ * associated Group – so it is wasting precious binary cache space */
+ APT_DEPRECATED map_stringitem_t Name;
/** \brief Architecture of the package */
- map_ptrloc Arch; // StringItem
+ map_stringitem_t Arch;
/** \brief Base of a singly linked list of versions
Each structure represents a unique version of the package.
@@ -375,24 +384,19 @@ struct pkgCache::Package
versions of a package can be cleanly handled by the system.
Furthermore, this linked list is guaranteed to be sorted
from Highest version to lowest version with no duplicate entries. */
- map_ptrloc VersionList; // Version
+ map_pointer_t VersionList; // Version
/** \brief index to the installed version */
- map_ptrloc CurrentVer; // Version
- /** \brief indicates the deduced section
-
- Should be the index to the string "Unknown" or to the section
- of the last parsed item. */
- map_ptrloc Section; // StringItem
+ map_pointer_t CurrentVer; // Version
/** \brief index of the group this package belongs to */
- map_ptrloc Group; // Group the Package belongs to
+ map_pointer_t Group; // Group the Package belongs to
// Linked list
/** \brief Link to the next package in the same bucket */
- map_ptrloc NextPackage; // Package
+ map_pointer_t Next; // Package
/** \brief List of all dependencies on this package */
- map_ptrloc RevDepends; // Dependency
+ map_pointer_t RevDepends; // Dependency
/** \brief List of all "packages" this package provide */
- map_ptrloc ProvidesList; // Provides
+ map_pointer_t ProvidesList; // Provides
// Install/Remove/Purge etc
/** \brief state that the user wishes the package to be in */
@@ -412,7 +416,7 @@ struct pkgCache::Package
This allows clients to create an array of size PackageCount and use it to store
state information for the package map. For instance the status file emitter uses
this to track which packages have been emitted already. */
- unsigned int ID;
+ map_id_t ID;
/** \brief some useful indicators of the package's state */
unsigned long Flags;
};
@@ -426,30 +430,30 @@ struct pkgCache::Package
struct pkgCache::PackageFile
{
/** \brief physical disk file that this PackageFile represents */
- map_ptrloc FileName; // StringItem
+ map_stringitem_t FileName;
/** \brief the release information
Please see the files document for a description of what the
release information means. */
- map_ptrloc Archive; // StringItem
- map_ptrloc Codename; // StringItem
- map_ptrloc Component; // StringItem
- map_ptrloc Version; // StringItem
- map_ptrloc Origin; // StringItem
- map_ptrloc Label; // StringItem
- map_ptrloc Architecture; // StringItem
+ map_stringitem_t Archive;
+ map_stringitem_t Codename;
+ map_stringitem_t Component;
+ map_stringitem_t Version;
+ map_stringitem_t Origin;
+ map_stringitem_t Label;
+ map_stringitem_t Architecture;
/** \brief The site the index file was fetched from */
- map_ptrloc Site; // StringItem
+ map_stringitem_t Site;
/** \brief indicates what sort of index file this is
@TODO enumerate at least the possible indexes */
- map_ptrloc IndexType; // StringItem
+ map_stringitem_t IndexType;
/** \brief Size of the file
Used together with the modification time as a
simple check to ensure that the Packages
file has not been altered since Cache generation. */
- unsigned long Size;
+ map_filesize_t Size;
/** \brief Modification time for the file */
time_t mtime;
@@ -458,9 +462,9 @@ struct pkgCache::PackageFile
// Linked list
/** \brief Link to the next PackageFile in the Cache */
- map_ptrloc NextFile; // PackageFile
+ map_pointer_t NextFile; // PackageFile
/** \brief unique sequel ID */
- unsigned int ID;
+ map_fileid_t ID;
};
/*}}}*/
// VerFile structure /*{{{*/
@@ -471,13 +475,13 @@ struct pkgCache::PackageFile
struct pkgCache::VerFile
{
/** \brief index of the package file that this version was found in */
- map_ptrloc File; // PackageFile
+ map_pointer_t File; // PackageFile
/** \brief next step in the linked list */
- map_ptrloc NextFile; // PkgVerFile
+ map_pointer_t NextFile; // PkgVerFile
/** \brief position in the package file */
- map_ptrloc Offset; // File offset
+ map_filesize_t Offset; // File offset
/** @TODO document pkgCache::VerFile::Size */
- unsigned long Size;
+ map_filesize_t Size;
};
/*}}}*/
// DescFile structure /*{{{*/
@@ -485,13 +489,13 @@ struct pkgCache::VerFile
struct pkgCache::DescFile
{
/** \brief index of the file that this description was found in */
- map_ptrloc File; // PackageFile
+ map_pointer_t File; // PackageFile
/** \brief next step in the linked list */
- map_ptrloc NextFile; // PkgVerFile
+ map_pointer_t NextFile; // PkgVerFile
/** \brief position in the file */
- map_ptrloc Offset; // File offset
+ map_filesize_t Offset; // File offset
/** @TODO document pkgCache::DescFile::Size */
- unsigned long Size;
+ map_filesize_t Size;
};
/*}}}*/
// Version structure /*{{{*/
@@ -503,9 +507,15 @@ struct pkgCache::DescFile
struct pkgCache::Version
{
/** \brief complete version string */
- map_ptrloc VerStr; // StringItem
+ map_stringitem_t VerStr;
/** \brief section this version is filled in */
- map_ptrloc Section; // StringItem
+ map_stringitem_t Section;
+ /** \brief source package name this version comes from
+ Always contains the name, even if it is the same as the binary name */
+ map_stringitem_t SourcePkgName;
+ /** \brief source version this version comes from
+ Always contains the version string, even if it is the same as the binary version */
+ map_stringitem_t SourceVerStr;
/** \brief Multi-Arch capabilities of a package version */
enum VerMultiArch { None = 0, /*!< is the default and doesn't trigger special behaviour */
@@ -527,33 +537,33 @@ struct pkgCache::Version
applies to. If FileList is 0 then this is a blank version.
The structure should also have a 0 in all other fields excluding
pkgCache::Version::VerStr and Possibly pkgCache::Version::NextVer. */
- map_ptrloc FileList; // VerFile
+ map_pointer_t FileList; // VerFile
/** \brief next (lower or equal) version in the linked list */
- map_ptrloc NextVer; // Version
+ map_pointer_t NextVer; // Version
/** \brief next description in the linked list */
- map_ptrloc DescriptionList; // Description
+ map_pointer_t DescriptionList; // Description
/** \brief base of the dependency list */
- map_ptrloc DependsList; // Dependency
+ map_pointer_t DependsList; // Dependency
/** \brief links to the owning package
This allows reverse dependencies to determine the package */
- map_ptrloc ParentPkg; // Package
+ map_pointer_t ParentPkg; // Package
/** \brief list of pkgCache::Provides */
- map_ptrloc ProvidesList; // Provides
+ map_pointer_t ProvidesList; // Provides
/** \brief archive size for this version
For Debian this is the size of the .deb file. */
- unsigned long long Size; // These are the .deb size
+ uint64_t Size; // These are the .deb size
/** \brief uncompressed size for this version */
- unsigned long long InstalledSize;
+ uint64_t InstalledSize;
/** \brief characteristic value representing this version
No two packages in existence should have the same VerStr
and Hash with different contents. */
unsigned short Hash;
/** \brief unique sequel ID */
- unsigned int ID;
+ map_id_t ID;
/** \brief parsed priority value */
unsigned char Priority;
};
@@ -566,22 +576,22 @@ struct pkgCache::Description
If the value has a 0 length then this is read using the Package
file else the Translation-CODE file is used. */
- map_ptrloc language_code; // StringItem
+ map_stringitem_t language_code;
/** \brief MD5sum of the original description
Used to map Translations of a description to a version
and to check that the Translation is up-to-date. */
- map_ptrloc md5sum; // StringItem
+ map_stringitem_t md5sum;
/** @TODO document pkgCache::Description::FileList */
- map_ptrloc FileList; // DescFile
+ map_pointer_t FileList; // DescFile
/** \brief next translation for this description */
- map_ptrloc NextDesc; // Description
+ map_pointer_t NextDesc; // Description
/** \brief the text is a description of this package */
- map_ptrloc ParentPkg; // Package
+ map_pointer_t ParentPkg; // Package
/** \brief unique sequel ID */
- unsigned int ID;
+ map_id_t ID;
};
/*}}}*/
// Dependency structure /*{{{*/
@@ -594,21 +604,21 @@ struct pkgCache::Description
struct pkgCache::Dependency
{
/** \brief string of the version the dependency is applied against */
- map_ptrloc Version; // StringItem
+ map_stringitem_t Version;
/** \brief index of the package this depends applies to
The generator will - if the package does not already exist -
create a blank (no version records) package. */
- map_ptrloc Package; // Package
+ map_pointer_t Package; // Package
/** \brief next dependency of this version */
- map_ptrloc NextDepends; // Dependency
+ map_pointer_t NextDepends; // Dependency
/** \brief next reverse dependency of this package */
- map_ptrloc NextRevDepends; // Dependency
+ map_pointer_t NextRevDepends; // Dependency
/** \brief version of the package which has the reverse depends */
- map_ptrloc ParentVer; // Version
+ map_pointer_t ParentVer; // Version
/** \brief unique sequel ID */
- map_ptrloc ID;
+ map_id_t ID;
/** \brief Dependency type - Depends, Recommends, Conflicts, etc */
unsigned char Type;
/** \brief comparison operator specified on the depends line
@@ -629,39 +639,21 @@ struct pkgCache::Dependency
struct pkgCache::Provides
{
/** \brief index of the package providing this */
- map_ptrloc ParentPkg; // Package
+ map_pointer_t ParentPkg; // Package
/** \brief index of the version this provide line applies to */
- map_ptrloc Version; // Version
+ map_pointer_t Version; // Version
/** \brief version in the provides line (if any)
This version allows dependencies to depend on specific versions of a
Provides, as well as allowing Provides to override existing packages.
This is experimental. Note that Debian doesn't allow versioned provides */
- map_ptrloc ProvideVersion; // StringItem
+ map_stringitem_t ProvideVersion;
/** \brief next provides (based of package) */
- map_ptrloc NextProvides; // Provides
+ map_pointer_t NextProvides; // Provides
/** \brief next provides (based of version) */
- map_ptrloc NextPkgProv; // Provides
+ map_pointer_t NextPkgProv; // Provides
};
/*}}}*/
-// StringItem structure /*{{{*/
-/** \brief used for generating single instances of strings
-
- Some things like Section Name are are useful to have as unique tags.
- It is part of a linked list based at pkgCache::Header::StringList
-
- All strings are simply inlined any place in the file that is natural
- for the writer. The client should make no assumptions about the positioning
- of strings. All StringItems should be null-terminated. */
-struct pkgCache::StringItem
-{
- /** \brief string this refers to */
- map_ptrloc String; // StringItem
- /** \brief Next link in the chain */
- map_ptrloc NextItem; // StringItem
-};
- /*}}}*/
-
inline char const * pkgCache::NativeArch()
{ return StrP + HeaderP->Architecture; }
diff --git a/apt-pkg/pkgcachegen.cc b/apt-pkg/pkgcachegen.cc
index 810f0b022..9e6931fa6 100644
--- a/apt-pkg/pkgcachegen.cc
+++ b/apt-pkg/pkgcachegen.cc
@@ -57,8 +57,7 @@ pkgCacheGenerator::pkgCacheGenerator(DynamicMMap *pMap,OpProgress *Prog) :
FoundFileDeps(0)
{
CurrentFile = 0;
- memset(UniqHash,0,sizeof(UniqHash));
-
+
if (_error->PendingError() == true)
return;
@@ -73,14 +72,35 @@ pkgCacheGenerator::pkgCacheGenerator(DynamicMMap *pMap,OpProgress *Prog) :
// Starting header
*Cache.HeaderP = pkgCache::Header();
- map_ptrloc const idxVerSysName = WriteStringInMap(_system->VS->Label);
+
+ // make room for the hashtables for packages and groups
+ if (Map.RawAllocate(2 * (Cache.HeaderP->HashTableSize * sizeof(map_pointer_t))) == 0)
+ return;
+
+ map_stringitem_t const idxVerSysName = WriteStringInMap(_system->VS->Label);
+ if (unlikely(idxVerSysName == 0))
+ return;
Cache.HeaderP->VerSysName = idxVerSysName;
- // this pointer is set in ReMap, but we need it now for WriteUniqString
- Cache.StringItemP = (pkgCache::StringItem *)Map.Data();
- map_ptrloc const idxArchitecture = WriteUniqString(_config->Find("APT::Architecture"));
- Cache.HeaderP->Architecture = idxArchitecture;
- if (unlikely(idxVerSysName == 0 || idxArchitecture == 0))
+ map_stringitem_t const idxArchitecture = StoreString(MIXED, _config->Find("APT::Architecture"));
+ if (unlikely(idxArchitecture == 0))
return;
+ Cache.HeaderP->Architecture = idxArchitecture;
+
+ std::vector<std::string> archs = APT::Configuration::getArchitectures();
+ if (archs.size() > 1)
+ {
+ std::vector<std::string>::const_iterator a = archs.begin();
+ std::string list = *a;
+ for (++a; a != archs.end(); ++a)
+ list.append(",").append(*a);
+ map_stringitem_t const idxArchitectures = WriteStringInMap(list);
+ if (unlikely(idxArchitectures == 0))
+ return;
+ Cache.HeaderP->Architectures = idxArchitectures;
+ }
+ else
+ Cache.HeaderP->Architectures = idxArchitecture;
+
Cache.ReMap();
}
else
@@ -92,9 +112,9 @@ pkgCacheGenerator::pkgCacheGenerator(DynamicMMap *pMap,OpProgress *Prog) :
{
_error->Error(_("Cache has an incompatible versioning system"));
return;
- }
+ }
}
-
+
Cache.HeaderP->Dirty = true;
Map.Sync(0,sizeof(pkgCache::Header));
}
@@ -126,10 +146,6 @@ void pkgCacheGenerator::ReMap(void const * const oldMap, void const * const newM
CurrentFile += (pkgCache::PackageFile const * const) newMap - (pkgCache::PackageFile const * const) oldMap;
- for (size_t i = 0; i < _count(UniqHash); ++i)
- if (UniqHash[i] != 0)
- UniqHash[i] += (pkgCache::StringItem const * const) newMap - (pkgCache::StringItem const * const) oldMap;
-
for (std::vector<pkgCache::GrpIterator*>::const_iterator i = Dynamic<pkgCache::GrpIterator>::toReMap.begin();
i != Dynamic<pkgCache::GrpIterator>::toReMap.end(); ++i)
(*i)->ReMap(oldMap, newMap);
@@ -153,27 +169,27 @@ void pkgCacheGenerator::ReMap(void const * const oldMap, void const * const newM
(*i)->ReMap(oldMap, newMap);
} /*}}}*/
// CacheGenerator::WriteStringInMap /*{{{*/
-map_ptrloc pkgCacheGenerator::WriteStringInMap(const char *String,
+map_stringitem_t pkgCacheGenerator::WriteStringInMap(const char *String,
const unsigned long &Len) {
void const * const oldMap = Map.Data();
- map_ptrloc const index = Map.WriteString(String, Len);
+ map_stringitem_t const index = Map.WriteString(String, Len);
if (index != 0)
ReMap(oldMap, Map.Data());
return index;
}
/*}}}*/
// CacheGenerator::WriteStringInMap /*{{{*/
-map_ptrloc pkgCacheGenerator::WriteStringInMap(const char *String) {
+map_stringitem_t pkgCacheGenerator::WriteStringInMap(const char *String) {
void const * const oldMap = Map.Data();
- map_ptrloc const index = Map.WriteString(String);
+ map_stringitem_t const index = Map.WriteString(String);
if (index != 0)
ReMap(oldMap, Map.Data());
return index;
}
/*}}}*/
-map_ptrloc pkgCacheGenerator::AllocateInMap(const unsigned long &size) {/*{{{*/
+map_pointer_t pkgCacheGenerator::AllocateInMap(const unsigned long &size) {/*{{{*/
void const * const oldMap = Map.Data();
- map_ptrloc const index = Map.Allocate(size);
+ map_pointer_t const index = Map.Allocate(size);
if (index != 0)
ReMap(oldMap, Map.Data());
return index;
@@ -253,16 +269,16 @@ bool pkgCacheGenerator::MergeList(ListParser &List,
}
}
- if (Cache.HeaderP->PackageCount >= (1ULL<<sizeof(Cache.PkgP->ID)*8)-1)
+ if (Cache.HeaderP->PackageCount >= std::numeric_limits<map_id_t>::max())
return _error->Error(_("Wow, you exceeded the number of package "
"names this APT is capable of."));
- if (Cache.HeaderP->VersionCount >= (1ULL<<(sizeof(Cache.VerP->ID)*8))-1)
+ if (Cache.HeaderP->VersionCount >= std::numeric_limits<map_id_t>::max())
return _error->Error(_("Wow, you exceeded the number of versions "
"this APT is capable of."));
- if (Cache.HeaderP->DescriptionCount >= (1ULL<<(sizeof(Cache.DescP->ID)*8))-1)
+ if (Cache.HeaderP->DescriptionCount >= std::numeric_limits<map_id_t>::max())
return _error->Error(_("Wow, you exceeded the number of descriptions "
"this APT is capable of."));
- if (Cache.HeaderP->DependsCount >= (1ULL<<(sizeof(Cache.DepP->ID)*8))-1ULL)
+ if (Cache.HeaderP->DependsCount >= std::numeric_limits<map_id_t>::max())
return _error->Error(_("Wow, you exceeded the number of dependencies "
"this APT is capable of."));
@@ -302,10 +318,9 @@ bool pkgCacheGenerator::MergeListPackage(ListParser &List, pkgCache::PkgIterator
// Find the right version to write the description
MD5SumValue CurMd5 = List.Description_md5();
- if (CurMd5.Value().empty() == true || List.Description().empty() == true)
+ if (CurMd5.Value().empty() == true && List.Description("").empty() == true)
return true;
- std::string CurLang = List.DescriptionLanguage();
-
+ std::vector<std::string> availDesc = List.AvailableDescriptionLanguages();
for (Ver = Pkg.VersionList(); Ver.end() == false; ++Ver)
{
pkgCache::DescIterator VerDesc = Ver.DescriptionList();
@@ -314,31 +329,16 @@ bool pkgCacheGenerator::MergeListPackage(ListParser &List, pkgCache::PkgIterator
if (VerDesc.end() == true || MD5SumValue(VerDesc.md5()) != CurMd5)
continue;
- // don't add a new description if we have one for the given
- // md5 && language
- if (IsDuplicateDescription(VerDesc, CurMd5, CurLang) == true)
- continue;
-
- pkgCache::DescIterator Desc;
- Dynamic<pkgCache::DescIterator> DynDesc(Desc);
-
- map_ptrloc const descindex = NewDescription(Desc, CurLang, CurMd5, VerDesc->md5sum);
- if (unlikely(descindex == 0 && _error->PendingError()))
- return _error->Error(_("Error occurred while processing %s (%s%d)"),
- Pkg.Name(), "NewDescription", 1);
-
- Desc->ParentPkg = Pkg.Index();
-
- // we add at the end, so that the start is constant as we need
- // that to be able to efficiently share these lists
- VerDesc = Ver.DescriptionList(); // old value might be invalid after ReMap
- for (;VerDesc.end() == false && VerDesc->NextDesc != 0; ++VerDesc);
- map_ptrloc * const LastNextDesc = (VerDesc.end() == true) ? &Ver->DescriptionList : &VerDesc->NextDesc;
- *LastNextDesc = descindex;
+ map_stringitem_t md5idx = VerDesc->md5sum;
+ for (std::vector<std::string>::const_iterator CurLang = availDesc.begin(); CurLang != availDesc.end(); ++CurLang)
+ {
+ // don't add a new description if we have one for the given
+ // md5 && language
+ if (IsDuplicateDescription(VerDesc, CurMd5, *CurLang) == true)
+ continue;
- if (NewFileDesc(Desc,List) == false)
- return _error->Error(_("Error occurred while processing %s (%s%d)"),
- Pkg.Name(), "NewFileDesc", 1);
+ AddNewDescription(List, Ver, *CurLang, CurMd5, md5idx);
+ }
// we can stop here as all "same" versions will share the description
break;
@@ -353,7 +353,7 @@ bool pkgCacheGenerator::MergeListVersion(ListParser &List, pkgCache::PkgIterator
{
pkgCache::VerIterator Ver = Pkg.VersionList();
Dynamic<pkgCache::VerIterator> DynVer(Ver);
- map_ptrloc *LastVer = &Pkg->VersionList;
+ map_pointer_t *LastVer = &Pkg->VersionList;
void const * oldMap = Map.Data();
unsigned short const Hash = List.VersionHash();
@@ -362,7 +362,7 @@ bool pkgCacheGenerator::MergeListVersion(ListParser &List, pkgCache::PkgIterator
/* We know the list is sorted so we use that fact in the search.
Insertion of new versions is done with correct sorting */
int Res = 1;
- for (; Ver.end() == false; LastVer = &Ver->NextVer, Ver++)
+ for (; Ver.end() == false; LastVer = &Ver->NextVer, ++Ver)
{
Res = Cache.VS->CmpVersion(Version,Ver.VerStr());
// Version is higher as current version - insert here
@@ -398,13 +398,13 @@ bool pkgCacheGenerator::MergeListVersion(ListParser &List, pkgCache::PkgIterator
}
// Add a new version
- map_ptrloc const verindex = NewVersion(Ver, Version, Pkg.Index(), Hash, *LastVer);
+ map_pointer_t const verindex = NewVersion(Ver, Version, Pkg.Index(), Hash, *LastVer);
if (verindex == 0 && _error->PendingError())
return _error->Error(_("Error occurred while processing %s (%s%d)"),
Pkg.Name(), "NewVersion", 1);
if (oldMap != Map.Data())
- LastVer += (map_ptrloc const * const) Map.Data() - (map_ptrloc const * const) oldMap;
+ LastVer += (map_pointer_t const * const) Map.Data() - (map_pointer_t const * const) oldMap;
*LastVer = verindex;
if (unlikely(List.NewVersion(Ver) == false))
@@ -465,7 +465,7 @@ bool pkgCacheGenerator::MergeListVersion(ListParser &List, pkgCache::PkgIterator
D.ParentPkg().Group() == Grp)
continue;
- map_ptrloc *OldDepLast = NULL;
+ map_pointer_t *OldDepLast = NULL;
pkgCache::VerIterator ConVersion = D.ParentVer();
Dynamic<pkgCache::VerIterator> DynV(ConVersion);
// duplicate the Conflicts/Breaks/Replaces for :none arch
@@ -486,11 +486,10 @@ bool pkgCacheGenerator::MergeListVersion(ListParser &List, pkgCache::PkgIterator
return true;
}
- /* Record the Description (it is not translated) */
+ /* Record the Description(s) based on their master md5sum */
MD5SumValue CurMd5 = List.Description_md5();
- if (CurMd5.Value().empty() == true || List.Description().empty() == true)
+ if (CurMd5.Value().empty() == true && List.Description("").empty() == true)
return true;
- std::string CurLang = List.DescriptionLanguage();
/* Before we add a new description we first search in the group for
a version with a description of the same MD5 - if so we reuse this
@@ -501,28 +500,44 @@ bool pkgCacheGenerator::MergeListVersion(ListParser &List, pkgCache::PkgIterator
for (pkgCache::VerIterator V = P.VersionList();
V.end() == false; ++V)
{
- if (IsDuplicateDescription(V.DescriptionList(), CurMd5, "") == false)
+ if (V->DescriptionList == 0 || MD5SumValue(V.DescriptionList().md5()) != CurMd5)
continue;
Ver->DescriptionList = V->DescriptionList;
- return true;
}
}
- // We haven't found reusable descriptions, so add the first description
- pkgCache::DescIterator Desc = Ver.DescriptionList();
+ // We haven't found reusable descriptions, so add the first description(s)
+ map_stringitem_t md5idx = Ver->DescriptionList == 0 ? 0 : Ver.DescriptionList()->md5sum;
+ std::vector<std::string> availDesc = List.AvailableDescriptionLanguages();
+ for (std::vector<std::string>::const_iterator CurLang = availDesc.begin(); CurLang != availDesc.end(); ++CurLang)
+ if (AddNewDescription(List, Ver, *CurLang, CurMd5, md5idx) == false)
+ return false;
+ return true;
+}
+ /*}}}*/
+bool pkgCacheGenerator::AddNewDescription(ListParser &List, pkgCache::VerIterator &Ver, std::string const &lang, MD5SumValue const &CurMd5, map_stringitem_t &md5idx) /*{{{*/
+{
+ pkgCache::DescIterator Desc;
Dynamic<pkgCache::DescIterator> DynDesc(Desc);
- map_ptrloc const descindex = NewDescription(Desc, CurLang, CurMd5, 0);
+ map_pointer_t const descindex = NewDescription(Desc, lang, CurMd5, md5idx);
if (unlikely(descindex == 0 && _error->PendingError()))
return _error->Error(_("Error occurred while processing %s (%s%d)"),
- Pkg.Name(), "NewDescription", 2);
+ Ver.ParentPkg().Name(), "NewDescription", 1);
+
+ md5idx = Desc->md5sum;
+ Desc->ParentPkg = Ver.ParentPkg().Index();
- Desc->ParentPkg = Pkg.Index();
- Ver->DescriptionList = descindex;
+ // we add at the end, so that the start is constant as we need
+ // that to be able to efficiently share these lists
+ pkgCache::DescIterator VerDesc = Ver.DescriptionList(); // old value might be invalid after ReMap
+ for (;VerDesc.end() == false && VerDesc->NextDesc != 0; ++VerDesc);
+ map_pointer_t * const LastNextDesc = (VerDesc.end() == true) ? &Ver->DescriptionList : &VerDesc->NextDesc;
+ *LastNextDesc = descindex;
if (NewFileDesc(Desc,List) == false)
return _error->Error(_("Error occurred while processing %s (%s%d)"),
- Pkg.Name(), "NewFileDesc", 2);
+ Ver.ParentPkg().Name(), "NewFileDesc", 1);
return true;
}
@@ -589,19 +604,19 @@ bool pkgCacheGenerator::NewGroup(pkgCache::GrpIterator &Grp, const string &Name)
return true;
// Get a structure
- map_ptrloc const Group = AllocateInMap(sizeof(pkgCache::Group));
+ map_pointer_t const Group = AllocateInMap(sizeof(pkgCache::Group));
if (unlikely(Group == 0))
return false;
Grp = pkgCache::GrpIterator(Cache, Cache.GrpP + Group);
- map_ptrloc const idxName = WriteStringInMap(Name);
+ map_stringitem_t const idxName = StoreString(PKGNAME, Name);
if (unlikely(idxName == 0))
return false;
Grp->Name = idxName;
// Insert it into the hash table
unsigned long const Hash = Cache.Hash(Name);
- map_ptrloc *insertAt = &Cache.HeaderP->GrpHashTable[Hash];
+ map_pointer_t *insertAt = &Cache.HeaderP->GrpHashTable()[Hash];
while (*insertAt != 0 && strcasecmp(Name.c_str(), Cache.StrP + (Cache.GrpP + *insertAt)->Name) > 0)
insertAt = &(Cache.GrpP + *insertAt)->Next;
Grp->Next = *insertAt;
@@ -626,7 +641,7 @@ bool pkgCacheGenerator::NewPackage(pkgCache::PkgIterator &Pkg,const string &Name
return true;
// Get a structure
- map_ptrloc const Package = AllocateInMap(sizeof(pkgCache::Package));
+ map_pointer_t const Package = AllocateInMap(sizeof(pkgCache::Package));
if (unlikely(Package == 0))
return false;
Pkg = pkgCache::PkgIterator(Cache,Cache.PkgP + Package);
@@ -636,27 +651,34 @@ bool pkgCacheGenerator::NewPackage(pkgCache::PkgIterator &Pkg,const string &Name
{
Grp->FirstPackage = Package;
// Insert it into the hash table
- unsigned long const Hash = Cache.Hash(Name);
- map_ptrloc *insertAt = &Cache.HeaderP->PkgHashTable[Hash];
- while (*insertAt != 0 && strcasecmp(Name.c_str(), Cache.StrP + (Cache.PkgP + *insertAt)->Name) > 0)
- insertAt = &(Cache.PkgP + *insertAt)->NextPackage;
- Pkg->NextPackage = *insertAt;
+ map_id_t const Hash = Cache.Hash(Name);
+ map_pointer_t *insertAt = &Cache.HeaderP->PkgHashTable()[Hash];
+ while (*insertAt != 0 && strcasecmp(Name.c_str(), Cache.StrP + (Cache.GrpP + (Cache.PkgP + *insertAt)->Group)->Name) > 0)
+ insertAt = &(Cache.PkgP + *insertAt)->Next;
+ Pkg->Next = *insertAt;
*insertAt = Package;
}
else // Group the Packages together
{
// this package is the new last package
pkgCache::PkgIterator LastPkg(Cache, Cache.PkgP + Grp->LastPackage);
- Pkg->NextPackage = LastPkg->NextPackage;
- LastPkg->NextPackage = Package;
+ Pkg->Next = LastPkg->Next;
+ LastPkg->Next = Package;
}
Grp->LastPackage = Package;
// Set the name, arch and the ID
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
Pkg->Name = Grp->Name;
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic pop
+#endif
Pkg->Group = Grp.Index();
// all is mapped to the native architecture
- map_ptrloc const idxArch = (Arch == "all") ? Cache.HeaderP->Architecture : WriteUniqString(Arch.c_str());
+ map_stringitem_t const idxArch = (Arch == "all") ? Cache.HeaderP->Architecture : StoreString(MIXED, Arch);
if (unlikely(idxArch == 0))
return false;
Pkg->Arch = idxArch;
@@ -673,14 +695,14 @@ bool pkgCacheGenerator::AddImplicitDepends(pkgCache::GrpIterator &G,
// copy P.Arch() into a string here as a cache remap
// in NewDepends() later may alter the pointer location
string Arch = P.Arch() == NULL ? "" : P.Arch();
- map_ptrloc *OldDepLast = NULL;
+ map_pointer_t *OldDepLast = NULL;
/* MultiArch handling introduces a lot of implicit Dependencies:
- MultiArch: same → Co-Installable if they have the same version
- All others conflict with all other group members */
bool const coInstall = ((V->MultiArch & pkgCache::Version::Same) == pkgCache::Version::Same);
pkgCache::PkgIterator D = G.PackageList();
Dynamic<pkgCache::PkgIterator> DynD(D);
- map_ptrloc const VerStrIdx = V->VerStr;
+ map_stringitem_t const VerStrIdx = V->VerStr;
for (; D.end() != true; D = G.NextPkg(D))
{
if (Arch == D.Arch() || D->VersionList == 0)
@@ -713,11 +735,11 @@ bool pkgCacheGenerator::AddImplicitDepends(pkgCache::VerIterator &V,
/* MultiArch handling introduces a lot of implicit Dependencies:
- MultiArch: same → Co-Installable if they have the same version
- All others conflict with all other group members */
- map_ptrloc *OldDepLast = NULL;
+ map_pointer_t *OldDepLast = NULL;
bool const coInstall = ((V->MultiArch & pkgCache::Version::Same) == pkgCache::Version::Same);
if (coInstall == true)
{
- map_ptrloc const VerStrIdx = V->VerStr;
+ map_stringitem_t const VerStrIdx = V->VerStr;
// Replaces: ${self}:other ( << ${binary:Version})
NewDepends(D, V, VerStrIdx,
pkgCache::Dep::Less, pkgCache::Dep::Replaces,
@@ -746,15 +768,15 @@ bool pkgCacheGenerator::NewFileVer(pkgCache::VerIterator &Ver,
return true;
// Get a structure
- map_ptrloc const VerFile = AllocateInMap(sizeof(pkgCache::VerFile));
+ map_pointer_t const VerFile = AllocateInMap(sizeof(pkgCache::VerFile));
if (VerFile == 0)
- return 0;
+ return false;
pkgCache::VerFileIterator VF(Cache,Cache.VerFileP + VerFile);
VF->File = CurrentFile - Cache.PkgFileP;
// Link it to the end of the list
- map_ptrloc *Last = &Ver->FileList;
+ map_pointer_t *Last = &Ver->FileList;
for (pkgCache::VerFileIterator V = Ver.FileList(); V.end() == false; ++V)
Last = &V->NextFile;
VF->NextFile = *Last;
@@ -772,14 +794,14 @@ bool pkgCacheGenerator::NewFileVer(pkgCache::VerIterator &Ver,
// CacheGenerator::NewVersion - Create a new Version /*{{{*/
// ---------------------------------------------------------------------
/* This puts a version structure in the linked list */
-unsigned long pkgCacheGenerator::NewVersion(pkgCache::VerIterator &Ver,
+map_pointer_t pkgCacheGenerator::NewVersion(pkgCache::VerIterator &Ver,
const string &VerStr,
- map_ptrloc const ParentPkg,
- unsigned long const Hash,
- unsigned long Next)
+ map_pointer_t const ParentPkg,
+ unsigned short const Hash,
+ map_pointer_t const Next)
{
// Get a structure
- map_ptrloc const Version = AllocateInMap(sizeof(pkgCache::Version));
+ map_pointer_t const Version = AllocateInMap(sizeof(pkgCache::Version));
if (Version == 0)
return 0;
@@ -814,7 +836,7 @@ unsigned long pkgCacheGenerator::NewVersion(pkgCache::VerIterator &Ver,
}
}
// haven't found the version string, so create
- map_ptrloc const idxVerStr = WriteStringInMap(VerStr);
+ map_stringitem_t const idxVerStr = StoreString(VERSIONNUMBER, VerStr);
if (unlikely(idxVerStr == 0))
return 0;
Ver->VerStr = idxVerStr;
@@ -831,7 +853,7 @@ bool pkgCacheGenerator::NewFileDesc(pkgCache::DescIterator &Desc,
return true;
// Get a structure
- map_ptrloc const DescFile = AllocateInMap(sizeof(pkgCache::DescFile));
+ map_pointer_t const DescFile = AllocateInMap(sizeof(pkgCache::DescFile));
if (DescFile == 0)
return false;
@@ -839,7 +861,7 @@ bool pkgCacheGenerator::NewFileDesc(pkgCache::DescIterator &Desc,
DF->File = CurrentFile - Cache.PkgFileP;
// Link it to the end of the list
- map_ptrloc *Last = &Desc->FileList;
+ map_pointer_t *Last = &Desc->FileList;
for (pkgCache::DescFileIterator D = Desc.FileList(); D.end() == false; ++D)
Last = &D->NextFile;
@@ -858,20 +880,20 @@ bool pkgCacheGenerator::NewFileDesc(pkgCache::DescIterator &Desc,
// CacheGenerator::NewDescription - Create a new Description /*{{{*/
// ---------------------------------------------------------------------
/* This puts a description structure in the linked list */
-map_ptrloc pkgCacheGenerator::NewDescription(pkgCache::DescIterator &Desc,
+map_pointer_t pkgCacheGenerator::NewDescription(pkgCache::DescIterator &Desc,
const string &Lang,
const MD5SumValue &md5sum,
- map_ptrloc idxmd5str)
+ map_stringitem_t const idxmd5str)
{
// Get a structure
- map_ptrloc const Description = AllocateInMap(sizeof(pkgCache::Description));
+ map_pointer_t const Description = AllocateInMap(sizeof(pkgCache::Description));
if (Description == 0)
return 0;
// Fill it in
Desc = pkgCache::DescIterator(Cache,Cache.DescP + Description);
Desc->ID = Cache.HeaderP->DescriptionCount++;
- map_ptrloc const idxlanguage_code = WriteUniqString(Lang);
+ map_stringitem_t const idxlanguage_code = StoreString(MIXED, Lang);
if (unlikely(idxlanguage_code == 0))
return 0;
Desc->language_code = idxlanguage_code;
@@ -880,7 +902,7 @@ map_ptrloc pkgCacheGenerator::NewDescription(pkgCache::DescIterator &Desc,
Desc->md5sum = idxmd5str;
else
{
- map_ptrloc const idxmd5sum = WriteStringInMap(md5sum.Value());
+ map_stringitem_t const idxmd5sum = WriteStringInMap(md5sum.Value());
if (unlikely(idxmd5sum == 0))
return 0;
Desc->md5sum = idxmd5sum;
@@ -898,9 +920,9 @@ bool pkgCacheGenerator::NewDepends(pkgCache::PkgIterator &Pkg,
string const &Version,
unsigned int const &Op,
unsigned int const &Type,
- map_ptrloc* &OldDepLast)
+ map_stringitem_t* &OldDepLast)
{
- map_ptrloc index = 0;
+ map_stringitem_t index = 0;
if (Version.empty() == false)
{
int const CmpOp = Op & 0x0F;
@@ -911,25 +933,25 @@ bool pkgCacheGenerator::NewDepends(pkgCache::PkgIterator &Pkg,
if (index == 0)
{
void const * const oldMap = Map.Data();
- index = WriteStringInMap(Version);
+ index = StoreString(VERSIONNUMBER, Version);
if (unlikely(index == 0))
return false;
if (OldDepLast != 0 && oldMap != Map.Data())
- OldDepLast += (map_ptrloc const * const) Map.Data() - (map_ptrloc const * const) oldMap;
+ OldDepLast += (map_pointer_t const * const) Map.Data() - (map_pointer_t const * const) oldMap;
}
}
return NewDepends(Pkg, Ver, index, Op, Type, OldDepLast);
}
bool pkgCacheGenerator::NewDepends(pkgCache::PkgIterator &Pkg,
pkgCache::VerIterator &Ver,
- map_ptrloc const Version,
+ map_pointer_t const Version,
unsigned int const &Op,
unsigned int const &Type,
- map_ptrloc* &OldDepLast)
+ map_pointer_t* &OldDepLast)
{
void const * const oldMap = Map.Data();
// Get a structure
- map_ptrloc const Dependency = AllocateInMap(sizeof(pkgCache::Dependency));
+ map_pointer_t const Dependency = AllocateInMap(sizeof(pkgCache::Dependency));
if (unlikely(Dependency == 0))
return false;
@@ -954,7 +976,7 @@ bool pkgCacheGenerator::NewDepends(pkgCache::PkgIterator &Pkg,
for (pkgCache::DepIterator D = Ver.DependsList(); D.end() == false; ++D)
OldDepLast = &D->NextDepends;
} else if (oldMap != Map.Data())
- OldDepLast += (map_ptrloc const * const) Map.Data() - (map_ptrloc const * const) oldMap;
+ OldDepLast += (map_pointer_t const * const) Map.Data() - (map_pointer_t const * const) oldMap;
Dep->NextDepends = *OldDepLast;
*OldDepLast = Dep.Index();
@@ -1019,7 +1041,7 @@ bool pkgCacheGenerator::ListParser::NewProvides(pkgCache::VerIterator &Ver,
return true;
// Get a structure
- map_ptrloc const Provides = Owner->AllocateInMap(sizeof(pkgCache::Provides));
+ map_pointer_t const Provides = Owner->AllocateInMap(sizeof(pkgCache::Provides));
if (unlikely(Provides == 0))
return false;
Cache.HeaderP->ProvidesCount++;
@@ -1031,7 +1053,7 @@ bool pkgCacheGenerator::ListParser::NewProvides(pkgCache::VerIterator &Ver,
Prv->NextPkgProv = Ver->ProvidesList;
Ver->ProvidesList = Prv.Index();
if (Version.empty() == false) {
- map_ptrloc const idxProvideVersion = WriteString(Version);
+ map_stringitem_t const idxProvideVersion = WriteString(Version);
Prv->ProvideVersion = idxProvideVersion;
if (unlikely(idxProvideVersion == 0))
return false;
@@ -1066,14 +1088,14 @@ bool pkgCacheGenerator::SelectFile(const string &File,const string &Site,
unsigned long Flags)
{
// Get some space for the structure
- map_ptrloc const idxFile = AllocateInMap(sizeof(*CurrentFile));
+ map_pointer_t const idxFile = AllocateInMap(sizeof(*CurrentFile));
if (unlikely(idxFile == 0))
return false;
CurrentFile = Cache.PkgFileP + idxFile;
// Fill it in
- map_ptrloc const idxFileName = WriteStringInMap(File);
- map_ptrloc const idxSite = WriteUniqString(Site);
+ map_stringitem_t const idxFileName = WriteStringInMap(File);
+ map_stringitem_t const idxSite = StoreString(MIXED, Site);
if (unlikely(idxFileName == 0 || idxSite == 0))
return false;
CurrentFile->FileName = idxFileName;
@@ -1081,7 +1103,7 @@ bool pkgCacheGenerator::SelectFile(const string &File,const string &Site,
CurrentFile->NextFile = Cache.HeaderP->FileList;
CurrentFile->Flags = Flags;
CurrentFile->ID = Cache.HeaderP->PackageFileCount;
- map_ptrloc const idxIndexType = WriteUniqString(Index.GetType()->Label);
+ map_stringitem_t const idxIndexType = StoreString(MIXED, Index.GetType()->Label);
if (unlikely(idxIndexType == 0))
return false;
CurrentFile->IndexType = idxIndexType;
@@ -1098,57 +1120,27 @@ bool pkgCacheGenerator::SelectFile(const string &File,const string &Site,
// ---------------------------------------------------------------------
/* This is used to create handles to strings. Given the same text it
always returns the same number */
-unsigned long pkgCacheGenerator::WriteUniqString(const char *S,
+map_stringitem_t pkgCacheGenerator::StoreString(enum StringType const type, const char *S,
unsigned int Size)
{
- /* We use a very small transient hash table here, this speeds up generation
- by a fair amount on slower machines */
- pkgCache::StringItem *&Bucket = UniqHash[(S[0]*5 + S[1]) % _count(UniqHash)];
- if (Bucket != 0 &&
- stringcmp(S,S+Size,Cache.StrP + Bucket->String) == 0)
- return Bucket->String;
-
- // Search for an insertion point
- pkgCache::StringItem *I = Cache.StringItemP + Cache.HeaderP->StringList;
- int Res = 1;
- map_ptrloc *Last = &Cache.HeaderP->StringList;
- for (; I != Cache.StringItemP; Last = &I->NextItem,
- I = Cache.StringItemP + I->NextItem)
- {
- Res = stringcmp(S,S+Size,Cache.StrP + I->String);
- if (Res >= 0)
- break;
- }
-
- // Match
- if (Res == 0)
- {
- Bucket = I;
- return I->String;
- }
-
- // Get a structure
- void const * const oldMap = Map.Data();
- map_ptrloc const Item = AllocateInMap(sizeof(pkgCache::StringItem));
- if (Item == 0)
- return 0;
-
- map_ptrloc const idxString = WriteStringInMap(S,Size);
- if (unlikely(idxString == 0))
- return 0;
- if (oldMap != Map.Data()) {
- Last += (map_ptrloc const * const) Map.Data() - (map_ptrloc const * const) oldMap;
- I += (pkgCache::StringItem const * const) Map.Data() - (pkgCache::StringItem const * const) oldMap;
+ std::string const key(S, Size);
+
+ std::map<std::string,map_stringitem_t> * strings;
+ switch(type) {
+ case MIXED: strings = &strMixed; break;
+ case PKGNAME: strings = &strPkgNames; break;
+ case VERSIONNUMBER: strings = &strVersions; break;
+ case SECTION: strings = &strSections; break;
+ default: _error->Fatal("Unknown enum type used for string storage of '%s'", key.c_str()); return 0;
}
- *Last = Item;
- // Fill in the structure
- pkgCache::StringItem *ItemP = Cache.StringItemP + Item;
- ItemP->NextItem = I - Cache.StringItemP;
- ItemP->String = idxString;
+ std::map<std::string,map_stringitem_t>::const_iterator const item = strings->find(key);
+ if (item != strings->end())
+ return item->second;
- Bucket = ItemP;
- return ItemP->String;
+ map_stringitem_t const idxString = WriteStringInMap(S,Size);
+ strings->insert(std::make_pair(key, idxString));
+ return idxString;
}
/*}}}*/
// CheckValidity - Check that a cache is up-to-date /*{{{*/
@@ -1258,9 +1250,9 @@ static bool CheckValidity(const string &CacheFile,
// ---------------------------------------------------------------------
/* Size is kind of an abstract notion that is only used for the progress
meter */
-static unsigned long ComputeSize(FileIterator Start,FileIterator End)
+static map_filesize_t ComputeSize(FileIterator Start,FileIterator End)
{
- unsigned long TotalSize = 0;
+ map_filesize_t TotalSize = 0;
for (; Start < End; ++Start)
{
if ((*Start)->HasPackages() == false)
@@ -1275,7 +1267,7 @@ static unsigned long ComputeSize(FileIterator Start,FileIterator End)
/* */
static bool BuildCache(pkgCacheGenerator &Gen,
OpProgress *Progress,
- unsigned long &CurrentSize,unsigned long TotalSize,
+ map_filesize_t &CurrentSize,map_filesize_t TotalSize,
FileIterator Start, FileIterator End)
{
FileIterator I;
@@ -1294,7 +1286,7 @@ static bool BuildCache(pkgCacheGenerator &Gen,
continue;
}
- unsigned long Size = (*I)->Size();
+ map_filesize_t Size = (*I)->Size();
if (Progress != NULL)
Progress->OverallProgress(CurrentSize,TotalSize,Size,_("Reading package lists"));
CurrentSize += Size;
@@ -1311,7 +1303,7 @@ static bool BuildCache(pkgCacheGenerator &Gen,
CurrentSize = 0;
for (I = Start; I != End; ++I)
{
- unsigned long Size = (*I)->Size();
+ map_filesize_t Size = (*I)->Size();
if (Progress != NULL)
Progress->OverallProgress(CurrentSize,TotalSize,Size,_("Collecting File Provides"));
CurrentSize += Size;
@@ -1325,9 +1317,9 @@ static bool BuildCache(pkgCacheGenerator &Gen,
/*}}}*/
// CacheGenerator::CreateDynamicMMap - load an mmap with configuration options /*{{{*/
DynamicMMap* pkgCacheGenerator::CreateDynamicMMap(FileFd *CacheF, unsigned long Flags) {
- unsigned long const MapStart = _config->FindI("APT::Cache-Start", 24*1024*1024);
- unsigned long const MapGrow = _config->FindI("APT::Cache-Grow", 1*1024*1024);
- unsigned long const MapLimit = _config->FindI("APT::Cache-Limit", 0);
+ map_filesize_t const MapStart = _config->FindI("APT::Cache-Start", 24*1024*1024);
+ map_filesize_t const MapGrow = _config->FindI("APT::Cache-Grow", 1*1024*1024);
+ map_filesize_t const MapLimit = _config->FindI("APT::Cache-Limit", 0);
Flags |= MMap::Moveable;
if (_config->FindB("APT::Cache-Fallback", false) == true)
Flags |= MMap::Fallback;
@@ -1365,7 +1357,7 @@ bool pkgCacheGenerator::MakeStatusCache(pkgSourceList &List,OpProgress *Progress
Files.push_back (*j);
}
- unsigned long const EndOfSource = Files.size();
+ map_filesize_t const EndOfSource = Files.size();
if (_system->AddStatusFiles(Files) == false)
return false;
@@ -1455,8 +1447,8 @@ bool pkgCacheGenerator::MakeStatusCache(pkgSourceList &List,OpProgress *Progress
}
// Lets try the source cache.
- unsigned long CurrentSize = 0;
- unsigned long TotalSize = 0;
+ map_filesize_t CurrentSize = 0;
+ map_filesize_t TotalSize = 0;
if (CheckValidity(SrcCacheFile, List, Files.begin(),
Files.begin()+EndOfSource) == true)
{
@@ -1464,7 +1456,7 @@ bool pkgCacheGenerator::MakeStatusCache(pkgSourceList &List,OpProgress *Progress
std::clog << "srcpkgcache.bin is valid - populate MMap with it." << std::endl;
// Preload the map with the source cache
FileFd SCacheF(SrcCacheFile,FileFd::ReadOnly);
- unsigned long const alloc = Map->RawAllocate(SCacheF.Size());
+ map_pointer_t const alloc = Map->RawAllocate(SCacheF.Size());
if ((alloc == 0 && _error->PendingError())
|| SCacheF.Read((unsigned char *)Map->Data() + alloc,
SCacheF.Size()) == false)
@@ -1551,13 +1543,13 @@ APT_DEPRECATED bool pkgMakeOnlyStatusCache(OpProgress &Progress,DynamicMMap **Ou
bool pkgCacheGenerator::MakeOnlyStatusCache(OpProgress *Progress,DynamicMMap **OutMap)
{
std::vector<pkgIndexFile *> Files;
- unsigned long EndOfSource = Files.size();
+ map_filesize_t EndOfSource = Files.size();
if (_system->AddStatusFiles(Files) == false)
return false;
SPtr<DynamicMMap> Map = CreateDynamicMMap(NULL);
- unsigned long CurrentSize = 0;
- unsigned long TotalSize = 0;
+ map_filesize_t CurrentSize = 0;
+ map_filesize_t TotalSize = 0;
TotalSize = ComputeSize(Files.begin()+EndOfSource,Files.end());
diff --git a/apt-pkg/pkgcachegen.h b/apt-pkg/pkgcachegen.h
index 1e1a71026..54c4f9e7a 100644
--- a/apt-pkg/pkgcachegen.h
+++ b/apt-pkg/pkgcachegen.h
@@ -27,6 +27,7 @@
#include <vector>
#include <string>
+#include <map>
class FileFd;
class pkgSourceList;
@@ -36,12 +37,15 @@ class pkgIndexFile;
class pkgCacheGenerator /*{{{*/
{
private:
+ APT_HIDDEN map_stringitem_t WriteStringInMap(std::string const &String) { return WriteStringInMap(String.c_str()); };
+ APT_HIDDEN map_stringitem_t WriteStringInMap(const char *String);
+ APT_HIDDEN map_stringitem_t WriteStringInMap(const char *String, const unsigned long &Len);
+ APT_HIDDEN map_pointer_t AllocateInMap(const unsigned long &size);
- pkgCache::StringItem *UniqHash[26];
- APT_HIDDEN map_ptrloc WriteStringInMap(std::string const &String) { return WriteStringInMap(String.c_str()); };
- APT_HIDDEN map_ptrloc WriteStringInMap(const char *String);
- APT_HIDDEN map_ptrloc WriteStringInMap(const char *String, const unsigned long &Len);
- APT_HIDDEN map_ptrloc AllocateInMap(const unsigned long &size);
+ std::map<std::string,map_stringitem_t> strMixed;
+ std::map<std::string,map_stringitem_t> strSections;
+ std::map<std::string,map_stringitem_t> strPkgNames;
+ std::map<std::string,map_stringitem_t> strVersions;
public:
@@ -78,21 +82,22 @@ class pkgCacheGenerator /*{{{*/
bool NewFileDesc(pkgCache::DescIterator &Desc,ListParser &List);
bool NewDepends(pkgCache::PkgIterator &Pkg, pkgCache::VerIterator &Ver,
std::string const &Version, unsigned int const &Op,
- unsigned int const &Type, map_ptrloc* &OldDepLast);
+ unsigned int const &Type, map_pointer_t* &OldDepLast);
bool NewDepends(pkgCache::PkgIterator &Pkg, pkgCache::VerIterator &Ver,
- map_ptrloc const Version, unsigned int const &Op,
- unsigned int const &Type, map_ptrloc* &OldDepLast);
- unsigned long NewVersion(pkgCache::VerIterator &Ver,const std::string &VerStr,unsigned long Next) APT_DEPRECATED
+ map_pointer_t const Version, unsigned int const &Op,
+ unsigned int const &Type, map_pointer_t* &OldDepLast);
+ map_pointer_t NewVersion(pkgCache::VerIterator &Ver,const std::string &VerStr,map_pointer_t const Next) APT_DEPRECATED
{ return NewVersion(Ver, VerStr, 0, 0, Next); }
- unsigned long NewVersion(pkgCache::VerIterator &Ver,const std::string &VerStr,
- map_ptrloc const ParentPkg, unsigned long const Hash,
- unsigned long Next);
- map_ptrloc NewDescription(pkgCache::DescIterator &Desc,const std::string &Lang,const MD5SumValue &md5sum,map_ptrloc Next);
+ map_pointer_t NewVersion(pkgCache::VerIterator &Ver,const std::string &VerStr,
+ map_pointer_t const ParentPkg, unsigned short const Hash,
+ map_pointer_t const Next);
+ map_pointer_t NewDescription(pkgCache::DescIterator &Desc,const std::string &Lang,const MD5SumValue &md5sum,map_stringitem_t const idxmd5str);
public:
- unsigned long WriteUniqString(const char *S,unsigned int Size);
- inline unsigned long WriteUniqString(const std::string &S) {return WriteUniqString(S.c_str(),S.length());};
+ enum StringType { MIXED, PKGNAME, VERSIONNUMBER, SECTION };
+ map_stringitem_t StoreString(StringType const type, const char * S, unsigned int const Size);
+ inline map_stringitem_t StoreString(enum StringType const type, const std::string &S) {return StoreString(type, S.c_str(),S.length());};
void DropProgress() {Progress = 0;};
bool SelectFile(const std::string &File,const std::string &Site,pkgIndexFile const &Index,
@@ -125,6 +130,9 @@ class pkgCacheGenerator /*{{{*/
APT_HIDDEN bool AddImplicitDepends(pkgCache::GrpIterator &G, pkgCache::PkgIterator &P,
pkgCache::VerIterator &V);
APT_HIDDEN bool AddImplicitDepends(pkgCache::VerIterator &V, pkgCache::PkgIterator &D);
+
+ APT_HIDDEN bool AddNewDescription(ListParser &List, pkgCache::VerIterator &Ver,
+ std::string const &lang, MD5SumValue const &CurMd5, map_stringitem_t &md5idx);
};
/*}}}*/
// This is the abstract package list parser class. /*{{{*/
@@ -135,17 +143,18 @@ class pkgCacheGenerator::ListParser
// Some cache items
pkgCache::VerIterator OldDepVer;
- map_ptrloc *OldDepLast;
+ map_pointer_t *OldDepLast;
// Flag file dependencies
bool FoundFileDeps;
protected:
- inline unsigned long WriteUniqString(std::string S) {return Owner->WriteUniqString(S);};
- inline unsigned long WriteUniqString(const char *S,unsigned int Size) {return Owner->WriteUniqString(S,Size);};
- inline unsigned long WriteString(const std::string &S) {return Owner->WriteStringInMap(S);};
- inline unsigned long WriteString(const char *S,unsigned int Size) {return Owner->WriteStringInMap(S,Size);};
+ inline map_stringitem_t StoreString(pkgCacheGenerator::StringType const type, std::string const &S) {return Owner->StoreString(type, S);};
+ inline map_stringitem_t StoreString(pkgCacheGenerator::StringType const type, const char *S,unsigned int Size) {return Owner->StoreString(type, S, Size);};
+
+ inline map_stringitem_t WriteString(const std::string &S) {return Owner->WriteStringInMap(S);};
+ inline map_stringitem_t WriteString(const char *S,unsigned int Size) {return Owner->WriteStringInMap(S,Size);};
bool NewDepends(pkgCache::VerIterator &Ver,const std::string &Package, const std::string &Arch,
const std::string &Version,unsigned int Op,
unsigned int Type);
@@ -160,8 +169,8 @@ class pkgCacheGenerator::ListParser
virtual bool ArchitectureAll() = 0;
virtual std::string Version() = 0;
virtual bool NewVersion(pkgCache::VerIterator &Ver) = 0;
- virtual std::string Description() = 0;
- virtual std::string DescriptionLanguage() = 0;
+ virtual std::string Description(std::string const &lang) = 0;
+ virtual std::vector<std::string> AvailableDescriptionLanguages() = 0;
virtual MD5SumValue Description_md5() = 0;
virtual unsigned short VersionHash() = 0;
/** compare currently parsed version with given version
@@ -175,8 +184,8 @@ class pkgCacheGenerator::ListParser
APT_PURE bool SameVersion(unsigned short const Hash, pkgCache::VerIterator const &Ver);
virtual bool UsePackage(pkgCache::PkgIterator &Pkg,
pkgCache::VerIterator &Ver) = 0;
- virtual unsigned long Offset() = 0;
- virtual unsigned long Size() = 0;
+ virtual map_filesize_t Offset() = 0;
+ virtual map_filesize_t Size() = 0;
virtual bool Step() = 0;
@@ -184,7 +193,7 @@ class pkgCacheGenerator::ListParser
virtual bool CollectFileProvides(pkgCache &/*Cache*/,
pkgCache::VerIterator &/*Ver*/) {return true;};
- ListParser() : FoundFileDeps(false) {};
+ ListParser() : Owner(NULL), OldDepLast(NULL), FoundFileDeps(false) {};
virtual ~ListParser() {};
};
/*}}}*/
diff --git a/apt-pkg/pkgrecords.cc b/apt-pkg/pkgrecords.cc
index c403e4dc3..859af3a09 100644
--- a/apt-pkg/pkgrecords.cc
+++ b/apt-pkg/pkgrecords.cc
@@ -26,7 +26,7 @@
// Records::pkgRecords - Constructor /*{{{*/
// ---------------------------------------------------------------------
/* This will create the necessary structures to access the status files */
-pkgRecords::pkgRecords(pkgCache &Cache) : d(NULL), Cache(Cache),
+pkgRecords::pkgRecords(pkgCache &aCache) : d(NULL), Cache(aCache),
Files(Cache.HeaderP->PackageFileCount)
{
for (pkgCache::PkgFileIterator I = Cache.FileBegin();
diff --git a/apt-pkg/pkgrecords.h b/apt-pkg/pkgrecords.h
index b5237b3a0..a902da8b8 100644
--- a/apt-pkg/pkgrecords.h
+++ b/apt-pkg/pkgrecords.h
@@ -18,6 +18,8 @@
#define PKGLIB_PKGRECORDS_H
#include <apt-pkg/pkgcache.h>
+#include <apt-pkg/hashes.h>
+#include <apt-pkg/macros.h>
#include <string>
#include <vector>
@@ -56,17 +58,39 @@ class pkgRecords::Parser /*{{{*/
// These refer to the archive file for the Version
virtual std::string FileName() {return std::string();};
- virtual std::string MD5Hash() {return std::string();};
- virtual std::string SHA1Hash() {return std::string();};
- virtual std::string SHA256Hash() {return std::string();};
- virtual std::string SHA512Hash() {return std::string();};
virtual std::string SourcePkg() {return std::string();};
virtual std::string SourceVer() {return std::string();};
+ /** return all known hashes in this record.
+ *
+ * For authentication proposes packages come with hashsums which
+ * this method is supposed to parse and return so that clients can
+ * choose the hash to be used.
+ */
+ virtual HashStringList Hashes() const { return HashStringList(); };
+ APT_DEPRECATED std::string MD5Hash() const { return GetHashFromHashes("MD5Sum"); };
+ APT_DEPRECATED std::string SHA1Hash() const { return GetHashFromHashes("SHA1"); };
+ APT_DEPRECATED std::string SHA256Hash() const { return GetHashFromHashes("SHA256"); };
+ APT_DEPRECATED std::string SHA512Hash() const { return GetHashFromHashes("SHA512"); };
+
// These are some general stats about the package
virtual std::string Maintainer() {return std::string();};
- virtual std::string ShortDesc() {return std::string();};
- virtual std::string LongDesc() {return std::string();};
+ /** return short description in language from record.
+ *
+ * @see #LongDesc
+ */
+ virtual std::string ShortDesc(std::string const &/*lang*/) {return std::string();};
+ /** return long description in language from record.
+ *
+ * If \b lang is empty the "best" available language will be
+ * returned as determined by the APT::Languages configuration.
+ * If a (requested) language can't be found in this record an empty
+ * string will be returned.
+ */
+ virtual std::string LongDesc(std::string const &/*lang*/) {return std::string();};
+ std::string ShortDesc() {return ShortDesc("");};
+ std::string LongDesc() {return LongDesc("");};
+
virtual std::string Name() {return std::string();};
virtual std::string Homepage() {return std::string();}
@@ -77,6 +101,14 @@ class pkgRecords::Parser /*{{{*/
virtual void GetRec(const char *&Start,const char *&Stop) {Start = Stop = 0;};
virtual ~Parser() {};
+
+ private:
+ APT_HIDDEN std::string GetHashFromHashes(char const * const type) const
+ {
+ HashStringList const hashes = Hashes();
+ HashString const * const hs = hashes.find(type);
+ return hs != NULL ? hs->HashValue() : "";
+ };
};
/*}}}*/
#endif
diff --git a/apt-pkg/pkgsystem.h b/apt-pkg/pkgsystem.h
index 6e33c67ed..f88ffa7c8 100644
--- a/apt-pkg/pkgsystem.h
+++ b/apt-pkg/pkgsystem.h
@@ -85,10 +85,12 @@ class pkgSystem
virtual bool AddStatusFiles(std::vector<pkgIndexFile *> &List) = 0;
virtual bool FindIndex(pkgCache::PkgFileIterator File,
pkgIndexFile *&Found) const = 0;
-
+
/* Evauluate how 'right' we are for this system based on the filesystem
etc.. */
- virtual signed Score(Configuration const &/*Cnf*/) {return 0;};
+ virtual signed Score(Configuration const &/*Cnf*/) {
+ return 0;
+ };
pkgSystem();
virtual ~pkgSystem() {};
diff --git a/apt-pkg/sourcelist.cc b/apt-pkg/sourcelist.cc
index e37899ec6..7170e8b5b 100644
--- a/apt-pkg/sourcelist.cc
+++ b/apt-pkg/sourcelist.cc
@@ -119,7 +119,7 @@ bool pkgSourceList::Type::ParseStanza(vector<metaIndex *> &List,
std::vector<std::string> list_section = StringSplit(Section, " ");
for (std::vector<std::string>::const_iterator U = list_uris.begin();
- U != list_uris.end(); U++)
+ U != list_uris.end(); ++U)
{
std::string URI = (*U);
if (!FixupURI(URI))
@@ -129,10 +129,10 @@ bool pkgSourceList::Type::ParseStanza(vector<metaIndex *> &List,
}
for (std::vector<std::string>::const_iterator I = list_dist.begin();
- I != list_dist.end(); I++)
+ I != list_dist.end(); ++I)
{
for (std::vector<std::string>::const_iterator J = list_section.begin();
- J != list_section.end(); J++)
+ J != list_section.end(); ++J)
{
if (CreateItem(List, URI, (*I), (*J), Options) == false)
{
@@ -408,7 +408,7 @@ int pkgSourceList::ParseFileDeb822(string File)
string const types = Tags.FindS("Types");
std::vector<std::string> list_types = StringSplit(types, " ");
for (std::vector<std::string>::const_iterator I = list_types.begin();
- I != list_types.end(); I++)
+ I != list_types.end(); ++I)
{
Type *Parse = Type::GetType((*I).c_str());
if (Parse == 0)
diff --git a/apt-pkg/sourcelist.h b/apt-pkg/sourcelist.h
index 9df0c1d74..35b786e1a 100644
--- a/apt-pkg/sourcelist.h
+++ b/apt-pkg/sourcelist.h
@@ -52,7 +52,15 @@ class pkgAcquire;
class pkgIndexFile;
class metaIndex;
-class pkgSourceList
+class pkgSource
+{
+ protected:
+
+ std::vector<metaIndex *> SrcList;
+
+};
+
+class pkgSourceList : public pkgSource
{
public:
@@ -86,15 +94,11 @@ class pkgSourceList
typedef std::vector<metaIndex *>::const_iterator const_iterator;
- protected:
-
- std::vector<metaIndex *> SrcList;
+ public:
int ParseFileDeb822(std::string File);
bool ParseFileOldStyle(std::string File);
- public:
-
bool ReadMainList();
bool Read(std::string File);
diff --git a/apt-pkg/srcrecords.h b/apt-pkg/srcrecords.h
index e000e176a..c68d374bb 100644
--- a/apt-pkg/srcrecords.h
+++ b/apt-pkg/srcrecords.h
@@ -14,6 +14,7 @@
#define PKGLIB_SRCRECORDS_H
#include <apt-pkg/macros.h>
+#include <apt-pkg/hashes.h>
#include <string>
#include <vector>
@@ -29,15 +30,24 @@ class pkgSrcRecords
{
public:
+#if __GNUC__ >= 4
+ // ensure that con- & de-structor don't trigger this warning
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
// Describes a single file
struct File
{
- std::string MD5Hash;
- unsigned long Size;
std::string Path;
std::string Type;
+ unsigned long long Size;
+ HashStringList Hashes;
+ APT_DEPRECATED std::string MD5Hash;
};
-
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic pop
+#endif
+
// Abstract parser for each source record
class Parser
{
diff --git a/apt-pkg/tagfile.cc b/apt-pkg/tagfile.cc
index bf865bdc4..b263baf66 100644
--- a/apt-pkg/tagfile.cc
+++ b/apt-pkg/tagfile.cc
@@ -47,16 +47,43 @@ public:
unsigned long long Size;
};
+static unsigned long AlphaHash(const char *Text, size_t Length) /*{{{*/
+{
+ /* This very simple hash function for the last 8 letters gives
+ very good performance on the debian package files */
+ if (Length > 8)
+ {
+ Text += (Length - 8);
+ Length = 8;
+ }
+ unsigned long Res = 0;
+ for (size_t i = 0; i < Length; ++i)
+ Res = ((unsigned long)(Text[i]) & 0xDF) ^ (Res << 1);
+ return Res & 0xFF;
+}
+ /*}}}*/
+
// TagFile::pkgTagFile - Constructor /*{{{*/
// ---------------------------------------------------------------------
/* */
pkgTagFile::pkgTagFile(FileFd *pFd,unsigned long long Size)
+ : d(NULL)
+{
+ Init(pFd, Size);
+}
+
+void pkgTagFile::Init(FileFd *pFd,unsigned long long Size)
{
/* The size is increased by 4 because if we start with the Size of the
filename we need to try to read 1 char more to see an EOF faster, 1
char the end-pointer can be on and maybe 2 newlines need to be added
to the end of the file -> 4 extra chars */
Size += 4;
+ if(d != NULL)
+ {
+ free(d->Buffer);
+ delete d;
+ }
d = new pkgTagFilePrivate(pFd, Size);
if (d->Fd.IsOpen() == false)
@@ -128,18 +155,23 @@ bool pkgTagFile::Resize(unsigned long long const newSize)
*/
bool pkgTagFile::Step(pkgTagSection &Tag)
{
- while (Tag.Scan(d->Start,d->End - d->Start) == false)
+ if(Tag.Scan(d->Start,d->End - d->Start) == false)
{
- if (Fill() == false)
- return false;
-
- if(Tag.Scan(d->Start,d->End - d->Start))
- break;
+ do
+ {
+ if (Fill() == false)
+ return false;
- if (Resize() == false)
- return _error->Error(_("Unable to parse package file %s (1)"),
- d->Fd.Name().c_str());
+ if(Tag.Scan(d->Start,d->End - d->Start, false))
+ break;
+
+ if (Resize() == false)
+ return _error->Error(_("Unable to parse package file %s (1)"),
+ d->Fd.Name().c_str());
+
+ } while (Tag.Scan(d->Start,d->End - d->Start, false) == false);
}
+
d->Start += Tag.size();
d->iOffset += Tag.size();
@@ -233,7 +265,7 @@ bool pkgTagFile::Jump(pkgTagSection &Tag,unsigned long long Offset)
if (Fill() == false)
return false;
- if (Tag.Scan(d->Start, d->End - d->Start) == false)
+ if (Tag.Scan(d->Start, d->End - d->Start, false) == false)
return _error->Error(_("Unable to parse package file %s (2)"),d->Fd.Name().c_str());
return true;
@@ -243,27 +275,46 @@ bool pkgTagFile::Jump(pkgTagSection &Tag,unsigned long long Offset)
// ---------------------------------------------------------------------
/* */
pkgTagSection::pkgTagSection()
- : Section(0), TagCount(0), d(NULL), Stop(0)
+ : Section(0), d(NULL), Stop(0)
{
- memset(&Indexes, 0, sizeof(Indexes));
- memset(&AlphaIndexes, 0, sizeof(AlphaIndexes));
+ memset(&LookupTable, 0, sizeof(LookupTable));
}
/*}}}*/
// TagSection::Scan - Scan for the end of the header information /*{{{*/
-// ---------------------------------------------------------------------
-/* This looks for the first double new line in the data stream.
- It also indexes the tags in the section. */
-bool pkgTagSection::Scan(const char *Start,unsigned long MaxLength)
+bool pkgTagSection::Scan(const char *Start,unsigned long MaxLength, bool const Restart)
{
+ Section = Start;
const char *End = Start + MaxLength;
- Stop = Section = Start;
- memset(AlphaIndexes,0,sizeof(AlphaIndexes));
+
+ if (Restart == false && Tags.empty() == false)
+ {
+ Stop = Section + Tags.back().StartTag;
+ if (End <= Stop)
+ return false;
+ Stop = (const char *)memchr(Stop,'\n',End - Stop);
+ if (Stop == NULL)
+ return false;
+ ++Stop;
+ }
+ else
+ {
+ Stop = Section;
+ if (Tags.empty() == false)
+ {
+ memset(&LookupTable, 0, sizeof(LookupTable));
+ Tags.clear();
+ }
+ Tags.reserve(0x100);
+ }
+ size_t TagCount = Tags.size();
if (Stop == 0)
return false;
- TagCount = 0;
- while (TagCount+1 < sizeof(Indexes)/sizeof(Indexes[0]) && Stop < End)
+ TagData lastTagData(0);
+ lastTagData.EndTag = 0;
+ unsigned long lastTagHash = 0;
+ while (Stop < End)
{
TrimRecord(true,End);
@@ -275,12 +326,39 @@ bool pkgTagSection::Scan(const char *Start,unsigned long MaxLength)
// Start a new index and add it to the hash
if (isspace(Stop[0]) == 0)
{
- Indexes[TagCount++] = Stop - Section;
- AlphaIndexes[AlphaHash(Stop,End)] = TagCount;
+ // store the last found tag
+ if (lastTagData.EndTag != 0)
+ {
+ if (LookupTable[lastTagHash] != 0)
+ lastTagData.NextInBucket = LookupTable[lastTagHash];
+ LookupTable[lastTagHash] = TagCount;
+ Tags.push_back(lastTagData);
+ }
+
+ ++TagCount;
+ lastTagData = TagData(Stop - Section);
+ // find the colon separating tag and value
+ char const * Colon = (char const *) memchr(Stop, ':', End - Stop);
+ if (Colon == NULL)
+ return false;
+ // find the end of the tag (which might or might not be the colon)
+ char const * EndTag = Colon;
+ --EndTag;
+ for (; EndTag > Stop && isspace(*EndTag) != 0; --EndTag)
+ ;
+ ++EndTag;
+ lastTagData.EndTag = EndTag - Section;
+ lastTagHash = AlphaHash(Stop, EndTag - Stop);
+ // find the beginning of the value
+ Stop = Colon + 1;
+ for (; isspace(*Stop) != 0; ++Stop);
+ if (Stop >= End)
+ return false;
+ lastTagData.StartValue = Stop - Section;
}
Stop = (const char *)memchr(Stop,'\n',End - Stop);
-
+
if (Stop == 0)
return false;
@@ -291,7 +369,16 @@ bool pkgTagSection::Scan(const char *Start,unsigned long MaxLength)
// Double newline marks the end of the record
if (Stop+1 < End && Stop[1] == '\n')
{
- Indexes[TagCount] = Stop - Section;
+ if (lastTagData.EndTag != 0)
+ {
+ if (LookupTable[lastTagHash] != 0)
+ lastTagData.NextInBucket = LookupTable[lastTagHash];
+ LookupTable[lastTagHash] = TagCount;
+ Tags.push_back(lastTagData);
+ }
+
+ TagData const td(Stop - Section);
+ Tags.push_back(td);
TrimRecord(false,End);
return true;
}
@@ -320,8 +407,8 @@ void pkgTagSection::Trim()
for (; Stop > Section + 2 && (Stop[-2] == '\n' || Stop[-2] == '\r'); Stop--);
}
/*}}}*/
-// TagSection::Exists - return True if a tag exists /*{{{*/
-bool pkgTagSection::Exists(const char* const Tag)
+// TagSection::Exists - return True if a tag exists /*{{{*/
+bool pkgTagSection::Exists(const char* const Tag) const
{
unsigned int tmp;
return Find(Tag, tmp);
@@ -332,73 +419,43 @@ bool pkgTagSection::Exists(const char* const Tag)
/* This searches the section for a tag that matches the given string. */
bool pkgTagSection::Find(const char *Tag,unsigned int &Pos) const
{
- unsigned int Length = strlen(Tag);
- unsigned int I = AlphaIndexes[AlphaHash(Tag)];
- if (I == 0)
+ size_t const Length = strlen(Tag);
+ unsigned int Bucket = LookupTable[AlphaHash(Tag, Length)];
+ if (Bucket == 0)
return false;
- I--;
-
- for (unsigned int Counter = 0; Counter != TagCount; Counter++,
- I = (I+1)%TagCount)
+
+ for (; Bucket != 0; Bucket = Tags[Bucket - 1].NextInBucket)
{
- const char *St;
- St = Section + Indexes[I];
- if (strncasecmp(Tag,St,Length) != 0)
+ if ((Tags[Bucket - 1].EndTag - Tags[Bucket - 1].StartTag) != Length)
continue;
- // Make sure the colon is in the right place
- const char *C = St + Length;
- for (; isspace(*C) != 0; C++);
- if (*C != ':')
+ char const * const St = Section + Tags[Bucket - 1].StartTag;
+ if (strncasecmp(Tag,St,Length) != 0)
continue;
- Pos = I;
+
+ Pos = Bucket - 1;
return true;
}
Pos = 0;
return false;
}
- /*}}}*/
-// TagSection::Find - Locate a tag /*{{{*/
-// ---------------------------------------------------------------------
-/* This searches the section for a tag that matches the given string. */
bool pkgTagSection::Find(const char *Tag,const char *&Start,
const char *&End) const
{
- unsigned int Length = strlen(Tag);
- unsigned int I = AlphaIndexes[AlphaHash(Tag)];
- if (I == 0)
+ unsigned int Pos;
+ if (Find(Tag, Pos) == false)
return false;
- I--;
-
- for (unsigned int Counter = 0; Counter != TagCount; Counter++,
- I = (I+1)%TagCount)
- {
- const char *St;
- St = Section + Indexes[I];
- if (strncasecmp(Tag,St,Length) != 0)
- continue;
-
- // Make sure the colon is in the right place
- const char *C = St + Length;
- for (; isspace(*C) != 0; C++);
- if (*C != ':')
- continue;
- // Strip off the gunk from the start end
- Start = C;
- End = Section + Indexes[I+1];
- if (Start >= End)
- return _error->Error("Internal parsing error");
-
- for (; (isspace(*Start) != 0 || *Start == ':') && Start < End; Start++);
- for (; isspace(End[-1]) != 0 && End > Start; End--);
-
- return true;
- }
-
- Start = End = 0;
- return false;
+ Start = Section + Tags[Pos].StartValue;
+ // Strip off the gunk from the end
+ End = Section + Tags[Pos + 1].StartTag;
+ if (unlikely(Start > End))
+ return _error->Error("Internal parsing error");
+
+ for (; isspace(End[-1]) != 0 && End > Start; --End);
+
+ return true;
}
/*}}}*/
// TagSection::FindS - Find a string /*{{{*/
@@ -461,6 +518,17 @@ unsigned long long pkgTagSection::FindULL(const char *Tag, unsigned long long co
return Result;
}
/*}}}*/
+// TagSection::FindB - Find boolean value /*{{{*/
+// ---------------------------------------------------------------------
+/* */
+bool pkgTagSection::FindB(const char *Tag, bool const &Default) const
+{
+ const char *Start, *Stop;
+ if (Find(Tag, Start, Stop) == false)
+ return Default;
+ return StringToBool(string(Start, Stop));
+}
+ /*}}}*/
// TagSection::FindFlag - Locate a yes/no type flag /*{{{*/
// ---------------------------------------------------------------------
/* The bits marked in Flag are masked on/off in Flags */
@@ -493,6 +561,13 @@ bool pkgTagSection::FindFlag(unsigned long &Flags, unsigned long Flag,
return true;
}
/*}}}*/
+APT_PURE unsigned int pkgTagSection::Count() const { /*{{{*/
+ if (Tags.empty() == true)
+ return 0;
+ // the last element is just marking the end and isn't a real one
+ return Tags.size() - 1;
+}
+ /*}}}*/
// TFRewrite - Rewrite a control record /*{{{*/
// ---------------------------------------------------------------------
/* This writes the control record to stdout rewriting it as necessary. The
@@ -682,3 +757,5 @@ bool TFRewrite(FILE *Output,pkgTagSection const &Tags,const char *Order[],
return true;
}
/*}}}*/
+
+pkgTagSection::~pkgTagSection() {}
diff --git a/apt-pkg/tagfile.h b/apt-pkg/tagfile.h
index d5b62e76d..4cd99b2fc 100644
--- a/apt-pkg/tagfile.h
+++ b/apt-pkg/tagfile.h
@@ -25,6 +25,8 @@
#include <stdio.h>
#include <string>
+#include <vector>
+#include <list>
#ifndef APT_8_CLEANER_HEADERS
#include <apt-pkg/fileutl.h>
@@ -35,23 +37,20 @@ class FileFd;
class pkgTagSection
{
const char *Section;
- // We have a limit of 256 tags per section.
- unsigned int Indexes[256];
- unsigned int AlphaIndexes[0x100];
- unsigned int TagCount;
+ struct TagData {
+ unsigned int StartTag;
+ unsigned int EndTag;
+ unsigned int StartValue;
+ unsigned int NextInBucket;
+
+ TagData(unsigned int const StartTag) : StartTag(StartTag), EndTag(0), StartValue(0), NextInBucket(0) {}
+ };
+ std::vector<TagData> Tags;
+ unsigned int LookupTable[0x100];
+
// dpointer placeholder (for later in case we need it)
void *d;
- /* This very simple hash function for the last 8 letters gives
- very good performance on the debian package files */
- inline static unsigned long AlphaHash(const char *Text, const char *End = 0)
- {
- unsigned long Res = 0;
- for (; Text != End && *Text != ':' && *Text != 0; Text++)
- Res = ((unsigned long)(*Text) & 0xDF) ^ (Res << 1);
- return Res & 0xFF;
- }
-
protected:
const char *Stop;
@@ -63,23 +62,46 @@ class pkgTagSection
bool Find(const char *Tag,const char *&Start, const char *&End) const;
bool Find(const char *Tag,unsigned int &Pos) const;
std::string FindS(const char *Tag) const;
- signed int FindI(const char *Tag,signed long Default = 0) const ;
+ signed int FindI(const char *Tag,signed long Default = 0) const;
+ bool FindB(const char *Tag, bool const &Default = false) const;
unsigned long long FindULL(const char *Tag, unsigned long long const &Default = 0) const;
bool FindFlag(const char *Tag,unsigned long &Flags,
unsigned long Flag) const;
bool static FindFlag(unsigned long &Flags, unsigned long Flag,
const char* Start, const char* Stop);
- bool Scan(const char *Start,unsigned long MaxLength);
+
+ /** \brief searches the boundaries of the current section
+ *
+ * While parameter Start marks the beginning of the section, this method
+ * will search for the first double newline in the data stream which marks
+ * the end of the section. It also does a first pass over the content of
+ * the section parsing it as encountered for processing later on by Find
+ *
+ * @param Start is the beginning of the section
+ * @param MaxLength is the size of valid data in the stream pointed to by Start
+ * @param Restart if enabled internal state will be cleared, otherwise it is
+ * assumed that now more data is available in the stream and the parsing will
+ * start were it encountered insufficent data the last time.
+ *
+ * @return \b true if section end was found, \b false otherwise.
+ * Beware that internal state will be inconsistent if \b false is returned!
+ */
+ APT_MUSTCHECK bool Scan(const char *Start, unsigned long MaxLength, bool const Restart = true);
inline unsigned long size() const {return Stop - Section;};
void Trim();
virtual void TrimRecord(bool BeforeRecord, const char* &End);
-
- inline unsigned int Count() const {return TagCount;};
- bool Exists(const char* const Tag);
-
+
+ /** \brief amount of Tags in the current section
+ *
+ * Note: if a Tag is mentioned repeatly it will be counted multiple
+ * times, but only the last occurrence is available via Find methods.
+ */
+ unsigned int Count() const;
+ bool Exists(const char* const Tag) const;
+
inline void Get(const char *&Start,const char *&Stop,unsigned int I) const
- {Start = Section + Indexes[I]; Stop = Section + Indexes[I+1];}
-
+ {Start = Section + Tags[I].StartTag; Stop = Section + Tags[I+1].StartTag;}
+
inline void GetSection(const char *&Start,const char *&Stop) const
{
Start = Section;
@@ -87,7 +109,7 @@ class pkgTagSection
};
pkgTagSection();
- virtual ~pkgTagSection() {};
+ virtual ~pkgTagSection();
};
class pkgTagFilePrivate;
@@ -105,6 +127,8 @@ class pkgTagFile
unsigned long Offset();
bool Jump(pkgTagSection &Tag,unsigned long long Offset);
+ void Init(FileFd *F,unsigned long long Size = 32*1024);
+
pkgTagFile(FileFd *F,unsigned long long Size = 32*1024);
virtual ~pkgTagFile();
};
diff --git a/apt-pkg/update.cc b/apt-pkg/update.cc
index 5d5b19626..2908a4820 100644
--- a/apt-pkg/update.cc
+++ b/apt-pkg/update.cc
@@ -27,8 +27,8 @@ bool ListUpdate(pkgAcquireStatus &Stat,
pkgSourceList &List,
int PulseInterval)
{
- pkgAcquire Fetcher;
- if (Fetcher.Setup(&Stat, _config->FindDir("Dir::State::Lists")) == false)
+ pkgAcquire Fetcher(&Stat);
+ if (Fetcher.GetLock(_config->FindDir("Dir::State::Lists")) == false)
return false;
// Populate it with the source selection
diff --git a/apt-pkg/update.h b/apt-pkg/update.h
index 3835644de..e35cd14f6 100644
--- a/apt-pkg/update.h
+++ b/apt-pkg/update.h
@@ -11,7 +11,8 @@
#define PKGLIB_UPDATE_H
class pkgAcquireStatus;
-
+class pkgSourceList;
+class pkgAcquire;
bool ListUpdate(pkgAcquireStatus &progress, pkgSourceList &List, int PulseInterval=0);
bool AcquireUpdate(pkgAcquire &Fetcher, int const PulseInterval = 0,
diff --git a/apt-pkg/upgrade.cc b/apt-pkg/upgrade.cc
index 29b11937b..ca670bdf5 100644
--- a/apt-pkg/upgrade.cc
+++ b/apt-pkg/upgrade.cc
@@ -24,13 +24,14 @@
The problem resolver is used to resolve the problems.
*/
-bool pkgDistUpgrade(pkgDepCache &Cache)
+bool pkgDistUpgrade(pkgDepCache &Cache, OpProgress * const Progress)
{
std::string const solver = _config->Find("APT::Solver", "internal");
- if (solver != "internal") {
- OpTextProgress Prog(*_config);
- return EDSP::ResolveExternal(solver.c_str(), Cache, false, true, false, &Prog);
- }
+ if (solver != "internal")
+ return EDSP::ResolveExternal(solver.c_str(), Cache, false, true, false, Progress);
+
+ if (Progress != NULL)
+ Progress->OverallProgress(0, 100, 1, _("Calculating upgrade"));
pkgDepCache::ActionGroup group(Cache);
@@ -41,12 +42,18 @@ bool pkgDistUpgrade(pkgDepCache &Cache)
if (I->CurrentVer != 0)
Cache.MarkInstall(I, false, 0, false);
+ if (Progress != NULL)
+ Progress->Progress(10);
+
/* Auto upgrade all installed packages, this provides the basis
for the installation */
for (pkgCache::PkgIterator I = Cache.PkgBegin(); I.end() == false; ++I)
if (I->CurrentVer != 0)
Cache.MarkInstall(I, true, 0, false);
+ if (Progress != NULL)
+ Progress->Progress(50);
+
/* Now, install each essential package which is not installed
(and not provided by another package in the same name group) */
std::string essential = _config->Find("pkgCacheGen::Essential", "all");
@@ -77,15 +84,24 @@ bool pkgDistUpgrade(pkgDepCache &Cache)
for (pkgCache::PkgIterator I = Cache.PkgBegin(); I.end() == false; ++I)
if ((I->Flags & pkgCache::Flag::Essential) == pkgCache::Flag::Essential)
Cache.MarkInstall(I, true, 0, false);
-
+
+ if (Progress != NULL)
+ Progress->Progress(55);
+
/* We do it again over all previously installed packages to force
conflict resolution on them all. */
for (pkgCache::PkgIterator I = Cache.PkgBegin(); I.end() == false; ++I)
if (I->CurrentVer != 0)
Cache.MarkInstall(I, false, 0, false);
+ if (Progress != NULL)
+ Progress->Progress(65);
+
pkgProblemResolver Fix(&Cache);
+ if (Progress != NULL)
+ Progress->Progress(95);
+
// Hold back held packages.
if (_config->FindB("APT::Ignore-Hold",false) == false)
{
@@ -98,18 +114,22 @@ bool pkgDistUpgrade(pkgDepCache &Cache)
}
}
}
-
- return Fix.Resolve();
+
+ bool const success = Fix.Resolve(false, Progress);
+ if (Progress != NULL)
+ Progress->Done();
+ return success;
}
/*}}}*/
// AllUpgradeNoNewPackages - Upgrade but no removals or new pkgs /*{{{*/
-static bool pkgAllUpgradeNoNewPackages(pkgDepCache &Cache)
+static bool pkgAllUpgradeNoNewPackages(pkgDepCache &Cache, OpProgress * const Progress)
{
std::string const solver = _config->Find("APT::Solver", "internal");
- if (solver != "internal") {
- OpTextProgress Prog(*_config);
- return EDSP::ResolveExternal(solver.c_str(), Cache, true, false, false, &Prog);
- }
+ if (solver != "internal")
+ return EDSP::ResolveExternal(solver.c_str(), Cache, true, false, false, Progress);
+
+ if (Progress != NULL)
+ Progress->OverallProgress(0, 100, 1, _("Calculating upgrade"));
pkgDepCache::ActionGroup group(Cache);
@@ -131,8 +151,15 @@ static bool pkgAllUpgradeNoNewPackages(pkgDepCache &Cache)
if (I->CurrentVer != 0 && Cache[I].InstallVer != 0)
Cache.MarkInstall(I, false, 0, false);
}
-
- return Fix.ResolveByKeep();
+
+ if (Progress != NULL)
+ Progress->Progress(50);
+
+ // resolve remaining issues via keep
+ bool const success = Fix.ResolveByKeep(Progress);
+ if (Progress != NULL)
+ Progress->Done();
+ return success;
}
/*}}}*/
// AllUpgradeWithNewInstalls - Upgrade + install new packages as needed /*{{{*/
@@ -141,13 +168,14 @@ static bool pkgAllUpgradeNoNewPackages(pkgDepCache &Cache)
* Upgrade as much as possible without deleting anything (useful for
* stable systems)
*/
-static bool pkgAllUpgradeWithNewPackages(pkgDepCache &Cache)
+static bool pkgAllUpgradeWithNewPackages(pkgDepCache &Cache, OpProgress * const Progress)
{
std::string const solver = _config->Find("APT::Solver", "internal");
- if (solver != "internal") {
- OpTextProgress Prog(*_config);
- return EDSP::ResolveExternal(solver.c_str(), Cache, true, false, false, &Prog);
- }
+ if (solver != "internal")
+ return EDSP::ResolveExternal(solver.c_str(), Cache, true, false, false, Progress);
+
+ if (Progress != NULL)
+ Progress->OverallProgress(0, 100, 1, _("Calculating upgrade"));
pkgDepCache::ActionGroup group(Cache);
@@ -170,18 +198,30 @@ static bool pkgAllUpgradeWithNewPackages(pkgDepCache &Cache)
}
}
+ if (Progress != NULL)
+ Progress->Progress(10);
+
// then let auto-install loose
for (pkgCache::PkgIterator I = Cache.PkgBegin(); I.end() == false; ++I)
if (Cache[I].Install())
Cache.MarkInstall(I, true, 0, false);
+ if (Progress != NULL)
+ Progress->Progress(50);
+
// ... but it may remove stuff, we we need to clean up afterwards again
for (pkgCache::PkgIterator I = Cache.PkgBegin(); I.end() == false; ++I)
if (Cache[I].Delete() == true)
Cache.MarkKeep(I, false, false);
+ if (Progress != NULL)
+ Progress->Progress(60);
+
// resolve remaining issues via keep
- return Fix.ResolveByKeep();
+ bool const success = Fix.ResolveByKeep(Progress);
+ if (Progress != NULL)
+ Progress->Done();
+ return success;
}
/*}}}*/
// AllUpgrade - Upgrade as many packages as possible /*{{{*/
@@ -189,9 +229,9 @@ static bool pkgAllUpgradeWithNewPackages(pkgDepCache &Cache)
/* Right now the system must be consistent before this can be called.
It also will not change packages marked for install, it only tries
to install packages not marked for install */
-bool pkgAllUpgrade(pkgDepCache &Cache)
+bool pkgAllUpgrade(pkgDepCache &Cache, OpProgress * const Progress)
{
- return pkgAllUpgradeNoNewPackages(Cache);
+ return pkgAllUpgradeNoNewPackages(Cache, Progress);
}
/*}}}*/
// MinimizeUpgrade - Minimizes the set of packages to be upgraded /*{{{*/
@@ -239,24 +279,25 @@ bool pkgMinimizeUpgrade(pkgDepCache &Cache)
return true;
}
/*}}}*/
-// APT::Upgrade::Upgrade - Upgrade using a specific strategy /*{{{*/
-bool APT::Upgrade::Upgrade(pkgDepCache &Cache, int mode)
+// APT::Upgrade::Upgrade - Upgrade using a specific strategy /*{{{*/
+bool APT::Upgrade::Upgrade(pkgDepCache &Cache, int mode, OpProgress * const Progress)
{
- if (mode == 0)
- {
- return pkgDistUpgrade(Cache);
- }
+#if __GNUC__ >= 4
+ // the deprecated methods will become our privates, so that is fine
+ #pragma GCC diagnostic push
+ #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+ if (mode == ALLOW_EVERYTHING)
+ return pkgDistUpgrade(Cache, Progress);
else if ((mode & ~FORBID_REMOVE_PACKAGES) == 0)
- {
- return pkgAllUpgradeWithNewPackages(Cache);
- }
+ return pkgAllUpgradeWithNewPackages(Cache, Progress);
else if ((mode & ~(FORBID_REMOVE_PACKAGES|FORBID_INSTALL_NEW_PACKAGES)) == 0)
- {
- return pkgAllUpgradeNoNewPackages(Cache);
- }
+ return pkgAllUpgradeNoNewPackages(Cache, Progress);
else
_error->Error("pkgAllUpgrade called with unsupported mode %i", mode);
-
+#if __GNUC__ >= 4
+ #pragma GCC diagnostic pop
+#endif
return false;
}
/*}}}*/
diff --git a/apt-pkg/upgrade.h b/apt-pkg/upgrade.h
index aa883df10..a3f693d86 100644
--- a/apt-pkg/upgrade.h
+++ b/apt-pkg/upgrade.h
@@ -10,23 +10,27 @@
#ifndef PKGLIB_UPGRADE_H
#define PKGLIB_UPGRADE_H
+#include <stddef.h>
+#include <apt-pkg/macros.h>
+
class pkgDepCache;
+class OpProgress;
namespace APT {
namespace Upgrade {
// FIXME: make this "enum class UpgradeMode {" once we enable c++11
enum UpgradeMode {
+ ALLOW_EVERYTHING = 0,
FORBID_REMOVE_PACKAGES = 1,
FORBID_INSTALL_NEW_PACKAGES = 2
};
- bool Upgrade(pkgDepCache &Cache, int UpgradeMode);
+ bool Upgrade(pkgDepCache &Cache, int UpgradeMode, OpProgress * const Progress = NULL);
}
}
// please use APT::Upgrade::Upgrade() instead
-bool pkgDistUpgrade(pkgDepCache &Cache);
-bool pkgAllUpgrade(pkgDepCache &Cache);
-bool pkgMinimizeUpgrade(pkgDepCache &Cache);
-
+APT_DEPRECATED bool pkgDistUpgrade(pkgDepCache &Cache, OpProgress * const Progress = NULL);
+APT_DEPRECATED bool pkgAllUpgrade(pkgDepCache &Cache, OpProgress * const Progress = NULL);
+bool pkgMinimizeUpgrade(pkgDepCache &Cache);
#endif