apt-get.cc 56 KB

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