You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

3473 lines
114 KiB

  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: apt-get.cc,v 1.156 2004/08/28 01:05:16 mdz Exp $
  4. /* ######################################################################
  5. apt-get - Cover for dpkg
  6. This is an allout cover for dpkg implementing a safer front end. It is
  7. based largely on libapt-pkg.
  8. The syntax is different,
  9. apt-get [opt] command [things]
  10. Where command is:
  11. update - Resyncronize the package files from their sources
  12. upgrade - Smart-Download the newest versions of all packages
  13. dselect-upgrade - Follows dselect's changes to the Status: field
  14. and installes new and removes old packages
  15. dist-upgrade - Powerfull upgrader designed to handle the issues with
  16. a new distribution.
  17. install - Download and install a given package (by name, not by .deb)
  18. check - Update the package cache and check for broken packages
  19. clean - Erase the .debs downloaded to /var/cache/apt/archives and
  20. the partial dir too
  21. ##################################################################### */
  22. /*}}}*/
  23. // Include Files /*{{{*/
  24. #define _LARGEFILE_SOURCE
  25. #define _LARGEFILE64_SOURCE
  26. #include <apt-pkg/aptconfiguration.h>
  27. #include <apt-pkg/error.h>
  28. #include <apt-pkg/cmndline.h>
  29. #include <apt-pkg/init.h>
  30. #include <apt-pkg/depcache.h>
  31. #include <apt-pkg/sourcelist.h>
  32. #include <apt-pkg/algorithms.h>
  33. #include <apt-pkg/acquire-item.h>
  34. #include <apt-pkg/strutl.h>
  35. #include <apt-pkg/clean.h>
  36. #include <apt-pkg/srcrecords.h>
  37. #include <apt-pkg/version.h>
  38. #include <apt-pkg/cachefile.h>
  39. #include <apt-pkg/cacheset.h>
  40. #include <apt-pkg/sptr.h>
  41. #include <apt-pkg/md5.h>
  42. #include <apt-pkg/versionmatch.h>
  43. #include <config.h>
  44. #include <apti18n.h>
  45. #include "acqprogress.h"
  46. #include <set>
  47. #include <locale.h>
  48. #include <langinfo.h>
  49. #include <fstream>
  50. #include <termios.h>
  51. #include <sys/ioctl.h>
  52. #include <sys/stat.h>
  53. #include <sys/statfs.h>
  54. #include <sys/statvfs.h>
  55. #include <signal.h>
  56. #include <unistd.h>
  57. #include <stdio.h>
  58. #include <errno.h>
  59. #include <regex.h>
  60. #include <sys/wait.h>
  61. #include <sstream>
  62. #define statfs statfs64
  63. #define statvfs statvfs64
  64. /*}}}*/
  65. #define RAMFS_MAGIC 0x858458f6
  66. using namespace std;
  67. ostream c0out(0);
  68. ostream c1out(0);
  69. ostream c2out(0);
  70. ofstream devnull("/dev/null");
  71. unsigned int ScreenWidth = 80 - 1; /* - 1 for the cursor */
  72. // class CacheFile - Cover class for some dependency cache functions /*{{{*/
  73. // ---------------------------------------------------------------------
  74. /* */
  75. class CacheFile : public pkgCacheFile
  76. {
  77. static pkgCache *SortCache;
  78. static int NameComp(const void *a,const void *b);
  79. public:
  80. pkgCache::Package **List;
  81. void Sort();
  82. bool CheckDeps(bool AllowBroken = false);
  83. bool BuildCaches(bool WithLock = true)
  84. {
  85. OpTextProgress Prog(*_config);
  86. if (pkgCacheFile::BuildCaches(&Prog,WithLock) == false)
  87. return false;
  88. return true;
  89. }
  90. bool Open(bool WithLock = true)
  91. {
  92. OpTextProgress Prog(*_config);
  93. if (pkgCacheFile::Open(&Prog,WithLock) == false)
  94. return false;
  95. Sort();
  96. return true;
  97. };
  98. bool OpenForInstall()
  99. {
  100. if (_config->FindB("APT::Get::Print-URIs") == true)
  101. return Open(false);
  102. else
  103. return Open(true);
  104. }
  105. CacheFile() : List(0) {};
  106. ~CacheFile() {
  107. delete[] List;
  108. }
  109. };
  110. /*}}}*/
  111. // YnPrompt - Yes No Prompt. /*{{{*/
  112. // ---------------------------------------------------------------------
  113. /* Returns true on a Yes.*/
  114. bool YnPrompt(bool Default=true)
  115. {
  116. if (_config->FindB("APT::Get::Assume-Yes",false) == true)
  117. {
  118. c1out << _("Y") << endl;
  119. return true;
  120. }
  121. char response[1024] = "";
  122. cin.getline(response, sizeof(response));
  123. if (!cin)
  124. return false;
  125. if (strlen(response) == 0)
  126. return Default;
  127. regex_t Pattern;
  128. int Res;
  129. Res = regcomp(&Pattern, nl_langinfo(YESEXPR),
  130. REG_EXTENDED|REG_ICASE|REG_NOSUB);
  131. if (Res != 0) {
  132. char Error[300];
  133. regerror(Res,&Pattern,Error,sizeof(Error));
  134. return _error->Error(_("Regex compilation error - %s"),Error);
  135. }
  136. Res = regexec(&Pattern, response, 0, NULL, 0);
  137. if (Res == 0)
  138. return true;
  139. return false;
  140. }
  141. /*}}}*/
  142. // AnalPrompt - Annoying Yes No Prompt. /*{{{*/
  143. // ---------------------------------------------------------------------
  144. /* Returns true on a Yes.*/
  145. bool AnalPrompt(const char *Text)
  146. {
  147. char Buf[1024];
  148. cin.getline(Buf,sizeof(Buf));
  149. if (strcmp(Buf,Text) == 0)
  150. return true;
  151. return false;
  152. }
  153. /*}}}*/
  154. // ShowList - Show a list /*{{{*/
  155. // ---------------------------------------------------------------------
  156. /* This prints out a string of space separated words with a title and
  157. a two space indent line wraped to the current screen width. */
  158. bool ShowList(ostream &out,string Title,string List,string VersionsList)
  159. {
  160. if (List.empty() == true)
  161. return true;
  162. // trim trailing space
  163. int NonSpace = List.find_last_not_of(' ');
  164. if (NonSpace != -1)
  165. {
  166. List = List.erase(NonSpace + 1);
  167. if (List.empty() == true)
  168. return true;
  169. }
  170. // Acount for the leading space
  171. int ScreenWidth = ::ScreenWidth - 3;
  172. out << Title << endl;
  173. string::size_type Start = 0;
  174. string::size_type VersionsStart = 0;
  175. while (Start < List.size())
  176. {
  177. if(_config->FindB("APT::Get::Show-Versions",false) == true &&
  178. VersionsList.size() > 0) {
  179. string::size_type End;
  180. string::size_type VersionsEnd;
  181. End = List.find(' ',Start);
  182. VersionsEnd = VersionsList.find('\n', VersionsStart);
  183. out << " " << string(List,Start,End - Start) << " (" <<
  184. string(VersionsList,VersionsStart,VersionsEnd - VersionsStart) <<
  185. ")" << endl;
  186. if (End == string::npos || End < Start)
  187. End = Start + ScreenWidth;
  188. Start = End + 1;
  189. VersionsStart = VersionsEnd + 1;
  190. } else {
  191. string::size_type End;
  192. if (Start + ScreenWidth >= List.size())
  193. End = List.size();
  194. else
  195. End = List.rfind(' ',Start+ScreenWidth);
  196. if (End == string::npos || End < Start)
  197. End = Start + ScreenWidth;
  198. out << " " << string(List,Start,End - Start) << endl;
  199. Start = End + 1;
  200. }
  201. }
  202. return false;
  203. }
  204. /*}}}*/
  205. // ShowBroken - Debugging aide /*{{{*/
  206. // ---------------------------------------------------------------------
  207. /* This prints out the names of all the packages that are broken along
  208. with the name of each each broken dependency and a quite version
  209. description.
  210. The output looks like:
  211. The following packages have unmet dependencies:
  212. exim: Depends: libc6 (>= 2.1.94) but 2.1.3-10 is to be installed
  213. Depends: libldap2 (>= 2.0.2-2) but it is not going to be installed
  214. Depends: libsasl7 but it is not going to be installed
  215. */
  216. void ShowBroken(ostream &out,CacheFile &Cache,bool Now)
  217. {
  218. out << _("The following packages have unmet dependencies:") << endl;
  219. for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
  220. {
  221. pkgCache::PkgIterator I(Cache,Cache.List[J]);
  222. if (Now == true)
  223. {
  224. if (Cache[I].NowBroken() == false)
  225. continue;
  226. }
  227. else
  228. {
  229. if (Cache[I].InstBroken() == false)
  230. continue;
  231. }
  232. // Print out each package and the failed dependencies
  233. out << " " << I.FullName(true) << " :";
  234. unsigned const Indent = I.FullName(true).size() + 3;
  235. bool First = true;
  236. pkgCache::VerIterator Ver;
  237. if (Now == true)
  238. Ver = I.CurrentVer();
  239. else
  240. Ver = Cache[I].InstVerIter(Cache);
  241. if (Ver.end() == true)
  242. {
  243. out << endl;
  244. continue;
  245. }
  246. for (pkgCache::DepIterator D = Ver.DependsList(); D.end() == false;)
  247. {
  248. // Compute a single dependency element (glob or)
  249. pkgCache::DepIterator Start;
  250. pkgCache::DepIterator End;
  251. D.GlobOr(Start,End); // advances D
  252. if (Cache->IsImportantDep(End) == false)
  253. continue;
  254. if (Now == true)
  255. {
  256. if ((Cache[End] & pkgDepCache::DepGNow) == pkgDepCache::DepGNow)
  257. continue;
  258. }
  259. else
  260. {
  261. if ((Cache[End] & pkgDepCache::DepGInstall) == pkgDepCache::DepGInstall)
  262. continue;
  263. }
  264. bool FirstOr = true;
  265. while (1)
  266. {
  267. if (First == false)
  268. for (unsigned J = 0; J != Indent; J++)
  269. out << ' ';
  270. First = false;
  271. if (FirstOr == false)
  272. {
  273. for (unsigned J = 0; J != strlen(End.DepType()) + 3; J++)
  274. out << ' ';
  275. }
  276. else
  277. out << ' ' << End.DepType() << ": ";
  278. FirstOr = false;
  279. out << Start.TargetPkg().FullName(true);
  280. // Show a quick summary of the version requirements
  281. if (Start.TargetVer() != 0)
  282. out << " (" << Start.CompType() << " " << Start.TargetVer() << ")";
  283. /* Show a summary of the target package if possible. In the case
  284. of virtual packages we show nothing */
  285. pkgCache::PkgIterator Targ = Start.TargetPkg();
  286. if (Targ->ProvidesList == 0)
  287. {
  288. out << ' ';
  289. pkgCache::VerIterator Ver = Cache[Targ].InstVerIter(Cache);
  290. if (Now == true)
  291. Ver = Targ.CurrentVer();
  292. if (Ver.end() == false)
  293. {
  294. if (Now == true)
  295. ioprintf(out,_("but %s is installed"),Ver.VerStr());
  296. else
  297. ioprintf(out,_("but %s is to be installed"),Ver.VerStr());
  298. }
  299. else
  300. {
  301. if (Cache[Targ].CandidateVerIter(Cache).end() == true)
  302. {
  303. if (Targ->ProvidesList == 0)
  304. out << _("but it is not installable");
  305. else
  306. out << _("but it is a virtual package");
  307. }
  308. else
  309. out << (Now?_("but it is not installed"):_("but it is not going to be installed"));
  310. }
  311. }
  312. if (Start != End)
  313. out << _(" or");
  314. out << endl;
  315. if (Start == End)
  316. break;
  317. ++Start;
  318. }
  319. }
  320. }
  321. }
  322. /*}}}*/
  323. // ShowNew - Show packages to newly install /*{{{*/
  324. // ---------------------------------------------------------------------
  325. /* */
  326. void ShowNew(ostream &out,CacheFile &Cache)
  327. {
  328. /* Print out a list of packages that are going to be installed extra
  329. to what the user asked */
  330. string List;
  331. string VersionsList;
  332. for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
  333. {
  334. pkgCache::PkgIterator I(Cache,Cache.List[J]);
  335. if (Cache[I].NewInstall() == true) {
  336. List += I.FullName(true) + " ";
  337. VersionsList += string(Cache[I].CandVersion) + "\n";
  338. }
  339. }
  340. ShowList(out,_("The following NEW packages will be installed:"),List,VersionsList);
  341. }
  342. /*}}}*/
  343. // ShowDel - Show packages to delete /*{{{*/
  344. // ---------------------------------------------------------------------
  345. /* */
  346. void ShowDel(ostream &out,CacheFile &Cache)
  347. {
  348. /* Print out a list of packages that are going to be removed extra
  349. to what the user asked */
  350. string List;
  351. string VersionsList;
  352. for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
  353. {
  354. pkgCache::PkgIterator I(Cache,Cache.List[J]);
  355. if (Cache[I].Delete() == true)
  356. {
  357. if ((Cache[I].iFlags & pkgDepCache::Purge) == pkgDepCache::Purge)
  358. List += I.FullName(true) + "* ";
  359. else
  360. List += I.FullName(true) + " ";
  361. VersionsList += string(Cache[I].CandVersion)+ "\n";
  362. }
  363. }
  364. ShowList(out,_("The following packages will be REMOVED:"),List,VersionsList);
  365. }
  366. /*}}}*/
  367. // ShowKept - Show kept packages /*{{{*/
  368. // ---------------------------------------------------------------------
  369. /* */
  370. void ShowKept(ostream &out,CacheFile &Cache)
  371. {
  372. string List;
  373. string VersionsList;
  374. for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
  375. {
  376. pkgCache::PkgIterator I(Cache,Cache.List[J]);
  377. // Not interesting
  378. if (Cache[I].Upgrade() == true || Cache[I].Upgradable() == false ||
  379. I->CurrentVer == 0 || Cache[I].Delete() == true)
  380. continue;
  381. List += I.FullName(true) + " ";
  382. VersionsList += string(Cache[I].CurVersion) + " => " + Cache[I].CandVersion + "\n";
  383. }
  384. ShowList(out,_("The following packages have been kept back:"),List,VersionsList);
  385. }
  386. /*}}}*/
  387. // ShowUpgraded - Show upgraded packages /*{{{*/
  388. // ---------------------------------------------------------------------
  389. /* */
  390. void ShowUpgraded(ostream &out,CacheFile &Cache)
  391. {
  392. string List;
  393. string VersionsList;
  394. for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
  395. {
  396. pkgCache::PkgIterator I(Cache,Cache.List[J]);
  397. // Not interesting
  398. if (Cache[I].Upgrade() == false || Cache[I].NewInstall() == true)
  399. continue;
  400. List += I.FullName(true) + " ";
  401. VersionsList += string(Cache[I].CurVersion) + " => " + Cache[I].CandVersion + "\n";
  402. }
  403. ShowList(out,_("The following packages will be upgraded:"),List,VersionsList);
  404. }
  405. /*}}}*/
  406. // ShowDowngraded - Show downgraded packages /*{{{*/
  407. // ---------------------------------------------------------------------
  408. /* */
  409. bool ShowDowngraded(ostream &out,CacheFile &Cache)
  410. {
  411. string List;
  412. string VersionsList;
  413. for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
  414. {
  415. pkgCache::PkgIterator I(Cache,Cache.List[J]);
  416. // Not interesting
  417. if (Cache[I].Downgrade() == false || Cache[I].NewInstall() == true)
  418. continue;
  419. List += I.FullName(true) + " ";
  420. VersionsList += string(Cache[I].CurVersion) + " => " + Cache[I].CandVersion + "\n";
  421. }
  422. return ShowList(out,_("The following packages will be DOWNGRADED:"),List,VersionsList);
  423. }
  424. /*}}}*/
  425. // ShowHold - Show held but changed packages /*{{{*/
  426. // ---------------------------------------------------------------------
  427. /* */
  428. bool ShowHold(ostream &out,CacheFile &Cache)
  429. {
  430. string List;
  431. string VersionsList;
  432. for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
  433. {
  434. pkgCache::PkgIterator I(Cache,Cache.List[J]);
  435. if (Cache[I].InstallVer != (pkgCache::Version *)I.CurrentVer() &&
  436. I->SelectedState == pkgCache::State::Hold) {
  437. List += I.FullName(true) + " ";
  438. VersionsList += string(Cache[I].CurVersion) + " => " + Cache[I].CandVersion + "\n";
  439. }
  440. }
  441. return ShowList(out,_("The following held packages will be changed:"),List,VersionsList);
  442. }
  443. /*}}}*/
  444. // ShowEssential - Show an essential package warning /*{{{*/
  445. // ---------------------------------------------------------------------
  446. /* This prints out a warning message that is not to be ignored. It shows
  447. all essential packages and their dependents that are to be removed.
  448. It is insanely risky to remove the dependents of an essential package! */
  449. bool ShowEssential(ostream &out,CacheFile &Cache)
  450. {
  451. string List;
  452. string VersionsList;
  453. bool *Added = new bool[Cache->Head().PackageCount];
  454. for (unsigned int I = 0; I != Cache->Head().PackageCount; I++)
  455. Added[I] = false;
  456. for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
  457. {
  458. pkgCache::PkgIterator I(Cache,Cache.List[J]);
  459. if ((I->Flags & pkgCache::Flag::Essential) != pkgCache::Flag::Essential &&
  460. (I->Flags & pkgCache::Flag::Important) != pkgCache::Flag::Important)
  461. continue;
  462. // The essential package is being removed
  463. if (Cache[I].Delete() == true)
  464. {
  465. if (Added[I->ID] == false)
  466. {
  467. Added[I->ID] = true;
  468. List += I.FullName(true) + " ";
  469. //VersionsList += string(Cache[I].CurVersion) + "\n"; ???
  470. }
  471. }
  472. else
  473. continue;
  474. if (I->CurrentVer == 0)
  475. continue;
  476. // Print out any essential package depenendents that are to be removed
  477. for (pkgCache::DepIterator D = I.CurrentVer().DependsList(); D.end() == false; ++D)
  478. {
  479. // Skip everything but depends
  480. if (D->Type != pkgCache::Dep::PreDepends &&
  481. D->Type != pkgCache::Dep::Depends)
  482. continue;
  483. pkgCache::PkgIterator P = D.SmartTargetPkg();
  484. if (Cache[P].Delete() == true)
  485. {
  486. if (Added[P->ID] == true)
  487. continue;
  488. Added[P->ID] = true;
  489. char S[300];
  490. snprintf(S,sizeof(S),_("%s (due to %s) "),P.FullName(true).c_str(),I.FullName(true).c_str());
  491. List += S;
  492. //VersionsList += "\n"; ???
  493. }
  494. }
  495. }
  496. delete [] Added;
  497. return ShowList(out,_("WARNING: The following essential packages will be removed.\n"
  498. "This should NOT be done unless you know exactly what you are doing!"),List,VersionsList);
  499. }
  500. /*}}}*/
  501. // Stats - Show some statistics /*{{{*/
  502. // ---------------------------------------------------------------------
  503. /* */
  504. void Stats(ostream &out,pkgDepCache &Dep)
  505. {
  506. unsigned long Upgrade = 0;
  507. unsigned long Downgrade = 0;
  508. unsigned long Install = 0;
  509. unsigned long ReInstall = 0;
  510. for (pkgCache::PkgIterator I = Dep.PkgBegin(); I.end() == false; ++I)
  511. {
  512. if (Dep[I].NewInstall() == true)
  513. Install++;
  514. else
  515. {
  516. if (Dep[I].Upgrade() == true)
  517. Upgrade++;
  518. else
  519. if (Dep[I].Downgrade() == true)
  520. Downgrade++;
  521. }
  522. if (Dep[I].Delete() == false && (Dep[I].iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
  523. ReInstall++;
  524. }
  525. ioprintf(out,_("%lu upgraded, %lu newly installed, "),
  526. Upgrade,Install);
  527. if (ReInstall != 0)
  528. ioprintf(out,_("%lu reinstalled, "),ReInstall);
  529. if (Downgrade != 0)
  530. ioprintf(out,_("%lu downgraded, "),Downgrade);
  531. ioprintf(out,_("%lu to remove and %lu not upgraded.\n"),
  532. Dep.DelCount(),Dep.KeepCount());
  533. if (Dep.BadCount() != 0)
  534. ioprintf(out,_("%lu not fully installed or removed.\n"),
  535. Dep.BadCount());
  536. }
  537. /*}}}*/
  538. // CacheSetHelperAPTGet - responsible for message telling from the CacheSets/*{{{*/
  539. class CacheSetHelperAPTGet : public APT::CacheSetHelper {
  540. /** \brief stream message should be printed to */
  541. std::ostream &out;
  542. /** \brief were things like Task or RegEx used to select packages? */
  543. bool explicitlyNamed;
  544. APT::PackageSet virtualPkgs;
  545. public:
  546. std::list<std::pair<pkgCache::VerIterator, std::string> > selectedByRelease;
  547. CacheSetHelperAPTGet(std::ostream &out) : APT::CacheSetHelper(true), out(out) {
  548. explicitlyNamed = true;
  549. }
  550. virtual void showTaskSelection(APT::PackageSet const &pkgset, string const &pattern) {
  551. for (APT::PackageSet::const_iterator Pkg = pkgset.begin(); Pkg != pkgset.end(); ++Pkg)
  552. ioprintf(out, _("Note, selecting '%s' for task '%s'\n"),
  553. Pkg.FullName(true).c_str(), pattern.c_str());
  554. explicitlyNamed = false;
  555. }
  556. virtual void showRegExSelection(APT::PackageSet const &pkgset, string const &pattern) {
  557. for (APT::PackageSet::const_iterator Pkg = pkgset.begin(); Pkg != pkgset.end(); ++Pkg)
  558. ioprintf(out, _("Note, selecting '%s' for regex '%s'\n"),
  559. Pkg.FullName(true).c_str(), pattern.c_str());
  560. explicitlyNamed = false;
  561. }
  562. virtual void showSelectedVersion(pkgCache::PkgIterator const &Pkg, pkgCache::VerIterator const Ver,
  563. string const &ver, bool const &verIsRel) {
  564. if (ver == Ver.VerStr())
  565. return;
  566. selectedByRelease.push_back(make_pair(Ver, ver));
  567. }
  568. bool showVirtualPackageErrors(pkgCacheFile &Cache) {
  569. if (virtualPkgs.empty() == true)
  570. return true;
  571. for (APT::PackageSet::const_iterator Pkg = virtualPkgs.begin();
  572. Pkg != virtualPkgs.end(); ++Pkg) {
  573. if (Pkg->ProvidesList != 0) {
  574. ioprintf(c1out,_("Package %s is a virtual package provided by:\n"),
  575. Pkg.FullName(true).c_str());
  576. pkgCache::PrvIterator I = Pkg.ProvidesList();
  577. unsigned short provider = 0;
  578. for (; I.end() == false; ++I) {
  579. pkgCache::PkgIterator Pkg = I.OwnerPkg();
  580. if (Cache[Pkg].CandidateVerIter(Cache) == I.OwnerVer()) {
  581. out << " " << Pkg.FullName(true) << " " << I.OwnerVer().VerStr();
  582. if (Cache[Pkg].Install() == true && Cache[Pkg].NewInstall() == false)
  583. out << _(" [Installed]");
  584. out << endl;
  585. ++provider;
  586. }
  587. }
  588. // if we found no candidate which provide this package, show non-candidates
  589. if (provider == 0)
  590. for (I = Pkg.ProvidesList(); I.end() == false; ++I)
  591. out << " " << I.OwnerPkg().FullName(true) << " " << I.OwnerVer().VerStr()
  592. << _(" [Not candidate version]") << endl;
  593. else
  594. out << _("You should explicitly select one to install.") << endl;
  595. } else {
  596. ioprintf(out,
  597. _("Package %s is not available, but is referred to by another package.\n"
  598. "This may mean that the package is missing, has been obsoleted, or\n"
  599. "is only available from another source\n"),Pkg.FullName(true).c_str());
  600. string List;
  601. string VersionsList;
  602. SPtrArray<bool> Seen = new bool[Cache.GetPkgCache()->Head().PackageCount];
  603. memset(Seen,0,Cache.GetPkgCache()->Head().PackageCount*sizeof(*Seen));
  604. for (pkgCache::DepIterator Dep = Pkg.RevDependsList();
  605. Dep.end() == false; ++Dep) {
  606. if (Dep->Type != pkgCache::Dep::Replaces)
  607. continue;
  608. if (Seen[Dep.ParentPkg()->ID] == true)
  609. continue;
  610. Seen[Dep.ParentPkg()->ID] = true;
  611. List += Dep.ParentPkg().FullName(true) + " ";
  612. //VersionsList += string(Dep.ParentPkg().CurVersion) + "\n"; ???
  613. }
  614. ShowList(out,_("However the following packages replace it:"),List,VersionsList);
  615. }
  616. out << std::endl;
  617. }
  618. return false;
  619. }
  620. virtual pkgCache::VerIterator canNotFindCandidateVer(pkgCacheFile &Cache, pkgCache::PkgIterator const &Pkg) {
  621. APT::VersionSet const verset = tryVirtualPackage(Cache, Pkg, APT::VersionSet::CANDIDATE);
  622. if (verset.empty() == false)
  623. return *(verset.begin());
  624. if (ShowError == true) {
  625. _error->Error(_("Package '%s' has no installation candidate"),Pkg.FullName(true).c_str());
  626. virtualPkgs.insert(Pkg);
  627. }
  628. return pkgCache::VerIterator(Cache, 0);
  629. }
  630. virtual pkgCache::VerIterator canNotFindNewestVer(pkgCacheFile &Cache, pkgCache::PkgIterator const &Pkg) {
  631. APT::VersionSet const verset = tryVirtualPackage(Cache, Pkg, APT::VersionSet::NEWEST);
  632. if (verset.empty() == false)
  633. return *(verset.begin());
  634. if (ShowError == true)
  635. ioprintf(out, _("Virtual packages like '%s' can't be removed\n"), Pkg.FullName(true).c_str());
  636. return pkgCache::VerIterator(Cache, 0);
  637. }
  638. APT::VersionSet tryVirtualPackage(pkgCacheFile &Cache, pkgCache::PkgIterator const &Pkg,
  639. APT::VersionSet::Version const &select) {
  640. /* This is a pure virtual package and there is a single available
  641. candidate providing it. */
  642. if (unlikely(Cache[Pkg].CandidateVer != 0) || Pkg->ProvidesList == 0)
  643. return APT::VersionSet();
  644. pkgCache::PkgIterator Prov;
  645. bool found_one = false;
  646. for (pkgCache::PrvIterator P = Pkg.ProvidesList(); P; ++P) {
  647. pkgCache::VerIterator const PVer = P.OwnerVer();
  648. pkgCache::PkgIterator const PPkg = PVer.ParentPkg();
  649. /* Ignore versions that are not a candidate. */
  650. if (Cache[PPkg].CandidateVer != PVer)
  651. continue;
  652. if (found_one == false) {
  653. Prov = PPkg;
  654. found_one = true;
  655. } else if (PPkg != Prov) {
  656. found_one = false; // we found at least two
  657. break;
  658. }
  659. }
  660. if (found_one == true) {
  661. ioprintf(out, _("Note, selecting '%s' instead of '%s'\n"),
  662. Prov.FullName(true).c_str(), Pkg.FullName(true).c_str());
  663. return APT::VersionSet::FromPackage(Cache, Prov, select, *this);
  664. }
  665. return APT::VersionSet();
  666. }
  667. inline bool allPkgNamedExplicitly() const { return explicitlyNamed; }
  668. };
  669. /*}}}*/
  670. // TryToInstall - Mark a package for installation /*{{{*/
  671. struct TryToInstall {
  672. pkgCacheFile* Cache;
  673. pkgProblemResolver* Fix;
  674. bool FixBroken;
  675. unsigned long AutoMarkChanged;
  676. APT::PackageSet doAutoInstallLater;
  677. TryToInstall(pkgCacheFile &Cache, pkgProblemResolver *PM, bool const &FixBroken) : Cache(&Cache), Fix(PM),
  678. FixBroken(FixBroken), AutoMarkChanged(0) {};
  679. void operator() (pkgCache::VerIterator const &Ver) {
  680. pkgCache::PkgIterator Pkg = Ver.ParentPkg();
  681. Cache->GetDepCache()->SetCandidateVersion(Ver);
  682. pkgDepCache::StateCache &State = (*Cache)[Pkg];
  683. // Handle the no-upgrade case
  684. if (_config->FindB("APT::Get::upgrade",true) == false && Pkg->CurrentVer != 0)
  685. ioprintf(c1out,_("Skipping %s, it is already installed and upgrade is not set.\n"),
  686. Pkg.FullName(true).c_str());
  687. // Ignore request for install if package would be new
  688. else if (_config->FindB("APT::Get::Only-Upgrade", false) == true && Pkg->CurrentVer == 0)
  689. ioprintf(c1out,_("Skipping %s, it is not installed and only upgrades are requested.\n"),
  690. Pkg.FullName(true).c_str());
  691. else {
  692. if (Fix != NULL) {
  693. Fix->Clear(Pkg);
  694. Fix->Protect(Pkg);
  695. }
  696. Cache->GetDepCache()->MarkInstall(Pkg,false);
  697. if (State.Install() == false) {
  698. if (_config->FindB("APT::Get::ReInstall",false) == true) {
  699. if (Pkg->CurrentVer == 0 || Pkg.CurrentVer().Downloadable() == false)
  700. ioprintf(c1out,_("Reinstallation of %s is not possible, it cannot be downloaded.\n"),
  701. Pkg.FullName(true).c_str());
  702. else
  703. Cache->GetDepCache()->SetReInstall(Pkg, true);
  704. } else
  705. ioprintf(c1out,_("%s is already the newest version.\n"),
  706. Pkg.FullName(true).c_str());
  707. }
  708. // Install it with autoinstalling enabled (if we not respect the minial
  709. // required deps or the policy)
  710. if (FixBroken == false)
  711. doAutoInstallLater.insert(Pkg);
  712. }
  713. // see if we need to fix the auto-mark flag
  714. // e.g. apt-get install foo
  715. // where foo is marked automatic
  716. if (State.Install() == false &&
  717. (State.Flags & pkgCache::Flag::Auto) &&
  718. _config->FindB("APT::Get::ReInstall",false) == false &&
  719. _config->FindB("APT::Get::Only-Upgrade",false) == false &&
  720. _config->FindB("APT::Get::Download-Only",false) == false)
  721. {
  722. ioprintf(c1out,_("%s set to manually installed.\n"),
  723. Pkg.FullName(true).c_str());
  724. Cache->GetDepCache()->MarkAuto(Pkg,false);
  725. AutoMarkChanged++;
  726. }
  727. }
  728. bool propergateReleaseCandiateSwitching(std::list<std::pair<pkgCache::VerIterator, std::string> > start, std::ostream &out)
  729. {
  730. for (std::list<std::pair<pkgCache::VerIterator, std::string> >::const_iterator s = start.begin();
  731. s != start.end(); ++s)
  732. Cache->GetDepCache()->SetCandidateVersion(s->first);
  733. bool Success = true;
  734. std::list<std::pair<pkgCache::VerIterator, pkgCache::VerIterator> > Changed;
  735. for (std::list<std::pair<pkgCache::VerIterator, std::string> >::const_iterator s = start.begin();
  736. s != start.end(); ++s)
  737. {
  738. Changed.push_back(std::make_pair(s->first, pkgCache::VerIterator(*Cache)));
  739. // We continue here even if it failed to enhance the ShowBroken output
  740. Success &= Cache->GetDepCache()->SetCandidateRelease(s->first, s->second, Changed);
  741. }
  742. for (std::list<std::pair<pkgCache::VerIterator, pkgCache::VerIterator> >::const_iterator c = Changed.begin();
  743. c != Changed.end(); ++c)
  744. {
  745. if (c->second.end() == true)
  746. ioprintf(out, _("Selected version '%s' (%s) for '%s'\n"),
  747. c->first.VerStr(), c->first.RelStr().c_str(), c->first.ParentPkg().FullName(true).c_str());
  748. else if (c->first.ParentPkg()->Group != c->second.ParentPkg()->Group)
  749. {
  750. pkgCache::VerIterator V = (*Cache)[c->first.ParentPkg()].CandidateVerIter(*Cache);
  751. ioprintf(out, _("Selected version '%s' (%s) for '%s' because of '%s'\n"), V.VerStr(),
  752. V.RelStr().c_str(), V.ParentPkg().FullName(true).c_str(), c->second.ParentPkg().FullName(true).c_str());
  753. }
  754. }
  755. return Success;
  756. }
  757. void doAutoInstall() {
  758. for (APT::PackageSet::const_iterator P = doAutoInstallLater.begin();
  759. P != doAutoInstallLater.end(); ++P) {
  760. pkgDepCache::StateCache &State = (*Cache)[P];
  761. if (State.InstBroken() == false && State.InstPolicyBroken() == false)
  762. continue;
  763. Cache->GetDepCache()->MarkInstall(P, true);
  764. }
  765. doAutoInstallLater.clear();
  766. }
  767. };
  768. /*}}}*/
  769. // TryToRemove - Mark a package for removal /*{{{*/
  770. struct TryToRemove {
  771. pkgCacheFile* Cache;
  772. pkgProblemResolver* Fix;
  773. bool PurgePkgs;
  774. TryToRemove(pkgCacheFile &Cache, pkgProblemResolver *PM) : Cache(&Cache), Fix(PM),
  775. PurgePkgs(_config->FindB("APT::Get::Purge", false)) {};
  776. void operator() (pkgCache::VerIterator const &Ver)
  777. {
  778. pkgCache::PkgIterator Pkg = Ver.ParentPkg();
  779. if (Fix != NULL)
  780. {
  781. Fix->Clear(Pkg);
  782. Fix->Protect(Pkg);
  783. Fix->Remove(Pkg);
  784. }
  785. if ((Pkg->CurrentVer == 0 && PurgePkgs == false) ||
  786. (PurgePkgs == true && Pkg->CurrentState == pkgCache::State::NotInstalled))
  787. {
  788. ioprintf(c1out,_("Package %s is not installed, so not removed\n"),Pkg.FullName(true).c_str());
  789. // MarkInstall refuses to install packages on hold
  790. Pkg->SelectedState = pkgCache::State::Hold;
  791. }
  792. else
  793. Cache->GetDepCache()->MarkDelete(Pkg, PurgePkgs);
  794. }
  795. };
  796. /*}}}*/
  797. // CacheFile::NameComp - QSort compare by name /*{{{*/
  798. // ---------------------------------------------------------------------
  799. /* */
  800. pkgCache *CacheFile::SortCache = 0;
  801. int CacheFile::NameComp(const void *a,const void *b)
  802. {
  803. if (*(pkgCache::Package **)a == 0 || *(pkgCache::Package **)b == 0)
  804. return *(pkgCache::Package **)a - *(pkgCache::Package **)b;
  805. const pkgCache::Package &A = **(pkgCache::Package **)a;
  806. const pkgCache::Package &B = **(pkgCache::Package **)b;
  807. return strcmp(SortCache->StrP + A.Name,SortCache->StrP + B.Name);
  808. }
  809. /*}}}*/
  810. // CacheFile::Sort - Sort by name /*{{{*/
  811. // ---------------------------------------------------------------------
  812. /* */
  813. void CacheFile::Sort()
  814. {
  815. delete [] List;
  816. List = new pkgCache::Package *[Cache->Head().PackageCount];
  817. memset(List,0,sizeof(*List)*Cache->Head().PackageCount);
  818. pkgCache::PkgIterator I = Cache->PkgBegin();
  819. for (;I.end() != true; ++I)
  820. List[I->ID] = I;
  821. SortCache = *this;
  822. qsort(List,Cache->Head().PackageCount,sizeof(*List),NameComp);
  823. }
  824. /*}}}*/
  825. // CacheFile::CheckDeps - Open the cache file /*{{{*/
  826. // ---------------------------------------------------------------------
  827. /* This routine generates the caches and then opens the dependency cache
  828. and verifies that the system is OK. */
  829. bool CacheFile::CheckDeps(bool AllowBroken)
  830. {
  831. bool FixBroken = _config->FindB("APT::Get::Fix-Broken",false);
  832. if (_error->PendingError() == true)
  833. return false;
  834. // Check that the system is OK
  835. if (DCache->DelCount() != 0 || DCache->InstCount() != 0)
  836. return _error->Error("Internal error, non-zero counts");
  837. // Apply corrections for half-installed packages
  838. if (pkgApplyStatus(*DCache) == false)
  839. return false;
  840. if (_config->FindB("APT::Get::Fix-Policy-Broken",false) == true)
  841. {
  842. FixBroken = true;
  843. if ((DCache->PolicyBrokenCount() > 0))
  844. {
  845. // upgrade all policy-broken packages with ForceImportantDeps=True
  846. for (pkgCache::PkgIterator I = Cache->PkgBegin(); !I.end(); ++I)
  847. if ((*DCache)[I].NowPolicyBroken() == true)
  848. DCache->MarkInstall(I,true,0, false, true);
  849. }
  850. }
  851. // Nothing is broken
  852. if (DCache->BrokenCount() == 0 || AllowBroken == true)
  853. return true;
  854. // Attempt to fix broken things
  855. if (FixBroken == true)
  856. {
  857. c1out << _("Correcting dependencies...") << flush;
  858. if (pkgFixBroken(*DCache) == false || DCache->BrokenCount() != 0)
  859. {
  860. c1out << _(" failed.") << endl;
  861. ShowBroken(c1out,*this,true);
  862. return _error->Error(_("Unable to correct dependencies"));
  863. }
  864. if (pkgMinimizeUpgrade(*DCache) == false)
  865. return _error->Error(_("Unable to minimize the upgrade set"));
  866. c1out << _(" Done") << endl;
  867. }
  868. else
  869. {
  870. c1out << _("You might want to run 'apt-get -f install' to correct these.") << endl;
  871. ShowBroken(c1out,*this,true);
  872. return _error->Error(_("Unmet dependencies. Try using -f."));
  873. }
  874. return true;
  875. }
  876. /*}}}*/
  877. // CheckAuth - check if each download comes form a trusted source /*{{{*/
  878. // ---------------------------------------------------------------------
  879. /* */
  880. static bool CheckAuth(pkgAcquire& Fetcher)
  881. {
  882. string UntrustedList;
  883. for (pkgAcquire::ItemIterator I = Fetcher.ItemsBegin(); I < Fetcher.ItemsEnd(); ++I)
  884. {
  885. if (!(*I)->IsTrusted())
  886. {
  887. UntrustedList += string((*I)->ShortDesc()) + " ";
  888. }
  889. }
  890. if (UntrustedList == "")
  891. {
  892. return true;
  893. }
  894. ShowList(c2out,_("WARNING: The following packages cannot be authenticated!"),UntrustedList,"");
  895. if (_config->FindB("APT::Get::AllowUnauthenticated",false) == true)
  896. {
  897. c2out << _("Authentication warning overridden.\n");
  898. return true;
  899. }
  900. if (_config->FindI("quiet",0) < 2
  901. && _config->FindB("APT::Get::Assume-Yes",false) == false)
  902. {
  903. c2out << _("Install these packages without verification [y/N]? ") << flush;
  904. if (!YnPrompt(false))
  905. return _error->Error(_("Some packages could not be authenticated"));
  906. return true;
  907. }
  908. else if (_config->FindB("APT::Get::Force-Yes",false) == true)
  909. {
  910. return true;
  911. }
  912. return _error->Error(_("There are problems and -y was used without --force-yes"));
  913. }
  914. /*}}}*/
  915. // InstallPackages - Actually download and install the packages /*{{{*/
  916. // ---------------------------------------------------------------------
  917. /* This displays the informative messages describing what is going to
  918. happen and then calls the download routines */
  919. bool InstallPackages(CacheFile &Cache,bool ShwKept,bool Ask = true,
  920. bool Safety = true)
  921. {
  922. if (_config->FindB("APT::Get::Purge",false) == true)
  923. {
  924. pkgCache::PkgIterator I = Cache->PkgBegin();
  925. for (; I.end() == false; ++I)
  926. {
  927. if (I.Purge() == false && Cache[I].Mode == pkgDepCache::ModeDelete)
  928. Cache->MarkDelete(I,true);
  929. }
  930. }
  931. bool Fail = false;
  932. bool Essential = false;
  933. // Show all the various warning indicators
  934. ShowDel(c1out,Cache);
  935. ShowNew(c1out,Cache);
  936. if (ShwKept == true)
  937. ShowKept(c1out,Cache);
  938. Fail |= !ShowHold(c1out,Cache);
  939. if (_config->FindB("APT::Get::Show-Upgraded",true) == true)
  940. ShowUpgraded(c1out,Cache);
  941. Fail |= !ShowDowngraded(c1out,Cache);
  942. if (_config->FindB("APT::Get::Download-Only",false) == false)
  943. Essential = !ShowEssential(c1out,Cache);
  944. Fail |= Essential;
  945. Stats(c1out,Cache);
  946. // Sanity check
  947. if (Cache->BrokenCount() != 0)
  948. {
  949. ShowBroken(c1out,Cache,false);
  950. return _error->Error(_("Internal error, InstallPackages was called with broken packages!"));
  951. }
  952. if (Cache->DelCount() == 0 && Cache->InstCount() == 0 &&
  953. Cache->BadCount() == 0)
  954. return true;
  955. // No remove flag
  956. if (Cache->DelCount() != 0 && _config->FindB("APT::Get::Remove",true) == false)
  957. return _error->Error(_("Packages need to be removed but remove is disabled."));
  958. // Run the simulator ..
  959. if (_config->FindB("APT::Get::Simulate") == true)
  960. {
  961. pkgSimulate PM(Cache);
  962. int status_fd = _config->FindI("APT::Status-Fd",-1);
  963. pkgPackageManager::OrderResult Res = PM.DoInstall(status_fd);
  964. if (Res == pkgPackageManager::Failed)
  965. return false;
  966. if (Res != pkgPackageManager::Completed)
  967. return _error->Error(_("Internal error, Ordering didn't finish"));
  968. return true;
  969. }
  970. // Create the text record parser
  971. pkgRecords Recs(Cache);
  972. if (_error->PendingError() == true)
  973. return false;
  974. // Create the download object
  975. pkgAcquire Fetcher;
  976. AcqTextStatus Stat(ScreenWidth,_config->FindI("quiet",0));
  977. if (_config->FindB("APT::Get::Print-URIs", false) == true)
  978. {
  979. // force a hashsum for compatibility reasons
  980. _config->CndSet("Acquire::ForceHash", "md5sum");
  981. }
  982. else if (Fetcher.Setup(&Stat, _config->FindDir("Dir::Cache::Archives")) == false)
  983. return false;
  984. // Read the source list
  985. if (Cache.BuildSourceList() == false)
  986. return false;
  987. pkgSourceList *List = Cache.GetSourceList();
  988. // Create the package manager and prepare to download
  989. SPtr<pkgPackageManager> PM= _system->CreatePM(Cache);
  990. if (PM->GetArchives(&Fetcher,List,&Recs) == false ||
  991. _error->PendingError() == true)
  992. return false;
  993. // Display statistics
  994. unsigned long long FetchBytes = Fetcher.FetchNeeded();
  995. unsigned long long FetchPBytes = Fetcher.PartialPresent();
  996. unsigned long long DebBytes = Fetcher.TotalNeeded();
  997. if (DebBytes != Cache->DebSize())
  998. {
  999. c0out << DebBytes << ',' << Cache->DebSize() << endl;
  1000. c0out << _("How odd.. The sizes didn't match, email apt@packages.debian.org") << endl;
  1001. }
  1002. // Number of bytes
  1003. if (DebBytes != FetchBytes)
  1004. //TRANSLATOR: The required space between number and unit is already included
  1005. // in the replacement strings, so %sB will be correctly translate in e.g. 1,5 MB
  1006. ioprintf(c1out,_("Need to get %sB/%sB of archives.\n"),
  1007. SizeToStr(FetchBytes).c_str(),SizeToStr(DebBytes).c_str());
  1008. else if (DebBytes != 0)
  1009. //TRANSLATOR: The required space between number and unit is already included
  1010. // in the replacement string, so %sB will be correctly translate in e.g. 1,5 MB
  1011. ioprintf(c1out,_("Need to get %sB of archives.\n"),
  1012. SizeToStr(DebBytes).c_str());
  1013. // Size delta
  1014. if (Cache->UsrSize() >= 0)
  1015. //TRANSLATOR: The required space between number and unit is already included
  1016. // in the replacement string, so %sB will be correctly translate in e.g. 1,5 MB
  1017. ioprintf(c1out,_("After this operation, %sB of additional disk space will be used.\n"),
  1018. SizeToStr(Cache->UsrSize()).c_str());
  1019. else
  1020. //TRANSLATOR: The required space between number and unit is already included
  1021. // in the replacement string, so %sB will be correctly translate in e.g. 1,5 MB
  1022. ioprintf(c1out,_("After this operation, %sB disk space will be freed.\n"),
  1023. SizeToStr(-1*Cache->UsrSize()).c_str());
  1024. if (_error->PendingError() == true)
  1025. return false;
  1026. /* Check for enough free space, but only if we are actually going to
  1027. download */
  1028. if (_config->FindB("APT::Get::Print-URIs") == false &&
  1029. _config->FindB("APT::Get::Download",true) == true)
  1030. {
  1031. struct statvfs Buf;
  1032. string OutputDir = _config->FindDir("Dir::Cache::Archives");
  1033. if (statvfs(OutputDir.c_str(),&Buf) != 0) {
  1034. if (errno == EOVERFLOW)
  1035. return _error->WarningE("statvfs",_("Couldn't determine free space in %s"),
  1036. OutputDir.c_str());
  1037. else
  1038. return _error->Errno("statvfs",_("Couldn't determine free space in %s"),
  1039. OutputDir.c_str());
  1040. } else if (unsigned(Buf.f_bfree) < (FetchBytes - FetchPBytes)/Buf.f_bsize)
  1041. {
  1042. struct statfs Stat;
  1043. if (statfs(OutputDir.c_str(),&Stat) != 0
  1044. #if HAVE_STRUCT_STATFS_F_TYPE
  1045. || unsigned(Stat.f_type) != RAMFS_MAGIC
  1046. #endif
  1047. )
  1048. return _error->Error(_("You don't have enough free space in %s."),
  1049. OutputDir.c_str());
  1050. }
  1051. }
  1052. // Fail safe check
  1053. if (_config->FindI("quiet",0) >= 2 ||
  1054. _config->FindB("APT::Get::Assume-Yes",false) == true)
  1055. {
  1056. if (Fail == true && _config->FindB("APT::Get::Force-Yes",false) == false)
  1057. return _error->Error(_("There are problems and -y was used without --force-yes"));
  1058. }
  1059. if (Essential == true && Safety == true)
  1060. {
  1061. if (_config->FindB("APT::Get::Trivial-Only",false) == true)
  1062. return _error->Error(_("Trivial Only specified but this is not a trivial operation."));
  1063. const char *Prompt = _("Yes, do as I say!");
  1064. ioprintf(c2out,
  1065. _("You are about to do something potentially harmful.\n"
  1066. "To continue type in the phrase '%s'\n"
  1067. " ?] "),Prompt);
  1068. c2out << flush;
  1069. if (AnalPrompt(Prompt) == false)
  1070. {
  1071. c2out << _("Abort.") << endl;
  1072. exit(1);
  1073. }
  1074. }
  1075. else
  1076. {
  1077. // Prompt to continue
  1078. if (Ask == true || Fail == true)
  1079. {
  1080. if (_config->FindB("APT::Get::Trivial-Only",false) == true)
  1081. return _error->Error(_("Trivial Only specified but this is not a trivial operation."));
  1082. if (_config->FindI("quiet",0) < 2 &&
  1083. _config->FindB("APT::Get::Assume-Yes",false) == false)
  1084. {
  1085. c2out << _("Do you want to continue [Y/n]? ") << flush;
  1086. if (YnPrompt() == false)
  1087. {
  1088. c2out << _("Abort.") << endl;
  1089. exit(1);
  1090. }
  1091. }
  1092. }
  1093. }
  1094. // Just print out the uris an exit if the --print-uris flag was used
  1095. if (_config->FindB("APT::Get::Print-URIs") == true)
  1096. {
  1097. pkgAcquire::UriIterator I = Fetcher.UriBegin();
  1098. for (; I != Fetcher.UriEnd(); ++I)
  1099. cout << '\'' << I->URI << "' " << flNotDir(I->Owner->DestFile) << ' ' <<
  1100. I->Owner->FileSize << ' ' << I->Owner->HashSum() << endl;
  1101. return true;
  1102. }
  1103. if (!CheckAuth(Fetcher))
  1104. return false;
  1105. /* Unlock the dpkg lock if we are not going to be doing an install
  1106. after. */
  1107. if (_config->FindB("APT::Get::Download-Only",false) == true)
  1108. _system->UnLock();
  1109. // Run it
  1110. while (1)
  1111. {
  1112. bool Transient = false;
  1113. if (_config->FindB("APT::Get::Download",true) == false)
  1114. {
  1115. for (pkgAcquire::ItemIterator I = Fetcher.ItemsBegin(); I < Fetcher.ItemsEnd();)
  1116. {
  1117. if ((*I)->Local == true)
  1118. {
  1119. ++I;
  1120. continue;
  1121. }
  1122. // Close the item and check if it was found in cache
  1123. (*I)->Finished();
  1124. if ((*I)->Complete == false)
  1125. Transient = true;
  1126. // Clear it out of the fetch list
  1127. delete *I;
  1128. I = Fetcher.ItemsBegin();
  1129. }
  1130. }
  1131. if (Fetcher.Run() == pkgAcquire::Failed)
  1132. return false;
  1133. // Print out errors
  1134. bool Failed = false;
  1135. for (pkgAcquire::ItemIterator I = Fetcher.ItemsBegin(); I != Fetcher.ItemsEnd(); ++I)
  1136. {
  1137. if ((*I)->Status == pkgAcquire::Item::StatDone &&
  1138. (*I)->Complete == true)
  1139. continue;
  1140. if ((*I)->Status == pkgAcquire::Item::StatIdle)
  1141. {
  1142. Transient = true;
  1143. // Failed = true;
  1144. continue;
  1145. }
  1146. fprintf(stderr,_("Failed to fetch %s %s\n"),(*I)->DescURI().c_str(),
  1147. (*I)->ErrorText.c_str());
  1148. Failed = true;
  1149. }
  1150. /* If we are in no download mode and missing files and there were
  1151. 'failures' then the user must specify -m. Furthermore, there
  1152. is no such thing as a transient error in no-download mode! */
  1153. if (Transient == true &&
  1154. _config->FindB("APT::Get::Download",true) == false)
  1155. {
  1156. Transient = false;
  1157. Failed = true;
  1158. }
  1159. if (_config->FindB("APT::Get::Download-Only",false) == true)
  1160. {
  1161. if (Failed == true && _config->FindB("APT::Get::Fix-Missing",false) == false)
  1162. return _error->Error(_("Some files failed to download"));
  1163. c1out << _("Download complete and in download only mode") << endl;
  1164. return true;
  1165. }
  1166. if (Failed == true && _config->FindB("APT::Get::Fix-Missing",false) == false)
  1167. {
  1168. return _error->Error(_("Unable to fetch some archives, maybe run apt-get update or try with --fix-missing?"));
  1169. }
  1170. if (Transient == true && Failed == true)
  1171. return _error->Error(_("--fix-missing and media swapping is not currently supported"));
  1172. // Try to deal with missing package files
  1173. if (Failed == true && PM->FixMissing() == false)
  1174. {
  1175. cerr << _("Unable to correct missing packages.") << endl;
  1176. return _error->Error(_("Aborting install."));
  1177. }
  1178. _system->UnLock();
  1179. int status_fd = _config->FindI("APT::Status-Fd",-1);
  1180. pkgPackageManager::OrderResult Res = PM->DoInstall(status_fd);
  1181. if (Res == pkgPackageManager::Failed || _error->PendingError() == true)
  1182. return false;
  1183. if (Res == pkgPackageManager::Completed)
  1184. break;
  1185. // Reload the fetcher object and loop again for media swapping
  1186. Fetcher.Shutdown();
  1187. if (PM->GetArchives(&Fetcher,List,&Recs) == false)
  1188. return false;
  1189. _system->Lock();
  1190. }
  1191. std::set<std::string> const disappearedPkgs = PM->GetDisappearedPackages();
  1192. if (disappearedPkgs.empty() == true)
  1193. return true;
  1194. string disappear;
  1195. for (std::set<std::string>::const_iterator d = disappearedPkgs.begin();
  1196. d != disappearedPkgs.end(); ++d)
  1197. disappear.append(*d).append(" ");
  1198. ShowList(c1out, P_("The following package disappeared from your system as\n"
  1199. "all files have been overwritten by other packages:",
  1200. "The following packages disappeared from your system as\n"
  1201. "all files have been overwritten by other packages:", disappearedPkgs.size()), disappear, "");
  1202. c0out << _("Note: This is done automatic and on purpose by dpkg.") << std::endl;
  1203. return true;
  1204. }
  1205. /*}}}*/
  1206. // TryToInstallBuildDep - Try to install a single package /*{{{*/
  1207. // ---------------------------------------------------------------------
  1208. /* This used to be inlined in DoInstall, but with the advent of regex package
  1209. name matching it was split out.. */
  1210. bool TryToInstallBuildDep(pkgCache::PkgIterator Pkg,pkgCacheFile &Cache,
  1211. pkgProblemResolver &Fix,bool Remove,bool BrokenFix,
  1212. bool AllowFail = true)
  1213. {
  1214. if (Cache[Pkg].CandidateVer == 0 && Pkg->ProvidesList != 0)
  1215. {
  1216. CacheSetHelperAPTGet helper(c1out);
  1217. helper.showErrors(AllowFail == false);
  1218. pkgCache::VerIterator Ver = helper.canNotFindNewestVer(Cache, Pkg);
  1219. if (Ver.end() == false)
  1220. Pkg = Ver.ParentPkg();
  1221. else if (helper.showVirtualPackageErrors(Cache) == false)
  1222. return AllowFail;
  1223. }
  1224. if (_config->FindB("Debug::BuildDeps",false) == true)
  1225. {
  1226. if (Remove == true)
  1227. cout << " Trying to remove " << Pkg << endl;
  1228. else
  1229. cout << " Trying to install " << Pkg << endl;
  1230. }
  1231. if (Remove == true)
  1232. {
  1233. TryToRemove RemoveAction(Cache, &Fix);
  1234. RemoveAction(Pkg.VersionList());
  1235. } else if (Cache[Pkg].CandidateVer != 0) {
  1236. TryToInstall InstallAction(Cache, &Fix, BrokenFix);
  1237. InstallAction(Cache[Pkg].CandidateVerIter(Cache));
  1238. InstallAction.doAutoInstall();
  1239. } else
  1240. return AllowFail;
  1241. return true;
  1242. }
  1243. /*}}}*/
  1244. // FindSrc - Find a source record /*{{{*/
  1245. // ---------------------------------------------------------------------
  1246. /* */
  1247. pkgSrcRecords::Parser *FindSrc(const char *Name,pkgRecords &Recs,
  1248. pkgSrcRecords &SrcRecs,string &Src,
  1249. pkgDepCache &Cache)
  1250. {
  1251. string VerTag;
  1252. string DefRel = _config->Find("APT::Default-Release");
  1253. string TmpSrc = Name;
  1254. // extract the version/release from the pkgname
  1255. const size_t found = TmpSrc.find_last_of("/=");
  1256. if (found != string::npos) {
  1257. if (TmpSrc[found] == '/')
  1258. DefRel = TmpSrc.substr(found+1);
  1259. else
  1260. VerTag = TmpSrc.substr(found+1);
  1261. TmpSrc = TmpSrc.substr(0,found);
  1262. }
  1263. /* Lookup the version of the package we would install if we were to
  1264. install a version and determine the source package name, then look
  1265. in the archive for a source package of the same name. */
  1266. bool MatchSrcOnly = _config->FindB("APT::Get::Only-Source");
  1267. const pkgCache::PkgIterator Pkg = Cache.FindPkg(TmpSrc);
  1268. if (MatchSrcOnly == false && Pkg.end() == false)
  1269. {
  1270. if(VerTag.empty() == false || DefRel.empty() == false)
  1271. {
  1272. bool fuzzy = false;
  1273. // we have a default release, try to locate the pkg. we do it like
  1274. // this because GetCandidateVer() will not "downgrade", that means
  1275. // "apt-get source -t stable apt" won't work on a unstable system
  1276. for (pkgCache::VerIterator Ver = Pkg.VersionList();; ++Ver)
  1277. {
  1278. // try first only exact matches, later fuzzy matches
  1279. if (Ver.end() == true)
  1280. {
  1281. if (fuzzy == true)
  1282. break;
  1283. fuzzy = true;
  1284. Ver = Pkg.VersionList();
  1285. // exit right away from the Pkg.VersionList() loop if we
  1286. // don't have any versions
  1287. if (Ver.end() == true)
  1288. break;
  1289. }
  1290. // We match against a concrete version (or a part of this version)
  1291. if (VerTag.empty() == false &&
  1292. (fuzzy == true || Cache.VS().CmpVersion(VerTag, Ver.VerStr()) != 0) && // exact match
  1293. (fuzzy == false || strncmp(VerTag.c_str(), Ver.VerStr(), VerTag.size()) != 0)) // fuzzy match
  1294. continue;
  1295. for (pkgCache::VerFileIterator VF = Ver.FileList();
  1296. VF.end() == false; ++VF)
  1297. {
  1298. /* If this is the status file, and the current version is not the
  1299. version in the status file (ie it is not installed, or somesuch)
  1300. then it is not a candidate for installation, ever. This weeds
  1301. out bogus entries that may be due to config-file states, or
  1302. other. */
  1303. if ((VF.File()->Flags & pkgCache::Flag::NotSource) ==
  1304. pkgCache::Flag::NotSource && Pkg.CurrentVer() != Ver)
  1305. continue;
  1306. // or we match against a release
  1307. if(VerTag.empty() == false ||
  1308. (VF.File().Archive() != 0 && VF.File().Archive() == DefRel) ||
  1309. (VF.File().Codename() != 0 && VF.File().Codename() == DefRel))
  1310. {
  1311. pkgRecords::Parser &Parse = Recs.Lookup(VF);
  1312. Src = Parse.SourcePkg();
  1313. // no SourcePkg name, so it is the "binary" name
  1314. if (Src.empty() == true)
  1315. Src = TmpSrc;
  1316. // the Version we have is possibly fuzzy or includes binUploads,
  1317. // so we use the Version of the SourcePkg (empty if same as package)
  1318. VerTag = Parse.SourceVer();
  1319. if (VerTag.empty() == true)
  1320. VerTag = Ver.VerStr();
  1321. break;
  1322. }
  1323. }
  1324. if (Src.empty() == false)
  1325. break;
  1326. }
  1327. if (Src.empty() == true)
  1328. {
  1329. // Sources files have no codename information
  1330. if (VerTag.empty() == true && DefRel.empty() == false)
  1331. {
  1332. _error->Error(_("Ignore unavailable target release '%s' of package '%s'"), DefRel.c_str(), TmpSrc.c_str());
  1333. return 0;
  1334. }
  1335. }
  1336. }
  1337. if (Src.empty() == true)
  1338. {
  1339. // if we don't have found a fitting package yet so we will
  1340. // choose a good candidate and proceed with that.
  1341. // Maybe we will find a source later on with the right VerTag
  1342. pkgCache::VerIterator Ver = Cache.GetCandidateVer(Pkg);
  1343. if (Ver.end() == false)
  1344. {
  1345. pkgRecords::Parser &Parse = Recs.Lookup(Ver.FileList());
  1346. Src = Parse.SourcePkg();
  1347. if (VerTag.empty() == true)
  1348. VerTag = Parse.SourceVer();
  1349. }
  1350. }
  1351. }
  1352. if (Src.empty() == true)
  1353. Src = TmpSrc;
  1354. else
  1355. {
  1356. /* if we have a source pkg name, make sure to only search
  1357. for srcpkg names, otherwise apt gets confused if there
  1358. is a binary package "pkg1" and a source package "pkg1"
  1359. with the same name but that comes from different packages */
  1360. MatchSrcOnly = true;
  1361. if (Src != TmpSrc)
  1362. {
  1363. ioprintf(c1out, _("Picking '%s' as source package instead of '%s'\n"), Src.c_str(), TmpSrc.c_str());
  1364. }
  1365. }
  1366. // The best hit
  1367. pkgSrcRecords::Parser *Last = 0;
  1368. unsigned long Offset = 0;
  1369. string Version;
  1370. /* Iterate over all of the hits, which includes the resulting
  1371. binary packages in the search */
  1372. pkgSrcRecords::Parser *Parse;
  1373. while (true)
  1374. {
  1375. SrcRecs.Restart();
  1376. while ((Parse = SrcRecs.Find(Src.c_str(), MatchSrcOnly)) != 0)
  1377. {
  1378. const string Ver = Parse->Version();
  1379. // Ignore all versions which doesn't fit
  1380. if (VerTag.empty() == false &&
  1381. Cache.VS().CmpVersion(VerTag, Ver) != 0) // exact match
  1382. continue;
  1383. // Newer version or an exact match? Save the hit
  1384. if (Last == 0 || Cache.VS().CmpVersion(Version,Ver) < 0) {
  1385. Last = Parse;
  1386. Offset = Parse->Offset();
  1387. Version = Ver;
  1388. }
  1389. // was the version check above an exact match? If so, we don't need to look further
  1390. if (VerTag.empty() == false && VerTag.size() == Ver.size())
  1391. break;
  1392. }
  1393. if (Last != 0 || VerTag.empty() == true)
  1394. break;
  1395. //if (VerTag.empty() == false && Last == 0)
  1396. _error->Error(_("Ignore unavailable version '%s' of package '%s'"), VerTag.c_str(), TmpSrc.c_str());
  1397. return 0;
  1398. }
  1399. if (Last == 0 || Last->Jump(Offset) == false)
  1400. return 0;
  1401. return Last;
  1402. }
  1403. /*}}}*/
  1404. // DoUpdate - Update the package lists /*{{{*/
  1405. // ---------------------------------------------------------------------
  1406. /* */
  1407. bool DoUpdate(CommandLine &CmdL)
  1408. {
  1409. if (CmdL.FileSize() != 1)
  1410. return _error->Error(_("The update command takes no arguments"));
  1411. CacheFile Cache;
  1412. // Get the source list
  1413. if (Cache.BuildSourceList() == false)
  1414. return false;
  1415. pkgSourceList *List = Cache.GetSourceList();
  1416. // Create the progress
  1417. AcqTextStatus Stat(ScreenWidth,_config->FindI("quiet",0));
  1418. // Just print out the uris an exit if the --print-uris flag was used
  1419. if (_config->FindB("APT::Get::Print-URIs") == true)
  1420. {
  1421. // force a hashsum for compatibility reasons
  1422. _config->CndSet("Acquire::ForceHash", "md5sum");
  1423. // get a fetcher
  1424. pkgAcquire Fetcher;
  1425. if (Fetcher.Setup(&Stat) == false)
  1426. return false;
  1427. // Populate it with the source selection and get all Indexes
  1428. // (GetAll=true)
  1429. if (List->GetIndexes(&Fetcher,true) == false)
  1430. return false;
  1431. pkgAcquire::UriIterator I = Fetcher.UriBegin();
  1432. for (; I != Fetcher.UriEnd(); ++I)
  1433. cout << '\'' << I->URI << "' " << flNotDir(I->Owner->DestFile) << ' ' <<
  1434. I->Owner->FileSize << ' ' << I->Owner->HashSum() << endl;
  1435. return true;
  1436. }
  1437. // do the work
  1438. if (_config->FindB("APT::Get::Download",true) == true)
  1439. ListUpdate(Stat, *List);
  1440. // Rebuild the cache.
  1441. pkgCacheFile::RemoveCaches();
  1442. if (Cache.BuildCaches() == false)
  1443. return false;
  1444. return true;
  1445. }
  1446. /*}}}*/
  1447. // DoAutomaticRemove - Remove all automatic unused packages /*{{{*/
  1448. // ---------------------------------------------------------------------
  1449. /* Remove unused automatic packages */
  1450. bool DoAutomaticRemove(CacheFile &Cache)
  1451. {
  1452. bool Debug = _config->FindI("Debug::pkgAutoRemove",false);
  1453. bool doAutoRemove = _config->FindB("APT::Get::AutomaticRemove", false);
  1454. bool hideAutoRemove = _config->FindB("APT::Get::HideAutoRemove");
  1455. pkgDepCache::ActionGroup group(*Cache);
  1456. if(Debug)
  1457. std::cout << "DoAutomaticRemove()" << std::endl;
  1458. if (doAutoRemove == true &&
  1459. _config->FindB("APT::Get::Remove",true) == false)
  1460. {
  1461. c1out << _("We are not supposed to delete stuff, can't start "
  1462. "AutoRemover") << std::endl;
  1463. return false;
  1464. }
  1465. bool purgePkgs = _config->FindB("APT::Get::Purge", false);
  1466. bool smallList = (hideAutoRemove == false &&
  1467. strcasecmp(_config->Find("APT::Get::HideAutoRemove","").c_str(),"small") == 0);
  1468. string autoremovelist, autoremoveversions;
  1469. unsigned long autoRemoveCount = 0;
  1470. APT::PackageSet tooMuch;
  1471. // look over the cache to see what can be removed
  1472. for (pkgCache::PkgIterator Pkg = Cache->PkgBegin(); ! Pkg.end(); ++Pkg)
  1473. {
  1474. if (Cache[Pkg].Garbage)
  1475. {
  1476. if(Pkg.CurrentVer() != 0 || Cache[Pkg].Install())
  1477. if(Debug)
  1478. std::cout << "We could delete %s" << Pkg.FullName(true).c_str() << std::endl;
  1479. if (doAutoRemove)
  1480. {
  1481. if(Pkg.CurrentVer() != 0 &&
  1482. Pkg->CurrentState != pkgCache::State::ConfigFiles)
  1483. Cache->MarkDelete(Pkg, purgePkgs);
  1484. else
  1485. Cache->MarkKeep(Pkg, false, false);
  1486. }
  1487. else
  1488. {
  1489. // if the package is a new install and already garbage we don't need to
  1490. // install it in the first place, so nuke it instead of show it
  1491. if (Cache[Pkg].Install() == true && Pkg.CurrentVer() == 0)
  1492. {
  1493. Cache->MarkDelete(Pkg, false);
  1494. tooMuch.insert(Pkg);
  1495. }
  1496. // only show stuff in the list that is not yet marked for removal
  1497. else if(hideAutoRemove == false && Cache[Pkg].Delete() == false)
  1498. {
  1499. ++autoRemoveCount;
  1500. // we don't need to fill the strings if we don't need them
  1501. if (smallList == false)
  1502. {
  1503. autoremovelist += Pkg.FullName(true) + " ";
  1504. autoremoveversions += string(Cache[Pkg].CandVersion) + "\n";
  1505. }
  1506. }
  1507. }
  1508. }
  1509. }
  1510. // we could have removed a new dependency of a garbage package,
  1511. // so check if a reverse depends is broken and if so install it again.
  1512. if (tooMuch.empty() == false && (Cache->BrokenCount() != 0 || Cache->PolicyBrokenCount() != 0))
  1513. {
  1514. bool Changed;
  1515. do {
  1516. Changed = false;
  1517. for (APT::PackageSet::const_iterator P = tooMuch.begin();
  1518. P != tooMuch.end() && Changed == false; ++P)
  1519. {
  1520. for (pkgCache::DepIterator R = P.RevDependsList();
  1521. R.end() == false; ++R)
  1522. {
  1523. if (R.IsNegative() == true ||
  1524. Cache->IsImportantDep(R) == false)
  1525. continue;
  1526. pkgCache::PkgIterator N = R.ParentPkg();
  1527. if (N.end() == true || (N->CurrentVer == 0 && (*Cache)[N].Install() == false))
  1528. continue;
  1529. if (Debug == true)
  1530. std::clog << "Save " << P << " as another installed garbage package depends on it" << std::endl;
  1531. Cache->MarkInstall(P, false);
  1532. if(hideAutoRemove == false)
  1533. {
  1534. ++autoRemoveCount;
  1535. if (smallList == false)
  1536. {
  1537. autoremovelist += P.FullName(true) + " ";
  1538. autoremoveversions += string(Cache[P].CandVersion) + "\n";
  1539. }
  1540. }
  1541. tooMuch.erase(P);
  1542. Changed = true;
  1543. break;
  1544. }
  1545. }
  1546. } while (Changed == true);
  1547. }
  1548. // Now see if we had destroyed anything (if we had done anything)
  1549. if (Cache->BrokenCount() != 0)
  1550. {
  1551. c1out << _("Hmm, seems like the AutoRemover destroyed something which really\n"
  1552. "shouldn't happen. Please file a bug report against apt.") << endl;
  1553. c1out << endl;
  1554. c1out << _("The following information may help to resolve the situation:") << endl;
  1555. c1out << endl;
  1556. ShowBroken(c1out,Cache,false);
  1557. return _error->Error(_("Internal Error, AutoRemover broke stuff"));
  1558. }
  1559. // if we don't remove them, we should show them!
  1560. if (doAutoRemove == false && (autoremovelist.empty() == false || autoRemoveCount != 0))
  1561. {
  1562. if (smallList == false)
  1563. ShowList(c1out, P_("The following package was automatically installed and is no longer required:",
  1564. "The following packages were automatically installed and are no longer required:",
  1565. autoRemoveCount), autoremovelist, autoremoveversions);
  1566. else
  1567. ioprintf(c1out, P_("%lu package was automatically installed and is no longer required.\n",
  1568. "%lu packages were automatically installed and are no longer required.\n", autoRemoveCount), autoRemoveCount);
  1569. c1out << _("Use 'apt-get autoremove' to remove them.") << std::endl;
  1570. }
  1571. return true;
  1572. }
  1573. /*}}}*/
  1574. // DoUpgrade - Upgrade all packages /*{{{*/
  1575. // ---------------------------------------------------------------------
  1576. /* Upgrade all packages without installing new packages or erasing old
  1577. packages */
  1578. bool DoUpgrade(CommandLine &CmdL)
  1579. {
  1580. CacheFile Cache;
  1581. if (Cache.OpenForInstall() == false || Cache.CheckDeps() == false)
  1582. return false;
  1583. // Do the upgrade
  1584. if (pkgAllUpgrade(Cache) == false)
  1585. {
  1586. ShowBroken(c1out,Cache,false);
  1587. return _error->Error(_("Internal error, AllUpgrade broke stuff"));
  1588. }
  1589. return InstallPackages(Cache,true);
  1590. }
  1591. /*}}}*/
  1592. // DoInstall - Install packages from the command line /*{{{*/
  1593. // ---------------------------------------------------------------------
  1594. /* Install named packages */
  1595. bool DoInstall(CommandLine &CmdL)
  1596. {
  1597. CacheFile Cache;
  1598. if (Cache.OpenForInstall() == false ||
  1599. Cache.CheckDeps(CmdL.FileSize() != 1) == false)
  1600. return false;
  1601. // Enter the special broken fixing mode if the user specified arguments
  1602. bool BrokenFix = false;
  1603. if (Cache->BrokenCount() != 0)
  1604. BrokenFix = true;
  1605. pkgProblemResolver* Fix = NULL;
  1606. if (_config->FindB("APT::Get::CallResolver", true) == true)
  1607. Fix = new pkgProblemResolver(Cache);
  1608. static const unsigned short MOD_REMOVE = 1;
  1609. static const unsigned short MOD_INSTALL = 2;
  1610. unsigned short fallback = MOD_INSTALL;
  1611. if (strcasecmp(CmdL.FileList[0],"remove") == 0)
  1612. fallback = MOD_REMOVE;
  1613. else if (strcasecmp(CmdL.FileList[0], "purge") == 0)
  1614. {
  1615. _config->Set("APT::Get::Purge", true);
  1616. fallback = MOD_REMOVE;
  1617. }
  1618. else if (strcasecmp(CmdL.FileList[0], "autoremove") == 0)
  1619. {
  1620. _config->Set("APT::Get::AutomaticRemove", "true");
  1621. fallback = MOD_REMOVE;
  1622. }
  1623. std::list<APT::VersionSet::Modifier> mods;
  1624. mods.push_back(APT::VersionSet::Modifier(MOD_INSTALL, "+",
  1625. APT::VersionSet::Modifier::POSTFIX, APT::VersionSet::CANDIDATE));
  1626. mods.push_back(APT::VersionSet::Modifier(MOD_REMOVE, "-",
  1627. APT::VersionSet::Modifier::POSTFIX, APT::VersionSet::NEWEST));
  1628. CacheSetHelperAPTGet helper(c0out);
  1629. std::map<unsigned short, APT::VersionSet> verset = APT::VersionSet::GroupedFromCommandLine(Cache,
  1630. CmdL.FileList + 1, mods, fallback, helper);
  1631. if (_error->PendingError() == true)
  1632. {
  1633. helper.showVirtualPackageErrors(Cache);
  1634. if (Fix != NULL)
  1635. delete Fix;
  1636. return false;
  1637. }
  1638. unsigned short const order[] = { MOD_REMOVE, MOD_INSTALL, 0 };
  1639. TryToInstall InstallAction(Cache, Fix, BrokenFix);
  1640. TryToRemove RemoveAction(Cache, Fix);
  1641. // new scope for the ActionGroup
  1642. {
  1643. pkgDepCache::ActionGroup group(Cache);
  1644. for (unsigned short i = 0; order[i] != 0; ++i)
  1645. {
  1646. if (order[i] == MOD_INSTALL)
  1647. InstallAction = std::for_each(verset[MOD_INSTALL].begin(), verset[MOD_INSTALL].end(), InstallAction);
  1648. else if (order[i] == MOD_REMOVE)
  1649. RemoveAction = std::for_each(verset[MOD_REMOVE].begin(), verset[MOD_REMOVE].end(), RemoveAction);
  1650. }
  1651. if (Fix != NULL && _config->FindB("APT::Get::AutoSolving", true) == true)
  1652. {
  1653. for (unsigned short i = 0; order[i] != 0; ++i)
  1654. {
  1655. if (order[i] != MOD_INSTALL)
  1656. continue;
  1657. InstallAction.propergateReleaseCandiateSwitching(helper.selectedByRelease, c0out);
  1658. InstallAction.doAutoInstall();
  1659. }
  1660. }
  1661. if (_error->PendingError() == true)
  1662. {
  1663. if (Fix != NULL)
  1664. delete Fix;
  1665. return false;
  1666. }
  1667. /* If we are in the Broken fixing mode we do not attempt to fix the
  1668. problems. This is if the user invoked install without -f and gave
  1669. packages */
  1670. if (BrokenFix == true && Cache->BrokenCount() != 0)
  1671. {
  1672. c1out << _("You might want to run 'apt-get -f install' to correct these:") << endl;
  1673. ShowBroken(c1out,Cache,false);
  1674. if (Fix != NULL)
  1675. delete Fix;
  1676. return _error->Error(_("Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution)."));
  1677. }
  1678. if (Fix != NULL)
  1679. {
  1680. // Call the scored problem resolver
  1681. Fix->InstallProtect();
  1682. if (Fix->Resolve(true) == false)
  1683. _error->Discard();
  1684. delete Fix;
  1685. }
  1686. // Now we check the state of the packages,
  1687. if (Cache->BrokenCount() != 0)
  1688. {
  1689. c1out <<
  1690. _("Some packages could not be installed. This may mean that you have\n"
  1691. "requested an impossible situation or if you are using the unstable\n"
  1692. "distribution that some required packages have not yet been created\n"
  1693. "or been moved out of Incoming.") << endl;
  1694. /*
  1695. if (Packages == 1)
  1696. {
  1697. c1out << endl;
  1698. c1out <<
  1699. _("Since you only requested a single operation it is extremely likely that\n"
  1700. "the package is simply not installable and a bug report against\n"
  1701. "that package should be filed.") << endl;
  1702. }
  1703. */
  1704. c1out << _("The following information may help to resolve the situation:") << endl;
  1705. c1out << endl;
  1706. ShowBroken(c1out,Cache,false);
  1707. return _error->Error(_("Broken packages"));
  1708. }
  1709. }
  1710. if (!DoAutomaticRemove(Cache))
  1711. return false;
  1712. /* Print out a list of packages that are going to be installed extra
  1713. to what the user asked */
  1714. if (Cache->InstCount() != verset[MOD_INSTALL].size())
  1715. {
  1716. string List;
  1717. string VersionsList;
  1718. for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
  1719. {
  1720. pkgCache::PkgIterator I(Cache,Cache.List[J]);
  1721. if ((*Cache)[I].Install() == false)
  1722. continue;
  1723. pkgCache::VerIterator Cand = Cache[I].CandidateVerIter(Cache);
  1724. if (verset[MOD_INSTALL].find(Cand) != verset[MOD_INSTALL].end())
  1725. continue;
  1726. List += I.FullName(true) + " ";
  1727. VersionsList += string(Cache[I].CandVersion) + "\n";
  1728. }
  1729. ShowList(c1out,_("The following extra packages will be installed:"),List,VersionsList);
  1730. }
  1731. /* Print out a list of suggested and recommended packages */
  1732. {
  1733. string SuggestsList, RecommendsList, List;
  1734. string SuggestsVersions, RecommendsVersions;
  1735. for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
  1736. {
  1737. pkgCache::PkgIterator Pkg(Cache,Cache.List[J]);
  1738. /* Just look at the ones we want to install */
  1739. if ((*Cache)[Pkg].Install() == false)
  1740. continue;
  1741. // get the recommends/suggests for the candidate ver
  1742. pkgCache::VerIterator CV = (*Cache)[Pkg].CandidateVerIter(*Cache);
  1743. for (pkgCache::DepIterator D = CV.DependsList(); D.end() == false; )
  1744. {
  1745. pkgCache::DepIterator Start;
  1746. pkgCache::DepIterator End;
  1747. D.GlobOr(Start,End); // advances D
  1748. // FIXME: we really should display a or-group as a or-group to the user
  1749. // the problem is that ShowList is incapable of doing this
  1750. string RecommendsOrList,RecommendsOrVersions;
  1751. string SuggestsOrList,SuggestsOrVersions;
  1752. bool foundInstalledInOrGroup = false;
  1753. for(;;)
  1754. {
  1755. /* Skip if package is installed already, or is about to be */
  1756. string target = Start.TargetPkg().FullName(true) + " ";
  1757. pkgCache::PkgIterator const TarPkg = Start.TargetPkg();
  1758. if (TarPkg->SelectedState == pkgCache::State::Install ||
  1759. TarPkg->SelectedState == pkgCache::State::Hold ||
  1760. Cache[Start.TargetPkg()].Install())
  1761. {
  1762. foundInstalledInOrGroup=true;
  1763. break;
  1764. }
  1765. /* Skip if we already saw it */
  1766. if (int(SuggestsList.find(target)) != -1 || int(RecommendsList.find(target)) != -1)
  1767. {
  1768. foundInstalledInOrGroup=true;
  1769. break;
  1770. }
  1771. // this is a dep on a virtual pkg, check if any package that provides it
  1772. // should be installed
  1773. if(Start.TargetPkg().ProvidesList() != 0)
  1774. {
  1775. pkgCache::PrvIterator I = Start.TargetPkg().ProvidesList();
  1776. for (; I.end() == false; ++I)
  1777. {
  1778. pkgCache::PkgIterator Pkg = I.OwnerPkg();
  1779. if (Cache[Pkg].CandidateVerIter(Cache) == I.OwnerVer() &&
  1780. Pkg.CurrentVer() != 0)
  1781. foundInstalledInOrGroup=true;
  1782. }
  1783. }
  1784. if (Start->Type == pkgCache::Dep::Suggests)
  1785. {
  1786. SuggestsOrList += target;
  1787. SuggestsOrVersions += string(Cache[Start.TargetPkg()].CandVersion) + "\n";
  1788. }
  1789. if (Start->Type == pkgCache::Dep::Recommends)
  1790. {
  1791. RecommendsOrList += target;
  1792. RecommendsOrVersions += string(Cache[Start.TargetPkg()].CandVersion) + "\n";
  1793. }
  1794. if (Start >= End)
  1795. break;
  1796. ++Start;
  1797. }
  1798. if(foundInstalledInOrGroup == false)
  1799. {
  1800. RecommendsList += RecommendsOrList;
  1801. RecommendsVersions += RecommendsOrVersions;
  1802. SuggestsList += SuggestsOrList;
  1803. SuggestsVersions += SuggestsOrVersions;
  1804. }
  1805. }
  1806. }
  1807. ShowList(c1out,_("Suggested packages:"),SuggestsList,SuggestsVersions);
  1808. ShowList(c1out,_("Recommended packages:"),RecommendsList,RecommendsVersions);
  1809. }
  1810. // if nothing changed in the cache, but only the automark information
  1811. // we write the StateFile here, otherwise it will be written in
  1812. // cache.commit()
  1813. if (InstallAction.AutoMarkChanged > 0 &&
  1814. Cache->DelCount() == 0 && Cache->InstCount() == 0 &&
  1815. Cache->BadCount() == 0 &&
  1816. _config->FindB("APT::Get::Simulate",false) == false)
  1817. Cache->writeStateFile(NULL);
  1818. // See if we need to prompt
  1819. // FIXME: check if really the packages in the set are going to be installed
  1820. if (Cache->InstCount() == verset[MOD_INSTALL].size() && Cache->DelCount() == 0)
  1821. return InstallPackages(Cache,false,false);
  1822. return InstallPackages(Cache,false);
  1823. }
  1824. /*}}}*/
  1825. /* mark packages as automatically/manually installed. {{{*/
  1826. bool DoMarkAuto(CommandLine &CmdL)
  1827. {
  1828. bool Action = true;
  1829. int AutoMarkChanged = 0;
  1830. OpTextProgress progress;
  1831. CacheFile Cache;
  1832. if (Cache.Open() == false)
  1833. return false;
  1834. if (strcasecmp(CmdL.FileList[0],"markauto") == 0)
  1835. Action = true;
  1836. else if (strcasecmp(CmdL.FileList[0],"unmarkauto") == 0)
  1837. Action = false;
  1838. for (const char **I = CmdL.FileList + 1; *I != 0; I++)
  1839. {
  1840. const char *S = *I;
  1841. // Locate the package
  1842. pkgCache::PkgIterator Pkg = Cache->FindPkg(S);
  1843. if (Pkg.end() == true) {
  1844. return _error->Error(_("Couldn't find package %s"),S);
  1845. }
  1846. else
  1847. {
  1848. if (!Action)
  1849. ioprintf(c1out,_("%s set to manually installed.\n"), Pkg.Name());
  1850. else
  1851. ioprintf(c1out,_("%s set to automatically installed.\n"),
  1852. Pkg.Name());
  1853. Cache->MarkAuto(Pkg,Action);
  1854. AutoMarkChanged++;
  1855. }
  1856. }
  1857. _error->Notice(_("This command is deprecated. Please use 'apt-mark auto' and 'apt-mark manual' instead."));
  1858. if (AutoMarkChanged && ! _config->FindB("APT::Get::Simulate",false))
  1859. return Cache->writeStateFile(NULL);
  1860. return false;
  1861. }
  1862. /*}}}*/
  1863. // DoDistUpgrade - Automatic smart upgrader /*{{{*/
  1864. // ---------------------------------------------------------------------
  1865. /* Intelligent upgrader that will install and remove packages at will */
  1866. bool DoDistUpgrade(CommandLine &CmdL)
  1867. {
  1868. CacheFile Cache;
  1869. if (Cache.OpenForInstall() == false || Cache.CheckDeps() == false)
  1870. return false;
  1871. c0out << _("Calculating upgrade... ") << flush;
  1872. if (pkgDistUpgrade(*Cache) == false)
  1873. {
  1874. c0out << _("Failed") << endl;
  1875. ShowBroken(c1out,Cache,false);
  1876. return false;
  1877. }
  1878. c0out << _("Done") << endl;
  1879. return InstallPackages(Cache,true);
  1880. }
  1881. /*}}}*/
  1882. // DoDSelectUpgrade - Do an upgrade by following dselects selections /*{{{*/
  1883. // ---------------------------------------------------------------------
  1884. /* Follows dselect's selections */
  1885. bool DoDSelectUpgrade(CommandLine &CmdL)
  1886. {
  1887. CacheFile Cache;
  1888. if (Cache.OpenForInstall() == false || Cache.CheckDeps() == false)
  1889. return false;
  1890. pkgDepCache::ActionGroup group(Cache);
  1891. // Install everything with the install flag set
  1892. pkgCache::PkgIterator I = Cache->PkgBegin();
  1893. for (;I.end() != true; ++I)
  1894. {
  1895. /* Install the package only if it is a new install, the autoupgrader
  1896. will deal with the rest */
  1897. if (I->SelectedState == pkgCache::State::Install)
  1898. Cache->MarkInstall(I,false);
  1899. }
  1900. /* Now install their deps too, if we do this above then order of
  1901. the status file is significant for | groups */
  1902. for (I = Cache->PkgBegin();I.end() != true; ++I)
  1903. {
  1904. /* Install the package only if it is a new install, the autoupgrader
  1905. will deal with the rest */
  1906. if (I->SelectedState == pkgCache::State::Install)
  1907. Cache->MarkInstall(I,true);
  1908. }
  1909. // Apply erasures now, they override everything else.
  1910. for (I = Cache->PkgBegin();I.end() != true; ++I)
  1911. {
  1912. // Remove packages
  1913. if (I->SelectedState == pkgCache::State::DeInstall ||
  1914. I->SelectedState == pkgCache::State::Purge)
  1915. Cache->MarkDelete(I,I->SelectedState == pkgCache::State::Purge);
  1916. }
  1917. /* Resolve any problems that dselect created, allupgrade cannot handle
  1918. such things. We do so quite agressively too.. */
  1919. if (Cache->BrokenCount() != 0)
  1920. {
  1921. pkgProblemResolver Fix(Cache);
  1922. // Hold back held packages.
  1923. if (_config->FindB("APT::Ignore-Hold",false) == false)
  1924. {
  1925. for (pkgCache::PkgIterator I = Cache->PkgBegin(); I.end() == false; ++I)
  1926. {
  1927. if (I->SelectedState == pkgCache::State::Hold)
  1928. {
  1929. Fix.Protect(I);
  1930. Cache->MarkKeep(I);
  1931. }
  1932. }
  1933. }
  1934. if (Fix.Resolve() == false)
  1935. {
  1936. ShowBroken(c1out,Cache,false);
  1937. return _error->Error(_("Internal error, problem resolver broke stuff"));
  1938. }
  1939. }
  1940. // Now upgrade everything
  1941. if (pkgAllUpgrade(Cache) == false)
  1942. {
  1943. ShowBroken(c1out,Cache,false);
  1944. return _error->Error(_("Internal error, problem resolver broke stuff"));
  1945. }
  1946. return InstallPackages(Cache,false);
  1947. }
  1948. /*}}}*/
  1949. // DoClean - Remove download archives /*{{{*/
  1950. // ---------------------------------------------------------------------
  1951. /* */
  1952. bool DoClean(CommandLine &CmdL)
  1953. {
  1954. std::string const archivedir = _config->FindDir("Dir::Cache::archives");
  1955. std::string const pkgcache = _config->FindFile("Dir::cache::pkgcache");
  1956. std::string const srcpkgcache = _config->FindFile("Dir::cache::srcpkgcache");
  1957. if (_config->FindB("APT::Get::Simulate") == true)
  1958. {
  1959. cout << "Del " << archivedir << "* " << archivedir << "partial/*"<< endl
  1960. << "Del " << pkgcache << " " << srcpkgcache << endl;
  1961. return true;
  1962. }
  1963. // Lock the archive directory
  1964. FileFd Lock;
  1965. if (_config->FindB("Debug::NoLocking",false) == false)
  1966. {
  1967. Lock.Fd(GetLock(archivedir + "lock"));
  1968. if (_error->PendingError() == true)
  1969. return _error->Error(_("Unable to lock the download directory"));
  1970. }
  1971. pkgAcquire Fetcher;
  1972. Fetcher.Clean(archivedir);
  1973. Fetcher.Clean(archivedir + "partial/");
  1974. pkgCacheFile::RemoveCaches();
  1975. return true;
  1976. }
  1977. /*}}}*/
  1978. // DoAutoClean - Smartly remove downloaded archives /*{{{*/
  1979. // ---------------------------------------------------------------------
  1980. /* This is similar to clean but it only purges things that cannot be
  1981. downloaded, that is old versions of cached packages. */
  1982. class LogCleaner : public pkgArchiveCleaner
  1983. {
  1984. protected:
  1985. virtual void Erase(const char *File,string Pkg,string Ver,struct stat &St)
  1986. {
  1987. c1out << "Del " << Pkg << " " << Ver << " [" << SizeToStr(St.st_size) << "B]" << endl;
  1988. if (_config->FindB("APT::Get::Simulate") == false)
  1989. unlink(File);
  1990. };
  1991. };
  1992. bool DoAutoClean(CommandLine &CmdL)
  1993. {
  1994. // Lock the archive directory
  1995. FileFd Lock;
  1996. if (_config->FindB("Debug::NoLocking",false) == false)
  1997. {
  1998. Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
  1999. if (_error->PendingError() == true)
  2000. return _error->Error(_("Unable to lock the download directory"));
  2001. }
  2002. CacheFile Cache;
  2003. if (Cache.Open() == false)
  2004. return false;
  2005. LogCleaner Cleaner;
  2006. return Cleaner.Go(_config->FindDir("Dir::Cache::archives"),*Cache) &&
  2007. Cleaner.Go(_config->FindDir("Dir::Cache::archives") + "partial/",*Cache);
  2008. }
  2009. /*}}}*/
  2010. // DoDownload - download a binary /*{{{*/
  2011. // ---------------------------------------------------------------------
  2012. bool DoDownload(CommandLine &CmdL)
  2013. {
  2014. CacheFile Cache;
  2015. if (Cache.ReadOnlyOpen() == false)
  2016. return false;
  2017. APT::CacheSetHelper helper(c0out);
  2018. APT::VersionSet verset = APT::VersionSet::FromCommandLine(Cache,
  2019. CmdL.FileList + 1, APT::VersionSet::CANDIDATE, helper);
  2020. if (verset.empty() == true)
  2021. return false;
  2022. pkgAcquire Fetcher;
  2023. AcqTextStatus Stat(ScreenWidth, _config->FindI("quiet",0));
  2024. if (_config->FindB("APT::Get::Print-URIs") == false)
  2025. Fetcher.Setup(&Stat);
  2026. pkgRecords Recs(Cache);
  2027. pkgSourceList *SrcList = Cache.GetSourceList();
  2028. for (APT::VersionSet::const_iterator Ver = verset.begin();
  2029. Ver != verset.end();
  2030. ++Ver)
  2031. {
  2032. string descr;
  2033. // get the right version
  2034. pkgCache::PkgIterator Pkg = Ver.ParentPkg();
  2035. pkgRecords::Parser &rec=Recs.Lookup(Ver.FileList());
  2036. pkgCache::VerFileIterator Vf = Ver.FileList();
  2037. if (Vf.end() == true)
  2038. return _error->Error("Can not find VerFile");
  2039. pkgCache::PkgFileIterator F = Vf.File();
  2040. pkgIndexFile *index;
  2041. if(SrcList->FindIndex(F, index) == false)
  2042. return _error->Error("FindIndex failed");
  2043. string uri = index->ArchiveURI(rec.FileName());
  2044. strprintf(descr, _("Downloading %s %s"), Pkg.Name(), Ver.VerStr());
  2045. // get the most appropriate hash
  2046. HashString hash;
  2047. if (rec.SHA256Hash() != "")
  2048. hash = HashString("sha256", rec.SHA256Hash());
  2049. else if (rec.SHA1Hash() != "")
  2050. hash = HashString("sha1", rec.SHA1Hash());
  2051. else if (rec.MD5Hash() != "")
  2052. hash = HashString("md5", rec.MD5Hash());
  2053. // get the file
  2054. new pkgAcqFile(&Fetcher, uri, hash.toStr(), (*Ver)->Size, descr, Pkg.Name(), ".");
  2055. }
  2056. // Just print out the uris and exit if the --print-uris flag was used
  2057. if (_config->FindB("APT::Get::Print-URIs") == true)
  2058. {
  2059. pkgAcquire::UriIterator I = Fetcher.UriBegin();
  2060. for (; I != Fetcher.UriEnd(); ++I)
  2061. cout << '\'' << I->URI << "' " << flNotDir(I->Owner->DestFile) << ' ' <<
  2062. I->Owner->FileSize << ' ' << I->Owner->HashSum() << endl;
  2063. return true;
  2064. }
  2065. return (Fetcher.Run() == pkgAcquire::Continue);
  2066. }
  2067. /*}}}*/
  2068. // DoCheck - Perform the check operation /*{{{*/
  2069. // ---------------------------------------------------------------------
  2070. /* Opening automatically checks the system, this command is mostly used
  2071. for debugging */
  2072. bool DoCheck(CommandLine &CmdL)
  2073. {
  2074. CacheFile Cache;
  2075. Cache.Open();
  2076. Cache.CheckDeps();
  2077. return true;
  2078. }
  2079. /*}}}*/
  2080. // DoSource - Fetch a source archive /*{{{*/
  2081. // ---------------------------------------------------------------------
  2082. /* Fetch souce packages */
  2083. struct DscFile
  2084. {
  2085. string Package;
  2086. string Version;
  2087. string Dsc;
  2088. };
  2089. bool DoSource(CommandLine &CmdL)
  2090. {
  2091. CacheFile Cache;
  2092. if (Cache.Open(false) == false)
  2093. return false;
  2094. if (CmdL.FileSize() <= 1)
  2095. return _error->Error(_("Must specify at least one package to fetch source for"));
  2096. // Read the source list
  2097. if (Cache.BuildSourceList() == false)
  2098. return false;
  2099. pkgSourceList *List = Cache.GetSourceList();
  2100. // Create the text record parsers
  2101. pkgRecords Recs(Cache);
  2102. pkgSrcRecords SrcRecs(*List);
  2103. if (_error->PendingError() == true)
  2104. return false;
  2105. // Create the download object
  2106. AcqTextStatus Stat(ScreenWidth,_config->FindI("quiet",0));
  2107. pkgAcquire Fetcher;
  2108. Fetcher.SetLog(&Stat);
  2109. DscFile *Dsc = new DscFile[CmdL.FileSize()];
  2110. // insert all downloaded uris into this set to avoid downloading them
  2111. // twice
  2112. set<string> queued;
  2113. // Diff only mode only fetches .diff files
  2114. bool const diffOnly = _config->FindB("APT::Get::Diff-Only", false);
  2115. // Tar only mode only fetches .tar files
  2116. bool const tarOnly = _config->FindB("APT::Get::Tar-Only", false);
  2117. // Dsc only mode only fetches .dsc files
  2118. bool const dscOnly = _config->FindB("APT::Get::Dsc-Only", false);
  2119. // Load the requestd sources into the fetcher
  2120. unsigned J = 0;
  2121. for (const char **I = CmdL.FileList + 1; *I != 0; I++, J++)
  2122. {
  2123. string Src;
  2124. pkgSrcRecords::Parser *Last = FindSrc(*I,Recs,SrcRecs,Src,*Cache);
  2125. if (Last == 0) {
  2126. delete[] Dsc;
  2127. return _error->Error(_("Unable to find a source package for %s"),Src.c_str());
  2128. }
  2129. string srec = Last->AsStr();
  2130. string::size_type pos = srec.find("\nVcs-");
  2131. while (pos != string::npos)
  2132. {
  2133. pos += strlen("\nVcs-");
  2134. string vcs = srec.substr(pos,srec.find(":",pos)-pos);
  2135. if(vcs == "Browser")
  2136. {
  2137. pos = srec.find("\nVcs-", pos);
  2138. continue;
  2139. }
  2140. pos += vcs.length()+2;
  2141. string::size_type epos = srec.find("\n", pos);
  2142. string uri = srec.substr(pos,epos-pos).c_str();
  2143. ioprintf(c1out, _("NOTICE: '%s' packaging is maintained in "
  2144. "the '%s' version control system at:\n"
  2145. "%s\n"),
  2146. Src.c_str(), vcs.c_str(), uri.c_str());
  2147. if(vcs == "Bzr")
  2148. ioprintf(c1out,_("Please use:\n"
  2149. "bzr get %s\n"
  2150. "to retrieve the latest (possibly unreleased) "
  2151. "updates to the package.\n"),
  2152. uri.c_str());
  2153. break;
  2154. }
  2155. // Back track
  2156. vector<pkgSrcRecords::File> Lst;
  2157. if (Last->Files(Lst) == false) {
  2158. delete[] Dsc;
  2159. return false;
  2160. }
  2161. // Load them into the fetcher
  2162. for (vector<pkgSrcRecords::File>::const_iterator I = Lst.begin();
  2163. I != Lst.end(); ++I)
  2164. {
  2165. // Try to guess what sort of file it is we are getting.
  2166. if (I->Type == "dsc")
  2167. {
  2168. Dsc[J].Package = Last->Package();
  2169. Dsc[J].Version = Last->Version();
  2170. Dsc[J].Dsc = flNotDir(I->Path);
  2171. }
  2172. // Handle the only options so that multiple can be used at once
  2173. if (diffOnly == true || tarOnly == true || dscOnly == true)
  2174. {
  2175. if ((diffOnly == true && I->Type == "diff") ||
  2176. (tarOnly == true && I->Type == "tar") ||
  2177. (dscOnly == true && I->Type == "dsc"))
  2178. ; // Fine, we want this file downloaded
  2179. else
  2180. continue;
  2181. }
  2182. // don't download the same uri twice (should this be moved to
  2183. // the fetcher interface itself?)
  2184. if(queued.find(Last->Index().ArchiveURI(I->Path)) != queued.end())
  2185. continue;
  2186. queued.insert(Last->Index().ArchiveURI(I->Path));
  2187. // check if we have a file with that md5 sum already localy
  2188. if(!I->MD5Hash.empty() && FileExists(flNotDir(I->Path)))
  2189. {
  2190. FileFd Fd(flNotDir(I->Path), FileFd::ReadOnly);
  2191. MD5Summation sum;
  2192. sum.AddFD(Fd.Fd(), Fd.Size());
  2193. Fd.Close();
  2194. if((string)sum.Result() == I->MD5Hash)
  2195. {
  2196. ioprintf(c1out,_("Skipping already downloaded file '%s'\n"),
  2197. flNotDir(I->Path).c_str());
  2198. continue;
  2199. }
  2200. }
  2201. new pkgAcqFile(&Fetcher,Last->Index().ArchiveURI(I->Path),
  2202. I->MD5Hash,I->Size,
  2203. Last->Index().SourceInfo(*Last,*I),Src);
  2204. }
  2205. }
  2206. // Display statistics
  2207. unsigned long long FetchBytes = Fetcher.FetchNeeded();
  2208. unsigned long long FetchPBytes = Fetcher.PartialPresent();
  2209. unsigned long long DebBytes = Fetcher.TotalNeeded();
  2210. // Check for enough free space
  2211. struct statvfs Buf;
  2212. string OutputDir = ".";
  2213. if (statvfs(OutputDir.c_str(),&Buf) != 0) {
  2214. delete[] Dsc;
  2215. if (errno == EOVERFLOW)
  2216. return _error->WarningE("statvfs",_("Couldn't determine free space in %s"),
  2217. OutputDir.c_str());
  2218. else
  2219. return _error->Errno("statvfs",_("Couldn't determine free space in %s"),
  2220. OutputDir.c_str());
  2221. } else if (unsigned(Buf.f_bfree) < (FetchBytes - FetchPBytes)/Buf.f_bsize)
  2222. {
  2223. struct statfs Stat;
  2224. if (statfs(OutputDir.c_str(),&Stat) != 0
  2225. #if HAVE_STRUCT_STATFS_F_TYPE
  2226. || unsigned(Stat.f_type) != RAMFS_MAGIC
  2227. #endif
  2228. ) {
  2229. delete[] Dsc;
  2230. return _error->Error(_("You don't have enough free space in %s"),
  2231. OutputDir.c_str());
  2232. }
  2233. }
  2234. // Number of bytes
  2235. if (DebBytes != FetchBytes)
  2236. //TRANSLATOR: The required space between number and unit is already included
  2237. // in the replacement strings, so %sB will be correctly translate in e.g. 1,5 MB
  2238. ioprintf(c1out,_("Need to get %sB/%sB of source archives.\n"),
  2239. SizeToStr(FetchBytes).c_str(),SizeToStr(DebBytes).c_str());
  2240. else
  2241. //TRANSLATOR: The required space between number and unit is already included
  2242. // in the replacement string, so %sB will be correctly translate in e.g. 1,5 MB
  2243. ioprintf(c1out,_("Need to get %sB of source archives.\n"),
  2244. SizeToStr(DebBytes).c_str());
  2245. if (_config->FindB("APT::Get::Simulate",false) == true)
  2246. {
  2247. for (unsigned I = 0; I != J; I++)
  2248. ioprintf(cout,_("Fetch source %s\n"),Dsc[I].Package.c_str());
  2249. delete[] Dsc;
  2250. return true;
  2251. }
  2252. // Just print out the uris an exit if the --print-uris flag was used
  2253. if (_config->FindB("APT::Get::Print-URIs") == true)
  2254. {
  2255. pkgAcquire::UriIterator I = Fetcher.UriBegin();
  2256. for (; I != Fetcher.UriEnd(); ++I)
  2257. cout << '\'' << I->URI << "' " << flNotDir(I->Owner->DestFile) << ' ' <<
  2258. I->Owner->FileSize << ' ' << I->Owner->HashSum() << endl;
  2259. delete[] Dsc;
  2260. return true;
  2261. }
  2262. // Run it
  2263. if (Fetcher.Run() == pkgAcquire::Failed)
  2264. {
  2265. delete[] Dsc;
  2266. return false;
  2267. }
  2268. // Print error messages
  2269. bool Failed = false;
  2270. for (pkgAcquire::ItemIterator I = Fetcher.ItemsBegin(); I != Fetcher.ItemsEnd(); ++I)
  2271. {
  2272. if ((*I)->Status == pkgAcquire::Item::StatDone &&
  2273. (*I)->Complete == true)
  2274. continue;
  2275. fprintf(stderr,_("Failed to fetch %s %s\n"),(*I)->DescURI().c_str(),
  2276. (*I)->ErrorText.c_str());
  2277. Failed = true;
  2278. }
  2279. if (Failed == true)
  2280. {
  2281. delete[] Dsc;
  2282. return _error->Error(_("Failed to fetch some archives."));
  2283. }
  2284. if (_config->FindB("APT::Get::Download-only",false) == true)
  2285. {
  2286. c1out << _("Download complete and in download only mode") << endl;
  2287. delete[] Dsc;
  2288. return true;
  2289. }
  2290. // Unpack the sources
  2291. pid_t Process = ExecFork();
  2292. if (Process == 0)
  2293. {
  2294. bool const fixBroken = _config->FindB("APT::Get::Fix-Broken", false);
  2295. for (unsigned I = 0; I != J; ++I)
  2296. {
  2297. string Dir = Dsc[I].Package + '-' + Cache->VS().UpstreamVersion(Dsc[I].Version.c_str());
  2298. // Diff only mode only fetches .diff files
  2299. if (_config->FindB("APT::Get::Diff-Only",false) == true ||
  2300. _config->FindB("APT::Get::Tar-Only",false) == true ||
  2301. Dsc[I].Dsc.empty() == true)
  2302. continue;
  2303. // See if the package is already unpacked
  2304. struct stat Stat;
  2305. if (fixBroken == false && stat(Dir.c_str(),&Stat) == 0 &&
  2306. S_ISDIR(Stat.st_mode) != 0)
  2307. {
  2308. ioprintf(c0out ,_("Skipping unpack of already unpacked source in %s\n"),
  2309. Dir.c_str());
  2310. }
  2311. else
  2312. {
  2313. // Call dpkg-source
  2314. char S[500];
  2315. snprintf(S,sizeof(S),"%s -x %s",
  2316. _config->Find("Dir::Bin::dpkg-source","dpkg-source").c_str(),
  2317. Dsc[I].Dsc.c_str());
  2318. if (system(S) != 0)
  2319. {
  2320. fprintf(stderr,_("Unpack command '%s' failed.\n"),S);
  2321. fprintf(stderr,_("Check if the 'dpkg-dev' package is installed.\n"));
  2322. _exit(1);
  2323. }
  2324. }
  2325. // Try to compile it with dpkg-buildpackage
  2326. if (_config->FindB("APT::Get::Compile",false) == true)
  2327. {
  2328. string buildopts = _config->Find("APT::Get::Host-Architecture");
  2329. if (buildopts.empty() == false)
  2330. buildopts = "-a " + buildopts + " ";
  2331. buildopts.append(_config->Find("DPkg::Build-Options","-b -uc"));
  2332. // Call dpkg-buildpackage
  2333. char S[500];
  2334. snprintf(S,sizeof(S),"cd %s && %s %s",
  2335. Dir.c_str(),
  2336. _config->Find("Dir::Bin::dpkg-buildpackage","dpkg-buildpackage").c_str(),
  2337. buildopts.c_str());
  2338. if (system(S) != 0)
  2339. {
  2340. fprintf(stderr,_("Build command '%s' failed.\n"),S);
  2341. _exit(1);
  2342. }
  2343. }
  2344. }
  2345. _exit(0);
  2346. }
  2347. delete[] Dsc;
  2348. // Wait for the subprocess
  2349. int Status = 0;
  2350. while (waitpid(Process,&Status,0) != Process)
  2351. {
  2352. if (errno == EINTR)
  2353. continue;
  2354. return _error->Errno("waitpid","Couldn't wait for subprocess");
  2355. }
  2356. if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
  2357. return _error->Error(_("Child process failed"));
  2358. return true;
  2359. }
  2360. /*}}}*/
  2361. // DoBuildDep - Install/removes packages to satisfy build dependencies /*{{{*/
  2362. // ---------------------------------------------------------------------
  2363. /* This function will look at the build depends list of the given source
  2364. package and install the necessary packages to make it true, or fail. */
  2365. bool DoBuildDep(CommandLine &CmdL)
  2366. {
  2367. CacheFile Cache;
  2368. _config->Set("APT::Install-Recommends", false);
  2369. if (Cache.Open(true) == false)
  2370. return false;
  2371. if (CmdL.FileSize() <= 1)
  2372. return _error->Error(_("Must specify at least one package to check builddeps for"));
  2373. // Read the source list
  2374. if (Cache.BuildSourceList() == false)
  2375. return false;
  2376. pkgSourceList *List = Cache.GetSourceList();
  2377. // Create the text record parsers
  2378. pkgRecords Recs(Cache);
  2379. pkgSrcRecords SrcRecs(*List);
  2380. if (_error->PendingError() == true)
  2381. return false;
  2382. // Create the download object
  2383. AcqTextStatus Stat(ScreenWidth,_config->FindI("quiet",0));
  2384. pkgAcquire Fetcher;
  2385. if (Fetcher.Setup(&Stat) == false)
  2386. return false;
  2387. bool StripMultiArch;
  2388. string hostArch = _config->Find("APT::Get::Host-Architecture");
  2389. if (hostArch.empty() == false)
  2390. {
  2391. std::vector<std::string> archs = APT::Configuration::getArchitectures();
  2392. if (std::find(archs.begin(), archs.end(), hostArch) == archs.end())
  2393. return _error->Error(_("No architecture information available for %s. See apt.conf(5) APT::Architectures for setup"), hostArch.c_str());
  2394. StripMultiArch = false;
  2395. }
  2396. else
  2397. StripMultiArch = true;
  2398. unsigned J = 0;
  2399. for (const char **I = CmdL.FileList + 1; *I != 0; I++, J++)
  2400. {
  2401. string Src;
  2402. pkgSrcRecords::Parser *Last = FindSrc(*I,Recs,SrcRecs,Src,*Cache);
  2403. if (Last == 0)
  2404. return _error->Error(_("Unable to find a source package for %s"),Src.c_str());
  2405. // Process the build-dependencies
  2406. vector<pkgSrcRecords::Parser::BuildDepRec> BuildDeps;
  2407. if (Last->BuildDepends(BuildDeps, _config->FindB("APT::Get::Arch-Only", false), StripMultiArch) == false)
  2408. return _error->Error(_("Unable to get build-dependency information for %s"),Src.c_str());
  2409. // Also ensure that build-essential packages are present
  2410. Configuration::Item const *Opts = _config->Tree("APT::Build-Essential");
  2411. if (Opts)
  2412. Opts = Opts->Child;
  2413. for (; Opts; Opts = Opts->Next)
  2414. {
  2415. if (Opts->Value.empty() == true)
  2416. continue;
  2417. pkgSrcRecords::Parser::BuildDepRec rec;
  2418. rec.Package = Opts->Value;
  2419. rec.Type = pkgSrcRecords::Parser::BuildDependIndep;
  2420. rec.Op = 0;
  2421. BuildDeps.push_back(rec);
  2422. }
  2423. if (BuildDeps.empty() == true)
  2424. {
  2425. ioprintf(c1out,_("%s has no build depends.\n"),Src.c_str());
  2426. continue;
  2427. }
  2428. // Install the requested packages
  2429. vector <pkgSrcRecords::Parser::BuildDepRec>::iterator D;
  2430. pkgProblemResolver Fix(Cache);
  2431. bool skipAlternatives = false; // skip remaining alternatives in an or group
  2432. for (D = BuildDeps.begin(); D != BuildDeps.end(); ++D)
  2433. {
  2434. bool hasAlternatives = (((*D).Op & pkgCache::Dep::Or) == pkgCache::Dep::Or);
  2435. if (skipAlternatives == true)
  2436. {
  2437. /*
  2438. * if there are alternatives, we've already picked one, so skip
  2439. * the rest
  2440. *
  2441. * TODO: this means that if there's a build-dep on A|B and B is
  2442. * installed, we'll still try to install A; more importantly,
  2443. * if A is currently broken, we cannot go back and try B. To fix
  2444. * this would require we do a Resolve cycle for each package we
  2445. * add to the install list. Ugh
  2446. */
  2447. if (!hasAlternatives)
  2448. skipAlternatives = false; // end of or group
  2449. continue;
  2450. }
  2451. if ((*D).Type == pkgSrcRecords::Parser::BuildConflict ||
  2452. (*D).Type == pkgSrcRecords::Parser::BuildConflictIndep)
  2453. {
  2454. pkgCache::GrpIterator Grp = Cache->FindGrp((*D).Package);
  2455. // Build-conflicts on unknown packages are silently ignored
  2456. if (Grp.end() == true)
  2457. continue;
  2458. for (pkgCache::PkgIterator Pkg = Grp.PackageList(); Pkg.end() == false; Pkg = Grp.NextPkg(Pkg))
  2459. {
  2460. pkgCache::VerIterator IV = (*Cache)[Pkg].InstVerIter(*Cache);
  2461. /*
  2462. * Remove if we have an installed version that satisfies the
  2463. * version criteria
  2464. */
  2465. if (IV.end() == false &&
  2466. Cache->VS().CheckDep(IV.VerStr(),(*D).Op,(*D).Version.c_str()) == true)
  2467. TryToInstallBuildDep(Pkg,Cache,Fix,true,false);
  2468. }
  2469. }
  2470. else // BuildDep || BuildDepIndep
  2471. {
  2472. if (_config->FindB("Debug::BuildDeps",false) == true)
  2473. cout << "Looking for " << (*D).Package << "...\n";
  2474. pkgCache::PkgIterator Pkg;
  2475. // Cross-Building?
  2476. if (StripMultiArch == false)
  2477. {
  2478. size_t const colon = D->Package.find(":");
  2479. if (colon != string::npos &&
  2480. (strcmp(D->Package.c_str() + colon, ":any") == 0 || strcmp(D->Package.c_str() + colon, ":native") == 0))
  2481. Pkg = Cache->FindPkg(D->Package.substr(0,colon));
  2482. else
  2483. Pkg = Cache->FindPkg(D->Package);
  2484. // We need to decide if host or build arch, so find a version we can look at
  2485. pkgCache::VerIterator Ver;
  2486. // a bad version either is invalid or doesn't satify dependency
  2487. #define BADVER(Ver) Ver.end() == true || \
  2488. (Ver.end() == false && D->Version.empty() == false && \
  2489. Cache->VS().CheckDep(Ver.VerStr(),D->Op,D->Version.c_str()) == false)
  2490. if (Pkg.end() == false)
  2491. {
  2492. Ver = (*Cache)[Pkg].InstVerIter(*Cache);
  2493. if (BADVER(Ver))
  2494. Ver = (*Cache)[Pkg].CandidateVerIter(*Cache);
  2495. }
  2496. if (BADVER(Ver))
  2497. {
  2498. pkgCache::PkgIterator HostPkg = Cache->FindPkg(D->Package, hostArch);
  2499. if (HostPkg.end() == false)
  2500. {
  2501. Ver = (*Cache)[HostPkg].InstVerIter(*Cache);
  2502. if (BADVER(Ver))
  2503. Ver = (*Cache)[HostPkg].CandidateVerIter(*Cache);
  2504. }
  2505. }
  2506. if ((BADVER(Ver)) == false)
  2507. {
  2508. string forbidden;
  2509. if (Ver->MultiArch == pkgCache::Version::None || Ver->MultiArch == pkgCache::Version::All);
  2510. else if (Ver->MultiArch == pkgCache::Version::Same)
  2511. {
  2512. if (colon != string::npos)
  2513. Pkg = Ver.ParentPkg().Group().FindPkg(hostArch);
  2514. else if (strcmp(D->Package.c_str() + colon, ":any") == 0)
  2515. forbidden = "Multi-Arch: same";
  2516. // :native gets the buildArch
  2517. }
  2518. else if (Ver->MultiArch == pkgCache::Version::Foreign || Ver->MultiArch == pkgCache::Version::AllForeign)
  2519. {
  2520. if (colon != string::npos)
  2521. forbidden = "Multi-Arch: foreign";
  2522. }
  2523. else if (Ver->MultiArch == pkgCache::Version::Allowed || Ver->MultiArch == pkgCache::Version::AllAllowed)
  2524. {
  2525. if (colon == string::npos)
  2526. Pkg = Ver.ParentPkg().Group().FindPkg(hostArch);
  2527. else if (strcmp(D->Package.c_str() + colon, ":any") == 0)
  2528. {
  2529. // prefer any installed over preferred non-installed architectures
  2530. pkgCache::GrpIterator Grp = Ver.ParentPkg().Group();
  2531. // we don't check for version here as we are better of with upgrading than remove and install
  2532. for (Pkg = Grp.PackageList(); Pkg.end() == false; Pkg = Grp.NextPkg(Pkg))
  2533. if (Pkg.CurrentVer().end() == false)
  2534. break;
  2535. if (Pkg.end() == true)
  2536. Pkg = Grp.FindPreferredPkg(true);
  2537. }
  2538. // native gets buildArch
  2539. }
  2540. if (forbidden.empty() == false)
  2541. {
  2542. if (_config->FindB("Debug::BuildDeps",false) == true)
  2543. cout << " :any is not allowed from M-A: same package " << (*D).Package << endl;
  2544. if (hasAlternatives)
  2545. continue;
  2546. return _error->Error(_("%s dependency for %s can't be satisfied "
  2547. "because %s is not allowed on '%s' packages"),
  2548. Last->BuildDepType(D->Type), Src.c_str(),
  2549. D->Package.c_str(), "Multi-Arch: same");
  2550. }
  2551. }
  2552. else if (_config->FindB("Debug::BuildDeps",false) == true)
  2553. cout << " No multiarch info as we have no satisfying installed nor candidate for " << D->Package << " on build or host arch" << endl;
  2554. #undef BADVER
  2555. }
  2556. else
  2557. Pkg = Cache->FindPkg(D->Package);
  2558. if (Pkg.end() == true)
  2559. {
  2560. if (_config->FindB("Debug::BuildDeps",false) == true)
  2561. cout << " (not found)" << (*D).Package << endl;
  2562. if (hasAlternatives)
  2563. continue;
  2564. return _error->Error(_("%s dependency for %s cannot be satisfied "
  2565. "because the package %s cannot be found"),
  2566. Last->BuildDepType((*D).Type),Src.c_str(),
  2567. (*D).Package.c_str());
  2568. }
  2569. pkgCache::VerIterator IV = (*Cache)[Pkg].InstVerIter(*Cache);
  2570. if (IV.end() == false)
  2571. {
  2572. if (_config->FindB("Debug::BuildDeps",false) == true)
  2573. cout << " Is installed\n";
  2574. if (D->Version.empty() == true ||
  2575. Cache->VS().CheckDep(IV.VerStr(),(*D).Op,(*D).Version.c_str()) == true)
  2576. {
  2577. skipAlternatives = hasAlternatives;
  2578. continue;
  2579. }
  2580. if (_config->FindB("Debug::BuildDeps",false) == true)
  2581. cout << " ...but the installed version doesn't meet the version requirement\n";
  2582. if (((*D).Op & pkgCache::Dep::LessEq) == pkgCache::Dep::LessEq)
  2583. return _error->Error(_("Failed to satisfy %s dependency for %s: Installed package %s is too new"),
  2584. Last->BuildDepType((*D).Type), Src.c_str(), Pkg.FullName(true).c_str());
  2585. }
  2586. // Only consider virtual packages if there is no versioned dependency
  2587. if ((*D).Version.empty() == true)
  2588. {
  2589. /*
  2590. * If this is a virtual package, we need to check the list of
  2591. * packages that provide it and see if any of those are
  2592. * installed
  2593. */
  2594. pkgCache::PrvIterator Prv = Pkg.ProvidesList();
  2595. for (; Prv.end() != true; ++Prv)
  2596. {
  2597. if (_config->FindB("Debug::BuildDeps",false) == true)
  2598. cout << " Checking provider " << Prv.OwnerPkg().FullName() << endl;
  2599. if ((*Cache)[Prv.OwnerPkg()].InstVerIter(*Cache).end() == false)
  2600. break;
  2601. }
  2602. if (Prv.end() == false)
  2603. {
  2604. if (_config->FindB("Debug::BuildDeps",false) == true)
  2605. cout << " Is provided by installed package " << Prv.OwnerPkg().FullName() << endl;
  2606. skipAlternatives = hasAlternatives;
  2607. continue;
  2608. }
  2609. }
  2610. else // versioned dependency
  2611. {
  2612. pkgCache::VerIterator CV = (*Cache)[Pkg].CandidateVerIter(*Cache);
  2613. if (CV.end() == true ||
  2614. Cache->VS().CheckDep(CV.VerStr(),(*D).Op,(*D).Version.c_str()) == false)
  2615. {
  2616. if (hasAlternatives)
  2617. continue;
  2618. else if (CV.end() == false)
  2619. return _error->Error(_("%s dependency for %s cannot be satisfied "
  2620. "because candidate version of package %s "
  2621. "can't satisfy version requirements"),
  2622. Last->BuildDepType(D->Type), Src.c_str(),
  2623. D->Package.c_str());
  2624. else
  2625. return _error->Error(_("%s dependency for %s cannot be satisfied "
  2626. "because package %s has no candidate version"),
  2627. Last->BuildDepType(D->Type), Src.c_str(),
  2628. D->Package.c_str());
  2629. }
  2630. }
  2631. if (TryToInstallBuildDep(Pkg,Cache,Fix,false,false) == true)
  2632. {
  2633. // We successfully installed something; skip remaining alternatives
  2634. skipAlternatives = hasAlternatives;
  2635. if(_config->FindB("APT::Get::Build-Dep-Automatic", false) == true)
  2636. Cache->MarkAuto(Pkg, true);
  2637. continue;
  2638. }
  2639. else if (hasAlternatives)
  2640. {
  2641. if (_config->FindB("Debug::BuildDeps",false) == true)
  2642. cout << " Unsatisfiable, trying alternatives\n";
  2643. continue;
  2644. }
  2645. else
  2646. {
  2647. return _error->Error(_("Failed to satisfy %s dependency for %s: %s"),
  2648. Last->BuildDepType((*D).Type),
  2649. Src.c_str(),
  2650. (*D).Package.c_str());
  2651. }
  2652. }
  2653. }
  2654. Fix.InstallProtect();
  2655. if (Fix.Resolve(true) == false)
  2656. _error->Discard();
  2657. // Now we check the state of the packages,
  2658. if (Cache->BrokenCount() != 0)
  2659. {
  2660. ShowBroken(cout, Cache, false);
  2661. return _error->Error(_("Build-dependencies for %s could not be satisfied."),*I);
  2662. }
  2663. }
  2664. if (InstallPackages(Cache, false, true) == false)
  2665. return _error->Error(_("Failed to process build dependencies"));
  2666. return true;
  2667. }
  2668. /*}}}*/
  2669. // GetChangelogPath - return a path pointing to a changelog file or dir /*{{{*/
  2670. // ---------------------------------------------------------------------
  2671. /* This returns a "path" string for the changelog url construction.
  2672. * Please note that its not complete, it either needs a "/changelog"
  2673. * appended (for the packages.debian.org/changelogs site) or a
  2674. * ".changelog" (for third party sites that store the changelog in the
  2675. * pool/ next to the deb itself)
  2676. * Example return: "pool/main/a/apt/apt_0.8.8ubuntu3"
  2677. */
  2678. string GetChangelogPath(CacheFile &Cache,
  2679. pkgCache::PkgIterator Pkg,
  2680. pkgCache::VerIterator Ver)
  2681. {
  2682. string path;
  2683. pkgRecords Recs(Cache);
  2684. pkgRecords::Parser &rec=Recs.Lookup(Ver.FileList());
  2685. string srcpkg = rec.SourcePkg().empty() ? Pkg.Name() : rec.SourcePkg();
  2686. string ver = Ver.VerStr();
  2687. // if there is a source version it always wins
  2688. if (rec.SourceVer() != "")
  2689. ver = rec.SourceVer();
  2690. path = flNotFile(rec.FileName());
  2691. path += srcpkg + "_" + StripEpoch(ver);
  2692. return path;
  2693. }
  2694. /*}}}*/
  2695. // GuessThirdPartyChangelogUri - return url /*{{{*/
  2696. // ---------------------------------------------------------------------
  2697. /* Contruct a changelog file path for third party sites that do not use
  2698. * packages.debian.org/changelogs
  2699. * This simply uses the ArchiveURI() of the source pkg and looks for
  2700. * a .changelog file there, Example for "mediabuntu":
  2701. * apt-get changelog mplayer-doc:
  2702. * http://packages.medibuntu.org/pool/non-free/m/mplayer/mplayer_1.0~rc4~try1.dsfg1-1ubuntu1+medibuntu1.changelog
  2703. */
  2704. bool GuessThirdPartyChangelogUri(CacheFile &Cache,
  2705. pkgCache::PkgIterator Pkg,
  2706. pkgCache::VerIterator Ver,
  2707. string &out_uri)
  2708. {
  2709. // get the binary deb server path
  2710. pkgCache::VerFileIterator Vf = Ver.FileList();
  2711. if (Vf.end() == true)
  2712. return false;
  2713. pkgCache::PkgFileIterator F = Vf.File();
  2714. pkgIndexFile *index;
  2715. pkgSourceList *SrcList = Cache.GetSourceList();
  2716. if(SrcList->FindIndex(F, index) == false)
  2717. return false;
  2718. // get archive uri for the binary deb
  2719. string path_without_dot_changelog = GetChangelogPath(Cache, Pkg, Ver);
  2720. out_uri = index->ArchiveURI(path_without_dot_changelog + ".changelog");
  2721. // now strip away the filename and add srcpkg_srcver.changelog
  2722. return true;
  2723. }
  2724. /*}}}*/
  2725. // DownloadChangelog - Download the changelog /*{{{*/
  2726. // ---------------------------------------------------------------------
  2727. bool DownloadChangelog(CacheFile &CacheFile, pkgAcquire &Fetcher,
  2728. pkgCache::VerIterator Ver, string targetfile)
  2729. /* Download a changelog file for the given package version to
  2730. * targetfile. This will first try the server from Apt::Changelogs::Server
  2731. * (http://packages.debian.org/changelogs by default) and if that gives
  2732. * a 404 tries to get it from the archive directly (see
  2733. * GuessThirdPartyChangelogUri for details how)
  2734. */
  2735. {
  2736. string path;
  2737. string descr;
  2738. string server;
  2739. string changelog_uri;
  2740. // data structures we need
  2741. pkgCache::PkgIterator Pkg = Ver.ParentPkg();
  2742. // make the server root configurable
  2743. server = _config->Find("Apt::Changelogs::Server",
  2744. "http://packages.debian.org/changelogs");
  2745. path = GetChangelogPath(CacheFile, Pkg, Ver);
  2746. strprintf(changelog_uri, "%s/%s/changelog", server.c_str(), path.c_str());
  2747. if (_config->FindB("APT::Get::Print-URIs", false) == true)
  2748. {
  2749. std::cout << '\'' << changelog_uri << '\'' << std::endl;
  2750. return true;
  2751. }
  2752. strprintf(descr, _("Changelog for %s (%s)"), Pkg.Name(), changelog_uri.c_str());
  2753. // queue it
  2754. new pkgAcqFile(&Fetcher, changelog_uri, "", 0, descr, Pkg.Name(), "ignored", targetfile);
  2755. // try downloading it, if that fails, try third-party-changelogs location
  2756. // FIXME: Fetcher.Run() is "Continue" even if I get a 404?!?
  2757. Fetcher.Run();
  2758. if (!FileExists(targetfile))
  2759. {
  2760. string third_party_uri;
  2761. if (GuessThirdPartyChangelogUri(CacheFile, Pkg, Ver, third_party_uri))
  2762. {
  2763. strprintf(descr, _("Changelog for %s (%s)"), Pkg.Name(), third_party_uri.c_str());
  2764. new pkgAcqFile(&Fetcher, third_party_uri, "", 0, descr, Pkg.Name(), "ignored", targetfile);
  2765. Fetcher.Run();
  2766. }
  2767. }
  2768. if (FileExists(targetfile))
  2769. return true;
  2770. // error
  2771. return _error->Error("changelog download failed");
  2772. }
  2773. /*}}}*/
  2774. // DisplayFileInPager - Display File with pager /*{{{*/
  2775. void DisplayFileInPager(string filename)
  2776. {
  2777. pid_t Process = ExecFork();
  2778. if (Process == 0)
  2779. {
  2780. const char *Args[3];
  2781. Args[0] = "/usr/bin/sensible-pager";
  2782. Args[1] = filename.c_str();
  2783. Args[2] = 0;
  2784. execvp(Args[0],(char **)Args);
  2785. exit(100);
  2786. }
  2787. // Wait for the subprocess
  2788. ExecWait(Process, "sensible-pager", false);
  2789. }
  2790. /*}}}*/
  2791. // DoChangelog - Get changelog from the command line /*{{{*/
  2792. // ---------------------------------------------------------------------
  2793. bool DoChangelog(CommandLine &CmdL)
  2794. {
  2795. CacheFile Cache;
  2796. if (Cache.ReadOnlyOpen() == false)
  2797. return false;
  2798. APT::CacheSetHelper helper(c0out);
  2799. APT::VersionSet verset = APT::VersionSet::FromCommandLine(Cache,
  2800. CmdL.FileList + 1, APT::VersionSet::CANDIDATE, helper);
  2801. if (verset.empty() == true)
  2802. return false;
  2803. pkgAcquire Fetcher;
  2804. if (_config->FindB("APT::Get::Print-URIs", false) == true)
  2805. for (APT::VersionSet::const_iterator Ver = verset.begin();
  2806. Ver != verset.end(); ++Ver)
  2807. return DownloadChangelog(Cache, Fetcher, Ver, "");
  2808. AcqTextStatus Stat(ScreenWidth, _config->FindI("quiet",0));
  2809. Fetcher.Setup(&Stat);
  2810. bool const downOnly = _config->FindB("APT::Get::Download-Only", false);
  2811. char tmpname[100];
  2812. char* tmpdir = NULL;
  2813. if (downOnly == false)
  2814. {
  2815. const char* const tmpDir = getenv("TMPDIR");
  2816. if (tmpDir != NULL && *tmpDir != '\0')
  2817. snprintf(tmpname, sizeof(tmpname), "%s/apt-changelog-XXXXXX", tmpDir);
  2818. else
  2819. strncpy(tmpname, "/tmp/apt-changelog-XXXXXX", sizeof(tmpname));
  2820. tmpdir = mkdtemp(tmpname);
  2821. if (tmpdir == NULL)
  2822. return _error->Errno("mkdtemp", "mkdtemp failed");
  2823. }
  2824. for (APT::VersionSet::const_iterator Ver = verset.begin();
  2825. Ver != verset.end();
  2826. ++Ver)
  2827. {
  2828. string changelogfile;
  2829. if (downOnly == false)
  2830. changelogfile.append(tmpname).append("changelog");
  2831. else
  2832. changelogfile.append(Ver.ParentPkg().Name()).append(".changelog");
  2833. if (DownloadChangelog(Cache, Fetcher, Ver, changelogfile) && downOnly == false)
  2834. {
  2835. DisplayFileInPager(changelogfile);
  2836. // cleanup temp file
  2837. unlink(changelogfile.c_str());
  2838. }
  2839. }
  2840. // clenaup tmp dir
  2841. if (tmpdir != NULL)
  2842. rmdir(tmpdir);
  2843. return true;
  2844. }
  2845. /*}}}*/
  2846. // DoMoo - Never Ask, Never Tell /*{{{*/
  2847. // ---------------------------------------------------------------------
  2848. /* */
  2849. bool DoMoo(CommandLine &CmdL)
  2850. {
  2851. cout <<
  2852. " (__) \n"
  2853. " (oo) \n"
  2854. " /------\\/ \n"
  2855. " / | || \n"
  2856. " * /\\---/\\ \n"
  2857. " ~~ ~~ \n"
  2858. "....\"Have you mooed today?\"...\n";
  2859. return true;
  2860. }
  2861. /*}}}*/
  2862. // ShowHelp - Show a help screen /*{{{*/
  2863. // ---------------------------------------------------------------------
  2864. /* */
  2865. bool ShowHelp(CommandLine &CmdL)
  2866. {
  2867. ioprintf(cout,_("%s %s for %s compiled on %s %s\n"),PACKAGE,VERSION,
  2868. COMMON_ARCH,__DATE__,__TIME__);
  2869. if (_config->FindB("version") == true)
  2870. {
  2871. cout << _("Supported modules:") << endl;
  2872. for (unsigned I = 0; I != pkgVersioningSystem::GlobalListLen; I++)
  2873. {
  2874. pkgVersioningSystem *VS = pkgVersioningSystem::GlobalList[I];
  2875. if (_system != 0 && _system->VS == VS)
  2876. cout << '*';
  2877. else
  2878. cout << ' ';
  2879. cout << "Ver: " << VS->Label << endl;
  2880. /* Print out all the packaging systems that will work with
  2881. this VS */
  2882. for (unsigned J = 0; J != pkgSystem::GlobalListLen; J++)
  2883. {
  2884. pkgSystem *Sys = pkgSystem::GlobalList[J];
  2885. if (_system == Sys)
  2886. cout << '*';
  2887. else
  2888. cout << ' ';
  2889. if (Sys->VS->TestCompatibility(*VS) == true)
  2890. cout << "Pkg: " << Sys->Label << " (Priority " << Sys->Score(*_config) << ")" << endl;
  2891. }
  2892. }
  2893. for (unsigned I = 0; I != pkgSourceList::Type::GlobalListLen; I++)
  2894. {
  2895. pkgSourceList::Type *Type = pkgSourceList::Type::GlobalList[I];
  2896. cout << " S.L: '" << Type->Name << "' " << Type->Label << endl;
  2897. }
  2898. for (unsigned I = 0; I != pkgIndexFile::Type::GlobalListLen; I++)
  2899. {
  2900. pkgIndexFile::Type *Type = pkgIndexFile::Type::GlobalList[I];
  2901. cout << " Idx: " << Type->Label << endl;
  2902. }
  2903. return true;
  2904. }
  2905. cout <<
  2906. _("Usage: apt-get [options] command\n"
  2907. " apt-get [options] install|remove pkg1 [pkg2 ...]\n"
  2908. " apt-get [options] source pkg1 [pkg2 ...]\n"
  2909. "\n"
  2910. "apt-get is a simple command line interface for downloading and\n"
  2911. "installing packages. The most frequently used commands are update\n"
  2912. "and install.\n"
  2913. "\n"
  2914. "Commands:\n"
  2915. " update - Retrieve new lists of packages\n"
  2916. " upgrade - Perform an upgrade\n"
  2917. " install - Install new packages (pkg is libc6 not libc6.deb)\n"
  2918. " remove - Remove packages\n"
  2919. " autoremove - Remove automatically all unused packages\n"
  2920. " purge - Remove packages and config files\n"
  2921. " source - Download source archives\n"
  2922. " build-dep - Configure build-dependencies for source packages\n"
  2923. " dist-upgrade - Distribution upgrade, see apt-get(8)\n"
  2924. " dselect-upgrade - Follow dselect selections\n"
  2925. " clean - Erase downloaded archive files\n"
  2926. " autoclean - Erase old downloaded archive files\n"
  2927. " check - Verify that there are no broken dependencies\n"
  2928. " changelog - Download and display the changelog for the given package\n"
  2929. " download - Download the binary package into the current directory\n"
  2930. "\n"
  2931. "Options:\n"
  2932. " -h This help text.\n"
  2933. " -q Loggable output - no progress indicator\n"
  2934. " -qq No output except for errors\n"
  2935. " -d Download only - do NOT install or unpack archives\n"
  2936. " -s No-act. Perform ordering simulation\n"
  2937. " -y Assume Yes to all queries and do not prompt\n"
  2938. " -f Attempt to correct a system with broken dependencies in place\n"
  2939. " -m Attempt to continue if archives are unlocatable\n"
  2940. " -u Show a list of upgraded packages as well\n"
  2941. " -b Build the source package after fetching it\n"
  2942. " -V Show verbose version numbers\n"
  2943. " -c=? Read this configuration file\n"
  2944. " -o=? Set an arbitrary configuration option, eg -o dir::cache=/tmp\n"
  2945. "See the apt-get(8), sources.list(5) and apt.conf(5) manual\n"
  2946. "pages for more information and options.\n"
  2947. " This APT has Super Cow Powers.\n");
  2948. return true;
  2949. }
  2950. /*}}}*/
  2951. // SigWinch - Window size change signal handler /*{{{*/
  2952. // ---------------------------------------------------------------------
  2953. /* */
  2954. void SigWinch(int)
  2955. {
  2956. // Riped from GNU ls
  2957. #ifdef TIOCGWINSZ
  2958. struct winsize ws;
  2959. if (ioctl(1, TIOCGWINSZ, &ws) != -1 && ws.ws_col >= 5)
  2960. ScreenWidth = ws.ws_col - 1;
  2961. #endif
  2962. }
  2963. /*}}}*/
  2964. int main(int argc,const char *argv[]) /*{{{*/
  2965. {
  2966. CommandLine::Args Args[] = {
  2967. {'h',"help","help",0},
  2968. {'v',"version","version",0},
  2969. {'V',"verbose-versions","APT::Get::Show-Versions",0},
  2970. {'q',"quiet","quiet",CommandLine::IntLevel},
  2971. {'q',"silent","quiet",CommandLine::IntLevel},
  2972. {'d',"download-only","APT::Get::Download-Only",0},
  2973. {'b',"compile","APT::Get::Compile",0},
  2974. {'b',"build","APT::Get::Compile",0},
  2975. {'s',"simulate","APT::Get::Simulate",0},
  2976. {'s',"just-print","APT::Get::Simulate",0},
  2977. {'s',"recon","APT::Get::Simulate",0},
  2978. {'s',"dry-run","APT::Get::Simulate",0},
  2979. {'s',"no-act","APT::Get::Simulate",0},
  2980. {'y',"yes","APT::Get::Assume-Yes",0},
  2981. {'y',"assume-yes","APT::Get::Assume-Yes",0},
  2982. {'f',"fix-broken","APT::Get::Fix-Broken",0},
  2983. {'u',"show-upgraded","APT::Get::Show-Upgraded",0},
  2984. {'m',"ignore-missing","APT::Get::Fix-Missing",0},
  2985. {'t',"target-release","APT::Default-Release",CommandLine::HasArg},
  2986. {'t',"default-release","APT::Default-Release",CommandLine::HasArg},
  2987. {'a',"host-architecture","APT::Get::Host-Architecture",CommandLine::HasArg},
  2988. {0,"download","APT::Get::Download",0},
  2989. {0,"fix-missing","APT::Get::Fix-Missing",0},
  2990. {0,"ignore-hold","APT::Ignore-Hold",0},
  2991. {0,"upgrade","APT::Get::upgrade",0},
  2992. {0,"only-upgrade","APT::Get::Only-Upgrade",0},
  2993. {0,"force-yes","APT::Get::force-yes",0},
  2994. {0,"print-uris","APT::Get::Print-URIs",0},
  2995. {0,"diff-only","APT::Get::Diff-Only",0},
  2996. {0,"debian-only","APT::Get::Diff-Only",0},
  2997. {0,"tar-only","APT::Get::Tar-Only",0},
  2998. {0,"dsc-only","APT::Get::Dsc-Only",0},
  2999. {0,"purge","APT::Get::Purge",0},
  3000. {0,"list-cleanup","APT::Get::List-Cleanup",0},
  3001. {0,"reinstall","APT::Get::ReInstall",0},
  3002. {0,"trivial-only","APT::Get::Trivial-Only",0},
  3003. {0,"remove","APT::Get::Remove",0},
  3004. {0,"only-source","APT::Get::Only-Source",0},
  3005. {0,"arch-only","APT::Get::Arch-Only",0},
  3006. {0,"auto-remove","APT::Get::AutomaticRemove",0},
  3007. {0,"allow-unauthenticated","APT::Get::AllowUnauthenticated",0},
  3008. {0,"install-recommends","APT::Install-Recommends",CommandLine::Boolean},
  3009. {0,"install-suggests","APT::Install-Suggests",CommandLine::Boolean},
  3010. {0,"fix-policy","APT::Get::Fix-Policy-Broken",0},
  3011. {'c',"config-file",0,CommandLine::ConfigFile},
  3012. {'o',"option",0,CommandLine::ArbItem},
  3013. {0,0,0,0}};
  3014. CommandLine::Dispatch Cmds[] = {{"update",&DoUpdate},
  3015. {"upgrade",&DoUpgrade},
  3016. {"install",&DoInstall},
  3017. {"remove",&DoInstall},
  3018. {"purge",&DoInstall},
  3019. {"autoremove",&DoInstall},
  3020. {"markauto",&DoMarkAuto},
  3021. {"unmarkauto",&DoMarkAuto},
  3022. {"dist-upgrade",&DoDistUpgrade},
  3023. {"dselect-upgrade",&DoDSelectUpgrade},
  3024. {"build-dep",&DoBuildDep},
  3025. {"clean",&DoClean},
  3026. {"autoclean",&DoAutoClean},
  3027. {"check",&DoCheck},
  3028. {"source",&DoSource},
  3029. {"download",&DoDownload},
  3030. {"changelog",&DoChangelog},
  3031. {"moo",&DoMoo},
  3032. {"help",&ShowHelp},
  3033. {0,0}};
  3034. // Set up gettext support
  3035. setlocale(LC_ALL,"");
  3036. textdomain(PACKAGE);
  3037. // Parse the command line and initialize the package library
  3038. CommandLine CmdL(Args,_config);
  3039. if (pkgInitConfig(*_config) == false ||
  3040. CmdL.Parse(argc,argv) == false ||
  3041. pkgInitSystem(*_config,_system) == false)
  3042. {
  3043. if (_config->FindB("version") == true)
  3044. ShowHelp(CmdL);
  3045. _error->DumpErrors();
  3046. return 100;
  3047. }
  3048. // See if the help should be shown
  3049. if (_config->FindB("help") == true ||
  3050. _config->FindB("version") == true ||
  3051. CmdL.FileSize() == 0)
  3052. {
  3053. ShowHelp(CmdL);
  3054. return 0;
  3055. }
  3056. // simulate user-friendly if apt-get has no root privileges
  3057. if (getuid() != 0 && _config->FindB("APT::Get::Simulate") == true &&
  3058. (CmdL.FileSize() == 0 ||
  3059. (strcmp(CmdL.FileList[0], "source") != 0 && strcmp(CmdL.FileList[0], "download") != 0 &&
  3060. strcmp(CmdL.FileList[0], "changelog") != 0)))
  3061. {
  3062. if (_config->FindB("APT::Get::Show-User-Simulation-Note",true) == true)
  3063. cout << _("NOTE: This is only a simulation!\n"
  3064. " apt-get needs root privileges for real execution.\n"
  3065. " Keep also in mind that locking is deactivated,\n"
  3066. " so don't depend on the relevance to the real current situation!"
  3067. ) << std::endl;
  3068. _config->Set("Debug::NoLocking",true);
  3069. }
  3070. // Deal with stdout not being a tty
  3071. if (!isatty(STDOUT_FILENO) && _config->FindI("quiet", -1) == -1)
  3072. _config->Set("quiet","1");
  3073. // Setup the output streams
  3074. c0out.rdbuf(cout.rdbuf());
  3075. c1out.rdbuf(cout.rdbuf());
  3076. c2out.rdbuf(cout.rdbuf());
  3077. if (_config->FindI("quiet",0) > 0)
  3078. c0out.rdbuf(devnull.rdbuf());
  3079. if (_config->FindI("quiet",0) > 1)
  3080. c1out.rdbuf(devnull.rdbuf());
  3081. // Setup the signals
  3082. signal(SIGPIPE,SIG_IGN);
  3083. signal(SIGWINCH,SigWinch);
  3084. SigWinch(0);
  3085. // Match the operation
  3086. CmdL.DispatchArg(Cmds);
  3087. // Print any errors or warnings found during parsing
  3088. bool const Errors = _error->PendingError();
  3089. if (_config->FindI("quiet",0) > 0)
  3090. _error->DumpErrors();
  3091. else
  3092. _error->DumpErrors(GlobalError::DEBUG);
  3093. return Errors == true ? 100 : 0;
  3094. }
  3095. /*}}}*/