apt-get.cc 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683
  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. #include <config.h>
  25. #include <apt-pkg/aptconfiguration.h>
  26. #include <apt-pkg/error.h>
  27. #include <apt-pkg/cmndline.h>
  28. #include <apt-pkg/init.h>
  29. #include <apt-pkg/depcache.h>
  30. #include <apt-pkg/sourcelist.h>
  31. #include <apt-pkg/algorithms.h>
  32. #include <apt-pkg/acquire-item.h>
  33. #include <apt-pkg/strutl.h>
  34. #include <apt-pkg/fileutl.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 <apt-pkg/progress.h>
  44. #include <apt-pkg/pkgsystem.h>
  45. #include <apt-pkg/pkgrecords.h>
  46. #include <apt-pkg/indexfile.h>
  47. #include <apt-pkg/upgrade.h>
  48. #include <apt-pkg/metaindex.h>
  49. #include <apt-pkg/indexrecords.h>
  50. #include <apt-private/private-download.h>
  51. #include <apt-private/private-install.h>
  52. #include <apt-private/private-upgrade.h>
  53. #include <apt-private/private-output.h>
  54. #include <apt-private/private-cacheset.h>
  55. #include <apt-private/private-update.h>
  56. #include <apt-private/private-cmndline.h>
  57. #include <apt-private/private-moo.h>
  58. #include <apt-private/private-utils.h>
  59. #include <apt-private/acqprogress.h>
  60. #include <set>
  61. #include <fstream>
  62. #include <sstream>
  63. #include <locale.h>
  64. #include <langinfo.h>
  65. #include <termios.h>
  66. #include <sys/ioctl.h>
  67. #include <sys/stat.h>
  68. #include <sys/statfs.h>
  69. #include <sys/statvfs.h>
  70. #include <signal.h>
  71. #include <unistd.h>
  72. #include <stdio.h>
  73. #include <errno.h>
  74. #include <regex.h>
  75. #include <sys/wait.h>
  76. #include <apt-private/private-output.h>
  77. #include <apt-private/private-main.h>
  78. #include <apti18n.h>
  79. /*}}}*/
  80. using namespace std;
  81. // TryToInstallBuildDep - Try to install a single package /*{{{*/
  82. // ---------------------------------------------------------------------
  83. /* This used to be inlined in DoInstall, but with the advent of regex package
  84. name matching it was split out.. */
  85. bool TryToInstallBuildDep(pkgCache::PkgIterator Pkg,pkgCacheFile &Cache,
  86. pkgProblemResolver &Fix,bool Remove,bool BrokenFix,
  87. bool AllowFail = true)
  88. {
  89. if (Cache[Pkg].CandidateVer == 0 && Pkg->ProvidesList != 0)
  90. {
  91. CacheSetHelperAPTGet helper(c1out);
  92. helper.showErrors(false);
  93. pkgCache::VerIterator Ver = helper.canNotFindNewestVer(Cache, Pkg);
  94. if (Ver.end() == false)
  95. Pkg = Ver.ParentPkg();
  96. else if (helper.showVirtualPackageErrors(Cache) == false)
  97. return AllowFail;
  98. }
  99. if (_config->FindB("Debug::BuildDeps",false) == true)
  100. {
  101. if (Remove == true)
  102. cout << " Trying to remove " << Pkg << endl;
  103. else
  104. cout << " Trying to install " << Pkg << endl;
  105. }
  106. if (Remove == true)
  107. {
  108. TryToRemove RemoveAction(Cache, &Fix);
  109. RemoveAction(Pkg.VersionList());
  110. } else if (Cache[Pkg].CandidateVer != 0) {
  111. TryToInstall InstallAction(Cache, &Fix, BrokenFix);
  112. InstallAction(Cache[Pkg].CandidateVerIter(Cache));
  113. InstallAction.doAutoInstall();
  114. } else
  115. return AllowFail;
  116. return true;
  117. }
  118. /*}}}*/
  119. // FindSrc - Find a source record /*{{{*/
  120. // ---------------------------------------------------------------------
  121. /* */
  122. pkgSrcRecords::Parser *FindSrc(const char *Name,pkgRecords &Recs,
  123. pkgSrcRecords &SrcRecs,string &Src,
  124. CacheFile &CacheFile)
  125. {
  126. string VerTag;
  127. string DefRel = _config->Find("APT::Default-Release");
  128. string TmpSrc = Name;
  129. pkgDepCache *Cache = CacheFile.GetDepCache();
  130. // extract the version/release from the pkgname
  131. const size_t found = TmpSrc.find_last_of("/=");
  132. if (found != string::npos) {
  133. if (TmpSrc[found] == '/')
  134. DefRel = TmpSrc.substr(found+1);
  135. else
  136. VerTag = TmpSrc.substr(found+1);
  137. TmpSrc = TmpSrc.substr(0,found);
  138. }
  139. /* Lookup the version of the package we would install if we were to
  140. install a version and determine the source package name, then look
  141. in the archive for a source package of the same name. */
  142. bool MatchSrcOnly = _config->FindB("APT::Get::Only-Source");
  143. const pkgCache::PkgIterator Pkg = Cache->FindPkg(TmpSrc);
  144. if (MatchSrcOnly == false && Pkg.end() == false)
  145. {
  146. if(VerTag.empty() == false || DefRel.empty() == false)
  147. {
  148. bool fuzzy = false;
  149. // we have a default release, try to locate the pkg. we do it like
  150. // this because GetCandidateVer() will not "downgrade", that means
  151. // "apt-get source -t stable apt" won't work on a unstable system
  152. for (pkgCache::VerIterator Ver = Pkg.VersionList();; ++Ver)
  153. {
  154. // try first only exact matches, later fuzzy matches
  155. if (Ver.end() == true)
  156. {
  157. if (fuzzy == true)
  158. break;
  159. fuzzy = true;
  160. Ver = Pkg.VersionList();
  161. // exit right away from the Pkg.VersionList() loop if we
  162. // don't have any versions
  163. if (Ver.end() == true)
  164. break;
  165. }
  166. // We match against a concrete version (or a part of this version)
  167. if (VerTag.empty() == false &&
  168. (fuzzy == true || Cache->VS().CmpVersion(VerTag, Ver.VerStr()) != 0) && // exact match
  169. (fuzzy == false || strncmp(VerTag.c_str(), Ver.VerStr(), VerTag.size()) != 0)) // fuzzy match
  170. continue;
  171. for (pkgCache::VerFileIterator VF = Ver.FileList();
  172. VF.end() == false; ++VF)
  173. {
  174. /* If this is the status file, and the current version is not the
  175. version in the status file (ie it is not installed, or somesuch)
  176. then it is not a candidate for installation, ever. This weeds
  177. out bogus entries that may be due to config-file states, or
  178. other. */
  179. if ((VF.File()->Flags & pkgCache::Flag::NotSource) ==
  180. pkgCache::Flag::NotSource && Pkg.CurrentVer() != Ver)
  181. continue;
  182. // or we match against a release
  183. if(VerTag.empty() == false ||
  184. (VF.File().Archive() != 0 && VF.File().Archive() == DefRel) ||
  185. (VF.File().Codename() != 0 && VF.File().Codename() == DefRel))
  186. {
  187. pkgRecords::Parser &Parse = Recs.Lookup(VF);
  188. Src = Parse.SourcePkg();
  189. // no SourcePkg name, so it is the "binary" name
  190. if (Src.empty() == true)
  191. Src = TmpSrc;
  192. // the Version we have is possibly fuzzy or includes binUploads,
  193. // so we use the Version of the SourcePkg (empty if same as package)
  194. VerTag = Parse.SourceVer();
  195. if (VerTag.empty() == true)
  196. VerTag = Ver.VerStr();
  197. break;
  198. }
  199. }
  200. if (Src.empty() == false)
  201. break;
  202. }
  203. #if 0
  204. if (Src.empty() == true)
  205. {
  206. // Sources files have no codename information
  207. if (VerTag.empty() == true && DefRel.empty() == false)
  208. {
  209. _error->Warning(_("Ignore unavailable target release '%s' of package '%s'"), DefRel.c_str(), TmpSrc.c_str());
  210. return 0;
  211. }
  212. }
  213. #endif
  214. }
  215. if (Src.empty() == true)
  216. {
  217. // if we don't have found a fitting package yet so we will
  218. // choose a good candidate and proceed with that.
  219. // Maybe we will find a source later on with the right VerTag
  220. pkgCache::VerIterator Ver = Cache->GetCandidateVer(Pkg);
  221. if (Ver.end() == false)
  222. {
  223. pkgRecords::Parser &Parse = Recs.Lookup(Ver.FileList());
  224. Src = Parse.SourcePkg();
  225. if (VerTag.empty() == true)
  226. VerTag = Parse.SourceVer();
  227. }
  228. }
  229. }
  230. if (Src.empty() == true)
  231. Src = TmpSrc;
  232. else
  233. {
  234. /* if we have a source pkg name, make sure to only search
  235. for srcpkg names, otherwise apt gets confused if there
  236. is a binary package "pkg1" and a source package "pkg1"
  237. with the same name but that comes from different packages */
  238. MatchSrcOnly = true;
  239. if (Src != TmpSrc)
  240. {
  241. ioprintf(c1out, _("Picking '%s' as source package instead of '%s'\n"), Src.c_str(), TmpSrc.c_str());
  242. }
  243. }
  244. // The best hit
  245. pkgSrcRecords::Parser *Last = 0;
  246. unsigned long Offset = 0;
  247. string Version;
  248. string FoundRel;
  249. /* Iterate over all of the hits, which includes the resulting
  250. binary packages in the search */
  251. pkgSrcRecords::Parser *Parse;
  252. while (true)
  253. {
  254. SrcRecs.Restart();
  255. while ((Parse = SrcRecs.Find(Src.c_str(), MatchSrcOnly)) != 0)
  256. {
  257. const string Ver = Parse->Version();
  258. // find release
  259. const pkgIndexFile& SI = Parse->Index();
  260. pkgSourceList *SrcList = CacheFile.GetSourceList();
  261. for (pkgSourceList::const_iterator S = SrcList->begin();
  262. S != SrcList->end(); ++S)
  263. {
  264. vector<pkgIndexFile *> *Indexes = (*S)->GetIndexFiles();
  265. for (vector<pkgIndexFile *>::const_iterator IF = Indexes->begin();
  266. IF != Indexes->end(); ++IF)
  267. {
  268. if (&SI == (*IF))
  269. {
  270. std::string dirname = _config->FindDir("Dir::State::lists");
  271. std::string path = dirname + URItoFileName((*S)->GetURI()) + "dists_" + (*S)->GetDist() + "_Release";
  272. indexRecords records;
  273. records.Load(path);
  274. if (records.GetSuite() == DefRel)
  275. {
  276. ioprintf(clog, "Selectied version '%s' (%s) for %s\n",
  277. Ver.c_str(), DefRel.c_str(), Src.c_str());
  278. Last = Parse;
  279. Offset = Parse->Offset();
  280. Version = Ver;
  281. FoundRel = DefRel;
  282. break;
  283. }
  284. }
  285. }
  286. }
  287. if (DefRel.empty() == false && (DefRel == FoundRel))
  288. break;
  289. // Ignore all versions which doesn't fit
  290. if (VerTag.empty() == false &&
  291. Cache->VS().CmpVersion(VerTag, Ver) != 0) // exact match
  292. continue;
  293. // Newer version or an exact match? Save the hit
  294. if (Last == 0 || Cache->VS().CmpVersion(Version,Ver) < 0) {
  295. Last = Parse;
  296. Offset = Parse->Offset();
  297. Version = Ver;
  298. }
  299. // was the version check above an exact match? If so, we don't need to look further
  300. if (VerTag.empty() == false && (VerTag == Ver))
  301. {
  302. std::cerr << "meep" << std::endl;
  303. break;
  304. }
  305. }
  306. if (Last != 0 || VerTag.empty() == true)
  307. break;
  308. return 0;
  309. }
  310. if (Last == 0 || Last->Jump(Offset) == false)
  311. return 0;
  312. return Last;
  313. }
  314. /*}}}*/
  315. /* mark packages as automatically/manually installed. {{{*/
  316. bool DoMarkAuto(CommandLine &CmdL)
  317. {
  318. bool Action = true;
  319. int AutoMarkChanged = 0;
  320. OpTextProgress progress;
  321. CacheFile Cache;
  322. if (Cache.Open() == false)
  323. return false;
  324. if (strcasecmp(CmdL.FileList[0],"markauto") == 0)
  325. Action = true;
  326. else if (strcasecmp(CmdL.FileList[0],"unmarkauto") == 0)
  327. Action = false;
  328. for (const char **I = CmdL.FileList + 1; *I != 0; I++)
  329. {
  330. const char *S = *I;
  331. // Locate the package
  332. pkgCache::PkgIterator Pkg = Cache->FindPkg(S);
  333. if (Pkg.end() == true) {
  334. return _error->Error(_("Couldn't find package %s"),S);
  335. }
  336. else
  337. {
  338. if (!Action)
  339. ioprintf(c1out,_("%s set to manually installed.\n"), Pkg.Name());
  340. else
  341. ioprintf(c1out,_("%s set to automatically installed.\n"),
  342. Pkg.Name());
  343. Cache->MarkAuto(Pkg,Action);
  344. AutoMarkChanged++;
  345. }
  346. }
  347. _error->Notice(_("This command is deprecated. Please use 'apt-mark auto' and 'apt-mark manual' instead."));
  348. if (AutoMarkChanged && ! _config->FindB("APT::Get::Simulate",false))
  349. return Cache->writeStateFile(NULL);
  350. return false;
  351. }
  352. /*}}}*/
  353. // DoDSelectUpgrade - Do an upgrade by following dselects selections /*{{{*/
  354. // ---------------------------------------------------------------------
  355. /* Follows dselect's selections */
  356. bool DoDSelectUpgrade(CommandLine &CmdL)
  357. {
  358. CacheFile Cache;
  359. if (Cache.OpenForInstall() == false || Cache.CheckDeps() == false)
  360. return false;
  361. pkgDepCache::ActionGroup group(Cache);
  362. // Install everything with the install flag set
  363. pkgCache::PkgIterator I = Cache->PkgBegin();
  364. for (;I.end() != true; ++I)
  365. {
  366. /* Install the package only if it is a new install, the autoupgrader
  367. will deal with the rest */
  368. if (I->SelectedState == pkgCache::State::Install)
  369. Cache->MarkInstall(I,false);
  370. }
  371. /* Now install their deps too, if we do this above then order of
  372. the status file is significant for | groups */
  373. for (I = Cache->PkgBegin();I.end() != true; ++I)
  374. {
  375. /* Install the package only if it is a new install, the autoupgrader
  376. will deal with the rest */
  377. if (I->SelectedState == pkgCache::State::Install)
  378. Cache->MarkInstall(I,true);
  379. }
  380. // Apply erasures now, they override everything else.
  381. for (I = Cache->PkgBegin();I.end() != true; ++I)
  382. {
  383. // Remove packages
  384. if (I->SelectedState == pkgCache::State::DeInstall ||
  385. I->SelectedState == pkgCache::State::Purge)
  386. Cache->MarkDelete(I,I->SelectedState == pkgCache::State::Purge);
  387. }
  388. /* Resolve any problems that dselect created, allupgrade cannot handle
  389. such things. We do so quite agressively too.. */
  390. if (Cache->BrokenCount() != 0)
  391. {
  392. pkgProblemResolver Fix(Cache);
  393. // Hold back held packages.
  394. if (_config->FindB("APT::Ignore-Hold",false) == false)
  395. {
  396. for (pkgCache::PkgIterator I = Cache->PkgBegin(); I.end() == false; ++I)
  397. {
  398. if (I->SelectedState == pkgCache::State::Hold)
  399. {
  400. Fix.Protect(I);
  401. Cache->MarkKeep(I);
  402. }
  403. }
  404. }
  405. if (Fix.Resolve() == false)
  406. {
  407. ShowBroken(c1out,Cache,false);
  408. return _error->Error(_("Internal error, problem resolver broke stuff"));
  409. }
  410. }
  411. // Now upgrade everything
  412. if (pkgAllUpgrade(Cache) == false)
  413. {
  414. ShowBroken(c1out,Cache,false);
  415. return _error->Error(_("Internal error, problem resolver broke stuff"));
  416. }
  417. return InstallPackages(Cache,false);
  418. }
  419. /*}}}*/
  420. // DoClean - Remove download archives /*{{{*/
  421. // ---------------------------------------------------------------------
  422. /* */
  423. bool DoClean(CommandLine &CmdL)
  424. {
  425. std::string const archivedir = _config->FindDir("Dir::Cache::archives");
  426. std::string const pkgcache = _config->FindFile("Dir::cache::pkgcache");
  427. std::string const srcpkgcache = _config->FindFile("Dir::cache::srcpkgcache");
  428. if (_config->FindB("APT::Get::Simulate") == true)
  429. {
  430. cout << "Del " << archivedir << "* " << archivedir << "partial/*"<< endl
  431. << "Del " << pkgcache << " " << srcpkgcache << endl;
  432. return true;
  433. }
  434. // Lock the archive directory
  435. FileFd Lock;
  436. if (_config->FindB("Debug::NoLocking",false) == false)
  437. {
  438. int lock_fd = GetLock(archivedir + "lock");
  439. if (lock_fd < 0)
  440. return _error->Error(_("Unable to lock the download directory"));
  441. Lock.Fd(lock_fd);
  442. }
  443. pkgAcquire Fetcher;
  444. Fetcher.Clean(archivedir);
  445. Fetcher.Clean(archivedir + "partial/");
  446. pkgCacheFile::RemoveCaches();
  447. return true;
  448. }
  449. /*}}}*/
  450. // DoAutoClean - Smartly remove downloaded archives /*{{{*/
  451. // ---------------------------------------------------------------------
  452. /* This is similar to clean but it only purges things that cannot be
  453. downloaded, that is old versions of cached packages. */
  454. class LogCleaner : public pkgArchiveCleaner
  455. {
  456. protected:
  457. virtual void Erase(const char *File,string Pkg,string Ver,struct stat &St)
  458. {
  459. c1out << "Del " << Pkg << " " << Ver << " [" << SizeToStr(St.st_size) << "B]" << endl;
  460. if (_config->FindB("APT::Get::Simulate") == false)
  461. unlink(File);
  462. };
  463. };
  464. bool DoAutoClean(CommandLine &CmdL)
  465. {
  466. // Lock the archive directory
  467. FileFd Lock;
  468. if (_config->FindB("Debug::NoLocking",false) == false)
  469. {
  470. int lock_fd = GetLock(_config->FindDir("Dir::Cache::Archives") + "lock");
  471. if (lock_fd < 0)
  472. return _error->Error(_("Unable to lock the download directory"));
  473. Lock.Fd(lock_fd);
  474. }
  475. CacheFile Cache;
  476. if (Cache.Open() == false)
  477. return false;
  478. LogCleaner Cleaner;
  479. return Cleaner.Go(_config->FindDir("Dir::Cache::archives"),*Cache) &&
  480. Cleaner.Go(_config->FindDir("Dir::Cache::archives") + "partial/",*Cache);
  481. }
  482. /*}}}*/
  483. // DoDownload - download a binary /*{{{*/
  484. // ---------------------------------------------------------------------
  485. bool DoDownload(CommandLine &CmdL)
  486. {
  487. CacheFile Cache;
  488. if (Cache.ReadOnlyOpen() == false)
  489. return false;
  490. APT::CacheSetHelper helper(c0out);
  491. APT::VersionList verset = APT::VersionList::FromCommandLine(Cache,
  492. CmdL.FileList + 1, APT::VersionList::CANDIDATE, helper);
  493. if (verset.empty() == true)
  494. return false;
  495. AcqTextStatus Stat(ScreenWidth, _config->FindI("quiet", 0));
  496. pkgAcquire Fetcher;
  497. if (Fetcher.Setup(&Stat) == false)
  498. return false;
  499. pkgRecords Recs(Cache);
  500. pkgSourceList *SrcList = Cache.GetSourceList();
  501. // reuse the usual acquire methods for deb files, but don't drop them into
  502. // the usual directories - keep everything in the current directory
  503. std::vector<std::string> storefile(verset.size());
  504. std::string const cwd = SafeGetCWD();
  505. _config->Set("Dir::Cache::Archives", cwd);
  506. int i = 0;
  507. for (APT::VersionList::const_iterator Ver = verset.begin();
  508. Ver != verset.end(); ++Ver, ++i)
  509. {
  510. pkgAcquire::Item *I = new pkgAcqArchive(&Fetcher, SrcList, &Recs, *Ver, storefile[i]);
  511. std::string const filename = cwd + flNotDir(storefile[i]);
  512. storefile[i].assign(filename);
  513. I->DestFile.assign(filename);
  514. }
  515. // Just print out the uris and exit if the --print-uris flag was used
  516. if (_config->FindB("APT::Get::Print-URIs") == true)
  517. {
  518. pkgAcquire::UriIterator I = Fetcher.UriBegin();
  519. for (; I != Fetcher.UriEnd(); ++I)
  520. cout << '\'' << I->URI << "' " << flNotDir(I->Owner->DestFile) << ' ' <<
  521. I->Owner->FileSize << ' ' << I->Owner->HashSum() << endl;
  522. return true;
  523. }
  524. if (_error->PendingError() == true || CheckAuth(Fetcher, false) == false)
  525. return false;
  526. bool Failed = false;
  527. if (AcquireRun(Fetcher, 0, &Failed, NULL) == false)
  528. return false;
  529. // copy files in local sources to the current directory
  530. for (pkgAcquire::ItemIterator I = Fetcher.ItemsBegin(); I != Fetcher.ItemsEnd(); ++I)
  531. if ((*I)->Local == true && (*I)->Status == pkgAcquire::Item::StatDone)
  532. {
  533. std::string const filename = cwd + flNotDir((*I)->DestFile);
  534. std::ifstream src((*I)->DestFile.c_str(), std::ios::binary);
  535. std::ofstream dst(filename.c_str(), std::ios::binary);
  536. dst << src.rdbuf();
  537. }
  538. return Failed == false;
  539. }
  540. /*}}}*/
  541. // DoCheck - Perform the check operation /*{{{*/
  542. // ---------------------------------------------------------------------
  543. /* Opening automatically checks the system, this command is mostly used
  544. for debugging */
  545. bool DoCheck(CommandLine &CmdL)
  546. {
  547. CacheFile Cache;
  548. Cache.Open();
  549. Cache.CheckDeps();
  550. return true;
  551. }
  552. /*}}}*/
  553. // DoSource - Fetch a source archive /*{{{*/
  554. // ---------------------------------------------------------------------
  555. /* Fetch souce packages */
  556. struct DscFile
  557. {
  558. string Package;
  559. string Version;
  560. string Dsc;
  561. };
  562. bool DoSource(CommandLine &CmdL)
  563. {
  564. CacheFile Cache;
  565. if (Cache.Open(false) == false)
  566. return false;
  567. if (CmdL.FileSize() <= 1)
  568. return _error->Error(_("Must specify at least one package to fetch source for"));
  569. // Read the source list
  570. if (Cache.BuildSourceList() == false)
  571. return false;
  572. pkgSourceList *List = Cache.GetSourceList();
  573. // Create the text record parsers
  574. pkgRecords Recs(Cache);
  575. pkgSrcRecords SrcRecs(*List);
  576. if (_error->PendingError() == true)
  577. return false;
  578. // Create the download object
  579. AcqTextStatus Stat(ScreenWidth,_config->FindI("quiet",0));
  580. pkgAcquire Fetcher;
  581. Fetcher.SetLog(&Stat);
  582. DscFile *Dsc = new DscFile[CmdL.FileSize()];
  583. // insert all downloaded uris into this set to avoid downloading them
  584. // twice
  585. set<string> queued;
  586. // Diff only mode only fetches .diff files
  587. bool const diffOnly = _config->FindB("APT::Get::Diff-Only", false);
  588. // Tar only mode only fetches .tar files
  589. bool const tarOnly = _config->FindB("APT::Get::Tar-Only", false);
  590. // Dsc only mode only fetches .dsc files
  591. bool const dscOnly = _config->FindB("APT::Get::Dsc-Only", false);
  592. // Load the requestd sources into the fetcher
  593. unsigned J = 0;
  594. for (const char **I = CmdL.FileList + 1; *I != 0; I++, J++)
  595. {
  596. string Src;
  597. pkgSrcRecords::Parser *Last = FindSrc(*I,Recs,SrcRecs,Src,Cache);
  598. if (Last == 0) {
  599. delete[] Dsc;
  600. return _error->Error(_("Unable to find a source package for %s"),Src.c_str());
  601. }
  602. string srec = Last->AsStr();
  603. string::size_type pos = srec.find("\nVcs-");
  604. while (pos != string::npos)
  605. {
  606. pos += strlen("\nVcs-");
  607. string vcs = srec.substr(pos,srec.find(":",pos)-pos);
  608. if(vcs == "Browser")
  609. {
  610. pos = srec.find("\nVcs-", pos);
  611. continue;
  612. }
  613. pos += vcs.length()+2;
  614. string::size_type epos = srec.find("\n", pos);
  615. string uri = srec.substr(pos,epos-pos).c_str();
  616. ioprintf(c1out, _("NOTICE: '%s' packaging is maintained in "
  617. "the '%s' version control system at:\n"
  618. "%s\n"),
  619. Src.c_str(), vcs.c_str(), uri.c_str());
  620. if(vcs == "Bzr")
  621. ioprintf(c1out,_("Please use:\n"
  622. "bzr branch %s\n"
  623. "to retrieve the latest (possibly unreleased) "
  624. "updates to the package.\n"),
  625. uri.c_str());
  626. break;
  627. }
  628. // Back track
  629. vector<pkgSrcRecords::File> Lst;
  630. if (Last->Files(Lst) == false) {
  631. delete[] Dsc;
  632. return false;
  633. }
  634. // Load them into the fetcher
  635. for (vector<pkgSrcRecords::File>::const_iterator I = Lst.begin();
  636. I != Lst.end(); ++I)
  637. {
  638. // Try to guess what sort of file it is we are getting.
  639. if (I->Type == "dsc")
  640. {
  641. Dsc[J].Package = Last->Package();
  642. Dsc[J].Version = Last->Version();
  643. Dsc[J].Dsc = flNotDir(I->Path);
  644. }
  645. // Handle the only options so that multiple can be used at once
  646. if (diffOnly == true || tarOnly == true || dscOnly == true)
  647. {
  648. if ((diffOnly == true && I->Type == "diff") ||
  649. (tarOnly == true && I->Type == "tar") ||
  650. (dscOnly == true && I->Type == "dsc"))
  651. ; // Fine, we want this file downloaded
  652. else
  653. continue;
  654. }
  655. // don't download the same uri twice (should this be moved to
  656. // the fetcher interface itself?)
  657. if(queued.find(Last->Index().ArchiveURI(I->Path)) != queued.end())
  658. continue;
  659. queued.insert(Last->Index().ArchiveURI(I->Path));
  660. // check if we have a file with that md5 sum already localy
  661. if(!I->MD5Hash.empty() && FileExists(flNotDir(I->Path)))
  662. {
  663. FileFd Fd(flNotDir(I->Path), FileFd::ReadOnly);
  664. MD5Summation sum;
  665. sum.AddFD(Fd.Fd(), Fd.Size());
  666. Fd.Close();
  667. if((string)sum.Result() == I->MD5Hash)
  668. {
  669. ioprintf(c1out,_("Skipping already downloaded file '%s'\n"),
  670. flNotDir(I->Path).c_str());
  671. continue;
  672. }
  673. }
  674. new pkgAcqFile(&Fetcher,Last->Index().ArchiveURI(I->Path),
  675. I->MD5Hash,I->Size,
  676. Last->Index().SourceInfo(*Last,*I),Src);
  677. }
  678. }
  679. // Display statistics
  680. unsigned long long FetchBytes = Fetcher.FetchNeeded();
  681. unsigned long long FetchPBytes = Fetcher.PartialPresent();
  682. unsigned long long DebBytes = Fetcher.TotalNeeded();
  683. // Check for enough free space
  684. struct statvfs Buf;
  685. string OutputDir = ".";
  686. if (statvfs(OutputDir.c_str(),&Buf) != 0) {
  687. delete[] Dsc;
  688. if (errno == EOVERFLOW)
  689. return _error->WarningE("statvfs",_("Couldn't determine free space in %s"),
  690. OutputDir.c_str());
  691. else
  692. return _error->Errno("statvfs",_("Couldn't determine free space in %s"),
  693. OutputDir.c_str());
  694. } else if (unsigned(Buf.f_bfree) < (FetchBytes - FetchPBytes)/Buf.f_bsize)
  695. {
  696. struct statfs Stat;
  697. if (statfs(OutputDir.c_str(),&Stat) != 0
  698. #if HAVE_STRUCT_STATFS_F_TYPE
  699. || unsigned(Stat.f_type) != RAMFS_MAGIC
  700. #endif
  701. ) {
  702. delete[] Dsc;
  703. return _error->Error(_("You don't have enough free space in %s"),
  704. OutputDir.c_str());
  705. }
  706. }
  707. // Number of bytes
  708. if (DebBytes != FetchBytes)
  709. //TRANSLATOR: The required space between number and unit is already included
  710. // in the replacement strings, so %sB will be correctly translate in e.g. 1,5 MB
  711. ioprintf(c1out,_("Need to get %sB/%sB of source archives.\n"),
  712. SizeToStr(FetchBytes).c_str(),SizeToStr(DebBytes).c_str());
  713. else
  714. //TRANSLATOR: The required space between number and unit is already included
  715. // in the replacement string, so %sB will be correctly translate in e.g. 1,5 MB
  716. ioprintf(c1out,_("Need to get %sB of source archives.\n"),
  717. SizeToStr(DebBytes).c_str());
  718. if (_config->FindB("APT::Get::Simulate",false) == true)
  719. {
  720. for (unsigned I = 0; I != J; I++)
  721. ioprintf(cout,_("Fetch source %s\n"),Dsc[I].Package.c_str());
  722. delete[] Dsc;
  723. return true;
  724. }
  725. // Just print out the uris an exit if the --print-uris flag was used
  726. if (_config->FindB("APT::Get::Print-URIs") == true)
  727. {
  728. pkgAcquire::UriIterator I = Fetcher.UriBegin();
  729. for (; I != Fetcher.UriEnd(); ++I)
  730. cout << '\'' << I->URI << "' " << flNotDir(I->Owner->DestFile) << ' ' <<
  731. I->Owner->FileSize << ' ' << I->Owner->HashSum() << endl;
  732. delete[] Dsc;
  733. return true;
  734. }
  735. // Run it
  736. bool Failed = false;
  737. if (AcquireRun(Fetcher, 0, &Failed, NULL) == false || Failed == true)
  738. {
  739. delete[] Dsc;
  740. return _error->Error(_("Failed to fetch some archives."));
  741. }
  742. if (_config->FindB("APT::Get::Download-only",false) == true)
  743. {
  744. c1out << _("Download complete and in download only mode") << endl;
  745. delete[] Dsc;
  746. return true;
  747. }
  748. // Unpack the sources
  749. pid_t Process = ExecFork();
  750. if (Process == 0)
  751. {
  752. bool const fixBroken = _config->FindB("APT::Get::Fix-Broken", false);
  753. for (unsigned I = 0; I != J; ++I)
  754. {
  755. string Dir = Dsc[I].Package + '-' + Cache->VS().UpstreamVersion(Dsc[I].Version.c_str());
  756. // Diff only mode only fetches .diff files
  757. if (_config->FindB("APT::Get::Diff-Only",false) == true ||
  758. _config->FindB("APT::Get::Tar-Only",false) == true ||
  759. Dsc[I].Dsc.empty() == true)
  760. continue;
  761. // See if the package is already unpacked
  762. struct stat Stat;
  763. if (fixBroken == false && stat(Dir.c_str(),&Stat) == 0 &&
  764. S_ISDIR(Stat.st_mode) != 0)
  765. {
  766. ioprintf(c0out ,_("Skipping unpack of already unpacked source in %s\n"),
  767. Dir.c_str());
  768. }
  769. else
  770. {
  771. // Call dpkg-source
  772. char S[500];
  773. snprintf(S,sizeof(S),"%s -x %s",
  774. _config->Find("Dir::Bin::dpkg-source","dpkg-source").c_str(),
  775. Dsc[I].Dsc.c_str());
  776. if (system(S) != 0)
  777. {
  778. fprintf(stderr,_("Unpack command '%s' failed.\n"),S);
  779. fprintf(stderr,_("Check if the 'dpkg-dev' package is installed.\n"));
  780. _exit(1);
  781. }
  782. }
  783. // Try to compile it with dpkg-buildpackage
  784. if (_config->FindB("APT::Get::Compile",false) == true)
  785. {
  786. string buildopts = _config->Find("APT::Get::Host-Architecture");
  787. if (buildopts.empty() == false)
  788. buildopts = "-a" + buildopts + " ";
  789. buildopts.append(_config->Find("DPkg::Build-Options","-b -uc"));
  790. // Call dpkg-buildpackage
  791. char S[500];
  792. snprintf(S,sizeof(S),"cd %s && %s %s",
  793. Dir.c_str(),
  794. _config->Find("Dir::Bin::dpkg-buildpackage","dpkg-buildpackage").c_str(),
  795. buildopts.c_str());
  796. if (system(S) != 0)
  797. {
  798. fprintf(stderr,_("Build command '%s' failed.\n"),S);
  799. _exit(1);
  800. }
  801. }
  802. }
  803. _exit(0);
  804. }
  805. delete[] Dsc;
  806. // Wait for the subprocess
  807. int Status = 0;
  808. while (waitpid(Process,&Status,0) != Process)
  809. {
  810. if (errno == EINTR)
  811. continue;
  812. return _error->Errno("waitpid","Couldn't wait for subprocess");
  813. }
  814. if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
  815. return _error->Error(_("Child process failed"));
  816. return true;
  817. }
  818. /*}}}*/
  819. // DoBuildDep - Install/removes packages to satisfy build dependencies /*{{{*/
  820. // ---------------------------------------------------------------------
  821. /* This function will look at the build depends list of the given source
  822. package and install the necessary packages to make it true, or fail. */
  823. bool DoBuildDep(CommandLine &CmdL)
  824. {
  825. CacheFile Cache;
  826. _config->Set("APT::Install-Recommends", false);
  827. if (Cache.Open(true) == false)
  828. return false;
  829. if (CmdL.FileSize() <= 1)
  830. return _error->Error(_("Must specify at least one package to check builddeps for"));
  831. // Read the source list
  832. if (Cache.BuildSourceList() == false)
  833. return false;
  834. pkgSourceList *List = Cache.GetSourceList();
  835. // Create the text record parsers
  836. pkgRecords Recs(Cache);
  837. pkgSrcRecords SrcRecs(*List);
  838. if (_error->PendingError() == true)
  839. return false;
  840. // Create the download object
  841. AcqTextStatus Stat(ScreenWidth,_config->FindI("quiet",0));
  842. pkgAcquire Fetcher;
  843. if (Fetcher.Setup(&Stat) == false)
  844. return false;
  845. bool StripMultiArch;
  846. string hostArch = _config->Find("APT::Get::Host-Architecture");
  847. if (hostArch.empty() == false)
  848. {
  849. std::vector<std::string> archs = APT::Configuration::getArchitectures();
  850. if (std::find(archs.begin(), archs.end(), hostArch) == archs.end())
  851. return _error->Error(_("No architecture information available for %s. See apt.conf(5) APT::Architectures for setup"), hostArch.c_str());
  852. StripMultiArch = false;
  853. }
  854. else
  855. StripMultiArch = true;
  856. unsigned J = 0;
  857. for (const char **I = CmdL.FileList + 1; *I != 0; I++, J++)
  858. {
  859. string Src;
  860. pkgSrcRecords::Parser *Last = FindSrc(*I,Recs,SrcRecs,Src,Cache);
  861. if (Last == 0)
  862. return _error->Error(_("Unable to find a source package for %s"),Src.c_str());
  863. // Process the build-dependencies
  864. vector<pkgSrcRecords::Parser::BuildDepRec> BuildDeps;
  865. // FIXME: Can't specify architecture to use for [wildcard] matching, so switch default arch temporary
  866. if (hostArch.empty() == false)
  867. {
  868. std::string nativeArch = _config->Find("APT::Architecture");
  869. _config->Set("APT::Architecture", hostArch);
  870. bool Success = Last->BuildDepends(BuildDeps, _config->FindB("APT::Get::Arch-Only", false), StripMultiArch);
  871. _config->Set("APT::Architecture", nativeArch);
  872. if (Success == false)
  873. return _error->Error(_("Unable to get build-dependency information for %s"),Src.c_str());
  874. }
  875. else if (Last->BuildDepends(BuildDeps, _config->FindB("APT::Get::Arch-Only", false), StripMultiArch) == false)
  876. return _error->Error(_("Unable to get build-dependency information for %s"),Src.c_str());
  877. // Also ensure that build-essential packages are present
  878. Configuration::Item const *Opts = _config->Tree("APT::Build-Essential");
  879. if (Opts)
  880. Opts = Opts->Child;
  881. for (; Opts; Opts = Opts->Next)
  882. {
  883. if (Opts->Value.empty() == true)
  884. continue;
  885. pkgSrcRecords::Parser::BuildDepRec rec;
  886. rec.Package = Opts->Value;
  887. rec.Type = pkgSrcRecords::Parser::BuildDependIndep;
  888. rec.Op = 0;
  889. BuildDeps.push_back(rec);
  890. }
  891. if (BuildDeps.empty() == true)
  892. {
  893. ioprintf(c1out,_("%s has no build depends.\n"),Src.c_str());
  894. continue;
  895. }
  896. // Install the requested packages
  897. vector <pkgSrcRecords::Parser::BuildDepRec>::iterator D;
  898. pkgProblemResolver Fix(Cache);
  899. bool skipAlternatives = false; // skip remaining alternatives in an or group
  900. for (D = BuildDeps.begin(); D != BuildDeps.end(); ++D)
  901. {
  902. bool hasAlternatives = (((*D).Op & pkgCache::Dep::Or) == pkgCache::Dep::Or);
  903. if (skipAlternatives == true)
  904. {
  905. /*
  906. * if there are alternatives, we've already picked one, so skip
  907. * the rest
  908. *
  909. * TODO: this means that if there's a build-dep on A|B and B is
  910. * installed, we'll still try to install A; more importantly,
  911. * if A is currently broken, we cannot go back and try B. To fix
  912. * this would require we do a Resolve cycle for each package we
  913. * add to the install list. Ugh
  914. */
  915. if (!hasAlternatives)
  916. skipAlternatives = false; // end of or group
  917. continue;
  918. }
  919. if ((*D).Type == pkgSrcRecords::Parser::BuildConflict ||
  920. (*D).Type == pkgSrcRecords::Parser::BuildConflictIndep)
  921. {
  922. pkgCache::GrpIterator Grp = Cache->FindGrp((*D).Package);
  923. // Build-conflicts on unknown packages are silently ignored
  924. if (Grp.end() == true)
  925. continue;
  926. for (pkgCache::PkgIterator Pkg = Grp.PackageList(); Pkg.end() == false; Pkg = Grp.NextPkg(Pkg))
  927. {
  928. pkgCache::VerIterator IV = (*Cache)[Pkg].InstVerIter(*Cache);
  929. /*
  930. * Remove if we have an installed version that satisfies the
  931. * version criteria
  932. */
  933. if (IV.end() == false &&
  934. Cache->VS().CheckDep(IV.VerStr(),(*D).Op,(*D).Version.c_str()) == true)
  935. TryToInstallBuildDep(Pkg,Cache,Fix,true,false);
  936. }
  937. }
  938. else // BuildDep || BuildDepIndep
  939. {
  940. if (_config->FindB("Debug::BuildDeps",false) == true)
  941. cout << "Looking for " << (*D).Package << "...\n";
  942. pkgCache::PkgIterator Pkg;
  943. // Cross-Building?
  944. if (StripMultiArch == false && D->Type != pkgSrcRecords::Parser::BuildDependIndep)
  945. {
  946. size_t const colon = D->Package.find(":");
  947. if (colon != string::npos)
  948. {
  949. if (strcmp(D->Package.c_str() + colon, ":any") == 0 || strcmp(D->Package.c_str() + colon, ":native") == 0)
  950. Pkg = Cache->FindPkg(D->Package.substr(0,colon));
  951. else
  952. Pkg = Cache->FindPkg(D->Package);
  953. }
  954. else
  955. Pkg = Cache->FindPkg(D->Package, hostArch);
  956. // a bad version either is invalid or doesn't satify dependency
  957. #define BADVER(Ver) (Ver.end() == true || \
  958. (D->Version.empty() == false && \
  959. Cache->VS().CheckDep(Ver.VerStr(),D->Op,D->Version.c_str()) == false))
  960. APT::VersionList verlist;
  961. if (Pkg.end() == false)
  962. {
  963. pkgCache::VerIterator Ver = (*Cache)[Pkg].InstVerIter(*Cache);
  964. if (BADVER(Ver) == false)
  965. verlist.insert(Ver);
  966. Ver = (*Cache)[Pkg].CandidateVerIter(*Cache);
  967. if (BADVER(Ver) == false)
  968. verlist.insert(Ver);
  969. }
  970. if (verlist.empty() == true)
  971. {
  972. pkgCache::PkgIterator BuildPkg = Cache->FindPkg(D->Package, "native");
  973. if (BuildPkg.end() == false && Pkg != BuildPkg)
  974. {
  975. pkgCache::VerIterator Ver = (*Cache)[BuildPkg].InstVerIter(*Cache);
  976. if (BADVER(Ver) == false)
  977. verlist.insert(Ver);
  978. Ver = (*Cache)[BuildPkg].CandidateVerIter(*Cache);
  979. if (BADVER(Ver) == false)
  980. verlist.insert(Ver);
  981. }
  982. }
  983. #undef BADVER
  984. string forbidden;
  985. // We need to decide if host or build arch, so find a version we can look at
  986. APT::VersionList::const_iterator Ver = verlist.begin();
  987. for (; Ver != verlist.end(); ++Ver)
  988. {
  989. forbidden.clear();
  990. if (Ver->MultiArch == pkgCache::Version::None || Ver->MultiArch == pkgCache::Version::All)
  991. {
  992. if (colon == string::npos)
  993. Pkg = Ver.ParentPkg().Group().FindPkg(hostArch);
  994. else if (strcmp(D->Package.c_str() + colon, ":any") == 0)
  995. forbidden = "Multi-Arch: none";
  996. else if (strcmp(D->Package.c_str() + colon, ":native") == 0)
  997. Pkg = Ver.ParentPkg().Group().FindPkg("native");
  998. }
  999. else if (Ver->MultiArch == pkgCache::Version::Same)
  1000. {
  1001. if (colon == string::npos)
  1002. Pkg = Ver.ParentPkg().Group().FindPkg(hostArch);
  1003. else if (strcmp(D->Package.c_str() + colon, ":any") == 0)
  1004. forbidden = "Multi-Arch: same";
  1005. else if (strcmp(D->Package.c_str() + colon, ":native") == 0)
  1006. Pkg = Ver.ParentPkg().Group().FindPkg("native");
  1007. }
  1008. else if ((Ver->MultiArch & pkgCache::Version::Foreign) == pkgCache::Version::Foreign)
  1009. {
  1010. if (colon == string::npos)
  1011. Pkg = Ver.ParentPkg().Group().FindPkg("native");
  1012. else if (strcmp(D->Package.c_str() + colon, ":any") == 0 ||
  1013. strcmp(D->Package.c_str() + colon, ":native") == 0)
  1014. forbidden = "Multi-Arch: foreign";
  1015. }
  1016. else if ((Ver->MultiArch & pkgCache::Version::Allowed) == pkgCache::Version::Allowed)
  1017. {
  1018. if (colon == string::npos)
  1019. Pkg = Ver.ParentPkg().Group().FindPkg(hostArch);
  1020. else if (strcmp(D->Package.c_str() + colon, ":any") == 0)
  1021. {
  1022. // prefer any installed over preferred non-installed architectures
  1023. pkgCache::GrpIterator Grp = Ver.ParentPkg().Group();
  1024. // we don't check for version here as we are better of with upgrading than remove and install
  1025. for (Pkg = Grp.PackageList(); Pkg.end() == false; Pkg = Grp.NextPkg(Pkg))
  1026. if (Pkg.CurrentVer().end() == false)
  1027. break;
  1028. if (Pkg.end() == true)
  1029. Pkg = Grp.FindPreferredPkg(true);
  1030. }
  1031. else if (strcmp(D->Package.c_str() + colon, ":native") == 0)
  1032. Pkg = Ver.ParentPkg().Group().FindPkg("native");
  1033. }
  1034. if (forbidden.empty() == false)
  1035. {
  1036. if (_config->FindB("Debug::BuildDeps",false) == true)
  1037. cout << D->Package.substr(colon, string::npos) << " is not allowed from " << forbidden << " package " << (*D).Package << " (" << Ver.VerStr() << ")" << endl;
  1038. continue;
  1039. }
  1040. //we found a good version
  1041. break;
  1042. }
  1043. if (Ver == verlist.end())
  1044. {
  1045. if (_config->FindB("Debug::BuildDeps",false) == true)
  1046. cout << " No multiarch info as we have no satisfying installed nor candidate for " << D->Package << " on build or host arch" << endl;
  1047. if (forbidden.empty() == false)
  1048. {
  1049. if (hasAlternatives)
  1050. continue;
  1051. return _error->Error(_("%s dependency for %s can't be satisfied "
  1052. "because %s is not allowed on '%s' packages"),
  1053. Last->BuildDepType(D->Type), Src.c_str(),
  1054. D->Package.c_str(), forbidden.c_str());
  1055. }
  1056. }
  1057. }
  1058. else
  1059. Pkg = Cache->FindPkg(D->Package);
  1060. if (Pkg.end() == true || (Pkg->VersionList == 0 && Pkg->ProvidesList == 0))
  1061. {
  1062. if (_config->FindB("Debug::BuildDeps",false) == true)
  1063. cout << " (not found)" << (*D).Package << endl;
  1064. if (hasAlternatives)
  1065. continue;
  1066. return _error->Error(_("%s dependency for %s cannot be satisfied "
  1067. "because the package %s cannot be found"),
  1068. Last->BuildDepType((*D).Type),Src.c_str(),
  1069. (*D).Package.c_str());
  1070. }
  1071. pkgCache::VerIterator IV = (*Cache)[Pkg].InstVerIter(*Cache);
  1072. if (IV.end() == false)
  1073. {
  1074. if (_config->FindB("Debug::BuildDeps",false) == true)
  1075. cout << " Is installed\n";
  1076. if (D->Version.empty() == true ||
  1077. Cache->VS().CheckDep(IV.VerStr(),(*D).Op,(*D).Version.c_str()) == true)
  1078. {
  1079. skipAlternatives = hasAlternatives;
  1080. continue;
  1081. }
  1082. if (_config->FindB("Debug::BuildDeps",false) == true)
  1083. cout << " ...but the installed version doesn't meet the version requirement\n";
  1084. if (((*D).Op & pkgCache::Dep::LessEq) == pkgCache::Dep::LessEq)
  1085. return _error->Error(_("Failed to satisfy %s dependency for %s: Installed package %s is too new"),
  1086. Last->BuildDepType((*D).Type), Src.c_str(), Pkg.FullName(true).c_str());
  1087. }
  1088. // Only consider virtual packages if there is no versioned dependency
  1089. if ((*D).Version.empty() == true)
  1090. {
  1091. /*
  1092. * If this is a virtual package, we need to check the list of
  1093. * packages that provide it and see if any of those are
  1094. * installed
  1095. */
  1096. pkgCache::PrvIterator Prv = Pkg.ProvidesList();
  1097. for (; Prv.end() != true; ++Prv)
  1098. {
  1099. if (_config->FindB("Debug::BuildDeps",false) == true)
  1100. cout << " Checking provider " << Prv.OwnerPkg().FullName() << endl;
  1101. if ((*Cache)[Prv.OwnerPkg()].InstVerIter(*Cache).end() == false)
  1102. break;
  1103. }
  1104. if (Prv.end() == false)
  1105. {
  1106. if (_config->FindB("Debug::BuildDeps",false) == true)
  1107. cout << " Is provided by installed package " << Prv.OwnerPkg().FullName() << endl;
  1108. skipAlternatives = hasAlternatives;
  1109. continue;
  1110. }
  1111. }
  1112. else // versioned dependency
  1113. {
  1114. pkgCache::VerIterator CV = (*Cache)[Pkg].CandidateVerIter(*Cache);
  1115. if (CV.end() == true ||
  1116. Cache->VS().CheckDep(CV.VerStr(),(*D).Op,(*D).Version.c_str()) == false)
  1117. {
  1118. if (hasAlternatives)
  1119. continue;
  1120. else if (CV.end() == false)
  1121. return _error->Error(_("%s dependency for %s cannot be satisfied "
  1122. "because candidate version of package %s "
  1123. "can't satisfy version requirements"),
  1124. Last->BuildDepType(D->Type), Src.c_str(),
  1125. D->Package.c_str());
  1126. else
  1127. return _error->Error(_("%s dependency for %s cannot be satisfied "
  1128. "because package %s has no candidate version"),
  1129. Last->BuildDepType(D->Type), Src.c_str(),
  1130. D->Package.c_str());
  1131. }
  1132. }
  1133. if (TryToInstallBuildDep(Pkg,Cache,Fix,false,false,false) == true)
  1134. {
  1135. // We successfully installed something; skip remaining alternatives
  1136. skipAlternatives = hasAlternatives;
  1137. if(_config->FindB("APT::Get::Build-Dep-Automatic", false) == true)
  1138. Cache->MarkAuto(Pkg, true);
  1139. continue;
  1140. }
  1141. else if (hasAlternatives)
  1142. {
  1143. if (_config->FindB("Debug::BuildDeps",false) == true)
  1144. cout << " Unsatisfiable, trying alternatives\n";
  1145. continue;
  1146. }
  1147. else
  1148. {
  1149. return _error->Error(_("Failed to satisfy %s dependency for %s: %s"),
  1150. Last->BuildDepType((*D).Type),
  1151. Src.c_str(),
  1152. (*D).Package.c_str());
  1153. }
  1154. }
  1155. }
  1156. if (Fix.Resolve(true) == false)
  1157. _error->Discard();
  1158. // Now we check the state of the packages,
  1159. if (Cache->BrokenCount() != 0)
  1160. {
  1161. ShowBroken(cout, Cache, false);
  1162. return _error->Error(_("Build-dependencies for %s could not be satisfied."),*I);
  1163. }
  1164. }
  1165. if (InstallPackages(Cache, false, true) == false)
  1166. return _error->Error(_("Failed to process build dependencies"));
  1167. return true;
  1168. }
  1169. /*}}}*/
  1170. // GetChangelogPath - return a path pointing to a changelog file or dir /*{{{*/
  1171. // ---------------------------------------------------------------------
  1172. /* This returns a "path" string for the changelog url construction.
  1173. * Please note that its not complete, it either needs a "/changelog"
  1174. * appended (for the packages.debian.org/changelogs site) or a
  1175. * ".changelog" (for third party sites that store the changelog in the
  1176. * pool/ next to the deb itself)
  1177. * Example return: "pool/main/a/apt/apt_0.8.8ubuntu3"
  1178. */
  1179. string GetChangelogPath(CacheFile &Cache,
  1180. pkgCache::PkgIterator Pkg,
  1181. pkgCache::VerIterator Ver)
  1182. {
  1183. string path;
  1184. pkgRecords Recs(Cache);
  1185. pkgRecords::Parser &rec=Recs.Lookup(Ver.FileList());
  1186. string srcpkg = rec.SourcePkg().empty() ? Pkg.Name() : rec.SourcePkg();
  1187. string ver = Ver.VerStr();
  1188. // if there is a source version it always wins
  1189. if (rec.SourceVer() != "")
  1190. ver = rec.SourceVer();
  1191. path = flNotFile(rec.FileName());
  1192. path += srcpkg + "_" + StripEpoch(ver);
  1193. return path;
  1194. }
  1195. /*}}}*/
  1196. // GuessThirdPartyChangelogUri - return url /*{{{*/
  1197. // ---------------------------------------------------------------------
  1198. /* Contruct a changelog file path for third party sites that do not use
  1199. * packages.debian.org/changelogs
  1200. * This simply uses the ArchiveURI() of the source pkg and looks for
  1201. * a .changelog file there, Example for "mediabuntu":
  1202. * apt-get changelog mplayer-doc:
  1203. * http://packages.medibuntu.org/pool/non-free/m/mplayer/mplayer_1.0~rc4~try1.dsfg1-1ubuntu1+medibuntu1.changelog
  1204. */
  1205. bool GuessThirdPartyChangelogUri(CacheFile &Cache,
  1206. pkgCache::PkgIterator Pkg,
  1207. pkgCache::VerIterator Ver,
  1208. string &out_uri)
  1209. {
  1210. // get the binary deb server path
  1211. pkgCache::VerFileIterator Vf = Ver.FileList();
  1212. if (Vf.end() == true)
  1213. return false;
  1214. pkgCache::PkgFileIterator F = Vf.File();
  1215. pkgIndexFile *index;
  1216. pkgSourceList *SrcList = Cache.GetSourceList();
  1217. if(SrcList->FindIndex(F, index) == false)
  1218. return false;
  1219. // get archive uri for the binary deb
  1220. string path_without_dot_changelog = GetChangelogPath(Cache, Pkg, Ver);
  1221. out_uri = index->ArchiveURI(path_without_dot_changelog + ".changelog");
  1222. // now strip away the filename and add srcpkg_srcver.changelog
  1223. return true;
  1224. }
  1225. /*}}}*/
  1226. // DownloadChangelog - Download the changelog /*{{{*/
  1227. // ---------------------------------------------------------------------
  1228. bool DownloadChangelog(CacheFile &CacheFile, pkgAcquire &Fetcher,
  1229. pkgCache::VerIterator Ver, string targetfile)
  1230. /* Download a changelog file for the given package version to
  1231. * targetfile. This will first try the server from Apt::Changelogs::Server
  1232. * (http://packages.debian.org/changelogs by default) and if that gives
  1233. * a 404 tries to get it from the archive directly (see
  1234. * GuessThirdPartyChangelogUri for details how)
  1235. */
  1236. {
  1237. string path;
  1238. string descr;
  1239. string server;
  1240. string changelog_uri;
  1241. // data structures we need
  1242. pkgCache::PkgIterator Pkg = Ver.ParentPkg();
  1243. // make the server root configurable
  1244. server = _config->Find("Apt::Changelogs::Server",
  1245. "http://packages.debian.org/changelogs");
  1246. path = GetChangelogPath(CacheFile, Pkg, Ver);
  1247. strprintf(changelog_uri, "%s/%s/changelog", server.c_str(), path.c_str());
  1248. if (_config->FindB("APT::Get::Print-URIs", false) == true)
  1249. {
  1250. std::cout << '\'' << changelog_uri << '\'' << std::endl;
  1251. return true;
  1252. }
  1253. strprintf(descr, _("Changelog for %s (%s)"), Pkg.Name(), changelog_uri.c_str());
  1254. // queue it
  1255. new pkgAcqFile(&Fetcher, changelog_uri, "", 0, descr, Pkg.Name(), "ignored", targetfile);
  1256. // try downloading it, if that fails, try third-party-changelogs location
  1257. // FIXME: Fetcher.Run() is "Continue" even if I get a 404?!?
  1258. Fetcher.Run();
  1259. if (!FileExists(targetfile))
  1260. {
  1261. string third_party_uri;
  1262. if (GuessThirdPartyChangelogUri(CacheFile, Pkg, Ver, third_party_uri))
  1263. {
  1264. strprintf(descr, _("Changelog for %s (%s)"), Pkg.Name(), third_party_uri.c_str());
  1265. new pkgAcqFile(&Fetcher, third_party_uri, "", 0, descr, Pkg.Name(), "ignored", targetfile);
  1266. Fetcher.Run();
  1267. }
  1268. }
  1269. if (FileExists(targetfile))
  1270. return true;
  1271. // error
  1272. return _error->Error("changelog download failed");
  1273. }
  1274. /*}}}*/
  1275. // DoChangelog - Get changelog from the command line /*{{{*/
  1276. // ---------------------------------------------------------------------
  1277. bool DoChangelog(CommandLine &CmdL)
  1278. {
  1279. CacheFile Cache;
  1280. if (Cache.ReadOnlyOpen() == false)
  1281. return false;
  1282. APT::CacheSetHelper helper(c0out);
  1283. APT::VersionList verset = APT::VersionList::FromCommandLine(Cache,
  1284. CmdL.FileList + 1, APT::VersionList::CANDIDATE, helper);
  1285. if (verset.empty() == true)
  1286. return false;
  1287. pkgAcquire Fetcher;
  1288. if (_config->FindB("APT::Get::Print-URIs", false) == true)
  1289. {
  1290. bool Success = true;
  1291. for (APT::VersionList::const_iterator Ver = verset.begin();
  1292. Ver != verset.end(); ++Ver)
  1293. Success &= DownloadChangelog(Cache, Fetcher, Ver, "");
  1294. return Success;
  1295. }
  1296. AcqTextStatus Stat(ScreenWidth, _config->FindI("quiet",0));
  1297. Fetcher.Setup(&Stat);
  1298. bool const downOnly = _config->FindB("APT::Get::Download-Only", false);
  1299. char tmpname[100];
  1300. char* tmpdir = NULL;
  1301. if (downOnly == false)
  1302. {
  1303. const char* const tmpDir = getenv("TMPDIR");
  1304. if (tmpDir != NULL && *tmpDir != '\0')
  1305. snprintf(tmpname, sizeof(tmpname), "%s/apt-changelog-XXXXXX", tmpDir);
  1306. else
  1307. strncpy(tmpname, "/tmp/apt-changelog-XXXXXX", sizeof(tmpname));
  1308. tmpdir = mkdtemp(tmpname);
  1309. if (tmpdir == NULL)
  1310. return _error->Errno("mkdtemp", "mkdtemp failed");
  1311. }
  1312. for (APT::VersionList::const_iterator Ver = verset.begin();
  1313. Ver != verset.end();
  1314. ++Ver)
  1315. {
  1316. string changelogfile;
  1317. if (downOnly == false)
  1318. changelogfile.append(tmpname).append("changelog");
  1319. else
  1320. changelogfile.append(Ver.ParentPkg().Name()).append(".changelog");
  1321. if (DownloadChangelog(Cache, Fetcher, Ver, changelogfile) && downOnly == false)
  1322. {
  1323. DisplayFileInPager(changelogfile);
  1324. // cleanup temp file
  1325. unlink(changelogfile.c_str());
  1326. }
  1327. }
  1328. // clenaup tmp dir
  1329. if (tmpdir != NULL)
  1330. rmdir(tmpdir);
  1331. return true;
  1332. }
  1333. /*}}}*/
  1334. // ShowHelp - Show a help screen /*{{{*/
  1335. // ---------------------------------------------------------------------
  1336. /* */
  1337. bool ShowHelp(CommandLine &CmdL)
  1338. {
  1339. ioprintf(cout,_("%s %s for %s compiled on %s %s\n"),PACKAGE,PACKAGE_VERSION,
  1340. COMMON_ARCH,__DATE__,__TIME__);
  1341. if (_config->FindB("version") == true)
  1342. {
  1343. cout << _("Supported modules:") << endl;
  1344. for (unsigned I = 0; I != pkgVersioningSystem::GlobalListLen; I++)
  1345. {
  1346. pkgVersioningSystem *VS = pkgVersioningSystem::GlobalList[I];
  1347. if (_system != 0 && _system->VS == VS)
  1348. cout << '*';
  1349. else
  1350. cout << ' ';
  1351. cout << "Ver: " << VS->Label << endl;
  1352. /* Print out all the packaging systems that will work with
  1353. this VS */
  1354. for (unsigned J = 0; J != pkgSystem::GlobalListLen; J++)
  1355. {
  1356. pkgSystem *Sys = pkgSystem::GlobalList[J];
  1357. if (_system == Sys)
  1358. cout << '*';
  1359. else
  1360. cout << ' ';
  1361. if (Sys->VS->TestCompatibility(*VS) == true)
  1362. cout << "Pkg: " << Sys->Label << " (Priority " << Sys->Score(*_config) << ")" << endl;
  1363. }
  1364. }
  1365. for (unsigned I = 0; I != pkgSourceList::Type::GlobalListLen; I++)
  1366. {
  1367. pkgSourceList::Type *Type = pkgSourceList::Type::GlobalList[I];
  1368. cout << " S.L: '" << Type->Name << "' " << Type->Label << endl;
  1369. }
  1370. for (unsigned I = 0; I != pkgIndexFile::Type::GlobalListLen; I++)
  1371. {
  1372. pkgIndexFile::Type *Type = pkgIndexFile::Type::GlobalList[I];
  1373. cout << " Idx: " << Type->Label << endl;
  1374. }
  1375. return true;
  1376. }
  1377. cout <<
  1378. _("Usage: apt-get [options] command\n"
  1379. " apt-get [options] install|remove pkg1 [pkg2 ...]\n"
  1380. " apt-get [options] source pkg1 [pkg2 ...]\n"
  1381. "\n"
  1382. "apt-get is a simple command line interface for downloading and\n"
  1383. "installing packages. The most frequently used commands are update\n"
  1384. "and install.\n"
  1385. "\n"
  1386. "Commands:\n"
  1387. " update - Retrieve new lists of packages\n"
  1388. " upgrade - Perform an upgrade\n"
  1389. " install - Install new packages (pkg is libc6 not libc6.deb)\n"
  1390. " remove - Remove packages\n"
  1391. " autoremove - Remove automatically all unused packages\n"
  1392. " purge - Remove packages and config files\n"
  1393. " source - Download source archives\n"
  1394. " build-dep - Configure build-dependencies for source packages\n"
  1395. " dist-upgrade - Distribution upgrade, see apt-get(8)\n"
  1396. " dselect-upgrade - Follow dselect selections\n"
  1397. " clean - Erase downloaded archive files\n"
  1398. " autoclean - Erase old downloaded archive files\n"
  1399. " check - Verify that there are no broken dependencies\n"
  1400. " changelog - Download and display the changelog for the given package\n"
  1401. " download - Download the binary package into the current directory\n"
  1402. "\n"
  1403. "Options:\n"
  1404. " -h This help text.\n"
  1405. " -q Loggable output - no progress indicator\n"
  1406. " -qq No output except for errors\n"
  1407. " -d Download only - do NOT install or unpack archives\n"
  1408. " -s No-act. Perform ordering simulation\n"
  1409. " -y Assume Yes to all queries and do not prompt\n"
  1410. " -f Attempt to correct a system with broken dependencies in place\n"
  1411. " -m Attempt to continue if archives are unlocatable\n"
  1412. " -u Show a list of upgraded packages as well\n"
  1413. " -b Build the source package after fetching it\n"
  1414. " -V Show verbose version numbers\n"
  1415. " -c=? Read this configuration file\n"
  1416. " -o=? Set an arbitrary configuration option, eg -o dir::cache=/tmp\n"
  1417. "See the apt-get(8), sources.list(5) and apt.conf(5) manual\n"
  1418. "pages for more information and options.\n"
  1419. " This APT has Super Cow Powers.\n");
  1420. return true;
  1421. }
  1422. /*}}}*/
  1423. // SigWinch - Window size change signal handler /*{{{*/
  1424. // ---------------------------------------------------------------------
  1425. /* */
  1426. void SigWinch(int)
  1427. {
  1428. // Riped from GNU ls
  1429. #ifdef TIOCGWINSZ
  1430. struct winsize ws;
  1431. if (ioctl(1, TIOCGWINSZ, &ws) != -1 && ws.ws_col >= 5)
  1432. ScreenWidth = ws.ws_col - 1;
  1433. #endif
  1434. }
  1435. /*}}}*/
  1436. bool DoUpgrade(CommandLine &CmdL) /*{{{*/
  1437. {
  1438. if (_config->FindB("APT::Get::Upgrade-Allow-New", false) == true)
  1439. return DoUpgradeWithAllowNewPackages(CmdL);
  1440. else
  1441. return DoUpgradeNoNewPackages(CmdL);
  1442. }
  1443. /*}}}*/
  1444. int main(int argc,const char *argv[]) /*{{{*/
  1445. {
  1446. CommandLine::Dispatch Cmds[] = {{"update",&DoUpdate},
  1447. {"upgrade",&DoUpgrade},
  1448. {"install",&DoInstall},
  1449. {"remove",&DoInstall},
  1450. {"purge",&DoInstall},
  1451. {"autoremove",&DoInstall},
  1452. {"markauto",&DoMarkAuto},
  1453. {"unmarkauto",&DoMarkAuto},
  1454. {"dist-upgrade",&DoDistUpgrade},
  1455. {"dselect-upgrade",&DoDSelectUpgrade},
  1456. {"build-dep",&DoBuildDep},
  1457. {"clean",&DoClean},
  1458. {"autoclean",&DoAutoClean},
  1459. {"check",&DoCheck},
  1460. {"source",&DoSource},
  1461. {"download",&DoDownload},
  1462. {"changelog",&DoChangelog},
  1463. {"moo",&DoMoo},
  1464. {"help",&ShowHelp},
  1465. {0,0}};
  1466. std::vector<CommandLine::Args> Args = getCommandArgs("apt-get", CommandLine::GetCommand(Cmds, argc, argv));
  1467. // Set up gettext support
  1468. setlocale(LC_ALL,"");
  1469. textdomain(PACKAGE);
  1470. // Parse the command line and initialize the package library
  1471. CommandLine CmdL(Args.data(),_config);
  1472. if (pkgInitConfig(*_config) == false ||
  1473. CmdL.Parse(argc,argv) == false ||
  1474. pkgInitSystem(*_config,_system) == false)
  1475. {
  1476. if (_config->FindB("version") == true)
  1477. ShowHelp(CmdL);
  1478. _error->DumpErrors();
  1479. return 100;
  1480. }
  1481. // See if the help should be shown
  1482. if (_config->FindB("help") == true ||
  1483. _config->FindB("version") == true ||
  1484. CmdL.FileSize() == 0)
  1485. {
  1486. ShowHelp(CmdL);
  1487. return 0;
  1488. }
  1489. // see if we are in simulate mode
  1490. CheckSimulateMode(CmdL);
  1491. // Deal with stdout not being a tty
  1492. if (!isatty(STDOUT_FILENO) && _config->FindI("quiet", -1) == -1)
  1493. _config->Set("quiet","1");
  1494. // Setup the output streams
  1495. InitOutput();
  1496. // Setup the signals
  1497. signal(SIGPIPE,SIG_IGN);
  1498. signal(SIGWINCH,SigWinch);
  1499. SigWinch(0);
  1500. // Match the operation
  1501. CmdL.DispatchArg(Cmds);
  1502. // Print any errors or warnings found during parsing
  1503. bool const Errors = _error->PendingError();
  1504. if (_config->FindI("quiet",0) > 0)
  1505. _error->DumpErrors();
  1506. else
  1507. _error->DumpErrors(GlobalError::DEBUG);
  1508. return Errors == true ? 100 : 0;
  1509. }
  1510. /*}}}*/