apt-get.cc 55 KB

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