apt-get.cc 56 KB

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