diff options
Diffstat (limited to 'apt-pkg')
67 files changed, 3529 insertions, 1603 deletions
diff --git a/apt-pkg/acquire-item.cc b/apt-pkg/acquire-item.cc index 2401364a9..f46c8a6e4 100644 --- a/apt-pkg/acquire-item.cc +++ b/apt-pkg/acquire-item.cc @@ -50,16 +50,35 @@ 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; +} + /*}}}*/ + // 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) : + Owner(Owner), FileSize(0), PartialSize(0), Mode(0), ID(0), Complete(false), + Local(false), QueueCounter(0), ExpectedAdditionalItems(0), + ExpectedHashes(ExpectedHashes) { Owner->Add(this); Status = StatIdle; } +#if __GNUC__ >= 4 + #pragma GCC diagnostic pop +#endif /*}}}*/ // Acquire::Item::~Item - Destructor /*{{{*/ // --------------------------------------------------------------------- @@ -117,7 +136,7 @@ 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.. @@ -228,8 +247,8 @@ void pkgAcquire::Item::ReportMirrorFailure(string FailCode) possibly query additional files */ pkgAcqSubIndex::pkgAcqSubIndex(pkgAcquire *Owner, string const &URI, string const &URIDesc, string const &ShortDesc, - HashString const &ExpectedHash) - : Item(Owner), ExpectedHash(ExpectedHash) + HashStringList const &ExpectedHashes) + : Item(Owner, ExpectedHashes) { /* XXX: Beware: Currently this class does nothing (of value) anymore ! */ Debug = _config->FindB("Debug::pkgAcquire::SubIndex",false); @@ -251,7 +270,7 @@ pkgAcqSubIndex::pkgAcqSubIndex(pkgAcquire *Owner, string const &URI, // AcqSubIndex::Custom600Headers - Insert custom request headers /*{{{*/ // --------------------------------------------------------------------- /* The only header we use is the last-modified header. */ -string pkgAcqSubIndex::Custom600Headers() +string pkgAcqSubIndex::Custom600Headers() const { string Final = _config->FindDir("Dir::State::lists"); Final += URItoFileName(Desc.URI); @@ -274,7 +293,7 @@ void pkgAcqSubIndex::Failed(string Message,pkgAcquire::MethodConfig * /*Cnf*/)/* // No good Index is provided } /*}}}*/ -void pkgAcqSubIndex::Done(string Message,unsigned long long Size,string Md5Hash, /*{{{*/ +void pkgAcqSubIndex::Done(string Message,unsigned long long Size,HashStringList const &Hashes, /*{{{*/ pkgAcquire::MethodConfig *Cnf) { if(Debug) @@ -296,7 +315,7 @@ void pkgAcqSubIndex::Done(string Message,unsigned long long Size,string Md5Hash, return; } - Item::Done(Message,Size,Md5Hash,Cnf); + Item::Done(Message, Size, Hashes, Cnf); string FinalFile = _config->FindDir("Dir::State::lists")+URItoFileName(Desc.URI); @@ -342,18 +361,19 @@ 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) + IndexTarget const * const Target, + HashStringList const &ExpectedHashes, + indexRecords *MetaIndexParser) + : pkgAcqBaseIndex(Owner, Target, ExpectedHashes, MetaIndexParser) { 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 + "/DiffIndex"; + Desc.ShortDesc = Target->ShortDesc; + Desc.URI = Target->URI + ".diff/Index"; DestFile = _config->FindDir("Dir::State::lists") + "partial/"; DestFile += URItoFileName(Desc.URI); @@ -389,7 +409,7 @@ 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); @@ -442,8 +462,8 @@ bool pkgAcqDiffIndex::ParseDiffIndex(string IndexDiffFile) /*{{{*/ 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); + new pkgAcqIndexDiffs(Owner, Target, ExpectedHashes, MetaIndexParser, + ServerSha1, available_patches); return true; } else @@ -528,14 +548,19 @@ bool pkgAcqDiffIndex::ParseDiffIndex(string IndexDiffFile) /*{{{*/ } if (pdiff_merge == false) - new pkgAcqIndexDiffs(Owner, RealURI, Description, Desc.ShortDesc, - ExpectedHash, ServerSha1, available_patches); - else + { + new pkgAcqIndexDiffs(Owner, Target, ExpectedHashes, MetaIndexParser, + ServerSha1, 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, RealURI, Description, Desc.ShortDesc, ExpectedHash, - available_patches[i], diffs); + (*diffs)[i] = new pkgAcqIndexMergeDiffs(Owner, Target, + ExpectedHashes, + MetaIndexParser, + available_patches[i], + diffs); } Complete = false; @@ -559,21 +584,20 @@ void pkgAcqDiffIndex::Failed(string Message,pkgAcquire::MethodConfig * /*Cnf*/)/ 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, Target, ExpectedHashes, MetaIndexParser); Complete = false; 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); string FinalFile; FinalFile = _config->FindDir("Dir::State::lists")+URItoFileName(RealURI); @@ -603,22 +627,24 @@ 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, + struct IndexTarget const * const Target, + HashStringList const &ExpectedHashes, + indexRecords *MetaIndexParser, string ServerSha1, vector<DiffInfo> diffs) - : Item(Owner), RealURI(URI), ExpectedHash(ExpectedHash), + : pkgAcqBaseIndex(Owner, Target, ExpectedHashes, MetaIndexParser), available_patches(diffs), ServerSha1(ServerSha1) { DestFile = _config->FindDir("Dir::State::lists") + "partial/"; - DestFile += URItoFileName(URI); + DestFile += URItoFileName(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) { @@ -638,8 +664,7 @@ 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, Target, ExpectedHashes, MetaIndexParser); Finish(); } /*}}}*/ @@ -653,7 +678,7 @@ void pkgAcqIndexDiffs::Finish(bool 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(); @@ -731,13 +756,13 @@ bool pkgAcqIndexDiffs::QueueNextDiff() /*{{{*/ 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); @@ -756,7 +781,15 @@ void pkgAcqIndexDiffs::Done(string Message,unsigned long long Size,string Md5Has Local = true; Desc.URI = "rred:" + FinalFile; QueueURI(Desc); + ActiveSubprocess = "rred"; +#if __GNUC__ >= 4 + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif Mode = "rred"; +#if __GNUC__ >= 4 + #pragma GCC diagnostic pop +#endif return; } @@ -779,8 +812,9 @@ 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, Target, + ExpectedHashes, MetaIndexParser, + ServerSha1, available_patches); return Finish(); } else return Finish(true); @@ -789,22 +823,24 @@ void pkgAcqIndexDiffs::Done(string Message,unsigned long long Size,string Md5Has /*}}}*/ // 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) + struct IndexTarget const * const Target, + HashStringList const &ExpectedHashes, + indexRecords *MetaIndexParser, + DiffInfo const &patch, + std::vector<pkgAcqIndexMergeDiffs*> const * const allPatches) + : pkgAcqBaseIndex(Owner, Target, ExpectedHashes, MetaIndexParser), + patch(patch), allPatches(allPatches), State(StateFetchDiff) { DestFile = _config->FindDir("Dir::State::lists") + "partial/"; - DestFile += URItoFileName(URI); + DestFile += URItoFileName(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; Desc.URI = RealURI + ".diff/" + patch.file + ".gz"; Desc.Description = Description + " " + patch.file + string(".pdiff"); @@ -835,17 +871,16 @@ 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, 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); @@ -874,14 +909,22 @@ void pkgAcqIndexMergeDiffs::Done(string Message,unsigned long long Size,string M Local = true; Desc.URI = "rred:" + FinalFile; QueueURI(Desc); + ActiveSubprocess = "rred"; +#if __GNUC__ >= 4 + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif Mode = "rred"; +#if __GNUC__ >= 4 + #pragma GCC diagnostic pop +#endif 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; @@ -918,8 +961,8 @@ void pkgAcqIndexMergeDiffs::Done(string Message,unsigned long long Size,string M 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, string comprExt) + : pkgAcqBaseIndex(Owner, NULL, ExpectedHash, NULL), RealURI(URI) { if(comprExt.empty() == true) { @@ -935,13 +978,15 @@ pkgAcqIndex::pkgAcqIndex(pkgAcquire *Owner, Init(URI, URIDesc, ShortDesc); } pkgAcqIndex::pkgAcqIndex(pkgAcquire *Owner, IndexTarget const *Target, - HashString const &ExpectedHash, indexRecords const *MetaIndexParser) - : Item(Owner), RealURI(Target->URI), ExpectedHash(ExpectedHash) + HashStringList const &ExpectedHash, + indexRecords *MetaIndexParser) + : pkgAcqBaseIndex(Owner, Target, ExpectedHash, MetaIndexParser), + RealURI(Target->URI) { // autoselect the compression method std::vector<std::string> types = APT::Configuration::getCompressionTypes(); CompressionExtension = ""; - if (ExpectedHash.empty() == false) + 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) @@ -967,11 +1012,29 @@ void pkgAcqIndex::Init(string const &URI, string const &URIDesc, string const &S DestFile += URItoFileName(URI); std::string const comprExt = CompressionExtension.substr(0, CompressionExtension.find(' ')); + std::string MetaKey; if (comprExt == "uncompressed") + { Desc.URI = URI; - else { + if(Target) + MetaKey = string(Target->MetaKey); + } + else + { Desc.URI = URI + '.' + comprExt; DestFile = DestFile + '.' + comprExt; + if(Target) + MetaKey = string(Target->MetaKey) + '.' + comprExt; + } + + // load the filesize + if(MetaIndexParser) + { + indexRecords::checkSum *Record = MetaIndexParser->Lookup(MetaKey); + if(Record) + FileSize = Record->Size; + + InitByHashIfNeeded(MetaKey); } Desc.Description = URIDesc; @@ -981,10 +1044,42 @@ 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"); @@ -993,10 +1088,7 @@ string pkgAcqIndex::Custom600Headers() Final += compExt; 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); @@ -1056,24 +1148,19 @@ void pkgAcqIndex::ReverifyAfterIMS(std::string const &FileName) 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, +void pkgAcqIndex::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); std::string const compExt = CompressionExtension.substr(0, CompressionExtension.find(' ')); if (Decompression == true) { - 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) + if (ExpectedHashes.usable() && ExpectedHashes != Hashes) { Desc.URI = RealURI; RenameOnError(HashSumMismatch); + printHashSumComparision(RealURI, ExpectedHashes, Hashes); return; } @@ -1102,7 +1189,7 @@ void pkgAcqIndex::Done(string Message,unsigned long long Size,string Hash, 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/"; @@ -1113,6 +1200,7 @@ void pkgAcqIndex::Done(string Message,unsigned long long Size,string Hash, // Remove the compressed version. if (Erase == true) unlink(DestFile.c_str()); + return; } @@ -1128,7 +1216,15 @@ void pkgAcqIndex::Done(string Message,unsigned long long Size,string Hash, DestFile += ".decomp"; Desc.URI = "copy:" + FileName; QueueURI(Desc); + ActiveSubprocess = "copy"; +#if __GNUC__ >= 4 + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif Mode = "copy"; +#if __GNUC__ >= 4 + #pragma GCC diagnostic pop +#endif return; } @@ -1195,8 +1291,15 @@ void pkgAcqIndex::Done(string Message,unsigned long long Size,string Hash, Desc.URI = decompProg + ":" + FileName; QueueURI(Desc); - // FIXME: this points to a c++ string that goes out of scope - Mode = decompProg.c_str(); + ActiveSubprocess = decompProg; +#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 } /*}}}*/ // AcqIndexTrans::pkgAcqIndexTrans - Constructor /*{{{*/ @@ -1204,18 +1307,22 @@ void pkgAcqIndex::Done(string Message,unsigned long long Size,string Hash, /* The Translation file is added to the queue */ pkgAcqIndexTrans::pkgAcqIndexTrans(pkgAcquire *Owner, string URI,string URIDesc,string ShortDesc) - : pkgAcqIndex(Owner, URI, URIDesc, ShortDesc, HashString(), "") + : 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, IndexTarget const * const Target, + HashStringList const &ExpectedHashes, indexRecords *MetaIndexParser) + : pkgAcqIndex(Owner, Target, ExpectedHashes, MetaIndexParser) { + // load the filesize + indexRecords::checkSum *Record = MetaIndexParser->Lookup(string(Target->MetaKey)); + if(Record) + FileSize = Record->Size; } /*}}}*/ // 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"); @@ -1262,7 +1369,7 @@ pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire *Owner, /*{{{*/ string MetaIndexShortDesc, const vector<IndexTarget*>* IndexTargets, indexRecords* MetaIndexParser) : - Item(Owner), RealURI(URI), MetaIndexURI(MetaIndexURI), + Item(Owner, HashStringList()), RealURI(URI), MetaIndexURI(MetaIndexURI), MetaIndexURIDesc(MetaIndexURIDesc), MetaIndexShortDesc(MetaIndexShortDesc), MetaIndexParser(MetaIndexParser), IndexTargets(IndexTargets) { @@ -1293,6 +1400,9 @@ pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire *Owner, /*{{{*/ Rename(Final,LastGoodSig); } + // we expect the indextargets + one additional Release file + ExpectedAdditionalItems = IndexTargets->size() + 1; + QueueURI(Desc); } /*}}}*/ @@ -1312,7 +1422,7 @@ pkgAcqMetaSig::~pkgAcqMetaSig() /*{{{*/ // 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) @@ -1321,10 +1431,10 @@ string pkgAcqMetaSig::Custom600Headers() return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime); } -void pkgAcqMetaSig::Done(string Message,unsigned long long Size,string MD5, +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) @@ -1345,6 +1455,9 @@ void pkgAcqMetaSig::Done(string Message,unsigned long long Size,string MD5, Complete = true; + // at this point pkgAcqMetaIndex takes over + ExpectedAdditionalItems = 0; + // 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 @@ -1362,6 +1475,9 @@ void pkgAcqMetaSig::Failed(string Message,pkgAcquire::MethodConfig *Cnf)/*{{{*/ { string Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI); + // at this point pkgAcqMetaIndex takes over + ExpectedAdditionalItems = 0; + // if we get a network error we fail gracefully if(Status == StatTransientNetworkError) { @@ -1398,9 +1514,9 @@ void pkgAcqMetaSig::Failed(string Message,pkgAcquire::MethodConfig *Cnf)/*{{{*/ pkgAcqMetaIndex::pkgAcqMetaIndex(pkgAcquire *Owner, /*{{{*/ string URI,string URIDesc,string ShortDesc, string SigFile, - const vector<struct IndexTarget*>* IndexTargets, + const vector<IndexTarget*>* IndexTargets, indexRecords* MetaIndexParser) : - Item(Owner), RealURI(URI), SigFile(SigFile), IndexTargets(IndexTargets), + Item(Owner, HashStringList()), RealURI(URI), SigFile(SigFile), IndexTargets(IndexTargets), MetaIndexParser(MetaIndexParser), AuthPass(false), IMSHit(false) { DestFile = _config->FindDir("Dir::State::lists") + "partial/"; @@ -1412,13 +1528,16 @@ pkgAcqMetaIndex::pkgAcqMetaIndex(pkgAcquire *Owner, /*{{{*/ Desc.ShortDesc = ShortDesc; Desc.URI = URI; + // 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); @@ -1430,10 +1549,10 @@ string pkgAcqMetaIndex::Custom600Headers() return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime); } /*}}}*/ -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 @@ -1462,16 +1581,35 @@ void pkgAcqMetaIndex::Done(string Message,unsigned long long Size,string Hash, / } else { + // FIXME: move this into pkgAcqMetaClearSig::Done on the next + // ABI break + + // 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 (SigFile == DestFile && !StartsWithGPGClearTextSignature(DestFile)) + { + Failed(Message, Cfg); + return; + } + // 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"; + ActiveSubprocess = "gpgv"; +#if __GNUC__ >= 4 + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + Mode = "gpgv"; +#if __GNUC__ >= 4 + #pragma GCC diagnostic pop +#endif return; } } @@ -1616,11 +1754,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) @@ -1644,14 +1784,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()); @@ -1663,15 +1805,14 @@ void pkgAcqMetaIndex::QueueIndexes(bool verify) /*{{{*/ { if ((*Target)->IsSubIndex() == true) new pkgAcqSubIndex(Owner, (*Target)->URI, (*Target)->Description, - (*Target)->ShortDesc, ExpectedIndexHash); + (*Target)->ShortDesc, ExpectedIndexHashes); else 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, *Target, ExpectedIndexHashes, MetaIndexParser); else - new pkgAcqIndexTrans(Owner, *Target, ExpectedIndexHash, MetaIndexParser); + new pkgAcqIndexTrans(Owner, *Target, ExpectedIndexHashes, MetaIndexParser); } continue; } @@ -1682,10 +1823,9 @@ 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, *Target, ExpectedIndexHashes, MetaIndexParser); else - new pkgAcqIndex(Owner, *Target, ExpectedIndexHash, MetaIndexParser); + new pkgAcqIndex(Owner, *Target, ExpectedIndexHashes, MetaIndexParser); } } /*}}}*/ @@ -1838,7 +1978,7 @@ 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), @@ -1846,6 +1986,10 @@ pkgAcqMetaClearSig::pkgAcqMetaClearSig(pkgAcquire *Owner, /*{{{*/ { 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) @@ -1870,7 +2014,7 @@ pkgAcqMetaClearSig::~pkgAcqMetaClearSig() /*{{{*/ // 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); @@ -1888,6 +2032,9 @@ string pkgAcqMetaClearSig::Custom600Headers() /*}}}*/ void pkgAcqMetaClearSig::Failed(string Message,pkgAcquire::MethodConfig *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 @@ -1916,7 +2063,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) { @@ -2001,7 +2148,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 @@ -2022,31 +2168,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."), @@ -2133,10 +2258,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) @@ -2144,11 +2269,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; } @@ -2220,7 +2346,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; } @@ -2239,11 +2365,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); @@ -2280,15 +2406,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; } @@ -2359,7 +2486,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..74b5de675 100644 --- a/apt-pkg/acquire-item.h +++ b/apt-pkg/acquire-item.h @@ -46,6 +46,7 @@ class indexRecords; class pkgRecords; class pkgSourceList; +class IndexTarget; /** \brief Represents the process by which a pkgAcquire object should {{{ * retrieve a file or a collection of files. @@ -132,7 +133,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,6 +172,16 @@ class pkgAcquire::Item : public WeakPointable * \sa pkgAcquire */ unsigned int QueueCounter; + + /** \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. @@ -201,12 +217,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 +244,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,18 +260,19 @@ 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 @@ -274,12 +291,11 @@ 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()); /** \brief Remove this item from its owner's queue by invoking * pkgAcquire::Remove. @@ -299,6 +315,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). */ /*{{{*/ @@ -325,20 +347,13 @@ class pkgAcqSubIndex : public pkgAcquire::Item /** \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 Hash that this file should have after download - */ - HashString ExpectedHash; - 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 Desc.URI;}; - virtual std::string Custom600Headers(); + virtual std::string Custom600Headers() const; virtual bool ParseIndex(std::string const &IndexFile); /** \brief Create a new pkgAcqSubIndex. @@ -351,10 +366,31 @@ class pkgAcqSubIndex : 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. */ pkgAcqSubIndex(pkgAcquire *Owner, std::string const &URI,std::string const &URIDesc, - std::string const &ShortDesc, HashString const &ExpectedHash); + std::string const &ShortDesc, HashStringList const &ExpectedHashes); +}; + /*}}}*/ + +/** \brief Common base class for all classes that deal with fetching {{{ + indexes + */ +class pkgAcqBaseIndex : public pkgAcquire::Item +{ + protected: + /** \brief Pointer to the IndexTarget data + */ + const struct IndexTarget * Target; + indexRecords *MetaIndexParser; + + pkgAcqBaseIndex(pkgAcquire *Owner, + struct IndexTarget const * const Target, + HashStringList const &ExpectedHashes, + indexRecords *MetaIndexParser) + : Item(Owner, ExpectedHashes), Target(Target), + MetaIndexParser(MetaIndexParser) {}; + }; /*}}}*/ /** \brief An item that is responsible for fetching an index file of {{{ @@ -366,25 +402,17 @@ class pkgAcqSubIndex : public pkgAcquire::Item * * \sa pkgAcqIndexDiffs, pkgAcqIndex */ -class pkgAcqDiffIndex : public pkgAcquire::Item +class pkgAcqDiffIndex : public pkgAcqBaseIndex { 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. */ @@ -398,10 +426,10 @@ class pkgAcqDiffIndex : public pkgAcquire::Item 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 +454,12 @@ 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, + struct IndexTarget const * const Target, + HashStringList const &ExpectedHashes, + indexRecords *MetaIndexParser); }; /*}}}*/ /** \brief An item that is responsible for fetching client-merge patches {{{ @@ -443,7 +473,7 @@ class pkgAcqDiffIndex : public pkgAcquire::Item * * \sa pkgAcqDiffIndex, pkgAcqIndex */ -class pkgAcqIndexMergeDiffs : public pkgAcquire::Item +class pkgAcqIndexMergeDiffs : public pkgAcqBaseIndex { protected: @@ -452,21 +482,11 @@ 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 +519,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 +534,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 +544,12 @@ 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, + 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,7 +563,7 @@ class pkgAcqIndexMergeDiffs : public pkgAcquire::Item * * \sa pkgAcqDiffIndex, pkgAcqIndex */ -class pkgAcqIndexDiffs : public pkgAcquire::Item +class pkgAcqIndexDiffs : public pkgAcqBaseIndex { private: @@ -559,8 +581,8 @@ class pkgAcqIndexDiffs : public pkgAcquire::Item /** \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. * @@ -576,21 +598,11 @@ 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; @@ -632,7 +644,7 @@ 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";}; @@ -650,7 +662,7 @@ 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 md5sum of the completely * reconstructed package index file; the index file will be tested * against this value when it is entirely reconstructed. * @@ -660,8 +672,10 @@ class pkgAcqIndexDiffs : public pkgAcquire::Item * 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, + pkgAcqIndexDiffs(pkgAcquire *Owner, + struct IndexTarget const * const Target, + HashStringList const &ExpectedHash, + indexRecords *MetaIndexParser, std::string ServerSha1, std::vector<DiffInfo> diffs=std::vector<DiffInfo>()); }; @@ -673,7 +687,7 @@ class pkgAcqIndexDiffs : public pkgAcquire::Item * * \todo Why does pkgAcqIndex have protected members? */ -class pkgAcqIndex : public pkgAcquire::Item +class pkgAcqIndex : public pkgAcqBaseIndex { protected: @@ -688,24 +702,20 @@ class pkgAcqIndex : public pkgAcquire::Item // Unused, used to be used to verify that "Packages: " header was there bool __DELME_ON_NEXT_ABI_BREAK_Verify; - /** \brief The download request that is currently being - * processed. - */ - pkgAcquire::ItemDesc Desc; - /** \brief The object that is actually being fetched (minus any * compression-related extensions). */ std::string RealURI; - /** \brief The expected hashsum of the decompressed index file. */ - HashString ExpectedHash; - /** \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; + + /** \brief Do the changes needed to fetch via AptByHash (if needed) */ + void InitByHashIfNeeded(const std::string MetaKey); + /** \brief Get the full pathname of the final file for the given URI */ std::string GetFinalFilename(std::string const &URI, @@ -718,11 +728,10 @@ class pkgAcqIndex : 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 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 +744,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 +753,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 ShortDesc, HashStringList const &ExpectedHashes, 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); + pkgAcqIndex(pkgAcquire *Owner, + 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 {{{ @@ -763,7 +775,7 @@ class pkgAcqIndexTrans : public pkgAcqIndex public: virtual void Failed(std::string Message,pkgAcquire::MethodConfig *Cnf); - virtual std::string Custom600Headers(); + virtual std::string Custom600Headers() const; /** \brief Create a pkgAcqIndexTrans. * @@ -778,8 +790,8 @@ class pkgAcqIndexTrans : public pkgAcqIndex */ 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, IndexTarget const * const Target, + HashStringList const &ExpectedHashes, indexRecords *MetaIndexParser); }; /*}}}*/ /** \brief Information about an index file. */ /*{{{*/ @@ -847,9 +859,6 @@ class pkgAcqMetaSig : public pkgAcquire::Item /** \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. @@ -877,21 +886,21 @@ class pkgAcqMetaSig : public pkgAcquire::Item * * \todo Why a list of pointers instead of a list of structs? */ - const std::vector<struct IndexTarget*>* IndexTargets; + 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, + 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 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, + const std::vector<IndexTarget*>* IndexTargets, indexRecords* MetaIndexParser); virtual ~pkgAcqMetaSig(); }; @@ -909,9 +918,6 @@ class pkgAcqMetaSig : public pkgAcquire::Item 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. */ @@ -925,7 +931,7 @@ class pkgAcqMetaIndex : public pkgAcquire::Item std::string SigFile; /** \brief The index files to download. */ - const std::vector<struct IndexTarget*>* IndexTargets; + const std::vector<IndexTarget*>* IndexTargets; /** \brief The parser for the meta-index file. */ indexRecords* MetaIndexParser; @@ -979,16 +985,16 @@ class pkgAcqMetaIndex : 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 Hash, + 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 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, + const std::vector<IndexTarget*>* IndexTargets, indexRecords* MetaIndexParser); }; /*}}}*/ @@ -1015,14 +1021,14 @@ class pkgAcqMetaClearSig : public pkgAcqMetaIndex public: void Failed(std::string Message,pkgAcquire::MethodConfig *Cnf); - virtual std::string Custom600Headers(); + virtual std::string Custom600Headers() const; /** \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, + const std::vector<IndexTarget*>* IndexTargets, indexRecords* MetaIndexParser); virtual ~pkgAcqMetaClearSig(); }; @@ -1038,9 +1044,6 @@ class pkgAcqArchive : public pkgAcquire::Item /** \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 +1054,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 +1080,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,12 +1118,6 @@ 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; - /** \brief How many times to retry the download, set from * Acquire::Retries. */ @@ -1137,11 +1130,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 +1142,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 +1166,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..82f2fb3ce 100644 --- a/apt-pkg/acquire-method.cc +++ b/apt-pkg/acquire-method.cc @@ -119,6 +119,18 @@ void pkgAcqMethod::Fail(string Err,bool Transient) std::cout << "\n" << std::flush; } /*}}}*/ +// AcqMethod::DropPrivsOrDie - Drop privileges or die /*{{{*/ +// --------------------------------------------------------------------- +/* */ +void pkgAcqMethod::DropPrivsOrDie() +{ + if (!DropPrivs()) { + Fail(false); + exit(112); /* call the european emergency number */ + } +} + + /*}}}*/ // AcqMethod::URIStart - Indicate a download is starting /*{{{*/ // --------------------------------------------------------------------- /* */ @@ -147,6 +159,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 +186,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 +215,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 +363,15 @@ 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)); + } Tmp->Next = 0; // Append it to the list @@ -442,12 +459,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() { /*{{{*/ diff --git a/apt-pkg/acquire-method.h b/apt-pkg/acquire-method.h index 221ccf273..cdeecc9a7 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,12 @@ class pkgAcqMethod time_t LastModified; bool IndexFile; bool FailIgnore; + HashStringList ExpectedHashes; }; 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 +60,7 @@ class pkgAcqMethod unsigned long long Size; unsigned long long ResumePoint; - void TakeHashes(Hashes &Hash); + void TakeHashes(class Hashes &Hash); FetchResult(); }; @@ -107,7 +105,7 @@ class pkgAcqMethod pkgAcqMethod(const char *Ver,unsigned long Flags = 0); 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..54be8e99f 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) { @@ -525,6 +530,9 @@ 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(); Message += Item->Owner->Custom600Headers(); Message += "\n\n"; diff --git a/apt-pkg/acquire.cc b/apt-pkg/acquire.cc index 057bc24cd..8119e4487 100644 --- a/apt-pkg/acquire.cc +++ b/apt-pkg/acquire.cc @@ -31,6 +31,7 @@ #include <stdlib.h> #include <string.h> #include <unistd.h> +#include <iomanip> #include <dirent.h> #include <sys/time.h> @@ -72,23 +73,27 @@ pkgAcquire::pkgAcquire(pkgAcquireStatus *Progress) : LockFD(-1), Queues(0), Wor // --------------------------------------------------------------------- /* Do everything needed to be a complete Acquire object and report the success (or failure) back so the user knows that something is wrong… */ -bool pkgAcquire::Setup(pkgAcquireStatus *Progress, string const &Lock) +bool pkgAcquire::Setup(pkgAcquireStatus *Progress, string const &Lock, + bool const createDirectories) { Log = Progress; // 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 (createDirectories == true) + { + 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.empty() == true || _config->FindB("Debug::NoLocking", false) == true) return true; @@ -580,27 +585,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 +800,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 +820,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 +833,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 +851,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 +862,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 +873,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 +899,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 +924,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()); diff --git a/apt-pkg/acquire.h b/apt-pkg/acquire.h index ef16d8556..7bceb4323 100644 --- a/apt-pkg/acquire.h +++ b/apt-pkg/acquire.h @@ -352,8 +352,11 @@ class pkgAcquire * \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. + * \param createDirectories can be used to disable the creation of directories, + * e.g. if the fetcher is used with different directories later on */ - bool Setup(pkgAcquireStatus *Progress = NULL, std::string const &Lock = ""); + bool Setup(pkgAcquireStatus *Progress = NULL, std::string const &Lock = "", + bool const createDirectories = true); void SetLog(pkgAcquireStatus *Progress) { Log = Progress; } @@ -585,7 +588,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) { @@ -714,6 +717,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() 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..4d3bfa81f 100644 --- a/apt-pkg/algorithms.h +++ b/apt-pkg/algorithms.h @@ -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..94b6bc246 100644 --- a/apt-pkg/aptconfiguration.cc +++ b/apt-pkg/aptconfiguration.cc @@ -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/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..892ad2dfc 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 PackageUniverse : public PackageContainerInterface { + pkgCache * const _cont; +public: + typedef pkgCache::PkgIterator iterator; + typedef pkgCache::PkgIterator const_iterator; + + bool empty() const { return false; } + size_t size() const { return _cont->Head().PackageCount; } + + const_iterator begin() const { return _cont->PkgBegin(); } + const_iterator end() const { return _cont->PkgEnd(); } + iterator begin() { return _cont->PkgBegin(); } + iterator end() { return _cont->PkgEnd(); } + + 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/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..fbe180f8e 100644 --- a/apt-pkg/contrib/configuration.cc +++ b/apt-pkg/contrib/configuration.cc @@ -254,7 +254,9 @@ string Configuration::FindDir(const char *Name,const char *Default) const // --------------------------------------------------------------------- /* 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, ""); } +vector<string> Configuration::FindVector(const char *Name) const { + return FindVector(Name, ""); +} #endif vector<string> Configuration::FindVector(const char *Name, std::string const &Default) const { diff --git a/apt-pkg/contrib/configuration.h b/apt-pkg/contrib/configuration.h index c256139f4..6345c8a5d 100644 --- a/apt-pkg/contrib/configuration.h +++ b/apt-pkg/contrib/configuration.h @@ -84,12 +84,10 @@ class Configuration * \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 +#if (APT_PKG_MAJOR >= 4 && APT_PKG_MINOR < 13) 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(std::string const &Name="") const { return FindVector(Name.c_str(), ""); }; 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; diff --git a/apt-pkg/contrib/fileutl.cc b/apt-pkg/contrib/fileutl.cc index 1ba4674e5..df409fa36 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 /*{{{*/ // --------------------------------------------------------------------- /* */ @@ -836,6 +858,27 @@ bool ExecWait(pid_t Pid,const char *Name,bool Reap) } /*}}}*/ + +// 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: #ifdef HAVE_ZLIB @@ -853,7 +896,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) { @@ -1913,7 +1956,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); @@ -2040,6 +2082,31 @@ 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; + } + + return Fd; +} + bool Rename(std::string From, std::string To) { if (rename(From.c_str(),To.c_str()) != 0) @@ -2050,3 +2117,145 @@ bool Rename(std::string From, std::string To) } 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 DropPrivs() +{ + // uid will be 0 in the end, but gid might be different anyway + uid_t old_uid = getuid(); + gid_t old_gid = getgid(); + + if (old_uid != 0) + return true; + if(_config->FindB("Debug::NoDropPrivs", false) == true) + return true; + + const std::string toUser = _config->Find("APT::Sandbox::User", "_apt"); + struct passwd *pw = getpwnam(toUser.c_str()); + if (pw == NULL) + return _error->Error("No user %s, can not drop rights", toUser.c_str()); + +#if __gnu_linux__ + // see prctl(2), needs linux3.5 + int ret = prctl(PR_SET_NO_NEW_PRIVS, 1, 0,0, 0); + if(ret < 0) + _error->Warning("PR_SET_NO_NEW_PRIVS failed with %i", ret); +#endif + // 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..9dd29eb9e 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 DropPrivs(); + // 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..199e395f6 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 = other.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..b268ce24c 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 13 #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..da8bebdb5 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 diff --git a/apt-pkg/deb/debindexfile.cc b/apt-pkg/deb/debindexfile.cc index 5b4289e92..f90731dd2 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> @@ -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,143 @@ 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 +853,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 +906,16 @@ 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; +} /*}}}*/ diff --git a/apt-pkg/deb/debindexfile.h b/apt-pkg/deb/debindexfile.h index 017c69a0a..18322dc1b 100644 --- a/apt-pkg/deb/debindexfile.h +++ b/apt-pkg/deb/debindexfile.h @@ -164,4 +164,57 @@ class debSourcesIndex : public pkgIndexFile 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 +{ + virtual const Type *GetType() const APT_CONST; +}; + #endif diff --git a/apt-pkg/deb/deblistparser.cc b/apt-pkg/deb/deblistparser.cc index 7d4fd52cf..103b126de 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::VERSION, 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. @@ -901,7 +935,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()); @@ -910,19 +944,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(VERSION, "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); @@ -963,3 +997,23 @@ 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; +} + + + diff --git a/apt-pkg/deb/deblistparser.h b/apt-pkg/deb/deblistparser.h index 3b6963211..b55e57d41 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(); @@ -101,9 +101,17 @@ class debListParser : public pkgCacheGenerator::ListParser debListParser(FileFd *File, std::string const &Arch = ""); 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..73010e867 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()) { @@ -255,10 +255,10 @@ bool debReleaseIndex::GetIndexes(pkgAcquire *Owner, bool const &GetAll) const // 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; @@ -471,6 +471,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 +516,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..7091c198f 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: @@ -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..d2c04d8b2 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() -{ - 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() +// RecordParser::Hashes - return the available archive hashes /*{{{*/ +HashStringList debRecordParser::Hashes() const { - 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; } /*}}}*/ diff --git a/apt-pkg/deb/debrecords.h b/apt-pkg/deb/debrecords.h index bdac6c90b..2bd3f3c8f 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(); @@ -66,4 +63,15 @@ class debRecordParser : public pkgRecords::Parser 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/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..6bd6ce0ee 100644 --- a/apt-pkg/deb/dpkgpm.h +++ b/apt-pkg/deb/dpkgpm.h @@ -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..16282df21 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 " 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..bb3b5d340 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; 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..e97ea0ac9 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; @@ -239,6 +258,6 @@ indexRecords::indexRecords() } indexRecords::indexRecords(const string ExpectedDist) : - ExpectedDist(ExpectedDist), ValidUntil(0) + ExpectedDist(ExpectedDist), ValidUntil(0), SupportsAcquireByHash(false) { } diff --git a/apt-pkg/indexrecords.h b/apt-pkg/indexrecords.h index e31f889ad..bb0fd5564 100644 --- a/apt-pkg/indexrecords.h +++ b/apt-pkg/indexrecords.h @@ -26,12 +26,15 @@ class indexRecords public: struct checkSum; std::string ErrorText; + // dpointer (for later9 + void * d; protected: std::string Dist; std::string Suite; std::string ExpectedDist; time_t ValidUntil; + bool SupportsAcquireByHash; std::map<std::string,checkSum *> Entries; @@ -41,7 +44,7 @@ class indexRecords 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(); @@ -49,17 +52,28 @@ class indexRecords virtual bool Load(std::string Filename); 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(){}; }; +#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/install-progress.cc b/apt-pkg/install-progress.cc index cf6c85912..0d180d59b 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..912700e8d 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) {}; 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..6a89eabd7 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 ⤅ - 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); @@ -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..6bb246e9f 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(VERSION, 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(VERSION, 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 VERSION: 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..e1d22b88f 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, VERSION, SECTION }; + map_stringitem_t StoreString(enum 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..26c895417 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 diff --git a/apt-pkg/tagfile.h b/apt-pkg/tagfile.h index d5b62e76d..39ec94d86 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; @@ -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/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 |