apt-get.cc 56 KB

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