diff options
author | Daniel Nicoletti <dantti12@gmail.com> | 2012-04-13 22:39:14 -0300 |
---|---|---|
committer | Daniel Nicoletti <dantti12@gmail.com> | 2012-04-13 22:39:14 -0300 |
commit | 0cb6228d593d44dbceb686b61846676e4b5ca6a5 (patch) | |
tree | 64ed3f55b19913dfcb76111687d219d5bb0ccbf9 /backends | |
parent | c19e1a6b5573eda4a953351c6b1261365695a4e7 (diff) |
aptcc: Reident the code and re-enforce KDElibs coding style
Diffstat (limited to 'backends')
-rw-r--r-- | backends/aptcc/acqpkitstatus.cpp | 238 | ||||
-rw-r--r-- | backends/aptcc/acqpkitstatus.h | 40 | ||||
-rw-r--r-- | backends/aptcc/apt-intf.cpp | 2424 | ||||
-rw-r--r-- | backends/aptcc/apt-intf.h | 264 | ||||
-rw-r--r-- | backends/aptcc/apt-messages.cpp | 316 | ||||
-rw-r--r-- | backends/aptcc/apt-messages.h | 4 | ||||
-rw-r--r-- | backends/aptcc/apt-sourceslist.cpp | 879 | ||||
-rw-r--r-- | backends/aptcc/apt-sourceslist.h | 147 | ||||
-rw-r--r-- | backends/aptcc/apt-utils.cpp | 428 | ||||
-rw-r--r-- | backends/aptcc/apt-utils.h | 53 | ||||
-rw-r--r-- | backends/aptcc/deb-file.cpp | 103 | ||||
-rw-r--r-- | backends/aptcc/deb-file.h | 38 | ||||
-rw-r--r-- | backends/aptcc/gstMatcher.cpp | 65 | ||||
-rw-r--r-- | backends/aptcc/matcher.cpp | 340 | ||||
-rw-r--r-- | backends/aptcc/matcher.h | 28 | ||||
-rw-r--r-- | backends/aptcc/pk-backend-aptcc.cpp | 2112 | ||||
-rw-r--r-- | backends/aptcc/pkg_acqfile.cpp | 197 | ||||
-rw-r--r-- | backends/aptcc/pkg_acqfile.h | 30 |
18 files changed, 3810 insertions, 3896 deletions
diff --git a/backends/aptcc/acqpkitstatus.cpp b/backends/aptcc/acqpkitstatus.cpp index b27b8c59..262bc608 100644 --- a/backends/aptcc/acqpkitstatus.cpp +++ b/backends/aptcc/acqpkitstatus.cpp @@ -34,11 +34,11 @@ using namespace std; // AcqPackageKitStatus::AcqPackageKitStatus - Constructor // --------------------------------------------------------------------- AcqPackageKitStatus::AcqPackageKitStatus(AptIntf *apt, PkBackend *backend, bool &cancelled) : - m_apt(apt), - m_backend(backend), - _cancelled(cancelled), - last_percent(PK_BACKEND_PERCENTAGE_INVALID), - last_sub_percent(PK_BACKEND_PERCENTAGE_INVALID) + m_apt(apt), + m_backend(backend), + _cancelled(cancelled), + last_percent(PK_BACKEND_PERCENTAGE_INVALID), + last_sub_percent(PK_BACKEND_PERCENTAGE_INVALID) { } @@ -46,9 +46,9 @@ AcqPackageKitStatus::AcqPackageKitStatus(AptIntf *apt, PkBackend *backend, bool // --------------------------------------------------------------------- void AcqPackageKitStatus::Start() { - pkgAcquireStatus::Start(); - ID = 1; -}; + pkgAcquireStatus::Start(); + ID = 1; +} // AcqPackageKitStatus::IMSHit - Called when an item got a HIT response /*{{{*/ // --------------------------------------------------------------------- @@ -61,56 +61,56 @@ void AcqPackageKitStatus::IMSHit(pkgAcquire::ItemDesc &Itm) false); } Update = true; -}; +} // AcqPackageKitStatus::Fetch - An item has started to download // --------------------------------------------------------------------- /* This prints out the short description and the expected size */ void AcqPackageKitStatus::Fetch(pkgAcquire::ItemDesc &Itm) { - Update = true; - if (Itm.Owner->Complete == true) - return; + Update = true; + if (Itm.Owner->Complete == true) + return; - Itm.Owner->ID = ID++; -}; + Itm.Owner->ID = ID++; +} // AcqPackageKitStatus::Done - Completed a download // --------------------------------------------------------------------- /* We don't display anything... */ void AcqPackageKitStatus::Done(pkgAcquire::ItemDesc &Itm) { - Update = true; -}; + Update = true; +} // AcqPackageKitStatus::Fail - Called when an item fails to download // --------------------------------------------------------------------- /* We print out the error text */ void AcqPackageKitStatus::Fail(pkgAcquire::ItemDesc &Itm) { - // Ignore certain kinds of transient failures (bad code) - if (Itm.Owner->Status == pkgAcquire::Item::StatIdle) { - return; - } + // Ignore certain kinds of transient failures (bad code) + if (Itm.Owner->Status == pkgAcquire::Item::StatIdle) { + return; + } - if (Itm.Owner->Status == pkgAcquire::Item::StatDone) - { + if (Itm.Owner->Status == pkgAcquire::Item::StatDone) + { if (packages.size() == 0) { pk_backend_repo_detail(m_backend, "", Itm.Description.c_str(), false); } - } else { - // an error was found (maybe 404, 403...) - // the item that got the error and the error text - _error->Error("Error %s\n %s", - Itm.Description.c_str(), - Itm.Owner->ErrorText.c_str()); - } + } else { + // an error was found (maybe 404, 403...) + // the item that got the error and the error text + _error->Error("Error %s\n %s", + Itm.Description.c_str(), + Itm.Owner->ErrorText.c_str()); + } - Update = true; -}; + Update = true; +} // AcqTextStatus::Stop - Finished downloading @@ -119,14 +119,14 @@ void AcqPackageKitStatus::Fail(pkgAcquire::ItemDesc &Itm) speed */ void AcqPackageKitStatus::Stop() { - pkgAcquireStatus::Stop(); - // the items that still on the set are finished - for (set<string>::iterator it = currentPackages.begin(); - it != currentPackages.end(); - it++ ) - { - emit_package(*it, true); - } + pkgAcquireStatus::Stop(); + // the items that still on the set are finished + for (set<string>::iterator it = currentPackages.begin(); + it != currentPackages.end(); + it++ ) + { + emit_package(*it, true); + } } @@ -137,71 +137,71 @@ void AcqPackageKitStatus::Stop() bandwidth and ETA indicator. */ bool AcqPackageKitStatus::Pulse(pkgAcquire *Owner) { - pkgAcquireStatus::Pulse(Owner); - - unsigned long percent_done; - percent_done = long(double((CurrentBytes + CurrentItems)*100.0)/double(TotalBytes+TotalItems)); - - // Emit the percent done - if (last_percent != percent_done) { - if (last_percent < percent_done) { - pk_backend_set_percentage(m_backend, percent_done); - } else { - pk_backend_set_percentage(m_backend, PK_BACKEND_PERCENTAGE_INVALID); - pk_backend_set_percentage(m_backend, percent_done); - } - last_percent = percent_done; - } - - set<string> localCurrentPackages = currentPackages;; - for (pkgAcquire::Worker *I = Owner->WorkersBegin(); I != 0; - I = Owner->WorkerStep(I)) - { + pkgAcquireStatus::Pulse(Owner); + + unsigned long percent_done; + percent_done = long(double((CurrentBytes + CurrentItems)*100.0)/double(TotalBytes+TotalItems)); + + // Emit the percent done + if (last_percent != percent_done) { + if (last_percent < percent_done) { + pk_backend_set_percentage(m_backend, percent_done); + } else { + pk_backend_set_percentage(m_backend, PK_BACKEND_PERCENTAGE_INVALID); + pk_backend_set_percentage(m_backend, percent_done); + } + last_percent = percent_done; + } + + set<string> localCurrentPackages = currentPackages;; + for (pkgAcquire::Worker *I = Owner->WorkersBegin(); I != 0; + I = Owner->WorkerStep(I)) + { // Check if there is no item running or if we don't have // any packages set we are probably refreshing the cache if (I->CurrentItem == 0 || packages.size() == 0) { continue; } - emit_package(I->CurrentItem->ShortDesc, false); - localCurrentPackages.erase(I->CurrentItem->ShortDesc); - - // Add the total size and percent - if (I->TotalSize > 0 && I->CurrentItem->Owner->Complete == false) - { - unsigned long sub_percent; - // TODO PackageKit needs to emit package with progress. - sub_percent = long(double(I->CurrentSize*100.0)/double(I->TotalSize)); - if (last_sub_percent != sub_percent) { - if (last_sub_percent < sub_percent) { - pk_backend_set_sub_percentage(m_backend, sub_percent); - } else { - pk_backend_set_sub_percentage(m_backend, PK_BACKEND_PERCENTAGE_INVALID); - pk_backend_set_sub_percentage(m_backend, sub_percent); - } - last_sub_percent = sub_percent; - } - } - } - - // the items that still on the set are finished - for (set<string>::iterator it = localCurrentPackages.begin(); - it != localCurrentPackages.end(); - it++ ) - { - emit_package(*it, true); - } - - double localCPS = (CurrentCPS >= 0) ? CurrentCPS : -1 * CurrentCPS; - if (localCPS != last_CPS) - { - last_CPS = localCPS; - pk_backend_set_speed(m_backend, (int) last_CPS); - } - - Update = false; - - return !_cancelled;; + emit_package(I->CurrentItem->ShortDesc, false); + localCurrentPackages.erase(I->CurrentItem->ShortDesc); + + // Add the total size and percent + if (I->TotalSize > 0 && I->CurrentItem->Owner->Complete == false) + { + unsigned long sub_percent; + // TODO PackageKit needs to emit package with progress. + sub_percent = long(double(I->CurrentSize*100.0)/double(I->TotalSize)); + if (last_sub_percent != sub_percent) { + if (last_sub_percent < sub_percent) { + pk_backend_set_sub_percentage(m_backend, sub_percent); + } else { + pk_backend_set_sub_percentage(m_backend, PK_BACKEND_PERCENTAGE_INVALID); + pk_backend_set_sub_percentage(m_backend, sub_percent); + } + last_sub_percent = sub_percent; + } + } + } + + // the items that still on the set are finished + for (set<string>::iterator it = localCurrentPackages.begin(); + it != localCurrentPackages.end(); + it++ ) + { + emit_package(*it, true); + } + + double localCPS = (CurrentCPS >= 0) ? CurrentCPS : -1 * CurrentCPS; + if (localCPS != last_CPS) + { + last_CPS = localCPS; + pk_backend_set_speed(m_backend, (int) last_CPS); + } + + Update = false; + + return !_cancelled;; } // AcqPackageKitStatus::MediaChange - Media need to be swapped @@ -209,32 +209,32 @@ bool AcqPackageKitStatus::Pulse(pkgAcquire *Owner) /* Prompt for a media swap */ bool AcqPackageKitStatus::MediaChange(string Media, string Drive) { - pk_backend_media_change_required(m_backend, - PK_MEDIA_TYPE_ENUM_DISC, - Media.c_str(), - Media.c_str()); - - char errorMsg[400]; - sprintf(errorMsg, - "Media change: please insert the disc labeled" - " '%s' " - "in the drive '%s' and try again.", - Media.c_str(), - Drive.c_str()); - - pk_backend_error_code(m_backend, - PK_ERROR_ENUM_MEDIA_CHANGE_REQUIRED, - errorMsg); - - // Set this so we can fail the transaction - Update = true; - return false; + pk_backend_media_change_required(m_backend, + PK_MEDIA_TYPE_ENUM_DISC, + Media.c_str(), + Media.c_str()); + + char errorMsg[400]; + sprintf(errorMsg, + "Media change: please insert the disc labeled" + " '%s' " + "in the drive '%s' and try again.", + Media.c_str(), + Drive.c_str()); + + pk_backend_error_code(m_backend, + PK_ERROR_ENUM_MEDIA_CHANGE_REQUIRED, + errorMsg); + + // Set this so we can fail the transaction + Update = true; + return false; } void AcqPackageKitStatus::addPackagePair(PkgPair packagePair) { - packages.push_back(packagePair); + packages.push_back(packagePair); } void AcqPackageKitStatus::emit_package(const string &name, bool finished) diff --git a/backends/aptcc/acqpkitstatus.h b/backends/aptcc/acqpkitstatus.h index 1ab9760d..4e018861 100644 --- a/backends/aptcc/acqpkitstatus.h +++ b/backends/aptcc/acqpkitstatus.h @@ -29,35 +29,35 @@ class AcqPackageKitStatus : public pkgAcquireStatus { public: - AcqPackageKitStatus(AptIntf *apt, PkBackend *backend, bool &cancelled); + AcqPackageKitStatus(AptIntf *apt, PkBackend *backend, bool &cancelled); - virtual bool MediaChange(string Media, string Drive); - virtual void IMSHit(pkgAcquire::ItemDesc &Itm); - virtual void Fetch(pkgAcquire::ItemDesc &Itm); - virtual void Done(pkgAcquire::ItemDesc &Itm); - virtual void Fail(pkgAcquire::ItemDesc &Itm); - virtual void Start(); - virtual void Stop(); + virtual bool MediaChange(string Media, string Drive); + virtual void IMSHit(pkgAcquire::ItemDesc &Itm); + virtual void Fetch(pkgAcquire::ItemDesc &Itm); + virtual void Done(pkgAcquire::ItemDesc &Itm); + virtual void Fail(pkgAcquire::ItemDesc &Itm); + virtual void Start(); + virtual void Stop(); - bool Pulse(pkgAcquire *Owner); + bool Pulse(pkgAcquire *Owner); - void addPackagePair(PkgPair packagePair); + void addPackagePair(PkgPair packagePair); private: - PkBackend *m_backend; - unsigned long ID; - bool &_cancelled; + PkBackend *m_backend; + unsigned long ID; + bool &_cancelled; - unsigned long last_percent; - unsigned long last_sub_percent; - double last_CPS; - string last_package_name; - AptIntf *m_apt; + unsigned long last_percent; + unsigned long last_sub_percent; + double last_CPS; + string last_package_name; + AptIntf *m_apt; PkgList packages; - set<string> currentPackages; + set<string> currentPackages; - void emit_package(const string &name, bool finished); + void emit_package(const string &name, bool finished); }; #endif diff --git a/backends/aptcc/apt-intf.cpp b/backends/aptcc/apt-intf.cpp index 4319723e..164d58c1 100644 --- a/backends/aptcc/apt-intf.cpp +++ b/backends/aptcc/apt-intf.cpp @@ -54,128 +54,122 @@ #define RAMFS_MAGIC 0x858458f6 -AptIntf::AptIntf(PkBackend *backend, bool &cancel) - : - packageRecords(0), - packageCache(0), - packageDepCache(0), - packageSourceList(0), - Map(0), - Policy(0), - m_backend(backend), - _cancel(cancel), - m_terminalTimeout(120), - m_lastSubProgress(0) +AptIntf::AptIntf(PkBackend *backend, bool &cancel) : + packageRecords(0), + packageCache(0), + packageDepCache(0), + packageSourceList(0), + Map(0), + Policy(0), + m_backend(backend), + _cancel(cancel), + m_terminalTimeout(120), + m_lastSubProgress(0) { - _cancel = false; + _cancel = false; } bool AptIntf::init() { - gchar *locale; - gchar *http_proxy; - gchar *ftp_proxy; - - m_isMultiArch = APT::Configuration::getArchitectures(false).size() > 1; - - // Set PackageKit status - pk_backend_set_status(m_backend, PK_STATUS_ENUM_LOADING_CACHE); - - // set locale - if (locale = pk_backend_get_locale(m_backend)) { - setlocale(LC_ALL, locale); -// TODO why this cuts characthers on ui? -// string _locale(locale); -// size_t found; -// found = _locale.find('.'); -// _locale.erase(found); -// _config->Set("APT::Acquire::Translation", _locale); - } - - // set http proxy - http_proxy = pk_backend_get_proxy_http(m_backend); - setenv("http_proxy", http_proxy, 1); - - // set ftp proxy - ftp_proxy = pk_backend_get_proxy_ftp(m_backend); - setenv("ftp_proxy", ftp_proxy, 1); - - packageSourceList = new pkgSourceList; - // Read the source list - packageSourceList->ReadMainList(); - - // Generate it and map it - bool Res = pkgMakeStatusCache(*packageSourceList, Progress, &Map, true); - Progress.Done(); - if(!Res) { - return false; - //"The package lists or status file could not be parsed or opened." - } - - packageCache = new pkgCache(Map); - if (_error->PendingError()) { - return false; - } - - // create depcache - Policy = new pkgPolicy(packageCache); - if (_error->PendingError()) { - return false; - } - - if (!ReadPinFile(*Policy)) { - return false; - } - - packageDepCache = new pkgDepCache(packageCache, Policy); - if (_error->PendingError()) { - return false; - } - - packageDepCache->Init(&Progress); - Progress.Done(); - if (_error->PendingError()) { - return false; - } - - // Create the text record parser - packageRecords = new pkgRecords(*packageDepCache); + gchar *locale; + gchar *http_proxy; + gchar *ftp_proxy; + + m_isMultiArch = APT::Configuration::getArchitectures(false).size() > 1; + + // Set PackageKit status + pk_backend_set_status(m_backend, PK_STATUS_ENUM_LOADING_CACHE); + + // set locale + if (locale = pk_backend_get_locale(m_backend)) { + setlocale(LC_ALL, locale); + // TODO why this cuts characthers on ui? + // string _locale(locale); + // size_t found; + // found = _locale.find('.'); + // _locale.erase(found); + // _config->Set("APT::Acquire::Translation", _locale); + } + + // set http proxy + http_proxy = pk_backend_get_proxy_http(m_backend); + setenv("http_proxy", http_proxy, 1); + + // set ftp proxy + ftp_proxy = pk_backend_get_proxy_ftp(m_backend); + setenv("ftp_proxy", ftp_proxy, 1); + + packageSourceList = new pkgSourceList; + // Read the source list + packageSourceList->ReadMainList(); + + // Generate it and map it + bool Res = pkgMakeStatusCache(*packageSourceList, Progress, &Map, true); + Progress.Done(); + if(!Res) { + return false; + //"The package lists or status file could not be parsed or opened." + } + + packageCache = new pkgCache(Map); + if (_error->PendingError()) { + return false; + } + + // create depcache + Policy = new pkgPolicy(packageCache); + if (_error->PendingError()) { + return false; + } + + if (!ReadPinFile(*Policy)) { + return false; + } + + packageDepCache = new pkgDepCache(packageCache, Policy); + if (_error->PendingError()) { + return false; + } + + packageDepCache->Init(&Progress); + Progress.Done(); + if (_error->PendingError()) { + return false; + } + + // Create the text record parser + packageRecords = new pkgRecords(*packageDepCache); } AptIntf::~AptIntf() { - if (packageRecords) - { - g_debug ("~apt_init packageRecords"); - delete packageRecords; - } - - if (packageCache) - { - g_debug ("~apt_init packageCache"); - delete packageCache; - } - - if (packageDepCache) - { - g_debug ("~apt_init packageDepCache"); - delete packageDepCache; - } - - if (Policy) - { - g_debug ("~apt_init Policy"); - delete Policy; - } - - if (packageSourceList) - { - delete packageSourceList; - } - - pk_backend_finished(m_backend); - - delete Map; + if (packageRecords) { + g_debug ("~apt_init packageRecords"); + delete packageRecords; + } + + if (packageCache) { + g_debug ("~apt_init packageCache"); + delete packageCache; + } + + if (packageDepCache) { + g_debug ("~apt_init packageDepCache"); + delete packageDepCache; + } + + if (Policy) { + g_debug ("~apt_init Policy"); + delete Policy; + } + + if (packageSourceList) { + delete packageSourceList; + } + + pk_backend_finished(m_backend); + + delete Map; } void AptIntf::cancel() @@ -205,8 +199,7 @@ PkgPair AptIntf::find_package_id(const gchar *package_id, bool &found) // Ignore packages that could not be found or that exist only due to dependencies. if (pkg_ver.first.end() == true || - (pkg_ver.first.VersionList().end() && pkg_ver.first.ProvidesList().end())) - { + (pkg_ver.first.VersionList().end() && pkg_ver.first.ProvidesList().end())) { g_strfreev(parts); return pkg_ver; } @@ -214,8 +207,7 @@ PkgPair AptIntf::find_package_id(const gchar *package_id, bool &found) ver = find_ver(pkg_ver.first); // check to see if the provided package isn't virtual too if (ver.end() == false && - strcmp(ver.VerStr(), parts[PK_PACKAGE_ID_VERSION]) == 0) - { + strcmp(ver.VerStr(), parts[PK_PACKAGE_ID_VERSION]) == 0) { g_strfreev(parts); pkg_ver.second = ver; return pkg_ver; @@ -224,8 +216,7 @@ PkgPair AptIntf::find_package_id(const gchar *package_id, bool &found) ver = find_candidate_ver(pkg_ver.first); // check to see if the provided package isn't virtual too if (ver.end() == false && - strcmp(ver.VerStr(), parts[PK_PACKAGE_ID_VERSION]) == 0) - { + strcmp(ver.VerStr(), parts[PK_PACKAGE_ID_VERSION]) == 0) { g_strfreev(parts); pkg_ver.second = ver; return pkg_ver; @@ -239,26 +230,25 @@ PkgPair AptIntf::find_package_id(const gchar *package_id, bool &found) pkgCache::VerIterator AptIntf::find_candidate_ver(const pkgCache::PkgIterator &pkg) { - // get the candidate version iterator - return (*packageDepCache)[pkg].CandidateVerIter(*packageDepCache); + // get the candidate version iterator + return (*packageDepCache)[pkg].CandidateVerIter(*packageDepCache); } pkgCache::VerIterator AptIntf::find_ver(const pkgCache::PkgIterator &pkg) { - // if the package is installed return the current version - if(!pkg.CurrentVer().end()) { - return pkg.CurrentVer(); - } - - // Else get the candidate version iterator - pkgCache::VerIterator candver = find_candidate_ver(pkg); - if(!candver.end()) - { - return candver; - } - - // return the version list as a last resource - return pkg.VersionList(); + // if the package is installed return the current version + if(!pkg.CurrentVer().end()) { + return pkg.CurrentVer(); + } + + // Else get the candidate version iterator + pkgCache::VerIterator candver = find_candidate_ver(pkg); + if(!candver.end()) { + return candver; + } + + // return the version list as a last resource + return pkg.VersionList(); } bool AptIntf::matchPackage(const PkgPair &pair, PkBitfield filters) @@ -278,7 +268,7 @@ bool AptIntf::matchPackage(const PkgPair &pair, PkBitfield filters) // don't emit the package if it does not match // the native architecture if (strcmp(ver.Arch(), "all") != 0 && - strcmp(ver.Arch(), _config->Find("APT::Architecture").c_str()) != 0) { + strcmp(ver.Arch(), _config->Find("APT::Architecture").c_str()) != 0) { return false; } } @@ -296,54 +286,54 @@ bool AptIntf::matchPackage(const PkgPair &pair, PkBitfield filters) } else if (pk_bitfield_contain(filters, PK_FILTER_ENUM_INSTALLED) && !installed) { return false; } - + if (pk_bitfield_contain(filters, PK_FILTER_ENUM_DEVELOPMENT)) { // if ver.end() means unknow // strcmp will be true when it's different than devel std::string pkgName = pkg.Name(); if (!ends_with(pkgName, "-dev") && - !ends_with(pkgName, "-dbg") && - section.compare("devel") && - section.compare("libdevel")) { + !ends_with(pkgName, "-dbg") && + section.compare("devel") && + section.compare("libdevel")) { return false; } } else if (pk_bitfield_contain(filters, PK_FILTER_ENUM_NOT_DEVELOPMENT)) { std::string pkgName = pkg.Name(); if (ends_with(pkgName, "-dev") || - ends_with(pkgName, "-dbg") || - !section.compare("devel") || - !section.compare("libdevel")) { + ends_with(pkgName, "-dbg") || + !section.compare("devel") || + !section.compare("libdevel")) { return false; } } - + if (pk_bitfield_contain(filters, PK_FILTER_ENUM_GUI)) { // if ver.end() means unknow // strcmp will be true when it's different than x11 if (section.compare("x11") && section.compare("gnome") && - section.compare("kde") && section.compare("graphics")) { + section.compare("kde") && section.compare("graphics")) { return false; } } else if (pk_bitfield_contain(filters, PK_FILTER_ENUM_NOT_GUI)) { if (!section.compare("x11") || !section.compare("gnome") || - !section.compare("kde") || !section.compare("graphics")) { + !section.compare("kde") || !section.compare("graphics")) { return false; } } - + // TODO add Ubuntu handling if (pk_bitfield_contain(filters, PK_FILTER_ENUM_FREE)) { if (!repo_section.compare("contrib") || - !repo_section.compare("non-free")) { + !repo_section.compare("non-free")) { return false; } } else if (pk_bitfield_contain(filters, PK_FILTER_ENUM_NOT_FREE)) { if (repo_section.compare("contrib") && - repo_section.compare("non-free")) { + repo_section.compare("non-free")) { return false; } } - + // TODO test this one.. if (pk_bitfield_contain(filters, PK_FILTER_ENUM_COLLECTIONS)) { if (!repo_section.compare("metapackages")) { @@ -384,18 +374,18 @@ void AptIntf::emit_package(const PkgPair &pair, // check the state enum to see if it was not set. if (state == PK_INFO_ENUM_UNKNOWN) { if (pkg->CurrentState == pkgCache::State::Installed && - pkg.CurrentVer() == ver) { + pkg.CurrentVer() == ver) { state = PK_INFO_ENUM_INSTALLED; } else { state = PK_INFO_ENUM_AVAILABLE; } - } + } // Check if the filters match the package if (!matchPackage(pair, filters)) { return; } - + pkgCache::VerFileIterator vf = ver.FileList(); gchar *package_id; @@ -441,7 +431,7 @@ void AptIntf::emitUpdates(PkgList &output, PkBitfield filters) output.erase(unique(output.begin(), output.end(), result_equality()), - output.end()); + output.end()); for (PkgList::iterator i = output.begin(); i != output.end(); ++i) { if (_cancel) { @@ -457,9 +447,9 @@ void AptIntf::emitUpdates(PkgList &output, PkBitfield filters) std::string archive = vf.File().Archive() == NULL ? "" : vf.File().Archive(); std::string label = vf.File().Label() == NULL ? "" : vf.File().Label(); if (origin.compare("Debian") == 0 || - origin.compare("Ubuntu") == 0) { + origin.compare("Ubuntu") == 0) { if (ends_with(archive, "-security") || - label.compare("Debian-Security") == 0) { + label.compare("Debian-Security") == 0) { state = PK_INFO_ENUM_SECURITY; } else if (ends_with(archive, "-backports")) { state = PK_INFO_ENUM_ENHANCEMENT; @@ -467,7 +457,7 @@ void AptIntf::emitUpdates(PkgList &output, PkBitfield filters) state = PK_INFO_ENUM_BUGFIX; } } else if (origin.compare("Backports.org archive") == 0 || - ends_with(origin, "-backports")) { + ends_with(origin, "-backports")) { state = PK_INFO_ENUM_ENHANCEMENT; } @@ -483,12 +473,12 @@ void AptIntf::providesCodec(PkgList &output, gchar **values) return; } - for (pkgCache::PkgIterator pkg = packageCache->PkgBegin(); !pkg.end(); ++pkg) - { + for (pkgCache::PkgIterator pkg = packageCache->PkgBegin(); !pkg.end(); ++pkg) { if (_cancel) { delete matcher; break; } + // Ignore packages that exist only due to dependencies. if (pkg.VersionList().end() && pkg.ProvidesList().end()) { continue; @@ -551,7 +541,7 @@ void AptIntf::providesLibrary(PkgList &output, gchar **values) string strvalue = string(value); ssize_t pos = strvalue.find (".so."); if ((pos != string::npos) && (pos > 0)) { - // If last char is a number, add a "-" (to be policy-compliant) + // If last char is a number, add a "-" (to be policy-compliant) if (g_ascii_isdigit (libPkgName.at (libPkgName.length () - 1))) { libPkgName.append ("-"); } @@ -640,8 +630,7 @@ void AptIntf::emitDetails(PkgList &pkgs) pkgs.erase(unique(pkgs.begin(), pkgs.end(), result_equality()), pkgs.end()); - for(PkgList::iterator i = pkgs.begin(); i != pkgs.end(); ++i) - { + for(PkgList::iterator i = pkgs.begin(); i != pkgs.end(); ++i) { if (_cancel) { break; } @@ -710,20 +699,20 @@ void AptIntf::emitUpdateDetails(const pkgCache::PkgIterator &pkg, const pkgCache if (origin.compare("Debian") == 0) { snprintf(uri, - 512, - "http://packages.debian.org/changelogs/pool/%s/%s/%s/%s_%s/changelog", src_section.c_str(), - prefix.c_str(), - srcpkg.c_str(), - srcpkg.c_str(), - verstr.c_str()); + 512, + "http://packages.debian.org/changelogs/pool/%s/%s/%s/%s_%s/changelog", src_section.c_str(), + prefix.c_str(), + srcpkg.c_str(), + srcpkg.c_str(), + verstr.c_str()); } else { snprintf(uri, - 512, - "http://changelogs.ubuntu.com/changelogs/pool/%s/%s/%s/%s_%s/changelog", src_section.c_str(), - prefix.c_str(), - srcpkg.c_str(), - srcpkg.c_str(), - verstr.c_str()); + 512, + "http://changelogs.ubuntu.com/changelogs/pool/%s/%s/%s/%s_%s/changelog", src_section.c_str(), + prefix.c_str(), + srcpkg.c_str(), + srcpkg.c_str(), + verstr.c_str()); } } else { string pkgfilename; @@ -745,8 +734,8 @@ void AptIntf::emitUpdateDetails(const pkgCache::PkgIterator &pkg, const pkgCache pkgfilename = pkgfilename.substr(0, pkgfilename.find_last_of('.')) + ".changelog"; snprintf(uri,512,"http://%s/%s", - cadidateOriginSiteUrl.c_str(), - pkgfilename.c_str()); + cadidateOriginSiteUrl.c_str(), + pkgfilename.c_str()); } // Create the download object AcqPackageKitStatus Stat(this, m_backend, _cancel); @@ -798,8 +787,8 @@ void AptIntf::emitUpdateDetails(const pkgCache::PkgIterator &pkg, const pkgCache // Compare if the current version is shown in the changelog, to not // display old changelog information if (_system != 0 && - _system->VS->DoCmpVersion(version, version + strlen(version), - currver.VerStr(), currver.VerStr() + strlen(currver.VerStr())) <= 0) { + _system->VS->DoCmpVersion(version, version + strlen(version), + currver.VerStr(), currver.VerStr() + strlen(currver.VerStr())) <= 0) { g_free (version); break; } else { @@ -860,16 +849,15 @@ void AptIntf::emitUpdateDetails(const pkgCache::PkgIterator &pkg, const pkgCache } else if (archive.compare("testing") == 0) { updateState = PK_UPDATE_STATE_ENUM_TESTING; } else if (archive.compare("unstable") == 0 || - archive.compare("experimental") == 0) - { + archive.compare("experimental") == 0) { updateState = PK_UPDATE_STATE_ENUM_UNSTABLE; } PkRestartEnum restart = PK_RESTART_ENUM_NONE; if (starts_with(pkg.Name(), "linux-image-") || - starts_with(pkg.Name(), "nvidia-") || - strcmp(pkg.Name(), "libc6") == 0 || - strcmp(pkg.Name(), "dbus") == 0) { + starts_with(pkg.Name(), "nvidia-") || + strcmp(pkg.Name(), "libc6") == 0 || + strcmp(pkg.Name(), "dbus") == 0) { restart = PK_RESTART_ENUM_SYSTEM; } @@ -893,8 +881,7 @@ void AptIntf::emitUpdateDetails(const pkgCache::PkgIterator &pkg, const pkgCache void AptIntf::emitUpdateDetails(PkgList &pkgs) { - for(PkgList::iterator i = pkgs.begin(); i != pkgs.end(); ++i) - { + for(PkgList::iterator i = pkgs.begin(); i != pkgs.end(); ++i) { if (_cancel) { break; } @@ -970,137 +957,137 @@ void AptIntf::get_requires(PkgList &output, // used to return files it reads, using the info from the files in /var/lib/dpkg/info/ vector<string> search_files (PkBackend *backend, gchar **values, bool &_cancel) { - vector<string> packageList; - regex_t re; - gchar *search; - gchar *values_str; - - values_str = g_strjoinv("$|^", values); - search = g_strdup_printf("^%s$", - values_str); - g_free(values_str); - if(regcomp(&re, search, REG_NOSUB) != 0) { - g_debug("Regex compilation error"); - g_free(search); - return vector<string>(); - } - g_free(search); - - DIR *dp; - struct dirent *dirp; - if (!(dp = opendir("/var/lib/dpkg/info/"))) { - g_debug ("Error opening /var/lib/dpkg/info/\n"); - regfree(&re); - return vector<string>(); - } - - string line; - while ((dirp = readdir(dp)) != NULL) { - if (_cancel) { - break; - } - if (ends_with(dirp->d_name, ".list")) { - string f = "/var/lib/dpkg/info/" + string(dirp->d_name); - ifstream in(f.c_str()); - if (!in != 0) { - continue; - } - while (!in.eof()) { - getline(in, line); - if (regexec(&re, line.c_str(), (size_t)0, NULL, 0) == 0) { - string file(dirp->d_name); - packageList.push_back(file.erase(file.size() - 5, file.size())); - break; - } - } - } - } - closedir(dp); - regfree(&re); - return packageList; + vector<string> packageList; + regex_t re; + gchar *search; + gchar *values_str; + + values_str = g_strjoinv("$|^", values); + search = g_strdup_printf("^%s$", + values_str); + g_free(values_str); + if(regcomp(&re, search, REG_NOSUB) != 0) { + g_debug("Regex compilation error"); + g_free(search); + return vector<string>(); + } + g_free(search); + + DIR *dp; + struct dirent *dirp; + if (!(dp = opendir("/var/lib/dpkg/info/"))) { + g_debug ("Error opening /var/lib/dpkg/info/\n"); + regfree(&re); + return vector<string>(); + } + + string line; + while ((dirp = readdir(dp)) != NULL) { + if (_cancel) { + break; + } + if (ends_with(dirp->d_name, ".list")) { + string f = "/var/lib/dpkg/info/" + string(dirp->d_name); + ifstream in(f.c_str()); + if (!in != 0) { + continue; + } + while (!in.eof()) { + getline(in, line); + if (regexec(&re, line.c_str(), (size_t)0, NULL, 0) == 0) { + string file(dirp->d_name); + packageList.push_back(file.erase(file.size() - 5, file.size())); + break; + } + } + } + } + closedir(dp); + regfree(&re); + return packageList; } // used to return files it reads, using the info from the files in /var/lib/dpkg/info/ vector<string> searchMimeType (PkBackend *backend, gchar **values, bool &error, bool &_cancel) { - vector<string> packageList; - regex_t re; - gchar *value; - gchar *values_str; - - values_str = g_strjoinv("|", values); - value = g_strdup_printf("^MimeType=\\(.*;\\)\\?\\(%s\\)\\(;.*\\)\\?$", - values_str); - g_free(values_str); - - if(regcomp(&re, value, REG_NOSUB) != 0) { - g_debug("Regex compilation error"); - g_free(value); - return vector<string>(); - } - g_free(value); - - DIR *dp; - struct dirent *dirp; - if (!(dp = opendir("/usr/share/app-install/desktop/"))) { - g_debug ("Error opening /usr/share/app-install/desktop/\n"); - regfree(&re); - error = true; - return vector<string>(); - } - - string line; - while ((dirp = readdir(dp)) != NULL) { - if (_cancel) { - break; - } - if (ends_with(dirp->d_name, ".desktop")) { - string f = "/usr/share/app-install/desktop/" + string(dirp->d_name); - ifstream in(f.c_str()); - if (!in != 0) { - continue; - } - bool getName = false; - while (!in.eof()) { - getline(in, line); - if (getName) { - if (starts_with(line, "X-AppInstall-Package=")) { - // Remove the X-AppInstall-Package= - packageList.push_back(line.substr(21)); - break; - } - } else { - if (regexec(&re, line.c_str(), (size_t)0, NULL, 0) == 0) { - in.seekg(ios_base::beg); - getName = true; - } - } - } - } - } - - closedir(dp); - regfree(&re); - return packageList; + vector<string> packageList; + regex_t re; + gchar *value; + gchar *values_str; + + values_str = g_strjoinv("|", values); + value = g_strdup_printf("^MimeType=\\(.*;\\)\\?\\(%s\\)\\(;.*\\)\\?$", + values_str); + g_free(values_str); + + if(regcomp(&re, value, REG_NOSUB) != 0) { + g_debug("Regex compilation error"); + g_free(value); + return vector<string>(); + } + g_free(value); + + DIR *dp; + struct dirent *dirp; + if (!(dp = opendir("/usr/share/app-install/desktop/"))) { + g_debug ("Error opening /usr/share/app-install/desktop/\n"); + regfree(&re); + error = true; + return vector<string>(); + } + + string line; + while ((dirp = readdir(dp)) != NULL) { + if (_cancel) { + break; + } + if (ends_with(dirp->d_name, ".desktop")) { + string f = "/usr/share/app-install/desktop/" + string(dirp->d_name); + ifstream in(f.c_str()); + if (!in != 0) { + continue; + } + bool getName = false; + while (!in.eof()) { + getline(in, line); + if (getName) { + if (starts_with(line, "X-AppInstall-Package=")) { + // Remove the X-AppInstall-Package= + packageList.push_back(line.substr(21)); + break; + } + } else { + if (regexec(&re, line.c_str(), (size_t)0, NULL, 0) == 0) { + in.seekg(ios_base::beg); + getName = true; + } + } + } + } + } + + closedir(dp); + regfree(&re); + return packageList; } // used to emit files it reads the info directly from the files void AptIntf::emitFiles(PkBackend *backend, const gchar *pi) { - static string filelist; - string line; - gchar **parts; + static string filelist; + string line; + gchar **parts; - parts = pk_package_id_split (pi); - filelist.erase(filelist.begin(), filelist.end()); + parts = pk_package_id_split (pi); + filelist.erase(filelist.begin(), filelist.end()); string fName; if (m_isMultiArch) { - fName = "/var/lib/dpkg/info/" + - string(parts[PK_PACKAGE_ID_NAME]) + - ":" + - string(parts[PK_PACKAGE_ID_ARCH]) + - ".list"; + fName = "/var/lib/dpkg/info/" + + string(parts[PK_PACKAGE_ID_NAME]) + + ":" + + string(parts[PK_PACKAGE_ID_ARCH]) + + ".list"; } else { fName = "/var/lib/dpkg/info/" + string(parts[PK_PACKAGE_ID_NAME]) + @@ -1108,199 +1095,190 @@ void AptIntf::emitFiles(PkBackend *backend, const gchar *pi) } g_strfreev (parts); - if (FileExists(fName)) { - ifstream in(fName.c_str()); - if (!in != 0) { - return; - } - while (in.eof() == false && filelist.empty()) { - getline(in, line); - filelist += line; - } - while (in.eof() == false) { - getline(in, line); - if (!line.empty()) { - filelist += ";" + line; - } - } - - if (!filelist.empty()) { - pk_backend_files (backend, pi, filelist.c_str()); - } - } + if (FileExists(fName)) { + ifstream in(fName.c_str()); + if (!in != 0) { + return; + } + while (in.eof() == false && filelist.empty()) { + getline(in, line); + filelist += line; + } + while (in.eof() == false) { + getline(in, line); + if (!line.empty()) { + filelist += ";" + line; + } + } + + if (!filelist.empty()) { + pk_backend_files (backend, pi, filelist.c_str()); + } + } } static bool checkTrusted(pkgAcquire &fetcher, PkBackend *backend) { - string UntrustedList; - for (pkgAcquire::ItemIterator I = fetcher.ItemsBegin(); I < fetcher.ItemsEnd(); ++I) - { - if (!(*I)->IsTrusted()) - { - UntrustedList += string((*I)->ShortDesc()) + " "; - } - } - - if (UntrustedList == "") - { - return true; - } - - if (pk_backend_get_bool(backend, "only_trusted") == false || - _config->FindB("APT::Get::AllowUnauthenticated", false) == true) - { - g_debug ("Authentication warning overridden.\n"); - return true; - } - - string warning("The following packages cannot be authenticated:\n"); - warning += UntrustedList; - pk_backend_error_code(backend, - PK_ERROR_ENUM_CANNOT_INSTALL_REPO_UNSIGNED, - warning.c_str()); - _error->Discard(); - return false; + string UntrustedList; + for (pkgAcquire::ItemIterator I = fetcher.ItemsBegin(); I < fetcher.ItemsEnd(); ++I) { + if (!(*I)->IsTrusted()) { + UntrustedList += string((*I)->ShortDesc()) + " "; + } + } + + if (UntrustedList == "") { + return true; + } + + if (pk_backend_get_bool(backend, "only_trusted") == false || + _config->FindB("APT::Get::AllowUnauthenticated", false) == true) { + g_debug ("Authentication warning overridden.\n"); + return true; + } + + string warning("The following packages cannot be authenticated:\n"); + warning += UntrustedList; + pk_backend_error_code(backend, + PK_ERROR_ENUM_CANNOT_INSTALL_REPO_UNSIGNED, + warning.c_str()); + _error->Discard(); + return false; } bool AptIntf::TryToInstall(pkgCache::PkgIterator Pkg, - pkgDepCache &Cache, - pkgProblemResolver &Fix, - bool Remove, - bool BrokenFix, - unsigned int &ExpectedInst) + pkgDepCache &Cache, + pkgProblemResolver &Fix, + bool Remove, + bool BrokenFix, + unsigned int &ExpectedInst) { - // This is a pure virtual package and there is a single available provides - if (Cache[Pkg].CandidateVer == 0 && Pkg->ProvidesList != 0 && - Pkg.ProvidesList()->NextProvides == 0) - { - pkgCache::PkgIterator Tmp = Pkg.ProvidesList().OwnerPkg(); - Pkg = Tmp; - } - - // Check if there is something at all to install - pkgDepCache::StateCache &State = Cache[Pkg]; - if (Remove == true && Pkg->CurrentVer == 0) - { - Fix.Clear(Pkg); - Fix.Protect(Pkg); - Fix.Remove(Pkg); - - return true; - } - - if (State.CandidateVer == 0 && Remove == false) - { - _error->Error("Package %s is virtual and has no installation candidate", Pkg.Name()); - - pk_backend_error_code(m_backend, - PK_ERROR_ENUM_DEP_RESOLUTION_FAILED, - g_strdup_printf("Package %s is virtual and has no " - "installation candidate", - Pkg.Name())); - return false; - } - - Fix.Clear(Pkg); - Fix.Protect(Pkg); - if (Remove == true) - { - Fix.Remove(Pkg); - Cache.MarkDelete(Pkg,_config->FindB("APT::Get::Purge", false)); - return true; - } - - // Install it - Cache.MarkInstall(Pkg,false); - if (State.Install() == false) - { - if (_config->FindB("APT::Get::ReInstall",false) == true) { - if (Pkg->CurrentVer == 0 || Pkg.CurrentVer().Downloadable() == false) { - // ioprintf(c1out,_("Reinstallation of %s is not possible, it cannot be downloaded.\n"), - // Pkg.Name()); - ; - } else { - Cache.SetReInstall(Pkg,true); - } - } else { - // if (AllowFail == true) - // ioprintf(c1out,_("%s is already the newest version.\n"), - // Pkg.Name()); - } - } else { - ExpectedInst++; - } - -// cout << "trytoinstall ExpectedInst " << ExpectedInst << endl; - // Install it with autoinstalling enabled (if we not respect the minial - // required deps or the policy) - if ((State.InstBroken() == true || State.InstPolicyBroken() == true) && - BrokenFix == false) { - Cache.MarkInstall(Pkg,true); - } - - return true; + // This is a pure virtual package and there is a single available provides + if (Cache[Pkg].CandidateVer == 0 && Pkg->ProvidesList != 0 && + Pkg.ProvidesList()->NextProvides == 0) { + pkgCache::PkgIterator Tmp = Pkg.ProvidesList().OwnerPkg(); + Pkg = Tmp; + } + + // Check if there is something at all to install + pkgDepCache::StateCache &State = Cache[Pkg]; + if (Remove == true && Pkg->CurrentVer == 0) { + Fix.Clear(Pkg); + Fix.Protect(Pkg); + Fix.Remove(Pkg); + + return true; + } + + if (State.CandidateVer == 0 && Remove == false) { + _error->Error("Package %s is virtual and has no installation candidate", Pkg.Name()); + + pk_backend_error_code(m_backend, + PK_ERROR_ENUM_DEP_RESOLUTION_FAILED, + g_strdup_printf("Package %s is virtual and has no " + "installation candidate", + Pkg.Name())); + return false; + } + + Fix.Clear(Pkg); + Fix.Protect(Pkg); + if (Remove == true) { + Fix.Remove(Pkg); + Cache.MarkDelete(Pkg,_config->FindB("APT::Get::Purge", false)); + return true; + } + + // Install it + Cache.MarkInstall(Pkg,false); + if (State.Install() == false) { + if (_config->FindB("APT::Get::ReInstall",false) == true) { + if (Pkg->CurrentVer == 0 || Pkg.CurrentVer().Downloadable() == false) { + // ioprintf(c1out,_("Reinstallation of %s is not possible, it cannot be downloaded.\n"), + // Pkg.Name()); + ; + } else { + Cache.SetReInstall(Pkg,true); + } + } else { + // if (AllowFail == true) + // ioprintf(c1out,_("%s is already the newest version.\n"), + // Pkg.Name()); + } + } else { + ExpectedInst++; + } + + // cout << "trytoinstall ExpectedInst " << ExpectedInst << endl; + // Install it with autoinstalling enabled (if we not respect the minial + // required deps or the policy) + if ((State.InstBroken() == true || State.InstPolicyBroken() == true) && + BrokenFix == false) { + Cache.MarkInstall(Pkg,true); + } + + return true; } // checks if there are Essential packages being removed bool AptIntf::removingEssentialPackages(pkgCacheFile &Cache) { - string List; - bool *Added = new bool[Cache->Head().PackageCount]; - for (unsigned int I = 0; I != Cache->Head().PackageCount; I++){ - Added[I] = false; - } - - for (pkgCache::PkgIterator I = Cache->PkgBegin(); ! I.end(); ++I) { - if ((I->Flags & pkgCache::Flag::Essential) != pkgCache::Flag::Essential && - (I->Flags & pkgCache::Flag::Important) != pkgCache::Flag::Important) { - continue; - } - - if (Cache[I].Delete() == true) { - if (Added[I->ID] == false) { - Added[I->ID] = true; - List += string(I.Name()) + " "; - } - } - - if (I->CurrentVer == 0) { - continue; - } - - // Print out any essential package depenendents that are to be removed - for (pkgCache::DepIterator D = I.CurrentVer().DependsList(); D.end() == false; D++) { - // Skip everything but depends - if (D->Type != pkgCache::Dep::PreDepends && - D->Type != pkgCache::Dep::Depends){ - continue; - } - - pkgCache::PkgIterator P = D.SmartTargetPkg(); - if (Cache[P].Delete() == true) - { - if (Added[P->ID] == true){ - continue; - } - Added[P->ID] = true; - - char S[300]; - snprintf(S, sizeof(S), "%s (due to %s) ", P.Name(), I.Name()); - List += S; - } - } - } - - delete [] Added; - if (!List.empty()) { - pk_backend_error_code(m_backend, - PK_ERROR_ENUM_CANNOT_REMOVE_SYSTEM_PACKAGE, - g_strdup_printf("WARNING: You are trying to remove the " - "following essential packages: %s", - List.c_str())); - return true; - } - - return false; + string List; + bool *Added = new bool[Cache->Head().PackageCount]; + for (unsigned int I = 0; I != Cache->Head().PackageCount; ++I) { + Added[I] = false; + } + + for (pkgCache::PkgIterator I = Cache->PkgBegin(); ! I.end(); ++I) { + if ((I->Flags & pkgCache::Flag::Essential) != pkgCache::Flag::Essential && + (I->Flags & pkgCache::Flag::Important) != pkgCache::Flag::Important) { + continue; + } + + if (Cache[I].Delete() == true) { + if (Added[I->ID] == false) { + Added[I->ID] = true; + List += string(I.Name()) + " "; + } + } + + if (I->CurrentVer == 0) { + continue; + } + + // Print out any essential package depenendents that are to be removed + for (pkgCache::DepIterator D = I.CurrentVer().DependsList(); D.end() == false; ++D) { + // Skip everything but depends + if (D->Type != pkgCache::Dep::PreDepends && + D->Type != pkgCache::Dep::Depends){ + continue; + } + + pkgCache::PkgIterator P = D.SmartTargetPkg(); + if (Cache[P].Delete() == true) + { + if (Added[P->ID] == true){ + continue; + } + Added[P->ID] = true; + + char S[300]; + snprintf(S, sizeof(S), "%s (due to %s) ", P.Name(), I.Name()); + List += S; + } + } + } + + delete [] Added; + if (!List.empty()) { + pk_backend_error_code(m_backend, + PK_ERROR_ENUM_CANNOT_REMOVE_SYSTEM_PACKAGE, + g_strdup_printf("WARNING: You are trying to remove the " + "following essential packages: %s", + List.c_str())); + return true; + } + + return false; } // emitChangedPackages - Show packages to newly install @@ -1314,8 +1292,7 @@ void AptIntf::emitChangedPackages(pkgCacheFile &Cache) PkgList downgrading; string VersionsList; - for (pkgCache::PkgIterator pkg = Cache->PkgBegin(); ! pkg.end(); ++pkg) - { + for (pkgCache::PkgIterator pkg = Cache->PkgBegin(); ! pkg.end(); ++pkg) { if (Cache[pkg].NewInstall() == true) { // installing installing.push_back(PkgPair(pkg, find_candidate_ver(pkg))); @@ -1370,88 +1347,86 @@ void AptIntf::emitTransactionPackage(string name, PkInfoEnum state) pkgPair.first = packageCache->FindPkg(name); // Ignore packages that could not be found or that exist only due to dependencies. if (pkgPair.first.end() == true || - (pkgPair.first.VersionList().end() && pkgPair.first.ProvidesList().end())) { + (pkgPair.first.VersionList().end() && pkgPair.first.ProvidesList().end())) { return; } pkgPair.second = find_ver(pkgPair.first); // check to see if the provided package isn't virtual too - if (pkgPair.second.end() == false) - { + if (pkgPair.second.end() == false) { emit_package(pkgPair, PK_FILTER_ENUM_NONE, state); } pkgPair.second = find_candidate_ver(pkgPair.first); // check to see if we found the package - if (pkgPair.second.end() == false) - { + if (pkgPair.second.end() == false) { emit_package(pkgPair, PK_FILTER_ENUM_NONE, state); } } void AptIntf::updateInterface(int fd, int writeFd) { - char buf[2]; - static char line[1024] = ""; - - while (1) { - // This algorithm should be improved (it's the same as the rpm one ;) - int len = read(fd, buf, 1); - - // nothing was read - if(len < 1) { - break; - } - - // update the time we last saw some action - m_lastTermAction = time(NULL); - - if( buf[0] == '\n') { - if (_cancel) { - kill(m_child_pid, SIGTERM); - } - //cout << "got line: " << line << endl; - - gchar **split = g_strsplit(line, ":",5); - gchar *status = g_strstrip(split[0]); - gchar *pkg = g_strstrip(split[1]); - gchar *percent = g_strstrip(split[2]); - gchar *str = g_strdup(g_strstrip(split[3])); - - // major problem here, we got unexpected input. should _never_ happen - if(!(pkg && status)) { - continue; - } - - // first check for errors and conf-file prompts - if (strstr(status, "pmerror") != NULL) { - // error from dpkg - pk_backend_error_code(m_backend, - PK_ERROR_ENUM_PACKAGE_FAILED_TO_INSTALL, - str); - } else if (strstr(status, "pmconffile") != NULL) { - // conffile-request from dpkg, needs to be parsed different - int i=0; - int count=0; - string orig_file, new_file; - - // go to first ' and read until the end - for(;str[i] != '\'' || str[i] == 0; i++) - /*nothing*/ - ; - i++; - for(;str[i] != '\'' || str[i] == 0; i++) - orig_file.append(1, str[i]); - i++; - - // same for second ' and read until the end - for(;str[i] != '\'' || str[i] == 0; i++) - /*nothing*/ - ; - i++; - for(;str[i] != '\'' || str[i] == 0; i++) - new_file.append(1, str[i]); - i++; + char buf[2]; + static char line[1024] = ""; + + while (1) { + // This algorithm should be improved (it's the same as the rpm one ;) + int len = read(fd, buf, 1); + + // nothing was read + if(len < 1) { + break; + } + + // update the time we last saw some action + m_lastTermAction = time(NULL); + + if( buf[0] == '\n') { + if (_cancel) { + kill(m_child_pid, SIGTERM); + } + //cout << "got line: " << line << endl; + + gchar **split = g_strsplit(line, ":",5); + gchar *status = g_strstrip(split[0]); + gchar *pkg = g_strstrip(split[1]); + gchar *percent = g_strstrip(split[2]); + gchar *str = g_strdup(g_strstrip(split[3])); + + // major problem here, we got unexpected input. should _never_ happen + if(!(pkg && status)) { + continue; + } + + // first check for errors and conf-file prompts + if (strstr(status, "pmerror") != NULL) { + // error from dpkg + pk_backend_error_code(m_backend, + PK_ERROR_ENUM_PACKAGE_FAILED_TO_INSTALL, + str); + } else if (strstr(status, "pmconffile") != NULL) { + // conffile-request from dpkg, needs to be parsed different + int i=0; + int count=0; + string orig_file, new_file; + + // go to first ' and read until the end + for(;str[i] != '\'' || str[i] == 0; i++) + /*nothing*/ + ; + i++; + for(;str[i] != '\'' || str[i] == 0; i++) + orig_file.append(1, str[i]); + i++; + + // same for second ' and read until the end + for(;str[i] != '\'' || str[i] == 0; i++) + /*nothing*/ + ; + i++; + for(;str[i] != '\'' || str[i] == 0; i++) + new_file.append(1, str[i]); + i++; gchar *filename; filename = g_build_filename(DATADIR, "PackageKit", "helpers", "aptcc", "pkconffile", NULL); @@ -1481,15 +1456,15 @@ void AptIntf::updateInterface(int fd, int writeFd) gboolean ret; gint exitStatus; ret = g_spawn_sync(NULL, // working dir - argv, // argv - envp, // envp - G_SPAWN_LEAVE_DESCRIPTORS_OPEN, - NULL, // child_setup - NULL, // user_data - NULL, // standard_output - NULL, // standard_error - &exitStatus, - &error); + argv, // argv + envp, // envp + G_SPAWN_LEAVE_DESCRIPTORS_OPEN, + NULL, // child_setup + NULL, // user_data + NULL, // standard_output + NULL, // standard_error + &exitStatus, + &error); int exit_code = WEXITSTATUS(exitStatus); cout << filename << " " << exit_code << " ret: "<< ret << endl; @@ -1510,11 +1485,11 @@ void AptIntf::updateInterface(int fd, int writeFd) // either the user didn't choose an option or the front end failed' gchar *confmsg; confmsg = g_strdup_printf("The configuration file '%s' " - "(modified by you or a script) " - "has a newer version '%s'.\n" - "Please verify your changes and update it manually.", - orig_file.c_str(), - new_file.c_str()); + "(modified by you or a script) " + "has a newer version '%s'.\n" + "Please verify your changes and update it manually.", + orig_file.c_str(), + new_file.c_str()); pk_backend_message(m_backend, PK_MESSAGE_ENUM_CONFIG_FILES_CHANGED, confmsg); @@ -1524,145 +1499,145 @@ void AptIntf::updateInterface(int fd, int writeFd) g_debug("Failed to write"); } } - } else if (strstr(status, "pmstatus") != NULL) { - // INSTALL & UPDATE - // - Running dpkg - // loops ALL - // - 0 Installing pkg (sometimes this is skiped) - // - 25 Preparing pkg - // - 50 Unpacking pkg - // - 75 Preparing to configure pkg - // ** Some pkgs have - // - Running post-installation - // - Running dpkg - // reloops all - // - 0 Configuring pkg - // - +25 Configuring pkg (SOMETIMES) - // - 100 Installed pkg - // after all - // - Running post-installation - - // REMOVE - // - Running dpkg - // loops - // - 25 Removing pkg - // - 50 Preparing for removal of pkg - // - 75 Removing pkg - // - 100 Removed pkg - // after all - // - Running post-installation - - // Let's start parsing the status: - if (starts_with(str, "Preparing to configure")) { - // Preparing to Install/configure -// cout << "Found Preparing to configure! " << line << endl; - // The next item might be Configuring so better it be 100 - m_lastSubProgress = 100; - emitTransactionPackage(pkg, PK_INFO_ENUM_PREPARING); - pk_backend_set_sub_percentage(m_backend, 75); - } else if (starts_with(str, "Preparing for removal")) { - // Preparing to Install/configure -// cout << "Found Preparing for removal! " << line << endl; - m_lastSubProgress = 50; - emitTransactionPackage(pkg, PK_INFO_ENUM_REMOVING); - pk_backend_set_sub_percentage(m_backend, m_lastSubProgress); - } else if (starts_with(str, "Preparing")) { - // Preparing to Install/configure -// cout << "Found Preparing! " << line << endl; - // if last package is different then finish it - if (!m_lastPackage.empty() && m_lastPackage.compare(pkg) != 0) { -// cout << "FINISH the last package: " << m_lastPackage << endl; - emitTransactionPackage(m_lastPackage, PK_INFO_ENUM_FINISHED); - } - emitTransactionPackage(pkg, PK_INFO_ENUM_PREPARING); - pk_backend_set_sub_percentage(m_backend, 25); - } else if (starts_with(str, "Unpacking")) { -// cout << "Found Unpacking! " << line << endl; - emitTransactionPackage(pkg, PK_INFO_ENUM_DECOMPRESSING); - pk_backend_set_sub_percentage(m_backend, 50); - } else if (starts_with(str, "Configuring")) { - // Installing Package -// cout << "Found Configuring! " << line << endl; - if (m_lastSubProgress >= 100 && !m_lastPackage.empty()) { - cout << "FINISH the last package: " << m_lastPackage << endl; - emitTransactionPackage(m_lastPackage, PK_INFO_ENUM_FINISHED); - m_lastSubProgress = 0; - } - emitTransactionPackage(pkg, PK_INFO_ENUM_INSTALLING); - pk_backend_set_sub_percentage(m_backend, m_lastSubProgress); - m_lastSubProgress += 25; - } else if (starts_with(str, "Running dpkg")) { -// cout << "Found Running dpkg! " << line << endl; - } else if (starts_with(str, "Running")) { -// cout << "Found Running! " << line << endl; - pk_backend_set_status (m_backend, PK_STATUS_ENUM_COMMIT); - } else if (starts_with(str, "Installing")) { -// cout << "Found Installing! " << line << endl; - // FINISH the last package - if (!m_lastPackage.empty()) { -// cout << "FINISH the last package: " << m_lastPackage << endl; - emitTransactionPackage(m_lastPackage, PK_INFO_ENUM_FINISHED); - } - m_lastSubProgress = 0; - emitTransactionPackage(pkg, PK_INFO_ENUM_INSTALLING); - pk_backend_set_sub_percentage(m_backend, 0); - } else if (starts_with(str, "Removing")) { -// cout << "Found Removing! " << line << endl; - if (m_lastSubProgress >= 100 && !m_lastPackage.empty()) { -// cout << "FINISH the last package: " << m_lastPackage << endl; - emitTransactionPackage(m_lastPackage, PK_INFO_ENUM_FINISHED); - } - m_lastSubProgress += 25; - emitTransactionPackage(pkg, PK_INFO_ENUM_REMOVING); - pk_backend_set_sub_percentage(m_backend, m_lastSubProgress); - } else if (starts_with(str, "Installed") || - starts_with(str, "Removed")) { -// cout << "Found FINISHED! " << line << endl; - m_lastSubProgress = 100; - emitTransactionPackage(pkg, PK_INFO_ENUM_FINISHED); - } else { - cout << ">>>Unmaped value<<< :" << line << endl; - } - - if (!starts_with(str, "Running")) { - m_lastPackage = pkg; - } - m_startCounting = true; - } else { - m_startCounting = true; - } - - int val = atoi(percent); - //cout << "progress: " << val << endl; - pk_backend_set_percentage(m_backend, val); - - // clean-up - g_strfreev(split); - g_free(str); - line[0] = 0; - } else { - buf[1] = 0; - strcat(line, buf); - } - } - - time_t now = time(NULL); - - if(!m_startCounting) { - usleep(100000); - // wait until we get the first message from apt - m_lastTermAction = now; - } - - if ((now - m_lastTermAction) > m_terminalTimeout) { - // get some debug info - g_warning("no statusfd changes/content updates in terminal for %i" - " seconds",m_terminalTimeout); - m_lastTermAction = time(NULL); - } - - // sleep for a while to don't obcess over it - usleep(5000); + } else if (strstr(status, "pmstatus") != NULL) { + // INSTALL & UPDATE + // - Running dpkg + // loops ALL + // - 0 Installing pkg (sometimes this is skiped) + // - 25 Preparing pkg + // - 50 Unpacking pkg + // - 75 Preparing to configure pkg + // ** Some pkgs have + // - Running post-installation + // - Running dpkg + // reloops all + // - 0 Configuring pkg + // - +25 Configuring pkg (SOMETIMES) + // - 100 Installed pkg + // after all + // - Running post-installation + + // REMOVE + // - Running dpkg + // loops + // - 25 Removing pkg + // - 50 Preparing for removal of pkg + // - 75 Removing pkg + // - 100 Removed pkg + // after all + // - Running post-installation + + // Let's start parsing the status: + if (starts_with(str, "Preparing to configure")) { + // Preparing to Install/configure + // cout << "Found Preparing to configure! " << line << endl; + // The next item might be Configuring so better it be 100 + m_lastSubProgress = 100; + emitTransactionPackage(pkg, PK_INFO_ENUM_PREPARING); + pk_backend_set_sub_percentage(m_backend, 75); + } else if (starts_with(str, "Preparing for removal")) { + // Preparing to Install/configure + // cout << "Found Preparing for removal! " << line << endl; + m_lastSubProgress = 50; + emitTransactionPackage(pkg, PK_INFO_ENUM_REMOVING); + pk_backend_set_sub_percentage(m_backend, m_lastSubProgress); + } else if (starts_with(str, "Preparing")) { + // Preparing to Install/configure + // cout << "Found Preparing! " << line << endl; + // if last package is different then finish it + if (!m_lastPackage.empty() && m_lastPackage.compare(pkg) != 0) { + // cout << "FINISH the last package: " << m_lastPackage << endl; + emitTransactionPackage(m_lastPackage, PK_INFO_ENUM_FINISHED); + } + emitTransactionPackage(pkg, PK_INFO_ENUM_PREPARING); + pk_backend_set_sub_percentage(m_backend, 25); + } else if (starts_with(str, "Unpacking")) { + // cout << "Found Unpacking! " << line << endl; + emitTransactionPackage(pkg, PK_INFO_ENUM_DECOMPRESSING); + pk_backend_set_sub_percentage(m_backend, 50); + } else if (starts_with(str, "Configuring")) { + // Installing Package + // cout << "Found Configuring! " << line << endl; + if (m_lastSubProgress >= 100 && !m_lastPackage.empty()) { + cout << "FINISH the last package: " << m_lastPackage << endl; + emitTransactionPackage(m_lastPackage, PK_INFO_ENUM_FINISHED); + m_lastSubProgress = 0; + } + emitTransactionPackage(pkg, PK_INFO_ENUM_INSTALLING); + pk_backend_set_sub_percentage(m_backend, m_lastSubProgress); + m_lastSubProgress += 25; + } else if (starts_with(str, "Running dpkg")) { + // cout << "Found Running dpkg! " << line << endl; + } else if (starts_with(str, "Running")) { + // cout << "Found Running! " << line << endl; + pk_backend_set_status (m_backend, PK_STATUS_ENUM_COMMIT); + } else if (starts_with(str, "Installing")) { + // cout << "Found Installing! " << line << endl; + // FINISH the last package + if (!m_lastPackage.empty()) { + // cout << "FINISH the last package: " << m_lastPackage << endl; + emitTransactionPackage(m_lastPackage, PK_INFO_ENUM_FINISHED); + } + m_lastSubProgress = 0; + emitTransactionPackage(pkg, PK_INFO_ENUM_INSTALLING); + pk_backend_set_sub_percentage(m_backend, 0); + } else if (starts_with(str, "Removing")) { + // cout << "Found Removing! " << line << endl; + if (m_lastSubProgress >= 100 && !m_lastPackage.empty()) { + // cout << "FINISH the last package: " << m_lastPackage << endl; + emitTransactionPackage(m_lastPackage, PK_INFO_ENUM_FINISHED); + } + m_lastSubProgress += 25; + emitTransactionPackage(pkg, PK_INFO_ENUM_REMOVING); + pk_backend_set_sub_percentage(m_backend, m_lastSubProgress); + } else if (starts_with(str, "Installed") || + starts_with(str, "Removed")) { + // cout << "Found FINISHED! " << line << endl; + m_lastSubProgress = 100; + emitTransactionPackage(pkg, PK_INFO_ENUM_FINISHED); + } else { + cout << ">>>Unmaped value<<< :" << line << endl; + } + + if (!starts_with(str, "Running")) { + m_lastPackage = pkg; + } + m_startCounting = true; + } else { + m_startCounting = true; + } + + int val = atoi(percent); + //cout << "progress: " << val << endl; + pk_backend_set_percentage(m_backend, val); + + // clean-up + g_strfreev(split); + g_free(str); + line[0] = 0; + } else { + buf[1] = 0; + strcat(line, buf); + } + } + + time_t now = time(NULL); + + if(!m_startCounting) { + usleep(100000); + // wait until we get the first message from apt + m_lastTermAction = now; + } + + if ((now - m_lastTermAction) > m_terminalTimeout) { + // get some debug info + g_warning("no statusfd changes/content updates in terminal for %i" + " seconds",m_terminalTimeout); + m_lastTermAction = time(NULL); + } + + // sleep for a while to don't obcess over it + usleep(5000); } // DoAutomaticRemove - Remove all automatic unused packages @@ -1670,41 +1645,38 @@ void AptIntf::updateInterface(int fd, int writeFd) /* Remove unused automatic packages */ bool AptIntf::DoAutomaticRemove(pkgCacheFile &Cache) { - bool doAutoRemove = _config->FindB("APT::Get::AutomaticRemove", false); - pkgDepCache::ActionGroup group(*Cache); - - if (_config->FindB("APT::Get::Remove",true) == false && - doAutoRemove == true) - { - cout << "We are not supposed to delete stuff, can't start " - "AutoRemover" << endl; - doAutoRemove = false; - } - - // look over the cache to see what can be removed - for (pkgCache::PkgIterator Pkg = Cache->PkgBegin(); ! Pkg.end(); ++Pkg) - { - if (Cache[Pkg].Garbage && doAutoRemove) - { - if (Pkg.CurrentVer() != 0 && - Pkg->CurrentState != pkgCache::State::ConfigFiles) { - Cache->MarkDelete(Pkg, _config->FindB("APT::Get::Purge", false)); - } else { - Cache->MarkKeep(Pkg, false, false); - } - } - } - - // Now see if we destroyed anything - if (Cache->BrokenCount() != 0) - { - cout << "Hmm, seems like the AutoRemover destroyed something which really\n" - "shouldn't happen. Please file a bug report against apt." << endl; - // TODO call show_broken - // ShowBroken(c1out,Cache,false); - return _error->Error("Internal Error, AutoRemover broke stuff"); - } - return true; + bool doAutoRemove = _config->FindB("APT::Get::AutomaticRemove", false); + pkgDepCache::ActionGroup group(*Cache); + + if (_config->FindB("APT::Get::Remove",true) == false && + doAutoRemove == true) { + cout << "We are not supposed to delete stuff, can't start " + "AutoRemover" << endl; + doAutoRemove = false; + } + + // look over the cache to see what can be removed + for (pkgCache::PkgIterator Pkg = Cache->PkgBegin(); ! Pkg.end(); ++Pkg) { + if (Cache[Pkg].Garbage && doAutoRemove) + { + if (Pkg.CurrentVer() != 0 && + Pkg->CurrentState != pkgCache::State::ConfigFiles) { + Cache->MarkDelete(Pkg, _config->FindB("APT::Get::Purge", false)); + } else { + Cache->MarkKeep(Pkg, false, false); + } + } + } + + // Now see if we destroyed anything + if (Cache->BrokenCount() != 0) { + cout << "Hmm, seems like the AutoRemover destroyed something which really\n" + "shouldn't happen. Please file a bug report against apt." << endl; + // TODO call show_broken + // ShowBroken(c1out,Cache,false); + return _error->Error("Internal Error, AutoRemover broke stuff"); + } + return true; } PkgList AptIntf::resolvePI(gchar **package_ids, PkBitfield filters) @@ -1716,7 +1688,7 @@ PkgList AptIntf::resolvePI(gchar **package_ids, PkBitfield filters) // Don't fail if package list is empty if (package_ids == NULL) - return ret; + return ret; for (uint i = 0; i < g_strv_length(package_ids); ++i) { if (_cancel) { @@ -1797,17 +1769,17 @@ PkgList AptIntf::resolvePI(gchar **package_ids, PkBitfield filters) bool AptIntf::markAutoInstalled(pkgCacheFile &cache, PkgList &pkgs, bool flag) { - bool ret; - for(PkgList::iterator i = pkgs.begin(); i != pkgs.end(); ++i) { - if (_cancel) { - break; - } + bool ret; + for(PkgList::iterator i = pkgs.begin(); i != pkgs.end(); ++i) { + if (_cancel) { + break; + } - // Mark package as auto-installed - cache->MarkAuto(i->first, flag); - } + // Mark package as auto-installed + cache->MarkAuto(i->first, flag); + } - return true; + return true; } bool AptIntf::markFileForInstall(const gchar *file, PkgList &install, PkgList &remove) @@ -1828,17 +1800,17 @@ bool AptIntf::markFileForInstall(const gchar *file, PkgList &install, PkgList &r gboolean ret; ret = g_spawn_sync(NULL, // working dir - argv, // argv - NULL, // envp - G_SPAWN_LEAVE_DESCRIPTORS_OPEN, - NULL, // child_setup - NULL, // user_data - &std_out, // standard_output - &std_err, // standard_error - &status, - &gerror); + argv, // argv + NULL, // envp + G_SPAWN_LEAVE_DESCRIPTORS_OPEN, + NULL, // child_setup + NULL, // user_data + &std_out, // standard_output + &std_err, // standard_error + &status, + &gerror); int exit_code = WEXITSTATUS(status); -// cout << "DebStatus " << exit_code << " WEXITSTATUS " << WEXITSTATUS(status) << " ret: "<< ret << endl; + // cout << "DebStatus " << exit_code << " WEXITSTATUS " << WEXITSTATUS(status) << " ret: "<< ret << endl; cout << "std_out " << strlen(std_out) << std_out << endl; cout << "std_err " << strlen(std_err) << std_err << endl; @@ -1859,27 +1831,27 @@ bool AptIntf::markFileForInstall(const gchar *file, PkgList &install, PkgList &r // The second line contains the packages to remove with '-' appended to // the end of the package name - gchar **removePkgs = NULL; - if (strlen(lines[1]) > 0) { - gchar *removeStr = g_strndup(lines[1], strlen(lines[1]) - 1); - removePkgs = g_strsplit(removeStr, "- ", 0); - g_free(removeStr); - } + gchar **removePkgs = NULL; + if (strlen(lines[1]) > 0) { + gchar *removeStr = g_strndup(lines[1], strlen(lines[1]) - 1); + removePkgs = g_strsplit(removeStr, "- ", 0); + g_free(removeStr); + } // Resolve the packages to install PkBitfield intallFilters; intallFilters = pk_bitfield_from_enums ( - PK_FILTER_ENUM_NOT_INSTALLED, - PK_FILTER_ENUM_ARCH, - -1); + PK_FILTER_ENUM_NOT_INSTALLED, + PK_FILTER_ENUM_ARCH, + -1); install = resolvePI(installPkgs, intallFilters); // Resolve the packages to remove PkBitfield removeFilters; removeFilters = pk_bitfield_from_enums ( - PK_FILTER_ENUM_INSTALLED, - PK_FILTER_ENUM_ARCH, - -1); + PK_FILTER_ENUM_INSTALLED, + PK_FILTER_ENUM_ARCH, + -1); remove = resolvePI(removePkgs, removeFilters); m_localDebFile = file; @@ -1893,142 +1865,142 @@ bool AptIntf::markFileForInstall(const gchar *file, PkgList &install, PkgList &r bool AptIntf::installFile(const gchar *path, bool simulate) { - if (path == NULL) { - g_error ("installFile() path was NULL!"); - return false; - } - - DebFile deb(path); - if (!deb.isValid()) { - pk_backend_error_code(m_backend, PK_ERROR_ENUM_TRANSACTION_ERROR, "DEB package is invalid!"); - return false; - } - - if (simulate) { - // TODO: Emit signal for to-be-installed package - //emit_package("", PK_FILTER_ENUM_NONE, PK_INFO_ENUM_INSTALLING); - return true; - } - - string arch = deb.architecture(); - string aptArch = _config->Find("APT::Architecture"); - - // TODO: Perform this check _before_ installing all dependencies. (The whole thing needs - // some rethinking anyway) - if ((arch != "all") && - (arch != aptArch)) { - cout << arch << " vs. " << aptArch << endl; - gchar *msg = g_strdup_printf ("Package has wrong architecture, it is %s, but we need %s", - arch.c_str(), aptArch.c_str()); - pk_backend_error_code(m_backend, PK_ERROR_ENUM_INCOMPATIBLE_ARCHITECTURE, msg); - g_free (msg); - return false; - } - - // Build package-id for the new package - gchar *deb_package_id = pk_package_id_build (deb.packageName ().c_str (), - deb.version ().c_str (), - deb.architecture ().c_str (), - "local"); - const gchar *deb_summary = deb.summary ().c_str (); - - gint status; - gchar **argv; - gchar **envp; - gchar *std_out; - gchar *std_err; - GError *error = NULL; - - argv = (gchar **) g_malloc(4 * sizeof(gchar *)); - argv[0] = g_strdup("/usr/bin/dpkg"); - argv[1] = g_strdup("-i"); - argv[2] = g_strdup(path); //g_strdup_printf("\'%s\'", path); - argv[3] = NULL; - - envp = (gchar **) g_malloc(4 * sizeof(gchar *)); - envp[0] = g_strdup("PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"); - envp[1] = g_strdup("DEBIAN_FRONTEND=passthrough"); - envp[2] = g_strdup_printf("DEBCONF_PIPE=%s", pk_backend_get_frontend_socket(m_backend)); - envp[3] = NULL; - - // We're installing the package now... - pk_backend_package (m_backend, PK_INFO_ENUM_INSTALLING, deb_package_id, deb_summary); - - g_spawn_sync(NULL, // working dir - argv, - envp, - G_SPAWN_LEAVE_DESCRIPTORS_OPEN, - NULL, // child_setup - NULL, // user_data - &std_out, // standard_output - &std_err, // standard_error - &status, - &error); - int exit_code = WEXITSTATUS(status); - - cout << "DpkgOut: " << std_out << endl; - cout << "DpkgErr: " << std_err << endl; - - if (error != NULL) { - // We couldn't run dpkg for some reason... - pk_backend_error_code(m_backend, PK_ERROR_ENUM_TRANSACTION_ERROR, error->message); - return false; - } - - // If installation has failed... - if (exit_code != 0) { - if ((std_out == NULL) || (strlen(std_out) == 0)) { - pk_backend_error_code(m_backend, PK_ERROR_ENUM_TRANSACTION_ERROR, std_err); - } else { - pk_backend_error_code(m_backend, PK_ERROR_ENUM_TRANSACTION_ERROR, std_out); - } - return false; - } - - // Emit data of the now-installed DEB package - pk_backend_package (m_backend, PK_INFO_ENUM_INSTALLED, deb_package_id, deb_summary); - g_free (deb_package_id); - - return true; + if (path == NULL) { + g_error ("installFile() path was NULL!"); + return false; + } + + DebFile deb(path); + if (!deb.isValid()) { + pk_backend_error_code(m_backend, PK_ERROR_ENUM_TRANSACTION_ERROR, "DEB package is invalid!"); + return false; + } + + if (simulate) { + // TODO: Emit signal for to-be-installed package + //emit_package("", PK_FILTER_ENUM_NONE, PK_INFO_ENUM_INSTALLING); + return true; + } + + string arch = deb.architecture(); + string aptArch = _config->Find("APT::Architecture"); + + // TODO: Perform this check _before_ installing all dependencies. (The whole thing needs + // some rethinking anyway) + if ((arch != "all") && + (arch != aptArch)) { + cout << arch << " vs. " << aptArch << endl; + gchar *msg = g_strdup_printf ("Package has wrong architecture, it is %s, but we need %s", + arch.c_str(), aptArch.c_str()); + pk_backend_error_code(m_backend, PK_ERROR_ENUM_INCOMPATIBLE_ARCHITECTURE, msg); + g_free (msg); + return false; + } + + // Build package-id for the new package + gchar *deb_package_id = pk_package_id_build (deb.packageName ().c_str (), + deb.version ().c_str (), + deb.architecture ().c_str (), + "local"); + const gchar *deb_summary = deb.summary ().c_str (); + + gint status; + gchar **argv; + gchar **envp; + gchar *std_out; + gchar *std_err; + GError *error = NULL; + + argv = (gchar **) g_malloc(4 * sizeof(gchar *)); + argv[0] = g_strdup("/usr/bin/dpkg"); + argv[1] = g_strdup("-i"); + argv[2] = g_strdup(path); //g_strdup_printf("\'%s\'", path); + argv[3] = NULL; + + envp = (gchar **) g_malloc(4 * sizeof(gchar *)); + envp[0] = g_strdup("PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"); + envp[1] = g_strdup("DEBIAN_FRONTEND=passthrough"); + envp[2] = g_strdup_printf("DEBCONF_PIPE=%s", pk_backend_get_frontend_socket(m_backend)); + envp[3] = NULL; + + // We're installing the package now... + pk_backend_package (m_backend, PK_INFO_ENUM_INSTALLING, deb_package_id, deb_summary); + + g_spawn_sync(NULL, // working dir + argv, + envp, + G_SPAWN_LEAVE_DESCRIPTORS_OPEN, + NULL, // child_setup + NULL, // user_data + &std_out, // standard_output + &std_err, // standard_error + &status, + &error); + int exit_code = WEXITSTATUS(status); + + cout << "DpkgOut: " << std_out << endl; + cout << "DpkgErr: " << std_err << endl; + + if (error != NULL) { + // We couldn't run dpkg for some reason... + pk_backend_error_code(m_backend, PK_ERROR_ENUM_TRANSACTION_ERROR, error->message); + return false; + } + + // If installation has failed... + if (exit_code != 0) { + if ((std_out == NULL) || (strlen(std_out) == 0)) { + pk_backend_error_code(m_backend, PK_ERROR_ENUM_TRANSACTION_ERROR, std_err); + } else { + pk_backend_error_code(m_backend, PK_ERROR_ENUM_TRANSACTION_ERROR, std_out); + } + return false; + } + + // Emit data of the now-installed DEB package + pk_backend_package (m_backend, PK_INFO_ENUM_INSTALLED, deb_package_id, deb_summary); + g_free (deb_package_id); + + return true; } bool AptIntf::runTransaction(PkgList &install, PkgList &remove, bool simulate, bool markAuto) { - //cout << "runTransaction" << simulate << remove << endl; - bool WithLock = !simulate; // Check to see if we are just simulating, - //since for that no lock is needed - - pkgCacheFile Cache; - OpTextProgress Prog(*_config); - int timeout = 10; - // TODO test this - while (Cache.Open(&Prog, WithLock) == false) { - // failed to open cache, try checkDeps then.. - // || Cache.CheckDeps(CmdL.FileSize() != 1) == false - if (WithLock == false || (timeout <= 0)) { - show_errors(m_backend, PK_ERROR_ENUM_CANNOT_GET_LOCK); - return false; - } else { - _error->Discard(); - pk_backend_set_status (m_backend, PK_STATUS_ENUM_WAITING_FOR_LOCK); - sleep(1); - timeout--; - } - } - pk_backend_set_status (m_backend, PK_STATUS_ENUM_RUNNING); - - // Enter the special broken fixing mode if the user specified arguments - bool BrokenFix = false; - if (Cache->BrokenCount() != 0) { - BrokenFix = true; - } - - unsigned int ExpectedInst = 0; - pkgProblemResolver Fix(Cache); - - // new scope for the ActionGroup - { - pkgDepCache::ActionGroup group(Cache); + //cout << "runTransaction" << simulate << remove << endl; + bool WithLock = !simulate; // Check to see if we are just simulating, + //since for that no lock is needed + + pkgCacheFile Cache; + OpTextProgress Prog(*_config); + int timeout = 10; + // TODO test this + while (Cache.Open(&Prog, WithLock) == false) { + // failed to open cache, try checkDeps then.. + // || Cache.CheckDeps(CmdL.FileSize() != 1) == false + if (WithLock == false || (timeout <= 0)) { + show_errors(m_backend, PK_ERROR_ENUM_CANNOT_GET_LOCK); + return false; + } else { + _error->Discard(); + pk_backend_set_status (m_backend, PK_STATUS_ENUM_WAITING_FOR_LOCK); + sleep(1); + timeout--; + } + } + pk_backend_set_status (m_backend, PK_STATUS_ENUM_RUNNING); + + // Enter the special broken fixing mode if the user specified arguments + bool BrokenFix = false; + if (Cache->BrokenCount() != 0) { + BrokenFix = true; + } + + unsigned int ExpectedInst = 0; + pkgProblemResolver Fix(Cache); + + // new scope for the ActionGroup + { + pkgDepCache::ActionGroup group(Cache); for(PkgList::iterator i = install.begin(); i != install.end(); ++i) { pkgCache::PkgIterator Pkg = i->first; if (_cancel) { @@ -2036,70 +2008,71 @@ bool AptIntf::runTransaction(PkgList &install, PkgList &remove, bool simulate, b } if (TryToInstall(Pkg, - Cache, - Fix, - false, // remove - BrokenFix, - ExpectedInst) == false) { + Cache, + Fix, + false, // remove + BrokenFix, + ExpectedInst) == false) { return false; } } - if (!simulate) - markAutoInstalled(Cache, install, markAuto); + if (!simulate) { + markAutoInstalled(Cache, install, markAuto); + } - for(PkgList::iterator i = remove.begin(); i != remove.end(); ++i) { + for (PkgList::iterator i = remove.begin(); i != remove.end(); ++i) { pkgCache::PkgIterator Pkg = i->first; if (_cancel) { break; } if (TryToInstall(Pkg, - Cache, - Fix, - true, // remove - BrokenFix, - ExpectedInst) == false) { + Cache, + Fix, + true, // remove + BrokenFix, + ExpectedInst) == false) { return false; } } - // Call the scored problem resolver - Fix.InstallProtect(); - if (Fix.Resolve(true) == false) { - _error->Discard(); - } - - // Now we check the state of the packages, - if (Cache->BrokenCount() != 0) - { - // if the problem resolver could not fix all broken things - // show what is broken - show_broken(m_backend, Cache, false); - return false; - } - } - // Try to auto-remove packages - if (!DoAutomaticRemove(Cache)) { - // TODO - return false; - } - - // check for essential packages!!! - if (removingEssentialPackages(Cache)) { - return false; - } - - if (simulate) { - // Print out a list of packages that are going to be installed extra - emitChangedPackages(Cache); - return true; - } else { - // Store the packages that are going to change - // so we can emit them as we process it. - populateInternalPackages(Cache); - return installPackages(Cache); - } + // Call the scored problem resolver + Fix.InstallProtect(); + if (Fix.Resolve(true) == false) { + _error->Discard(); + } + + // Now we check the state of the packages, + if (Cache->BrokenCount() != 0) { + // if the problem resolver could not fix all broken things + // show what is broken + show_broken(m_backend, Cache, false); + return false; + } + } + + // Try to auto-remove packages + if (!DoAutomaticRemove(Cache)) { + // TODO + return false; + } + + // check for essential packages!!! + if (removingEssentialPackages(Cache)) { + return false; + } + + if (simulate) { + // Print out a list of packages that are going to be installed extra + emitChangedPackages(Cache); + return true; + } else { + // Store the packages that are going to change + // so we can emit them as we process it. + populateInternalPackages(Cache); + return installPackages(Cache); + } } // InstallPackages - Download and install the packages @@ -2108,287 +2081,276 @@ bool AptIntf::runTransaction(PkgList &install, PkgList &remove, bool simulate, b happen and then calls the download routines */ bool AptIntf::installPackages(pkgCacheFile &Cache) { - //cout << "installPackages() called" << endl; - if (_config->FindB("APT::Get::Purge",false) == true) - { - pkgCache::PkgIterator I = Cache->PkgBegin(); - for (; I.end() == false; I++) - { - if (I.Purge() == false && Cache[I].Mode == pkgDepCache::ModeDelete) { - Cache->MarkDelete(I,true); - } - } - } - - // check for essential packages!!! - if (removingEssentialPackages(Cache)) { - return false; - } - - // Sanity check - if (Cache->BrokenCount() != 0) - { - // TODO - show_broken(m_backend, Cache, false); - _error->Error("Internal error, InstallPackages was called with broken packages!"); - return false; - } - - if (Cache->DelCount() == 0 && Cache->InstCount() == 0 && - Cache->BadCount() == 0) { - return true; - } - - // No remove flag - if (Cache->DelCount() != 0 && _config->FindB("APT::Get::Remove", true) == false) { - pk_backend_error_code(m_backend, - PK_ERROR_ENUM_PACKAGE_FAILED_TO_REMOVE, - "Packages need to be removed but remove is disabled."); - return false; - } - - // Create the text record parser - pkgRecords Recs(Cache); - if (_error->PendingError() == true) { - return false; - } - - // Lock the archive directory - FileFd Lock; - if (_config->FindB("Debug::NoLocking", false) == false) - { - Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock")); - if (_error->PendingError() == true) { - return _error->Error("Unable to lock the download directory"); - } - } - - // Create the download object - AcqPackageKitStatus Stat(this, m_backend, _cancel); - - // get a fetcher - pkgAcquire fetcher; - fetcher.Setup(&Stat); - - // Create the package manager and prepare to download -// SPtr<pkgPackageManager> PM= _system->CreatePM(Cache); - SPtr<pkgPackageManager> PM = new pkgDebDPkgPM(Cache); - if (PM->GetArchives(&fetcher, packageSourceList, &Recs) == false || - _error->PendingError() == true) { - return false; - } - - // Generate the list of affected packages - for (pkgCache::PkgIterator pkg = Cache->PkgBegin(); pkg.end() == false; ++pkg) - { - // Ignore no-version packages - if (pkg->VersionList == 0) { - continue; - } + //cout << "installPackages() called" << endl; + if (_config->FindB("APT::Get::Purge",false) == true) { + pkgCache::PkgIterator I = Cache->PkgBegin(); + for (; I.end() == false; ++I) { + if (I.Purge() == false && Cache[I].Mode == pkgDepCache::ModeDelete) { + Cache->MarkDelete(I,true); + } + } + } - // Not interesting - if ((Cache[pkg].Keep() == true || - Cache[pkg].InstVerIter(Cache) == pkg.CurrentVer()) && - pkg.State() == pkgCache::PkgIterator::NeedsNothing && - (Cache[pkg].iFlags & pkgDepCache::ReInstall) != pkgDepCache::ReInstall && - (pkg.Purge() != false || Cache[pkg].Mode != pkgDepCache::ModeDelete || - (Cache[pkg].iFlags & pkgDepCache::Purge) != pkgDepCache::Purge)) - { - continue; - } + // check for essential packages!!! + if (removingEssentialPackages(Cache)) { + return false; + } - pkgCache::VerIterator ver = Cache[pkg].InstVerIter(Cache); - if (ver.end() && (ver = find_candidate_ver(pkg))) { - // Ignore invalid versions - continue; - } + // Sanity check + if (Cache->BrokenCount() != 0) { + // TODO + show_broken(m_backend, Cache, false); + _error->Error("Internal error, InstallPackages was called with broken packages!"); + return false; + } - // Append it to the list - Stat.addPackagePair(PkgPair(pkg, ver)); - } - - // Display statistics - double FetchBytes = fetcher.FetchNeeded(); - double FetchPBytes = fetcher.PartialPresent(); - double DebBytes = fetcher.TotalNeeded(); - if (DebBytes != Cache->DebSize()) - { - cout << DebBytes << ',' << Cache->DebSize() << endl; -cout << "How odd.. The sizes didn't match, email apt@packages.debian.org"; -/* _error->Warning("How odd.. The sizes didn't match, email apt@packages.debian.org");*/ - } - - // Number of bytes -// if (DebBytes != FetchBytes) -// ioprintf(c1out, "Need to get %sB/%sB of archives.\n", -// SizeToStr(FetchBytes).c_str(),SizeToStr(DebBytes).c_str()); -// else if (DebBytes != 0) -// ioprintf(c1out, "Need to get %sB of archives.\n", -// SizeToStr(DebBytes).c_str()); - - // Size delta -// if (Cache->UsrSize() >= 0) -// ioprintf(c1out, "After this operation, %sB of additional disk space will be used.\n", -// SizeToStr(Cache->UsrSize()).c_str()); -// else -// ioprintf(c1out, "After this operation, %sB disk space will be freed.\n", -// SizeToStr(-1*Cache->UsrSize()).c_str()); - - if (_error->PendingError() == true) { - cout << "PendingError " << endl; - return false; - } - - /* Check for enough free space */ - struct statvfs Buf; - string OutputDir = _config->FindDir("Dir::Cache::Archives"); - if (statvfs(OutputDir.c_str(),&Buf) != 0) { - return _error->Errno("statvfs", - "Couldn't determine free space in %s", - OutputDir.c_str()); - } - if (unsigned(Buf.f_bfree) < (FetchBytes - FetchPBytes)/Buf.f_bsize) - { - struct statfs Stat; - if (statfs(OutputDir.c_str(), &Stat) != 0 || - unsigned(Stat.f_type) != RAMFS_MAGIC) - { - pk_backend_error_code(m_backend, - PK_ERROR_ENUM_NO_SPACE_ON_DEVICE, - string("You don't have enough free space in ").append(OutputDir).c_str()); - return _error->Error("You don't have enough free space in %s.", - OutputDir.c_str()); - } - } - - if (!checkTrusted(fetcher, m_backend)) { - return false; - } - - pk_backend_set_status (m_backend, PK_STATUS_ENUM_DOWNLOAD); - pk_backend_set_simultaneous_mode(m_backend, true); - // Download and check if we can continue - if (fetcher.Run() != pkgAcquire::Continue - && _cancel == false) - { - // We failed and we did not cancel - show_errors(m_backend, PK_ERROR_ENUM_PACKAGE_DOWNLOAD_FAILED); - return false; - } - pk_backend_set_simultaneous_mode(m_backend, false); - - if (_error->PendingError() == true) { - cout << "PendingError download" << endl; - return false; - } - - // Right now it's not safe to cancel - pk_backend_set_allow_cancel (m_backend, false); - - // TODO true or false? - if (_cancel) { - return true; - } - - // Download should be finished by now, changing it's status - pk_backend_set_status (m_backend, PK_STATUS_ENUM_RUNNING); - pk_backend_set_percentage(m_backend, PK_BACKEND_PERCENTAGE_INVALID); - pk_backend_set_sub_percentage(m_backend, PK_BACKEND_PERCENTAGE_INVALID); - - // TODO DBus activated does not have all vars - // we could try to see if this is the case - setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 1); - _system->UnLock(); - - if (!m_localDebFile.empty()) { - // add the local file name to be proccessed by the PM queue - pkgDebDPkgPM *pm = static_cast<pkgDebDPkgPM*>(&*PM); - pm->addDebFile(m_localDebFile); - } - - pkgPackageManager::OrderResult res; - res = PM->DoInstallPreFork(); - if (res == pkgPackageManager::Failed) { - g_warning ("Failed to prepare installation"); - show_errors(m_backend, PK_ERROR_ENUM_PACKAGE_DOWNLOAD_FAILED); - return false; - } - - // File descriptors for reading dpkg --status-fd - int readFromChildFD[2]; - if (pipe(readFromChildFD) < 0) { - cout << "Failed to create a pipe" << endl; - return false; - } - - int pty_master; - m_child_pid = forkpty(&pty_master, NULL, NULL, NULL); - if (m_child_pid == -1) { - return false; - } - - if (m_child_pid == 0) { - //cout << "FORKED: installPackages(): DoInstall" << endl; - - // close pipe we don't need - close(readFromChildFD[0]); - - // Change the locale to not get libapt localization - setlocale(LC_ALL, "C"); - - // Debconf handlying - gchar *socket; - if (socket = pk_backend_get_frontend_socket(m_backend)) { - setenv("DEBIAN_FRONTEND", "passthrough", 1); - setenv("DEBCONF_PIPE", socket, 1); - } else { - // we don't have a socket set, let's fallback to noninteractive - setenv("DEBIAN_FRONTEND", "noninteractive", 1); - } - - gchar *locale; - // Set the LANGUAGE so debconf messages get localization - if (locale = pk_backend_get_locale(m_backend)) { - setenv("LANGUAGE", locale, 1); - setenv("LANG", locale, 1); - //setenv("LANG", "C", 1); - } - - // Pass the write end of the pipe to the install function - res = PM->DoInstallPostFork(readFromChildFD[1]); - - // dump errors into cerr (pass it to the parent process) - _error->DumpErrors(); - - close(readFromChildFD[1]); - - return res == 0; - } - - cout << "PARENT proccess running..." << endl; - // make it nonblocking, verry important otherwise - // when the child finish we stay stuck. - fcntl(readFromChildFD[0], F_SETFL, O_NONBLOCK); - fcntl(pty_master, F_SETFL, O_NONBLOCK); - - // init the timer - m_lastTermAction = time(NULL); - m_startCounting = false; - - // Check if the child died - int ret; - char masterbuf[1024]; - while (waitpid(m_child_pid, &ret, WNOHANG) == 0) { - // TODO: This is dpkg's raw output. Maybe save it for error-solving? - while(read(pty_master, masterbuf, sizeof(masterbuf)) > 0); - updateInterface(readFromChildFD[0], pty_master); - } - - close(readFromChildFD[0]); - close(readFromChildFD[1]); - close(pty_master); - - cout << "Parent finished..." << endl; - return true; -} + if (Cache->DelCount() == 0 && Cache->InstCount() == 0 && + Cache->BadCount() == 0) { + return true; + } + + // No remove flag + if (Cache->DelCount() != 0 && _config->FindB("APT::Get::Remove", true) == false) { + pk_backend_error_code(m_backend, + PK_ERROR_ENUM_PACKAGE_FAILED_TO_REMOVE, + "Packages need to be removed but remove is disabled."); + return false; + } + + // Create the text record parser + pkgRecords Recs(Cache); + if (_error->PendingError() == true) { + return false; + } + + // Lock the archive directory + FileFd Lock; + if (_config->FindB("Debug::NoLocking", false) == false) { + Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock")); + if (_error->PendingError() == true) { + return _error->Error("Unable to lock the download directory"); + } + } + + // Create the download object + AcqPackageKitStatus Stat(this, m_backend, _cancel); + + // get a fetcher + pkgAcquire fetcher; + fetcher.Setup(&Stat); + + // Create the package manager and prepare to download + // SPtr<pkgPackageManager> PM= _system->CreatePM(Cache); + SPtr<pkgPackageManager> PM = new pkgDebDPkgPM(Cache); + if (PM->GetArchives(&fetcher, packageSourceList, &Recs) == false || + _error->PendingError() == true) { + return false; + } + + // Generate the list of affected packages + for (pkgCache::PkgIterator pkg = Cache->PkgBegin(); pkg.end() == false; ++pkg) { + // Ignore no-version packages + if (pkg->VersionList == 0) { + continue; + } + + // Not interesting + if ((Cache[pkg].Keep() == true || + Cache[pkg].InstVerIter(Cache) == pkg.CurrentVer()) && + pkg.State() == pkgCache::PkgIterator::NeedsNothing && + (Cache[pkg].iFlags & pkgDepCache::ReInstall) != pkgDepCache::ReInstall && + (pkg.Purge() != false || Cache[pkg].Mode != pkgDepCache::ModeDelete || + (Cache[pkg].iFlags & pkgDepCache::Purge) != pkgDepCache::Purge)) { + continue; + } + + pkgCache::VerIterator ver = Cache[pkg].InstVerIter(Cache); + if (ver.end() && (ver = find_candidate_ver(pkg))) { + // Ignore invalid versions + continue; + } + + // Append it to the list + Stat.addPackagePair(PkgPair(pkg, ver)); + } + + // Display statistics + double FetchBytes = fetcher.FetchNeeded(); + double FetchPBytes = fetcher.PartialPresent(); + double DebBytes = fetcher.TotalNeeded(); + if (DebBytes != Cache->DebSize()) { + cout << DebBytes << ',' << Cache->DebSize() << endl; + cout << "How odd.. The sizes didn't match, email apt@packages.debian.org"; + /* _error->Warning("How odd.. The sizes didn't match, email apt@packages.debian.org");*/ + } + + // Number of bytes + // if (DebBytes != FetchBytes) + // ioprintf(c1out, "Need to get %sB/%sB of archives.\n", + // SizeToStr(FetchBytes).c_str(),SizeToStr(DebBytes).c_str()); + // else if (DebBytes != 0) + // ioprintf(c1out, "Need to get %sB of archives.\n", + // SizeToStr(DebBytes).c_str()); + + // Size delta + // if (Cache->UsrSize() >= 0) + // ioprintf(c1out, "After this operation, %sB of additional disk space will be used.\n", + // SizeToStr(Cache->UsrSize()).c_str()); + // else + // ioprintf(c1out, "After this operation, %sB disk space will be freed.\n", + // SizeToStr(-1*Cache->UsrSize()).c_str()); + + if (_error->PendingError() == true) { + cout << "PendingError " << endl; + return false; + } + + /* Check for enough free space */ + struct statvfs Buf; + string OutputDir = _config->FindDir("Dir::Cache::Archives"); + if (statvfs(OutputDir.c_str(),&Buf) != 0) { + return _error->Errno("statvfs", + "Couldn't determine free space in %s", + OutputDir.c_str()); + } + if (unsigned(Buf.f_bfree) < (FetchBytes - FetchPBytes)/Buf.f_bsize) { + struct statfs Stat; + if (statfs(OutputDir.c_str(), &Stat) != 0 || + unsigned(Stat.f_type) != RAMFS_MAGIC) { + pk_backend_error_code(m_backend, + PK_ERROR_ENUM_NO_SPACE_ON_DEVICE, + string("You don't have enough free space in ").append(OutputDir).c_str()); + return _error->Error("You don't have enough free space in %s.", + OutputDir.c_str()); + } + } + + if (!checkTrusted(fetcher, m_backend)) { + return false; + } + + pk_backend_set_status (m_backend, PK_STATUS_ENUM_DOWNLOAD); + pk_backend_set_simultaneous_mode(m_backend, true); + // Download and check if we can continue + if (fetcher.Run() != pkgAcquire::Continue + && _cancel == false) { + // We failed and we did not cancel + show_errors(m_backend, PK_ERROR_ENUM_PACKAGE_DOWNLOAD_FAILED); + return false; + } + pk_backend_set_simultaneous_mode(m_backend, false); + + if (_error->PendingError() == true) { + cout << "PendingError download" << endl; + return false; + } + + // Right now it's not safe to cancel + pk_backend_set_allow_cancel (m_backend, false); + // TODO true or false? + if (_cancel) { + return true; + } + + // Download should be finished by now, changing it's status + pk_backend_set_status (m_backend, PK_STATUS_ENUM_RUNNING); + pk_backend_set_percentage(m_backend, PK_BACKEND_PERCENTAGE_INVALID); + pk_backend_set_sub_percentage(m_backend, PK_BACKEND_PERCENTAGE_INVALID); + + // TODO DBus activated does not have all vars + // we could try to see if this is the case + setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 1); + _system->UnLock(); + + if (!m_localDebFile.empty()) { + // add the local file name to be proccessed by the PM queue + pkgDebDPkgPM *pm = static_cast<pkgDebDPkgPM*>(&*PM); + pm->addDebFile(m_localDebFile); + } + + pkgPackageManager::OrderResult res; + res = PM->DoInstallPreFork(); + if (res == pkgPackageManager::Failed) { + g_warning ("Failed to prepare installation"); + show_errors(m_backend, PK_ERROR_ENUM_PACKAGE_DOWNLOAD_FAILED); + return false; + } + + // File descriptors for reading dpkg --status-fd + int readFromChildFD[2]; + if (pipe(readFromChildFD) < 0) { + cout << "Failed to create a pipe" << endl; + return false; + } + + int pty_master; + m_child_pid = forkpty(&pty_master, NULL, NULL, NULL); + if (m_child_pid == -1) { + return false; + } + + if (m_child_pid == 0) { + //cout << "FORKED: installPackages(): DoInstall" << endl; + + // close pipe we don't need + close(readFromChildFD[0]); + + // Change the locale to not get libapt localization + setlocale(LC_ALL, "C"); + + // Debconf handlying + gchar *socket; + if (socket = pk_backend_get_frontend_socket(m_backend)) { + setenv("DEBIAN_FRONTEND", "passthrough", 1); + setenv("DEBCONF_PIPE", socket, 1); + } else { + // we don't have a socket set, let's fallback to noninteractive + setenv("DEBIAN_FRONTEND", "noninteractive", 1); + } + + gchar *locale; + // Set the LANGUAGE so debconf messages get localization + if (locale = pk_backend_get_locale(m_backend)) { + setenv("LANGUAGE", locale, 1); + setenv("LANG", locale, 1); + //setenv("LANG", "C", 1); + } + + // Pass the write end of the pipe to the install function + res = PM->DoInstallPostFork(readFromChildFD[1]); + + // dump errors into cerr (pass it to the parent process) + _error->DumpErrors(); + + close(readFromChildFD[1]); + + return res == 0; + } + + cout << "PARENT proccess running..." << endl; + // make it nonblocking, verry important otherwise + // when the child finish we stay stuck. + fcntl(readFromChildFD[0], F_SETFL, O_NONBLOCK); + fcntl(pty_master, F_SETFL, O_NONBLOCK); + + // init the timer + m_lastTermAction = time(NULL); + m_startCounting = false; + + // Check if the child died + int ret; + char masterbuf[1024]; + while (waitpid(m_child_pid, &ret, WNOHANG) == 0) { + // TODO: This is dpkg's raw output. Maybe save it for error-solving? + while(read(pty_master, masterbuf, sizeof(masterbuf)) > 0); + updateInterface(readFromChildFD[0], pty_master); + } + + close(readFromChildFD[0]); + close(readFromChildFD[1]); + close(pty_master); + + cout << "Parent finished..." << endl; + return true; +} diff --git a/backends/aptcc/apt-intf.h b/backends/aptcc/apt-intf.h index ea835207..c6c8c563 100644 --- a/backends/aptcc/apt-intf.h +++ b/backends/aptcc/apt-intf.h @@ -37,13 +37,13 @@ using namespace std; /** -* returns a list of packages names -*/ + * returns a list of packages names + */ vector<string> search_files (PkBackend *backend, gchar **values, bool &_cancel); /** -* returns a list of packages names -*/ + * returns a list of packages names + */ vector<string> searchMimeType (PkBackend *backend, gchar **values, bool &error, bool &_cancel); typedef pair<pkgCache::PkgIterator, pkgCache::VerIterator> PkgPair; @@ -55,47 +55,47 @@ class AptIntf { public: - AptIntf(PkBackend *backend, bool &cancel); - ~AptIntf(); - - bool init(); - void cancel(); - - // Check the returned VerIterator.end() - // if it's true we could not find it - pair<pkgCache::PkgIterator, pkgCache::VerIterator> - find_package_id(const gchar *package_id, bool &found); - pkgCache::VerIterator find_ver(const pkgCache::PkgIterator &pkg); - pkgCache::VerIterator find_candidate_ver(const pkgCache::PkgIterator &pkg); - - PkgList resolvePI(gchar **package_ids, PkBitfield filters = PK_FILTER_ENUM_NONE); - bool markFileForInstall(const gchar *file, PkgList &install, PkgList &remove); - - bool markAutoInstalled(pkgCacheFile &cache, PkgList &pkgs, bool flag); - - /** - * runs a transaction to install/remove/update packages - * - for install and update, \p remove should be set to false - * - if you are going to remove, \p remove should be true - * - if you don't want to actually install/update/remove - * \p simulate should be true, in this case packages with - * what's going to happen will be emitted. - */ - bool runTransaction(PkgList &install, PkgList &remove, bool simulate, bool markAuto = false); - - /** - * Get depends - */ - void get_depends(PkgList &output, - pkgCache::PkgIterator pkg, - bool recursive); - - /** - * Get requires - */ - void get_requires(PkgList &output, - pkgCache::PkgIterator pkg, - bool recursive); + AptIntf(PkBackend *backend, bool &cancel); + ~AptIntf(); + + bool init(); + void cancel(); + + // Check the returned VerIterator.end() + // if it's true we could not find it + pair<pkgCache::PkgIterator, pkgCache::VerIterator> + find_package_id(const gchar *package_id, bool &found); + pkgCache::VerIterator find_ver(const pkgCache::PkgIterator &pkg); + pkgCache::VerIterator find_candidate_ver(const pkgCache::PkgIterator &pkg); + + PkgList resolvePI(gchar **package_ids, PkBitfield filters = PK_FILTER_ENUM_NONE); + bool markFileForInstall(const gchar *file, PkgList &install, PkgList &remove); + + bool markAutoInstalled(pkgCacheFile &cache, PkgList &pkgs, bool flag); + + /** + * runs a transaction to install/remove/update packages + * - for install and update, \p remove should be set to false + * - if you are going to remove, \p remove should be true + * - if you don't want to actually install/update/remove + * \p simulate should be true, in this case packages with + * what's going to happen will be emitted. + */ + bool runTransaction(PkgList &install, PkgList &remove, bool simulate, bool markAuto = false); + + /** + * Get depends + */ + void get_depends(PkgList &output, + pkgCache::PkgIterator pkg, + bool recursive); + + /** + * Get requires + */ + void get_requires(PkgList &output, + pkgCache::PkgIterator pkg, + bool recursive); /** * Emits a package if it match the filters @@ -103,98 +103,98 @@ public: void emit_package(const PkgPair &pair, PkBitfield filters = PK_FILTER_ENUM_NONE, PkInfoEnum state = PK_INFO_ENUM_UNKNOWN); - + bool matchPackage(const PkgPair &pair, PkBitfield filters); PkgList filterPackages(PkgList &packages, PkBitfield filters); - void emit_packages(PkgList &output, - PkBitfield filters = PK_FILTER_ENUM_NONE, - PkInfoEnum state = PK_INFO_ENUM_UNKNOWN); - - void emitUpdates(PkgList &output, PkBitfield filters = PK_FILTER_ENUM_NONE); - - /** - * Emits details - */ - void emitDetails(const pkgCache::PkgIterator &pkg, const pkgCache::VerIterator &ver); - void emitDetails(PkgList &pkgs); - - /** - * Emits update detail - */ - void emitUpdateDetails(const pkgCache::PkgIterator &pkg, const pkgCache::VerIterator &ver); - void emitUpdateDetails(PkgList &pkgs); - - /** - * Emits files of packages - */ - void emitFiles(PkBackend *backend, const gchar *pi); - - /** - * Download and install packages - */ - bool installPackages(pkgCacheFile &Cache); - - /** - * Install a DEB file - * - * If you don't want to actually install/update/remove - * \p simulate should be true, in this case packages with - * what's going to happen will be emitted. - */ - bool installFile(const gchar *path, bool simulate); - - /** - * Check which package provides the codec - */ - void providesCodec(PkgList &output, gchar **values); - - /** - * Check which package provides a shared library - */ - void providesLibrary(PkgList &output, gchar **values); - - pkgRecords *packageRecords; - pkgCache *packageCache; - pkgDepCache *packageDepCache; - pkgSourceList *packageSourceList; + void emit_packages(PkgList &output, + PkBitfield filters = PK_FILTER_ENUM_NONE, + PkInfoEnum state = PK_INFO_ENUM_UNKNOWN); + + void emitUpdates(PkgList &output, PkBitfield filters = PK_FILTER_ENUM_NONE); + + /** + * Emits details + */ + void emitDetails(const pkgCache::PkgIterator &pkg, const pkgCache::VerIterator &ver); + void emitDetails(PkgList &pkgs); + + /** + * Emits update detail + */ + void emitUpdateDetails(const pkgCache::PkgIterator &pkg, const pkgCache::VerIterator &ver); + void emitUpdateDetails(PkgList &pkgs); + + /** + * Emits files of packages + */ + void emitFiles(PkBackend *backend, const gchar *pi); + + /** + * Download and install packages + */ + bool installPackages(pkgCacheFile &Cache); + + /** + * Install a DEB file + * + * If you don't want to actually install/update/remove + * \p simulate should be true, in this case packages with + * what's going to happen will be emitted. + */ + bool installFile(const gchar *path, bool simulate); + + /** + * Check which package provides the codec + */ + void providesCodec(PkgList &output, gchar **values); + + /** + * Check which package provides a shared library + */ + void providesLibrary(PkgList &output, gchar **values); + + pkgRecords *packageRecords; + pkgCache *packageCache; + pkgDepCache *packageDepCache; + pkgSourceList *packageSourceList; private: - MMap *Map; - OpProgress Progress; - pkgPolicy *Policy; - PkBackend *m_backend; - bool &_cancel; - - bool TryToInstall(pkgCache::PkgIterator Pkg, - pkgDepCache &Cache, - pkgProblemResolver &Fix, - bool Remove, - bool BrokenFix, - unsigned int &ExpectedInst); - - /** - * interprets dpkg status fd - */ - void updateInterface(int readFd, int writeFd); - bool DoAutomaticRemove(pkgCacheFile &Cache); - void emitChangedPackages(pkgCacheFile &Cache); - bool removingEssentialPackages(pkgCacheFile &Cache); - - bool m_isMultiArch; - PkgList m_pkgs; - string m_localDebFile; - void populateInternalPackages(pkgCacheFile &Cache); - void emitTransactionPackage(string name, PkInfoEnum state); - time_t m_lastTermAction; - string m_lastPackage; - uint m_lastSubProgress; - PkInfoEnum m_state; - bool m_startCounting; - - // when the internal terminal timesout after no activity - int m_terminalTimeout; - pid_t m_child_pid; + MMap *Map; + OpProgress Progress; + pkgPolicy *Policy; + PkBackend *m_backend; + bool &_cancel; + + bool TryToInstall(pkgCache::PkgIterator Pkg, + pkgDepCache &Cache, + pkgProblemResolver &Fix, + bool Remove, + bool BrokenFix, + unsigned int &ExpectedInst); + + /** + * interprets dpkg status fd + */ + void updateInterface(int readFd, int writeFd); + bool DoAutomaticRemove(pkgCacheFile &Cache); + void emitChangedPackages(pkgCacheFile &Cache); + bool removingEssentialPackages(pkgCacheFile &Cache); + + bool m_isMultiArch; + PkgList m_pkgs; + string m_localDebFile; + void populateInternalPackages(pkgCacheFile &Cache); + void emitTransactionPackage(string name, PkInfoEnum state); + time_t m_lastTermAction; + string m_lastPackage; + uint m_lastSubProgress; + PkInfoEnum m_state; + bool m_startCounting; + + // when the internal terminal timesout after no activity + int m_terminalTimeout; + pid_t m_child_pid; }; #endif diff --git a/backends/aptcc/apt-messages.cpp b/backends/aptcc/apt-messages.cpp index 623100c7..33638573 100644 --- a/backends/aptcc/apt-messages.cpp +++ b/backends/aptcc/apt-messages.cpp @@ -30,173 +30,169 @@ using namespace std; bool show_errors(PkBackend *backend, PkErrorEnum errorCode) { - stringstream errors; - - string Err; - while (_error->empty() == false) - { - bool Type = _error->PopMessage(Err); - if (Type == true) { - errors << "E: " << Err << endl; - } else { - errors << "W: " << Err << endl; - } - } - - if (!errors.str().empty()) - { - pk_backend_error_code(backend, errorCode, errors.str().c_str()); - } + stringstream errors; + + string Err; + while (_error->empty() == false) { + bool Type = _error->PopMessage(Err); + if (Type == true) { + errors << "E: " << Err << endl; + } else { + errors << "W: " << Err << endl; + } + } + + if (!errors.str().empty()) { + pk_backend_error_code(backend, errorCode, errors.str().c_str()); + } } bool show_warnings(PkBackend *backend, PkMessageEnum message) { - stringstream warnings; - - string Err; - while (_error->empty() == false) - { - bool Type = _error->PopMessage(Err); - if (Type == true) { - warnings << "E: " << Err << endl; - } else { - warnings << "W: " << Err << endl; - } - } - - if (!warnings.str().empty()) - { - pk_backend_message(backend, message, warnings.str().c_str()); - } + stringstream warnings; + + string Err; + while (_error->empty() == false) { + bool Type = _error->PopMessage(Err); + if (Type == true) { + warnings << "E: " << Err << endl; + } else { + warnings << "W: " << Err << endl; + } + } + + if (!warnings.str().empty()) { + pk_backend_message(backend, message, warnings.str().c_str()); + } } /** Shows broken dependencies for a single package */ void show_broken(PkBackend *backend, pkgCacheFile &Cache, bool Now) { - stringstream out; - - out << "The following packages have unmet dependencies:" << endl; - for (pkgCache::PkgIterator I = Cache->PkgBegin(); ! I.end(); ++I) { - if (Now == true) { - if (Cache[I].NowBroken() == false) { - continue; - } - } else { - if (Cache[I].InstBroken() == false){ - continue; - } - } - - // Print out each package and the failed dependencies - out << " " << I.Name() << ":"; - unsigned Indent = strlen(I.Name()) + 3; - bool First = true; - pkgCache::VerIterator Ver; - - if (Now == true) { - Ver = I.CurrentVer(); - } else { - Ver = Cache[I].InstVerIter(Cache); - } - - if (Ver.end() == true) { - out << endl; - continue; - } - - for (pkgCache::DepIterator D = Ver.DependsList(); D.end() == false;) { - // Compute a single dependency element (glob or) - pkgCache::DepIterator Start; - pkgCache::DepIterator End; - D.GlobOr(Start,End); // advances D - - if (Cache->IsImportantDep(End) == false){ - continue; - } - - if (Now == true) { - if ((Cache[End] & pkgDepCache::DepGNow) == pkgDepCache::DepGNow){ - continue; - } - } else { - if ((Cache[End] & pkgDepCache::DepGInstall) == pkgDepCache::DepGInstall) { - continue; - } - } - - bool FirstOr = true; - while (1) { - if (First == false){ - for (unsigned J = 0; J != Indent; J++) { - out << ' '; - } - } - First = false; - - if (FirstOr == false) { - for (unsigned J = 0; J != strlen(End.DepType()) + 3; J++) { - out << ' '; - } - } else { - out << ' ' << End.DepType() << ": "; - } - FirstOr = false; - - out << Start.TargetPkg().Name(); - - // Show a quick summary of the version requirements - if (Start.TargetVer() != 0) { - out << " (" << Start.CompType() << " " << Start.TargetVer() << ")"; - } - - /* Show a summary of the target package if possible. In the case - of virtual packages we show nothing */ - pkgCache::PkgIterator Targ = Start.TargetPkg(); - if (Targ->ProvidesList == 0) { - out << ' '; - pkgCache::VerIterator Ver = Cache[Targ].InstVerIter(Cache); - if (Now == true) { - Ver = Targ.CurrentVer(); - } - - if (Ver.end() == false) - { - char buffer[1024]; - if (Now == true) { - sprintf(buffer, "but %s is installed", Ver.VerStr()); - } else { - sprintf(buffer, "but %s is to be installed", Ver.VerStr()); - } - - out << buffer; - } else { - if (Cache[Targ].CandidateVerIter(Cache).end() == true) { - if (Targ->ProvidesList == 0) { - out << "but it is not installable"; - } else { - out << "but it is a virtual package"; - } - } else { - if (Now) { - out << "but it is not installed"; - } else { - out << "but it is not going to be installed"; - } - } - } - } - - if (Start != End) { - out << " or"; - } - out << endl; - - if (Start == End){ - break; - } - Start++; - } - } - } - pk_backend_error_code (backend, PK_ERROR_ENUM_DEP_RESOLUTION_FAILED, out.str().c_str()); + stringstream out; + + out << "The following packages have unmet dependencies:" << endl; + for (pkgCache::PkgIterator I = Cache->PkgBegin(); ! I.end(); ++I) { + if (Now == true) { + if (Cache[I].NowBroken() == false) { + continue; + } + } else { + if (Cache[I].InstBroken() == false){ + continue; + } + } + + // Print out each package and the failed dependencies + out << " " << I.Name() << ":"; + unsigned Indent = strlen(I.Name()) + 3; + bool First = true; + pkgCache::VerIterator Ver; + + if (Now == true) { + Ver = I.CurrentVer(); + } else { + Ver = Cache[I].InstVerIter(Cache); + } + + if (Ver.end() == true) { + out << endl; + continue; + } + + for (pkgCache::DepIterator D = Ver.DependsList(); D.end() == false;) { + // Compute a single dependency element (glob or) + pkgCache::DepIterator Start; + pkgCache::DepIterator End; + D.GlobOr(Start,End); // advances D + + if (Cache->IsImportantDep(End) == false){ + continue; + } + + if (Now == true) { + if ((Cache[End] & pkgDepCache::DepGNow) == pkgDepCache::DepGNow){ + continue; + } + } else { + if ((Cache[End] & pkgDepCache::DepGInstall) == pkgDepCache::DepGInstall) { + continue; + } + } + + bool FirstOr = true; + while (1) { + if (First == false){ + for (unsigned J = 0; J != Indent; J++) { + out << ' '; + } + } + First = false; + + if (FirstOr == false) { + for (unsigned J = 0; J != strlen(End.DepType()) + 3; J++) { + out << ' '; + } + } else { + out << ' ' << End.DepType() << ": "; + } + FirstOr = false; + + out << Start.TargetPkg().Name(); + + // Show a quick summary of the version requirements + if (Start.TargetVer() != 0) { + out << " (" << Start.CompType() << " " << Start.TargetVer() << ")"; + } + + /* Show a summary of the target package if possible. In the case + of virtual packages we show nothing */ + pkgCache::PkgIterator Targ = Start.TargetPkg(); + if (Targ->ProvidesList == 0) { + out << ' '; + pkgCache::VerIterator Ver = Cache[Targ].InstVerIter(Cache); + if (Now == true) { + Ver = Targ.CurrentVer(); + } + + if (Ver.end() == false) + { + char buffer[1024]; + if (Now == true) { + sprintf(buffer, "but %s is installed", Ver.VerStr()); + } else { + sprintf(buffer, "but %s is to be installed", Ver.VerStr()); + } + + out << buffer; + } else { + if (Cache[Targ].CandidateVerIter(Cache).end() == true) { + if (Targ->ProvidesList == 0) { + out << "but it is not installable"; + } else { + out << "but it is a virtual package"; + } + } else { + if (Now) { + out << "but it is not installed"; + } else { + out << "but it is not going to be installed"; + } + } + } + } + + if (Start != End) { + out << " or"; + } + out << endl; + + if (Start == End){ + break; + } + Start++; + } + } + } + pk_backend_error_code (backend, PK_ERROR_ENUM_DEP_RESOLUTION_FAILED, out.str().c_str()); } diff --git a/backends/aptcc/apt-messages.h b/backends/aptcc/apt-messages.h index 68267d78..95666f3f 100644 --- a/backends/aptcc/apt-messages.h +++ b/backends/aptcc/apt-messages.h @@ -33,13 +33,13 @@ * Call the Packagekit error dialog */ bool show_errors(PkBackend *backend, - PkErrorEnum errorCode = PK_ERROR_ENUM_UNKNOWN); + PkErrorEnum errorCode = PK_ERROR_ENUM_UNKNOWN); /** * Call the Packagekit message dialog */ bool show_warnings(PkBackend *backend, - PkMessageEnum message = PK_MESSAGE_ENUM_UNKNOWN); + PkMessageEnum message = PK_MESSAGE_ENUM_UNKNOWN); /** Shows a list of all broken packages together with their * dependencies. Similar to and based on the equivalent routine in diff --git a/backends/aptcc/apt-sourceslist.cpp b/backends/aptcc/apt-sourceslist.cpp index 06e0a743..a984493c 100644 --- a/backends/aptcc/apt-sourceslist.cpp +++ b/backends/aptcc/apt-sourceslist.cpp @@ -41,525 +41,568 @@ SourcesList::~SourcesList() { - for (list<SourceRecord *>::iterator it = SourceRecords.begin(); - it != SourceRecords.end(); it++) - delete *it; - for (list<VendorRecord *>::iterator it = VendorRecords.begin(); - it != VendorRecords.end(); it++) - delete *it; + for (list<SourceRecord *>::iterator it = SourceRecords.begin(); + it != SourceRecords.end(); ++it) { + delete *it; + } + + for (list<VendorRecord *>::iterator it = VendorRecords.begin(); + it != VendorRecords.end(); ++it) { + delete *it; + } } SourcesList::SourceRecord *SourcesList::AddSourceNode(SourceRecord &rec) { - SourceRecord *newrec = new SourceRecord; - *newrec = rec; - SourceRecords.push_back(newrec); + SourceRecord *newrec = new SourceRecord; + *newrec = rec; + SourceRecords.push_back(newrec); - return newrec; + return newrec; } bool SourcesList::ReadSourcePart(string listpath) { - //cout << "SourcesList::ReadSourcePart() "<< listpath << endl; - char buf[512]; - const char *p; - ifstream ifs(listpath.c_str(), ios::in); - bool record_ok = true; - - // cannot open file - if (!ifs != 0) - return _error->Error("Can't read %s", listpath.c_str()); - - while (ifs.eof() == false) { - p = buf; - SourceRecord rec; - string Type; - string Section; - string VURI; - - ifs.getline(buf, sizeof(buf)); - - rec.SourceFile = listpath; - while (isspace(*p)) - p++; - if (*p == '#') { - rec.Type = Disabled; - p++; - while (isspace(*p)) + //cout << "SourcesList::ReadSourcePart() "<< listpath << endl; + char buf[512]; + const char *p; + ifstream ifs(listpath.c_str(), ios::in); + bool record_ok = true; + + // cannot open file + if (!ifs != 0) { + return _error->Error("Can't read %s", listpath.c_str()); + } + + while (ifs.eof() == false) { + p = buf; + SourceRecord rec; + string Type; + string Section; + string VURI; + + ifs.getline(buf, sizeof(buf)); + + rec.SourceFile = listpath; + while (isspace(*p)) { p++; - } - - if (*p == '\r' || *p == '\n' || *p == 0) { - rec.Type = Comment; - rec.Comment = p; - - AddSourceNode(rec); - continue; - } - - bool Failed = true; - if (ParseQuoteWord(p, Type) == true && - rec.SetType(Type) == true && ParseQuoteWord(p, VURI) == true) { - if (VURI[0] == '[') { - rec.VendorID = VURI.substr(1, VURI.length() - 2); - if (ParseQuoteWord(p, VURI) == true && rec.SetURI(VURI) == true) - Failed = false; - } else if (rec.SetURI(VURI) == true) { - Failed = false; - } - if (Failed == false && ParseQuoteWord(p, rec.Dist) == false) - Failed = true; - } - - if (Failed == true) { - if (rec.Type == Disabled) { - // treat as a comment field - rec.Type = Comment; - rec.Comment = buf; - } else { - // syntax error on line + } + + if (*p == '#') { + rec.Type = Disabled; + p++; + while (isspace(*p)) + p++; + } + + if (*p == '\r' || *p == '\n' || *p == 0) { rec.Type = Comment; - string s = "#" + string(buf); - rec.Comment = s; - record_ok = false; - //return _error->Error("Syntax error in line %s", buf); - } - } + rec.Comment = p; + + AddSourceNode(rec); + continue; + } + + bool Failed = true; + if (ParseQuoteWord(p, Type) == true && + rec.SetType(Type) == true && ParseQuoteWord(p, VURI) == true) { + if (VURI[0] == '[') { + rec.VendorID = VURI.substr(1, VURI.length() - 2); + if (ParseQuoteWord(p, VURI) == true && rec.SetURI(VURI) == true) + Failed = false; + } else if (rec.SetURI(VURI) == true) { + Failed = false; + } + if (Failed == false && ParseQuoteWord(p, rec.Dist) == false) + Failed = true; + } + + if (Failed == true) { + if (rec.Type == Disabled) { + // treat as a comment field + rec.Type = Comment; + rec.Comment = buf; + } else { + // syntax error on line + rec.Type = Comment; + string s = "#" + string(buf); + rec.Comment = s; + record_ok = false; + //return _error->Error("Syntax error in line %s", buf); + } + } #ifndef HAVE_RPM - // check for absolute dist - if (rec.Dist.empty() == false && rec.Dist[rec.Dist.size() - 1] == '/') { - // make sure there's no section - if (ParseQuoteWord(p, Section) == true) - return _error->Error("Syntax error in line %s", buf); - - rec.Dist = SubstVar(rec.Dist, "$(ARCH)", - _config->Find("APT::Architecture")); - - AddSourceNode(rec); - continue; - } + // check for absolute dist + if (rec.Dist.empty() == false && rec.Dist[rec.Dist.size() - 1] == '/') { + // make sure there's no section + if (ParseQuoteWord(p, Section) == true) + return _error->Error("Syntax error in line %s", buf); + + rec.Dist = SubstVar(rec.Dist, "$(ARCH)", + _config->Find("APT::Architecture")); + + AddSourceNode(rec); + continue; + } #endif - const char *tmp = p; - rec.NumSections = 0; - while (ParseQuoteWord(p, Section) == true) - rec.NumSections++; - if (rec.NumSections > 0) { - p = tmp; - rec.Sections = new string[rec.NumSections]; - rec.NumSections = 0; - while (ParseQuoteWord(p, Section) == true) { - // comments inside the record are preserved - if (Section[0] == '#') { - SourceRecord rec; - string s = Section + string(p); - rec.Type = Comment; - rec.Comment = s; - rec.SourceFile = listpath; - AddSourceNode(rec); - break; - } else { - rec.Sections[rec.NumSections++] = Section; + const char *tmp = p; + rec.NumSections = 0; + while (ParseQuoteWord(p, Section) == true) + rec.NumSections++; + if (rec.NumSections > 0) { + p = tmp; + rec.Sections = new string[rec.NumSections]; + rec.NumSections = 0; + while (ParseQuoteWord(p, Section) == true) { + // comments inside the record are preserved + if (Section[0] == '#') { + SourceRecord rec; + string s = Section + string(p); + rec.Type = Comment; + rec.Comment = s; + rec.SourceFile = listpath; + AddSourceNode(rec); + break; + } else { + rec.Sections[rec.NumSections++] = Section; + } } - } - } - AddSourceNode(rec); - } + } + AddSourceNode(rec); + } - ifs.close(); - return record_ok; + ifs.close(); + return record_ok; } bool SourcesList::ReadSourceDir(string Dir) { - //cout << "SourcesList::ReadSourceDir() " << Dir << endl; - - DIR *D = opendir(Dir.c_str()); - if (D == 0) - return _error->Errno("opendir", "Unable to read %s", Dir.c_str()); - - vector<string> List; - for (struct dirent * Ent = readdir(D); Ent != 0; Ent = readdir(D)) { - if (Ent->d_name[0] == '.') - continue; - - // Skip bad file names ala run-parts - const char *C = Ent->d_name; - for (; *C != 0; C++) - if (isalpha(*C) == 0 && isdigit(*C) == 0 - && *C != '_' && *C != '-' && *C != '.') - break; - if (*C != 0) - continue; - - // Only look at files ending in .list to skip .rpmnew etc files - if (strcmp(Ent->d_name + strlen(Ent->d_name) - 5, ".list") != 0) - continue; - - // Make sure it is a file and not something else - string File = flCombine(Dir, Ent->d_name); - struct stat St; - if (stat(File.c_str(), &St) != 0 || S_ISREG(St.st_mode) == 0) - continue; - List.push_back(File); - - } - closedir(D); - - sort(List.begin(), List.end()); - - // Read the files - for (vector<string>::const_iterator I = List.begin(); I != List.end(); - I++) - if (ReadSourcePart(*I) == false) - return false; - return true; + //cout << "SourcesList::ReadSourceDir() " << Dir << endl; + + DIR *D = opendir(Dir.c_str()); + if (D == 0) { + return _error->Errno("opendir", "Unable to read %s", Dir.c_str()); + } + + vector<string> List; + for (struct dirent * Ent = readdir(D); Ent != 0; Ent = readdir(D)) { + if (Ent->d_name[0] == '.') { + continue; + } + + // Skip bad file names ala run-parts + const char *C = Ent->d_name; + for (; *C != 0; C++) { + if (isalpha(*C) == 0 && isdigit(*C) == 0 + && *C != '_' && *C != '-' && *C != '.') { + break; + } + } + if (*C != 0) { + continue; + } + + // Only look at files ending in .list to skip .rpmnew etc files + if (strcmp(Ent->d_name + strlen(Ent->d_name) - 5, ".list") != 0) { + continue; + } + + // Make sure it is a file and not something else + string File = flCombine(Dir, Ent->d_name); + struct stat St; + if (stat(File.c_str(), &St) != 0 || S_ISREG(St.st_mode) == 0) { + continue; + } + List.push_back(File); + + } + closedir(D); + + sort(List.begin(), List.end()); + + // Read the files + for (vector<string>::const_iterator I = List.begin(); I != List.end(); ++I) { + if (ReadSourcePart(*I) == false) { + return false; + } + } + return true; } bool SourcesList::ReadSources() { - //cout << "SourcesList::ReadSources() " << endl; + //cout << "SourcesList::ReadSources() " << endl; - bool Res = true; + bool Res = true; - string Parts = _config->FindDir("Dir::Etc::sourceparts"); - if (FileExists(Parts) == true) - Res &= ReadSourceDir(Parts); - string Main = _config->FindFile("Dir::Etc::sourcelist"); - if (FileExists(Main) == true) - Res &= ReadSourcePart(Main); + string Parts = _config->FindDir("Dir::Etc::sourceparts"); + if (FileExists(Parts) == true) { + Res &= ReadSourceDir(Parts); + } - return Res; + string Main = _config->FindFile("Dir::Etc::sourcelist"); + if (FileExists(Main) == true) { + Res &= ReadSourcePart(Main); + } + + return Res; } SourcesList::SourceRecord *SourcesList::AddEmptySource() { - SourceRecord rec; + SourceRecord rec; #ifdef HAVE_RPM - rec.Type = Rpm; + rec.Type = Rpm; #else - rec.Type = Deb; + rec.Type = Deb; #endif - rec.VendorID = ""; - rec.SourceFile = _config->FindFile("Dir::Etc::sourcelist"); - rec.Dist = ""; - rec.NumSections = 0; - return AddSourceNode(rec); + rec.VendorID = ""; + rec.SourceFile = _config->FindFile("Dir::Etc::sourcelist"); + rec.Dist = ""; + rec.NumSections = 0; + return AddSourceNode(rec); } SourcesList::SourceRecord *SourcesList::AddSource(RecType Type, - string VendorID, string URI, - string Dist, - string *Sections, - unsigned short count, - string SourceFile) + string VendorID, string URI, + string Dist, + string *Sections, + unsigned short count, + string SourceFile) { - SourceRecord rec; - rec.Type = Type; - rec.VendorID = VendorID; - rec.SourceFile = SourceFile; - - if (rec.SetURI(URI) == false) { - return NULL; - } - rec.Dist = Dist; - rec.NumSections = count; - rec.Sections = new string[count]; - for (unsigned int i = 0; i < count; i++) - rec.Sections[i] = Sections[i]; - - return AddSourceNode(rec); + SourceRecord rec; + rec.Type = Type; + rec.VendorID = VendorID; + rec.SourceFile = SourceFile; + + if (rec.SetURI(URI) == false) { + return NULL; + } + rec.Dist = Dist; + rec.NumSections = count; + rec.Sections = new string[count]; + for (unsigned int i = 0; i < count; ++i) { + rec.Sections[i] = Sections[i]; + } + + return AddSourceNode(rec); } void SourcesList::RemoveSource(SourceRecord *&rec) { - SourceRecords.remove(rec); - delete rec; - rec = 0; + SourceRecords.remove(rec); + delete rec; + rec = 0; } void SourcesList::SwapSources( SourceRecord *&rec_one, SourceRecord *&rec_two ) { - list<SourceRecord *>::iterator rec_p; - list<SourceRecord *>::iterator rec_n; + list<SourceRecord *>::iterator rec_p; + list<SourceRecord *>::iterator rec_n; - rec_p = find( SourceRecords.begin(), SourceRecords.end(), rec_one ); - rec_n = find( SourceRecords.begin(), SourceRecords.end(), rec_two ); + rec_p = find( SourceRecords.begin(), SourceRecords.end(), rec_one ); + rec_n = find( SourceRecords.begin(), SourceRecords.end(), rec_two ); - SourceRecords.insert( rec_p, rec_two ); - SourceRecords.erase( rec_n ); + SourceRecords.insert( rec_p, rec_two ); + SourceRecords.erase( rec_n ); } bool SourcesList::UpdateSources() { - list<string> filenames; - for (list<SourceRecord *>::iterator it = SourceRecords.begin(); - it != SourceRecords.end(); it++) { - if ((*it)->SourceFile == "") - continue; - filenames.push_front((*it)->SourceFile); - } - filenames.sort(); - filenames.unique(); - - for (list<string>::iterator fi = filenames.begin(); - fi != filenames.end(); fi++) { - ofstream ofs((*fi).c_str(), ios::out); - if (!ofs != 0) - return false; - - for (list<SourceRecord *>::iterator it = SourceRecords.begin(); - it != SourceRecords.end(); it++) { - if ((*fi) != (*it)->SourceFile) - continue; - string S; - if (((*it)->Type & Comment) != 0) { - S = (*it)->Comment; - } else if ((*it)->URI.empty() || (*it)->Dist.empty()) { + list<string> filenames; + for (list<SourceRecord *>::iterator it = SourceRecords.begin(); + it != SourceRecords.end(); ++it) { + if ((*it)->SourceFile == "") { continue; - } else { - if (((*it)->Type & Disabled) != 0) - S = "# "; - - S += (*it)->GetType() + " "; - - if ((*it)->VendorID.empty() == false) - S += "[" + (*it)->VendorID + "] "; - - S += (*it)->URI + " "; - S += (*it)->Dist + " "; - - for (unsigned int J = 0; J < (*it)->NumSections; J++) - S += (*it)->Sections[J] + " "; - } - ofs << S << endl; - } - ofs.close(); - } - return true; + } + filenames.push_front((*it)->SourceFile); + } + filenames.sort(); + filenames.unique(); + + for (list<string>::iterator fi = filenames.begin(); + fi != filenames.end(); fi++) { + ofstream ofs((*fi).c_str(), ios::out); + if (!ofs != 0) { + return false; + } + + for (list<SourceRecord *>::iterator it = SourceRecords.begin(); + it != SourceRecords.end(); it++) { + if ((*fi) != (*it)->SourceFile) { + continue; + } + + string S; + if (((*it)->Type & Comment) != 0) { + S = (*it)->Comment; + } else if ((*it)->URI.empty() || (*it)->Dist.empty()) { + continue; + } else { + if (((*it)->Type & Disabled) != 0) + S = "# "; + + S += (*it)->GetType() + " "; + + if ((*it)->VendorID.empty() == false) + S += "[" + (*it)->VendorID + "] "; + + S += (*it)->URI + " "; + S += (*it)->Dist + " "; + + for (unsigned int J = 0; J < (*it)->NumSections; ++J) { + S += (*it)->Sections[J] + " "; + } + } + ofs << S << endl; + } + ofs.close(); + } + return true; } bool SourcesList::SourceRecord::SetType(string S) { - if (S == "deb") - Type |= Deb; - else if (S == "deb-src") - Type |= DebSrc; - else if (S == "rpm") - Type |= Rpm; - else if (S == "rpm-src") - Type |= RpmSrc; - else if (S == "rpm-dir") - Type |= RpmDir; - else if (S == "rpm-src-dir") - Type |= RpmSrcDir; - else if (S == "repomd") - Type |= Repomd; - else if (S == "repomd-src") - Type |= RepomdSrc; - else - return false; - //cout << S << " settype " << (Type | Repomd) << endl; - return true; + if (S == "deb") { + Type |= Deb; + } else if (S == "deb-src") { + Type |= DebSrc; + } else if (S == "rpm") { + Type |= Rpm; + } else if (S == "rpm-src") { + Type |= RpmSrc; + } else if (S == "rpm-dir") { + Type |= RpmDir; + } else if (S == "rpm-src-dir") { + Type |= RpmSrcDir; + } else if (S == "repomd") { + Type |= Repomd; + } else if (S == "repomd-src") { + Type |= RepomdSrc; + } else { + return false; + } + + //cout << S << " settype " << (Type | Repomd) << endl; + return true; } string SourcesList::SourceRecord::GetType() { - if ((Type & Deb) != 0) - return "deb"; - else if ((Type & DebSrc) != 0) - return "deb-src"; - else if ((Type & Rpm) != 0) - return "rpm"; - else if ((Type & RpmSrc) != 0) - return "rpm-src"; - else if ((Type & RpmDir) != 0) - return "rpm-dir"; - else if ((Type & RpmSrcDir) != 0) - return "rpm-src-dir"; - else if ((Type & Repomd) != 0) - return "repomd"; - else if ((Type & RepomdSrc) != 0) - return "repomd-src"; - //cout << "type " << (Type & Repomd) << endl; - return "unknown"; + if ((Type & Deb) != 0) { + return "deb"; + } else if ((Type & DebSrc) != 0) { + return "deb-src"; + } else if ((Type & Rpm) != 0) { + return "rpm"; + } else if ((Type & RpmSrc) != 0) { + return "rpm-src"; + } else if ((Type & RpmDir) != 0) { + return "rpm-dir"; + } else if ((Type & RpmSrcDir) != 0) { + return "rpm-src-dir"; + } else if ((Type & Repomd) != 0) { + return "repomd"; + } else if ((Type & RepomdSrc) != 0) { + return "repomd-src"; + } + + //cout << "type " << (Type & Repomd) << endl; + return "unknown"; } bool SourcesList::SourceRecord::SetURI(string S) { - if (S.empty() == true) - return false; - if (S.find(':') == string::npos) - return false; - - S = SubstVar(S, "$(ARCH)", _config->Find("APT::Architecture")); - S = SubstVar(S, "$(VERSION)", _config->Find("APT::DistroVersion")); - URI = S; - - // append a / to the end if one is not already there - if (URI[URI.size() - 1] != '/') - URI += '/'; - - return true; + if (S.empty() == true) { + return false; + } + if (S.find(':') == string::npos) { + return false; + } + + S = SubstVar(S, "$(ARCH)", _config->Find("APT::Architecture")); + S = SubstVar(S, "$(VERSION)", _config->Find("APT::DistroVersion")); + URI = S; + + // append a / to the end if one is not already there + if (URI[URI.size() - 1] != '/') { + URI += '/'; + } + + return true; } -SourcesList::SourceRecord &SourcesList::SourceRecord:: -operator=(const SourceRecord &rhs) +SourcesList::SourceRecord &SourcesList::SourceRecord::operator=(const SourceRecord &rhs) { - // Needed for a proper deep copy of the record; uses the string operator= to properly copy the strings - Type = rhs.Type; - VendorID = rhs.VendorID; - URI = rhs.URI; - Dist = rhs.Dist; - Sections = new string[rhs.NumSections]; - for (unsigned int I = 0; I < rhs.NumSections; I++) - Sections[I] = rhs.Sections[I]; - NumSections = rhs.NumSections; - Comment = rhs.Comment; - SourceFile = rhs.SourceFile; - - return *this; + // Needed for a proper deep copy of the record; uses the string operator= to properly copy the strings + Type = rhs.Type; + VendorID = rhs.VendorID; + URI = rhs.URI; + Dist = rhs.Dist; + Sections = new string[rhs.NumSections]; + for (unsigned int I = 0; I < rhs.NumSections; ++I) { + Sections[I] = rhs.Sections[I]; + } + NumSections = rhs.NumSections; + Comment = rhs.Comment; + SourceFile = rhs.SourceFile; + + return *this; } SourcesList::VendorRecord *SourcesList::AddVendorNode(VendorRecord &rec) { - VendorRecord *newrec = new VendorRecord; - *newrec = rec; - VendorRecords.push_back(newrec); + VendorRecord *newrec = new VendorRecord; + *newrec = rec; + VendorRecords.push_back(newrec); - return newrec; + return newrec; } bool SourcesList::ReadVendors() { - Configuration Cnf; - - string CnfFile = _config->FindFile("Dir::Etc::vendorlist"); - if (FileExists(CnfFile) == true) - if (ReadConfigFile(Cnf, CnfFile, true) == false) - return false; - - for (list<VendorRecord *>::const_iterator I = VendorRecords.begin(); - I != VendorRecords.end(); I++) - delete *I; - VendorRecords.clear(); - - // Process 'simple-key' type sections - const Configuration::Item *Top = Cnf.Tree("simple-key"); - for (Top = (Top == 0 ? 0 : Top->Child); Top != 0; Top = Top->Next) { - Configuration Block(Top); - VendorRecord Vendor; - - Vendor.VendorID = Top->Tag; - Vendor.FingerPrint = Block.Find("Fingerprint"); - Vendor.Description = Block.Find("Name"); - - char *buffer = new char[Vendor.FingerPrint.length() + 1]; - char *p = buffer;; - for (string::const_iterator I = Vendor.FingerPrint.begin(); - I != Vendor.FingerPrint.end(); I++) { - if (*I != ' ' && *I != '\t') - *p++ = *I; - } - *p = 0; - Vendor.FingerPrint = buffer; - delete[]buffer; - - if (Vendor.FingerPrint.empty() == true || - Vendor.Description.empty() == true) { - _error->Error("Vendor block %s is invalid", - Vendor.VendorID.c_str()); - continue; - } - - AddVendorNode(Vendor); - } - - return !_error->PendingError(); + Configuration Cnf; + + string CnfFile = _config->FindFile("Dir::Etc::vendorlist"); + if (FileExists(CnfFile) == true) { + if (ReadConfigFile(Cnf, CnfFile, true) == false) { + return false; + } + } + + for (list<VendorRecord *>::const_iterator I = VendorRecords.begin(); + I != VendorRecords.end(); ++I) { + delete *I; + } + VendorRecords.clear(); + + // Process 'simple-key' type sections + const Configuration::Item *Top = Cnf.Tree("simple-key"); + for (Top = (Top == 0 ? 0 : Top->Child); Top != 0; Top = Top->Next) { + Configuration Block(Top); + VendorRecord Vendor; + + Vendor.VendorID = Top->Tag; + Vendor.FingerPrint = Block.Find("Fingerprint"); + Vendor.Description = Block.Find("Name"); + + char *buffer = new char[Vendor.FingerPrint.length() + 1]; + char *p = buffer;; + for (string::const_iterator I = Vendor.FingerPrint.begin(); + I != Vendor.FingerPrint.end(); ++I) { + if (*I != ' ' && *I != '\t') { + *p++ = *I; + } + } + *p = 0; + Vendor.FingerPrint = buffer; + delete[]buffer; + + if (Vendor.FingerPrint.empty() == true || + Vendor.Description.empty() == true) { + _error->Error("Vendor block %s is invalid", + Vendor.VendorID.c_str()); + continue; + } + + AddVendorNode(Vendor); + } + + return !_error->PendingError(); } SourcesList::VendorRecord *SourcesList::AddVendor(string VendorID, string FingerPrint, string Description) { - VendorRecord rec; - rec.VendorID = VendorID; - rec.FingerPrint = FingerPrint; - rec.Description = Description; - return AddVendorNode(rec); + VendorRecord rec; + rec.VendorID = VendorID; + rec.FingerPrint = FingerPrint; + rec.Description = Description; + return AddVendorNode(rec); } bool SourcesList::UpdateVendors() { - ofstream ofs(_config->FindFile("Dir::Etc::vendorlist").c_str(), ios::out); - if (!ofs != 0) - return false; - - for (list<VendorRecord *>::iterator it = VendorRecords.begin(); - it != VendorRecords.end(); it++) { - ofs << "simple-key \"" << (*it)->VendorID << "\" {" << endl; - ofs << "\tFingerPrint \"" << (*it)->FingerPrint << "\";" << endl; - ofs << "\tName \"" << (*it)->Description << "\";" << endl; - ofs << "}" << endl; - } - - ofs.close(); - return true; + ofstream ofs(_config->FindFile("Dir::Etc::vendorlist").c_str(), ios::out); + if (!ofs != 0) { + return false; + } + + for (list<VendorRecord *>::iterator it = VendorRecords.begin(); + it != VendorRecords.end(); ++it) { + ofs << "simple-key \"" << (*it)->VendorID << "\" {" << endl; + ofs << "\tFingerPrint \"" << (*it)->FingerPrint << "\";" << endl; + ofs << "\tName \"" << (*it)->Description << "\";" << endl; + ofs << "}" << endl; + } + + ofs.close(); + return true; } void SourcesList::RemoveVendor(VendorRecord *&rec) { - VendorRecords.remove(rec); - delete rec; - rec = 0; + VendorRecords.remove(rec); + delete rec; + rec = 0; } ostream &operator<<(ostream &os, const SourcesList::SourceRecord &rec) { - os << "Type: "; - if ((rec.Type & SourcesList::Comment) != 0) - os << "Comment "; - if ((rec.Type & SourcesList::Disabled) != 0) - os << "Disabled "; - if ((rec.Type & SourcesList::Deb) != 0) - os << "Deb"; - if ((rec.Type & SourcesList::DebSrc) != 0) - os << "DebSrc"; - if ((rec.Type & SourcesList::Rpm) != 0) - os << "Rpm"; - if ((rec.Type & SourcesList::RpmSrc) != 0) - os << "RpmSrc"; - if ((rec.Type & SourcesList::RpmDir) != 0) - os << "RpmDir"; - if ((rec.Type & SourcesList::RpmSrcDir) != 0) - os << "RpmSrcDir"; - if ((rec.Type & SourcesList::Repomd) != 0) - os << "Repomd"; - if ((rec.Type & SourcesList::RepomdSrc) != 0) - os << "RepomdSrc"; - os << endl; - os << "SourceFile: " << rec.SourceFile << endl; - os << "VendorID: " << rec.VendorID << endl; - os << "URI: " << rec.URI << endl; - os << "Dist: " << rec.Dist << endl; - os << "Section(s):" << endl; + os << "Type: "; + if ((rec.Type & SourcesList::Comment) != 0) { + os << "Comment "; + } + if ((rec.Type & SourcesList::Disabled) != 0) { + os << "Disabled "; + } + if ((rec.Type & SourcesList::Deb) != 0) { + os << "Deb"; + } + if ((rec.Type & SourcesList::DebSrc) != 0) { + os << "DebSrc"; + } + if ((rec.Type & SourcesList::Rpm) != 0) { + os << "Rpm"; + } + if ((rec.Type & SourcesList::RpmSrc) != 0) { + os << "RpmSrc"; + } + if ((rec.Type & SourcesList::RpmDir) != 0) { + os << "RpmDir"; + } + if ((rec.Type & SourcesList::RpmSrcDir) != 0) { + os << "RpmSrcDir"; + } + if ((rec.Type & SourcesList::Repomd) != 0) { + os << "Repomd"; + } + if ((rec.Type & SourcesList::RepomdSrc) != 0) { + os << "RepomdSrc"; + } + os << endl; + os << "SourceFile: " << rec.SourceFile << endl; + os << "VendorID: " << rec.VendorID << endl; + os << "URI: " << rec.URI << endl; + os << "Dist: " << rec.Dist << endl; + os << "Section(s):" << endl; #if 0 - for (unsigned int J = 0; J < rec.NumSections; J++) { - cout << "\t" << rec.Sections[J] << endl; - } + for (unsigned int J = 0; J < rec.NumSections; ++J) { + cout << "\t" << rec.Sections[J] << endl; + } #endif - os << endl; - return os; + os << endl; + return os; } ostream &operator<<(ostream &os, const SourcesList::VendorRecord &rec) { - os << "VendorID: " << rec.VendorID << endl; - os << "FingerPrint: " << rec.FingerPrint << endl; - os << "Description: " << rec.Description << endl; - return os; + os << "VendorID: " << rec.VendorID << endl; + os << "FingerPrint: " << rec.FingerPrint << endl; + os << "Description: " << rec.Description << endl; + return os; } - -// vim:sts=4:sw=4 diff --git a/backends/aptcc/apt-sourceslist.h b/backends/aptcc/apt-sourceslist.h index 8b409e5a..f15b60d6 100644 --- a/backends/aptcc/apt-sourceslist.h +++ b/backends/aptcc/apt-sourceslist.h @@ -32,80 +32,79 @@ using namespace std; class SourcesList { - public: - enum RecType { - Deb = 1 << 0, - DebSrc = 1 << 1, - Rpm = 1 << 2, - RpmSrc = 1 << 3, - Disabled = 1 << 4, - Comment = 1 << 5, - RpmDir = 1 << 6, - RpmSrcDir = 1 << 7, - Repomd = 1 << 8, - RepomdSrc = 1 << 9 - }; - - struct SourceRecord { - unsigned int Type; - string VendorID; - string URI; - string Dist; - string *Sections; - unsigned short NumSections; - string Comment; - string SourceFile; - - bool SetType(string); - string GetType(); - bool SetURI(string); - - SourceRecord():Type(0), Sections(0), NumSections(0) { - }; - ~SourceRecord() { - if (Sections) - delete[]Sections; - }; - SourceRecord &operator=(const SourceRecord &); - }; - - struct VendorRecord { - string VendorID; - string FingerPrint; - string Description; - }; - - list<SourceRecord *> SourceRecords; - list<VendorRecord *> VendorRecords; - - private: - SourceRecord *AddSourceNode(SourceRecord &); - VendorRecord *AddVendorNode(VendorRecord &); - - public: - SourceRecord *AddSource(RecType Type, - string VendorID, - string URI, - string Dist, - string *Sections, - unsigned short count, string SourceFile); - SourceRecord *AddEmptySource(); - void RemoveSource(SourceRecord *&); - void SwapSources( SourceRecord *&, SourceRecord *& ); - bool ReadSourcePart(string listpath); - bool ReadSourceDir(string Dir); - bool ReadSources(); - bool UpdateSources(); - - VendorRecord *AddVendor(string VendorID, - string FingerPrint, string Description); - void RemoveVendor(VendorRecord *&); - bool ReadVendors(); - bool UpdateVendors(); - - SourcesList() { - }; - ~SourcesList(); +public: + enum RecType { + Deb = 1 << 0, + DebSrc = 1 << 1, + Rpm = 1 << 2, + RpmSrc = 1 << 3, + Disabled = 1 << 4, + Comment = 1 << 5, + RpmDir = 1 << 6, + RpmSrcDir = 1 << 7, + Repomd = 1 << 8, + RepomdSrc = 1 << 9 + }; + + struct SourceRecord { + unsigned int Type; + string VendorID; + string URI; + string Dist; + string *Sections; + unsigned short NumSections; + string Comment; + string SourceFile; + + bool SetType(string); + string GetType(); + bool SetURI(string); + + SourceRecord():Type(0), Sections(0), NumSections(0) {} + ~SourceRecord() { + if (Sections) { + delete [] Sections; + } + } + SourceRecord &operator=(const SourceRecord &); + }; + + struct VendorRecord { + string VendorID; + string FingerPrint; + string Description; + }; + + list<SourceRecord *> SourceRecords; + list<VendorRecord *> VendorRecords; + +private: + SourceRecord *AddSourceNode(SourceRecord &); + VendorRecord *AddVendorNode(VendorRecord &); + +public: + SourceRecord *AddSource(RecType Type, + string VendorID, + string URI, + string Dist, + string *Sections, + unsigned short count, string SourceFile); + SourceRecord *AddEmptySource(); + void RemoveSource(SourceRecord *&); + void SwapSources( SourceRecord *&, SourceRecord *& ); + bool ReadSourcePart(string listpath); + bool ReadSourceDir(string Dir); + bool ReadSources(); + bool UpdateSources(); + + VendorRecord *AddVendor(string VendorID, + string FingerPrint, string Description); + void RemoveVendor(VendorRecord *&); + bool ReadVendors(); + bool UpdateVendors(); + + SourcesList() {} + ~SourcesList(); }; typedef list<SourcesList::SourceRecord *>::iterator SourcesListIter; diff --git a/backends/aptcc/apt-utils.cpp b/backends/aptcc/apt-utils.cpp index 953ee680..2cc4ffb1 100644 --- a/backends/aptcc/apt-utils.cpp +++ b/backends/aptcc/apt-utils.cpp @@ -27,216 +27,215 @@ static string debParser(string descr); string get_default_short_description(const pkgCache::VerIterator &ver, - pkgRecords *records) + pkgRecords *records) { - if(ver.end() || ver.FileList().end() || records == NULL) { - return string(); - } + if(ver.end() || ver.FileList().end() || records == NULL) { + return string(); + } - pkgCache::VerFileIterator vf = ver.FileList(); + pkgCache::VerFileIterator vf = ver.FileList(); - if (vf.end()) { - return string(); - } else { - return records->Lookup(vf).ShortDesc(); - } + if (vf.end()) { + return string(); + } else { + return records->Lookup(vf).ShortDesc(); + } } string get_short_description(const pkgCache::VerIterator &ver, - pkgRecords *records) + pkgRecords *records) { - if (ver.end() || ver.FileList().end() || records == NULL) { - return string(); - } + if (ver.end() || ver.FileList().end() || records == NULL) { + return string(); + } - pkgCache::DescIterator d = ver.TranslatedDescription(); + pkgCache::DescIterator d = ver.TranslatedDescription(); - if (d.end()) { - return string(); - } + if (d.end()) { + return string(); + } - pkgCache::DescFileIterator df = d.FileList(); + pkgCache::DescFileIterator df = d.FileList(); - if (df.end()) { - return string(); - } else { - return records->Lookup(df).ShortDesc(); - } + if (df.end()) { + return string(); + } else { + return records->Lookup(df).ShortDesc(); + } } string get_long_description(const pkgCache::VerIterator &ver, - pkgRecords *records) + pkgRecords *records) { - if (ver.end() || ver.FileList().end() || records == NULL) { - return string(); - } + if (ver.end() || ver.FileList().end() || records == NULL) { + return string(); + } - pkgCache::DescIterator d = ver.TranslatedDescription(); + pkgCache::DescIterator d = ver.TranslatedDescription(); - if (d.end()) { - return string(); - } + if (d.end()) { + return string(); + } - pkgCache::DescFileIterator df = d.FileList(); + pkgCache::DescFileIterator df = d.FileList(); - if (df.end()) { - return string(); - } else { - return records->Lookup(df).LongDesc(); - } + if (df.end()) { + return string(); + } else { + return records->Lookup(df).LongDesc(); + } } string get_long_description_parsed(const pkgCache::VerIterator &ver, - pkgRecords *records) + pkgRecords *records) { - return debParser(get_long_description(ver, records)); + return debParser(get_long_description(ver, records)); } string get_default_long_description(const pkgCache::VerIterator &ver, - pkgRecords *records) + pkgRecords *records) { - if(ver.end() || ver.FileList().end() || records == NULL) { - return string(); - } + if(ver.end() || ver.FileList().end() || records == NULL) { + return string(); + } - pkgCache::VerFileIterator vf = ver.FileList(); + pkgCache::VerFileIterator vf = ver.FileList(); - if (vf.end()) { - return string(); - } else { - return records->Lookup(vf).LongDesc(); - } + if (vf.end()) { + return string(); + } else { + return records->Lookup(vf).LongDesc(); + } } static string debParser(string descr) { - // Policy page on package descriptions - // http://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-Description - unsigned int i; - string::size_type nlpos=0; - - nlpos = descr.find('\n'); - // delete first line - if (nlpos != string::npos) { - descr.erase(0, nlpos + 2); // del "\n " too - } - - // avoid replacing '\n' for a ' ' after a '.\n' is found - bool removedFullStop = false; - while (nlpos < descr.length()) { - // find the new line position - nlpos = descr.find('\n', nlpos); - if (nlpos == string::npos) { - // if it could not find the new line - // get out of the loop - break; - } - - i = nlpos; - // erase the char after '\n' which is always " " - descr.erase(++i, 1); - - // remove lines likes this: " .", making it a \n - if (descr[i] == '.') { - descr.erase(i, 1); - nlpos = i; - // don't permit the next round to replace a '\n' to a ' ' - removedFullStop = true; - continue; - } else if (descr[i] != ' ' && removedFullStop == false) { - // it's not a line to be verbatim displayed - // So it's a paragraph let's replace '\n' with a ' ' - // replace new line with " " - descr.replace(nlpos, 1, " "); - } - - removedFullStop = false; - nlpos++; - } - - return descr; + // Policy page on package descriptions + // http://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-Description + unsigned int i; + string::size_type nlpos=0; + + nlpos = descr.find('\n'); + // delete first line + if (nlpos != string::npos) { + descr.erase(0, nlpos + 2); // del "\n " too + } + + // avoid replacing '\n' for a ' ' after a '.\n' is found + bool removedFullStop = false; + while (nlpos < descr.length()) { + // find the new line position + nlpos = descr.find('\n', nlpos); + if (nlpos == string::npos) { + // if it could not find the new line + // get out of the loop + break; + } + + i = nlpos; + // erase the char after '\n' which is always " " + descr.erase(++i, 1); + + // remove lines likes this: " .", making it a \n + if (descr[i] == '.') { + descr.erase(i, 1); + nlpos = i; + // don't permit the next round to replace a '\n' to a ' ' + removedFullStop = true; + continue; + } else if (descr[i] != ' ' && removedFullStop == false) { + // it's not a line to be verbatim displayed + // So it's a paragraph let's replace '\n' with a ' ' + // replace new line with " " + descr.replace(nlpos, 1, " "); + } + + removedFullStop = false; + nlpos++; + } + + return descr; } -PkGroupEnum -get_enum_group (string group) +PkGroupEnum get_enum_group(string group) { - if (group.compare ("admin") == 0) { - return PK_GROUP_ENUM_ADMIN_TOOLS; - } else if (group.compare ("base") == 0) { - return PK_GROUP_ENUM_SYSTEM; - } else if (group.compare ("comm") == 0) { - return PK_GROUP_ENUM_COMMUNICATION; - } else if (group.compare ("devel") == 0) { - return PK_GROUP_ENUM_PROGRAMMING; - } else if (group.compare ("doc") == 0) { - return PK_GROUP_ENUM_DOCUMENTATION; - } else if (group.compare ("editors") == 0) { - return PK_GROUP_ENUM_PUBLISHING; - } else if (group.compare ("electronics") == 0) { - return PK_GROUP_ENUM_ELECTRONICS; - } else if (group.compare ("embedded") == 0) { - return PK_GROUP_ENUM_SYSTEM; - } else if (group.compare ("fonts") == 0) { - return PK_GROUP_ENUM_FONTS; - } else if (group.compare ("games") == 0) { - return PK_GROUP_ENUM_GAMES; - } else if (group.compare ("gnome") == 0) { - return PK_GROUP_ENUM_DESKTOP_GNOME; - } else if (group.compare ("graphics") == 0) { - return PK_GROUP_ENUM_GRAPHICS; - } else if (group.compare ("hamradio") == 0) { - return PK_GROUP_ENUM_COMMUNICATION; - } else if (group.compare ("interpreters") == 0) { - return PK_GROUP_ENUM_PROGRAMMING; - } else if (group.compare ("kde") == 0) { - return PK_GROUP_ENUM_DESKTOP_KDE; - } else if (group.compare ("libdevel") == 0) { - return PK_GROUP_ENUM_PROGRAMMING; - } else if (group.compare ("libs") == 0) { - return PK_GROUP_ENUM_SYSTEM; - } else if (group.compare ("mail") == 0) { - return PK_GROUP_ENUM_INTERNET; - } else if (group.compare ("math") == 0) { - return PK_GROUP_ENUM_SCIENCE; - } else if (group.compare ("misc") == 0) { - return PK_GROUP_ENUM_OTHER; - } else if (group.compare ("net") == 0) { - return PK_GROUP_ENUM_NETWORK; - } else if (group.compare ("news") == 0) { - return PK_GROUP_ENUM_INTERNET; - } else if (group.compare ("oldlibs") == 0) { - return PK_GROUP_ENUM_LEGACY; - } else if (group.compare ("otherosfs") == 0) { - return PK_GROUP_ENUM_SYSTEM; - } else if (group.compare ("perl") == 0) { - return PK_GROUP_ENUM_PROGRAMMING; - } else if (group.compare ("python") == 0) { - return PK_GROUP_ENUM_PROGRAMMING; - } else if (group.compare ("science") == 0) { - return PK_GROUP_ENUM_SCIENCE; - } else if (group.compare ("shells") == 0) { - return PK_GROUP_ENUM_SYSTEM; - } else if (group.compare ("sound") == 0) { - return PK_GROUP_ENUM_MULTIMEDIA; - } else if (group.compare ("tex") == 0) { - return PK_GROUP_ENUM_PUBLISHING; - } else if (group.compare ("text") == 0) { - return PK_GROUP_ENUM_PUBLISHING; - } else if (group.compare ("utils") == 0) { - return PK_GROUP_ENUM_ACCESSORIES; - } else if (group.compare ("web") == 0) { - return PK_GROUP_ENUM_INTERNET; - } else if (group.compare ("x11") == 0) { - return PK_GROUP_ENUM_DESKTOP_OTHER; - } else if (group.compare ("alien") == 0) { - return PK_GROUP_ENUM_UNKNOWN;//FIXME alien is an unknown group? - } else if (group.compare ("translations") == 0) { - return PK_GROUP_ENUM_LOCALIZATION; - } else if (group.compare ("metapackages") == 0) { - return PK_GROUP_ENUM_COLLECTIONS; - } else { - return PK_GROUP_ENUM_UNKNOWN; - } + if (group.compare ("admin") == 0) { + return PK_GROUP_ENUM_ADMIN_TOOLS; + } else if (group.compare ("base") == 0) { + return PK_GROUP_ENUM_SYSTEM; + } else if (group.compare ("comm") == 0) { + return PK_GROUP_ENUM_COMMUNICATION; + } else if (group.compare ("devel") == 0) { + return PK_GROUP_ENUM_PROGRAMMING; + } else if (group.compare ("doc") == 0) { + return PK_GROUP_ENUM_DOCUMENTATION; + } else if (group.compare ("editors") == 0) { + return PK_GROUP_ENUM_PUBLISHING; + } else if (group.compare ("electronics") == 0) { + return PK_GROUP_ENUM_ELECTRONICS; + } else if (group.compare ("embedded") == 0) { + return PK_GROUP_ENUM_SYSTEM; + } else if (group.compare ("fonts") == 0) { + return PK_GROUP_ENUM_FONTS; + } else if (group.compare ("games") == 0) { + return PK_GROUP_ENUM_GAMES; + } else if (group.compare ("gnome") == 0) { + return PK_GROUP_ENUM_DESKTOP_GNOME; + } else if (group.compare ("graphics") == 0) { + return PK_GROUP_ENUM_GRAPHICS; + } else if (group.compare ("hamradio") == 0) { + return PK_GROUP_ENUM_COMMUNICATION; + } else if (group.compare ("interpreters") == 0) { + return PK_GROUP_ENUM_PROGRAMMING; + } else if (group.compare ("kde") == 0) { + return PK_GROUP_ENUM_DESKTOP_KDE; + } else if (group.compare ("libdevel") == 0) { + return PK_GROUP_ENUM_PROGRAMMING; + } else if (group.compare ("libs") == 0) { + return PK_GROUP_ENUM_SYSTEM; + } else if (group.compare ("mail") == 0) { + return PK_GROUP_ENUM_INTERNET; + } else if (group.compare ("math") == 0) { + return PK_GROUP_ENUM_SCIENCE; + } else if (group.compare ("misc") == 0) { + return PK_GROUP_ENUM_OTHER; + } else if (group.compare ("net") == 0) { + return PK_GROUP_ENUM_NETWORK; + } else if (group.compare ("news") == 0) { + return PK_GROUP_ENUM_INTERNET; + } else if (group.compare ("oldlibs") == 0) { + return PK_GROUP_ENUM_LEGACY; + } else if (group.compare ("otherosfs") == 0) { + return PK_GROUP_ENUM_SYSTEM; + } else if (group.compare ("perl") == 0) { + return PK_GROUP_ENUM_PROGRAMMING; + } else if (group.compare ("python") == 0) { + return PK_GROUP_ENUM_PROGRAMMING; + } else if (group.compare ("science") == 0) { + return PK_GROUP_ENUM_SCIENCE; + } else if (group.compare ("shells") == 0) { + return PK_GROUP_ENUM_SYSTEM; + } else if (group.compare ("sound") == 0) { + return PK_GROUP_ENUM_MULTIMEDIA; + } else if (group.compare ("tex") == 0) { + return PK_GROUP_ENUM_PUBLISHING; + } else if (group.compare ("text") == 0) { + return PK_GROUP_ENUM_PUBLISHING; + } else if (group.compare ("utils") == 0) { + return PK_GROUP_ENUM_ACCESSORIES; + } else if (group.compare ("web") == 0) { + return PK_GROUP_ENUM_INTERNET; + } else if (group.compare ("x11") == 0) { + return PK_GROUP_ENUM_DESKTOP_OTHER; + } else if (group.compare ("alien") == 0) { + return PK_GROUP_ENUM_UNKNOWN;//FIXME alien is an unknown group? + } else if (group.compare ("translations") == 0) { + return PK_GROUP_ENUM_LOCALIZATION; + } else if (group.compare ("metapackages") == 0) { + return PK_GROUP_ENUM_COLLECTIONS; + } else { + return PK_GROUP_ENUM_UNKNOWN; + } } string getChangelogFile(const string &name, @@ -246,20 +245,20 @@ string getChangelogFile(const string &name, const string &uri, pkgAcquire *fetcher) { - string descr("Changelog for "); - descr += name; + string descr("Changelog for "); + descr += name; - // no need to translate this, the changelog is in english anyway - string filename = "/tmp/aptcc_changelog"; + // no need to translate this, the changelog is in english anyway + string filename = "/tmp/aptcc_changelog"; - new pkgAcqFileSane(fetcher, uri, descr, name, filename); + new pkgAcqFileSane(fetcher, uri, descr, name, filename); - ofstream out(filename.c_str()); - if(fetcher->Run() == pkgAcquire::Failed) { - out << "Failed to download the list of changes. " << endl; - out << "Please check your Internet connection." << endl; - // FIXME: Need to dequeue the item - } else { + ofstream out(filename.c_str()); + if (fetcher->Run() == pkgAcquire::Failed) { + out << "Failed to download the list of changes. " << endl; + out << "Please check your Internet connection." << endl; + // FIXME: Need to dequeue the item + } else { struct stat filestatus; stat(filename.c_str(), &filestatus ); @@ -268,7 +267,7 @@ string getChangelogFile(const string &name, if (origin.compare("Ubuntu") == 0) { out << "The list of changes is not available yet.\n" << endl; out << "Please use http://launchpad.net/ubuntu/+source/"<< srcPkg << - "/" << verstr << "/+changelog" << endl; + "/" << verstr << "/+changelog" << endl; out << "until the changes become available or try again later." << endl; } else { out << "This change is not coming from a source that supports changelogs.\n" << endl; @@ -276,10 +275,10 @@ string getChangelogFile(const string &name, out << "URI was: " << uri << endl; } } - } - out.close(); + } + out.close(); - return filename; + return filename; } string getCVEUrls(const string &changelog) @@ -376,40 +375,41 @@ string getBugzillaUrls(const string &changelog) return ret; } -bool contains(vector<pair<pkgCache::PkgIterator, pkgCache::VerIterator> > packages, - const pkgCache::PkgIterator pkg) +bool contains(PkgList packages, const pkgCache::PkgIterator pkg) { - for(vector<pair<pkgCache::PkgIterator, pkgCache::VerIterator> >::iterator it = packages.begin(); - it != packages.end(); ++it) - { - if (it->first == pkg) { - return true; - } - } - return false; + for (PkgList::iterator it = packages.begin(); it != packages.end(); ++it) { + if (it->first == pkg) { + return true; + } + } + return false; } -bool ends_with (const string &str, const char *end) +bool ends_with(const string &str, const char *end) { - size_t endSize = strlen(end); - return str.size() >= endSize && (memcmp(str.data() + str.size() - endSize, end, endSize) == 0); + size_t endSize = strlen(end); + return str.size() >= endSize && (memcmp(str.data() + str.size() - endSize, end, endSize) == 0); } -bool starts_with (const string &str, const char *start) +bool starts_with(const string &str, const char *start) { - size_t startSize = strlen(start); - return str.size() >= startSize && (strncmp(str.data(), start, startSize) == 0); + size_t startSize = strlen(start); + return str.size() >= startSize && (strncmp(str.data(), start, startSize) == 0); } const char *utf8(const char *str) { - static char *_str = NULL; - if (str == NULL) - return NULL; - if (g_utf8_validate(str, -1, NULL) == true) - return str; - g_free(_str); - _str = NULL; - _str = g_locale_to_utf8(str, -1, NULL, NULL, NULL); - return _str; + static char *_str = NULL; + if (str == NULL) { + return NULL; + } + + if (g_utf8_validate(str, -1, NULL) == true) { + return str; + } + + g_free(_str); + _str = NULL; + _str = g_locale_to_utf8(str, -1, NULL, NULL, NULL); + return _str; } diff --git a/backends/aptcc/apt-utils.h b/backends/aptcc/apt-utils.h index 30b143bd..11abf16b 100644 --- a/backends/aptcc/apt-utils.h +++ b/backends/aptcc/apt-utils.h @@ -28,74 +28,70 @@ #include <set> #include <pk-backend.h> +#include "apt-intf.h" #include "pkg_acqfile.h" -typedef std::vector<pkgCache::PkgIterator> pkgvector; - using namespace std; // compare...uses the candidate version of each package. class compare { public: - compare() {} - - bool operator()(const pair<pkgCache::PkgIterator, pkgCache::VerIterator> &a, - const pair<pkgCache::PkgIterator, pkgCache::VerIterator> &b) - { - int ret = strcmp(a.first.Name(), b.first.Name()); - if (ret == 0) { - return strcmp(a.second.VerStr(), b.second.VerStr()) < 0; - } - return ret < 0; - } + compare() {} + + bool operator()(const PkgPair &a, + const PkgPair &b) { + int ret = strcmp(a.first.Name(), b.first.Name()); + if (ret == 0) { + return strcmp(a.second.VerStr(), b.second.VerStr()) < 0; + } + return ret < 0; + } }; /** \brief operator== for match results. */ class result_equality { public: - result_equality() {} - - bool operator()(const pair<pkgCache::PkgIterator, pkgCache::VerIterator> &a, - const pair<pkgCache::PkgIterator, pkgCache::VerIterator> &b) - { - return strcmp(a.first.Name(), b.first.Name()) == 0 && - strcmp(a.second.VerStr(), b.second.VerStr()) == 0 && - strcmp(a.second.Arch(), b.second.Arch()) == 0; - } + result_equality() {} + + bool operator() (const PkgPair &a, const PkgPair &b) { + return strcmp(a.first.Name(), b.first.Name()) == 0 && + strcmp(a.second.VerStr(), b.second.VerStr()) == 0 && + strcmp(a.second.Arch(), b.second.Arch()) == 0; + } }; /** \return a short description string corresponding to the given * version. */ string get_default_short_description(const pkgCache::VerIterator &ver, - pkgRecords *records); + pkgRecords *records); /** \return a short description string corresponding to the given * version. */ string get_short_description(const pkgCache::VerIterator &ver, - pkgRecords *records); + pkgRecords *records); /** \return a short description string corresponding to the given * version. */ string get_default_long_description(const pkgCache::VerIterator &ver, - pkgRecords *records); + pkgRecords *records); /** \return a short description string corresponding to the given * version. */ string get_long_description(const pkgCache::VerIterator &ver, - pkgRecords *records); + pkgRecords *records); /** \return a short description string corresponding to the given * version. */ string get_long_description_parsed(const pkgCache::VerIterator &ver, - pkgRecords *records); + pkgRecords *records); /** * Return the PkEnumGroup of the give group string. @@ -125,8 +121,7 @@ string getBugzillaUrls(const string &changelog); /** * Return if the given vector contain a package */ -bool contains(vector<pair<pkgCache::PkgIterator, pkgCache::VerIterator> > packages, - const pkgCache::PkgIterator pkg); +bool contains(PkgList packages, const pkgCache::PkgIterator pkg); /** * Return if the given string ends with the other diff --git a/backends/aptcc/deb-file.cpp b/backends/aptcc/deb-file.cpp index 8fa812a6..aebe9746 100644 --- a/backends/aptcc/deb-file.cpp +++ b/backends/aptcc/deb-file.cpp @@ -28,19 +28,19 @@ #include <iostream> -DebFile::DebFile(const std::string &filename) - : m_filePath(filename) +DebFile::DebFile(const std::string &filename) : + m_filePath(filename) { FileFd in(filename, FileFd::ReadOnly); debDebFile deb(in); // Extract control data m_extractor = new debDebFile::MemControlExtract("control"); - if(!m_extractor->Read(deb)) { - m_isValid = false; - return; + if (!m_extractor->Read(deb)) { + m_isValid = false; + return; } else { - m_isValid = true; + m_isValid = true; } m_controlData = m_extractor->Section; @@ -104,56 +104,55 @@ bool DebFile::check() std::cout << architecture() << std::endl; if (architecture().compare("all") != 0 && - architecture().compare(_config->Find("APT::Architecture")) != 0) - { + architecture().compare(_config->Find("APT::Architecture")) != 0) { m_errorMsg = "Wrong architecture "; m_errorMsg.append(architecture()); return false; } -// if not "Architecture" in self._sections: -// self._dbg(1, "ERROR: no architecture field") -// self._failure_string = _("No Architecture field in the package") -// return False -// arch = self._sections["Architecture"] -// if arch != "all" and arch != apt_pkg.config.find("APT::Architecture"): -// self._dbg(1, "ERROR: Wrong architecture dude!") -// self._failure_string = _("Wrong architecture '%s'") % arch -// return False -// -// // check version -// if self.compare_to_version_in_cache() == self.VERSION_OUTDATED: -// if self._cache[self.pkgname].installed: -// // the deb is older than the installed -// self._failure_string = _("A later version is already installed") -// return False -// -// // FIXME: this sort of error handling sux -// self._failure_string = "" -// -// // check conflicts -// if not self.check_conflicts(): -// return False -// -// // check if installing it would break anything on the -// // current system -// if not self.check_breaks_existing_packages(): -// return False -// -// // try to satisfy the dependencies -// if not self._satisfy_depends(self.depends): -// return False -// -// // check for conflicts again (this time with the packages that are -// // makeed for install) -// if not self.check_conflicts(): -// return False -// -// if self._cache._depcache.broken_count > 0: -// self._failure_string = _("Failed to satisfy all dependencies " -// "(broken cache)") -// // clean the cache again -// self._cache.clear() -// return False + // if not "Architecture" in self._sections: + // self._dbg(1, "ERROR: no architecture field") + // self._failure_string = _("No Architecture field in the package") + // return False + // arch = self._sections["Architecture"] + // if arch != "all" and arch != apt_pkg.config.find("APT::Architecture"): + // self._dbg(1, "ERROR: Wrong architecture dude!") + // self._failure_string = _("Wrong architecture '%s'") % arch + // return False + // + // // check version + // if self.compare_to_version_in_cache() == self.VERSION_OUTDATED: + // if self._cache[self.pkgname].installed: + // // the deb is older than the installed + // self._failure_string = _("A later version is already installed") + // return False + // + // // FIXME: this sort of error handling sux + // self._failure_string = "" + // + // // check conflicts + // if not self.check_conflicts(): + // return False + // + // // check if installing it would break anything on the + // // current system + // if not self.check_breaks_existing_packages(): + // return False + // + // // try to satisfy the dependencies + // if not self._satisfy_depends(self.depends): + // return False + // + // // check for conflicts again (this time with the packages that are + // // makeed for install) + // if not self.check_conflicts(): + // return False + // + // if self._cache._depcache.broken_count > 0: + // self._failure_string = _("Failed to satisfy all dependencies " + // "(broken cache)") + // // clean the cache again + // self._cache.clear() + // return False return true; } diff --git a/backends/aptcc/deb-file.h b/backends/aptcc/deb-file.h index bf19bf3a..187c4b68 100644 --- a/backends/aptcc/deb-file.h +++ b/backends/aptcc/deb-file.h @@ -28,30 +28,30 @@ class DebFile { -// typedef int user_tag_reference; + // typedef int user_tag_reference; public: - DebFile(const std::string &filename); - bool isValid() const; + DebFile(const std::string &filename); + bool isValid() const; - std::string filePath() const; - std::string packageName() const; - std::string sourcePackage() const; - std::string version() const; - std::string architecture() const; - std::string summary() const; - std::string description() const; - std::string conflicts() const; + std::string filePath() const; + std::string packageName() const; + std::string sourcePackage() const; + std::string version() const; + std::string architecture() const; + std::string summary() const; + std::string description() const; + std::string conflicts() const; - // THIS should be moved to AptIntf class - bool check(); - std::string errorMsg() const; + // THIS should be moved to AptIntf class + bool check(); + std::string errorMsg() const; private: - std::string m_filePath; - debDebFile::MemControlExtract *m_extractor; - pkgTagSection m_controlData; - std::string m_errorMsg; - bool m_isValid; + std::string m_filePath; + debDebFile::MemControlExtract *m_extractor; + pkgTagSection m_controlData; + std::string m_errorMsg; + bool m_isValid; }; #endif diff --git a/backends/aptcc/gstMatcher.cpp b/backends/aptcc/gstMatcher.cpp index 4dd867cf..43a42d62 100644 --- a/backends/aptcc/gstMatcher.cpp +++ b/backends/aptcc/gstMatcher.cpp @@ -32,17 +32,17 @@ GstMatcher::GstMatcher(gchar **values) // gstreamer0.10(urisource-foobar) // gstreamer0.10(decoder-audio/x-wma)(wmaversion=3) const char *pkreg = "^gstreamer\\([0-9\\.]\\+\\)" - "(\\(encoder\\|decoder\\|urisource\\|urisink\\|element\\)-\\([^)]\\+\\))" - "\\(([^\\(^\\)]*)\\)\\?"; + "(\\(encoder\\|decoder\\|urisource\\|urisink\\|element\\)-\\([^)]\\+\\))" + "\\(([^\\(^\\)]*)\\)\\?"; regex_t pkre; - if(regcomp(&pkre, pkreg, 0) != 0) { + if (regcomp(&pkre, pkreg, 0) != 0) { g_debug("Regex compilation error: ", pkreg); return; } gchar *value; - for (uint i = 0; i < g_strv_length(values); i++) { + for (uint i = 0; i < g_strv_length(values); ++i) { value = values[i]; regmatch_t matches[5]; if (regexec(&pkre, value, 5, matches, 0) != REG_NOMATCH) { @@ -76,10 +76,10 @@ GstMatcher::GstMatcher(gchar **values) } else if (type.compare("element") == 0) { type = "Gstreamer-Elements: "; } -// cout << version << endl; -// cout << type << endl; -// cout << data << endl; -// cout << opt << endl; + // cout << version << endl; + // cout << type << endl; + // cout << data << endl; + // cout << opt << endl; gchar *capsString; if (opt.empty()) { @@ -120,37 +120,36 @@ GstMatcher::~GstMatcher() bool GstMatcher::matches(string record) { for (vector<Match>::iterator i = m_matches.begin(); i != m_matches.end(); ++i) { - // Tries to find "Gstreamer-version: xxx" - if (record.find(i->version) != string::npos) { - size_t found; - found = record.find(i->type); - // Tries to find the type "Gstreamer-Uri-Sinks: " - if (found != string::npos) { - found += i->type.size(); // skips the "Gstreamer-Uri-Sinks: " string - size_t endOfLine; - endOfLine = record.find('\n', found); - - GstCaps *caps; - caps = gst_caps_from_string(record.substr(found, endOfLine - found).c_str()); - if (caps == NULL) { - continue; - } - - // if the record is capable of intersect them we found the package - bool provides = gst_caps_can_intersect(static_cast<GstCaps*>(i->caps), caps); - gst_caps_unref(caps); - - if (provides) { - return true; - } + // Tries to find "Gstreamer-version: xxx" + if (record.find(i->version) != string::npos) { + size_t found; + found = record.find(i->type); + // Tries to find the type "Gstreamer-Uri-Sinks: " + if (found != string::npos) { + found += i->type.size(); // skips the "Gstreamer-Uri-Sinks: " string + size_t endOfLine; + endOfLine = record.find('\n', found); + + GstCaps *caps; + caps = gst_caps_from_string(record.substr(found, endOfLine - found).c_str()); + if (caps == NULL) { + continue; + } + + // if the record is capable of intersect them we found the package + bool provides = gst_caps_can_intersect(static_cast<GstCaps*>(i->caps), caps); + gst_caps_unref(caps); + + if (provides) { + return true; } } } - return false; + } + return false; } bool GstMatcher::hasMatches() const { return !m_matches.empty(); } - diff --git a/backends/aptcc/matcher.cpp b/backends/aptcc/matcher.cpp index 4f88074a..de4c27a9 100644 --- a/backends/aptcc/matcher.cpp +++ b/backends/aptcc/matcher.cpp @@ -24,155 +24,150 @@ #include <stdio.h> #include <iostream> -Matcher::Matcher(const string &matchers) - : m_hasError(false) +Matcher::Matcher(const string &matchers) : + m_hasError(false) { - string::const_iterator start = matchers.begin(); - parse_pattern(start, matchers.end()); - if (m_hasError) { - cerr << "ERROR: " << m_error << endl; - } + string::const_iterator start = matchers.begin(); + parse_pattern(start, matchers.end()); + if (m_hasError) { + cerr << "ERROR: " << m_error << endl; + } } Matcher::~Matcher() { - for (vector<regex_t>::iterator i=m_matches.begin(); - i != m_matches.end(); ++i) - { - regfree(&*i); - } + for (vector<regex_t>::iterator i=m_matches.begin(); + i != m_matches.end(); ++i) { + regfree(&*i); + } } bool do_compile(const string &_pattern, - regex_t &pattern, - int cflags) + regex_t &pattern, + int cflags) { - return !regcomp(&pattern, _pattern.c_str(), cflags); + return !regcomp(&pattern, _pattern.c_str(), cflags); } bool string_matches(const char *s, regex_t &pattern_nogroup) { - return !regexec(&pattern_nogroup, s, 0, NULL, 0); + return !regexec(&pattern_nogroup, s, 0, NULL, 0); } bool Matcher::matches(const string &s) { - int matchesCount = 0; - for (vector<regex_t>::iterator i=m_matches.begin(); - i != m_matches.end(); ++i) - { - if (string_matches(s.c_str(), *i)) { - matchesCount++; - } - } - return m_matches.size() == matchesCount; + int matchesCount = 0; + for (vector<regex_t>::iterator i=m_matches.begin(); + i != m_matches.end(); ++i) { + if (string_matches(s.c_str(), *i)) { + matchesCount++; + } + } + return m_matches.size() == matchesCount; } // This matcher is to be used for files // pass a map so it can remember which patter was alread used bool Matcher::matchesFile(const string &s, map<int, bool> &matchers_used) { - int matchesCount = 0; - for (vector<regex_t>::iterator i = m_matches.begin(); - i != m_matches.end(); ++i) - for (int i = 0; i < m_matches.size(); i++) - { - bool not_used = true; - if (matchers_used.find(i) != matchers_used.end()) { - not_used = true; - } - - if (not_used && string_matches(s.c_str(), m_matches.at(i))) { - matchers_used[i] = true; - } - } - return m_matches.size() == matchers_used.size(); + int matchesCount = 0; + for (vector<regex_t>::iterator i = m_matches.begin(); + i != m_matches.end(); ++i) { + for (int i = 0; i < m_matches.size(); ++i) { + bool not_used = true; + if (matchers_used.find(i) != matchers_used.end()) { + not_used = true; + } + + if (not_used && string_matches(s.c_str(), m_matches.at(i))) { + matchers_used[i] = true; + } + } + } + + return m_matches.size() == matchers_used.size(); } bool Matcher::parse_pattern(string::const_iterator &start, - const std::string::const_iterator &end) + const std::string::const_iterator &end) { - // Just filter blank strings out immediately. - while (start != end && isspace(*start)) { - ++start; - } - - if (start == end) { - return false; - } - - while (start != end && *start != '|' && *start != ')') { - string subString = parse_substr(start, end); - - if (subString.empty()) { - continue; - } - - regex_t pattern_nogroup; - if (do_compile(subString, pattern_nogroup, REG_ICASE|REG_EXTENDED|REG_NOSUB)) { - m_matches.push_back(pattern_nogroup); - } else { - regfree(&pattern_nogroup); - m_error = string("Regex compilation error"); - m_hasError = true; - return false; - } - -// regex_t pattern_group; -// if (do_compile(subString, pattern_group, REG_ICASE|REG_EXTENDED)) { -// m_matches.push_back(pattern_group); -// } else { -// regfree(&pattern_group); -// m_error = string("Regex compilation error"); -// m_hasError = true; -// return false; -// } - } - return true; - + // Just filter blank strings out immediately. + while (start != end && isspace(*start)) { + ++start; + } + + if (start == end) { + return false; + } + + while (start != end && *start != '|' && *start != ')') { + string subString = parse_substr(start, end); + + if (subString.empty()) { + continue; + } + + regex_t pattern_nogroup; + if (do_compile(subString, pattern_nogroup, REG_ICASE|REG_EXTENDED|REG_NOSUB)) { + m_matches.push_back(pattern_nogroup); + } else { + regfree(&pattern_nogroup); + m_error = string("Regex compilation error"); + m_hasError = true; + return false; + } + + // regex_t pattern_group; + // if (do_compile(subString, pattern_group, REG_ICASE|REG_EXTENDED)) { + // m_matches.push_back(pattern_group); + // } else { + // regfree(&pattern_group); + // m_error = string("Regex compilation error"); + // m_hasError = true; + // return false; + // } + } + + return true; } string Matcher::parse_literal_string_tail(string::const_iterator &start, - const string::const_iterator end) + const string::const_iterator end) { - std::string rval; - - while (start != end && *start != '"') - { - if (*start == '\\') - { - ++start; - if (start != end) - { - switch (*start) - { - case 'n': - rval += '\n'; - break; - case 't': - rval += '\t'; - break; - default: - rval += *start; - break; - } - ++start; - } - } else { - rval += *start; - ++start; - } - } - - if (start == end || *start != '"') { - m_error = string("Unterminated literal string after " + rval); - m_hasError = true; - return string(); - } - - ++start; - - return rval; + std::string rval; + + while (start != end && *start != '"') { + if (*start == '\\') { + ++start; + if (start != end) { + switch (*start) { + case 'n': + rval += '\n'; + break; + case 't': + rval += '\t'; + break; + default: + rval += *start; + break; + } + ++start; + } + } else { + rval += *start; + ++start; + } + } + + if (start == end || *start != '"') { + m_error = string("Unterminated literal string after " + rval); + m_hasError = true; + return string(); + } + + ++start; + + return rval; } // Returns a substring up to the first metacharacter, including escaped @@ -180,66 +175,61 @@ string Matcher::parse_literal_string_tail(string::const_iterator &start, // // Advances loc to the first character of 's' following the escaped string. string Matcher::parse_substr(string::const_iterator &start, - const string::const_iterator &end) + const string::const_iterator &end) { - std::string rval; - bool done=false; - - // Strip leading whitespace. - while (start != end && isspace(*start)) - ++start; - - do - { - while (start != end && - *start != '(' && - *start != ')' && - *start != '!' && - *start != '~' && - *start != '|' && - *start != '"' && - !isspace(*start)) - { - rval += *start; - ++start; - } - - if (start != end && *start == '"') - { - ++start; - - rval += parse_literal_string_tail(start, end); - if (m_hasError) { - return string(); - } - } - - // We quit because we ran off the end of the string or saw a - // metacharacter. If the latter case and it was a tilde-escape, - // add the escaped character to the string and continue. - if (start != end && start+1 != end && *start == '~') - { - const char next = *(start+1); - - if (next == '(' || next == ')' || - next == '!' || next == '~' || - next == '|' || next == '"' || - isspace(next)) - { - rval += next; - start += 2; - } else { - done = true; - } - } else { - done = true; - } - } while(!done); - - return rval; + std::string rval; + bool done=false; + + // Strip leading whitespace. + while (start != end && isspace(*start)) + ++start; + + do { + while (start != end && + *start != '(' && + *start != ')' && + *start != '!' && + *start != '~' && + *start != '|' && + *start != '"' && + !isspace(*start)) { + rval += *start; + ++start; + } + + if (start != end && *start == '"') { + ++start; + + rval += parse_literal_string_tail(start, end); + if (m_hasError) { + return string(); + } + } + + // We quit because we ran off the end of the string or saw a + // metacharacter. If the latter case and it was a tilde-escape, + // add the escaped character to the string and continue. + if (start != end && start+1 != end && *start == '~') { + const char next = *(start+1); + + if (next == '(' || next == ')' || + next == '!' || next == '~' || + next == '|' || next == '"' || + isspace(next)) { + rval += next; + start += 2; + } else { + done = true; + } + } else { + done = true; + } + } while(!done); + + return rval; } bool Matcher::hasError() const { - return m_hasError; + return m_hasError; } diff --git a/backends/aptcc/matcher.h b/backends/aptcc/matcher.h index e4d1cb2c..23c97ab0 100644 --- a/backends/aptcc/matcher.h +++ b/backends/aptcc/matcher.h @@ -33,23 +33,23 @@ using namespace std; class Matcher { public: - Matcher(const string &matchers); - ~Matcher(); + Matcher(const string &matchers); + ~Matcher(); - bool matches(const string &s); - bool matchesFile(const string &s, map<int, bool> &matchers_used); - bool hasError() const; + bool matches(const string &s); + bool matchesFile(const string &s, map<int, bool> &matchers_used); + bool hasError() const; private: - bool m_hasError; - string m_error; - bool parse_pattern(string::const_iterator &start, - const std::string::const_iterator &end); - string parse_substr(string::const_iterator &start, - const string::const_iterator &end); - string parse_literal_string_tail(string::const_iterator &start, - const string::const_iterator end); - vector<regex_t> m_matches; + bool m_hasError; + string m_error; + bool parse_pattern(string::const_iterator &start, + const std::string::const_iterator &end); + string parse_substr(string::const_iterator &start, + const string::const_iterator &end); + string parse_literal_string_tail(string::const_iterator &start, + const string::const_iterator end); + vector<regex_t> m_matches; }; #endif diff --git a/backends/aptcc/pk-backend-aptcc.cpp b/backends/aptcc/pk-backend-aptcc.cpp index 1645f107..87f3b34e 100644 --- a/backends/aptcc/pk-backend-aptcc.cpp +++ b/backends/aptcc/pk-backend-aptcc.cpp @@ -44,95 +44,88 @@ static PkBackendSpawn *spawn; /** * pk_backend_get_description: */ -gchar * -pk_backend_get_description (PkBackend *backend) +gchar* pk_backend_get_description(PkBackend *backend) { - return g_strdup ("APTcc"); + return g_strdup ("APTcc"); } /** * pk_backend_get_author: */ -gchar * -pk_backend_get_author (PkBackend *backend) +gchar* pk_backend_get_author(PkBackend *backend) { - return g_strdup ("Daniel Nicoletti <dantti85-pk@yahoo.com.br>"); + return g_strdup ("Daniel Nicoletti <dantti85-pk@yahoo.com.br>"); } /** * pk_backend_initialize: */ -void -pk_backend_initialize (PkBackend *backend) +void pk_backend_initialize(PkBackend *backend) { - g_debug ("APTcc Initializing"); + g_debug ("APTcc Initializing"); - if (pkgInitConfig(*_config) == false || - pkgInitSystem(*_config, _system) == false) - { - g_debug ("ERROR initializing backend"); - } + if (pkgInitConfig(*_config) == false || + pkgInitSystem(*_config, _system) == false) { + g_debug ("ERROR initializing backend"); + } // Disable apt-listbugs as it freezes PK setenv("APT_LISTBUGS_FRONTEND", "none", 1); - spawn = pk_backend_spawn_new (); - pk_backend_spawn_set_name (spawn, "aptcc"); + spawn = pk_backend_spawn_new (); + pk_backend_spawn_set_name (spawn, "aptcc"); } /** * pk_backend_destroy: */ -void -pk_backend_destroy (PkBackend *backend) +void pk_backend_destroy(PkBackend *backend) { - g_debug ("APTcc being destroyed"); + g_debug ("APTcc being destroyed"); } /** * pk_backend_get_groups: */ -PkBitfield -pk_backend_get_groups (PkBackend *backend) +PkBitfield pk_backend_get_groups(PkBackend *backend) { - return pk_bitfield_from_enums ( - PK_GROUP_ENUM_ACCESSORIES, - PK_GROUP_ENUM_ADMIN_TOOLS, - PK_GROUP_ENUM_COMMUNICATION, - PK_GROUP_ENUM_DOCUMENTATION, - PK_GROUP_ENUM_DESKTOP_GNOME, - PK_GROUP_ENUM_DESKTOP_KDE, - PK_GROUP_ENUM_DESKTOP_OTHER, - PK_GROUP_ENUM_ELECTRONICS, - PK_GROUP_ENUM_FONTS, - PK_GROUP_ENUM_GAMES, - PK_GROUP_ENUM_GRAPHICS, - PK_GROUP_ENUM_INTERNET, - PK_GROUP_ENUM_LEGACY, - PK_GROUP_ENUM_LOCALIZATION, - PK_GROUP_ENUM_MULTIMEDIA, - PK_GROUP_ENUM_NETWORK, - PK_GROUP_ENUM_OTHER, - PK_GROUP_ENUM_PROGRAMMING, - PK_GROUP_ENUM_PUBLISHING, - PK_GROUP_ENUM_SCIENCE, - PK_GROUP_ENUM_SYSTEM, - -1); + return pk_bitfield_from_enums ( + PK_GROUP_ENUM_ACCESSORIES, + PK_GROUP_ENUM_ADMIN_TOOLS, + PK_GROUP_ENUM_COMMUNICATION, + PK_GROUP_ENUM_DOCUMENTATION, + PK_GROUP_ENUM_DESKTOP_GNOME, + PK_GROUP_ENUM_DESKTOP_KDE, + PK_GROUP_ENUM_DESKTOP_OTHER, + PK_GROUP_ENUM_ELECTRONICS, + PK_GROUP_ENUM_FONTS, + PK_GROUP_ENUM_GAMES, + PK_GROUP_ENUM_GRAPHICS, + PK_GROUP_ENUM_INTERNET, + PK_GROUP_ENUM_LEGACY, + PK_GROUP_ENUM_LOCALIZATION, + PK_GROUP_ENUM_MULTIMEDIA, + PK_GROUP_ENUM_NETWORK, + PK_GROUP_ENUM_OTHER, + PK_GROUP_ENUM_PROGRAMMING, + PK_GROUP_ENUM_PUBLISHING, + PK_GROUP_ENUM_SCIENCE, + PK_GROUP_ENUM_SYSTEM, + -1); } /** * pk_backend_get_filters: */ -PkBitfield -pk_backend_get_filters (PkBackend *backend) +PkBitfield pk_backend_get_filters(PkBackend *backend) { PkBitfield filters; filters = pk_bitfield_from_enums ( - PK_FILTER_ENUM_GUI, - PK_FILTER_ENUM_INSTALLED, - PK_FILTER_ENUM_DEVELOPMENT, - PK_FILTER_ENUM_FREE, - -1); + PK_FILTER_ENUM_GUI, + PK_FILTER_ENUM_INSTALLED, + PK_FILTER_ENUM_DEVELOPMENT, + PK_FILTER_ENUM_FREE, + -1); // if we have multiArch support we add the native filter if (APT::Configuration::getArchitectures(false).size() > 1) { @@ -145,204 +138,192 @@ pk_backend_get_filters (PkBackend *backend) /** * pk_backend_get_mime_types: */ -gchar * -pk_backend_get_mime_types (PkBackend *backend) +gchar* pk_backend_get_mime_types(PkBackend *backend) { - return g_strdup ("application/x-deb"); + return g_strdup ("application/x-deb"); } /** * pk_backend_cancel: */ -void -pk_backend_cancel (PkBackend *backend) +void pk_backend_cancel(PkBackend *backend) { - AptIntf *m_apt = (AptIntf*) pk_backend_get_pointer(backend, "aptcc_obj"); - if (m_apt) { - m_apt->cancel(); - } + AptIntf *m_apt = (AptIntf*) pk_backend_get_pointer(backend, "aptcc_obj"); + if (m_apt) { + m_apt->cancel(); + } } -static gboolean -backend_get_depends_or_requires_thread (PkBackend *backend) +static gboolean backend_get_depends_or_requires_thread(PkBackend *backend) { - gchar **package_ids; - PkBitfield filters; - gchar *pi; - bool recursive; - - package_ids = pk_backend_get_strv (backend, "package_ids"); - filters = (PkBitfield) pk_backend_get_uint (backend, "filters"); - recursive = pk_backend_get_bool (backend, "recursive"); - - pk_backend_set_allow_cancel (backend, true); - - AptIntf *m_apt = new AptIntf(backend, _cancel); - pk_backend_set_pointer(backend, "aptcc_obj", m_apt); - if (m_apt->init()) { - g_debug ("Failed to create apt cache"); - delete m_apt; - return false; - } - - bool depends = pk_backend_get_bool(backend, "get_depends"); - - pk_backend_set_status (backend, PK_STATUS_ENUM_QUERY); - PkgList output; - for (uint i = 0; i < g_strv_length(package_ids); i++) { - if (_cancel) { - break; - } - pi = package_ids[i]; - if (pk_package_id_check(pi) == false) { - pk_backend_error_code (backend, - PK_ERROR_ENUM_PACKAGE_ID_INVALID, - pi); - delete m_apt; - return false; - } - - PkgPair pkg_ver; + gchar **package_ids; + PkBitfield filters; + gchar *pi; + bool recursive; + + package_ids = pk_backend_get_strv (backend, "package_ids"); + filters = (PkBitfield) pk_backend_get_uint (backend, "filters"); + recursive = pk_backend_get_bool (backend, "recursive"); + + pk_backend_set_allow_cancel (backend, true); + + AptIntf *m_apt = new AptIntf(backend, _cancel); + pk_backend_set_pointer(backend, "aptcc_obj", m_apt); + if (m_apt->init()) { + g_debug ("Failed to create apt cache"); + delete m_apt; + return false; + } + + bool depends = pk_backend_get_bool(backend, "get_depends"); + + pk_backend_set_status (backend, PK_STATUS_ENUM_QUERY); + PkgList output; + for (uint i = 0; i < g_strv_length(package_ids); ++i) { + if (_cancel) { + break; + } + pi = package_ids[i]; + if (pk_package_id_check(pi) == false) { + pk_backend_error_code (backend, + PK_ERROR_ENUM_PACKAGE_ID_INVALID, + pi); + delete m_apt; + return false; + } + + PkgPair pkg_ver; bool found; - pkg_ver = m_apt->find_package_id(pi, found); - if (!found) - { - pk_backend_error_code (backend, - PK_ERROR_ENUM_PACKAGE_NOT_FOUND, - "Couldn't find package"); - delete m_apt; - return false; - } - - if (depends) { - m_apt->get_depends(output, pkg_ver.first, recursive); - } else { - m_apt->get_requires(output, pkg_ver.first, recursive); - } - } - - // It's faster to emmit the packages here than in the matching part - m_apt->emit_packages(output, filters); - - delete m_apt; - return true; + pkg_ver = m_apt->find_package_id(pi, found); + if (!found) { + pk_backend_error_code (backend, + PK_ERROR_ENUM_PACKAGE_NOT_FOUND, + "Couldn't find package"); + delete m_apt; + return false; + } + + if (depends) { + m_apt->get_depends(output, pkg_ver.first, recursive); + } else { + m_apt->get_requires(output, pkg_ver.first, recursive); + } + } + + // It's faster to emmit the packages here than in the matching part + m_apt->emit_packages(output, filters); + + delete m_apt; + return true; } /** * pk_backend_get_depends: */ -void -pk_backend_get_depends (PkBackend *backend, PkBitfield filters, gchar **package_ids, gboolean recursive) +void pk_backend_get_depends(PkBackend *backend, PkBitfield filters, gchar **package_ids, gboolean recursive) { - pk_backend_set_bool (backend, "get_depends", true); - pk_backend_set_bool (backend, "recursive", recursive); - pk_backend_thread_create (backend, backend_get_depends_or_requires_thread); + pk_backend_set_bool (backend, "get_depends", true); + pk_backend_set_bool (backend, "recursive", recursive); + pk_backend_thread_create (backend, backend_get_depends_or_requires_thread); } /** * pk_backend_get_requires: */ -void -pk_backend_get_requires (PkBackend *backend, PkBitfield filters, gchar **package_ids, gboolean recursive) +void pk_backend_get_requires(PkBackend *backend, PkBitfield filters, gchar **package_ids, gboolean recursive) { - pk_backend_set_bool (backend, "get_depends", false); - pk_backend_set_bool (backend, "recursive", recursive); - pk_backend_thread_create (backend, backend_get_depends_or_requires_thread); + pk_backend_set_bool (backend, "get_depends", false); + pk_backend_set_bool (backend, "recursive", recursive); + pk_backend_thread_create (backend, backend_get_depends_or_requires_thread); } /** * pk_backend_get_distro_upgrades: */ -void -pk_backend_get_distro_upgrades (PkBackend *backend) +void pk_backend_get_distro_upgrades(PkBackend *backend) { - pk_backend_spawn_helper (spawn, "get-distro-upgrade.py", "get-distro-upgrades", NULL); + pk_backend_spawn_helper (spawn, "get-distro-upgrade.py", "get-distro-upgrades", NULL); } -static gboolean -backend_get_files_thread (PkBackend *backend) +static gboolean backend_get_files_thread(PkBackend *backend) { - gchar **package_ids; - gchar *pi; - - package_ids = pk_backend_get_strv (backend, "package_ids"); - if (package_ids == NULL) { - pk_backend_error_code (backend, - PK_ERROR_ENUM_PACKAGE_ID_INVALID, - "Invalid package id"); - pk_backend_finished (backend); - return false; - } - - AptIntf *m_apt = new AptIntf(backend, _cancel); - pk_backend_set_pointer(backend, "aptcc_obj", m_apt); - if (m_apt->init()) { - g_debug ("Failed to create apt cache"); - delete m_apt; - return false; - } - - pk_backend_set_status (backend, PK_STATUS_ENUM_QUERY); - for (uint i = 0; i < g_strv_length(package_ids); i++) { - pi = package_ids[i]; - if (pk_package_id_check(pi) == false) { - pk_backend_error_code (backend, - PK_ERROR_ENUM_PACKAGE_ID_INVALID, - pi); - delete m_apt; - return false; - } - - PkgPair pkg_ver; + gchar **package_ids; + gchar *pi; + + package_ids = pk_backend_get_strv (backend, "package_ids"); + if (package_ids == NULL) { + pk_backend_error_code(backend, + PK_ERROR_ENUM_PACKAGE_ID_INVALID, + "Invalid package id"); + pk_backend_finished(backend); + return false; + } + + AptIntf *m_apt = new AptIntf(backend, _cancel); + pk_backend_set_pointer(backend, "aptcc_obj", m_apt); + if (m_apt->init()) { + g_debug ("Failed to create apt cache"); + delete m_apt; + return false; + } + + pk_backend_set_status(backend, PK_STATUS_ENUM_QUERY); + for (uint i = 0; i < g_strv_length(package_ids); ++i) { + pi = package_ids[i]; + if (pk_package_id_check(pi) == false) { + pk_backend_error_code(backend, + PK_ERROR_ENUM_PACKAGE_ID_INVALID, + pi); + delete m_apt; + return false; + } + + PkgPair pkg_ver; bool found; - pkg_ver = m_apt->find_package_id(pi, found); - if (!found) - { - pk_backend_error_code (backend, PK_ERROR_ENUM_PACKAGE_NOT_FOUND, "Couldn't find package"); - delete m_apt; - return false; - } - - m_apt->emitFiles(backend, pi); - } - - delete m_apt; - return true; + pkg_ver = m_apt->find_package_id(pi, found); + if (!found) { + pk_backend_error_code(backend, PK_ERROR_ENUM_PACKAGE_NOT_FOUND, "Couldn't find package"); + delete m_apt; + return false; + } + + m_apt->emitFiles(backend, pi); + } + + delete m_apt; + return true; } /** * pk_backend_get_files: */ -void -pk_backend_get_files (PkBackend *backend, gchar **package_ids) +void pk_backend_get_files(PkBackend *backend, gchar **package_ids) { - pk_backend_thread_create (backend, backend_get_files_thread); + pk_backend_thread_create(backend, backend_get_files_thread); } -static gboolean -backend_get_details_thread (PkBackend *backend) +static gboolean backend_get_details_thread(PkBackend *backend) { - gchar **package_ids; - gchar *pi; + gchar **package_ids; PkRoleEnum role = pk_backend_get_role (backend); - bool updateDetail = role == PK_ROLE_ENUM_GET_UPDATE_DETAIL ? true : false; - package_ids = pk_backend_get_strv (backend, "package_ids"); - if (package_ids == NULL) { - pk_backend_error_code (backend, - PK_ERROR_ENUM_PACKAGE_ID_INVALID, - "Invalid package id"); - pk_backend_finished (backend); - return false; - } - - AptIntf *m_apt = new AptIntf(backend, _cancel); - pk_backend_set_pointer(backend, "aptcc_obj", m_apt); - if (m_apt->init()) { - g_debug ("Failed to create apt cache"); - delete m_apt; - return false; - } + bool updateDetail = role == PK_ROLE_ENUM_GET_UPDATE_DETAIL ? true : false; + package_ids = pk_backend_get_strv (backend, "package_ids"); + if (package_ids == NULL) { + pk_backend_error_code (backend, + PK_ERROR_ENUM_PACKAGE_ID_INVALID, + "Invalid package id"); + pk_backend_finished (backend); + return false; + } + + AptIntf *m_apt = new AptIntf(backend, _cancel); + pk_backend_set_pointer(backend, "aptcc_obj", m_apt); + if (m_apt->init()) { + g_debug ("Failed to create apt cache"); + delete m_apt; + return false; + } if (updateDetail) { // this is needed to compare the changelog verstion to @@ -359,656 +340,627 @@ backend_get_details_thread (PkBackend *backend) m_apt->emitDetails(pkgs); } - delete m_apt; - return true; + delete m_apt; + return true; } /** * pk_backend_get_update_detail: */ -void -pk_backend_get_update_detail (PkBackend *backend, gchar **package_ids) +void pk_backend_get_update_detail(PkBackend *backend, gchar **package_ids) { - pk_backend_thread_create (backend, backend_get_details_thread); + pk_backend_thread_create(backend, backend_get_details_thread); } /** * pk_backend_get_details: */ -void -pk_backend_get_details (PkBackend *backend, gchar **package_ids) +void pk_backend_get_details(PkBackend *backend, gchar **package_ids) { - pk_backend_thread_create (backend, backend_get_details_thread); + pk_backend_thread_create(backend, backend_get_details_thread); } -static gboolean -backend_get_or_update_system_thread (PkBackend *backend) +static gboolean backend_get_or_update_system_thread (PkBackend *backend) { - PkBitfield filters; - bool getUpdates; - filters = (PkBitfield) pk_backend_get_uint (backend, "filters"); - getUpdates = pk_backend_get_bool(backend, "getUpdates"); - pk_backend_set_allow_cancel (backend, true); - - AptIntf *m_apt = new AptIntf(backend, _cancel); - pk_backend_set_pointer(backend, "aptcc_obj", m_apt); - if (m_apt->init()) { - g_debug ("Failed to create apt cache"); - delete m_apt; - return false; - } - - pk_backend_set_status (backend, PK_STATUS_ENUM_QUERY); - - pkgCacheFile Cache; - OpTextProgress Prog(*_config); - int timeout = 10; - // TODO test this - while (Cache.Open(&Prog, !getUpdates) == false) { - // failed to open cache, try checkDeps then.. - // || Cache.CheckDeps(CmdL.FileSize() != 1) == false - if (getUpdates == true || (timeout <= 0)) { - pk_backend_error_code(backend, - PK_ERROR_ENUM_NO_CACHE, - "Could not open package cache."); - return false; - } else { - pk_backend_set_status (backend, PK_STATUS_ENUM_WAITING_FOR_LOCK); - sleep(1); - timeout--; - } - } - pk_backend_set_status (backend, PK_STATUS_ENUM_RUNNING); - - if (pkgDistUpgrade(*Cache) == false) - { - show_broken(backend, Cache, false); - g_debug ("Internal error, DistUpgrade broke stuff"); - delete m_apt; - return false; - } - - bool res = true; - if (getUpdates) { - PkgList update; - PkgList kept; - - for(pkgCache::PkgIterator pkg=m_apt->packageCache->PkgBegin(); - !pkg.end(); - ++pkg) - { - if((*Cache)[pkg].Upgrade() == true && - (*Cache)[pkg].NewInstall() == false) { - update.push_back( - PkgPair(pkg, m_apt->find_candidate_ver(pkg))); - } else if ((*Cache)[pkg].Upgradable() == true && - pkg->CurrentVer != 0 && - (*Cache)[pkg].Delete() == false) { - kept.push_back( - PkgPair(pkg, m_apt->find_candidate_ver(pkg))); - } - } - - m_apt->emitUpdates(update, filters); - m_apt->emit_packages(kept, filters, PK_INFO_ENUM_BLOCKED); - } else { - res = m_apt->installPackages(Cache); - } - - delete m_apt; - return res; + PkBitfield filters; + bool getUpdates; + filters = (PkBitfield) pk_backend_get_uint(backend, "filters"); + getUpdates = pk_backend_get_bool(backend, "getUpdates"); + pk_backend_set_allow_cancel(backend, true); + + AptIntf *m_apt = new AptIntf(backend, _cancel); + pk_backend_set_pointer(backend, "aptcc_obj", m_apt); + if (m_apt->init()) { + g_debug ("Failed to create apt cache"); + delete m_apt; + return false; + } + + pk_backend_set_status(backend, PK_STATUS_ENUM_QUERY); + + pkgCacheFile Cache; + OpTextProgress Prog(*_config); + int timeout = 10; + // TODO test this + while (Cache.Open(&Prog, !getUpdates) == false) { + // failed to open cache, try checkDeps then.. + // || Cache.CheckDeps(CmdL.FileSize() != 1) == false + if (getUpdates == true || (timeout <= 0)) { + pk_backend_error_code(backend, + PK_ERROR_ENUM_NO_CACHE, + "Could not open package cache."); + return false; + } else { + pk_backend_set_status (backend, PK_STATUS_ENUM_WAITING_FOR_LOCK); + sleep(1); + timeout--; + } + } + pk_backend_set_status (backend, PK_STATUS_ENUM_RUNNING); + + if (pkgDistUpgrade(*Cache) == false) { + show_broken(backend, Cache, false); + g_debug ("Internal error, DistUpgrade broke stuff"); + delete m_apt; + return false; + } + + bool res = true; + if (getUpdates) { + PkgList update; + PkgList kept; + + for (pkgCache::PkgIterator pkg = m_apt->packageCache->PkgBegin(); + !pkg.end(); + ++pkg) { + if ((*Cache)[pkg].Upgrade() == true && + (*Cache)[pkg].NewInstall() == false) { + update.push_back(PkgPair(pkg, m_apt->find_candidate_ver(pkg))); + } else if ((*Cache)[pkg].Upgradable() == true && + pkg->CurrentVer != 0 && + (*Cache)[pkg].Delete() == false) { + kept.push_back(PkgPair(pkg, m_apt->find_candidate_ver(pkg))); + } + } + + m_apt->emitUpdates(update, filters); + m_apt->emit_packages(kept, filters, PK_INFO_ENUM_BLOCKED); + } else { + res = m_apt->installPackages(Cache); + } + + delete m_apt; + return res; } /** * pk_backend_get_updates: */ -void -pk_backend_get_updates (PkBackend *backend, PkBitfield filters) +void pk_backend_get_updates(PkBackend *backend, PkBitfield filters) { - pk_backend_set_bool (backend, "getUpdates", true); - pk_backend_thread_create (backend, backend_get_or_update_system_thread); + pk_backend_set_bool(backend, "getUpdates", true); + pk_backend_thread_create(backend, backend_get_or_update_system_thread); } /** * pk_backend_update_system: */ -void -pk_backend_update_system (PkBackend *backend, gboolean only_trusted) +void pk_backend_update_system(PkBackend *backend, gboolean only_trusted) { - pk_backend_set_bool (backend, "getUpdates", false); - pk_backend_thread_create (backend, backend_get_or_update_system_thread); + pk_backend_set_bool(backend, "getUpdates", false); + pk_backend_thread_create(backend, backend_get_or_update_system_thread); } -static gboolean -backend_what_provides_thread (PkBackend *backend) +static gboolean backend_what_provides_thread(PkBackend *backend) { - PkProvidesEnum provides; - PkBitfield filters; - const gchar *provides_text; - gchar **values; - bool error = false; - - filters = (PkBitfield) pk_backend_get_uint (backend, "filters"); - provides = (PkProvidesEnum) pk_backend_get_uint (backend, "provides"); - values = pk_backend_get_strv (backend, "search"); - - pk_backend_set_status (backend, PK_STATUS_ENUM_QUERY); - - // We can handle libraries, mimetypes and codecs - if (provides == PK_PROVIDES_ENUM_SHARED_LIB || - provides == PK_PROVIDES_ENUM_MIMETYPE || - provides == PK_PROVIDES_ENUM_CODEC || - provides == PK_PROVIDES_ENUM_ANY) { - AptIntf *m_apt = new AptIntf(backend, _cancel); - pk_backend_set_pointer(backend, "aptcc_obj", m_apt); - if (m_apt->init()) { - g_debug ("Failed to create apt cache"); - g_strfreev (values); - delete m_apt; - return false; - } - - pk_backend_set_status (backend, PK_STATUS_ENUM_QUERY); - vector<string> packages; - PkgList output; - - if (provides == PK_PROVIDES_ENUM_SHARED_LIB) { - m_apt->providesLibrary (output, values); - } else if (provides == PK_PROVIDES_ENUM_MIMETYPE) { - packages = searchMimeType (backend, values, error, _cancel); - } else if (provides == PK_PROVIDES_ENUM_CODEC) { - m_apt->providesCodec (output, values); - } else { - // PK_PROVIDES_ENUM_ANY, just search for everything a package can provide - m_apt->providesLibrary (output, values); - m_apt->providesCodec (output, values); - packages = searchMimeType (backend, values, error, _cancel); - } - - for (vector<string>::iterator i = packages.begin(); - i != packages.end(); ++i) { - if (_cancel) { - break; - } - pkgCache::PkgIterator pkg = m_apt->packageCache->FindPkg(i->c_str()); - if (pkg.end() == true) { - continue; - } - pkgCache::VerIterator ver = m_apt->find_ver(pkg); - if (ver.end() == true) { - continue; - } - output.push_back(PkgPair(pkg, ver)); - } - - if (error && provides == PK_PROVIDES_ENUM_MIMETYPE) { - // check if app-install-data is installed - pkgCache::PkgIterator pkg; - pkg = m_apt->packageCache->FindPkg("app-install-data"); - if (pkg->CurrentState != pkgCache::State::Installed) { - pk_backend_error_code (backend, - PK_ERROR_ENUM_INTERNAL_ERROR, - "You need the app-install-data " - "package to be able to look for " - "applications that can handle " - "this kind of file"); - } - } else { - // It's faster to emmit the packages here rather than in the matching part - m_apt->emit_packages(output, filters); - } - - delete m_apt; - - } else { - provides_text = pk_provides_enum_to_string (provides); - pk_backend_error_code (backend, - PK_ERROR_ENUM_NOT_SUPPORTED, - "Provides %s not supported", - provides_text); + PkProvidesEnum provides; + PkBitfield filters; + const gchar *provides_text; + gchar **values; + bool error = false; + + filters = (PkBitfield) pk_backend_get_uint(backend, "filters"); + provides = (PkProvidesEnum) pk_backend_get_uint(backend, "provides"); + values = pk_backend_get_strv(backend, "search"); + + pk_backend_set_status(backend, PK_STATUS_ENUM_QUERY); + + // We can handle libraries, mimetypes and codecs + if (provides == PK_PROVIDES_ENUM_SHARED_LIB || + provides == PK_PROVIDES_ENUM_MIMETYPE || + provides == PK_PROVIDES_ENUM_CODEC || + provides == PK_PROVIDES_ENUM_ANY) { + AptIntf *m_apt = new AptIntf(backend, _cancel); + pk_backend_set_pointer(backend, "aptcc_obj", m_apt); + if (m_apt->init()) { + g_debug ("Failed to create apt cache"); + g_strfreev (values); + delete m_apt; + return false; + } + + pk_backend_set_status (backend, PK_STATUS_ENUM_QUERY); + vector<string> packages; + PkgList output; + + if (provides == PK_PROVIDES_ENUM_SHARED_LIB) { + m_apt->providesLibrary (output, values); + } else if (provides == PK_PROVIDES_ENUM_MIMETYPE) { + packages = searchMimeType (backend, values, error, _cancel); + } else if (provides == PK_PROVIDES_ENUM_CODEC) { + m_apt->providesCodec (output, values); + } else { + // PK_PROVIDES_ENUM_ANY, just search for everything a package can provide + m_apt->providesLibrary (output, values); + m_apt->providesCodec (output, values); + packages = searchMimeType (backend, values, error, _cancel); + } + + for (vector<string>::iterator i = packages.begin(); + i != packages.end(); ++i) { + if (_cancel) { + break; + } + pkgCache::PkgIterator pkg = m_apt->packageCache->FindPkg(i->c_str()); + if (pkg.end() == true) { + continue; + } + pkgCache::VerIterator ver = m_apt->find_ver(pkg); + if (ver.end() == true) { + continue; + } + output.push_back(PkgPair(pkg, ver)); + } + + if (error && provides == PK_PROVIDES_ENUM_MIMETYPE) { + // check if app-install-data is installed + pkgCache::PkgIterator pkg; + pkg = m_apt->packageCache->FindPkg("app-install-data"); + if (pkg->CurrentState != pkgCache::State::Installed) { + pk_backend_error_code (backend, + PK_ERROR_ENUM_INTERNAL_ERROR, + "You need the app-install-data " + "package to be able to look for " + "applications that can handle " + "this kind of file"); + } + } else { + // It's faster to emmit the packages here rather than in the matching part + m_apt->emit_packages(output, filters); + } + + delete m_apt; + + } else { + provides_text = pk_provides_enum_to_string (provides); + pk_backend_error_code (backend, + PK_ERROR_ENUM_NOT_SUPPORTED, + "Provides %s not supported", + provides_text); pk_backend_finished (backend); - } + } - return true; + return true; } /** * pk_backend_what_provides */ -void -pk_backend_what_provides (PkBackend *backend, - PkBitfield filters, - PkProvidesEnum provide, - gchar **values) +void pk_backend_what_provides(PkBackend *backend, + PkBitfield filters, + PkProvidesEnum provide, + gchar **values) { - pk_backend_thread_create (backend, backend_what_provides_thread); + pk_backend_thread_create(backend, backend_what_provides_thread); } /** * pk_backend_download_packages_thread: */ -static gboolean -pk_backend_download_packages_thread (PkBackend *backend) +static gboolean pk_backend_download_packages_thread(PkBackend *backend) { - gchar **package_ids; - string directory; - - package_ids = pk_backend_get_strv(backend, "package_ids"); - directory = _config->FindDir("Dir::Cache::archives") + "partial/"; - pk_backend_set_allow_cancel (backend, true); - - AptIntf *m_apt = new AptIntf(backend, _cancel); - pk_backend_set_pointer(backend, "aptcc_obj", m_apt); - if (m_apt->init()) { - g_debug ("Failed to create apt cache"); - delete m_apt; - return false; - } - - pk_backend_set_status (backend, PK_STATUS_ENUM_QUERY); - // Create the progress - AcqPackageKitStatus Stat(m_apt, backend, _cancel); - - // get a fetcher - pkgAcquire fetcher; - fetcher.Setup(&Stat); - string filelist; - gchar *pi; - - // TODO this might be useful when the item is in the cache -// for (pkgAcquire::ItemIterator I = fetcher.ItemsBegin(); I < fetcher.ItemsEnd();) -// { -// if ((*I)->Local == true) -// { -// I++; -// continue; -// } -// -// // Close the item and check if it was found in cache -// (*I)->Finished(); -// if ((*I)->Complete == false) { -// Transient = true; -// } -// -// // Clear it out of the fetch list -// delete *I; -// I = fetcher.ItemsBegin(); -// } - - for (uint i = 0; i < g_strv_length(package_ids); i++) { - pi = package_ids[i]; - if (pk_package_id_check(pi) == false) { - pk_backend_error_code (backend, - PK_ERROR_ENUM_PACKAGE_ID_INVALID, - pi); - delete m_apt; - return false; - } - - if (_cancel) { - break; - } - - PkgPair pkg_ver; + gchar **package_ids; + string directory; + + package_ids = pk_backend_get_strv(backend, "package_ids"); + directory = _config->FindDir("Dir::Cache::archives") + "partial/"; + pk_backend_set_allow_cancel(backend, true); + + AptIntf *m_apt = new AptIntf(backend, _cancel); + pk_backend_set_pointer(backend, "aptcc_obj", m_apt); + if (m_apt->init()) { + g_debug ("Failed to create apt cache"); + delete m_apt; + return false; + } + + pk_backend_set_status (backend, PK_STATUS_ENUM_QUERY); + // Create the progress + AcqPackageKitStatus Stat(m_apt, backend, _cancel); + + // get a fetcher + pkgAcquire fetcher; + fetcher.Setup(&Stat); + string filelist; + gchar *pi; + + // TODO this might be useful when the item is in the cache + // for (pkgAcquire::ItemIterator I = fetcher.ItemsBegin(); I < fetcher.ItemsEnd();) + // { + // if ((*I)->Local == true) + // { + // I++; + // continue; + // } + // + // // Close the item and check if it was found in cache + // (*I)->Finished(); + // if ((*I)->Complete == false) { + // Transient = true; + // } + // + // // Clear it out of the fetch list + // delete *I; + // I = fetcher.ItemsBegin(); + // } + + for (uint i = 0; i < g_strv_length(package_ids); ++i) { + pi = package_ids[i]; + if (pk_package_id_check(pi) == false) { + pk_backend_error_code(backend, + PK_ERROR_ENUM_PACKAGE_ID_INVALID, + pi); + delete m_apt; + return false; + } + + if (_cancel) { + break; + } + + PkgPair pkg_ver; bool found; - pkg_ver = m_apt->find_package_id(pi, found); - // Ignore packages that could not be found or that exist only due to dependencies. - if (!found) - { - _error->Error("Can't find this package id \"%s\".", pi); - continue; - } else { - if(!pkg_ver.second.Downloadable()) { - _error->Error("No downloadable files for %s," - "perhaps it is a local or obsolete" "package?", - pi); - continue; - } - - string storeFileName; - if (get_archive(&fetcher, - m_apt->packageSourceList, - m_apt->packageRecords, - pkg_ver.second, - directory, - storeFileName)) - { - Stat.addPackagePair(pkg_ver); - } - string destFile = directory + "/" + flNotDir(storeFileName); - if (filelist.empty()) { - filelist = destFile; - } else { - filelist.append(";" + destFile); - } - } - } - - if (fetcher.Run() != pkgAcquire::Continue - && _cancel == false) - // We failed and we did not cancel - { - show_errors(backend, PK_ERROR_ENUM_PACKAGE_DOWNLOAD_FAILED); - delete m_apt; - return _cancel; - } - - // send the filelist - pk_backend_files(backend, NULL, filelist.c_str()); - - delete m_apt; - return true; + pkg_ver = m_apt->find_package_id(pi, found); + // Ignore packages that could not be found or that exist only due to dependencies. + if (!found) { + _error->Error("Can't find this package id \"%s\".", pi); + continue; + } else { + if(!pkg_ver.second.Downloadable()) { + _error->Error("No downloadable files for %s," + "perhaps it is a local or obsolete" "package?", + pi); + continue; + } + + string storeFileName; + if (get_archive(&fetcher, + m_apt->packageSourceList, + m_apt->packageRecords, + pkg_ver.second, + directory, + storeFileName)) { + Stat.addPackagePair(pkg_ver); + } + string destFile = directory + "/" + flNotDir(storeFileName); + if (filelist.empty()) { + filelist = destFile; + } else { + filelist.append(";" + destFile); + } + } + } + + if (fetcher.Run() != pkgAcquire::Continue + && _cancel == false) { + // We failed and we did not cancel + show_errors(backend, PK_ERROR_ENUM_PACKAGE_DOWNLOAD_FAILED); + delete m_apt; + return _cancel; + } + + // send the filelist + pk_backend_files(backend, NULL, filelist.c_str()); + + delete m_apt; + return true; } /** * pk_backend_download_packages: */ -void -pk_backend_download_packages (PkBackend *backend, gchar **package_ids, const gchar *directory) +void pk_backend_download_packages(PkBackend *backend, gchar **package_ids, const gchar *directory) { - pk_backend_thread_create (backend, pk_backend_download_packages_thread); + pk_backend_thread_create(backend, pk_backend_download_packages_thread); } /** * pk_backend_refresh_cache_thread: */ -static gboolean -pk_backend_refresh_cache_thread (PkBackend *backend) +static gboolean pk_backend_refresh_cache_thread(PkBackend *backend) { - pk_backend_set_allow_cancel (backend, true); - - AptIntf *m_apt = new AptIntf(backend, _cancel); - pk_backend_set_pointer(backend, "aptcc_obj", m_apt); - if (m_apt->init()) { - g_debug ("Failed to create apt cache"); - delete m_apt; - return false; - } - - pk_backend_set_status (backend, PK_STATUS_ENUM_REFRESH_CACHE); - // Lock the list directory - FileFd Lock; - if (_config->FindB("Debug::NoLocking", false) == false) - { - Lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock")); - if (_error->PendingError() == true) { - pk_backend_error_code (backend, PK_ERROR_ENUM_CANNOT_GET_LOCK, "Unable to lock the list directory"); - delete m_apt; - return false; - // return _error->Error(_("Unable to lock the list directory")); - } - } - // Create the progress - AcqPackageKitStatus Stat(m_apt, backend, _cancel); - - // do the work - ListUpdate(Stat, *m_apt->packageSourceList); - - // Rebuild the cache. - pkgCacheFile Cache; - OpTextProgress Prog(*_config); - if (Cache.BuildCaches(&Prog, true) == false) { - if (_error->PendingError() == true) { - show_errors(backend, PK_ERROR_ENUM_CANNOT_FETCH_SOURCES); - } - delete m_apt; - return false; - } - - // missing gpg signature would appear here - // TODO we need a better enum - if (_error->PendingError() == false && _error->empty() == false) { - //show_warnings(backend, PK_MESSAGE_ENUM_UNTRUSTED_PACKAGE); - //TODO: emit a package with PK_INFO_ENUM_UNTRUSTED - } - - delete m_apt; - return true; + pk_backend_set_allow_cancel(backend, true); + + AptIntf *m_apt = new AptIntf(backend, _cancel); + pk_backend_set_pointer(backend, "aptcc_obj", m_apt); + if (m_apt->init()) { + g_debug ("Failed to create apt cache"); + delete m_apt; + return false; + } + + pk_backend_set_status (backend, PK_STATUS_ENUM_REFRESH_CACHE); + // Lock the list directory + FileFd Lock; + if (_config->FindB("Debug::NoLocking", false) == false) { + Lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock")); + if (_error->PendingError() == true) { + pk_backend_error_code (backend, PK_ERROR_ENUM_CANNOT_GET_LOCK, "Unable to lock the list directory"); + delete m_apt; + return false; + // return _error->Error(_("Unable to lock the list directory")); + } + } + // Create the progress + AcqPackageKitStatus Stat(m_apt, backend, _cancel); + + // do the work + ListUpdate(Stat, *m_apt->packageSourceList); + + // Rebuild the cache. + pkgCacheFile Cache; + OpTextProgress Prog(*_config); + if (Cache.BuildCaches(&Prog, true) == false) { + if (_error->PendingError() == true) { + show_errors(backend, PK_ERROR_ENUM_CANNOT_FETCH_SOURCES); + } + delete m_apt; + return false; + } + + // missing gpg signature would appear here + // TODO we need a better enum + if (_error->PendingError() == false && _error->empty() == false) { + //show_warnings(backend, PK_MESSAGE_ENUM_UNTRUSTED_PACKAGE); + //TODO: emit a package with PK_INFO_ENUM_UNTRUSTED + } + + delete m_apt; + return true; } /** * pk_backend_refresh_cache: */ -void -pk_backend_refresh_cache (PkBackend *backend, gboolean force) +void pk_backend_refresh_cache(PkBackend *backend, gboolean force) { - pk_backend_thread_create (backend, pk_backend_refresh_cache_thread); + pk_backend_thread_create(backend, pk_backend_refresh_cache_thread); } -static gboolean -pk_backend_resolve_thread (PkBackend *backend) +static gboolean pk_backend_resolve_thread(PkBackend *backend) { - gchar **package_ids; - PkBitfield filters; + gchar **package_ids; + PkBitfield filters; - filters = (PkBitfield) pk_backend_get_uint (backend, "filters"); - package_ids = pk_backend_get_strv (backend, "package_ids"); - pk_backend_set_allow_cancel (backend, true); + filters = (PkBitfield) pk_backend_get_uint (backend, "filters"); + package_ids = pk_backend_get_strv (backend, "package_ids"); + pk_backend_set_allow_cancel (backend, true); - AptIntf *m_apt = new AptIntf(backend, _cancel); - pk_backend_set_pointer(backend, "aptcc_obj", m_apt); - if (m_apt->init()) { - g_debug ("Failed to create apt cache"); - delete m_apt; - return false; - } + AptIntf *m_apt = new AptIntf(backend, _cancel); + pk_backend_set_pointer(backend, "aptcc_obj", m_apt); + if (m_apt->init()) { + g_debug ("Failed to create apt cache"); + delete m_apt; + return false; + } PkgList pkgs = m_apt->resolvePI(package_ids); // It's faster to emmit the packages here rather than in the matching part m_apt->emit_packages(pkgs, filters); - delete m_apt; - return true; + delete m_apt; + return true; } /** * pk_backend_resolve: */ -void -pk_backend_resolve (PkBackend *backend, PkBitfield filters, gchar **packages) +void pk_backend_resolve(PkBackend *backend, PkBitfield filters, gchar **packages) { - pk_backend_thread_create (backend, pk_backend_resolve_thread); + pk_backend_thread_create(backend, pk_backend_resolve_thread); } -static gboolean -pk_backend_search_files_thread (PkBackend *backend) +static gboolean pk_backend_search_files_thread(PkBackend *backend) { - gchar **values; - PkBitfield filters; - - values = pk_backend_get_strv (backend, "search"); - filters = (PkBitfield) pk_backend_get_uint (backend, "filters"); - - pk_backend_set_allow_cancel (backend, true); - - // as we can only search for installed files lets avoid the opposite - if (!pk_bitfield_contain (filters, PK_FILTER_ENUM_NOT_INSTALLED)) { - AptIntf *m_apt = new AptIntf(backend, _cancel); - pk_backend_set_pointer(backend, "aptcc_obj", m_apt); - if (m_apt->init()) { - g_debug ("Failed to create apt cache"); - delete m_apt; - return false; - } - - pk_backend_set_status (backend, PK_STATUS_ENUM_QUERY); - vector<string> packages = search_files (backend, values, _cancel); - PkgList output; - for(vector<string>::iterator i = packages.begin(); - i != packages.end(); ++i) - { - if (_cancel) { - break; - } - pkgCache::PkgIterator pkg = m_apt->packageCache->FindPkg(i->c_str()); + gchar **values; + PkBitfield filters; + + values = pk_backend_get_strv(backend, "search"); + filters = (PkBitfield) pk_backend_get_uint(backend, "filters"); + + pk_backend_set_allow_cancel(backend, true); + + // as we can only search for installed files lets avoid the opposite + if (!pk_bitfield_contain(filters, PK_FILTER_ENUM_NOT_INSTALLED)) { + AptIntf *m_apt = new AptIntf(backend, _cancel); + pk_backend_set_pointer(backend, "aptcc_obj", m_apt); + if (m_apt->init()) { + g_debug ("Failed to create apt cache"); + delete m_apt; + return false; + } + + pk_backend_set_status(backend, PK_STATUS_ENUM_QUERY); + vector<string> packages = search_files(backend, values, _cancel); + PkgList output; + for(vector<string>::iterator i = packages.begin(); + i != packages.end(); ++i) { + if (_cancel) { + break; + } + pkgCache::PkgIterator pkg = m_apt->packageCache->FindPkg(i->c_str()); if (pkg.end() == true) { continue; } - pkgCache::VerIterator ver = m_apt->find_ver(pkg); - if (ver.end() == true) - { - continue; - } - output.push_back(PkgPair(pkg, ver)); - } - // It's faster to emmit the packages here rather than in the matching part - m_apt->emit_packages(output, filters); - - delete m_apt; + pkgCache::VerIterator ver = m_apt->find_ver(pkg); + if (ver.end() == true) { + continue; + } + output.push_back(PkgPair(pkg, ver)); + } + // It's faster to emmit the packages here rather than in the matching part + m_apt->emit_packages(output, filters); + + delete m_apt; } else { pk_backend_finished (backend); } - return true; + return true; } /** * pk_backend_search_files: */ -void -pk_backend_search_files (PkBackend *backend, PkBitfield filters, gchar **values) +void pk_backend_search_files(PkBackend *backend, PkBitfield filters, gchar **values) { - pk_backend_thread_create (backend, pk_backend_search_files_thread); + pk_backend_thread_create(backend, pk_backend_search_files_thread); } -static gboolean -backend_search_groups_thread (PkBackend *backend) +static gboolean backend_search_groups_thread (PkBackend *backend) { - gchar **values; - PkBitfield filters; - vector<PkGroupEnum> groups; - - values = pk_backend_get_strv (backend, "search"); - filters = (PkBitfield) pk_backend_get_uint (backend, "filters"); - pk_backend_set_allow_cancel (backend, true); - - int len = g_strv_length(values); - for (uint i = 0; i < len; i++) { - if (values[i] == NULL) { - pk_backend_error_code (backend, - PK_ERROR_ENUM_GROUP_NOT_FOUND, - values[i]); - pk_backend_finished (backend); - return false; - } else { - groups.push_back(pk_group_enum_from_string(values[i])); - } - } - - AptIntf *m_apt = new AptIntf(backend, _cancel); - pk_backend_set_pointer(backend, "aptcc_obj", m_apt); - if (m_apt->init()) { - g_debug ("Failed to create apt cache"); - delete m_apt; - return false; - } - - pk_backend_set_status (backend, PK_STATUS_ENUM_QUERY); - PkgList output; - for (pkgCache::PkgIterator pkg = m_apt->packageCache->PkgBegin(); !pkg.end(); ++pkg) { - if (_cancel) { - break; - } - // Ignore packages that exist only due to dependencies. - if (pkg.VersionList().end() && pkg.ProvidesList().end()) { - continue; - } - - // Ignore virtual packages - pkgCache::VerIterator ver = m_apt->find_ver(pkg); - if (ver.end() == false) { - string section = pkg.VersionList().Section() == NULL ? "" : pkg.VersionList().Section(); - - size_t found; - found = section.find_last_of("/"); - section = section.substr(found + 1); - - // Don't insert virtual packages instead add what it provides - for (vector<PkGroupEnum>::iterator i = groups.begin(); - i != groups.end(); - ++i) { - if (*i == get_enum_group(section)) { - output.push_back(PkgPair(pkg, ver)); - break; - } - } - } - } - - // It's faster to emmit the packages here rather than in the matching part - m_apt->emit_packages(output, filters); + gchar **values; + PkBitfield filters; + vector<PkGroupEnum> groups; + + values = pk_backend_get_strv(backend, "search"); + filters = (PkBitfield) pk_backend_get_uint (backend, "filters"); + pk_backend_set_allow_cancel(backend, true); + + int len = g_strv_length(values); + for (uint i = 0; i < len; i++) { + if (values[i] == NULL) { + pk_backend_error_code(backend, + PK_ERROR_ENUM_GROUP_NOT_FOUND, + values[i]); + pk_backend_finished(backend); + return false; + } else { + groups.push_back(pk_group_enum_from_string(values[i])); + } + } + + AptIntf *m_apt = new AptIntf(backend, _cancel); + pk_backend_set_pointer(backend, "aptcc_obj", m_apt); + if (m_apt->init()) { + g_debug ("Failed to create apt cache"); + delete m_apt; + return false; + } + + pk_backend_set_status (backend, PK_STATUS_ENUM_QUERY); + PkgList output; + for (pkgCache::PkgIterator pkg = m_apt->packageCache->PkgBegin(); !pkg.end(); ++pkg) { + if (_cancel) { + break; + } + // Ignore packages that exist only due to dependencies. + if (pkg.VersionList().end() && pkg.ProvidesList().end()) { + continue; + } + + // Ignore virtual packages + pkgCache::VerIterator ver = m_apt->find_ver(pkg); + if (ver.end() == false) { + string section = pkg.VersionList().Section() == NULL ? "" : pkg.VersionList().Section(); + + size_t found; + found = section.find_last_of("/"); + section = section.substr(found + 1); + + // Don't insert virtual packages instead add what it provides + for (vector<PkGroupEnum>::iterator i = groups.begin(); + i != groups.end(); + ++i) { + if (*i == get_enum_group(section)) { + output.push_back(PkgPair(pkg, ver)); + break; + } + } + } + } + + // It's faster to emmit the packages here rather than in the matching part + m_apt->emit_packages(output, filters); pk_backend_set_percentage (backend, 100); - delete m_apt; - return true; + delete m_apt; + return true; } /** * pk_backend_search_groups: */ -void -pk_backend_search_groups (PkBackend *backend, PkBitfield filters, gchar **values) +void pk_backend_search_groups(PkBackend *backend, PkBitfield filters, gchar **values) { - pk_backend_thread_create (backend, backend_search_groups_thread); + pk_backend_thread_create(backend, backend_search_groups_thread); } -static gboolean -backend_search_package_thread (PkBackend *backend) +static gboolean backend_search_package_thread(PkBackend *backend) { - gchar **values; - gchar *search; - PkBitfield filters; - - values = pk_backend_get_strv (backend, "search"); - search = g_strjoinv("|", values); - filters = (PkBitfield) pk_backend_get_uint (backend, "filters"); - - pk_backend_set_percentage (backend, PK_BACKEND_PERCENTAGE_INVALID); - pk_backend_set_allow_cancel (backend, true); - - Matcher *m_matcher = new Matcher(search); - g_free(search); - if (m_matcher->hasError()) { - g_debug("Regex compilation error"); - delete m_matcher; - pk_backend_finished (backend); - return false; - } - - AptIntf *m_apt = new AptIntf(backend, _cancel); - pk_backend_set_pointer(backend, "aptcc_obj", m_apt); - if (m_apt->init()) { - g_debug ("Failed to create apt cache"); - delete m_matcher; - delete m_apt; - return false; - } - - if (_error->PendingError() == true) - { - delete m_matcher; - delete m_apt; - return false; - } - - pk_backend_set_status (backend, PK_STATUS_ENUM_QUERY); - pkgDepCache::Policy Plcy; - PkgList output; - if (pk_backend_get_bool (backend, "search_details")) { - for (pkgCache::PkgIterator pkg = m_apt->packageCache->PkgBegin(); !pkg.end(); ++pkg) { - if (_cancel) { - break; - } - // Ignore packages that exist only due to dependencies. - if (pkg.VersionList().end() && pkg.ProvidesList().end()) { - continue; - } + gchar **values; + gchar *search; + PkBitfield filters; + + values = pk_backend_get_strv(backend, "search"); + search = g_strjoinv("|", values); + filters = (PkBitfield) pk_backend_get_uint(backend, "filters"); + + pk_backend_set_percentage(backend, PK_BACKEND_PERCENTAGE_INVALID); + pk_backend_set_allow_cancel(backend, true); + + Matcher *m_matcher = new Matcher(search); + g_free(search); + if (m_matcher->hasError()) { + g_debug("Regex compilation error"); + delete m_matcher; + pk_backend_finished (backend); + return false; + } + + AptIntf *m_apt = new AptIntf(backend, _cancel); + pk_backend_set_pointer(backend, "aptcc_obj", m_apt); + if (m_apt->init()) { + g_debug ("Failed to create apt cache"); + delete m_matcher; + delete m_apt; + return false; + } + + if (_error->PendingError() == true) { + delete m_matcher; + delete m_apt; + return false; + } + + pk_backend_set_status(backend, PK_STATUS_ENUM_QUERY); + pkgDepCache::Policy Plcy; + PkgList output; + if (pk_backend_get_bool(backend, "search_details")) { + for (pkgCache::PkgIterator pkg = m_apt->packageCache->PkgBegin(); !pkg.end(); ++pkg) { + if (_cancel) { + break; + } + // Ignore packages that exist only due to dependencies. + if (pkg.VersionList().end() && pkg.ProvidesList().end()) { + continue; + } pkgCache::VerIterator ver = m_apt->find_ver(pkg); if (ver.end() == false) { if (m_matcher->matches(pkg.Name()) || - m_matcher->matches(get_long_description(ver, m_apt->packageRecords))) { + m_matcher->matches(get_long_description(ver, m_apt->packageRecords))) { // The package matched output.push_back(PkgPair(pkg, ver)); } @@ -1017,83 +969,79 @@ backend_search_package_thread (PkBackend *backend) // Don't insert virtual packages instead add what it provides // iterate over the provides list - for (pkgCache::PrvIterator Prv = pkg.ProvidesList(); Prv.end() == false; Prv++) { - ver = m_apt->find_ver(Prv.OwnerPkg()); + for (pkgCache::PrvIterator Prv = pkg.ProvidesList(); Prv.end() == false; ++Prv) { + ver = m_apt->find_ver(Prv.OwnerPkg()); // check to see if the provided package isn't virtual too - if (ver.end() == false) - { + if (ver.end() == false) { // we add the package now because we will need to // remove duplicates later anyway output.push_back(PkgPair(Prv.OwnerPkg(), ver)); } } } - } - } else { - for (pkgCache::PkgIterator pkg = m_apt->packageCache->PkgBegin(); !pkg.end(); ++pkg) { - if (_cancel) { - break; - } - // Ignore packages that exist only due to dependencies. - if (pkg.VersionList().end() && pkg.ProvidesList().end()) { - continue; - } - - if (m_matcher->matches(pkg.Name())) { - // Don't insert virtual packages instead add what it provides - pkgCache::VerIterator ver = m_apt->find_ver(pkg); - if (ver.end() == false) { - output.push_back(PkgPair(pkg, ver)); - } else { - // iterate over the provides list - for (pkgCache::PrvIterator Prv = pkg.ProvidesList(); Prv.end() == false; Prv++) { - ver = m_apt->find_ver(Prv.OwnerPkg()); - - // check to see if the provided package isn't virtual too - if (ver.end() == false) - { - // we add the package now because we will need to - // remove duplicates later anyway - output.push_back(PkgPair(Prv.OwnerPkg(), ver)); - } - } - } - } - } - } - - // It's faster to emmit the packages here than in the matching part - m_apt->emit_packages(output, filters); - - delete m_matcher; + } + } else { + for (pkgCache::PkgIterator pkg = m_apt->packageCache->PkgBegin(); !pkg.end(); ++pkg) { + if (_cancel) { + break; + } + // Ignore packages that exist only due to dependencies. + if (pkg.VersionList().end() && pkg.ProvidesList().end()) { + continue; + } + + if (m_matcher->matches(pkg.Name())) { + // Don't insert virtual packages instead add what it provides + pkgCache::VerIterator ver = m_apt->find_ver(pkg); + if (ver.end() == false) { + output.push_back(PkgPair(pkg, ver)); + } else { + // iterate over the provides list + for (pkgCache::PrvIterator Prv = pkg.ProvidesList(); Prv.end() == false; ++Prv) { + ver = m_apt->find_ver(Prv.OwnerPkg()); + + // check to see if the provided package isn't virtual too + if (ver.end() == false) + { + // we add the package now because we will need to + // remove duplicates later anyway + output.push_back(PkgPair(Prv.OwnerPkg(), ver)); + } + } + } + } + } + } + + // It's faster to emmit the packages here than in the matching part + m_apt->emit_packages(output, filters); + + delete m_matcher; pk_backend_set_percentage (backend, 100); - delete m_apt; - return true; + delete m_apt; + return true; } /** * pk_backend_search_names: */ -void -pk_backend_search_names (PkBackend *backend, PkBitfield filters, gchar **values) +void pk_backend_search_names(PkBackend *backend, PkBitfield filters, gchar **values) { - pk_backend_set_bool(backend, "search_details", false); - pk_backend_thread_create(backend, backend_search_package_thread); + pk_backend_set_bool(backend, "search_details", false); + pk_backend_thread_create(backend, backend_search_package_thread); } /** * pk_backend_search_details: */ -void -pk_backend_search_details (PkBackend *backend, PkBitfield filters, gchar **values) +void pk_backend_search_details(PkBackend *backend, PkBitfield filters, gchar **values) { - pk_backend_set_bool(backend, "search_details", true); - pk_backend_thread_create(backend, backend_search_package_thread); + pk_backend_set_bool(backend, "search_details", true); + pk_backend_thread_create(backend, backend_search_package_thread); } -static gboolean -backend_manage_packages_thread (PkBackend *backend) +static gboolean backend_manage_packages_thread(PkBackend *backend) { bool simulate = false; bool remove = false; @@ -1103,351 +1051,336 @@ backend_manage_packages_thread (PkBackend *backend) PkRoleEnum role = pk_backend_get_role (backend); if (role == PK_ROLE_ENUM_SIMULATE_INSTALL_FILES || - role == PK_ROLE_ENUM_SIMULATE_INSTALL_PACKAGES || - role == PK_ROLE_ENUM_SIMULATE_UPDATE_PACKAGES || - role == PK_ROLE_ENUM_SIMULATE_REMOVE_PACKAGES) { + role == PK_ROLE_ENUM_SIMULATE_INSTALL_PACKAGES || + role == PK_ROLE_ENUM_SIMULATE_UPDATE_PACKAGES || + role == PK_ROLE_ENUM_SIMULATE_REMOVE_PACKAGES) { simulate = true; } if (role == PK_ROLE_ENUM_SIMULATE_REMOVE_PACKAGES || - role == PK_ROLE_ENUM_REMOVE_PACKAGES) { + role == PK_ROLE_ENUM_REMOVE_PACKAGES) { remove = true; } if (role == PK_ROLE_ENUM_SIMULATE_INSTALL_FILES || - role == PK_ROLE_ENUM_INSTALL_FILES) { + role == PK_ROLE_ENUM_INSTALL_FILES) { full_paths = pk_backend_get_strv (backend, "full_paths"); fileInstall = true; } - g_debug ("FILE INSTALL: %i", fileInstall); - pk_backend_set_allow_cancel (backend, true); - - AptIntf *m_apt = new AptIntf(backend, _cancel); - pk_backend_set_pointer(backend, "aptcc_obj", m_apt); - if (m_apt->init()) { - g_debug ("Failed to create apt cache"); - delete m_apt; - return false; - } - - pk_backend_set_status (backend, PK_STATUS_ENUM_QUERY); - PkgList installPkgs, removePkgs; - - if (fileInstall) { - // File installation EXPERIMENTAL - - // GDebi can not install more than one package at time - if (g_strv_length(full_paths) > 1) { - pk_backend_error_code(backend, - PK_ERROR_ENUM_NOT_SUPPORTED, - "The backend can only proccess one file at time."); - delete m_apt; - return false; - } - - // get the list of packages to install - if (!m_apt->markFileForInstall(full_paths[0], installPkgs, removePkgs)) { - delete m_apt; - return false; - } - - // Mark newly installed packages as auto-installed - // (they're dependencies of the new local package) - markAuto = true; - - cout << "installPkgs.size: " << installPkgs.size() << endl; - cout << "removePkgs.size: " << removePkgs.size() << endl; - - } else { - // Resolve the given packages - gchar **package_ids = pk_backend_get_strv(backend, "package_ids"); - if (remove) { - removePkgs = m_apt->resolvePI(package_ids); - } else { - installPkgs = m_apt->resolvePI(package_ids); - } - - if (removePkgs.size() == 0 && installPkgs.size() == 0) { - pk_backend_error_code(backend, - PK_ERROR_ENUM_PACKAGE_NOT_FOUND, - "Could not find package(s)"); - delete m_apt; - return false; - } - } - - // Install/Update/Remove packages, or just simulate - if (!m_apt->runTransaction(installPkgs, removePkgs, simulate, markAuto)) { - // Print transaction errors - cout << "runTransaction failed" << endl; - delete m_apt; - return false; - } - - if (fileInstall) { - // Now perform the installation! - gchar *path; - for (uint i = 0; i < g_strv_length(full_paths); i++) { - if (_cancel) { - break; - } - - path = full_paths[i]; - if (!m_apt->installFile(path, simulate)) { - cout << "Installation of DEB file " << path << " failed." << endl; - delete m_apt; - return false; - } - } - } - - delete m_apt; - return true; + g_debug ("FILE INSTALL: %i", fileInstall); + pk_backend_set_allow_cancel (backend, true); + + AptIntf *m_apt = new AptIntf(backend, _cancel); + pk_backend_set_pointer(backend, "aptcc_obj", m_apt); + if (m_apt->init()) { + g_debug ("Failed to create apt cache"); + delete m_apt; + return false; + } + + pk_backend_set_status (backend, PK_STATUS_ENUM_QUERY); + PkgList installPkgs, removePkgs; + + if (fileInstall) { + // File installation EXPERIMENTAL + + // GDebi can not install more than one package at time + if (g_strv_length(full_paths) > 1) { + pk_backend_error_code(backend, + PK_ERROR_ENUM_NOT_SUPPORTED, + "The backend can only proccess one file at time."); + delete m_apt; + return false; + } + + // get the list of packages to install + if (!m_apt->markFileForInstall(full_paths[0], installPkgs, removePkgs)) { + delete m_apt; + return false; + } + + // Mark newly installed packages as auto-installed + // (they're dependencies of the new local package) + markAuto = true; + + cout << "installPkgs.size: " << installPkgs.size() << endl; + cout << "removePkgs.size: " << removePkgs.size() << endl; + + } else { + // Resolve the given packages + gchar **package_ids = pk_backend_get_strv(backend, "package_ids"); + if (remove) { + removePkgs = m_apt->resolvePI(package_ids); + } else { + installPkgs = m_apt->resolvePI(package_ids); + } + + if (removePkgs.size() == 0 && installPkgs.size() == 0) { + pk_backend_error_code(backend, + PK_ERROR_ENUM_PACKAGE_NOT_FOUND, + "Could not find package(s)"); + delete m_apt; + return false; + } + } + + // Install/Update/Remove packages, or just simulate + if (!m_apt->runTransaction(installPkgs, removePkgs, simulate, markAuto)) { + // Print transaction errors + cout << "runTransaction failed" << endl; + delete m_apt; + return false; + } + + if (fileInstall) { + // Now perform the installation! + gchar *path; + for (uint i = 0; i < g_strv_length(full_paths); ++i) { + if (_cancel) { + break; + } + + path = full_paths[i]; + if (!m_apt->installFile(path, simulate)) { + cout << "Installation of DEB file " << path << " failed." << endl; + delete m_apt; + return false; + } + } + } + + delete m_apt; + return true; } /** * pk_backend_simulate_install_packages: */ -void -pk_backend_simulate_install_packages (PkBackend *backend, gchar **packages) +void pk_backend_simulate_install_packages(PkBackend *backend, gchar **packages) { - pk_backend_thread_create (backend, backend_manage_packages_thread); + pk_backend_thread_create(backend, backend_manage_packages_thread); } /** * pk_backend_install_packages: */ -void -pk_backend_install_packages (PkBackend *backend, gboolean only_trusted, gchar **package_ids) +void pk_backend_install_packages(PkBackend *backend, gboolean only_trusted, gchar **package_ids) { - pk_backend_thread_create (backend, backend_manage_packages_thread); + pk_backend_thread_create(backend, backend_manage_packages_thread); } /** * pk_backend_simulate_update_packages: */ -void -pk_backend_simulate_update_packages (PkBackend *backend, gchar **packages) +void pk_backend_simulate_update_packages(PkBackend *backend, gchar **packages) { - pk_backend_thread_create (backend, backend_manage_packages_thread); + pk_backend_thread_create(backend, backend_manage_packages_thread); } /** * pk_backend_update_packages: */ -void -pk_backend_update_packages (PkBackend *backend, gboolean only_trusted, gchar **package_ids) +void pk_backend_update_packages(PkBackend *backend, gboolean only_trusted, gchar **package_ids) { - pk_backend_thread_create (backend, backend_manage_packages_thread); + pk_backend_thread_create(backend, backend_manage_packages_thread); } /** * pk_backend_simulate_install_files: */ -void -pk_backend_simulate_install_files (PkBackend *backend, gchar **full_paths) +void pk_backend_simulate_install_files(PkBackend *backend, gchar **full_paths) { - pk_backend_thread_create (backend, backend_manage_packages_thread); + pk_backend_thread_create(backend, backend_manage_packages_thread); } /** * pk_backend_install_files: */ -void -pk_backend_install_files (PkBackend *backend, gboolean only_trusted, gchar **full_paths) +void pk_backend_install_files(PkBackend *backend, gboolean only_trusted, gchar **full_paths) { - pk_backend_thread_create (backend, backend_manage_packages_thread); + pk_backend_thread_create(backend, backend_manage_packages_thread); } /** * pk_backend_simulate_remove_packages: */ -void -pk_backend_simulate_remove_packages (PkBackend *backend, gchar **packages, gboolean autoremove) +void pk_backend_simulate_remove_packages(PkBackend *backend, gchar **packages, gboolean autoremove) { - pk_backend_thread_create (backend, backend_manage_packages_thread); + pk_backend_thread_create(backend, backend_manage_packages_thread); } /** * pk_backend_remove_packages: */ -void -pk_backend_remove_packages (PkBackend *backend, gchar **package_ids, gboolean allow_deps, gboolean autoremove) +void pk_backend_remove_packages(PkBackend *backend, gchar **package_ids, gboolean allow_deps, gboolean autoremove) { - pk_backend_thread_create (backend, backend_manage_packages_thread); + pk_backend_thread_create(backend, backend_manage_packages_thread); } -static gboolean -backend_repo_manager_thread (PkBackend *backend) +static gboolean backend_repo_manager_thread(PkBackend *backend) { - // list - PkBitfield filters; - bool notDevelopment; - // enable - const gchar *repo_id; - bool enabled; - bool found = false; - // generic - const char *const salt = "$1$/iSaq7rB$EoUw5jJPPvAPECNaaWzMK/"; - bool list = pk_backend_get_bool(backend, "list"); - - if (list) { - pk_backend_set_status (backend, PK_STATUS_ENUM_QUERY); - filters = (PkBitfield) pk_backend_get_uint(backend, "filters"); - notDevelopment = pk_bitfield_contain(filters, PK_FILTER_ENUM_NOT_DEVELOPMENT); - } else { - pk_backend_set_status (backend, PK_STATUS_ENUM_REQUEST); - repo_id = pk_backend_get_string(backend, "repo_id"); - enabled = pk_backend_get_bool(backend, "enabled"); - } - - SourcesList _lst; - if (_lst.ReadSources() == false) { - _error-> - Warning("Ignoring invalid record(s) in sources.list file!"); - //return false; - } - - if (_lst.ReadVendors() == false) { - _error->Error("Cannot read vendors.list file"); - show_errors(backend, PK_ERROR_ENUM_FAILED_CONFIG_PARSING); - pk_backend_finished (backend); - return false; - } - - for (SourcesListIter it = _lst.SourceRecords.begin(); - it != _lst.SourceRecords.end(); it++) - { - if ((*it)->Type & SourcesList::Comment) { - continue; - } - - string Sections; - for (unsigned int J = 0; J < (*it)->NumSections; J++) { - Sections += (*it)->Sections[J]; - Sections += " "; - } - - if (notDevelopment && - ((*it)->Type & SourcesList::DebSrc || - (*it)->Type & SourcesList::RpmSrc || - (*it)->Type & SourcesList::RpmSrcDir || - (*it)->Type & SourcesList::RepomdSrc)) - { - continue; - } - - string repo; - repo = (*it)->GetType(); - repo += " " + (*it)->VendorID; - repo += " " + (*it)->URI; - repo += " " + (*it)->Dist; - repo += " " + Sections; - gchar *hash; - const gchar allowedChars[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; - hash = crypt(repo.c_str(), salt); - g_strcanon(hash, allowedChars, 'D'); - string repoId(hash); - - if (list) { - pk_backend_repo_detail(backend, - repoId.c_str(), - repo.c_str(), - !((*it)->Type & SourcesList::Disabled)); - } else { - if (repoId.compare(repo_id) == 0) { - if (enabled) { - (*it)->Type = (*it)->Type & ~SourcesList::Disabled; - } else { - (*it)->Type |= SourcesList::Disabled; - } - found = true; - break; - } - } - } - - if (!list) { - if (!found) { - _error->Error("Could not found the repositorie"); - show_errors(backend, PK_ERROR_ENUM_REPO_NOT_AVAILABLE); - } else if (!_lst.UpdateSources()) { - _error->Error("Could not update sources file"); - show_errors(backend, PK_ERROR_ENUM_CANNOT_WRITE_REPO_CONFIG); - } - } - pk_backend_finished (backend); - return true; + // list + PkBitfield filters; + bool notDevelopment; + // enable + const gchar *repo_id; + bool enabled; + bool found = false; + // generic + const char *const salt = "$1$/iSaq7rB$EoUw5jJPPvAPECNaaWzMK/"; + bool list = pk_backend_get_bool(backend, "list"); + + if (list) { + pk_backend_set_status (backend, PK_STATUS_ENUM_QUERY); + filters = (PkBitfield) pk_backend_get_uint(backend, "filters"); + notDevelopment = pk_bitfield_contain(filters, PK_FILTER_ENUM_NOT_DEVELOPMENT); + } else { + pk_backend_set_status (backend, PK_STATUS_ENUM_REQUEST); + repo_id = pk_backend_get_string(backend, "repo_id"); + enabled = pk_backend_get_bool(backend, "enabled"); + } + + SourcesList _lst; + if (_lst.ReadSources() == false) { + _error-> + Warning("Ignoring invalid record(s) in sources.list file!"); + //return false; + } + + if (_lst.ReadVendors() == false) { + _error->Error("Cannot read vendors.list file"); + show_errors(backend, PK_ERROR_ENUM_FAILED_CONFIG_PARSING); + pk_backend_finished (backend); + return false; + } + + for (SourcesListIter it = _lst.SourceRecords.begin(); + it != _lst.SourceRecords.end(); ++it) { + if ((*it)->Type & SourcesList::Comment) { + continue; + } + + string Sections; + for (unsigned int j = 0; j < (*it)->NumSections; ++j) { + Sections += (*it)->Sections[j]; + Sections += " "; + } + + if (notDevelopment && + ((*it)->Type & SourcesList::DebSrc || + (*it)->Type & SourcesList::RpmSrc || + (*it)->Type & SourcesList::RpmSrcDir || + (*it)->Type & SourcesList::RepomdSrc)) { + continue; + } + + string repo; + repo = (*it)->GetType(); + repo += " " + (*it)->VendorID; + repo += " " + (*it)->URI; + repo += " " + (*it)->Dist; + repo += " " + Sections; + gchar *hash; + const gchar allowedChars[] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + hash = crypt(repo.c_str(), salt); + g_strcanon(hash, allowedChars, 'D'); + string repoId(hash); + + if (list) { + pk_backend_repo_detail(backend, + repoId.c_str(), + repo.c_str(), + !((*it)->Type & SourcesList::Disabled)); + } else { + if (repoId.compare(repo_id) == 0) { + if (enabled) { + (*it)->Type = (*it)->Type & ~SourcesList::Disabled; + } else { + (*it)->Type |= SourcesList::Disabled; + } + found = true; + break; + } + } + } + + if (!list) { + if (!found) { + _error->Error("Could not found the repositorie"); + show_errors(backend, PK_ERROR_ENUM_REPO_NOT_AVAILABLE); + } else if (!_lst.UpdateSources()) { + _error->Error("Could not update sources file"); + show_errors(backend, PK_ERROR_ENUM_CANNOT_WRITE_REPO_CONFIG); + } + } + pk_backend_finished(backend); + return true; } /** * pk_backend_get_repo_list: */ -void -pk_backend_get_repo_list (PkBackend *backend, PkBitfield filters) +void pk_backend_get_repo_list(PkBackend *backend, PkBitfield filters) { - pk_backend_set_bool(backend, "list", true); - pk_backend_thread_create(backend, backend_repo_manager_thread); + pk_backend_set_bool(backend, "list", true); + pk_backend_thread_create(backend, backend_repo_manager_thread); } /** * pk_backend_repo_enable: */ -void -pk_backend_repo_enable (PkBackend *backend, const gchar *rid, gboolean enabled) +void pk_backend_repo_enable(PkBackend *backend, const gchar *rid, gboolean enabled) { - pk_backend_set_bool(backend, "list", false); - pk_backend_thread_create(backend, backend_repo_manager_thread); + pk_backend_set_bool(backend, "list", false); + pk_backend_thread_create(backend, backend_repo_manager_thread); } -static gboolean -backend_get_packages_thread (PkBackend *backend) +static gboolean backend_get_packages_thread(PkBackend *backend) { - PkBitfield filters; - filters = (PkBitfield) pk_backend_get_uint (backend, "filters"); - pk_backend_set_allow_cancel (backend, true); - - AptIntf *m_apt = new AptIntf(backend, _cancel); - pk_backend_set_pointer(backend, "aptcc_obj", m_apt); - if (m_apt->init()) { - g_debug ("Failed to create apt cache"); - delete m_apt; - return false; - } - - pk_backend_set_status (backend, PK_STATUS_ENUM_QUERY); - PkgList output; - output.reserve(m_apt->packageCache->HeaderP->PackageCount); - for(pkgCache::PkgIterator pkg = m_apt->packageCache->PkgBegin(); - !pkg.end(); ++pkg) - { - if (_cancel) { - break; - } - // Ignore packages that exist only due to dependencies. - if(pkg.VersionList().end() && pkg.ProvidesList().end()) - continue; - - // Don't insert virtual packages as they don't have all kinds of info - pkgCache::VerIterator ver = m_apt->find_ver(pkg); - if (ver.end() == false) { - output.push_back(PkgPair(pkg, ver)); - } - } - - // It's faster to emmit the packages rather here than in the matching part - m_apt->emit_packages(output, filters); - - delete m_apt; - return true; + PkBitfield filters; + filters = (PkBitfield) pk_backend_get_uint(backend, "filters"); + pk_backend_set_allow_cancel (backend, true); + + AptIntf *m_apt = new AptIntf(backend, _cancel); + pk_backend_set_pointer(backend, "aptcc_obj", m_apt); + if (m_apt->init()) { + g_debug ("Failed to create apt cache"); + delete m_apt; + return false; + } + + pk_backend_set_status (backend, PK_STATUS_ENUM_QUERY); + PkgList output; + output.reserve(m_apt->packageCache->HeaderP->PackageCount); + for (pkgCache::PkgIterator pkg = m_apt->packageCache->PkgBegin(); + !pkg.end(); ++pkg) { + if (_cancel) { + break; + } + // Ignore packages that exist only due to dependencies. + if(pkg.VersionList().end() && pkg.ProvidesList().end()) { + continue; + } + + // Don't insert virtual packages as they don't have all kinds of info + pkgCache::VerIterator ver = m_apt->find_ver(pkg); + if (ver.end() == false) { + output.push_back(PkgPair(pkg, ver)); + } + } + + // It's faster to emmit the packages rather here than in the matching part + m_apt->emit_packages(output, filters); + + delete m_apt; + return true; } /** * pk_backend_get_packages: */ -void -pk_backend_get_packages (PkBackend *backend, PkBitfield filter) +void pk_backend_get_packages(PkBackend *backend, PkBitfield filter) { - pk_backend_thread_create (backend, backend_get_packages_thread); + pk_backend_thread_create(backend, backend_get_packages_thread); } @@ -1458,45 +1391,44 @@ pk_backend_get_packages (PkBackend *backend, PkBitfield filter) void pk_backend_get_categories (PkBackend *backend) { - pk_backend_thread_create (backend, pk_backend_get_categories_thread); + pk_backend_thread_create (backend, pk_backend_get_categories_thread); } */ /** * pk_backend_get_roles: */ -PkBitfield -pk_backend_get_roles (PkBackend *backend) +PkBitfield pk_backend_get_roles(PkBackend *backend) { PkBitfield roles; - roles = pk_bitfield_from_enums ( - PK_ROLE_ENUM_CANCEL, - PK_ROLE_ENUM_GET_DEPENDS, - PK_ROLE_ENUM_GET_DETAILS, - PK_ROLE_ENUM_GET_FILES, - PK_ROLE_ENUM_GET_REQUIRES, - PK_ROLE_ENUM_GET_PACKAGES, - PK_ROLE_ENUM_WHAT_PROVIDES, - PK_ROLE_ENUM_GET_UPDATES, - PK_ROLE_ENUM_GET_UPDATE_DETAIL, - PK_ROLE_ENUM_INSTALL_PACKAGES, - PK_ROLE_ENUM_INSTALL_SIGNATURE, - PK_ROLE_ENUM_REFRESH_CACHE, - PK_ROLE_ENUM_REMOVE_PACKAGES, - PK_ROLE_ENUM_DOWNLOAD_PACKAGES, - PK_ROLE_ENUM_RESOLVE, - PK_ROLE_ENUM_SEARCH_DETAILS, - PK_ROLE_ENUM_SEARCH_FILE, - PK_ROLE_ENUM_SEARCH_GROUP, - PK_ROLE_ENUM_SEARCH_NAME, - PK_ROLE_ENUM_UPDATE_PACKAGES, - PK_ROLE_ENUM_UPDATE_SYSTEM, - PK_ROLE_ENUM_GET_REPO_LIST, - PK_ROLE_ENUM_REPO_ENABLE, - PK_ROLE_ENUM_SIMULATE_INSTALL_PACKAGES, - PK_ROLE_ENUM_SIMULATE_UPDATE_PACKAGES, - PK_ROLE_ENUM_SIMULATE_REMOVE_PACKAGES, - -1); + roles = pk_bitfield_from_enums( + PK_ROLE_ENUM_CANCEL, + PK_ROLE_ENUM_GET_DEPENDS, + PK_ROLE_ENUM_GET_DETAILS, + PK_ROLE_ENUM_GET_FILES, + PK_ROLE_ENUM_GET_REQUIRES, + PK_ROLE_ENUM_GET_PACKAGES, + PK_ROLE_ENUM_WHAT_PROVIDES, + PK_ROLE_ENUM_GET_UPDATES, + PK_ROLE_ENUM_GET_UPDATE_DETAIL, + PK_ROLE_ENUM_INSTALL_PACKAGES, + PK_ROLE_ENUM_INSTALL_SIGNATURE, + PK_ROLE_ENUM_REFRESH_CACHE, + PK_ROLE_ENUM_REMOVE_PACKAGES, + PK_ROLE_ENUM_DOWNLOAD_PACKAGES, + PK_ROLE_ENUM_RESOLVE, + PK_ROLE_ENUM_SEARCH_DETAILS, + PK_ROLE_ENUM_SEARCH_FILE, + PK_ROLE_ENUM_SEARCH_GROUP, + PK_ROLE_ENUM_SEARCH_NAME, + PK_ROLE_ENUM_UPDATE_PACKAGES, + PK_ROLE_ENUM_UPDATE_SYSTEM, + PK_ROLE_ENUM_GET_REPO_LIST, + PK_ROLE_ENUM_REPO_ENABLE, + PK_ROLE_ENUM_SIMULATE_INSTALL_PACKAGES, + PK_ROLE_ENUM_SIMULATE_UPDATE_PACKAGES, + PK_ROLE_ENUM_SIMULATE_REMOVE_PACKAGES, + -1); // only add GetDistroUpgrades if the binary is present if (g_file_test (PREUPGRADE_BINARY, G_FILE_TEST_EXISTS)) { diff --git a/backends/aptcc/pkg_acqfile.cpp b/backends/aptcc/pkg_acqfile.cpp index d20cff1d..94ffe0b4 100644 --- a/backends/aptcc/pkg_acqfile.cpp +++ b/backends/aptcc/pkg_acqfile.cpp @@ -43,119 +43,118 @@ // Let's all sing a song about apt-pkg's brokenness.. pkgAcqFileSane::pkgAcqFileSane(pkgAcquire *Owner, string URI, - string Description, string ShortDesc, - string filename): - Item(Owner) + string Description, string ShortDesc, + string filename) : + Item(Owner) { - Retries=_config->FindI("Acquire::Retries",0); - DestFile=filename; + Retries=_config->FindI("Acquire::Retries",0); + DestFile=filename; - Desc.URI=URI; - Desc.Description=Description; - Desc.Owner=this; - Desc.ShortDesc=ShortDesc; + Desc.URI=URI; + Desc.Description=Description; + Desc.Owner=this; + Desc.ShortDesc=ShortDesc; - QueueURI(Desc); + QueueURI(Desc); } // Straight from acquire-item.cc /* Here we try other sources */ void pkgAcqFileSane::Failed(string Message,pkgAcquire::MethodConfig *Cnf) { - ErrorText = LookupTag(Message,"Message"); - - // This is the retry counter - if (Retries != 0 && - Cnf->LocalOnly == false && - StringToBool(LookupTag(Message,"Transient-Failure"),false) == true) - { - Retries--; - QueueURI(Desc); - return; + ErrorText = LookupTag(Message,"Message"); + + // This is the retry counter + if (Retries != 0 && + Cnf->LocalOnly == false && + StringToBool(LookupTag(Message,"Transient-Failure"),false) == true) { + Retries--; + QueueURI(Desc); + return; } - Item::Failed(Message,Cnf); + Item::Failed(Message,Cnf); } // Mostly copied from pkgAcqArchive. bool get_archive(pkgAcquire *Owner, pkgSourceList *Sources, - pkgRecords *Recs, pkgCache::VerIterator const &Version, - string directory, string &StoreFilename) + pkgRecords *Recs, pkgCache::VerIterator const &Version, + string directory, string &StoreFilename) { - pkgCache::VerFileIterator Vf=Version.FileList(); - - if (Version.Arch() == 0) { - return _error->Error("I wasn't able to locate a file for the %s package. " - "This might mean you need to manually fix this package. (due to missing arch)", - Version.ParentPkg().Name()); - } - - /* We need to find a filename to determine the extension. We make the - assumption here that all the available sources for this version share - the same extension.. */ - // Skip not source sources, they do not have file fields. - for (; Vf.end() == false; Vf++) { - if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0) { - continue; - } - break; - } - - // Does not really matter here.. we are going to fail out below - if (Vf.end() != true) { - // If this fails to get a file name we will bomb out below. - pkgRecords::Parser &Parse = Recs->Lookup(Vf); - if (_error->PendingError() == true) { - return false; - } - - // Generate the final file name as: package_version_arch.foo - StoreFilename = QuoteString(Version.ParentPkg().Name(),"_:") + '_' + - QuoteString(Version.VerStr(),"_:") + '_' + - QuoteString(Version.Arch(),"_:.") + - "." + flExtension(Parse.FileName()); - } - - for (; Vf.end() == false; Vf++) { - // Ignore not source sources - if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0) { - continue; - } - - // Try to cross match against the source list - pkgIndexFile *Index; - if (Sources->FindIndex(Vf.File(),Index) == false) { - continue; - } - - // Grab the text package record - pkgRecords::Parser &Parse = Recs->Lookup(Vf); - if (_error->PendingError() == true) { - return false; - } - - const string PkgFile = Parse.FileName(); - const string MD5 = Parse.MD5Hash(); - if (PkgFile.empty() == true) { - return _error->Error("The package index files are corrupted. No Filename: " - "field for package %s.", - Version.ParentPkg().Name()); - } - - string DestFile = directory + "/" + flNotDir(StoreFilename); - - // Create the item - new pkgAcqFile(Owner, - Index->ArchiveURI(PkgFile), - MD5, - Version->Size, - Index->ArchiveInfo(Version), - Version.ParentPkg().Name(), - "", - DestFile); - - Vf++; - return true; - } - return false; + pkgCache::VerFileIterator Vf=Version.FileList(); + + if (Version.Arch() == 0) { + return _error->Error("I wasn't able to locate a file for the %s package. " + "This might mean you need to manually fix this package. (due to missing arch)", + Version.ParentPkg().Name()); + } + + /* We need to find a filename to determine the extension. We make the + assumption here that all the available sources for this version share + the same extension.. */ + // Skip not source sources, they do not have file fields. + for (; Vf.end() == false; Vf++) { + if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0) { + continue; + } + break; + } + + // Does not really matter here.. we are going to fail out below + if (Vf.end() != true) { + // If this fails to get a file name we will bomb out below. + pkgRecords::Parser &Parse = Recs->Lookup(Vf); + if (_error->PendingError() == true) { + return false; + } + + // Generate the final file name as: package_version_arch.foo + StoreFilename = QuoteString(Version.ParentPkg().Name(),"_:") + '_' + + QuoteString(Version.VerStr(),"_:") + '_' + + QuoteString(Version.Arch(),"_:.") + + "." + flExtension(Parse.FileName()); + } + + for (; Vf.end() == false; Vf++) { + // Ignore not source sources + if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0) { + continue; + } + + // Try to cross match against the source list + pkgIndexFile *Index; + if (Sources->FindIndex(Vf.File(),Index) == false) { + continue; + } + + // Grab the text package record + pkgRecords::Parser &Parse = Recs->Lookup(Vf); + if (_error->PendingError() == true) { + return false; + } + + const string PkgFile = Parse.FileName(); + const string MD5 = Parse.MD5Hash(); + if (PkgFile.empty() == true) { + return _error->Error("The package index files are corrupted. No Filename: " + "field for package %s.", + Version.ParentPkg().Name()); + } + + string DestFile = directory + "/" + flNotDir(StoreFilename); + + // Create the item + new pkgAcqFile(Owner, + Index->ArchiveURI(PkgFile), + MD5, + Version->Size, + Index->ArchiveInfo(Version), + Version.ParentPkg().Name(), + "", + DestFile); + + Vf++; + return true; + } + return false; } diff --git a/backends/aptcc/pkg_acqfile.h b/backends/aptcc/pkg_acqfile.h index 337ff764..fb6c72e9 100644 --- a/backends/aptcc/pkg_acqfile.h +++ b/backends/aptcc/pkg_acqfile.h @@ -29,30 +29,30 @@ */ class pkgAcqFileSane : public pkgAcquire::Item -// This is frustrating: pkgAcqFile is **almost** good enough, but has some -// hardcoded stuff that makes it not quite work. -// -// Based heavily on that class, though. + // This is frustrating: pkgAcqFile is **almost** good enough, but has some + // hardcoded stuff that makes it not quite work. + // + // Based heavily on that class, though. { - pkgAcquire::ItemDesc Desc; - string Md5Hash; - unsigned int Retries; + pkgAcquire::ItemDesc Desc; + string Md5Hash; + unsigned int Retries; public: - pkgAcqFileSane(pkgAcquire *Owner, string URI, - string Description, string ShortDesc, string filename); + pkgAcqFileSane(pkgAcquire *Owner, string URI, + string Description, string ShortDesc, string filename); - void Failed(string Message, pkgAcquire::MethodConfig *Cnf); - string MD5Sum() {return Md5Hash;} - string DescURI() {return Desc.URI;} - virtual ~pkgAcqFileSane() {} + void Failed(string Message, pkgAcquire::MethodConfig *Cnf); + string MD5Sum() {return Md5Hash;} + string DescURI() {return Desc.URI;} + virtual ~pkgAcqFileSane() {} }; /** Like pkgAcqArchive, but uses generic File objects to download to * the cwd (and copies from file:/ URLs). */ bool get_archive(pkgAcquire *Owner, pkgSourceList *Sources, - pkgRecords *Recs, pkgCache::VerIterator const &Version, - std::string directory, std::string &StoreFilename); + pkgRecords *Recs, pkgCache::VerIterator const &Version, + std::string directory, std::string &StoreFilename); #endif |