apt-get.cc 107 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255
  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. #define _LARGEFILE_SOURCE
  25. #define _LARGEFILE64_SOURCE
  26. #include <apt-pkg/aptconfiguration.h>
  27. #include <apt-pkg/error.h>
  28. #include <apt-pkg/cmndline.h>
  29. #include <apt-pkg/init.h>
  30. #include <apt-pkg/depcache.h>
  31. #include <apt-pkg/sourcelist.h>
  32. #include <apt-pkg/algorithms.h>
  33. #include <apt-pkg/acquire-item.h>
  34. #include <apt-pkg/strutl.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 <config.h>
  44. #include <apti18n.h>
  45. #include "acqprogress.h"
  46. #include <set>
  47. #include <locale.h>
  48. #include <langinfo.h>
  49. #include <fstream>
  50. #include <termios.h>
  51. #include <sys/ioctl.h>
  52. #include <sys/stat.h>
  53. #include <sys/statfs.h>
  54. #include <sys/statvfs.h>
  55. #include <signal.h>
  56. #include <unistd.h>
  57. #include <stdio.h>
  58. #include <errno.h>
  59. #include <regex.h>
  60. #include <sys/wait.h>
  61. #include <sstream>
  62. #define statfs statfs64
  63. #define statvfs statvfs64
  64. /*}}}*/
  65. #define RAMFS_MAGIC 0x858458f6
  66. using namespace std;
  67. ostream c0out(0);
  68. ostream c1out(0);
  69. ostream c2out(0);
  70. ofstream devnull("/dev/null");
  71. unsigned int ScreenWidth = 80 - 1; /* - 1 for the cursor */
  72. // class CacheFile - Cover class for some dependency cache functions /*{{{*/
  73. // ---------------------------------------------------------------------
  74. /* */
  75. class CacheFile : public pkgCacheFile
  76. {
  77. static pkgCache *SortCache;
  78. static int NameComp(const void *a,const void *b);
  79. public:
  80. pkgCache::Package **List;
  81. void Sort();
  82. bool CheckDeps(bool AllowBroken = false);
  83. bool BuildCaches(bool WithLock = true)
  84. {
  85. OpTextProgress Prog(*_config);
  86. if (pkgCacheFile::BuildCaches(&Prog,WithLock) == false)
  87. return false;
  88. return true;
  89. }
  90. bool Open(bool WithLock = true)
  91. {
  92. OpTextProgress Prog(*_config);
  93. if (pkgCacheFile::Open(&Prog,WithLock) == false)
  94. return false;
  95. Sort();
  96. return true;
  97. };
  98. bool OpenForInstall()
  99. {
  100. if (_config->FindB("APT::Get::Print-URIs") == true)
  101. return Open(false);
  102. else
  103. return Open(true);
  104. }
  105. CacheFile() : List(0) {};
  106. ~CacheFile() {
  107. delete[] List;
  108. }
  109. };
  110. /*}}}*/
  111. // YnPrompt - Yes No Prompt. /*{{{*/
  112. // ---------------------------------------------------------------------
  113. /* Returns true on a Yes.*/
  114. bool YnPrompt(bool Default=true)
  115. {
  116. if (_config->FindB("APT::Get::Assume-Yes",false) == true)
  117. {
  118. c1out << _("Y") << endl;
  119. return true;
  120. }
  121. char response[1024] = "";
  122. cin.getline(response, sizeof(response));
  123. if (!cin)
  124. return false;
  125. if (strlen(response) == 0)
  126. return Default;
  127. regex_t Pattern;
  128. int Res;
  129. Res = regcomp(&Pattern, nl_langinfo(YESEXPR),
  130. REG_EXTENDED|REG_ICASE|REG_NOSUB);
  131. if (Res != 0) {
  132. char Error[300];
  133. regerror(Res,&Pattern,Error,sizeof(Error));
  134. return _error->Error(_("Regex compilation error - %s"),Error);
  135. }
  136. Res = regexec(&Pattern, response, 0, NULL, 0);
  137. if (Res == 0)
  138. return true;
  139. return false;
  140. }
  141. /*}}}*/
  142. // AnalPrompt - Annoying Yes No Prompt. /*{{{*/
  143. // ---------------------------------------------------------------------
  144. /* Returns true on a Yes.*/
  145. bool AnalPrompt(const char *Text)
  146. {
  147. char Buf[1024];
  148. cin.getline(Buf,sizeof(Buf));
  149. if (strcmp(Buf,Text) == 0)
  150. return true;
  151. return false;
  152. }
  153. /*}}}*/
  154. // ShowList - Show a list /*{{{*/
  155. // ---------------------------------------------------------------------
  156. /* This prints out a string of space separated words with a title and
  157. a two space indent line wraped to the current screen width. */
  158. bool ShowList(ostream &out,string Title,string List,string VersionsList)
  159. {
  160. if (List.empty() == true)
  161. return true;
  162. // trim trailing space
  163. int NonSpace = List.find_last_not_of(' ');
  164. if (NonSpace != -1)
  165. {
  166. List = List.erase(NonSpace + 1);
  167. if (List.empty() == true)
  168. return true;
  169. }
  170. // Acount for the leading space
  171. int ScreenWidth = ::ScreenWidth - 3;
  172. out << Title << endl;
  173. string::size_type Start = 0;
  174. string::size_type VersionsStart = 0;
  175. while (Start < List.size())
  176. {
  177. if(_config->FindB("APT::Get::Show-Versions",false) == true &&
  178. VersionsList.size() > 0) {
  179. string::size_type End;
  180. string::size_type VersionsEnd;
  181. End = List.find(' ',Start);
  182. VersionsEnd = VersionsList.find('\n', VersionsStart);
  183. out << " " << string(List,Start,End - Start) << " (" <<
  184. string(VersionsList,VersionsStart,VersionsEnd - VersionsStart) <<
  185. ")" << endl;
  186. if (End == string::npos || End < Start)
  187. End = Start + ScreenWidth;
  188. Start = End + 1;
  189. VersionsStart = VersionsEnd + 1;
  190. } else {
  191. string::size_type End;
  192. if (Start + ScreenWidth >= List.size())
  193. End = List.size();
  194. else
  195. End = List.rfind(' ',Start+ScreenWidth);
  196. if (End == string::npos || End < Start)
  197. End = Start + ScreenWidth;
  198. out << " " << string(List,Start,End - Start) << endl;
  199. Start = End + 1;
  200. }
  201. }
  202. return false;
  203. }
  204. /*}}}*/
  205. // ShowBroken - Debugging aide /*{{{*/
  206. // ---------------------------------------------------------------------
  207. /* This prints out the names of all the packages that are broken along
  208. with the name of each each broken dependency and a quite version
  209. description.
  210. The output looks like:
  211. The following packages have unmet dependencies:
  212. exim: Depends: libc6 (>= 2.1.94) but 2.1.3-10 is to be installed
  213. Depends: libldap2 (>= 2.0.2-2) but it is not going to be installed
  214. Depends: libsasl7 but it is not going to be installed
  215. */
  216. void ShowBroken(ostream &out,CacheFile &Cache,bool Now)
  217. {
  218. out << _("The following packages have unmet dependencies:") << endl;
  219. for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
  220. {
  221. pkgCache::PkgIterator I(Cache,Cache.List[J]);
  222. if (Now == true)
  223. {
  224. if (Cache[I].NowBroken() == false)
  225. continue;
  226. }
  227. else
  228. {
  229. if (Cache[I].InstBroken() == false)
  230. continue;
  231. }
  232. // Print out each package and the failed dependencies
  233. out << " " << I.FullName(true) << " :";
  234. unsigned const Indent = I.FullName(true).size() + 3;
  235. bool First = true;
  236. pkgCache::VerIterator Ver;
  237. if (Now == true)
  238. Ver = I.CurrentVer();
  239. else
  240. Ver = Cache[I].InstVerIter(Cache);
  241. if (Ver.end() == true)
  242. {
  243. out << endl;
  244. continue;
  245. }
  246. for (pkgCache::DepIterator D = Ver.DependsList(); D.end() == false;)
  247. {
  248. // Compute a single dependency element (glob or)
  249. pkgCache::DepIterator Start;
  250. pkgCache::DepIterator End;
  251. D.GlobOr(Start,End); // advances D
  252. if (Cache->IsImportantDep(End) == false)
  253. continue;
  254. if (Now == true)
  255. {
  256. if ((Cache[End] & pkgDepCache::DepGNow) == pkgDepCache::DepGNow)
  257. continue;
  258. }
  259. else
  260. {
  261. if ((Cache[End] & pkgDepCache::DepGInstall) == pkgDepCache::DepGInstall)
  262. continue;
  263. }
  264. bool FirstOr = true;
  265. while (1)
  266. {
  267. if (First == false)
  268. for (unsigned J = 0; J != Indent; J++)
  269. out << ' ';
  270. First = false;
  271. if (FirstOr == false)
  272. {
  273. for (unsigned J = 0; J != strlen(End.DepType()) + 3; J++)
  274. out << ' ';
  275. }
  276. else
  277. out << ' ' << End.DepType() << ": ";
  278. FirstOr = false;
  279. out << Start.TargetPkg().FullName(true);
  280. // Show a quick summary of the version requirements
  281. if (Start.TargetVer() != 0)
  282. out << " (" << Start.CompType() << " " << Start.TargetVer() << ")";
  283. /* Show a summary of the target package if possible. In the case
  284. of virtual packages we show nothing */
  285. pkgCache::PkgIterator Targ = Start.TargetPkg();
  286. if (Targ->ProvidesList == 0)
  287. {
  288. out << ' ';
  289. pkgCache::VerIterator Ver = Cache[Targ].InstVerIter(Cache);
  290. if (Now == true)
  291. Ver = Targ.CurrentVer();
  292. if (Ver.end() == false)
  293. {
  294. if (Now == true)
  295. ioprintf(out,_("but %s is installed"),Ver.VerStr());
  296. else
  297. ioprintf(out,_("but %s is to be installed"),Ver.VerStr());
  298. }
  299. else
  300. {
  301. if (Cache[Targ].CandidateVerIter(Cache).end() == true)
  302. {
  303. if (Targ->ProvidesList == 0)
  304. out << _("but it is not installable");
  305. else
  306. out << _("but it is a virtual package");
  307. }
  308. else
  309. out << (Now?_("but it is not installed"):_("but it is not going to be installed"));
  310. }
  311. }
  312. if (Start != End)
  313. out << _(" or");
  314. out << endl;
  315. if (Start == End)
  316. break;
  317. Start++;
  318. }
  319. }
  320. }
  321. }
  322. /*}}}*/
  323. // ShowNew - Show packages to newly install /*{{{*/
  324. // ---------------------------------------------------------------------
  325. /* */
  326. void ShowNew(ostream &out,CacheFile &Cache)
  327. {
  328. /* Print out a list of packages that are going to be installed extra
  329. to what the user asked */
  330. string List;
  331. string VersionsList;
  332. for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
  333. {
  334. pkgCache::PkgIterator I(Cache,Cache.List[J]);
  335. if (Cache[I].NewInstall() == true) {
  336. if (Cache[I].CandidateVerIter(Cache).Pseudo() == true)
  337. continue;
  338. List += I.FullName(true) + " ";
  339. VersionsList += string(Cache[I].CandVersion) + "\n";
  340. }
  341. }
  342. ShowList(out,_("The following NEW packages will be installed:"),List,VersionsList);
  343. }
  344. /*}}}*/
  345. // ShowDel - Show packages to delete /*{{{*/
  346. // ---------------------------------------------------------------------
  347. /* */
  348. void ShowDel(ostream &out,CacheFile &Cache)
  349. {
  350. /* Print out a list of packages that are going to be removed extra
  351. to what the user asked */
  352. string List;
  353. string VersionsList;
  354. for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
  355. {
  356. pkgCache::PkgIterator I(Cache,Cache.List[J]);
  357. if (Cache[I].Delete() == true)
  358. {
  359. if (Cache[I].CandidateVerIter(Cache).Pseudo() == true)
  360. continue;
  361. if ((Cache[I].iFlags & pkgDepCache::Purge) == pkgDepCache::Purge)
  362. List += I.FullName(true) + "* ";
  363. else
  364. List += I.FullName(true) + " ";
  365. VersionsList += string(Cache[I].CandVersion)+ "\n";
  366. }
  367. }
  368. ShowList(out,_("The following packages will be REMOVED:"),List,VersionsList);
  369. }
  370. /*}}}*/
  371. // ShowKept - Show kept packages /*{{{*/
  372. // ---------------------------------------------------------------------
  373. /* */
  374. void ShowKept(ostream &out,CacheFile &Cache)
  375. {
  376. string List;
  377. string VersionsList;
  378. for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
  379. {
  380. pkgCache::PkgIterator I(Cache,Cache.List[J]);
  381. // Not interesting
  382. if (Cache[I].Upgrade() == true || Cache[I].Upgradable() == false ||
  383. I->CurrentVer == 0 || Cache[I].Delete() == true)
  384. continue;
  385. List += I.FullName(true) + " ";
  386. VersionsList += string(Cache[I].CurVersion) + " => " + Cache[I].CandVersion + "\n";
  387. }
  388. ShowList(out,_("The following packages have been kept back:"),List,VersionsList);
  389. }
  390. /*}}}*/
  391. // ShowUpgraded - Show upgraded packages /*{{{*/
  392. // ---------------------------------------------------------------------
  393. /* */
  394. void ShowUpgraded(ostream &out,CacheFile &Cache)
  395. {
  396. string List;
  397. string VersionsList;
  398. for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
  399. {
  400. pkgCache::PkgIterator I(Cache,Cache.List[J]);
  401. // Not interesting
  402. if (Cache[I].Upgrade() == false || Cache[I].NewInstall() == true)
  403. continue;
  404. if (Cache[I].CandidateVerIter(Cache).Pseudo() == true)
  405. continue;
  406. List += I.FullName(true) + " ";
  407. VersionsList += string(Cache[I].CurVersion) + " => " + Cache[I].CandVersion + "\n";
  408. }
  409. ShowList(out,_("The following packages will be upgraded:"),List,VersionsList);
  410. }
  411. /*}}}*/
  412. // ShowDowngraded - Show downgraded packages /*{{{*/
  413. // ---------------------------------------------------------------------
  414. /* */
  415. bool ShowDowngraded(ostream &out,CacheFile &Cache)
  416. {
  417. string List;
  418. string VersionsList;
  419. for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
  420. {
  421. pkgCache::PkgIterator I(Cache,Cache.List[J]);
  422. // Not interesting
  423. if (Cache[I].Downgrade() == false || Cache[I].NewInstall() == true)
  424. continue;
  425. if (Cache[I].CandidateVerIter(Cache).Pseudo() == true)
  426. continue;
  427. List += I.FullName(true) + " ";
  428. VersionsList += string(Cache[I].CurVersion) + " => " + Cache[I].CandVersion + "\n";
  429. }
  430. return ShowList(out,_("The following packages will be DOWNGRADED:"),List,VersionsList);
  431. }
  432. /*}}}*/
  433. // ShowHold - Show held but changed packages /*{{{*/
  434. // ---------------------------------------------------------------------
  435. /* */
  436. bool ShowHold(ostream &out,CacheFile &Cache)
  437. {
  438. string List;
  439. string VersionsList;
  440. for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
  441. {
  442. pkgCache::PkgIterator I(Cache,Cache.List[J]);
  443. if (Cache[I].InstallVer != (pkgCache::Version *)I.CurrentVer() &&
  444. I->SelectedState == pkgCache::State::Hold) {
  445. List += I.FullName(true) + " ";
  446. VersionsList += string(Cache[I].CurVersion) + " => " + Cache[I].CandVersion + "\n";
  447. }
  448. }
  449. return ShowList(out,_("The following held packages will be changed:"),List,VersionsList);
  450. }
  451. /*}}}*/
  452. // ShowEssential - Show an essential package warning /*{{{*/
  453. // ---------------------------------------------------------------------
  454. /* This prints out a warning message that is not to be ignored. It shows
  455. all essential packages and their dependents that are to be removed.
  456. It is insanely risky to remove the dependents of an essential package! */
  457. bool ShowEssential(ostream &out,CacheFile &Cache)
  458. {
  459. string List;
  460. string VersionsList;
  461. bool *Added = new bool[Cache->Head().PackageCount];
  462. for (unsigned int I = 0; I != Cache->Head().PackageCount; I++)
  463. Added[I] = false;
  464. for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
  465. {
  466. pkgCache::PkgIterator I(Cache,Cache.List[J]);
  467. if ((I->Flags & pkgCache::Flag::Essential) != pkgCache::Flag::Essential &&
  468. (I->Flags & pkgCache::Flag::Important) != pkgCache::Flag::Important)
  469. continue;
  470. // The essential package is being removed
  471. if (Cache[I].Delete() == true)
  472. {
  473. if (Added[I->ID] == false)
  474. {
  475. Added[I->ID] = true;
  476. List += I.FullName(true) + " ";
  477. //VersionsList += string(Cache[I].CurVersion) + "\n"; ???
  478. }
  479. }
  480. else
  481. continue;
  482. if (I->CurrentVer == 0)
  483. continue;
  484. // Print out any essential package depenendents that are to be removed
  485. for (pkgCache::DepIterator D = I.CurrentVer().DependsList(); D.end() == false; D++)
  486. {
  487. // Skip everything but depends
  488. if (D->Type != pkgCache::Dep::PreDepends &&
  489. D->Type != pkgCache::Dep::Depends)
  490. continue;
  491. pkgCache::PkgIterator P = D.SmartTargetPkg();
  492. if (Cache[P].Delete() == true)
  493. {
  494. if (Added[P->ID] == true)
  495. continue;
  496. Added[P->ID] = true;
  497. char S[300];
  498. snprintf(S,sizeof(S),_("%s (due to %s) "),P.FullName(true).c_str(),I.FullName(true).c_str());
  499. List += S;
  500. //VersionsList += "\n"; ???
  501. }
  502. }
  503. }
  504. delete [] Added;
  505. return ShowList(out,_("WARNING: The following essential packages will be removed.\n"
  506. "This should NOT be done unless you know exactly what you are doing!"),List,VersionsList);
  507. }
  508. /*}}}*/
  509. // Stats - Show some statistics /*{{{*/
  510. // ---------------------------------------------------------------------
  511. /* */
  512. void Stats(ostream &out,pkgDepCache &Dep)
  513. {
  514. unsigned long Upgrade = 0;
  515. unsigned long Downgrade = 0;
  516. unsigned long Install = 0;
  517. unsigned long ReInstall = 0;
  518. for (pkgCache::PkgIterator I = Dep.PkgBegin(); I.end() == false; I++)
  519. {
  520. if (pkgCache::VerIterator(Dep, Dep[I].CandidateVer).Pseudo() == true)
  521. continue;
  522. if (Dep[I].NewInstall() == true)
  523. Install++;
  524. else
  525. {
  526. if (Dep[I].Upgrade() == true)
  527. Upgrade++;
  528. else
  529. if (Dep[I].Downgrade() == true)
  530. Downgrade++;
  531. }
  532. if (Dep[I].Delete() == false && (Dep[I].iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
  533. ReInstall++;
  534. }
  535. ioprintf(out,_("%lu upgraded, %lu newly installed, "),
  536. Upgrade,Install);
  537. if (ReInstall != 0)
  538. ioprintf(out,_("%lu reinstalled, "),ReInstall);
  539. if (Downgrade != 0)
  540. ioprintf(out,_("%lu downgraded, "),Downgrade);
  541. ioprintf(out,_("%lu to remove and %lu not upgraded.\n"),
  542. Dep.DelCount(),Dep.KeepCount());
  543. if (Dep.BadCount() != 0)
  544. ioprintf(out,_("%lu not fully installed or removed.\n"),
  545. Dep.BadCount());
  546. }
  547. /*}}}*/
  548. // CacheSetHelperAPTGet - responsible for message telling from the CacheSets/*{{{*/
  549. class CacheSetHelperAPTGet : public APT::CacheSetHelper {
  550. /** \brief stream message should be printed to */
  551. std::ostream &out;
  552. /** \brief were things like Task or RegEx used to select packages? */
  553. bool explicitlyNamed;
  554. APT::PackageSet virtualPkgs;
  555. public:
  556. std::list<std::pair<pkgCache::VerIterator, std::string> > selectedByRelease;
  557. CacheSetHelperAPTGet(std::ostream &out) : APT::CacheSetHelper(true), out(out) {
  558. explicitlyNamed = true;
  559. }
  560. virtual void showTaskSelection(APT::PackageSet const &pkgset, string const &pattern) {
  561. for (APT::PackageSet::const_iterator Pkg = pkgset.begin(); Pkg != pkgset.end(); ++Pkg)
  562. ioprintf(out, _("Note, selecting '%s' for task '%s'\n"),
  563. Pkg.FullName(true).c_str(), pattern.c_str());
  564. explicitlyNamed = false;
  565. }
  566. virtual void showRegExSelection(APT::PackageSet const &pkgset, string const &pattern) {
  567. for (APT::PackageSet::const_iterator Pkg = pkgset.begin(); Pkg != pkgset.end(); ++Pkg)
  568. ioprintf(out, _("Note, selecting '%s' for regex '%s'\n"),
  569. Pkg.FullName(true).c_str(), pattern.c_str());
  570. explicitlyNamed = false;
  571. }
  572. virtual void showSelectedVersion(pkgCache::PkgIterator const &Pkg, pkgCache::VerIterator const Ver,
  573. string const &ver, bool const &verIsRel) {
  574. if (ver == Ver.VerStr())
  575. return;
  576. selectedByRelease.push_back(make_pair(Ver, ver));
  577. }
  578. bool showVirtualPackageErrors(pkgCacheFile &Cache) {
  579. if (virtualPkgs.empty() == true)
  580. return true;
  581. for (APT::PackageSet::const_iterator Pkg = virtualPkgs.begin();
  582. Pkg != virtualPkgs.end(); ++Pkg) {
  583. if (Pkg->ProvidesList != 0) {
  584. ioprintf(c1out,_("Package %s is a virtual package provided by:\n"),
  585. Pkg.FullName(true).c_str());
  586. pkgCache::PrvIterator I = Pkg.ProvidesList();
  587. unsigned short provider = 0;
  588. for (; I.end() == false; ++I) {
  589. pkgCache::PkgIterator Pkg = I.OwnerPkg();
  590. if (Cache[Pkg].CandidateVerIter(Cache) == I.OwnerVer()) {
  591. out << " " << Pkg.FullName(true) << " " << I.OwnerVer().VerStr();
  592. if (Cache[Pkg].Install() == true && Cache[Pkg].NewInstall() == false)
  593. out << _(" [Installed]");
  594. out << endl;
  595. ++provider;
  596. }
  597. }
  598. // if we found no candidate which provide this package, show non-candidates
  599. if (provider == 0)
  600. for (I = Pkg.ProvidesList(); I.end() == false; I++)
  601. out << " " << I.OwnerPkg().FullName(true) << " " << I.OwnerVer().VerStr()
  602. << _(" [Not candidate version]") << endl;
  603. else
  604. out << _("You should explicitly select one to install.") << endl;
  605. } else {
  606. ioprintf(out,
  607. _("Package %s is not available, but is referred to by another package.\n"
  608. "This may mean that the package is missing, has been obsoleted, or\n"
  609. "is only available from another source\n"),Pkg.FullName(true).c_str());
  610. string List;
  611. string VersionsList;
  612. SPtrArray<bool> Seen = new bool[Cache.GetPkgCache()->Head().PackageCount];
  613. memset(Seen,0,Cache.GetPkgCache()->Head().PackageCount*sizeof(*Seen));
  614. for (pkgCache::DepIterator Dep = Pkg.RevDependsList();
  615. Dep.end() == false; Dep++) {
  616. if (Dep->Type != pkgCache::Dep::Replaces)
  617. continue;
  618. if (Seen[Dep.ParentPkg()->ID] == true)
  619. continue;
  620. Seen[Dep.ParentPkg()->ID] = true;
  621. List += Dep.ParentPkg().FullName(true) + " ";
  622. //VersionsList += string(Dep.ParentPkg().CurVersion) + "\n"; ???
  623. }
  624. ShowList(out,_("However the following packages replace it:"),List,VersionsList);
  625. }
  626. out << std::endl;
  627. }
  628. return false;
  629. }
  630. virtual pkgCache::VerIterator canNotFindCandidateVer(pkgCacheFile &Cache, pkgCache::PkgIterator const &Pkg) {
  631. APT::VersionSet const verset = tryVirtualPackage(Cache, Pkg, APT::VersionSet::CANDIDATE);
  632. if (verset.empty() == false)
  633. return *(verset.begin());
  634. if (ShowError == true) {
  635. _error->Error(_("Package '%s' has no installation candidate"),Pkg.FullName(true).c_str());
  636. virtualPkgs.insert(Pkg);
  637. }
  638. return pkgCache::VerIterator(Cache, 0);
  639. }
  640. virtual pkgCache::VerIterator canNotFindNewestVer(pkgCacheFile &Cache, pkgCache::PkgIterator const &Pkg) {
  641. APT::VersionSet const verset = tryVirtualPackage(Cache, Pkg, APT::VersionSet::NEWEST);
  642. if (verset.empty() == false)
  643. return *(verset.begin());
  644. if (ShowError == true)
  645. ioprintf(out, _("Virtual packages like '%s' can't be removed\n"), Pkg.FullName(true).c_str());
  646. return pkgCache::VerIterator(Cache, 0);
  647. }
  648. APT::VersionSet tryVirtualPackage(pkgCacheFile &Cache, pkgCache::PkgIterator const &Pkg,
  649. APT::VersionSet::Version const &select) {
  650. /* This is a pure virtual package and there is a single available
  651. candidate providing it. */
  652. if (unlikely(Cache[Pkg].CandidateVer != 0) || Pkg->ProvidesList == 0)
  653. return APT::VersionSet();
  654. pkgCache::PkgIterator Prov;
  655. bool found_one = false;
  656. for (pkgCache::PrvIterator P = Pkg.ProvidesList(); P; ++P) {
  657. pkgCache::VerIterator const PVer = P.OwnerVer();
  658. pkgCache::PkgIterator const PPkg = PVer.ParentPkg();
  659. /* Ignore versions that are not a candidate. */
  660. if (Cache[PPkg].CandidateVer != PVer)
  661. continue;
  662. if (found_one == false) {
  663. Prov = PPkg;
  664. found_one = true;
  665. } else if (PPkg != Prov) {
  666. found_one = false; // we found at least two
  667. break;
  668. }
  669. }
  670. if (found_one == true) {
  671. ioprintf(out, _("Note, selecting '%s' instead of '%s'\n"),
  672. Prov.FullName(true).c_str(), Pkg.FullName(true).c_str());
  673. return APT::VersionSet::FromPackage(Cache, Prov, select, *this);
  674. }
  675. return APT::VersionSet();
  676. }
  677. inline bool allPkgNamedExplicitly() const { return explicitlyNamed; }
  678. };
  679. /*}}}*/
  680. // TryToInstall - Mark a package for installation /*{{{*/
  681. struct TryToInstall {
  682. pkgCacheFile* Cache;
  683. pkgProblemResolver* Fix;
  684. bool FixBroken;
  685. unsigned long AutoMarkChanged;
  686. APT::PackageSet doAutoInstallLater;
  687. TryToInstall(pkgCacheFile &Cache, pkgProblemResolver &PM, bool const &FixBroken) : Cache(&Cache), Fix(&PM),
  688. FixBroken(FixBroken), AutoMarkChanged(0) {};
  689. void operator() (pkgCache::VerIterator const &Ver) {
  690. pkgCache::PkgIterator Pkg = Ver.ParentPkg();
  691. Cache->GetDepCache()->SetCandidateVersion(Ver);
  692. pkgDepCache::StateCache &State = (*Cache)[Pkg];
  693. // Handle the no-upgrade case
  694. if (_config->FindB("APT::Get::upgrade",true) == false && Pkg->CurrentVer != 0)
  695. ioprintf(c1out,_("Skipping %s, it is already installed and upgrade is not set.\n"),
  696. Pkg.FullName(true).c_str());
  697. // Ignore request for install if package would be new
  698. else if (_config->FindB("APT::Get::Only-Upgrade", false) == true && Pkg->CurrentVer == 0)
  699. ioprintf(c1out,_("Skipping %s, it is not installed and only upgrades are requested.\n"),
  700. Pkg.FullName(true).c_str());
  701. else {
  702. Fix->Clear(Pkg);
  703. Fix->Protect(Pkg);
  704. Cache->GetDepCache()->MarkInstall(Pkg,false);
  705. if (State.Install() == false) {
  706. if (_config->FindB("APT::Get::ReInstall",false) == true) {
  707. if (Pkg->CurrentVer == 0 || Pkg.CurrentVer().Downloadable() == false)
  708. ioprintf(c1out,_("Reinstallation of %s is not possible, it cannot be downloaded.\n"),
  709. Pkg.FullName(true).c_str());
  710. else
  711. Cache->GetDepCache()->SetReInstall(Pkg, true);
  712. } else
  713. ioprintf(c1out,_("%s is already the newest version.\n"),
  714. Pkg.FullName(true).c_str());
  715. }
  716. // Install it with autoinstalling enabled (if we not respect the minial
  717. // required deps or the policy)
  718. if (FixBroken == false)
  719. doAutoInstallLater.insert(Pkg);
  720. }
  721. // see if we need to fix the auto-mark flag
  722. // e.g. apt-get install foo
  723. // where foo is marked automatic
  724. if (State.Install() == false &&
  725. (State.Flags & pkgCache::Flag::Auto) &&
  726. _config->FindB("APT::Get::ReInstall",false) == false &&
  727. _config->FindB("APT::Get::Only-Upgrade",false) == false &&
  728. _config->FindB("APT::Get::Download-Only",false) == false)
  729. {
  730. ioprintf(c1out,_("%s set to manually installed.\n"),
  731. Pkg.FullName(true).c_str());
  732. Cache->GetDepCache()->MarkAuto(Pkg,false);
  733. AutoMarkChanged++;
  734. }
  735. }
  736. bool propergateReleaseCandiateSwitching(std::list<std::pair<pkgCache::VerIterator, std::string> > start, std::ostream &out)
  737. {
  738. for (std::list<std::pair<pkgCache::VerIterator, std::string> >::const_iterator s = start.begin();
  739. s != start.end(); ++s)
  740. Cache->GetDepCache()->SetCandidateVersion(s->first);
  741. bool Success = true;
  742. std::list<std::pair<pkgCache::VerIterator, pkgCache::VerIterator> > Changed;
  743. for (std::list<std::pair<pkgCache::VerIterator, std::string> >::const_iterator s = start.begin();
  744. s != start.end(); ++s)
  745. {
  746. Changed.push_back(std::make_pair(s->first, pkgCache::VerIterator(*Cache)));
  747. // We continue here even if it failed to enhance the ShowBroken output
  748. Success &= Cache->GetDepCache()->SetCandidateRelease(s->first, s->second, Changed);
  749. }
  750. for (std::list<std::pair<pkgCache::VerIterator, pkgCache::VerIterator> >::const_iterator c = Changed.begin();
  751. c != Changed.end(); ++c)
  752. {
  753. if (c->second.end() == true)
  754. ioprintf(out, _("Selected version '%s' (%s) for '%s'\n"),
  755. c->first.VerStr(), c->first.RelStr().c_str(), c->first.ParentPkg().FullName(true).c_str());
  756. else if (c->first.ParentPkg()->Group != c->second.ParentPkg()->Group)
  757. {
  758. pkgCache::VerIterator V = (*Cache)[c->first.ParentPkg()].CandidateVerIter(*Cache);
  759. ioprintf(out, _("Selected version '%s' (%s) for '%s' because of '%s'\n"), V.VerStr(),
  760. V.RelStr().c_str(), V.ParentPkg().FullName(true).c_str(), c->second.ParentPkg().FullName(true).c_str());
  761. }
  762. }
  763. return Success;
  764. }
  765. void doAutoInstall() {
  766. for (APT::PackageSet::const_iterator P = doAutoInstallLater.begin();
  767. P != doAutoInstallLater.end(); ++P) {
  768. pkgDepCache::StateCache &State = (*Cache)[P];
  769. if (State.InstBroken() == false && State.InstPolicyBroken() == false)
  770. continue;
  771. Cache->GetDepCache()->MarkInstall(P, true);
  772. }
  773. doAutoInstallLater.clear();
  774. }
  775. };
  776. /*}}}*/
  777. // TryToRemove - Mark a package for removal /*{{{*/
  778. struct TryToRemove {
  779. pkgCacheFile* Cache;
  780. pkgProblemResolver* Fix;
  781. bool FixBroken;
  782. bool PurgePkgs;
  783. unsigned long AutoMarkChanged;
  784. TryToRemove(pkgCacheFile &Cache, pkgProblemResolver &PM) : Cache(&Cache), Fix(&PM),
  785. PurgePkgs(_config->FindB("APT::Get::Purge", false)) {};
  786. void operator() (pkgCache::VerIterator const &Ver)
  787. {
  788. pkgCache::PkgIterator Pkg = Ver.ParentPkg();
  789. Fix->Clear(Pkg);
  790. Fix->Protect(Pkg);
  791. Fix->Remove(Pkg);
  792. if ((Pkg->CurrentVer == 0 && PurgePkgs == false) ||
  793. (PurgePkgs == true && Pkg->CurrentState == pkgCache::State::NotInstalled))
  794. ioprintf(c1out,_("Package %s is not installed, so not removed\n"),Pkg.FullName(true).c_str());
  795. else
  796. Cache->GetDepCache()->MarkDelete(Pkg, PurgePkgs);
  797. }
  798. };
  799. /*}}}*/
  800. // CacheFile::NameComp - QSort compare by name /*{{{*/
  801. // ---------------------------------------------------------------------
  802. /* */
  803. pkgCache *CacheFile::SortCache = 0;
  804. int CacheFile::NameComp(const void *a,const void *b)
  805. {
  806. if (*(pkgCache::Package **)a == 0 || *(pkgCache::Package **)b == 0)
  807. return *(pkgCache::Package **)a - *(pkgCache::Package **)b;
  808. const pkgCache::Package &A = **(pkgCache::Package **)a;
  809. const pkgCache::Package &B = **(pkgCache::Package **)b;
  810. return strcmp(SortCache->StrP + A.Name,SortCache->StrP + B.Name);
  811. }
  812. /*}}}*/
  813. // CacheFile::Sort - Sort by name /*{{{*/
  814. // ---------------------------------------------------------------------
  815. /* */
  816. void CacheFile::Sort()
  817. {
  818. delete [] List;
  819. List = new pkgCache::Package *[Cache->Head().PackageCount];
  820. memset(List,0,sizeof(*List)*Cache->Head().PackageCount);
  821. pkgCache::PkgIterator I = Cache->PkgBegin();
  822. for (;I.end() != true; I++)
  823. List[I->ID] = I;
  824. SortCache = *this;
  825. qsort(List,Cache->Head().PackageCount,sizeof(*List),NameComp);
  826. }
  827. /*}}}*/
  828. // CacheFile::CheckDeps - Open the cache file /*{{{*/
  829. // ---------------------------------------------------------------------
  830. /* This routine generates the caches and then opens the dependency cache
  831. and verifies that the system is OK. */
  832. bool CacheFile::CheckDeps(bool AllowBroken)
  833. {
  834. bool FixBroken = _config->FindB("APT::Get::Fix-Broken",false);
  835. if (_error->PendingError() == true)
  836. return false;
  837. // Check that the system is OK
  838. if (DCache->DelCount() != 0 || DCache->InstCount() != 0)
  839. return _error->Error("Internal error, non-zero counts");
  840. // Apply corrections for half-installed packages
  841. if (pkgApplyStatus(*DCache) == false)
  842. return false;
  843. if (_config->FindB("APT::Get::Fix-Policy-Broken",false) == true)
  844. {
  845. FixBroken = true;
  846. if ((DCache->PolicyBrokenCount() > 0))
  847. {
  848. // upgrade all policy-broken packages with ForceImportantDeps=True
  849. for (pkgCache::PkgIterator I = Cache->PkgBegin(); !I.end(); I++)
  850. if ((*DCache)[I].NowPolicyBroken() == true)
  851. DCache->MarkInstall(I,true,0, false, true);
  852. }
  853. }
  854. // Nothing is broken
  855. if (DCache->BrokenCount() == 0 || AllowBroken == true)
  856. return true;
  857. // Attempt to fix broken things
  858. if (FixBroken == true)
  859. {
  860. c1out << _("Correcting dependencies...") << flush;
  861. if (pkgFixBroken(*DCache) == false || DCache->BrokenCount() != 0)
  862. {
  863. c1out << _(" failed.") << endl;
  864. ShowBroken(c1out,*this,true);
  865. return _error->Error(_("Unable to correct dependencies"));
  866. }
  867. if (pkgMinimizeUpgrade(*DCache) == false)
  868. return _error->Error(_("Unable to minimize the upgrade set"));
  869. c1out << _(" Done") << endl;
  870. }
  871. else
  872. {
  873. c1out << _("You might want to run 'apt-get -f install' to correct these.") << endl;
  874. ShowBroken(c1out,*this,true);
  875. return _error->Error(_("Unmet dependencies. Try using -f."));
  876. }
  877. return true;
  878. }
  879. /*}}}*/
  880. // CheckAuth - check if each download comes form a trusted source /*{{{*/
  881. // ---------------------------------------------------------------------
  882. /* */
  883. static bool CheckAuth(pkgAcquire& Fetcher)
  884. {
  885. string UntrustedList;
  886. for (pkgAcquire::ItemIterator I = Fetcher.ItemsBegin(); I < Fetcher.ItemsEnd(); ++I)
  887. {
  888. if (!(*I)->IsTrusted())
  889. {
  890. UntrustedList += string((*I)->ShortDesc()) + " ";
  891. }
  892. }
  893. if (UntrustedList == "")
  894. {
  895. return true;
  896. }
  897. ShowList(c2out,_("WARNING: The following packages cannot be authenticated!"),UntrustedList,"");
  898. if (_config->FindB("APT::Get::AllowUnauthenticated",false) == true)
  899. {
  900. c2out << _("Authentication warning overridden.\n");
  901. return true;
  902. }
  903. if (_config->FindI("quiet",0) < 2
  904. && _config->FindB("APT::Get::Assume-Yes",false) == false)
  905. {
  906. c2out << _("Install these packages without verification [y/N]? ") << flush;
  907. if (!YnPrompt(false))
  908. return _error->Error(_("Some packages could not be authenticated"));
  909. return true;
  910. }
  911. else if (_config->FindB("APT::Get::Force-Yes",false) == true)
  912. {
  913. return true;
  914. }
  915. return _error->Error(_("There are problems and -y was used without --force-yes"));
  916. }
  917. /*}}}*/
  918. // InstallPackages - Actually download and install the packages /*{{{*/
  919. // ---------------------------------------------------------------------
  920. /* This displays the informative messages describing what is going to
  921. happen and then calls the download routines */
  922. bool InstallPackages(CacheFile &Cache,bool ShwKept,bool Ask = true,
  923. bool Safety = true)
  924. {
  925. if (_config->FindB("APT::Get::Purge",false) == true)
  926. {
  927. pkgCache::PkgIterator I = Cache->PkgBegin();
  928. for (; I.end() == false; I++)
  929. {
  930. if (I.Purge() == false && Cache[I].Mode == pkgDepCache::ModeDelete)
  931. Cache->MarkDelete(I,true);
  932. }
  933. }
  934. bool Fail = false;
  935. bool Essential = false;
  936. // Show all the various warning indicators
  937. ShowDel(c1out,Cache);
  938. ShowNew(c1out,Cache);
  939. if (ShwKept == true)
  940. ShowKept(c1out,Cache);
  941. Fail |= !ShowHold(c1out,Cache);
  942. if (_config->FindB("APT::Get::Show-Upgraded",true) == true)
  943. ShowUpgraded(c1out,Cache);
  944. Fail |= !ShowDowngraded(c1out,Cache);
  945. if (_config->FindB("APT::Get::Download-Only",false) == false)
  946. Essential = !ShowEssential(c1out,Cache);
  947. Fail |= Essential;
  948. Stats(c1out,Cache);
  949. // Sanity check
  950. if (Cache->BrokenCount() != 0)
  951. {
  952. ShowBroken(c1out,Cache,false);
  953. return _error->Error(_("Internal error, InstallPackages was called with broken packages!"));
  954. }
  955. if (Cache->DelCount() == 0 && Cache->InstCount() == 0 &&
  956. Cache->BadCount() == 0)
  957. return true;
  958. // No remove flag
  959. if (Cache->DelCount() != 0 && _config->FindB("APT::Get::Remove",true) == false)
  960. return _error->Error(_("Packages need to be removed but remove is disabled."));
  961. // Run the simulator ..
  962. if (_config->FindB("APT::Get::Simulate") == true)
  963. {
  964. pkgSimulate PM(Cache);
  965. int status_fd = _config->FindI("APT::Status-Fd",-1);
  966. pkgPackageManager::OrderResult Res = PM.DoInstall(status_fd);
  967. if (Res == pkgPackageManager::Failed)
  968. return false;
  969. if (Res != pkgPackageManager::Completed)
  970. return _error->Error(_("Internal error, Ordering didn't finish"));
  971. return true;
  972. }
  973. // Create the text record parser
  974. pkgRecords Recs(Cache);
  975. if (_error->PendingError() == true)
  976. return false;
  977. // Create the download object
  978. pkgAcquire Fetcher;
  979. AcqTextStatus Stat(ScreenWidth,_config->FindI("quiet",0));
  980. if (_config->FindB("APT::Get::Print-URIs", false) == true)
  981. {
  982. // force a hashsum for compatibility reasons
  983. _config->CndSet("Acquire::ForceHash", "md5sum");
  984. }
  985. else if (Fetcher.Setup(&Stat, _config->FindDir("Dir::Cache::Archives")) == false)
  986. return false;
  987. // Read the source list
  988. if (Cache.BuildSourceList() == false)
  989. return false;
  990. pkgSourceList *List = Cache.GetSourceList();
  991. // Create the package manager and prepare to download
  992. SPtr<pkgPackageManager> PM= _system->CreatePM(Cache);
  993. if (PM->GetArchives(&Fetcher,List,&Recs) == false ||
  994. _error->PendingError() == true)
  995. return false;
  996. // Display statistics
  997. unsigned long long FetchBytes = Fetcher.FetchNeeded();
  998. unsigned long long FetchPBytes = Fetcher.PartialPresent();
  999. unsigned long long DebBytes = Fetcher.TotalNeeded();
  1000. if (DebBytes != Cache->DebSize())
  1001. {
  1002. c0out << DebBytes << ',' << Cache->DebSize() << endl;
  1003. c0out << _("How odd.. The sizes didn't match, email apt@packages.debian.org") << endl;
  1004. }
  1005. // Number of bytes
  1006. if (DebBytes != FetchBytes)
  1007. //TRANSLATOR: The required space between number and unit is already included
  1008. // in the replacement strings, so %sB will be correctly translate in e.g. 1,5 MB
  1009. ioprintf(c1out,_("Need to get %sB/%sB of archives.\n"),
  1010. SizeToStr(FetchBytes).c_str(),SizeToStr(DebBytes).c_str());
  1011. else if (DebBytes != 0)
  1012. //TRANSLATOR: The required space between number and unit is already included
  1013. // in the replacement string, so %sB will be correctly translate in e.g. 1,5 MB
  1014. ioprintf(c1out,_("Need to get %sB of archives.\n"),
  1015. SizeToStr(DebBytes).c_str());
  1016. // Size delta
  1017. if (Cache->UsrSize() >= 0)
  1018. //TRANSLATOR: The required space between number and unit is already included
  1019. // in the replacement string, so %sB will be correctly translate in e.g. 1,5 MB
  1020. ioprintf(c1out,_("After this operation, %sB of additional disk space will be used.\n"),
  1021. SizeToStr(Cache->UsrSize()).c_str());
  1022. else
  1023. //TRANSLATOR: The required space between number and unit is already included
  1024. // in the replacement string, so %sB will be correctly translate in e.g. 1,5 MB
  1025. ioprintf(c1out,_("After this operation, %sB disk space will be freed.\n"),
  1026. SizeToStr(-1*Cache->UsrSize()).c_str());
  1027. if (_error->PendingError() == true)
  1028. return false;
  1029. /* Check for enough free space, but only if we are actually going to
  1030. download */
  1031. if (_config->FindB("APT::Get::Print-URIs") == false &&
  1032. _config->FindB("APT::Get::Download",true) == true)
  1033. {
  1034. struct statvfs Buf;
  1035. string OutputDir = _config->FindDir("Dir::Cache::Archives");
  1036. if (statvfs(OutputDir.c_str(),&Buf) != 0) {
  1037. if (errno == EOVERFLOW)
  1038. return _error->WarningE("statvfs",_("Couldn't determine free space in %s"),
  1039. OutputDir.c_str());
  1040. else
  1041. return _error->Errno("statvfs",_("Couldn't determine free space in %s"),
  1042. OutputDir.c_str());
  1043. } else if (unsigned(Buf.f_bfree) < (FetchBytes - FetchPBytes)/Buf.f_bsize)
  1044. {
  1045. struct statfs Stat;
  1046. if (statfs(OutputDir.c_str(),&Stat) != 0
  1047. #if HAVE_STRUCT_STATFS_F_TYPE
  1048. || unsigned(Stat.f_type) != RAMFS_MAGIC
  1049. #endif
  1050. )
  1051. return _error->Error(_("You don't have enough free space in %s."),
  1052. OutputDir.c_str());
  1053. }
  1054. }
  1055. // Fail safe check
  1056. if (_config->FindI("quiet",0) >= 2 ||
  1057. _config->FindB("APT::Get::Assume-Yes",false) == true)
  1058. {
  1059. if (Fail == true && _config->FindB("APT::Get::Force-Yes",false) == false)
  1060. return _error->Error(_("There are problems and -y was used without --force-yes"));
  1061. }
  1062. if (Essential == true && Safety == true)
  1063. {
  1064. if (_config->FindB("APT::Get::Trivial-Only",false) == true)
  1065. return _error->Error(_("Trivial Only specified but this is not a trivial operation."));
  1066. const char *Prompt = _("Yes, do as I say!");
  1067. ioprintf(c2out,
  1068. _("You are about to do something potentially harmful.\n"
  1069. "To continue type in the phrase '%s'\n"
  1070. " ?] "),Prompt);
  1071. c2out << flush;
  1072. if (AnalPrompt(Prompt) == false)
  1073. {
  1074. c2out << _("Abort.") << endl;
  1075. exit(1);
  1076. }
  1077. }
  1078. else
  1079. {
  1080. // Prompt to continue
  1081. if (Ask == true || Fail == true)
  1082. {
  1083. if (_config->FindB("APT::Get::Trivial-Only",false) == true)
  1084. return _error->Error(_("Trivial Only specified but this is not a trivial operation."));
  1085. if (_config->FindI("quiet",0) < 2 &&
  1086. _config->FindB("APT::Get::Assume-Yes",false) == false)
  1087. {
  1088. c2out << _("Do you want to continue [Y/n]? ") << flush;
  1089. if (YnPrompt() == false)
  1090. {
  1091. c2out << _("Abort.") << endl;
  1092. exit(1);
  1093. }
  1094. }
  1095. }
  1096. }
  1097. // Just print out the uris an exit if the --print-uris flag was used
  1098. if (_config->FindB("APT::Get::Print-URIs") == true)
  1099. {
  1100. pkgAcquire::UriIterator I = Fetcher.UriBegin();
  1101. for (; I != Fetcher.UriEnd(); I++)
  1102. cout << '\'' << I->URI << "' " << flNotDir(I->Owner->DestFile) << ' ' <<
  1103. I->Owner->FileSize << ' ' << I->Owner->HashSum() << endl;
  1104. return true;
  1105. }
  1106. if (!CheckAuth(Fetcher))
  1107. return false;
  1108. /* Unlock the dpkg lock if we are not going to be doing an install
  1109. after. */
  1110. if (_config->FindB("APT::Get::Download-Only",false) == true)
  1111. _system->UnLock();
  1112. // Run it
  1113. while (1)
  1114. {
  1115. bool Transient = false;
  1116. if (_config->FindB("APT::Get::Download",true) == false)
  1117. {
  1118. for (pkgAcquire::ItemIterator I = Fetcher.ItemsBegin(); I < Fetcher.ItemsEnd();)
  1119. {
  1120. if ((*I)->Local == true)
  1121. {
  1122. I++;
  1123. continue;
  1124. }
  1125. // Close the item and check if it was found in cache
  1126. (*I)->Finished();
  1127. if ((*I)->Complete == false)
  1128. Transient = true;
  1129. // Clear it out of the fetch list
  1130. delete *I;
  1131. I = Fetcher.ItemsBegin();
  1132. }
  1133. }
  1134. if (Fetcher.Run() == pkgAcquire::Failed)
  1135. return false;
  1136. // Print out errors
  1137. bool Failed = false;
  1138. for (pkgAcquire::ItemIterator I = Fetcher.ItemsBegin(); I != Fetcher.ItemsEnd(); I++)
  1139. {
  1140. if ((*I)->Status == pkgAcquire::Item::StatDone &&
  1141. (*I)->Complete == true)
  1142. continue;
  1143. if ((*I)->Status == pkgAcquire::Item::StatIdle)
  1144. {
  1145. Transient = true;
  1146. // Failed = true;
  1147. continue;
  1148. }
  1149. fprintf(stderr,_("Failed to fetch %s %s\n"),(*I)->DescURI().c_str(),
  1150. (*I)->ErrorText.c_str());
  1151. Failed = true;
  1152. }
  1153. /* If we are in no download mode and missing files and there were
  1154. 'failures' then the user must specify -m. Furthermore, there
  1155. is no such thing as a transient error in no-download mode! */
  1156. if (Transient == true &&
  1157. _config->FindB("APT::Get::Download",true) == false)
  1158. {
  1159. Transient = false;
  1160. Failed = true;
  1161. }
  1162. if (_config->FindB("APT::Get::Download-Only",false) == true)
  1163. {
  1164. if (Failed == true && _config->FindB("APT::Get::Fix-Missing",false) == false)
  1165. return _error->Error(_("Some files failed to download"));
  1166. c1out << _("Download complete and in download only mode") << endl;
  1167. return true;
  1168. }
  1169. if (Failed == true && _config->FindB("APT::Get::Fix-Missing",false) == false)
  1170. {
  1171. return _error->Error(_("Unable to fetch some archives, maybe run apt-get update or try with --fix-missing?"));
  1172. }
  1173. if (Transient == true && Failed == true)
  1174. return _error->Error(_("--fix-missing and media swapping is not currently supported"));
  1175. // Try to deal with missing package files
  1176. if (Failed == true && PM->FixMissing() == false)
  1177. {
  1178. cerr << _("Unable to correct missing packages.") << endl;
  1179. return _error->Error(_("Aborting install."));
  1180. }
  1181. _system->UnLock();
  1182. int status_fd = _config->FindI("APT::Status-Fd",-1);
  1183. pkgPackageManager::OrderResult Res = PM->DoInstall(status_fd);
  1184. if (Res == pkgPackageManager::Failed || _error->PendingError() == true)
  1185. return false;
  1186. if (Res == pkgPackageManager::Completed)
  1187. break;
  1188. // Reload the fetcher object and loop again for media swapping
  1189. Fetcher.Shutdown();
  1190. if (PM->GetArchives(&Fetcher,List,&Recs) == false)
  1191. return false;
  1192. _system->Lock();
  1193. }
  1194. std::set<std::string> const disappearedPkgs = PM->GetDisappearedPackages();
  1195. if (disappearedPkgs.empty() == true)
  1196. return true;
  1197. string disappear;
  1198. for (std::set<std::string>::const_iterator d = disappearedPkgs.begin();
  1199. d != disappearedPkgs.end(); ++d)
  1200. disappear.append(*d).append(" ");
  1201. ShowList(c1out, P_("The following package disappeared from your system as\n"
  1202. "all files have been overwritten by other packages:",
  1203. "The following packages disappeared from your system as\n"
  1204. "all files have been overwritten by other packages:", disappearedPkgs.size()), disappear, "");
  1205. c0out << _("Note: This is done automatic and on purpose by dpkg.") << std::endl;
  1206. return true;
  1207. }
  1208. /*}}}*/
  1209. // TryToInstallBuildDep - Try to install a single package /*{{{*/
  1210. // ---------------------------------------------------------------------
  1211. /* This used to be inlined in DoInstall, but with the advent of regex package
  1212. name matching it was split out.. */
  1213. bool TryToInstallBuildDep(pkgCache::PkgIterator Pkg,pkgCacheFile &Cache,
  1214. pkgProblemResolver &Fix,bool Remove,bool BrokenFix,
  1215. bool AllowFail = true)
  1216. {
  1217. if (Cache[Pkg].CandidateVer == 0 && Pkg->ProvidesList != 0)
  1218. {
  1219. CacheSetHelperAPTGet helper(c1out);
  1220. helper.showErrors(AllowFail == false);
  1221. pkgCache::VerIterator Ver = helper.canNotFindNewestVer(Cache, Pkg);
  1222. if (Ver.end() == false)
  1223. Pkg = Ver.ParentPkg();
  1224. else if (helper.showVirtualPackageErrors(Cache) == false)
  1225. return AllowFail;
  1226. }
  1227. if (Remove == true)
  1228. {
  1229. TryToRemove RemoveAction(Cache, Fix);
  1230. RemoveAction(Pkg.VersionList());
  1231. } else if (Cache[Pkg].CandidateVer != 0) {
  1232. TryToInstall InstallAction(Cache, Fix, BrokenFix);
  1233. InstallAction(Cache[Pkg].CandidateVerIter(Cache));
  1234. InstallAction.doAutoInstall();
  1235. } else
  1236. return AllowFail;
  1237. return true;
  1238. }
  1239. /*}}}*/
  1240. // FindSrc - Find a source record /*{{{*/
  1241. // ---------------------------------------------------------------------
  1242. /* */
  1243. pkgSrcRecords::Parser *FindSrc(const char *Name,pkgRecords &Recs,
  1244. pkgSrcRecords &SrcRecs,string &Src,
  1245. pkgDepCache &Cache)
  1246. {
  1247. string VerTag;
  1248. string DefRel = _config->Find("APT::Default-Release");
  1249. string TmpSrc = Name;
  1250. // extract the version/release from the pkgname
  1251. const size_t found = TmpSrc.find_last_of("/=");
  1252. if (found != string::npos) {
  1253. if (TmpSrc[found] == '/')
  1254. DefRel = TmpSrc.substr(found+1);
  1255. else
  1256. VerTag = TmpSrc.substr(found+1);
  1257. TmpSrc = TmpSrc.substr(0,found);
  1258. }
  1259. /* Lookup the version of the package we would install if we were to
  1260. install a version and determine the source package name, then look
  1261. in the archive for a source package of the same name. */
  1262. bool MatchSrcOnly = _config->FindB("APT::Get::Only-Source");
  1263. const pkgCache::PkgIterator Pkg = Cache.FindPkg(TmpSrc);
  1264. if (MatchSrcOnly == false && Pkg.end() == false)
  1265. {
  1266. if(VerTag.empty() == false || DefRel.empty() == false)
  1267. {
  1268. bool fuzzy = false;
  1269. // we have a default release, try to locate the pkg. we do it like
  1270. // this because GetCandidateVer() will not "downgrade", that means
  1271. // "apt-get source -t stable apt" won't work on a unstable system
  1272. for (pkgCache::VerIterator Ver = Pkg.VersionList();; Ver++)
  1273. {
  1274. // try first only exact matches, later fuzzy matches
  1275. if (Ver.end() == true)
  1276. {
  1277. if (fuzzy == true)
  1278. break;
  1279. fuzzy = true;
  1280. Ver = Pkg.VersionList();
  1281. // exit right away from the Pkg.VersionList() loop if we
  1282. // don't have any versions
  1283. if (Ver.end() == true)
  1284. break;
  1285. }
  1286. // We match against a concrete version (or a part of this version)
  1287. if (VerTag.empty() == false &&
  1288. (fuzzy == true || Cache.VS().CmpVersion(VerTag, Ver.VerStr()) != 0) && // exact match
  1289. (fuzzy == false || strncmp(VerTag.c_str(), Ver.VerStr(), VerTag.size()) != 0)) // fuzzy match
  1290. continue;
  1291. for (pkgCache::VerFileIterator VF = Ver.FileList();
  1292. VF.end() == false; VF++)
  1293. {
  1294. /* If this is the status file, and the current version is not the
  1295. version in the status file (ie it is not installed, or somesuch)
  1296. then it is not a candidate for installation, ever. This weeds
  1297. out bogus entries that may be due to config-file states, or
  1298. other. */
  1299. if ((VF.File()->Flags & pkgCache::Flag::NotSource) ==
  1300. pkgCache::Flag::NotSource && Pkg.CurrentVer() != Ver)
  1301. continue;
  1302. // or we match against a release
  1303. if(VerTag.empty() == false ||
  1304. (VF.File().Archive() != 0 && VF.File().Archive() == DefRel) ||
  1305. (VF.File().Codename() != 0 && VF.File().Codename() == DefRel))
  1306. {
  1307. pkgRecords::Parser &Parse = Recs.Lookup(VF);
  1308. Src = Parse.SourcePkg();
  1309. // no SourcePkg name, so it is the "binary" name
  1310. if (Src.empty() == true)
  1311. Src = TmpSrc;
  1312. // the Version we have is possibly fuzzy or includes binUploads,
  1313. // so we use the Version of the SourcePkg (empty if same as package)
  1314. VerTag = Parse.SourceVer();
  1315. if (VerTag.empty() == true)
  1316. VerTag = Ver.VerStr();
  1317. break;
  1318. }
  1319. }
  1320. if (Src.empty() == false)
  1321. break;
  1322. }
  1323. if (Src.empty() == true)
  1324. {
  1325. // Sources files have no codename information
  1326. if (VerTag.empty() == true && DefRel.empty() == false)
  1327. {
  1328. _error->Error(_("Ignore unavailable target release '%s' of package '%s'"), DefRel.c_str(), TmpSrc.c_str());
  1329. return 0;
  1330. }
  1331. }
  1332. }
  1333. if (Src.empty() == true)
  1334. {
  1335. // if we don't have found a fitting package yet so we will
  1336. // choose a good candidate and proceed with that.
  1337. // Maybe we will find a source later on with the right VerTag
  1338. pkgCache::VerIterator Ver = Cache.GetCandidateVer(Pkg);
  1339. if (Ver.end() == false)
  1340. {
  1341. pkgRecords::Parser &Parse = Recs.Lookup(Ver.FileList());
  1342. Src = Parse.SourcePkg();
  1343. if (VerTag.empty() == true)
  1344. VerTag = Parse.SourceVer();
  1345. }
  1346. }
  1347. }
  1348. if (Src.empty() == true)
  1349. Src = TmpSrc;
  1350. else
  1351. {
  1352. /* if we have a source pkg name, make sure to only search
  1353. for srcpkg names, otherwise apt gets confused if there
  1354. is a binary package "pkg1" and a source package "pkg1"
  1355. with the same name but that comes from different packages */
  1356. MatchSrcOnly = true;
  1357. if (Src != TmpSrc)
  1358. {
  1359. ioprintf(c1out, _("Picking '%s' as source package instead of '%s'\n"), Src.c_str(), TmpSrc.c_str());
  1360. }
  1361. }
  1362. // The best hit
  1363. pkgSrcRecords::Parser *Last = 0;
  1364. unsigned long Offset = 0;
  1365. string Version;
  1366. /* Iterate over all of the hits, which includes the resulting
  1367. binary packages in the search */
  1368. pkgSrcRecords::Parser *Parse;
  1369. while (true)
  1370. {
  1371. SrcRecs.Restart();
  1372. while ((Parse = SrcRecs.Find(Src.c_str(), MatchSrcOnly)) != 0)
  1373. {
  1374. const string Ver = Parse->Version();
  1375. // Ignore all versions which doesn't fit
  1376. if (VerTag.empty() == false &&
  1377. Cache.VS().CmpVersion(VerTag, Ver) != 0) // exact match
  1378. continue;
  1379. // Newer version or an exact match? Save the hit
  1380. if (Last == 0 || Cache.VS().CmpVersion(Version,Ver) < 0) {
  1381. Last = Parse;
  1382. Offset = Parse->Offset();
  1383. Version = Ver;
  1384. }
  1385. // was the version check above an exact match? If so, we don't need to look further
  1386. if (VerTag.empty() == false && VerTag.size() == Ver.size())
  1387. break;
  1388. }
  1389. if (Last != 0 || VerTag.empty() == true)
  1390. break;
  1391. //if (VerTag.empty() == false && Last == 0)
  1392. _error->Error(_("Ignore unavailable version '%s' of package '%s'"), VerTag.c_str(), TmpSrc.c_str());
  1393. return 0;
  1394. }
  1395. if (Last == 0 || Last->Jump(Offset) == false)
  1396. return 0;
  1397. return Last;
  1398. }
  1399. /*}}}*/
  1400. // DoUpdate - Update the package lists /*{{{*/
  1401. // ---------------------------------------------------------------------
  1402. /* */
  1403. bool DoUpdate(CommandLine &CmdL)
  1404. {
  1405. if (CmdL.FileSize() != 1)
  1406. return _error->Error(_("The update command takes no arguments"));
  1407. CacheFile Cache;
  1408. // Get the source list
  1409. if (Cache.BuildSourceList() == false)
  1410. return false;
  1411. pkgSourceList *List = Cache.GetSourceList();
  1412. // Create the progress
  1413. AcqTextStatus Stat(ScreenWidth,_config->FindI("quiet",0));
  1414. // Just print out the uris an exit if the --print-uris flag was used
  1415. if (_config->FindB("APT::Get::Print-URIs") == true)
  1416. {
  1417. // force a hashsum for compatibility reasons
  1418. _config->CndSet("Acquire::ForceHash", "md5sum");
  1419. // get a fetcher
  1420. pkgAcquire Fetcher;
  1421. if (Fetcher.Setup(&Stat) == false)
  1422. return false;
  1423. // Populate it with the source selection and get all Indexes
  1424. // (GetAll=true)
  1425. if (List->GetIndexes(&Fetcher,true) == false)
  1426. return false;
  1427. pkgAcquire::UriIterator I = Fetcher.UriBegin();
  1428. for (; I != Fetcher.UriEnd(); I++)
  1429. cout << '\'' << I->URI << "' " << flNotDir(I->Owner->DestFile) << ' ' <<
  1430. I->Owner->FileSize << ' ' << I->Owner->HashSum() << endl;
  1431. return true;
  1432. }
  1433. // do the work
  1434. if (_config->FindB("APT::Get::Download",true) == true)
  1435. ListUpdate(Stat, *List);
  1436. // Rebuild the cache.
  1437. if (Cache.BuildCaches() == false)
  1438. return false;
  1439. return true;
  1440. }
  1441. /*}}}*/
  1442. // DoAutomaticRemove - Remove all automatic unused packages /*{{{*/
  1443. // ---------------------------------------------------------------------
  1444. /* Remove unused automatic packages */
  1445. bool DoAutomaticRemove(CacheFile &Cache)
  1446. {
  1447. bool Debug = _config->FindI("Debug::pkgAutoRemove",false);
  1448. bool doAutoRemove = _config->FindB("APT::Get::AutomaticRemove", false);
  1449. bool hideAutoRemove = _config->FindB("APT::Get::HideAutoRemove");
  1450. pkgDepCache::ActionGroup group(*Cache);
  1451. if(Debug)
  1452. std::cout << "DoAutomaticRemove()" << std::endl;
  1453. if (doAutoRemove == true &&
  1454. _config->FindB("APT::Get::Remove",true) == false)
  1455. {
  1456. c1out << _("We are not supposed to delete stuff, can't start "
  1457. "AutoRemover") << std::endl;
  1458. return false;
  1459. }
  1460. bool purgePkgs = _config->FindB("APT::Get::Purge", false);
  1461. bool smallList = (hideAutoRemove == false &&
  1462. strcasecmp(_config->Find("APT::Get::HideAutoRemove","").c_str(),"small") == 0);
  1463. string autoremovelist, autoremoveversions;
  1464. unsigned long autoRemoveCount = 0;
  1465. // look over the cache to see what can be removed
  1466. for (pkgCache::PkgIterator Pkg = Cache->PkgBegin(); ! Pkg.end(); ++Pkg)
  1467. {
  1468. if (Cache[Pkg].Garbage)
  1469. {
  1470. if(Pkg.CurrentVer() != 0 || Cache[Pkg].Install())
  1471. if(Debug)
  1472. std::cout << "We could delete %s" << Pkg.FullName(true).c_str() << std::endl;
  1473. if (doAutoRemove)
  1474. {
  1475. if(Pkg.CurrentVer() != 0 &&
  1476. Pkg->CurrentState != pkgCache::State::ConfigFiles)
  1477. Cache->MarkDelete(Pkg, purgePkgs);
  1478. else
  1479. Cache->MarkKeep(Pkg, false, false);
  1480. }
  1481. else
  1482. {
  1483. // if the package is a new install and already garbage we don't need to
  1484. // install it in the first place, so nuke it instead of show it
  1485. if (Cache[Pkg].Install() == true && Pkg.CurrentVer() == 0)
  1486. Cache->MarkDelete(Pkg, false);
  1487. // only show stuff in the list that is not yet marked for removal
  1488. else if(hideAutoRemove == false && Cache[Pkg].Delete() == false)
  1489. {
  1490. ++autoRemoveCount;
  1491. // we don't need to fill the strings if we don't need them
  1492. if (smallList == false)
  1493. {
  1494. autoremovelist += Pkg.FullName(true) + " ";
  1495. autoremoveversions += string(Cache[Pkg].CandVersion) + "\n";
  1496. }
  1497. }
  1498. }
  1499. }
  1500. }
  1501. // Now see if we had destroyed anything (if we had done anything)
  1502. if (Cache->BrokenCount() != 0)
  1503. {
  1504. c1out << _("Hmm, seems like the AutoRemover destroyed something which really\n"
  1505. "shouldn't happen. Please file a bug report against apt.") << endl;
  1506. c1out << endl;
  1507. c1out << _("The following information may help to resolve the situation:") << endl;
  1508. c1out << endl;
  1509. ShowBroken(c1out,Cache,false);
  1510. return _error->Error(_("Internal Error, AutoRemover broke stuff"));
  1511. }
  1512. // if we don't remove them, we should show them!
  1513. if (doAutoRemove == false && (autoremovelist.empty() == false || autoRemoveCount != 0))
  1514. {
  1515. if (smallList == false)
  1516. ShowList(c1out, P_("The following package was automatically installed and is no longer required:",
  1517. "The following packages were automatically installed and are no longer required:",
  1518. autoRemoveCount), autoremovelist, autoremoveversions);
  1519. else
  1520. ioprintf(c1out, P_("%lu package was automatically installed and is no longer required.\n",
  1521. "%lu packages were automatically installed and are no longer required.\n", autoRemoveCount), autoRemoveCount);
  1522. c1out << _("Use 'apt-get autoremove' to remove them.") << std::endl;
  1523. }
  1524. return true;
  1525. }
  1526. /*}}}*/
  1527. // DoUpgrade - Upgrade all packages /*{{{*/
  1528. // ---------------------------------------------------------------------
  1529. /* Upgrade all packages without installing new packages or erasing old
  1530. packages */
  1531. bool DoUpgrade(CommandLine &CmdL)
  1532. {
  1533. CacheFile Cache;
  1534. if (Cache.OpenForInstall() == false || Cache.CheckDeps() == false)
  1535. return false;
  1536. // Do the upgrade
  1537. if (pkgAllUpgrade(Cache) == false)
  1538. {
  1539. ShowBroken(c1out,Cache,false);
  1540. return _error->Error(_("Internal error, AllUpgrade broke stuff"));
  1541. }
  1542. return InstallPackages(Cache,true);
  1543. }
  1544. /*}}}*/
  1545. // DoInstall - Install packages from the command line /*{{{*/
  1546. // ---------------------------------------------------------------------
  1547. /* Install named packages */
  1548. bool DoInstall(CommandLine &CmdL)
  1549. {
  1550. CacheFile Cache;
  1551. if (Cache.OpenForInstall() == false ||
  1552. Cache.CheckDeps(CmdL.FileSize() != 1) == false)
  1553. return false;
  1554. // Enter the special broken fixing mode if the user specified arguments
  1555. bool BrokenFix = false;
  1556. if (Cache->BrokenCount() != 0)
  1557. BrokenFix = true;
  1558. pkgProblemResolver Fix(Cache);
  1559. static const unsigned short MOD_REMOVE = 1;
  1560. static const unsigned short MOD_INSTALL = 2;
  1561. unsigned short fallback = MOD_INSTALL;
  1562. if (strcasecmp(CmdL.FileList[0],"remove") == 0)
  1563. fallback = MOD_REMOVE;
  1564. else if (strcasecmp(CmdL.FileList[0], "purge") == 0)
  1565. {
  1566. _config->Set("APT::Get::Purge", true);
  1567. fallback = MOD_REMOVE;
  1568. }
  1569. else if (strcasecmp(CmdL.FileList[0], "autoremove") == 0)
  1570. {
  1571. _config->Set("APT::Get::AutomaticRemove", "true");
  1572. fallback = MOD_REMOVE;
  1573. }
  1574. std::list<APT::VersionSet::Modifier> mods;
  1575. mods.push_back(APT::VersionSet::Modifier(MOD_INSTALL, "+",
  1576. APT::VersionSet::Modifier::POSTFIX, APT::VersionSet::CANDIDATE));
  1577. mods.push_back(APT::VersionSet::Modifier(MOD_REMOVE, "-",
  1578. APT::VersionSet::Modifier::POSTFIX, APT::VersionSet::NEWEST));
  1579. CacheSetHelperAPTGet helper(c0out);
  1580. std::map<unsigned short, APT::VersionSet> verset = APT::VersionSet::GroupedFromCommandLine(Cache,
  1581. CmdL.FileList + 1, mods, fallback, helper);
  1582. if (_error->PendingError() == true)
  1583. {
  1584. helper.showVirtualPackageErrors(Cache);
  1585. return false;
  1586. }
  1587. unsigned short order[] = { 0, 0, 0 };
  1588. if (fallback == MOD_INSTALL) {
  1589. order[0] = MOD_INSTALL;
  1590. order[1] = MOD_REMOVE;
  1591. } else {
  1592. order[0] = MOD_REMOVE;
  1593. order[1] = MOD_INSTALL;
  1594. }
  1595. TryToInstall InstallAction(Cache, Fix, BrokenFix);
  1596. TryToRemove RemoveAction(Cache, Fix);
  1597. // new scope for the ActionGroup
  1598. {
  1599. pkgDepCache::ActionGroup group(Cache);
  1600. for (unsigned short i = 0; order[i] != 0; ++i)
  1601. {
  1602. if (order[i] == MOD_INSTALL) {
  1603. InstallAction = std::for_each(verset[MOD_INSTALL].begin(), verset[MOD_INSTALL].end(), InstallAction);
  1604. InstallAction.propergateReleaseCandiateSwitching(helper.selectedByRelease, c0out);
  1605. InstallAction.doAutoInstall();
  1606. }
  1607. else if (order[i] == MOD_REMOVE)
  1608. RemoveAction = std::for_each(verset[MOD_REMOVE].begin(), verset[MOD_REMOVE].end(), RemoveAction);
  1609. }
  1610. if (_error->PendingError() == true)
  1611. return false;
  1612. /* If we are in the Broken fixing mode we do not attempt to fix the
  1613. problems. This is if the user invoked install without -f and gave
  1614. packages */
  1615. if (BrokenFix == true && Cache->BrokenCount() != 0)
  1616. {
  1617. c1out << _("You might want to run 'apt-get -f install' to correct these:") << endl;
  1618. ShowBroken(c1out,Cache,false);
  1619. return _error->Error(_("Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution)."));
  1620. }
  1621. // Call the scored problem resolver
  1622. Fix.InstallProtect();
  1623. if (Fix.Resolve(true) == false)
  1624. _error->Discard();
  1625. // Now we check the state of the packages,
  1626. if (Cache->BrokenCount() != 0)
  1627. {
  1628. c1out <<
  1629. _("Some packages could not be installed. This may mean that you have\n"
  1630. "requested an impossible situation or if you are using the unstable\n"
  1631. "distribution that some required packages have not yet been created\n"
  1632. "or been moved out of Incoming.") << endl;
  1633. /*
  1634. if (Packages == 1)
  1635. {
  1636. c1out << endl;
  1637. c1out <<
  1638. _("Since you only requested a single operation it is extremely likely that\n"
  1639. "the package is simply not installable and a bug report against\n"
  1640. "that package should be filed.") << endl;
  1641. }
  1642. */
  1643. c1out << _("The following information may help to resolve the situation:") << endl;
  1644. c1out << endl;
  1645. ShowBroken(c1out,Cache,false);
  1646. return _error->Error(_("Broken packages"));
  1647. }
  1648. }
  1649. if (!DoAutomaticRemove(Cache))
  1650. return false;
  1651. /* Print out a list of packages that are going to be installed extra
  1652. to what the user asked */
  1653. if (Cache->InstCount() != verset[MOD_INSTALL].size())
  1654. {
  1655. string List;
  1656. string VersionsList;
  1657. for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
  1658. {
  1659. pkgCache::PkgIterator I(Cache,Cache.List[J]);
  1660. if ((*Cache)[I].Install() == false)
  1661. continue;
  1662. pkgCache::VerIterator Cand = Cache[I].CandidateVerIter(Cache);
  1663. if (Cand.Pseudo() == true)
  1664. continue;
  1665. if (verset[MOD_INSTALL].find(Cand) != verset[MOD_INSTALL].end())
  1666. continue;
  1667. List += I.FullName(true) + " ";
  1668. VersionsList += string(Cache[I].CandVersion) + "\n";
  1669. }
  1670. ShowList(c1out,_("The following extra packages will be installed:"),List,VersionsList);
  1671. }
  1672. /* Print out a list of suggested and recommended packages */
  1673. {
  1674. string SuggestsList, RecommendsList, List;
  1675. string SuggestsVersions, RecommendsVersions;
  1676. for (unsigned J = 0; J < Cache->Head().PackageCount; J++)
  1677. {
  1678. pkgCache::PkgIterator Pkg(Cache,Cache.List[J]);
  1679. /* Just look at the ones we want to install */
  1680. if ((*Cache)[Pkg].Install() == false)
  1681. continue;
  1682. // get the recommends/suggests for the candidate ver
  1683. pkgCache::VerIterator CV = (*Cache)[Pkg].CandidateVerIter(*Cache);
  1684. for (pkgCache::DepIterator D = CV.DependsList(); D.end() == false; )
  1685. {
  1686. pkgCache::DepIterator Start;
  1687. pkgCache::DepIterator End;
  1688. D.GlobOr(Start,End); // advances D
  1689. // FIXME: we really should display a or-group as a or-group to the user
  1690. // the problem is that ShowList is incapable of doing this
  1691. string RecommendsOrList,RecommendsOrVersions;
  1692. string SuggestsOrList,SuggestsOrVersions;
  1693. bool foundInstalledInOrGroup = false;
  1694. for(;;)
  1695. {
  1696. /* Skip if package is installed already, or is about to be */
  1697. string target = Start.TargetPkg().FullName(true) + " ";
  1698. pkgCache::PkgIterator const TarPkg = Start.TargetPkg();
  1699. if (TarPkg->SelectedState == pkgCache::State::Install ||
  1700. TarPkg->SelectedState == pkgCache::State::Hold ||
  1701. Cache[Start.TargetPkg()].Install())
  1702. {
  1703. foundInstalledInOrGroup=true;
  1704. break;
  1705. }
  1706. /* Skip if we already saw it */
  1707. if (int(SuggestsList.find(target)) != -1 || int(RecommendsList.find(target)) != -1)
  1708. {
  1709. foundInstalledInOrGroup=true;
  1710. break;
  1711. }
  1712. // this is a dep on a virtual pkg, check if any package that provides it
  1713. // should be installed
  1714. if(Start.TargetPkg().ProvidesList() != 0)
  1715. {
  1716. pkgCache::PrvIterator I = Start.TargetPkg().ProvidesList();
  1717. for (; I.end() == false; I++)
  1718. {
  1719. pkgCache::PkgIterator Pkg = I.OwnerPkg();
  1720. if (Cache[Pkg].CandidateVerIter(Cache) == I.OwnerVer() &&
  1721. Pkg.CurrentVer() != 0)
  1722. foundInstalledInOrGroup=true;
  1723. }
  1724. }
  1725. if (Start->Type == pkgCache::Dep::Suggests)
  1726. {
  1727. SuggestsOrList += target;
  1728. SuggestsOrVersions += string(Cache[Start.TargetPkg()].CandVersion) + "\n";
  1729. }
  1730. if (Start->Type == pkgCache::Dep::Recommends)
  1731. {
  1732. RecommendsOrList += target;
  1733. RecommendsOrVersions += string(Cache[Start.TargetPkg()].CandVersion) + "\n";
  1734. }
  1735. if (Start >= End)
  1736. break;
  1737. Start++;
  1738. }
  1739. if(foundInstalledInOrGroup == false)
  1740. {
  1741. RecommendsList += RecommendsOrList;
  1742. RecommendsVersions += RecommendsOrVersions;
  1743. SuggestsList += SuggestsOrList;
  1744. SuggestsVersions += SuggestsOrVersions;
  1745. }
  1746. }
  1747. }
  1748. ShowList(c1out,_("Suggested packages:"),SuggestsList,SuggestsVersions);
  1749. ShowList(c1out,_("Recommended packages:"),RecommendsList,RecommendsVersions);
  1750. }
  1751. // if nothing changed in the cache, but only the automark information
  1752. // we write the StateFile here, otherwise it will be written in
  1753. // cache.commit()
  1754. if (InstallAction.AutoMarkChanged > 0 &&
  1755. Cache->DelCount() == 0 && Cache->InstCount() == 0 &&
  1756. Cache->BadCount() == 0 &&
  1757. _config->FindB("APT::Get::Simulate",false) == false)
  1758. Cache->writeStateFile(NULL);
  1759. // See if we need to prompt
  1760. // FIXME: check if really the packages in the set are going to be installed
  1761. if (Cache->InstCount() == verset[MOD_INSTALL].size() && Cache->DelCount() == 0)
  1762. return InstallPackages(Cache,false,false);
  1763. return InstallPackages(Cache,false);
  1764. }
  1765. /* mark packages as automatically/manually installed. */
  1766. bool DoMarkAuto(CommandLine &CmdL)
  1767. {
  1768. bool Action = true;
  1769. int AutoMarkChanged = 0;
  1770. OpTextProgress progress;
  1771. CacheFile Cache;
  1772. if (Cache.Open() == false)
  1773. return false;
  1774. if (strcasecmp(CmdL.FileList[0],"markauto") == 0)
  1775. Action = true;
  1776. else if (strcasecmp(CmdL.FileList[0],"unmarkauto") == 0)
  1777. Action = false;
  1778. for (const char **I = CmdL.FileList + 1; *I != 0; I++)
  1779. {
  1780. const char *S = *I;
  1781. // Locate the package
  1782. pkgCache::PkgIterator Pkg = Cache->FindPkg(S);
  1783. if (Pkg.end() == true) {
  1784. return _error->Error(_("Couldn't find package %s"),S);
  1785. }
  1786. else
  1787. {
  1788. if (!Action)
  1789. ioprintf(c1out,_("%s set to manually installed.\n"), Pkg.Name());
  1790. else
  1791. ioprintf(c1out,_("%s set to automatically installed.\n"),
  1792. Pkg.Name());
  1793. Cache->MarkAuto(Pkg,Action);
  1794. AutoMarkChanged++;
  1795. }
  1796. }
  1797. if (AutoMarkChanged && ! _config->FindB("APT::Get::Simulate",false))
  1798. return Cache->writeStateFile(NULL);
  1799. return false;
  1800. }
  1801. /*}}}*/
  1802. // DoDistUpgrade - Automatic smart upgrader /*{{{*/
  1803. // ---------------------------------------------------------------------
  1804. /* Intelligent upgrader that will install and remove packages at will */
  1805. bool DoDistUpgrade(CommandLine &CmdL)
  1806. {
  1807. CacheFile Cache;
  1808. if (Cache.OpenForInstall() == false || Cache.CheckDeps() == false)
  1809. return false;
  1810. c0out << _("Calculating upgrade... ") << flush;
  1811. if (pkgDistUpgrade(*Cache) == false)
  1812. {
  1813. c0out << _("Failed") << endl;
  1814. ShowBroken(c1out,Cache,false);
  1815. return false;
  1816. }
  1817. c0out << _("Done") << endl;
  1818. return InstallPackages(Cache,true);
  1819. }
  1820. /*}}}*/
  1821. // DoDSelectUpgrade - Do an upgrade by following dselects selections /*{{{*/
  1822. // ---------------------------------------------------------------------
  1823. /* Follows dselect's selections */
  1824. bool DoDSelectUpgrade(CommandLine &CmdL)
  1825. {
  1826. CacheFile Cache;
  1827. if (Cache.OpenForInstall() == false || Cache.CheckDeps() == false)
  1828. return false;
  1829. pkgDepCache::ActionGroup group(Cache);
  1830. // Install everything with the install flag set
  1831. pkgCache::PkgIterator I = Cache->PkgBegin();
  1832. for (;I.end() != true; I++)
  1833. {
  1834. /* Install the package only if it is a new install, the autoupgrader
  1835. will deal with the rest */
  1836. if (I->SelectedState == pkgCache::State::Install)
  1837. Cache->MarkInstall(I,false);
  1838. }
  1839. /* Now install their deps too, if we do this above then order of
  1840. the status file is significant for | groups */
  1841. for (I = Cache->PkgBegin();I.end() != true; I++)
  1842. {
  1843. /* Install the package only if it is a new install, the autoupgrader
  1844. will deal with the rest */
  1845. if (I->SelectedState == pkgCache::State::Install)
  1846. Cache->MarkInstall(I,true);
  1847. }
  1848. // Apply erasures now, they override everything else.
  1849. for (I = Cache->PkgBegin();I.end() != true; I++)
  1850. {
  1851. // Remove packages
  1852. if (I->SelectedState == pkgCache::State::DeInstall ||
  1853. I->SelectedState == pkgCache::State::Purge)
  1854. Cache->MarkDelete(I,I->SelectedState == pkgCache::State::Purge);
  1855. }
  1856. /* Resolve any problems that dselect created, allupgrade cannot handle
  1857. such things. We do so quite agressively too.. */
  1858. if (Cache->BrokenCount() != 0)
  1859. {
  1860. pkgProblemResolver Fix(Cache);
  1861. // Hold back held packages.
  1862. if (_config->FindB("APT::Ignore-Hold",false) == false)
  1863. {
  1864. for (pkgCache::PkgIterator I = Cache->PkgBegin(); I.end() == false; I++)
  1865. {
  1866. if (I->SelectedState == pkgCache::State::Hold)
  1867. {
  1868. Fix.Protect(I);
  1869. Cache->MarkKeep(I);
  1870. }
  1871. }
  1872. }
  1873. if (Fix.Resolve() == false)
  1874. {
  1875. ShowBroken(c1out,Cache,false);
  1876. return _error->Error(_("Internal error, problem resolver broke stuff"));
  1877. }
  1878. }
  1879. // Now upgrade everything
  1880. if (pkgAllUpgrade(Cache) == false)
  1881. {
  1882. ShowBroken(c1out,Cache,false);
  1883. return _error->Error(_("Internal error, problem resolver broke stuff"));
  1884. }
  1885. return InstallPackages(Cache,false);
  1886. }
  1887. /*}}}*/
  1888. // DoClean - Remove download archives /*{{{*/
  1889. // ---------------------------------------------------------------------
  1890. /* */
  1891. bool DoClean(CommandLine &CmdL)
  1892. {
  1893. if (_config->FindB("APT::Get::Simulate") == true)
  1894. {
  1895. cout << "Del " << _config->FindDir("Dir::Cache::archives") << "* " <<
  1896. _config->FindDir("Dir::Cache::archives") << "partial/*" << endl;
  1897. return true;
  1898. }
  1899. // Lock the archive directory
  1900. FileFd Lock;
  1901. if (_config->FindB("Debug::NoLocking",false) == false)
  1902. {
  1903. Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
  1904. if (_error->PendingError() == true)
  1905. return _error->Error(_("Unable to lock the download directory"));
  1906. }
  1907. pkgAcquire Fetcher;
  1908. Fetcher.Clean(_config->FindDir("Dir::Cache::archives"));
  1909. Fetcher.Clean(_config->FindDir("Dir::Cache::archives") + "partial/");
  1910. return true;
  1911. }
  1912. /*}}}*/
  1913. // DoAutoClean - Smartly remove downloaded archives /*{{{*/
  1914. // ---------------------------------------------------------------------
  1915. /* This is similar to clean but it only purges things that cannot be
  1916. downloaded, that is old versions of cached packages. */
  1917. class LogCleaner : public pkgArchiveCleaner
  1918. {
  1919. protected:
  1920. virtual void Erase(const char *File,string Pkg,string Ver,struct stat &St)
  1921. {
  1922. c1out << "Del " << Pkg << " " << Ver << " [" << SizeToStr(St.st_size) << "B]" << endl;
  1923. if (_config->FindB("APT::Get::Simulate") == false)
  1924. unlink(File);
  1925. };
  1926. };
  1927. bool DoAutoClean(CommandLine &CmdL)
  1928. {
  1929. // Lock the archive directory
  1930. FileFd Lock;
  1931. if (_config->FindB("Debug::NoLocking",false) == false)
  1932. {
  1933. Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
  1934. if (_error->PendingError() == true)
  1935. return _error->Error(_("Unable to lock the download directory"));
  1936. }
  1937. CacheFile Cache;
  1938. if (Cache.Open() == false)
  1939. return false;
  1940. LogCleaner Cleaner;
  1941. return Cleaner.Go(_config->FindDir("Dir::Cache::archives"),*Cache) &&
  1942. Cleaner.Go(_config->FindDir("Dir::Cache::archives") + "partial/",*Cache);
  1943. }
  1944. /*}}}*/
  1945. // DoDownload - download a binary /*{{{*/
  1946. // ---------------------------------------------------------------------
  1947. bool DoDownload(CommandLine &CmdL)
  1948. {
  1949. CacheFile Cache;
  1950. if (Cache.ReadOnlyOpen() == false)
  1951. return false;
  1952. APT::CacheSetHelper helper(c0out);
  1953. APT::VersionSet verset = APT::VersionSet::FromCommandLine(Cache,
  1954. CmdL.FileList + 1, APT::VersionSet::CANDIDATE, helper);
  1955. pkgAcquire Fetcher;
  1956. AcqTextStatus Stat(ScreenWidth, _config->FindI("quiet",0));
  1957. Fetcher.Setup(&Stat);
  1958. if (verset.empty() == true)
  1959. return false;
  1960. pkgRecords Recs(Cache);
  1961. pkgSourceList *SrcList = Cache.GetSourceList();
  1962. for (APT::VersionSet::const_iterator Ver = verset.begin();
  1963. Ver != verset.end();
  1964. ++Ver)
  1965. {
  1966. string descr;
  1967. // get the right version
  1968. pkgCache::PkgIterator Pkg = Ver.ParentPkg();
  1969. pkgRecords::Parser &rec=Recs.Lookup(Ver.FileList());
  1970. pkgCache::VerFileIterator Vf = Ver.FileList();
  1971. if (Vf.end() == true)
  1972. return _error->Error("Can not find VerFile");
  1973. pkgCache::PkgFileIterator F = Vf.File();
  1974. pkgIndexFile *index;
  1975. if(SrcList->FindIndex(F, index) == false)
  1976. return _error->Error("FindIndex failed");
  1977. string uri = index->ArchiveURI(rec.FileName());
  1978. strprintf(descr, _("Downloading %s %s"), Pkg.Name(), Ver.VerStr());
  1979. // get the most appropriate hash
  1980. HashString hash;
  1981. if (rec.SHA512Hash() != "")
  1982. hash = HashString("sha512", rec.SHA512Hash());
  1983. if (rec.SHA256Hash() != "")
  1984. hash = HashString("sha256", rec.SHA256Hash());
  1985. else if (rec.SHA1Hash() != "")
  1986. hash = HashString("sha1", rec.SHA1Hash());
  1987. else if (rec.MD5Hash() != "")
  1988. hash = HashString("md5", rec.MD5Hash());
  1989. // get the file
  1990. new pkgAcqFile(&Fetcher, uri, hash.toStr(), (*Ver)->Size, descr, Pkg.Name(), ".");
  1991. }
  1992. bool result = (Fetcher.Run() == pkgAcquire::Continue);
  1993. return result;
  1994. }
  1995. /*}}}*/
  1996. // DoCheck - Perform the check operation /*{{{*/
  1997. // ---------------------------------------------------------------------
  1998. /* Opening automatically checks the system, this command is mostly used
  1999. for debugging */
  2000. bool DoCheck(CommandLine &CmdL)
  2001. {
  2002. CacheFile Cache;
  2003. Cache.Open();
  2004. Cache.CheckDeps();
  2005. return true;
  2006. }
  2007. /*}}}*/
  2008. // DoSource - Fetch a source archive /*{{{*/
  2009. // ---------------------------------------------------------------------
  2010. /* Fetch souce packages */
  2011. struct DscFile
  2012. {
  2013. string Package;
  2014. string Version;
  2015. string Dsc;
  2016. };
  2017. bool DoSource(CommandLine &CmdL)
  2018. {
  2019. CacheFile Cache;
  2020. if (Cache.Open(false) == false)
  2021. return false;
  2022. if (CmdL.FileSize() <= 1)
  2023. return _error->Error(_("Must specify at least one package to fetch source for"));
  2024. // Read the source list
  2025. if (Cache.BuildSourceList() == false)
  2026. return false;
  2027. pkgSourceList *List = Cache.GetSourceList();
  2028. // Create the text record parsers
  2029. pkgRecords Recs(Cache);
  2030. pkgSrcRecords SrcRecs(*List);
  2031. if (_error->PendingError() == true)
  2032. return false;
  2033. // Create the download object
  2034. AcqTextStatus Stat(ScreenWidth,_config->FindI("quiet",0));
  2035. pkgAcquire Fetcher;
  2036. if (Fetcher.Setup(&Stat) == false)
  2037. return false;
  2038. DscFile *Dsc = new DscFile[CmdL.FileSize()];
  2039. // insert all downloaded uris into this set to avoid downloading them
  2040. // twice
  2041. set<string> queued;
  2042. // Diff only mode only fetches .diff files
  2043. bool const diffOnly = _config->FindB("APT::Get::Diff-Only", false);
  2044. // Tar only mode only fetches .tar files
  2045. bool const tarOnly = _config->FindB("APT::Get::Tar-Only", false);
  2046. // Dsc only mode only fetches .dsc files
  2047. bool const dscOnly = _config->FindB("APT::Get::Dsc-Only", false);
  2048. // Load the requestd sources into the fetcher
  2049. unsigned J = 0;
  2050. for (const char **I = CmdL.FileList + 1; *I != 0; I++, J++)
  2051. {
  2052. string Src;
  2053. pkgSrcRecords::Parser *Last = FindSrc(*I,Recs,SrcRecs,Src,*Cache);
  2054. if (Last == 0)
  2055. return _error->Error(_("Unable to find a source package for %s"),Src.c_str());
  2056. string srec = Last->AsStr();
  2057. string::size_type pos = srec.find("\nVcs-");
  2058. while (pos != string::npos)
  2059. {
  2060. pos += strlen("\nVcs-");
  2061. string vcs = srec.substr(pos,srec.find(":",pos)-pos);
  2062. if(vcs == "Browser")
  2063. {
  2064. pos = srec.find("\nVcs-", pos);
  2065. continue;
  2066. }
  2067. pos += vcs.length()+2;
  2068. string::size_type epos = srec.find("\n", pos);
  2069. string uri = srec.substr(pos,epos-pos).c_str();
  2070. ioprintf(c1out, _("NOTICE: '%s' packaging is maintained in "
  2071. "the '%s' version control system at:\n"
  2072. "%s\n"),
  2073. Src.c_str(), vcs.c_str(), uri.c_str());
  2074. if(vcs == "Bzr")
  2075. ioprintf(c1out,_("Please use:\n"
  2076. "bzr get %s\n"
  2077. "to retrieve the latest (possibly unreleased) "
  2078. "updates to the package.\n"),
  2079. uri.c_str());
  2080. break;
  2081. }
  2082. // Back track
  2083. vector<pkgSrcRecords::File> Lst;
  2084. if (Last->Files(Lst) == false)
  2085. return false;
  2086. // Load them into the fetcher
  2087. for (vector<pkgSrcRecords::File>::const_iterator I = Lst.begin();
  2088. I != Lst.end(); I++)
  2089. {
  2090. // Try to guess what sort of file it is we are getting.
  2091. if (I->Type == "dsc")
  2092. {
  2093. Dsc[J].Package = Last->Package();
  2094. Dsc[J].Version = Last->Version();
  2095. Dsc[J].Dsc = flNotDir(I->Path);
  2096. }
  2097. // Handle the only options so that multiple can be used at once
  2098. if (diffOnly == true || tarOnly == true || dscOnly == true)
  2099. {
  2100. if ((diffOnly == true && I->Type == "diff") ||
  2101. (tarOnly == true && I->Type == "tar") ||
  2102. (dscOnly == true && I->Type == "dsc"))
  2103. ; // Fine, we want this file downloaded
  2104. else
  2105. continue;
  2106. }
  2107. // don't download the same uri twice (should this be moved to
  2108. // the fetcher interface itself?)
  2109. if(queued.find(Last->Index().ArchiveURI(I->Path)) != queued.end())
  2110. continue;
  2111. queued.insert(Last->Index().ArchiveURI(I->Path));
  2112. // check if we have a file with that md5 sum already localy
  2113. if(!I->MD5Hash.empty() && FileExists(flNotDir(I->Path)))
  2114. {
  2115. FileFd Fd(flNotDir(I->Path), FileFd::ReadOnly);
  2116. MD5Summation sum;
  2117. sum.AddFD(Fd.Fd(), Fd.Size());
  2118. Fd.Close();
  2119. if((string)sum.Result() == I->MD5Hash)
  2120. {
  2121. ioprintf(c1out,_("Skipping already downloaded file '%s'\n"),
  2122. flNotDir(I->Path).c_str());
  2123. continue;
  2124. }
  2125. }
  2126. new pkgAcqFile(&Fetcher,Last->Index().ArchiveURI(I->Path),
  2127. I->MD5Hash,I->Size,
  2128. Last->Index().SourceInfo(*Last,*I),Src);
  2129. }
  2130. }
  2131. // Display statistics
  2132. unsigned long long FetchBytes = Fetcher.FetchNeeded();
  2133. unsigned long long FetchPBytes = Fetcher.PartialPresent();
  2134. unsigned long long DebBytes = Fetcher.TotalNeeded();
  2135. // Check for enough free space
  2136. struct statvfs Buf;
  2137. string OutputDir = ".";
  2138. if (statvfs(OutputDir.c_str(),&Buf) != 0) {
  2139. if (errno == EOVERFLOW)
  2140. return _error->WarningE("statvfs",_("Couldn't determine free space in %s"),
  2141. OutputDir.c_str());
  2142. else
  2143. return _error->Errno("statvfs",_("Couldn't determine free space in %s"),
  2144. OutputDir.c_str());
  2145. } else if (unsigned(Buf.f_bfree) < (FetchBytes - FetchPBytes)/Buf.f_bsize)
  2146. {
  2147. struct statfs Stat;
  2148. if (statfs(OutputDir.c_str(),&Stat) != 0
  2149. #if HAVE_STRUCT_STATFS_F_TYPE
  2150. || unsigned(Stat.f_type) != RAMFS_MAGIC
  2151. #endif
  2152. )
  2153. return _error->Error(_("You don't have enough free space in %s"),
  2154. OutputDir.c_str());
  2155. }
  2156. // Number of bytes
  2157. if (DebBytes != FetchBytes)
  2158. //TRANSLATOR: The required space between number and unit is already included
  2159. // in the replacement strings, so %sB will be correctly translate in e.g. 1,5 MB
  2160. ioprintf(c1out,_("Need to get %sB/%sB of source archives.\n"),
  2161. SizeToStr(FetchBytes).c_str(),SizeToStr(DebBytes).c_str());
  2162. else
  2163. //TRANSLATOR: The required space between number and unit is already included
  2164. // in the replacement string, so %sB will be correctly translate in e.g. 1,5 MB
  2165. ioprintf(c1out,_("Need to get %sB of source archives.\n"),
  2166. SizeToStr(DebBytes).c_str());
  2167. if (_config->FindB("APT::Get::Simulate",false) == true)
  2168. {
  2169. for (unsigned I = 0; I != J; I++)
  2170. ioprintf(cout,_("Fetch source %s\n"),Dsc[I].Package.c_str());
  2171. delete[] Dsc;
  2172. return true;
  2173. }
  2174. // Just print out the uris an exit if the --print-uris flag was used
  2175. if (_config->FindB("APT::Get::Print-URIs") == true)
  2176. {
  2177. pkgAcquire::UriIterator I = Fetcher.UriBegin();
  2178. for (; I != Fetcher.UriEnd(); I++)
  2179. cout << '\'' << I->URI << "' " << flNotDir(I->Owner->DestFile) << ' ' <<
  2180. I->Owner->FileSize << ' ' << I->Owner->HashSum() << endl;
  2181. delete[] Dsc;
  2182. return true;
  2183. }
  2184. // Run it
  2185. if (Fetcher.Run() == pkgAcquire::Failed)
  2186. return false;
  2187. // Print error messages
  2188. bool Failed = false;
  2189. for (pkgAcquire::ItemIterator I = Fetcher.ItemsBegin(); I != Fetcher.ItemsEnd(); I++)
  2190. {
  2191. if ((*I)->Status == pkgAcquire::Item::StatDone &&
  2192. (*I)->Complete == true)
  2193. continue;
  2194. fprintf(stderr,_("Failed to fetch %s %s\n"),(*I)->DescURI().c_str(),
  2195. (*I)->ErrorText.c_str());
  2196. Failed = true;
  2197. }
  2198. if (Failed == true)
  2199. return _error->Error(_("Failed to fetch some archives."));
  2200. if (_config->FindB("APT::Get::Download-only",false) == true)
  2201. {
  2202. c1out << _("Download complete and in download only mode") << endl;
  2203. delete[] Dsc;
  2204. return true;
  2205. }
  2206. // Unpack the sources
  2207. pid_t Process = ExecFork();
  2208. if (Process == 0)
  2209. {
  2210. bool const fixBroken = _config->FindB("APT::Get::Fix-Broken", false);
  2211. for (unsigned I = 0; I != J; I++)
  2212. {
  2213. string Dir = Dsc[I].Package + '-' + Cache->VS().UpstreamVersion(Dsc[I].Version.c_str());
  2214. // Diff only mode only fetches .diff files
  2215. if (_config->FindB("APT::Get::Diff-Only",false) == true ||
  2216. _config->FindB("APT::Get::Tar-Only",false) == true ||
  2217. Dsc[I].Dsc.empty() == true)
  2218. continue;
  2219. // See if the package is already unpacked
  2220. struct stat Stat;
  2221. if (fixBroken == false && stat(Dir.c_str(),&Stat) == 0 &&
  2222. S_ISDIR(Stat.st_mode) != 0)
  2223. {
  2224. ioprintf(c0out ,_("Skipping unpack of already unpacked source in %s\n"),
  2225. Dir.c_str());
  2226. }
  2227. else
  2228. {
  2229. // Call dpkg-source
  2230. char S[500];
  2231. snprintf(S,sizeof(S),"%s -x %s",
  2232. _config->Find("Dir::Bin::dpkg-source","dpkg-source").c_str(),
  2233. Dsc[I].Dsc.c_str());
  2234. if (system(S) != 0)
  2235. {
  2236. fprintf(stderr,_("Unpack command '%s' failed.\n"),S);
  2237. fprintf(stderr,_("Check if the 'dpkg-dev' package is installed.\n"));
  2238. _exit(1);
  2239. }
  2240. }
  2241. // Try to compile it with dpkg-buildpackage
  2242. if (_config->FindB("APT::Get::Compile",false) == true)
  2243. {
  2244. // Call dpkg-buildpackage
  2245. char S[500];
  2246. snprintf(S,sizeof(S),"cd %s && %s %s",
  2247. Dir.c_str(),
  2248. _config->Find("Dir::Bin::dpkg-buildpackage","dpkg-buildpackage").c_str(),
  2249. _config->Find("DPkg::Build-Options","-b -uc").c_str());
  2250. if (system(S) != 0)
  2251. {
  2252. fprintf(stderr,_("Build command '%s' failed.\n"),S);
  2253. _exit(1);
  2254. }
  2255. }
  2256. }
  2257. _exit(0);
  2258. }
  2259. delete[] Dsc;
  2260. // Wait for the subprocess
  2261. int Status = 0;
  2262. while (waitpid(Process,&Status,0) != Process)
  2263. {
  2264. if (errno == EINTR)
  2265. continue;
  2266. return _error->Errno("waitpid","Couldn't wait for subprocess");
  2267. }
  2268. if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
  2269. return _error->Error(_("Child process failed"));
  2270. return true;
  2271. }
  2272. /*}}}*/
  2273. // DoBuildDep - Install/removes packages to satisfy build dependencies /*{{{*/
  2274. // ---------------------------------------------------------------------
  2275. /* This function will look at the build depends list of the given source
  2276. package and install the necessary packages to make it true, or fail. */
  2277. bool DoBuildDep(CommandLine &CmdL)
  2278. {
  2279. CacheFile Cache;
  2280. if (Cache.Open(true) == false)
  2281. return false;
  2282. if (CmdL.FileSize() <= 1)
  2283. return _error->Error(_("Must specify at least one package to check builddeps for"));
  2284. // Read the source list
  2285. if (Cache.BuildSourceList() == false)
  2286. return false;
  2287. pkgSourceList *List = Cache.GetSourceList();
  2288. // Create the text record parsers
  2289. pkgRecords Recs(Cache);
  2290. pkgSrcRecords SrcRecs(*List);
  2291. if (_error->PendingError() == true)
  2292. return false;
  2293. // Create the download object
  2294. AcqTextStatus Stat(ScreenWidth,_config->FindI("quiet",0));
  2295. pkgAcquire Fetcher;
  2296. if (Fetcher.Setup(&Stat) == false)
  2297. return false;
  2298. unsigned J = 0;
  2299. bool const StripMultiArch = APT::Configuration::getArchitectures().size() <= 1;
  2300. for (const char **I = CmdL.FileList + 1; *I != 0; I++, J++)
  2301. {
  2302. string Src;
  2303. pkgSrcRecords::Parser *Last = FindSrc(*I,Recs,SrcRecs,Src,*Cache);
  2304. if (Last == 0)
  2305. return _error->Error(_("Unable to find a source package for %s"),Src.c_str());
  2306. // Process the build-dependencies
  2307. vector<pkgSrcRecords::Parser::BuildDepRec> BuildDeps;
  2308. if (Last->BuildDepends(BuildDeps, _config->FindB("APT::Get::Arch-Only", false), StripMultiArch) == false)
  2309. return _error->Error(_("Unable to get build-dependency information for %s"),Src.c_str());
  2310. // Also ensure that build-essential packages are present
  2311. Configuration::Item const *Opts = _config->Tree("APT::Build-Essential");
  2312. if (Opts)
  2313. Opts = Opts->Child;
  2314. for (; Opts; Opts = Opts->Next)
  2315. {
  2316. if (Opts->Value.empty() == true)
  2317. continue;
  2318. pkgSrcRecords::Parser::BuildDepRec rec;
  2319. rec.Package = Opts->Value;
  2320. rec.Type = pkgSrcRecords::Parser::BuildDependIndep;
  2321. rec.Op = 0;
  2322. BuildDeps.push_back(rec);
  2323. }
  2324. if (BuildDeps.size() == 0)
  2325. {
  2326. ioprintf(c1out,_("%s has no build depends.\n"),Src.c_str());
  2327. continue;
  2328. }
  2329. // Install the requested packages
  2330. vector <pkgSrcRecords::Parser::BuildDepRec>::iterator D;
  2331. pkgProblemResolver Fix(Cache);
  2332. bool skipAlternatives = false; // skip remaining alternatives in an or group
  2333. for (D = BuildDeps.begin(); D != BuildDeps.end(); D++)
  2334. {
  2335. bool hasAlternatives = (((*D).Op & pkgCache::Dep::Or) == pkgCache::Dep::Or);
  2336. if (skipAlternatives == true)
  2337. {
  2338. if (!hasAlternatives)
  2339. skipAlternatives = false; // end of or group
  2340. continue;
  2341. }
  2342. if ((*D).Type == pkgSrcRecords::Parser::BuildConflict ||
  2343. (*D).Type == pkgSrcRecords::Parser::BuildConflictIndep)
  2344. {
  2345. pkgCache::PkgIterator Pkg = Cache->FindPkg((*D).Package);
  2346. // Build-conflicts on unknown packages are silently ignored
  2347. if (Pkg.end() == true)
  2348. continue;
  2349. pkgCache::VerIterator IV = (*Cache)[Pkg].InstVerIter(*Cache);
  2350. /*
  2351. * Remove if we have an installed version that satisfies the
  2352. * version criteria
  2353. */
  2354. if (IV.end() == false &&
  2355. Cache->VS().CheckDep(IV.VerStr(),(*D).Op,(*D).Version.c_str()) == true)
  2356. TryToInstallBuildDep(Pkg,Cache,Fix,true,false);
  2357. }
  2358. else // BuildDep || BuildDepIndep
  2359. {
  2360. pkgCache::PkgIterator Pkg = Cache->FindPkg((*D).Package);
  2361. if (_config->FindB("Debug::BuildDeps",false) == true)
  2362. cout << "Looking for " << (*D).Package << "...\n";
  2363. if (Pkg.end() == true)
  2364. {
  2365. if (_config->FindB("Debug::BuildDeps",false) == true)
  2366. cout << " (not found)" << (*D).Package << endl;
  2367. if (hasAlternatives)
  2368. continue;
  2369. return _error->Error(_("%s dependency for %s cannot be satisfied "
  2370. "because the package %s cannot be found"),
  2371. Last->BuildDepType((*D).Type),Src.c_str(),
  2372. (*D).Package.c_str());
  2373. }
  2374. /*
  2375. * if there are alternatives, we've already picked one, so skip
  2376. * the rest
  2377. *
  2378. * TODO: this means that if there's a build-dep on A|B and B is
  2379. * installed, we'll still try to install A; more importantly,
  2380. * if A is currently broken, we cannot go back and try B. To fix
  2381. * this would require we do a Resolve cycle for each package we
  2382. * add to the install list. Ugh
  2383. */
  2384. /*
  2385. * If this is a virtual package, we need to check the list of
  2386. * packages that provide it and see if any of those are
  2387. * installed
  2388. */
  2389. pkgCache::PrvIterator Prv = Pkg.ProvidesList();
  2390. for (; Prv.end() != true; Prv++)
  2391. {
  2392. if (_config->FindB("Debug::BuildDeps",false) == true)
  2393. cout << " Checking provider " << Prv.OwnerPkg().FullName() << endl;
  2394. if ((*Cache)[Prv.OwnerPkg()].InstVerIter(*Cache).end() == false)
  2395. break;
  2396. }
  2397. // Get installed version and version we are going to install
  2398. pkgCache::VerIterator IV = (*Cache)[Pkg].InstVerIter(*Cache);
  2399. if ((*D).Version[0] != '\0') {
  2400. // Versioned dependency
  2401. pkgCache::VerIterator CV = (*Cache)[Pkg].CandidateVerIter(*Cache);
  2402. for (; CV.end() != true; CV++)
  2403. {
  2404. if (Cache->VS().CheckDep(CV.VerStr(),(*D).Op,(*D).Version.c_str()) == true)
  2405. break;
  2406. }
  2407. if (CV.end() == true)
  2408. {
  2409. if (hasAlternatives)
  2410. {
  2411. continue;
  2412. }
  2413. else
  2414. {
  2415. return _error->Error(_("%s dependency for %s cannot be satisfied "
  2416. "because no available versions of package %s "
  2417. "can satisfy version requirements"),
  2418. Last->BuildDepType((*D).Type),Src.c_str(),
  2419. (*D).Package.c_str());
  2420. }
  2421. }
  2422. }
  2423. else
  2424. {
  2425. // Only consider virtual packages if there is no versioned dependency
  2426. if (Prv.end() == false)
  2427. {
  2428. if (_config->FindB("Debug::BuildDeps",false) == true)
  2429. cout << " Is provided by installed package " << Prv.OwnerPkg().FullName() << endl;
  2430. skipAlternatives = hasAlternatives;
  2431. continue;
  2432. }
  2433. }
  2434. if (IV.end() == false)
  2435. {
  2436. if (_config->FindB("Debug::BuildDeps",false) == true)
  2437. cout << " Is installed\n";
  2438. if (Cache->VS().CheckDep(IV.VerStr(),(*D).Op,(*D).Version.c_str()) == true)
  2439. {
  2440. skipAlternatives = hasAlternatives;
  2441. continue;
  2442. }
  2443. if (_config->FindB("Debug::BuildDeps",false) == true)
  2444. cout << " ...but the installed version doesn't meet the version requirement\n";
  2445. if (((*D).Op & pkgCache::Dep::LessEq) == pkgCache::Dep::LessEq)
  2446. {
  2447. return _error->Error(_("Failed to satisfy %s dependency for %s: Installed package %s is too new"),
  2448. Last->BuildDepType((*D).Type),
  2449. Src.c_str(),
  2450. Pkg.FullName(true).c_str());
  2451. }
  2452. }
  2453. if (_config->FindB("Debug::BuildDeps",false) == true)
  2454. cout << " Trying to install " << (*D).Package << endl;
  2455. if (TryToInstallBuildDep(Pkg,Cache,Fix,false,false) == true)
  2456. {
  2457. // We successfully installed something; skip remaining alternatives
  2458. skipAlternatives = hasAlternatives;
  2459. if(_config->FindB("APT::Get::Build-Dep-Automatic", false) == true)
  2460. Cache->MarkAuto(Pkg, true);
  2461. continue;
  2462. }
  2463. else if (hasAlternatives)
  2464. {
  2465. if (_config->FindB("Debug::BuildDeps",false) == true)
  2466. cout << " Unsatisfiable, trying alternatives\n";
  2467. continue;
  2468. }
  2469. else
  2470. {
  2471. return _error->Error(_("Failed to satisfy %s dependency for %s: %s"),
  2472. Last->BuildDepType((*D).Type),
  2473. Src.c_str(),
  2474. (*D).Package.c_str());
  2475. }
  2476. }
  2477. }
  2478. Fix.InstallProtect();
  2479. if (Fix.Resolve(true) == false)
  2480. _error->Discard();
  2481. // Now we check the state of the packages,
  2482. if (Cache->BrokenCount() != 0)
  2483. {
  2484. ShowBroken(cout, Cache, false);
  2485. return _error->Error(_("Build-dependencies for %s could not be satisfied."),*I);
  2486. }
  2487. }
  2488. if (InstallPackages(Cache, false, true) == false)
  2489. return _error->Error(_("Failed to process build dependencies"));
  2490. return true;
  2491. }
  2492. /*}}}*/
  2493. // GetChangelogPath - return a path pointing to a changelog file or dir /*{{{*/
  2494. // ---------------------------------------------------------------------
  2495. /* This returns a "path" string for the changelog url construction.
  2496. * Please note that its not complete, it either needs a "/changelog"
  2497. * appended (for the packages.debian.org/changelogs site) or a
  2498. * ".changelog" (for third party sites that store the changelog in the
  2499. * pool/ next to the deb itself)
  2500. * Example return: "pool/main/a/apt/apt_0.8.8ubuntu3"
  2501. */
  2502. string GetChangelogPath(CacheFile &Cache,
  2503. pkgCache::PkgIterator Pkg,
  2504. pkgCache::VerIterator Ver)
  2505. {
  2506. string path;
  2507. pkgRecords Recs(Cache);
  2508. pkgRecords::Parser &rec=Recs.Lookup(Ver.FileList());
  2509. string srcpkg = rec.SourcePkg().empty() ? Pkg.Name() : rec.SourcePkg();
  2510. string ver = Ver.VerStr();
  2511. // if there is a source version it always wins
  2512. if (rec.SourceVer() != "")
  2513. ver = rec.SourceVer();
  2514. path = flNotFile(rec.FileName());
  2515. path += srcpkg + "_" + StripEpoch(ver);
  2516. return path;
  2517. }
  2518. /*}}}*/
  2519. // GuessThirdPartyChangelogUri - return url /*{{{*/
  2520. // ---------------------------------------------------------------------
  2521. /* Contruct a changelog file path for third party sites that do not use
  2522. * packages.debian.org/changelogs
  2523. * This simply uses the ArchiveURI() of the source pkg and looks for
  2524. * a .changelog file there, Example for "mediabuntu":
  2525. * apt-get changelog mplayer-doc:
  2526. * http://packages.medibuntu.org/pool/non-free/m/mplayer/mplayer_1.0~rc4~try1.dsfg1-1ubuntu1+medibuntu1.changelog
  2527. */
  2528. bool GuessThirdPartyChangelogUri(CacheFile &Cache,
  2529. pkgCache::PkgIterator Pkg,
  2530. pkgCache::VerIterator Ver,
  2531. string &out_uri)
  2532. {
  2533. // get the binary deb server path
  2534. pkgCache::VerFileIterator Vf = Ver.FileList();
  2535. if (Vf.end() == true)
  2536. return false;
  2537. pkgCache::PkgFileIterator F = Vf.File();
  2538. pkgIndexFile *index;
  2539. pkgSourceList *SrcList = Cache.GetSourceList();
  2540. if(SrcList->FindIndex(F, index) == false)
  2541. return false;
  2542. // get archive uri for the binary deb
  2543. string path_without_dot_changelog = GetChangelogPath(Cache, Pkg, Ver);
  2544. out_uri = index->ArchiveURI(path_without_dot_changelog + ".changelog");
  2545. // now strip away the filename and add srcpkg_srcver.changelog
  2546. return true;
  2547. }
  2548. // DownloadChangelog - Download the changelog /*{{{*/
  2549. // ---------------------------------------------------------------------
  2550. bool DownloadChangelog(CacheFile &CacheFile, pkgAcquire &Fetcher,
  2551. pkgCache::VerIterator Ver, string targetfile)
  2552. /* Download a changelog file for the given package version to
  2553. * targetfile. This will first try the server from Apt::Changelogs::Server
  2554. * (http://packages.debian.org/changelogs by default) and if that gives
  2555. * a 404 tries to get it from the archive directly (see
  2556. * GuessThirdPartyChangelogUri for details how)
  2557. */
  2558. {
  2559. string path;
  2560. string descr;
  2561. string server;
  2562. string changelog_uri;
  2563. // data structures we need
  2564. pkgCache::PkgIterator Pkg = Ver.ParentPkg();
  2565. // make the server root configurable
  2566. server = _config->Find("Apt::Changelogs::Server",
  2567. "http://packages.debian.org/changelogs");
  2568. path = GetChangelogPath(CacheFile, Pkg, Ver);
  2569. strprintf(changelog_uri, "%s/%s/changelog", server.c_str(), path.c_str());
  2570. strprintf(descr, _("Changelog for %s (%s)"), Pkg.Name(), changelog_uri.c_str());
  2571. // queue it
  2572. new pkgAcqFile(&Fetcher, changelog_uri, "", 0, descr, Pkg.Name(), "ignored", targetfile);
  2573. // try downloading it, if that fails, they third-party-changelogs location
  2574. // FIXME: res is "Continue" even if I get a 404?!?
  2575. int res = Fetcher.Run();
  2576. if (!FileExists(targetfile))
  2577. {
  2578. string third_party_uri;
  2579. if (GuessThirdPartyChangelogUri(CacheFile, Pkg, Ver, third_party_uri))
  2580. {
  2581. strprintf(descr, _("Changelog for %s (%s)"), Pkg.Name(), third_party_uri.c_str());
  2582. new pkgAcqFile(&Fetcher, third_party_uri, "", 0, descr, Pkg.Name(), "ignored", targetfile);
  2583. res = Fetcher.Run();
  2584. }
  2585. }
  2586. if (FileExists(targetfile))
  2587. return true;
  2588. // error
  2589. return _error->Error("changelog download failed");
  2590. }
  2591. /*}}}*/
  2592. // DisplayFileInPager - Display File with pager /*{{{*/
  2593. void DisplayFileInPager(string filename)
  2594. {
  2595. pid_t Process = ExecFork();
  2596. if (Process == 0)
  2597. {
  2598. const char *Args[3];
  2599. Args[0] = "/usr/bin/sensible-pager";
  2600. Args[1] = filename.c_str();
  2601. Args[2] = 0;
  2602. execvp(Args[0],(char **)Args);
  2603. exit(100);
  2604. }
  2605. // Wait for the subprocess
  2606. ExecWait(Process, "sensible-pager", false);
  2607. }
  2608. /*}}}*/
  2609. // DoChangelog - Get changelog from the command line /*{{{*/
  2610. // ---------------------------------------------------------------------
  2611. bool DoChangelog(CommandLine &CmdL)
  2612. {
  2613. CacheFile Cache;
  2614. if (Cache.ReadOnlyOpen() == false)
  2615. return false;
  2616. APT::CacheSetHelper helper(c0out);
  2617. APT::VersionSet verset = APT::VersionSet::FromCommandLine(Cache,
  2618. CmdL.FileList + 1, APT::VersionSet::CANDIDATE, helper);
  2619. pkgAcquire Fetcher;
  2620. AcqTextStatus Stat(ScreenWidth, _config->FindI("quiet",0));
  2621. Fetcher.Setup(&Stat);
  2622. if (verset.empty() == true)
  2623. return false;
  2624. char *tmpdir = mkdtemp(strdup("/tmp/apt-changelog-XXXXXX"));
  2625. if (tmpdir == NULL) {
  2626. return _error->Errno("mkdtemp", "mkdtemp failed");
  2627. }
  2628. for (APT::VersionSet::const_iterator Ver = verset.begin();
  2629. Ver != verset.end();
  2630. ++Ver)
  2631. {
  2632. string changelogfile = string(tmpdir) + "changelog";
  2633. if (DownloadChangelog(Cache, Fetcher, Ver, changelogfile))
  2634. DisplayFileInPager(changelogfile);
  2635. // cleanup temp file
  2636. unlink(changelogfile.c_str());
  2637. }
  2638. // clenaup tmp dir
  2639. rmdir(tmpdir);
  2640. free(tmpdir);
  2641. return true;
  2642. }
  2643. /*}}}*/
  2644. // DoMoo - Never Ask, Never Tell /*{{{*/
  2645. // ---------------------------------------------------------------------
  2646. /* */
  2647. bool DoMoo(CommandLine &CmdL)
  2648. {
  2649. cout <<
  2650. " (__) \n"
  2651. " (oo) \n"
  2652. " /------\\/ \n"
  2653. " / | || \n"
  2654. " * /\\---/\\ \n"
  2655. " ~~ ~~ \n"
  2656. "....\"Have you mooed today?\"...\n";
  2657. return true;
  2658. }
  2659. /*}}}*/
  2660. // ShowHelp - Show a help screen /*{{{*/
  2661. // ---------------------------------------------------------------------
  2662. /* */
  2663. bool ShowHelp(CommandLine &CmdL)
  2664. {
  2665. ioprintf(cout,_("%s %s for %s compiled on %s %s\n"),PACKAGE,VERSION,
  2666. COMMON_ARCH,__DATE__,__TIME__);
  2667. if (_config->FindB("version") == true)
  2668. {
  2669. cout << _("Supported modules:") << endl;
  2670. for (unsigned I = 0; I != pkgVersioningSystem::GlobalListLen; I++)
  2671. {
  2672. pkgVersioningSystem *VS = pkgVersioningSystem::GlobalList[I];
  2673. if (_system != 0 && _system->VS == VS)
  2674. cout << '*';
  2675. else
  2676. cout << ' ';
  2677. cout << "Ver: " << VS->Label << endl;
  2678. /* Print out all the packaging systems that will work with
  2679. this VS */
  2680. for (unsigned J = 0; J != pkgSystem::GlobalListLen; J++)
  2681. {
  2682. pkgSystem *Sys = pkgSystem::GlobalList[J];
  2683. if (_system == Sys)
  2684. cout << '*';
  2685. else
  2686. cout << ' ';
  2687. if (Sys->VS->TestCompatibility(*VS) == true)
  2688. cout << "Pkg: " << Sys->Label << " (Priority " << Sys->Score(*_config) << ")" << endl;
  2689. }
  2690. }
  2691. for (unsigned I = 0; I != pkgSourceList::Type::GlobalListLen; I++)
  2692. {
  2693. pkgSourceList::Type *Type = pkgSourceList::Type::GlobalList[I];
  2694. cout << " S.L: '" << Type->Name << "' " << Type->Label << endl;
  2695. }
  2696. for (unsigned I = 0; I != pkgIndexFile::Type::GlobalListLen; I++)
  2697. {
  2698. pkgIndexFile::Type *Type = pkgIndexFile::Type::GlobalList[I];
  2699. cout << " Idx: " << Type->Label << endl;
  2700. }
  2701. return true;
  2702. }
  2703. cout <<
  2704. _("Usage: apt-get [options] command\n"
  2705. " apt-get [options] install|remove pkg1 [pkg2 ...]\n"
  2706. " apt-get [options] source pkg1 [pkg2 ...]\n"
  2707. "\n"
  2708. "apt-get is a simple command line interface for downloading and\n"
  2709. "installing packages. The most frequently used commands are update\n"
  2710. "and install.\n"
  2711. "\n"
  2712. "Commands:\n"
  2713. " update - Retrieve new lists of packages\n"
  2714. " upgrade - Perform an upgrade\n"
  2715. " install - Install new packages (pkg is libc6 not libc6.deb)\n"
  2716. " remove - Remove packages\n"
  2717. " autoremove - Remove automatically all unused packages\n"
  2718. " purge - Remove packages and config files\n"
  2719. " source - Download source archives\n"
  2720. " build-dep - Configure build-dependencies for source packages\n"
  2721. " dist-upgrade - Distribution upgrade, see apt-get(8)\n"
  2722. " dselect-upgrade - Follow dselect selections\n"
  2723. " clean - Erase downloaded archive files\n"
  2724. " autoclean - Erase old downloaded archive files\n"
  2725. " check - Verify that there are no broken dependencies\n"
  2726. " markauto - Mark the given packages as automatically installed\n"
  2727. " unmarkauto - Mark the given packages as manually installed\n"
  2728. " changelog - Download and display the changelog for the given package\n"
  2729. " download - Download the binary package into the current directory\n"
  2730. "\n"
  2731. "Options:\n"
  2732. " -h This help text.\n"
  2733. " -q Loggable output - no progress indicator\n"
  2734. " -qq No output except for errors\n"
  2735. " -d Download only - do NOT install or unpack archives\n"
  2736. " -s No-act. Perform ordering simulation\n"
  2737. " -y Assume Yes to all queries and do not prompt\n"
  2738. " -f Attempt to correct a system with broken dependencies in place\n"
  2739. " -m Attempt to continue if archives are unlocatable\n"
  2740. " -u Show a list of upgraded packages as well\n"
  2741. " -b Build the source package after fetching it\n"
  2742. " -V Show verbose version numbers\n"
  2743. " -c=? Read this configuration file\n"
  2744. " -o=? Set an arbitrary configuration option, eg -o dir::cache=/tmp\n"
  2745. "See the apt-get(8), sources.list(5) and apt.conf(5) manual\n"
  2746. "pages for more information and options.\n"
  2747. " This APT has Super Cow Powers.\n");
  2748. return true;
  2749. }
  2750. /*}}}*/
  2751. // SigWinch - Window size change signal handler /*{{{*/
  2752. // ---------------------------------------------------------------------
  2753. /* */
  2754. void SigWinch(int)
  2755. {
  2756. // Riped from GNU ls
  2757. #ifdef TIOCGWINSZ
  2758. struct winsize ws;
  2759. if (ioctl(1, TIOCGWINSZ, &ws) != -1 && ws.ws_col >= 5)
  2760. ScreenWidth = ws.ws_col - 1;
  2761. #endif
  2762. }
  2763. /*}}}*/
  2764. int main(int argc,const char *argv[]) /*{{{*/
  2765. {
  2766. CommandLine::Args Args[] = {
  2767. {'h',"help","help",0},
  2768. {'v',"version","version",0},
  2769. {'V',"verbose-versions","APT::Get::Show-Versions",0},
  2770. {'q',"quiet","quiet",CommandLine::IntLevel},
  2771. {'q',"silent","quiet",CommandLine::IntLevel},
  2772. {'d',"download-only","APT::Get::Download-Only",0},
  2773. {'b',"compile","APT::Get::Compile",0},
  2774. {'b',"build","APT::Get::Compile",0},
  2775. {'s',"simulate","APT::Get::Simulate",0},
  2776. {'s',"just-print","APT::Get::Simulate",0},
  2777. {'s',"recon","APT::Get::Simulate",0},
  2778. {'s',"dry-run","APT::Get::Simulate",0},
  2779. {'s',"no-act","APT::Get::Simulate",0},
  2780. {'y',"yes","APT::Get::Assume-Yes",0},
  2781. {'y',"assume-yes","APT::Get::Assume-Yes",0},
  2782. {'f',"fix-broken","APT::Get::Fix-Broken",0},
  2783. {'u',"show-upgraded","APT::Get::Show-Upgraded",0},
  2784. {'m',"ignore-missing","APT::Get::Fix-Missing",0},
  2785. {'t',"target-release","APT::Default-Release",CommandLine::HasArg},
  2786. {'t',"default-release","APT::Default-Release",CommandLine::HasArg},
  2787. {0,"download","APT::Get::Download",0},
  2788. {0,"fix-missing","APT::Get::Fix-Missing",0},
  2789. {0,"ignore-hold","APT::Ignore-Hold",0},
  2790. {0,"upgrade","APT::Get::upgrade",0},
  2791. {0,"only-upgrade","APT::Get::Only-Upgrade",0},
  2792. {0,"force-yes","APT::Get::force-yes",0},
  2793. {0,"print-uris","APT::Get::Print-URIs",0},
  2794. {0,"diff-only","APT::Get::Diff-Only",0},
  2795. {0,"debian-only","APT::Get::Diff-Only",0},
  2796. {0,"tar-only","APT::Get::Tar-Only",0},
  2797. {0,"dsc-only","APT::Get::Dsc-Only",0},
  2798. {0,"purge","APT::Get::Purge",0},
  2799. {0,"list-cleanup","APT::Get::List-Cleanup",0},
  2800. {0,"reinstall","APT::Get::ReInstall",0},
  2801. {0,"trivial-only","APT::Get::Trivial-Only",0},
  2802. {0,"remove","APT::Get::Remove",0},
  2803. {0,"only-source","APT::Get::Only-Source",0},
  2804. {0,"arch-only","APT::Get::Arch-Only",0},
  2805. {0,"auto-remove","APT::Get::AutomaticRemove",0},
  2806. {0,"allow-unauthenticated","APT::Get::AllowUnauthenticated",0},
  2807. {0,"install-recommends","APT::Install-Recommends",CommandLine::Boolean},
  2808. {0,"fix-policy","APT::Get::Fix-Policy-Broken",0},
  2809. {'c',"config-file",0,CommandLine::ConfigFile},
  2810. {'o',"option",0,CommandLine::ArbItem},
  2811. {0,0,0,0}};
  2812. CommandLine::Dispatch Cmds[] = {{"update",&DoUpdate},
  2813. {"upgrade",&DoUpgrade},
  2814. {"install",&DoInstall},
  2815. {"remove",&DoInstall},
  2816. {"purge",&DoInstall},
  2817. {"autoremove",&DoInstall},
  2818. {"markauto",&DoMarkAuto},
  2819. {"unmarkauto",&DoMarkAuto},
  2820. {"dist-upgrade",&DoDistUpgrade},
  2821. {"dselect-upgrade",&DoDSelectUpgrade},
  2822. {"build-dep",&DoBuildDep},
  2823. {"clean",&DoClean},
  2824. {"autoclean",&DoAutoClean},
  2825. {"check",&DoCheck},
  2826. {"source",&DoSource},
  2827. {"download",&DoDownload},
  2828. {"changelog",&DoChangelog},
  2829. {"moo",&DoMoo},
  2830. {"help",&ShowHelp},
  2831. {0,0}};
  2832. // Set up gettext support
  2833. setlocale(LC_ALL,"");
  2834. textdomain(PACKAGE);
  2835. // Parse the command line and initialize the package library
  2836. CommandLine CmdL(Args,_config);
  2837. if (pkgInitConfig(*_config) == false ||
  2838. CmdL.Parse(argc,argv) == false ||
  2839. pkgInitSystem(*_config,_system) == false)
  2840. {
  2841. if (_config->FindB("version") == true)
  2842. ShowHelp(CmdL);
  2843. _error->DumpErrors();
  2844. return 100;
  2845. }
  2846. // See if the help should be shown
  2847. if (_config->FindB("help") == true ||
  2848. _config->FindB("version") == true ||
  2849. CmdL.FileSize() == 0)
  2850. {
  2851. ShowHelp(CmdL);
  2852. return 0;
  2853. }
  2854. // simulate user-friendly if apt-get has no root privileges
  2855. if (getuid() != 0 && _config->FindB("APT::Get::Simulate") == true)
  2856. {
  2857. if (_config->FindB("APT::Get::Show-User-Simulation-Note",true) == true)
  2858. cout << _("NOTE: This is only a simulation!\n"
  2859. " apt-get needs root privileges for real execution.\n"
  2860. " Keep also in mind that locking is deactivated,\n"
  2861. " so don't depend on the relevance to the real current situation!"
  2862. ) << std::endl;
  2863. _config->Set("Debug::NoLocking",true);
  2864. }
  2865. // Deal with stdout not being a tty
  2866. if (!isatty(STDOUT_FILENO) && _config->FindI("quiet", -1) == -1)
  2867. _config->Set("quiet","1");
  2868. // Setup the output streams
  2869. c0out.rdbuf(cout.rdbuf());
  2870. c1out.rdbuf(cout.rdbuf());
  2871. c2out.rdbuf(cout.rdbuf());
  2872. if (_config->FindI("quiet",0) > 0)
  2873. c0out.rdbuf(devnull.rdbuf());
  2874. if (_config->FindI("quiet",0) > 1)
  2875. c1out.rdbuf(devnull.rdbuf());
  2876. // Setup the signals
  2877. signal(SIGPIPE,SIG_IGN);
  2878. signal(SIGWINCH,SigWinch);
  2879. SigWinch(0);
  2880. // Match the operation
  2881. CmdL.DispatchArg(Cmds);
  2882. // Print any errors or warnings found during parsing
  2883. bool const Errors = _error->PendingError();
  2884. if (_config->FindI("quiet",0) > 0)
  2885. _error->DumpErrors();
  2886. else
  2887. _error->DumpErrors(GlobalError::DEBUG);
  2888. return Errors == true ? 100 : 0;
  2889. }
  2890. /*}}}*/