apt-get.cc 56 KB

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