acquire-item.cc 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: acquire-item.cc,v 1.46.2.9 2004/01/16 18:51:11 mdz Exp $
  4. /* ######################################################################
  5. Acquire Item - Item to acquire
  6. Each item can download to exactly one file at a time. This means you
  7. cannot create an item that fetches two uri's to two files at the same
  8. time. The pkgAcqIndex class creates a second class upon instantiation
  9. to fetch the other index files because of this.
  10. ##################################################################### */
  11. /*}}}*/
  12. // Include Files /*{{{*/
  13. #include <config.h>
  14. #include <apt-pkg/acquire-item.h>
  15. #include <apt-pkg/configuration.h>
  16. #include <apt-pkg/aptconfiguration.h>
  17. #include <apt-pkg/sourcelist.h>
  18. #include <apt-pkg/error.h>
  19. #include <apt-pkg/strutl.h>
  20. #include <apt-pkg/fileutl.h>
  21. #include <apt-pkg/sha1.h>
  22. #include <apt-pkg/tagfile.h>
  23. #include <apt-pkg/indexrecords.h>
  24. #include <apt-pkg/acquire.h>
  25. #include <apt-pkg/hashes.h>
  26. #include <apt-pkg/indexfile.h>
  27. #include <apt-pkg/pkgcache.h>
  28. #include <apt-pkg/cacheiterators.h>
  29. #include <apt-pkg/pkgrecords.h>
  30. #include <stddef.h>
  31. #include <stdlib.h>
  32. #include <string.h>
  33. #include <iostream>
  34. #include <vector>
  35. #include <sys/stat.h>
  36. #include <unistd.h>
  37. #include <errno.h>
  38. #include <string>
  39. #include <sstream>
  40. #include <stdio.h>
  41. #include <ctime>
  42. #include <sys/types.h>
  43. #include <pwd.h>
  44. #include <grp.h>
  45. #include <apti18n.h>
  46. /*}}}*/
  47. using namespace std;
  48. static void printHashSumComparision(std::string const &URI, HashStringList const &Expected, HashStringList const &Actual) /*{{{*/
  49. {
  50. if (_config->FindB("Debug::Acquire::HashSumMismatch", false) == false)
  51. return;
  52. std::cerr << std::endl << URI << ":" << std::endl << " Expected Hash: " << std::endl;
  53. for (HashStringList::const_iterator hs = Expected.begin(); hs != Expected.end(); ++hs)
  54. std::cerr << "\t- " << hs->toStr() << std::endl;
  55. std::cerr << " Actual Hash: " << std::endl;
  56. for (HashStringList::const_iterator hs = Actual.begin(); hs != Actual.end(); ++hs)
  57. std::cerr << "\t- " << hs->toStr() << std::endl;
  58. }
  59. /*}}}*/
  60. static void ChangeOwnerAndPermissionOfFile(char const * const requester, char const * const file, char const * const user, char const * const group, mode_t const mode) /*{{{*/
  61. {
  62. // ensure the file is owned by root and has good permissions
  63. struct passwd const * const pw = getpwnam(user);
  64. struct group const * const gr = getgrnam(group);
  65. if (getuid() == 0) // if we aren't root, we can't chown, so don't try it
  66. {
  67. if (pw != NULL && gr != NULL && chown(file, pw->pw_uid, gr->gr_gid) != 0)
  68. _error->WarningE(requester, "chown to %s:%s of file %s failed", user, group, file);
  69. }
  70. if (chmod(file, mode) != 0)
  71. _error->WarningE(requester, "chmod 0%o of file %s failed", mode, file);
  72. }
  73. /*}}}*/
  74. static std::string GetPartialFileName(std::string const &file) /*{{{*/
  75. {
  76. std::string DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  77. DestFile += file;
  78. return DestFile;
  79. }
  80. /*}}}*/
  81. static std::string GetPartialFileNameFromURI(std::string const &uri) /*{{{*/
  82. {
  83. return GetPartialFileName(URItoFileName(uri));
  84. }
  85. /*}}}*/
  86. static std::string GetCompressedFileName(std::string const &URI, std::string const &Name, std::string const &Ext) /*{{{*/
  87. {
  88. if (Ext.empty() || Ext == "uncompressed")
  89. return Name;
  90. // do not reverify cdrom sources as apt-cdrom may rewrite the Packages
  91. // file when its doing the indexcopy
  92. if (URI.substr(0,6) == "cdrom:")
  93. return Name;
  94. // adjust DestFile if its compressed on disk
  95. if (_config->FindB("Acquire::GzipIndexes",false) == true)
  96. return Name + '.' + Ext;
  97. return Name;
  98. }
  99. /*}}}*/
  100. static bool AllowInsecureRepositories(indexRecords const * const MetaIndexParser, pkgAcqMetaBase * const TransactionManager, pkgAcquire::Item * const I) /*{{{*/
  101. {
  102. if(MetaIndexParser->IsAlwaysTrusted() || _config->FindB("Acquire::AllowInsecureRepositories") == true)
  103. return true;
  104. _error->Error(_("Use --allow-insecure-repositories to force the update"));
  105. TransactionManager->AbortTransaction();
  106. I->Status = pkgAcquire::Item::StatError;
  107. return false;
  108. }
  109. /*}}}*/
  110. // Acquire::Item::Item - Constructor /*{{{*/
  111. #if __GNUC__ >= 4
  112. #pragma GCC diagnostic push
  113. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  114. #endif
  115. pkgAcquire::Item::Item(pkgAcquire *Owner,
  116. HashStringList const &ExpectedHashes,
  117. pkgAcqMetaBase *TransactionManager)
  118. : Owner(Owner), FileSize(0), PartialSize(0), Mode(0), ID(0), Complete(false),
  119. Local(false), QueueCounter(0), TransactionManager(TransactionManager),
  120. ExpectedAdditionalItems(0), ExpectedHashes(ExpectedHashes)
  121. {
  122. Owner->Add(this);
  123. Status = StatIdle;
  124. if(TransactionManager != NULL)
  125. TransactionManager->Add(this);
  126. }
  127. #if __GNUC__ >= 4
  128. #pragma GCC diagnostic pop
  129. #endif
  130. /*}}}*/
  131. // Acquire::Item::~Item - Destructor /*{{{*/
  132. // ---------------------------------------------------------------------
  133. /* */
  134. pkgAcquire::Item::~Item()
  135. {
  136. Owner->Remove(this);
  137. }
  138. /*}}}*/
  139. // Acquire::Item::Failed - Item failed to download /*{{{*/
  140. // ---------------------------------------------------------------------
  141. /* We return to an idle state if there are still other queues that could
  142. fetch this object */
  143. void pkgAcquire::Item::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  144. {
  145. if(ErrorText == "")
  146. ErrorText = LookupTag(Message,"Message");
  147. UsedMirror = LookupTag(Message,"UsedMirror");
  148. if (QueueCounter <= 1)
  149. {
  150. /* This indicates that the file is not available right now but might
  151. be sometime later. If we do a retry cycle then this should be
  152. retried [CDROMs] */
  153. if (Cnf != NULL && Cnf->LocalOnly == true &&
  154. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  155. {
  156. Status = StatIdle;
  157. Dequeue();
  158. return;
  159. }
  160. Status = StatError;
  161. Complete = false;
  162. Dequeue();
  163. }
  164. else
  165. Status = StatIdle;
  166. // check fail reason
  167. string FailReason = LookupTag(Message, "FailReason");
  168. if(FailReason == "MaximumSizeExceeded")
  169. Rename(DestFile, DestFile+".FAILED");
  170. // report mirror failure back to LP if we actually use a mirror
  171. if(FailReason.size() != 0)
  172. ReportMirrorFailure(FailReason);
  173. else
  174. ReportMirrorFailure(ErrorText);
  175. }
  176. /*}}}*/
  177. // Acquire::Item::Start - Item has begun to download /*{{{*/
  178. // ---------------------------------------------------------------------
  179. /* Stash status and the file size. Note that setting Complete means
  180. sub-phases of the acquire process such as decompresion are operating */
  181. void pkgAcquire::Item::Start(string /*Message*/,unsigned long long Size)
  182. {
  183. Status = StatFetching;
  184. if (FileSize == 0 && Complete == false)
  185. FileSize = Size;
  186. }
  187. /*}}}*/
  188. // Acquire::Item::Done - Item downloaded OK /*{{{*/
  189. // ---------------------------------------------------------------------
  190. /* */
  191. void pkgAcquire::Item::Done(string Message,unsigned long long Size,HashStringList const &/*Hash*/,
  192. pkgAcquire::MethodConfig * /*Cnf*/)
  193. {
  194. // We just downloaded something..
  195. string FileName = LookupTag(Message,"Filename");
  196. UsedMirror = LookupTag(Message,"UsedMirror");
  197. if (Complete == false && !Local && FileName == DestFile)
  198. {
  199. if (Owner->Log != 0)
  200. Owner->Log->Fetched(Size,atoi(LookupTag(Message,"Resume-Point","0").c_str()));
  201. }
  202. if (FileSize == 0)
  203. FileSize= Size;
  204. Status = StatDone;
  205. ErrorText = string();
  206. Owner->Dequeue(this);
  207. }
  208. /*}}}*/
  209. // Acquire::Item::Rename - Rename a file /*{{{*/
  210. // ---------------------------------------------------------------------
  211. /* This helper function is used by a lot of item methods as their final
  212. step */
  213. bool pkgAcquire::Item::Rename(string From,string To)
  214. {
  215. if (rename(From.c_str(),To.c_str()) == 0)
  216. return true;
  217. std::string S;
  218. strprintf(S, _("rename failed, %s (%s -> %s)."), strerror(errno),
  219. From.c_str(),To.c_str());
  220. Status = StatError;
  221. ErrorText += S;
  222. return false;
  223. }
  224. /*}}}*/
  225. void pkgAcquire::Item::QueueURI(ItemDesc &Item) /*{{{*/
  226. {
  227. if (RealFileExists(DestFile))
  228. {
  229. std::string SandboxUser = _config->Find("APT::Sandbox::User");
  230. ChangeOwnerAndPermissionOfFile("Item::QueueURI", DestFile.c_str(),
  231. SandboxUser.c_str(), "root", 0600);
  232. }
  233. Owner->Enqueue(Item);
  234. }
  235. /*}}}*/
  236. void pkgAcquire::Item::Dequeue() /*{{{*/
  237. {
  238. Owner->Dequeue(this);
  239. }
  240. /*}}}*/
  241. bool pkgAcquire::Item::RenameOnError(pkgAcquire::Item::RenameOnErrorState const error)/*{{{*/
  242. {
  243. if(FileExists(DestFile))
  244. Rename(DestFile, DestFile + ".FAILED");
  245. switch (error)
  246. {
  247. case HashSumMismatch:
  248. ErrorText = _("Hash Sum mismatch");
  249. Status = StatAuthError;
  250. ReportMirrorFailure("HashChecksumFailure");
  251. break;
  252. case SizeMismatch:
  253. ErrorText = _("Size mismatch");
  254. Status = StatAuthError;
  255. ReportMirrorFailure("SizeFailure");
  256. break;
  257. case InvalidFormat:
  258. ErrorText = _("Invalid file format");
  259. Status = StatError;
  260. // do not report as usually its not the mirrors fault, but Portal/Proxy
  261. break;
  262. case SignatureError:
  263. ErrorText = _("Signature error");
  264. Status = StatError;
  265. break;
  266. case NotClearsigned:
  267. ErrorText = _("Does not start with a cleartext signature");
  268. Status = StatError;
  269. break;
  270. }
  271. return false;
  272. }
  273. /*}}}*/
  274. void pkgAcquire::Item::SetActiveSubprocess(const std::string &subprocess)/*{{{*/
  275. {
  276. ActiveSubprocess = subprocess;
  277. #if __GNUC__ >= 4
  278. #pragma GCC diagnostic push
  279. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  280. #endif
  281. Mode = ActiveSubprocess.c_str();
  282. #if __GNUC__ >= 4
  283. #pragma GCC diagnostic pop
  284. #endif
  285. }
  286. /*}}}*/
  287. // Acquire::Item::ReportMirrorFailure /*{{{*/
  288. // ---------------------------------------------------------------------
  289. void pkgAcquire::Item::ReportMirrorFailure(string FailCode)
  290. {
  291. // we only act if a mirror was used at all
  292. if(UsedMirror.empty())
  293. return;
  294. #if 0
  295. std::cerr << "\nReportMirrorFailure: "
  296. << UsedMirror
  297. << " Uri: " << DescURI()
  298. << " FailCode: "
  299. << FailCode << std::endl;
  300. #endif
  301. string report = _config->Find("Methods::Mirror::ProblemReporting",
  302. "/usr/lib/apt/apt-report-mirror-failure");
  303. if(!FileExists(report))
  304. return;
  305. std::vector<char const*> Args;
  306. Args.push_back(report.c_str());
  307. Args.push_back(UsedMirror.c_str());
  308. Args.push_back(DescURI().c_str());
  309. Args.push_back(FailCode.c_str());
  310. Args.push_back(NULL);
  311. pid_t pid = ExecFork();
  312. if(pid < 0)
  313. {
  314. _error->Error("ReportMirrorFailure Fork failed");
  315. return;
  316. }
  317. else if(pid == 0)
  318. {
  319. execvp(Args[0], (char**)Args.data());
  320. std::cerr << "Could not exec " << Args[0] << std::endl;
  321. _exit(100);
  322. }
  323. if(!ExecWait(pid, "report-mirror-failure"))
  324. {
  325. _error->Warning("Couldn't report problem to '%s'",
  326. _config->Find("Methods::Mirror::ProblemReporting").c_str());
  327. }
  328. }
  329. /*}}}*/
  330. // AcqDiffIndex::AcqDiffIndex - Constructor /*{{{*/
  331. // ---------------------------------------------------------------------
  332. /* Get the DiffIndex file first and see if there are patches available
  333. * If so, create a pkgAcqIndexDiffs fetcher that will get and apply the
  334. * patches. If anything goes wrong in that process, it will fall back to
  335. * the original packages file
  336. */
  337. pkgAcqDiffIndex::pkgAcqDiffIndex(pkgAcquire *Owner,
  338. pkgAcqMetaBase *TransactionManager,
  339. IndexTarget const * const Target,
  340. HashStringList const &ExpectedHashes,
  341. indexRecords *MetaIndexParser)
  342. : pkgAcqBaseIndex(Owner, TransactionManager, Target, ExpectedHashes,
  343. MetaIndexParser), PackagesFileReadyInPartial(false)
  344. {
  345. Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
  346. RealURI = Target->URI;
  347. Desc.Owner = this;
  348. Desc.Description = Target->Description + ".diff/Index";
  349. Desc.ShortDesc = Target->ShortDesc;
  350. Desc.URI = Target->URI + ".diff/Index";
  351. DestFile = GetPartialFileNameFromURI(Desc.URI);
  352. if(Debug)
  353. std::clog << "pkgAcqDiffIndex: " << Desc.URI << std::endl;
  354. // look for the current package file
  355. CurrentPackagesFile = _config->FindDir("Dir::State::lists");
  356. CurrentPackagesFile += URItoFileName(RealURI);
  357. // FIXME: this file:/ check is a hack to prevent fetching
  358. // from local sources. this is really silly, and
  359. // should be fixed cleanly as soon as possible
  360. if(!FileExists(CurrentPackagesFile) ||
  361. Desc.URI.substr(0,strlen("file:/")) == "file:/")
  362. {
  363. // we don't have a pkg file or we don't want to queue
  364. Failed("No index file, local or canceld by user", NULL);
  365. return;
  366. }
  367. if(Debug)
  368. std::clog << "pkgAcqDiffIndex::pkgAcqDiffIndex(): "
  369. << CurrentPackagesFile << std::endl;
  370. QueueURI(Desc);
  371. }
  372. /*}}}*/
  373. // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
  374. // ---------------------------------------------------------------------
  375. /* The only header we use is the last-modified header. */
  376. string pkgAcqDiffIndex::Custom600Headers() const
  377. {
  378. string Final = _config->FindDir("Dir::State::lists");
  379. Final += URItoFileName(Desc.URI);
  380. if(Debug)
  381. std::clog << "Custom600Header-IMS: " << Final << std::endl;
  382. struct stat Buf;
  383. if (stat(Final.c_str(),&Buf) != 0)
  384. return "\nIndex-File: true";
  385. return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  386. }
  387. /*}}}*/
  388. bool pkgAcqDiffIndex::ParseDiffIndex(string IndexDiffFile) /*{{{*/
  389. {
  390. // failing here is fine: our caller will take care of trying to
  391. // get the complete file if patching fails
  392. if(Debug)
  393. std::clog << "pkgAcqDiffIndex::ParseIndexDiff() " << IndexDiffFile
  394. << std::endl;
  395. FileFd Fd(IndexDiffFile,FileFd::ReadOnly);
  396. pkgTagFile TF(&Fd);
  397. if (_error->PendingError() == true)
  398. return false;
  399. pkgTagSection Tags;
  400. if(unlikely(TF.Step(Tags) == false))
  401. return false;
  402. HashStringList ServerHashes;
  403. unsigned long long ServerSize = 0;
  404. for (char const * const * type = HashString::SupportedHashes(); *type != NULL; ++type)
  405. {
  406. std::string tagname = *type;
  407. tagname.append("-Current");
  408. std::string const tmp = Tags.FindS(tagname.c_str());
  409. if (tmp.empty() == true)
  410. continue;
  411. string hash;
  412. unsigned long long size;
  413. std::stringstream ss(tmp);
  414. ss >> hash >> size;
  415. if (unlikely(hash.empty() == true))
  416. continue;
  417. if (unlikely(ServerSize != 0 && ServerSize != size))
  418. continue;
  419. ServerHashes.push_back(HashString(*type, hash));
  420. ServerSize = size;
  421. }
  422. if (ServerHashes.usable() == false)
  423. {
  424. if (Debug == true)
  425. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": Did not find a good hashsum in the index" << std::endl;
  426. return false;
  427. }
  428. if (ServerHashes != HashSums())
  429. {
  430. if (Debug == true)
  431. {
  432. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": Index has different hashes than parser, probably older, so fail pdiffing" << std::endl;
  433. printHashSumComparision(CurrentPackagesFile, ServerHashes, HashSums());
  434. }
  435. return false;
  436. }
  437. if (ServerHashes.VerifyFile(CurrentPackagesFile) == true)
  438. {
  439. // we have the same sha1 as the server so we are done here
  440. if(Debug)
  441. std::clog << "pkgAcqDiffIndex: Package file " << CurrentPackagesFile << " is up-to-date" << std::endl;
  442. // list cleanup needs to know that this file as well as the already
  443. // present index is ours, so we create an empty diff to save it for us
  444. new pkgAcqIndexDiffs(Owner, TransactionManager, Target,
  445. ExpectedHashes, MetaIndexParser);
  446. return true;
  447. }
  448. FileFd fd(CurrentPackagesFile, FileFd::ReadOnly);
  449. Hashes LocalHashesCalc;
  450. LocalHashesCalc.AddFD(fd);
  451. HashStringList const LocalHashes = LocalHashesCalc.GetHashStringList();
  452. if(Debug)
  453. std::clog << "Server-Current: " << ServerHashes.find(NULL)->toStr() << " and we start at "
  454. << fd.Name() << " " << fd.FileSize() << " " << LocalHashes.find(NULL)->toStr() << std::endl;
  455. // parse all of (provided) history
  456. vector<DiffInfo> available_patches;
  457. bool firstAcceptedHashes = true;
  458. for (char const * const * type = HashString::SupportedHashes(); *type != NULL; ++type)
  459. {
  460. if (LocalHashes.find(*type) == NULL)
  461. continue;
  462. std::string tagname = *type;
  463. tagname.append("-History");
  464. std::string const tmp = Tags.FindS(tagname.c_str());
  465. if (tmp.empty() == true)
  466. continue;
  467. string hash, filename;
  468. unsigned long long size;
  469. std::stringstream ss(tmp);
  470. while (ss >> hash >> size >> filename)
  471. {
  472. if (unlikely(hash.empty() == true || filename.empty() == true))
  473. continue;
  474. // see if we have a record for this file already
  475. std::vector<DiffInfo>::iterator cur = available_patches.begin();
  476. for (; cur != available_patches.end(); ++cur)
  477. {
  478. if (cur->file != filename || unlikely(cur->result_size != size))
  479. continue;
  480. cur->result_hashes.push_back(HashString(*type, hash));
  481. break;
  482. }
  483. if (cur != available_patches.end())
  484. continue;
  485. if (firstAcceptedHashes == true)
  486. {
  487. DiffInfo next;
  488. next.file = filename;
  489. next.result_hashes.push_back(HashString(*type, hash));
  490. next.result_size = size;
  491. next.patch_size = 0;
  492. available_patches.push_back(next);
  493. }
  494. else
  495. {
  496. if (Debug == true)
  497. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": File " << filename
  498. << " wasn't in the list for the first parsed hash! (history)" << std::endl;
  499. break;
  500. }
  501. }
  502. firstAcceptedHashes = false;
  503. }
  504. if (unlikely(available_patches.empty() == true))
  505. {
  506. if (Debug)
  507. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": "
  508. << "Couldn't find any patches for the patch series." << std::endl;
  509. return false;
  510. }
  511. for (char const * const * type = HashString::SupportedHashes(); *type != NULL; ++type)
  512. {
  513. if (LocalHashes.find(*type) == NULL)
  514. continue;
  515. std::string tagname = *type;
  516. tagname.append("-Patches");
  517. std::string const tmp = Tags.FindS(tagname.c_str());
  518. if (tmp.empty() == true)
  519. continue;
  520. string hash, filename;
  521. unsigned long long size;
  522. std::stringstream ss(tmp);
  523. while (ss >> hash >> size >> filename)
  524. {
  525. if (unlikely(hash.empty() == true || filename.empty() == true))
  526. continue;
  527. // see if we have a record for this file already
  528. std::vector<DiffInfo>::iterator cur = available_patches.begin();
  529. for (; cur != available_patches.end(); ++cur)
  530. {
  531. if (cur->file != filename)
  532. continue;
  533. if (unlikely(cur->patch_size != 0 && cur->patch_size != size))
  534. continue;
  535. cur->patch_hashes.push_back(HashString(*type, hash));
  536. cur->patch_size = size;
  537. break;
  538. }
  539. if (cur != available_patches.end())
  540. continue;
  541. if (Debug == true)
  542. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": File " << filename
  543. << " wasn't in the list for the first parsed hash! (patches)" << std::endl;
  544. break;
  545. }
  546. }
  547. bool foundStart = false;
  548. for (std::vector<DiffInfo>::iterator cur = available_patches.begin();
  549. cur != available_patches.end(); ++cur)
  550. {
  551. if (LocalHashes != cur->result_hashes)
  552. continue;
  553. available_patches.erase(available_patches.begin(), cur);
  554. foundStart = true;
  555. break;
  556. }
  557. if (foundStart == false || unlikely(available_patches.empty() == true))
  558. {
  559. if (Debug)
  560. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": "
  561. << "Couldn't find the start of the patch series." << std::endl;
  562. return false;
  563. }
  564. // patching with too many files is rather slow compared to a fast download
  565. unsigned long const fileLimit = _config->FindI("Acquire::PDiffs::FileLimit", 0);
  566. if (fileLimit != 0 && fileLimit < available_patches.size())
  567. {
  568. if (Debug)
  569. std::clog << "Need " << available_patches.size() << " diffs (Limit is " << fileLimit
  570. << ") so fallback to complete download" << std::endl;
  571. return false;
  572. }
  573. // calculate the size of all patches we have to get
  574. // note that all sizes are uncompressed, while we download compressed files
  575. unsigned long long patchesSize = 0;
  576. for (std::vector<DiffInfo>::const_iterator cur = available_patches.begin();
  577. cur != available_patches.end(); ++cur)
  578. patchesSize += cur->patch_size;
  579. unsigned long long const sizeLimit = ServerSize * _config->FindI("Acquire::PDiffs::SizeLimit", 100);
  580. if (false && sizeLimit > 0 && (sizeLimit/100) < patchesSize)
  581. {
  582. if (Debug)
  583. std::clog << "Need " << patchesSize << " bytes (Limit is " << sizeLimit/100
  584. << ") so fallback to complete download" << std::endl;
  585. return false;
  586. }
  587. // FIXME: make this use the method
  588. PackagesFileReadyInPartial = true;
  589. std::string const Partial = GetPartialFileNameFromURI(RealURI);
  590. FileFd From(CurrentPackagesFile, FileFd::ReadOnly);
  591. FileFd To(Partial, FileFd::WriteEmpty);
  592. if(CopyFile(From, To) == false)
  593. return _error->Errno("CopyFile", "failed to copy");
  594. if(Debug)
  595. std::cerr << "Done copying " << CurrentPackagesFile
  596. << " -> " << Partial
  597. << std::endl;
  598. // we have something, queue the diffs
  599. string::size_type const last_space = Description.rfind(" ");
  600. if(last_space != string::npos)
  601. Description.erase(last_space, Description.size()-last_space);
  602. /* decide if we should download patches one by one or in one go:
  603. The first is good if the server merges patches, but many don't so client
  604. based merging can be attempt in which case the second is better.
  605. "bad things" will happen if patches are merged on the server,
  606. but client side merging is attempt as well */
  607. bool pdiff_merge = _config->FindB("Acquire::PDiffs::Merge", true);
  608. if (pdiff_merge == true)
  609. {
  610. // reprepro adds this flag if it has merged patches on the server
  611. std::string const precedence = Tags.FindS("X-Patch-Precedence");
  612. pdiff_merge = (precedence != "merged");
  613. }
  614. if (pdiff_merge == false)
  615. {
  616. new pkgAcqIndexDiffs(Owner, TransactionManager, Target, ExpectedHashes,
  617. MetaIndexParser, available_patches);
  618. }
  619. else
  620. {
  621. std::vector<pkgAcqIndexMergeDiffs*> *diffs = new std::vector<pkgAcqIndexMergeDiffs*>(available_patches.size());
  622. for(size_t i = 0; i < available_patches.size(); ++i)
  623. (*diffs)[i] = new pkgAcqIndexMergeDiffs(Owner, TransactionManager,
  624. Target,
  625. ExpectedHashes,
  626. MetaIndexParser,
  627. available_patches[i],
  628. diffs);
  629. }
  630. Complete = false;
  631. Status = StatDone;
  632. Dequeue();
  633. return true;
  634. }
  635. /*}}}*/
  636. void pkgAcqDiffIndex::Failed(string Message,pkgAcquire::MethodConfig * Cnf)/*{{{*/
  637. {
  638. if(Debug)
  639. std::clog << "pkgAcqDiffIndex failed: " << Desc.URI << " with " << Message << std::endl
  640. << "Falling back to normal index file acquire" << std::endl;
  641. new pkgAcqIndex(Owner, TransactionManager, Target, ExpectedHashes, MetaIndexParser);
  642. Item::Failed(Message,Cnf);
  643. Status = StatDone;
  644. }
  645. /*}}}*/
  646. void pkgAcqDiffIndex::Done(string Message,unsigned long long Size,HashStringList const &Hashes, /*{{{*/
  647. pkgAcquire::MethodConfig *Cnf)
  648. {
  649. if(Debug)
  650. std::clog << "pkgAcqDiffIndex::Done(): " << Desc.URI << std::endl;
  651. Item::Done(Message, Size, Hashes, Cnf);
  652. // verify the index target
  653. if(Target && Target->MetaKey != "" && MetaIndexParser && Hashes.usable())
  654. {
  655. std::string IndexMetaKey = Target->MetaKey + ".diff/Index";
  656. indexRecords::checkSum *Record = MetaIndexParser->Lookup(IndexMetaKey);
  657. if(Record && Record->Hashes.usable() && Hashes != Record->Hashes)
  658. {
  659. RenameOnError(HashSumMismatch);
  660. printHashSumComparision(RealURI, Record->Hashes, Hashes);
  661. Failed(Message, Cnf);
  662. return;
  663. }
  664. }
  665. string FinalFile;
  666. FinalFile = _config->FindDir("Dir::State::lists");
  667. FinalFile += URItoFileName(Desc.URI);
  668. if(StringToBool(LookupTag(Message,"IMS-Hit"),false))
  669. DestFile = FinalFile;
  670. if(!ParseDiffIndex(DestFile))
  671. return Failed("Message: Couldn't parse pdiff index", Cnf);
  672. // queue for final move
  673. TransactionManager->TransactionStageCopy(this, DestFile, FinalFile);
  674. Complete = true;
  675. Status = StatDone;
  676. Dequeue();
  677. return;
  678. }
  679. /*}}}*/
  680. // AcqIndexDiffs::AcqIndexDiffs - Constructor /*{{{*/
  681. // ---------------------------------------------------------------------
  682. /* The package diff is added to the queue. one object is constructed
  683. * for each diff and the index
  684. */
  685. pkgAcqIndexDiffs::pkgAcqIndexDiffs(pkgAcquire *Owner,
  686. pkgAcqMetaBase *TransactionManager,
  687. struct IndexTarget const * const Target,
  688. HashStringList const &ExpectedHashes,
  689. indexRecords *MetaIndexParser,
  690. vector<DiffInfo> diffs)
  691. : pkgAcqBaseIndex(Owner, TransactionManager, Target, ExpectedHashes, MetaIndexParser),
  692. available_patches(diffs)
  693. {
  694. DestFile = GetPartialFileNameFromURI(Target->URI);
  695. Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
  696. RealURI = Target->URI;
  697. Desc.Owner = this;
  698. Description = Target->Description;
  699. Desc.ShortDesc = Target->ShortDesc;
  700. if(available_patches.empty() == true)
  701. {
  702. // we are done (yeah!), check hashes against the final file
  703. DestFile = _config->FindDir("Dir::State::lists");
  704. DestFile += URItoFileName(Target->URI);
  705. Finish(true);
  706. }
  707. else
  708. {
  709. // get the next diff
  710. State = StateFetchDiff;
  711. QueueNextDiff();
  712. }
  713. }
  714. /*}}}*/
  715. void pkgAcqIndexDiffs::Failed(string Message,pkgAcquire::MethodConfig * /*Cnf*/)/*{{{*/
  716. {
  717. if(Debug)
  718. std::clog << "pkgAcqIndexDiffs failed: " << Desc.URI << " with " << Message << std::endl
  719. << "Falling back to normal index file acquire" << std::endl;
  720. new pkgAcqIndex(Owner, TransactionManager, Target, ExpectedHashes, MetaIndexParser);
  721. Finish();
  722. }
  723. /*}}}*/
  724. // Finish - helper that cleans the item out of the fetcher queue /*{{{*/
  725. void pkgAcqIndexDiffs::Finish(bool allDone)
  726. {
  727. if(Debug)
  728. std::clog << "pkgAcqIndexDiffs::Finish(): "
  729. << allDone << " "
  730. << Desc.URI << std::endl;
  731. // we restore the original name, this is required, otherwise
  732. // the file will be cleaned
  733. if(allDone)
  734. {
  735. if(HashSums().usable() && !HashSums().VerifyFile(DestFile))
  736. {
  737. RenameOnError(HashSumMismatch);
  738. Dequeue();
  739. return;
  740. }
  741. // queue for copy
  742. std::string FinalFile = _config->FindDir("Dir::State::lists");
  743. FinalFile += URItoFileName(RealURI);
  744. TransactionManager->TransactionStageCopy(this, DestFile, FinalFile);
  745. // this is for the "real" finish
  746. Complete = true;
  747. Status = StatDone;
  748. Dequeue();
  749. if(Debug)
  750. std::clog << "\n\nallDone: " << DestFile << "\n" << std::endl;
  751. return;
  752. }
  753. if(Debug)
  754. std::clog << "Finishing: " << Desc.URI << std::endl;
  755. Complete = false;
  756. Status = StatDone;
  757. Dequeue();
  758. return;
  759. }
  760. /*}}}*/
  761. bool pkgAcqIndexDiffs::QueueNextDiff() /*{{{*/
  762. {
  763. // calc sha1 of the just patched file
  764. std::string const FinalFile = GetPartialFileNameFromURI(RealURI);
  765. if(!FileExists(FinalFile))
  766. {
  767. Failed("Message: No FinalFile " + FinalFile + " available", NULL);
  768. return false;
  769. }
  770. FileFd fd(FinalFile, FileFd::ReadOnly);
  771. Hashes LocalHashesCalc;
  772. LocalHashesCalc.AddFD(fd);
  773. HashStringList const LocalHashes = LocalHashesCalc.GetHashStringList();
  774. if(Debug)
  775. std::clog << "QueueNextDiff: " << FinalFile << " (" << LocalHashes.find(NULL)->toStr() << ")" << std::endl;
  776. if (unlikely(LocalHashes.usable() == false || ExpectedHashes.usable() == false))
  777. {
  778. Failed("Local/Expected hashes are not usable", NULL);
  779. return false;
  780. }
  781. // final file reached before all patches are applied
  782. if(LocalHashes == ExpectedHashes)
  783. {
  784. Finish(true);
  785. return true;
  786. }
  787. // remove all patches until the next matching patch is found
  788. // this requires the Index file to be ordered
  789. for(vector<DiffInfo>::iterator I = available_patches.begin();
  790. available_patches.empty() == false &&
  791. I != available_patches.end() &&
  792. I->result_hashes != LocalHashes;
  793. ++I)
  794. {
  795. available_patches.erase(I);
  796. }
  797. // error checking and falling back if no patch was found
  798. if(available_patches.empty() == true)
  799. {
  800. Failed("No patches left to reach target", NULL);
  801. return false;
  802. }
  803. // queue the right diff
  804. Desc.URI = RealURI + ".diff/" + available_patches[0].file + ".gz";
  805. Desc.Description = Description + " " + available_patches[0].file + string(".pdiff");
  806. DestFile = GetPartialFileNameFromURI(RealURI + ".diff/" + available_patches[0].file);
  807. if(Debug)
  808. std::clog << "pkgAcqIndexDiffs::QueueNextDiff(): " << Desc.URI << std::endl;
  809. QueueURI(Desc);
  810. return true;
  811. }
  812. /*}}}*/
  813. void pkgAcqIndexDiffs::Done(string Message,unsigned long long Size, HashStringList const &Hashes, /*{{{*/
  814. pkgAcquire::MethodConfig *Cnf)
  815. {
  816. if(Debug)
  817. std::clog << "pkgAcqIndexDiffs::Done(): " << Desc.URI << std::endl;
  818. Item::Done(Message, Size, Hashes, Cnf);
  819. // FIXME: verify this download too before feeding it to rred
  820. std::string const FinalFile = GetPartialFileNameFromURI(RealURI);
  821. // success in downloading a diff, enter ApplyDiff state
  822. if(State == StateFetchDiff)
  823. {
  824. FileFd fd(DestFile, FileFd::ReadOnly, FileFd::Gzip);
  825. class Hashes LocalHashesCalc;
  826. LocalHashesCalc.AddFD(fd);
  827. HashStringList const LocalHashes = LocalHashesCalc.GetHashStringList();
  828. if (fd.Size() != available_patches[0].patch_size ||
  829. available_patches[0].patch_hashes != LocalHashes)
  830. {
  831. Failed("Patch has Size/Hashsum mismatch", NULL);
  832. return;
  833. }
  834. // rred excepts the patch as $FinalFile.ed
  835. Rename(DestFile,FinalFile+".ed");
  836. if(Debug)
  837. std::clog << "Sending to rred method: " << FinalFile << std::endl;
  838. State = StateApplyDiff;
  839. Local = true;
  840. Desc.URI = "rred:" + FinalFile;
  841. QueueURI(Desc);
  842. SetActiveSubprocess("rred");
  843. return;
  844. }
  845. // success in download/apply a diff, queue next (if needed)
  846. if(State == StateApplyDiff)
  847. {
  848. // remove the just applied patch
  849. available_patches.erase(available_patches.begin());
  850. unlink((FinalFile + ".ed").c_str());
  851. // move into place
  852. if(Debug)
  853. {
  854. std::clog << "Moving patched file in place: " << std::endl
  855. << DestFile << " -> " << FinalFile << std::endl;
  856. }
  857. Rename(DestFile,FinalFile);
  858. chmod(FinalFile.c_str(),0644);
  859. // see if there is more to download
  860. if(available_patches.empty() == false) {
  861. new pkgAcqIndexDiffs(Owner, TransactionManager, Target,
  862. ExpectedHashes, MetaIndexParser,
  863. available_patches);
  864. return Finish();
  865. } else
  866. // update
  867. DestFile = FinalFile;
  868. return Finish(true);
  869. }
  870. }
  871. /*}}}*/
  872. // AcqIndexMergeDiffs::AcqIndexMergeDiffs - Constructor /*{{{*/
  873. pkgAcqIndexMergeDiffs::pkgAcqIndexMergeDiffs(pkgAcquire *Owner,
  874. pkgAcqMetaBase *TransactionManager,
  875. struct IndexTarget const * const Target,
  876. HashStringList const &ExpectedHashes,
  877. indexRecords *MetaIndexParser,
  878. DiffInfo const &patch,
  879. std::vector<pkgAcqIndexMergeDiffs*> const * const allPatches)
  880. : pkgAcqBaseIndex(Owner, TransactionManager, Target, ExpectedHashes, MetaIndexParser),
  881. patch(patch), allPatches(allPatches), State(StateFetchDiff)
  882. {
  883. Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
  884. RealURI = Target->URI;
  885. Desc.Owner = this;
  886. Description = Target->Description;
  887. Desc.ShortDesc = Target->ShortDesc;
  888. Desc.URI = RealURI + ".diff/" + patch.file + ".gz";
  889. Desc.Description = Description + " " + patch.file + string(".pdiff");
  890. DestFile = GetPartialFileNameFromURI(RealURI + ".diff/" + patch.file);
  891. if(Debug)
  892. std::clog << "pkgAcqIndexMergeDiffs: " << Desc.URI << std::endl;
  893. QueueURI(Desc);
  894. }
  895. /*}}}*/
  896. void pkgAcqIndexMergeDiffs::Failed(string Message,pkgAcquire::MethodConfig * Cnf)/*{{{*/
  897. {
  898. if(Debug)
  899. std::clog << "pkgAcqIndexMergeDiffs failed: " << Desc.URI << " with " << Message << std::endl;
  900. Item::Failed(Message,Cnf);
  901. Status = StatDone;
  902. // check if we are the first to fail, otherwise we are done here
  903. State = StateDoneDiff;
  904. for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
  905. I != allPatches->end(); ++I)
  906. if ((*I)->State == StateErrorDiff)
  907. return;
  908. // first failure means we should fallback
  909. State = StateErrorDiff;
  910. std::clog << "Falling back to normal index file acquire" << std::endl;
  911. new pkgAcqIndex(Owner, TransactionManager, Target, ExpectedHashes, MetaIndexParser);
  912. }
  913. /*}}}*/
  914. void pkgAcqIndexMergeDiffs::Done(string Message,unsigned long long Size,HashStringList const &Hashes, /*{{{*/
  915. pkgAcquire::MethodConfig *Cnf)
  916. {
  917. if(Debug)
  918. std::clog << "pkgAcqIndexMergeDiffs::Done(): " << Desc.URI << std::endl;
  919. Item::Done(Message,Size,Hashes,Cnf);
  920. // FIXME: verify download before feeding it to rred
  921. string const FinalFile = GetPartialFileNameFromURI(RealURI);
  922. if (State == StateFetchDiff)
  923. {
  924. FileFd fd(DestFile, FileFd::ReadOnly, FileFd::Gzip);
  925. class Hashes LocalHashesCalc;
  926. LocalHashesCalc.AddFD(fd);
  927. HashStringList const LocalHashes = LocalHashesCalc.GetHashStringList();
  928. if (fd.Size() != patch.patch_size || patch.patch_hashes != LocalHashes)
  929. {
  930. Failed("Patch has Size/Hashsum mismatch", NULL);
  931. return;
  932. }
  933. // rred expects the patch as $FinalFile.ed.$patchname.gz
  934. Rename(DestFile, FinalFile + ".ed." + patch.file + ".gz");
  935. // check if this is the last completed diff
  936. State = StateDoneDiff;
  937. for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
  938. I != allPatches->end(); ++I)
  939. if ((*I)->State != StateDoneDiff)
  940. {
  941. if(Debug)
  942. std::clog << "Not the last done diff in the batch: " << Desc.URI << std::endl;
  943. return;
  944. }
  945. // this is the last completed diff, so we are ready to apply now
  946. State = StateApplyDiff;
  947. if(Debug)
  948. std::clog << "Sending to rred method: " << FinalFile << std::endl;
  949. Local = true;
  950. Desc.URI = "rred:" + FinalFile;
  951. QueueURI(Desc);
  952. SetActiveSubprocess("rred");
  953. return;
  954. }
  955. // success in download/apply all diffs, clean up
  956. else if (State == StateApplyDiff)
  957. {
  958. // see if we really got the expected file
  959. if(ExpectedHashes.usable() && !ExpectedHashes.VerifyFile(DestFile))
  960. {
  961. RenameOnError(HashSumMismatch);
  962. return;
  963. }
  964. std::string FinalFile = _config->FindDir("Dir::State::lists");
  965. FinalFile += URItoFileName(RealURI);
  966. // move the result into place
  967. if(Debug)
  968. std::clog << "Queue patched file in place: " << std::endl
  969. << DestFile << " -> " << FinalFile << std::endl;
  970. // queue for copy by the transaction manager
  971. TransactionManager->TransactionStageCopy(this, DestFile, FinalFile);
  972. // ensure the ed's are gone regardless of list-cleanup
  973. for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
  974. I != allPatches->end(); ++I)
  975. {
  976. std::string const PartialFile = GetPartialFileNameFromURI(RealURI);
  977. std::string patch = PartialFile + ".ed." + (*I)->patch.file + ".gz";
  978. unlink(patch.c_str());
  979. }
  980. // all set and done
  981. Complete = true;
  982. if(Debug)
  983. std::clog << "allDone: " << DestFile << "\n" << std::endl;
  984. }
  985. }
  986. /*}}}*/
  987. // AcqBaseIndex::VerifyHashByMetaKey - verify hash for the given metakey /*{{{*/
  988. bool pkgAcqBaseIndex::VerifyHashByMetaKey(HashStringList const &Hashes)
  989. {
  990. if(MetaKey != "" && Hashes.usable())
  991. {
  992. indexRecords::checkSum *Record = MetaIndexParser->Lookup(MetaKey);
  993. if(Record && Record->Hashes.usable() && Hashes != Record->Hashes)
  994. {
  995. printHashSumComparision(RealURI, Record->Hashes, Hashes);
  996. return false;
  997. }
  998. }
  999. return true;
  1000. }
  1001. /*}}}*/
  1002. // AcqIndex::AcqIndex - Constructor /*{{{*/
  1003. // ---------------------------------------------------------------------
  1004. /* The package file is added to the queue and a second class is
  1005. instantiated to fetch the revision file */
  1006. pkgAcqIndex::pkgAcqIndex(pkgAcquire *Owner,
  1007. string URI,string URIDesc,string ShortDesc,
  1008. HashStringList const &ExpectedHash)
  1009. : pkgAcqBaseIndex(Owner, 0, NULL, ExpectedHash, NULL)
  1010. {
  1011. RealURI = URI;
  1012. AutoSelectCompression();
  1013. Init(URI, URIDesc, ShortDesc);
  1014. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1015. std::clog << "New pkgIndex with TransactionManager "
  1016. << TransactionManager << std::endl;
  1017. }
  1018. /*}}}*/
  1019. // AcqIndex::AcqIndex - Constructor /*{{{*/
  1020. pkgAcqIndex::pkgAcqIndex(pkgAcquire *Owner,
  1021. pkgAcqMetaBase *TransactionManager,
  1022. IndexTarget const *Target,
  1023. HashStringList const &ExpectedHash,
  1024. indexRecords *MetaIndexParser)
  1025. : pkgAcqBaseIndex(Owner, TransactionManager, Target, ExpectedHash,
  1026. MetaIndexParser)
  1027. {
  1028. RealURI = Target->URI;
  1029. // autoselect the compression method
  1030. AutoSelectCompression();
  1031. Init(Target->URI, Target->Description, Target->ShortDesc);
  1032. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1033. std::clog << "New pkgIndex with TransactionManager "
  1034. << TransactionManager << std::endl;
  1035. }
  1036. /*}}}*/
  1037. // AcqIndex::AutoSelectCompression - Select compression /*{{{*/
  1038. void pkgAcqIndex::AutoSelectCompression()
  1039. {
  1040. std::vector<std::string> types = APT::Configuration::getCompressionTypes();
  1041. CompressionExtensions = "";
  1042. if (ExpectedHashes.usable())
  1043. {
  1044. for (std::vector<std::string>::const_iterator t = types.begin();
  1045. t != types.end(); ++t)
  1046. {
  1047. std::string CompressedMetaKey = string(Target->MetaKey).append(".").append(*t);
  1048. if (*t == "uncompressed" ||
  1049. MetaIndexParser->Exists(CompressedMetaKey) == true)
  1050. CompressionExtensions.append(*t).append(" ");
  1051. }
  1052. }
  1053. else
  1054. {
  1055. for (std::vector<std::string>::const_iterator t = types.begin(); t != types.end(); ++t)
  1056. CompressionExtensions.append(*t).append(" ");
  1057. }
  1058. if (CompressionExtensions.empty() == false)
  1059. CompressionExtensions.erase(CompressionExtensions.end()-1);
  1060. }
  1061. /*}}}*/
  1062. // AcqIndex::Init - defered Constructor /*{{{*/
  1063. void pkgAcqIndex::Init(string const &URI, string const &URIDesc,
  1064. string const &ShortDesc)
  1065. {
  1066. Stage = STAGE_DOWNLOAD;
  1067. DestFile = GetPartialFileNameFromURI(URI);
  1068. CurrentCompressionExtension = CompressionExtensions.substr(0, CompressionExtensions.find(' '));
  1069. if (CurrentCompressionExtension == "uncompressed")
  1070. {
  1071. Desc.URI = URI;
  1072. if(Target)
  1073. MetaKey = string(Target->MetaKey);
  1074. }
  1075. else
  1076. {
  1077. Desc.URI = URI + '.' + CurrentCompressionExtension;
  1078. DestFile = DestFile + '.' + CurrentCompressionExtension;
  1079. if(Target)
  1080. MetaKey = string(Target->MetaKey) + '.' + CurrentCompressionExtension;
  1081. }
  1082. // load the filesize
  1083. if(MetaIndexParser)
  1084. {
  1085. indexRecords::checkSum *Record = MetaIndexParser->Lookup(MetaKey);
  1086. if(Record)
  1087. FileSize = Record->Size;
  1088. InitByHashIfNeeded(MetaKey);
  1089. }
  1090. Desc.Description = URIDesc;
  1091. Desc.Owner = this;
  1092. Desc.ShortDesc = ShortDesc;
  1093. QueueURI(Desc);
  1094. }
  1095. /*}}}*/
  1096. // AcqIndex::AdjustForByHash - modify URI for by-hash support /*{{{*/
  1097. void pkgAcqIndex::InitByHashIfNeeded(const std::string MetaKey)
  1098. {
  1099. // TODO:
  1100. // - (maybe?) add support for by-hash into the sources.list as flag
  1101. // - make apt-ftparchive generate the hashes (and expire?)
  1102. std::string HostKnob = "APT::Acquire::" + ::URI(Desc.URI).Host + "::By-Hash";
  1103. if(_config->FindB("APT::Acquire::By-Hash", false) == true ||
  1104. _config->FindB(HostKnob, false) == true ||
  1105. MetaIndexParser->GetSupportsAcquireByHash())
  1106. {
  1107. indexRecords::checkSum *Record = MetaIndexParser->Lookup(MetaKey);
  1108. if(Record)
  1109. {
  1110. // FIXME: should we really use the best hash here? or a fixed one?
  1111. const HashString *TargetHash = Record->Hashes.find("");
  1112. std::string ByHash = "/by-hash/" + TargetHash->HashType() + "/" + TargetHash->HashValue();
  1113. size_t trailing_slash = Desc.URI.find_last_of("/");
  1114. Desc.URI = Desc.URI.replace(
  1115. trailing_slash,
  1116. Desc.URI.substr(trailing_slash+1).size()+1,
  1117. ByHash);
  1118. } else {
  1119. _error->Warning(
  1120. "Fetching ByHash requested but can not find record for %s",
  1121. MetaKey.c_str());
  1122. }
  1123. }
  1124. }
  1125. /*}}}*/
  1126. // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
  1127. // ---------------------------------------------------------------------
  1128. /* The only header we use is the last-modified header. */
  1129. string pkgAcqIndex::Custom600Headers() const
  1130. {
  1131. string Final = GetFinalFilename();
  1132. string msg = "\nIndex-File: true";
  1133. struct stat Buf;
  1134. if (stat(Final.c_str(),&Buf) == 0)
  1135. msg += "\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  1136. return msg;
  1137. }
  1138. /*}}}*/
  1139. // pkgAcqIndex::Failed - getting the indexfile failed /*{{{*/
  1140. void pkgAcqIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  1141. {
  1142. size_t const nextExt = CompressionExtensions.find(' ');
  1143. if (nextExt != std::string::npos)
  1144. {
  1145. CompressionExtensions = CompressionExtensions.substr(nextExt+1);
  1146. Init(RealURI, Desc.Description, Desc.ShortDesc);
  1147. return;
  1148. }
  1149. // on decompression failure, remove bad versions in partial/
  1150. if (Stage == STAGE_DECOMPRESS_AND_VERIFY)
  1151. {
  1152. unlink(EraseFileName.c_str());
  1153. }
  1154. Item::Failed(Message,Cnf);
  1155. /// cancel the entire transaction
  1156. TransactionManager->AbortTransaction();
  1157. }
  1158. /*}}}*/
  1159. // pkgAcqIndex::GetFinalFilename - Return the full final file path /*{{{*/
  1160. std::string pkgAcqIndex::GetFinalFilename() const
  1161. {
  1162. std::string FinalFile = _config->FindDir("Dir::State::lists");
  1163. FinalFile += URItoFileName(RealURI);
  1164. return GetCompressedFileName(RealURI, FinalFile, CurrentCompressionExtension);
  1165. }
  1166. /*}}}*/
  1167. // AcqIndex::ReverifyAfterIMS - Reverify index after an ims-hit /*{{{*/
  1168. void pkgAcqIndex::ReverifyAfterIMS()
  1169. {
  1170. // update destfile to *not* include the compression extension when doing
  1171. // a reverify (as its uncompressed on disk already)
  1172. DestFile = GetCompressedFileName(RealURI, GetPartialFileNameFromURI(RealURI), CurrentCompressionExtension);
  1173. // copy FinalFile into partial/ so that we check the hash again
  1174. string FinalFile = GetFinalFilename();
  1175. Stage = STAGE_DECOMPRESS_AND_VERIFY;
  1176. Desc.URI = "copy:" + FinalFile;
  1177. QueueURI(Desc);
  1178. }
  1179. /*}}}*/
  1180. // AcqIndex::ValidateFile - Validate the content of the downloaded file /*{{{*/
  1181. bool pkgAcqIndex::ValidateFile(const std::string &FileName)
  1182. {
  1183. // FIXME: this can go away once we only ever download stuff that
  1184. // has a valid hash and we never do GET based probing
  1185. // FIXME2: this also leaks debian-isms into the code and should go therefore
  1186. /* Always validate the index file for correctness (all indexes must
  1187. * have a Package field) (LP: #346386) (Closes: #627642)
  1188. */
  1189. FileFd fd(FileName, FileFd::ReadOnly, FileFd::Extension);
  1190. // Only test for correctness if the content of the file is not empty
  1191. // (empty is ok)
  1192. if (fd.Size() > 0)
  1193. {
  1194. pkgTagSection sec;
  1195. pkgTagFile tag(&fd);
  1196. // all our current indexes have a field 'Package' in each section
  1197. if (_error->PendingError() == true ||
  1198. tag.Step(sec) == false ||
  1199. sec.Exists("Package") == false)
  1200. return false;
  1201. }
  1202. return true;
  1203. }
  1204. /*}}}*/
  1205. // AcqIndex::Done - Finished a fetch /*{{{*/
  1206. // ---------------------------------------------------------------------
  1207. /* This goes through a number of states.. On the initial fetch the
  1208. method could possibly return an alternate filename which points
  1209. to the uncompressed version of the file. If this is so the file
  1210. is copied into the partial directory. In all other cases the file
  1211. is decompressed with a compressed uri. */
  1212. void pkgAcqIndex::Done(string Message,
  1213. unsigned long long Size,
  1214. HashStringList const &Hashes,
  1215. pkgAcquire::MethodConfig *Cfg)
  1216. {
  1217. Item::Done(Message,Size,Hashes,Cfg);
  1218. switch(Stage)
  1219. {
  1220. case STAGE_DOWNLOAD:
  1221. StageDownloadDone(Message, Hashes, Cfg);
  1222. break;
  1223. case STAGE_DECOMPRESS_AND_VERIFY:
  1224. StageDecompressDone(Message, Hashes, Cfg);
  1225. break;
  1226. }
  1227. }
  1228. /*}}}*/
  1229. // AcqIndex::StageDownloadDone - Queue for decompress and verify /*{{{*/
  1230. void pkgAcqIndex::StageDownloadDone(string Message,
  1231. HashStringList const &Hashes,
  1232. pkgAcquire::MethodConfig *Cfg)
  1233. {
  1234. // First check if the calculcated Hash of the (compressed) downloaded
  1235. // file matches the hash we have in the MetaIndexRecords for this file
  1236. if(VerifyHashByMetaKey(Hashes) == false)
  1237. {
  1238. RenameOnError(HashSumMismatch);
  1239. Failed(Message, Cfg);
  1240. return;
  1241. }
  1242. Complete = true;
  1243. // Handle the unzipd case
  1244. string FileName = LookupTag(Message,"Alt-Filename");
  1245. if (FileName.empty() == false)
  1246. {
  1247. Stage = STAGE_DECOMPRESS_AND_VERIFY;
  1248. Local = true;
  1249. DestFile += ".decomp";
  1250. Desc.URI = "copy:" + FileName;
  1251. QueueURI(Desc);
  1252. SetActiveSubprocess("copy");
  1253. return;
  1254. }
  1255. FileName = LookupTag(Message,"Filename");
  1256. if (FileName.empty() == true)
  1257. {
  1258. Status = StatError;
  1259. ErrorText = "Method gave a blank filename";
  1260. }
  1261. // Methods like e.g. "file:" will give us a (compressed) FileName that is
  1262. // not the "DestFile" we set, in this case we uncompress from the local file
  1263. if (FileName != DestFile)
  1264. Local = true;
  1265. else
  1266. EraseFileName = FileName;
  1267. // we need to verify the file against the current Release file again
  1268. // on if-modfied-since hit to avoid a stale attack against us
  1269. if(StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  1270. {
  1271. // The files timestamp matches, reverify by copy into partial/
  1272. EraseFileName = "";
  1273. ReverifyAfterIMS();
  1274. return;
  1275. }
  1276. // If we have compressed indexes enabled, queue for hash verification
  1277. if (_config->FindB("Acquire::GzipIndexes",false))
  1278. {
  1279. DestFile = GetPartialFileNameFromURI(RealURI + '.' + CurrentCompressionExtension);
  1280. EraseFileName = "";
  1281. Stage = STAGE_DECOMPRESS_AND_VERIFY;
  1282. Desc.URI = "copy:" + FileName;
  1283. QueueURI(Desc);
  1284. SetActiveSubprocess("copy");
  1285. return;
  1286. }
  1287. // get the binary name for your used compression type
  1288. string decompProg;
  1289. if(CurrentCompressionExtension == "uncompressed")
  1290. decompProg = "copy";
  1291. else
  1292. decompProg = _config->Find(string("Acquire::CompressionTypes::").append(CurrentCompressionExtension),"");
  1293. if(decompProg.empty() == true)
  1294. {
  1295. _error->Error("Unsupported extension: %s", CurrentCompressionExtension.c_str());
  1296. return;
  1297. }
  1298. // queue uri for the next stage
  1299. Stage = STAGE_DECOMPRESS_AND_VERIFY;
  1300. DestFile += ".decomp";
  1301. Desc.URI = decompProg + ":" + FileName;
  1302. QueueURI(Desc);
  1303. SetActiveSubprocess(decompProg);
  1304. }
  1305. /*}}}*/
  1306. // pkgAcqIndex::StageDecompressDone - Final verification /*{{{*/
  1307. void pkgAcqIndex::StageDecompressDone(string Message,
  1308. HashStringList const &Hashes,
  1309. pkgAcquire::MethodConfig *Cfg)
  1310. {
  1311. if (ExpectedHashes.usable() && ExpectedHashes != Hashes)
  1312. {
  1313. Desc.URI = RealURI;
  1314. RenameOnError(HashSumMismatch);
  1315. printHashSumComparision(RealURI, ExpectedHashes, Hashes);
  1316. Failed(Message, Cfg);
  1317. return;
  1318. }
  1319. if(!ValidateFile(DestFile))
  1320. {
  1321. RenameOnError(InvalidFormat);
  1322. Failed(Message, Cfg);
  1323. return;
  1324. }
  1325. // remove the compressed version of the file
  1326. unlink(EraseFileName.c_str());
  1327. // Done, queue for rename on transaction finished
  1328. TransactionManager->TransactionStageCopy(this, DestFile, GetFinalFilename());
  1329. return;
  1330. }
  1331. /*}}}*/
  1332. // AcqIndexTrans::pkgAcqIndexTrans - Constructor /*{{{*/
  1333. // ---------------------------------------------------------------------
  1334. /* The Translation file is added to the queue */
  1335. pkgAcqIndexTrans::pkgAcqIndexTrans(pkgAcquire *Owner,
  1336. string URI,string URIDesc,string ShortDesc)
  1337. : pkgAcqIndex(Owner, URI, URIDesc, ShortDesc, HashStringList())
  1338. {
  1339. }
  1340. pkgAcqIndexTrans::pkgAcqIndexTrans(pkgAcquire *Owner,
  1341. pkgAcqMetaBase *TransactionManager,
  1342. IndexTarget const * const Target,
  1343. HashStringList const &ExpectedHashes,
  1344. indexRecords *MetaIndexParser)
  1345. : pkgAcqIndex(Owner, TransactionManager, Target, ExpectedHashes, MetaIndexParser)
  1346. {
  1347. }
  1348. /*}}}*/
  1349. // AcqIndexTrans::Custom600Headers - Insert custom request headers /*{{{*/
  1350. string pkgAcqIndexTrans::Custom600Headers() const
  1351. {
  1352. string Final = GetFinalFilename();
  1353. struct stat Buf;
  1354. if (stat(Final.c_str(),&Buf) != 0)
  1355. return "\nFail-Ignore: true\nIndex-File: true";
  1356. return "\nFail-Ignore: true\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  1357. }
  1358. /*}}}*/
  1359. // AcqIndexTrans::Failed - Silence failure messages for missing files /*{{{*/
  1360. void pkgAcqIndexTrans::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  1361. {
  1362. size_t const nextExt = CompressionExtensions.find(' ');
  1363. if (nextExt != std::string::npos)
  1364. {
  1365. CompressionExtensions = CompressionExtensions.substr(nextExt+1);
  1366. Init(RealURI, Desc.Description, Desc.ShortDesc);
  1367. Status = StatIdle;
  1368. return;
  1369. }
  1370. Item::Failed(Message,Cnf);
  1371. // FIXME: this is used often (e.g. in pkgAcqIndexTrans) so refactor
  1372. if (Cnf->LocalOnly == true ||
  1373. StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
  1374. {
  1375. // Ignore this
  1376. Status = StatDone;
  1377. }
  1378. }
  1379. /*}}}*/
  1380. // AcqMetaBase::Add - Add a item to the current Transaction /*{{{*/
  1381. void pkgAcqMetaBase::Add(Item *I)
  1382. {
  1383. Transaction.push_back(I);
  1384. }
  1385. /*}}}*/
  1386. // AcqMetaBase::AbortTransaction - Abort the current Transaction /*{{{*/
  1387. void pkgAcqMetaBase::AbortTransaction()
  1388. {
  1389. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1390. std::clog << "AbortTransaction: " << TransactionManager << std::endl;
  1391. // ensure the toplevel is in error state too
  1392. for (std::vector<Item*>::iterator I = Transaction.begin();
  1393. I != Transaction.end(); ++I)
  1394. {
  1395. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1396. std::clog << " Cancel: " << (*I)->DestFile << std::endl;
  1397. // the transaction will abort, so stop anything that is idle
  1398. if ((*I)->Status == pkgAcquire::Item::StatIdle)
  1399. (*I)->Status = pkgAcquire::Item::StatDone;
  1400. // kill failed files in partial
  1401. if ((*I)->Status == pkgAcquire::Item::StatError)
  1402. {
  1403. std::string const PartialFile = GetPartialFileName(flNotDir((*I)->DestFile));
  1404. if(FileExists(PartialFile))
  1405. Rename(PartialFile, PartialFile + ".FAILED");
  1406. }
  1407. // fix permissions for existing files which were part of a reverify
  1408. // like InRelease files or files in partial we might work with next time
  1409. else if (FileExists((*I)->DestFile))
  1410. ChangeOwnerAndPermissionOfFile("AbortTransaction", (*I)->DestFile.c_str(), "root", "root", 0644);
  1411. }
  1412. Transaction.clear();
  1413. }
  1414. /*}}}*/
  1415. // AcqMetaBase::TransactionHasError - Check for errors in Transaction /*{{{*/
  1416. bool pkgAcqMetaBase::TransactionHasError()
  1417. {
  1418. for (pkgAcquire::ItemIterator I = Transaction.begin();
  1419. I != Transaction.end(); ++I)
  1420. if((*I)->Status != pkgAcquire::Item::StatDone &&
  1421. (*I)->Status != pkgAcquire::Item::StatIdle)
  1422. return true;
  1423. return false;
  1424. }
  1425. /*}}}*/
  1426. // AcqMetaBase::CommitTransaction - Commit a transaction /*{{{*/
  1427. void pkgAcqMetaBase::CommitTransaction()
  1428. {
  1429. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1430. std::clog << "CommitTransaction: " << this << std::endl;
  1431. // move new files into place *and* remove files that are not
  1432. // part of the transaction but are still on disk
  1433. for (std::vector<Item*>::iterator I = Transaction.begin();
  1434. I != Transaction.end(); ++I)
  1435. {
  1436. if((*I)->PartialFile != "")
  1437. {
  1438. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1439. std::clog << "mv " << (*I)->PartialFile << " -> "<< (*I)->DestFile << " "
  1440. << (*I)->DescURI() << std::endl;
  1441. Rename((*I)->PartialFile, (*I)->DestFile);
  1442. ChangeOwnerAndPermissionOfFile("CommitTransaction", (*I)->DestFile.c_str(), "root", "root", 0644);
  1443. } else {
  1444. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1445. std::clog << "rm "
  1446. << (*I)->DestFile
  1447. << " "
  1448. << (*I)->DescURI()
  1449. << std::endl;
  1450. unlink((*I)->DestFile.c_str());
  1451. }
  1452. // mark that this transaction is finished
  1453. (*I)->TransactionManager = 0;
  1454. }
  1455. Transaction.clear();
  1456. }
  1457. /*}}}*/
  1458. // AcqMetaBase::TransactionStageCopy - Stage a file for copying /*{{{*/
  1459. void pkgAcqMetaBase::TransactionStageCopy(Item *I,
  1460. const std::string &From,
  1461. const std::string &To)
  1462. {
  1463. I->PartialFile = From;
  1464. I->DestFile = To;
  1465. }
  1466. /*}}}*/
  1467. // AcqMetaBase::TransactionStageRemoval - Sage a file for removal /*{{{*/
  1468. void pkgAcqMetaBase::TransactionStageRemoval(Item *I,
  1469. const std::string &FinalFile)
  1470. {
  1471. I->PartialFile = "";
  1472. I->DestFile = FinalFile;
  1473. }
  1474. /*}}}*/
  1475. // AcqMetaBase::GenerateAuthWarning - Check gpg authentication error /*{{{*/
  1476. bool pkgAcqMetaBase::CheckStopAuthentication(const std::string &RealURI,
  1477. const std::string &Message)
  1478. {
  1479. // FIXME: this entire function can do now that we disallow going to
  1480. // a unauthenticated state and can cleanly rollback
  1481. string Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
  1482. if(FileExists(Final))
  1483. {
  1484. Status = StatTransientNetworkError;
  1485. _error->Warning(_("An error occurred during the signature "
  1486. "verification. The repository is not updated "
  1487. "and the previous index files will be used. "
  1488. "GPG error: %s: %s\n"),
  1489. Desc.Description.c_str(),
  1490. LookupTag(Message,"Message").c_str());
  1491. RunScripts("APT::Update::Auth-Failure");
  1492. return true;
  1493. } else if (LookupTag(Message,"Message").find("NODATA") != string::npos) {
  1494. /* Invalid signature file, reject (LP: #346386) (Closes: #627642) */
  1495. _error->Error(_("GPG error: %s: %s"),
  1496. Desc.Description.c_str(),
  1497. LookupTag(Message,"Message").c_str());
  1498. Status = StatError;
  1499. return true;
  1500. } else {
  1501. _error->Warning(_("GPG error: %s: %s"),
  1502. Desc.Description.c_str(),
  1503. LookupTag(Message,"Message").c_str());
  1504. }
  1505. // gpgv method failed
  1506. ReportMirrorFailure("GPGFailure");
  1507. return false;
  1508. }
  1509. /*}}}*/
  1510. // AcqMetaSig::AcqMetaSig - Constructor /*{{{*/
  1511. pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire *Owner,
  1512. pkgAcqMetaBase *TransactionManager,
  1513. string URI,string URIDesc,string ShortDesc,
  1514. string MetaIndexFile,
  1515. const vector<IndexTarget*>* IndexTargets,
  1516. indexRecords* MetaIndexParser) :
  1517. pkgAcqMetaBase(Owner, IndexTargets, MetaIndexParser,
  1518. HashStringList(), TransactionManager),
  1519. RealURI(URI), MetaIndexFile(MetaIndexFile), URIDesc(URIDesc),
  1520. ShortDesc(ShortDesc)
  1521. {
  1522. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  1523. DestFile += URItoFileName(RealURI);
  1524. // remove any partial downloaded sig-file in partial/.
  1525. // it may confuse proxies and is too small to warrant a
  1526. // partial download anyway
  1527. unlink(DestFile.c_str());
  1528. // set the TransactionManager
  1529. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1530. std::clog << "New pkgAcqMetaSig with TransactionManager "
  1531. << TransactionManager << std::endl;
  1532. // Create the item
  1533. Desc.Description = URIDesc;
  1534. Desc.Owner = this;
  1535. Desc.ShortDesc = ShortDesc;
  1536. Desc.URI = URI;
  1537. QueueURI(Desc);
  1538. }
  1539. /*}}}*/
  1540. pkgAcqMetaSig::~pkgAcqMetaSig() /*{{{*/
  1541. {
  1542. }
  1543. /*}}}*/
  1544. // pkgAcqMetaSig::Custom600Headers - Insert custom request headers /*{{{*/
  1545. // ---------------------------------------------------------------------
  1546. string pkgAcqMetaSig::Custom600Headers() const
  1547. {
  1548. std::string Header = GetCustom600Headers(RealURI);
  1549. return Header;
  1550. }
  1551. /*}}}*/
  1552. // pkgAcqMetaSig::Done - The signature was downloaded/verified /*{{{*/
  1553. // ---------------------------------------------------------------------
  1554. /* The only header we use is the last-modified header. */
  1555. void pkgAcqMetaSig::Done(string Message,unsigned long long Size,
  1556. HashStringList const &Hashes,
  1557. pkgAcquire::MethodConfig *Cfg)
  1558. {
  1559. Item::Done(Message, Size, Hashes, Cfg);
  1560. if(AuthPass == false)
  1561. {
  1562. if(CheckDownloadDone(Message, RealURI) == true)
  1563. {
  1564. // destfile will be modified to point to MetaIndexFile for the
  1565. // gpgv method, so we need to save it here
  1566. MetaIndexFileSignature = DestFile;
  1567. QueueForSignatureVerify(MetaIndexFile, MetaIndexFileSignature);
  1568. }
  1569. return;
  1570. }
  1571. else
  1572. {
  1573. if(CheckAuthDone(Message, RealURI) == true)
  1574. {
  1575. std::string FinalFile = _config->FindDir("Dir::State::lists");
  1576. FinalFile += URItoFileName(RealURI);
  1577. TransactionManager->TransactionStageCopy(this, MetaIndexFileSignature, FinalFile);
  1578. }
  1579. }
  1580. }
  1581. /*}}}*/
  1582. void pkgAcqMetaSig::Failed(string Message,pkgAcquire::MethodConfig *Cnf)/*{{{*/
  1583. {
  1584. string Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
  1585. // check if we need to fail at this point
  1586. if (AuthPass == true && CheckStopAuthentication(RealURI, Message))
  1587. return;
  1588. // FIXME: meh, this is not really elegant
  1589. string InReleaseURI = RealURI.replace(RealURI.rfind("Release.gpg"), 12,
  1590. "InRelease");
  1591. string FinalInRelease = _config->FindDir("Dir::State::lists") + URItoFileName(InReleaseURI);
  1592. if (RealFileExists(Final) || RealFileExists(FinalInRelease))
  1593. {
  1594. std::string downgrade_msg;
  1595. strprintf(downgrade_msg, _("The repository '%s' is no longer signed."),
  1596. URIDesc.c_str());
  1597. if(_config->FindB("Acquire::AllowDowngradeToInsecureRepositories"))
  1598. {
  1599. // meh, the users wants to take risks (we still mark the packages
  1600. // from this repository as unauthenticated)
  1601. _error->Warning("%s", downgrade_msg.c_str());
  1602. _error->Warning(_("This is normally not allowed, but the option "
  1603. "Acquire::AllowDowngradeToInsecureRepositories was "
  1604. "given to override it."));
  1605. } else {
  1606. _error->Error("%s", downgrade_msg.c_str());
  1607. Rename(MetaIndexFile, MetaIndexFile+".FAILED");
  1608. Item::Failed("Message: " + downgrade_msg, Cnf);
  1609. TransactionManager->AbortTransaction();
  1610. return;
  1611. }
  1612. }
  1613. else
  1614. _error->Warning(_("The data from '%s' is not signed. Packages "
  1615. "from that repository can not be authenticated."),
  1616. URIDesc.c_str());
  1617. // this ensures that any file in the lists/ dir is removed by the
  1618. // transaction
  1619. DestFile = GetPartialFileNameFromURI(RealURI);
  1620. TransactionManager->TransactionStageRemoval(this, DestFile);
  1621. // only allow going further if the users explicitely wants it
  1622. if(AllowInsecureRepositories(MetaIndexParser, TransactionManager, this) == true)
  1623. {
  1624. // we parse the indexes here because at this point the user wanted
  1625. // a repository that may potentially harm him
  1626. MetaIndexParser->Load(MetaIndexFile);
  1627. QueueIndexes(true);
  1628. }
  1629. Item::Failed(Message,Cnf);
  1630. // FIXME: this is used often (e.g. in pkgAcqIndexTrans) so refactor
  1631. if (Cnf->LocalOnly == true ||
  1632. StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
  1633. {
  1634. // Ignore this
  1635. Status = StatDone;
  1636. }
  1637. }
  1638. /*}}}*/
  1639. pkgAcqMetaIndex::pkgAcqMetaIndex(pkgAcquire *Owner, /*{{{*/
  1640. pkgAcqMetaBase *TransactionManager,
  1641. string URI,string URIDesc,string ShortDesc,
  1642. string MetaIndexSigURI,string MetaIndexSigURIDesc, string MetaIndexSigShortDesc,
  1643. const vector<IndexTarget*>* IndexTargets,
  1644. indexRecords* MetaIndexParser) :
  1645. pkgAcqMetaBase(Owner, IndexTargets, MetaIndexParser, HashStringList(),
  1646. TransactionManager),
  1647. RealURI(URI), URIDesc(URIDesc), ShortDesc(ShortDesc),
  1648. MetaIndexSigURI(MetaIndexSigURI), MetaIndexSigURIDesc(MetaIndexSigURIDesc),
  1649. MetaIndexSigShortDesc(MetaIndexSigShortDesc)
  1650. {
  1651. if(TransactionManager == NULL)
  1652. {
  1653. this->TransactionManager = this;
  1654. this->TransactionManager->Add(this);
  1655. }
  1656. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1657. std::clog << "New pkgAcqMetaIndex with TransactionManager "
  1658. << this->TransactionManager << std::endl;
  1659. Init(URIDesc, ShortDesc);
  1660. }
  1661. /*}}}*/
  1662. // pkgAcqMetaIndex::Init - Delayed constructor /*{{{*/
  1663. void pkgAcqMetaIndex::Init(std::string URIDesc, std::string ShortDesc)
  1664. {
  1665. DestFile = GetPartialFileNameFromURI(RealURI);
  1666. // Create the item
  1667. Desc.Description = URIDesc;
  1668. Desc.Owner = this;
  1669. Desc.ShortDesc = ShortDesc;
  1670. Desc.URI = RealURI;
  1671. // we expect more item
  1672. ExpectedAdditionalItems = IndexTargets->size();
  1673. QueueURI(Desc);
  1674. }
  1675. /*}}}*/
  1676. // pkgAcqMetaIndex::Custom600Headers - Insert custom request headers /*{{{*/
  1677. // ---------------------------------------------------------------------
  1678. string pkgAcqMetaIndex::Custom600Headers() const
  1679. {
  1680. return GetCustom600Headers(RealURI);
  1681. }
  1682. /*}}}*/
  1683. void pkgAcqMetaIndex::Done(string Message,unsigned long long Size, /*{{{*/
  1684. HashStringList const &Hashes,
  1685. pkgAcquire::MethodConfig *Cfg)
  1686. {
  1687. Item::Done(Message,Size,Hashes,Cfg);
  1688. if(CheckDownloadDone(Message, RealURI))
  1689. {
  1690. // we have a Release file, now download the Signature, all further
  1691. // verify/queue for additional downloads will be done in the
  1692. // pkgAcqMetaSig::Done() code
  1693. std::string MetaIndexFile = DestFile;
  1694. new pkgAcqMetaSig(Owner, TransactionManager,
  1695. MetaIndexSigURI, MetaIndexSigURIDesc,
  1696. MetaIndexSigShortDesc, MetaIndexFile, IndexTargets,
  1697. MetaIndexParser);
  1698. string FinalFile = _config->FindDir("Dir::State::lists");
  1699. FinalFile += URItoFileName(RealURI);
  1700. TransactionManager->TransactionStageCopy(this, DestFile, FinalFile);
  1701. }
  1702. }
  1703. /*}}}*/
  1704. bool pkgAcqMetaBase::CheckAuthDone(string Message, const string &RealURI) /*{{{*/
  1705. {
  1706. // At this point, the gpgv method has succeeded, so there is a
  1707. // valid signature from a key in the trusted keyring. We
  1708. // perform additional verification of its contents, and use them
  1709. // to verify the indexes we are about to download
  1710. if (!MetaIndexParser->Load(DestFile))
  1711. {
  1712. Status = StatAuthError;
  1713. ErrorText = MetaIndexParser->ErrorText;
  1714. return false;
  1715. }
  1716. if (!VerifyVendor(Message, RealURI))
  1717. {
  1718. return false;
  1719. }
  1720. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1721. std::cerr << "Signature verification succeeded: "
  1722. << DestFile << std::endl;
  1723. // Download further indexes with verification
  1724. //
  1725. // it would be really nice if we could simply do
  1726. // if (IMSHit == false) QueueIndexes(true)
  1727. // and skip the download if the Release file has not changed
  1728. // - but right now the list cleaner will needs to be tricked
  1729. // to not delete all our packages/source indexes in this case
  1730. QueueIndexes(true);
  1731. return true;
  1732. }
  1733. /*}}}*/
  1734. // pkgAcqMetaBase::GetCustom600Headers - Get header for AcqMetaBase /*{{{*/
  1735. // ---------------------------------------------------------------------
  1736. string pkgAcqMetaBase::GetCustom600Headers(const string &RealURI) const
  1737. {
  1738. std::string Header = "\nIndex-File: true";
  1739. std::string MaximumSize;
  1740. strprintf(MaximumSize, "\nMaximum-Size: %i",
  1741. _config->FindI("Acquire::MaxReleaseFileSize", 10*1000*1000));
  1742. Header += MaximumSize;
  1743. string FinalFile = _config->FindDir("Dir::State::lists");
  1744. FinalFile += URItoFileName(RealURI);
  1745. struct stat Buf;
  1746. if (stat(FinalFile.c_str(),&Buf) == 0)
  1747. Header += "\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  1748. return Header;
  1749. }
  1750. /*}}}*/
  1751. // pkgAcqMetaBase::QueueForSignatureVerify /*{{{*/
  1752. void pkgAcqMetaBase::QueueForSignatureVerify(const std::string &MetaIndexFile,
  1753. const std::string &MetaIndexFileSignature)
  1754. {
  1755. AuthPass = true;
  1756. Desc.URI = "gpgv:" + MetaIndexFileSignature;
  1757. DestFile = MetaIndexFile;
  1758. QueueURI(Desc);
  1759. SetActiveSubprocess("gpgv");
  1760. }
  1761. /*}}}*/
  1762. // pkgAcqMetaBase::CheckDownloadDone /*{{{*/
  1763. bool pkgAcqMetaBase::CheckDownloadDone(const std::string &Message,
  1764. const std::string &RealURI)
  1765. {
  1766. // We have just finished downloading a Release file (it is not
  1767. // verified yet)
  1768. string FileName = LookupTag(Message,"Filename");
  1769. if (FileName.empty() == true)
  1770. {
  1771. Status = StatError;
  1772. ErrorText = "Method gave a blank filename";
  1773. return false;
  1774. }
  1775. if (FileName != DestFile)
  1776. {
  1777. Local = true;
  1778. Desc.URI = "copy:" + FileName;
  1779. QueueURI(Desc);
  1780. return false;
  1781. }
  1782. // make sure to verify against the right file on I-M-S hit
  1783. IMSHit = StringToBool(LookupTag(Message,"IMS-Hit"),false);
  1784. if(IMSHit)
  1785. {
  1786. string FinalFile = _config->FindDir("Dir::State::lists");
  1787. FinalFile += URItoFileName(RealURI);
  1788. DestFile = FinalFile;
  1789. }
  1790. // set Item to complete as the remaining work is all local (verify etc)
  1791. Complete = true;
  1792. return true;
  1793. }
  1794. /*}}}*/
  1795. void pkgAcqMetaBase::QueueIndexes(bool verify) /*{{{*/
  1796. {
  1797. bool transInRelease = false;
  1798. {
  1799. std::vector<std::string> const keys = MetaIndexParser->MetaKeys();
  1800. for (std::vector<std::string>::const_iterator k = keys.begin(); k != keys.end(); ++k)
  1801. // FIXME: Feels wrong to check for hardcoded string here, but what should we do else…
  1802. if (k->find("Translation-") != std::string::npos)
  1803. {
  1804. transInRelease = true;
  1805. break;
  1806. }
  1807. }
  1808. // at this point the real Items are loaded in the fetcher
  1809. ExpectedAdditionalItems = 0;
  1810. for (vector <IndexTarget*>::const_iterator Target = IndexTargets->begin();
  1811. Target != IndexTargets->end();
  1812. ++Target)
  1813. {
  1814. HashStringList ExpectedIndexHashes;
  1815. const indexRecords::checkSum *Record = MetaIndexParser->Lookup((*Target)->MetaKey);
  1816. bool compressedAvailable = false;
  1817. if (Record == NULL)
  1818. {
  1819. if ((*Target)->IsOptional() == true)
  1820. {
  1821. std::vector<std::string> types = APT::Configuration::getCompressionTypes();
  1822. for (std::vector<std::string>::const_iterator t = types.begin(); t != types.end(); ++t)
  1823. if (MetaIndexParser->Exists((*Target)->MetaKey + "." + *t) == true)
  1824. {
  1825. compressedAvailable = true;
  1826. break;
  1827. }
  1828. }
  1829. else if (verify == true)
  1830. {
  1831. Status = StatAuthError;
  1832. strprintf(ErrorText, _("Unable to find expected entry '%s' in Release file (Wrong sources.list entry or malformed file)"), (*Target)->MetaKey.c_str());
  1833. return;
  1834. }
  1835. }
  1836. else
  1837. {
  1838. ExpectedIndexHashes = Record->Hashes;
  1839. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1840. {
  1841. std::cerr << "Queueing: " << (*Target)->URI << std::endl
  1842. << "Expected Hash:" << std::endl;
  1843. for (HashStringList::const_iterator hs = ExpectedIndexHashes.begin(); hs != ExpectedIndexHashes.end(); ++hs)
  1844. std::cerr << "\t- " << hs->toStr() << std::endl;
  1845. std::cerr << "For: " << Record->MetaKeyFilename << std::endl;
  1846. }
  1847. if (verify == true && ExpectedIndexHashes.empty() == true && (*Target)->IsOptional() == false)
  1848. {
  1849. Status = StatAuthError;
  1850. strprintf(ErrorText, _("Unable to find hash sum for '%s' in Release file"), (*Target)->MetaKey.c_str());
  1851. return;
  1852. }
  1853. }
  1854. if ((*Target)->IsOptional() == true)
  1855. {
  1856. if (transInRelease == false || Record != NULL || compressedAvailable == true)
  1857. {
  1858. if (_config->FindB("Acquire::PDiffs",true) == true && transInRelease == true &&
  1859. MetaIndexParser->Exists((*Target)->MetaKey + ".diff/Index") == true)
  1860. new pkgAcqDiffIndex(Owner, TransactionManager, *Target, ExpectedIndexHashes, MetaIndexParser);
  1861. else
  1862. new pkgAcqIndexTrans(Owner, TransactionManager, *Target, ExpectedIndexHashes, MetaIndexParser);
  1863. }
  1864. continue;
  1865. }
  1866. /* Queue Packages file (either diff or full packages files, depending
  1867. on the users option) - we also check if the PDiff Index file is listed
  1868. in the Meta-Index file. Ideal would be if pkgAcqDiffIndex would test this
  1869. instead, but passing the required info to it is to much hassle */
  1870. if(_config->FindB("Acquire::PDiffs",true) == true && (verify == false ||
  1871. MetaIndexParser->Exists((*Target)->MetaKey + ".diff/Index") == true))
  1872. new pkgAcqDiffIndex(Owner, TransactionManager, *Target, ExpectedIndexHashes, MetaIndexParser);
  1873. else
  1874. new pkgAcqIndex(Owner, TransactionManager, *Target, ExpectedIndexHashes, MetaIndexParser);
  1875. }
  1876. }
  1877. /*}}}*/
  1878. bool pkgAcqMetaBase::VerifyVendor(string Message, const string &RealURI)/*{{{*/
  1879. {
  1880. string::size_type pos;
  1881. // check for missing sigs (that where not fatal because otherwise we had
  1882. // bombed earlier)
  1883. string missingkeys;
  1884. string msg = _("There is no public key available for the "
  1885. "following key IDs:\n");
  1886. pos = Message.find("NO_PUBKEY ");
  1887. if (pos != std::string::npos)
  1888. {
  1889. string::size_type start = pos+strlen("NO_PUBKEY ");
  1890. string Fingerprint = Message.substr(start, Message.find("\n")-start);
  1891. missingkeys += (Fingerprint);
  1892. }
  1893. if(!missingkeys.empty())
  1894. _error->Warning("%s", (msg + missingkeys).c_str());
  1895. string Transformed = MetaIndexParser->GetExpectedDist();
  1896. if (Transformed == "../project/experimental")
  1897. {
  1898. Transformed = "experimental";
  1899. }
  1900. pos = Transformed.rfind('/');
  1901. if (pos != string::npos)
  1902. {
  1903. Transformed = Transformed.substr(0, pos);
  1904. }
  1905. if (Transformed == ".")
  1906. {
  1907. Transformed = "";
  1908. }
  1909. if (_config->FindB("Acquire::Check-Valid-Until", true) == true &&
  1910. MetaIndexParser->GetValidUntil() > 0) {
  1911. time_t const invalid_since = time(NULL) - MetaIndexParser->GetValidUntil();
  1912. if (invalid_since > 0)
  1913. // TRANSLATOR: The first %s is the URL of the bad Release file, the second is
  1914. // the time since then the file is invalid - formated in the same way as in
  1915. // the download progress display (e.g. 7d 3h 42min 1s)
  1916. return _error->Error(
  1917. _("Release file for %s is expired (invalid since %s). "
  1918. "Updates for this repository will not be applied."),
  1919. RealURI.c_str(), TimeToStr(invalid_since).c_str());
  1920. }
  1921. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1922. {
  1923. std::cerr << "Got Codename: " << MetaIndexParser->GetDist() << std::endl;
  1924. std::cerr << "Expecting Dist: " << MetaIndexParser->GetExpectedDist() << std::endl;
  1925. std::cerr << "Transformed Dist: " << Transformed << std::endl;
  1926. }
  1927. if (MetaIndexParser->CheckDist(Transformed) == false)
  1928. {
  1929. // This might become fatal one day
  1930. // Status = StatAuthError;
  1931. // ErrorText = "Conflicting distribution; expected "
  1932. // + MetaIndexParser->GetExpectedDist() + " but got "
  1933. // + MetaIndexParser->GetDist();
  1934. // return false;
  1935. if (!Transformed.empty())
  1936. {
  1937. _error->Warning(_("Conflicting distribution: %s (expected %s but got %s)"),
  1938. Desc.Description.c_str(),
  1939. Transformed.c_str(),
  1940. MetaIndexParser->GetDist().c_str());
  1941. }
  1942. }
  1943. return true;
  1944. }
  1945. /*}}}*/
  1946. // pkgAcqMetaIndex::Failed - no Release file present /*{{{*/
  1947. void pkgAcqMetaIndex::Failed(string Message,
  1948. pkgAcquire::MethodConfig * Cnf)
  1949. {
  1950. pkgAcquire::Item::Failed(Message, Cnf);
  1951. Status = StatDone;
  1952. string FinalFile = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
  1953. _error->Warning(_("The repository '%s' does not have a Release file. "
  1954. "This is deprecated, please contact the owner of the "
  1955. "repository."), URIDesc.c_str());
  1956. // No Release file was present so fall
  1957. // back to queueing Packages files without verification
  1958. // only allow going further if the users explicitely wants it
  1959. if(AllowInsecureRepositories(MetaIndexParser, TransactionManager, this) == true)
  1960. {
  1961. // Done, queue for rename on transaction finished
  1962. if (FileExists(DestFile))
  1963. TransactionManager->TransactionStageCopy(this, DestFile, FinalFile);
  1964. // queue without any kind of hashsum support
  1965. QueueIndexes(false);
  1966. }
  1967. }
  1968. /*}}}*/
  1969. void pkgAcqMetaIndex::Finished() /*{{{*/
  1970. {
  1971. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1972. std::clog << "Finished: " << DestFile <<std::endl;
  1973. if(TransactionManager != NULL &&
  1974. TransactionManager->TransactionHasError() == false)
  1975. TransactionManager->CommitTransaction();
  1976. }
  1977. /*}}}*/
  1978. pkgAcqMetaClearSig::pkgAcqMetaClearSig(pkgAcquire *Owner, /*{{{*/
  1979. string const &URI, string const &URIDesc, string const &ShortDesc,
  1980. string const &MetaIndexURI, string const &MetaIndexURIDesc, string const &MetaIndexShortDesc,
  1981. string const &MetaSigURI, string const &MetaSigURIDesc, string const &MetaSigShortDesc,
  1982. const vector<IndexTarget*>* IndexTargets,
  1983. indexRecords* MetaIndexParser) :
  1984. pkgAcqMetaIndex(Owner, NULL, URI, URIDesc, ShortDesc, MetaSigURI, MetaSigURIDesc,MetaSigShortDesc, IndexTargets, MetaIndexParser),
  1985. MetaIndexURI(MetaIndexURI), MetaIndexURIDesc(MetaIndexURIDesc), MetaIndexShortDesc(MetaIndexShortDesc),
  1986. MetaSigURI(MetaSigURI), MetaSigURIDesc(MetaSigURIDesc), MetaSigShortDesc(MetaSigShortDesc)
  1987. {
  1988. // index targets + (worst case:) Release/Release.gpg
  1989. ExpectedAdditionalItems = IndexTargets->size() + 2;
  1990. }
  1991. /*}}}*/
  1992. pkgAcqMetaClearSig::~pkgAcqMetaClearSig() /*{{{*/
  1993. {
  1994. }
  1995. /*}}}*/
  1996. // pkgAcqMetaClearSig::Custom600Headers - Insert custom request headers /*{{{*/
  1997. // ---------------------------------------------------------------------
  1998. string pkgAcqMetaClearSig::Custom600Headers() const
  1999. {
  2000. string Header = GetCustom600Headers(RealURI);
  2001. Header += "\nFail-Ignore: true";
  2002. return Header;
  2003. }
  2004. /*}}}*/
  2005. // pkgAcqMetaClearSig::Done - We got a file /*{{{*/
  2006. // ---------------------------------------------------------------------
  2007. void pkgAcqMetaClearSig::Done(std::string Message,unsigned long long /*Size*/,
  2008. HashStringList const &/*Hashes*/,
  2009. pkgAcquire::MethodConfig *Cnf)
  2010. {
  2011. // if we expect a ClearTextSignature (InRelase), ensure that
  2012. // this is what we get and if not fail to queue a
  2013. // Release/Release.gpg, see #346386
  2014. if (FileExists(DestFile) && !StartsWithGPGClearTextSignature(DestFile))
  2015. {
  2016. pkgAcquire::Item::Failed(Message, Cnf);
  2017. RenameOnError(NotClearsigned);
  2018. TransactionManager->AbortTransaction();
  2019. return;
  2020. }
  2021. if(AuthPass == false)
  2022. {
  2023. if(CheckDownloadDone(Message, RealURI) == true)
  2024. QueueForSignatureVerify(DestFile, DestFile);
  2025. return;
  2026. }
  2027. else
  2028. {
  2029. if(CheckAuthDone(Message, RealURI) == true)
  2030. {
  2031. string FinalFile = _config->FindDir("Dir::State::lists");
  2032. FinalFile += URItoFileName(RealURI);
  2033. // queue for copy in place
  2034. TransactionManager->TransactionStageCopy(this, DestFile, FinalFile);
  2035. }
  2036. }
  2037. }
  2038. /*}}}*/
  2039. void pkgAcqMetaClearSig::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
  2040. {
  2041. Item::Failed(Message, Cnf);
  2042. // we failed, we will not get additional items from this method
  2043. ExpectedAdditionalItems = 0;
  2044. if (AuthPass == false)
  2045. {
  2046. // Queue the 'old' InRelease file for removal if we try Release.gpg
  2047. // as otherwise the file will stay around and gives a false-auth
  2048. // impression (CVE-2012-0214)
  2049. string FinalFile = _config->FindDir("Dir::State::lists");
  2050. FinalFile.append(URItoFileName(RealURI));
  2051. TransactionManager->TransactionStageRemoval(this, FinalFile);
  2052. Status = StatDone;
  2053. new pkgAcqMetaIndex(Owner, TransactionManager,
  2054. MetaIndexURI, MetaIndexURIDesc, MetaIndexShortDesc,
  2055. MetaSigURI, MetaSigURIDesc, MetaSigShortDesc,
  2056. IndexTargets, MetaIndexParser);
  2057. }
  2058. else
  2059. {
  2060. if(CheckStopAuthentication(RealURI, Message))
  2061. return;
  2062. _error->Warning(_("The data from '%s' is not signed. Packages "
  2063. "from that repository can not be authenticated."),
  2064. URIDesc.c_str());
  2065. // No Release file was present, or verification failed, so fall
  2066. // back to queueing Packages files without verification
  2067. // only allow going further if the users explicitely wants it
  2068. if(AllowInsecureRepositories(MetaIndexParser, TransactionManager, this) == true)
  2069. {
  2070. Status = StatDone;
  2071. /* Always move the meta index, even if gpgv failed. This ensures
  2072. * that PackageFile objects are correctly filled in */
  2073. if (FileExists(DestFile))
  2074. {
  2075. string FinalFile = _config->FindDir("Dir::State::lists");
  2076. FinalFile += URItoFileName(RealURI);
  2077. /* InRelease files become Release files, otherwise
  2078. * they would be considered as trusted later on */
  2079. RealURI = RealURI.replace(RealURI.rfind("InRelease"), 9,
  2080. "Release");
  2081. FinalFile = FinalFile.replace(FinalFile.rfind("InRelease"), 9,
  2082. "Release");
  2083. // Done, queue for rename on transaction finished
  2084. TransactionManager->TransactionStageCopy(this, DestFile, FinalFile);
  2085. }
  2086. QueueIndexes(false);
  2087. }
  2088. }
  2089. }
  2090. /*}}}*/
  2091. // AcqArchive::AcqArchive - Constructor /*{{{*/
  2092. // ---------------------------------------------------------------------
  2093. /* This just sets up the initial fetch environment and queues the first
  2094. possibilitiy */
  2095. pkgAcqArchive::pkgAcqArchive(pkgAcquire *Owner,pkgSourceList *Sources,
  2096. pkgRecords *Recs,pkgCache::VerIterator const &Version,
  2097. string &StoreFilename) :
  2098. Item(Owner, HashStringList()), Version(Version), Sources(Sources), Recs(Recs),
  2099. StoreFilename(StoreFilename), Vf(Version.FileList()),
  2100. Trusted(false)
  2101. {
  2102. Retries = _config->FindI("Acquire::Retries",0);
  2103. if (Version.Arch() == 0)
  2104. {
  2105. _error->Error(_("I wasn't able to locate a file for the %s package. "
  2106. "This might mean you need to manually fix this package. "
  2107. "(due to missing arch)"),
  2108. Version.ParentPkg().FullName().c_str());
  2109. return;
  2110. }
  2111. /* We need to find a filename to determine the extension. We make the
  2112. assumption here that all the available sources for this version share
  2113. the same extension.. */
  2114. // Skip not source sources, they do not have file fields.
  2115. for (; Vf.end() == false; ++Vf)
  2116. {
  2117. if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
  2118. continue;
  2119. break;
  2120. }
  2121. // Does not really matter here.. we are going to fail out below
  2122. if (Vf.end() != true)
  2123. {
  2124. // If this fails to get a file name we will bomb out below.
  2125. pkgRecords::Parser &Parse = Recs->Lookup(Vf);
  2126. if (_error->PendingError() == true)
  2127. return;
  2128. // Generate the final file name as: package_version_arch.foo
  2129. StoreFilename = QuoteString(Version.ParentPkg().Name(),"_:") + '_' +
  2130. QuoteString(Version.VerStr(),"_:") + '_' +
  2131. QuoteString(Version.Arch(),"_:.") +
  2132. "." + flExtension(Parse.FileName());
  2133. }
  2134. // check if we have one trusted source for the package. if so, switch
  2135. // to "TrustedOnly" mode - but only if not in AllowUnauthenticated mode
  2136. bool const allowUnauth = _config->FindB("APT::Get::AllowUnauthenticated", false);
  2137. bool const debugAuth = _config->FindB("Debug::pkgAcquire::Auth", false);
  2138. bool seenUntrusted = false;
  2139. for (pkgCache::VerFileIterator i = Version.FileList(); i.end() == false; ++i)
  2140. {
  2141. pkgIndexFile *Index;
  2142. if (Sources->FindIndex(i.File(),Index) == false)
  2143. continue;
  2144. if (debugAuth == true)
  2145. std::cerr << "Checking index: " << Index->Describe()
  2146. << "(Trusted=" << Index->IsTrusted() << ")" << std::endl;
  2147. if (Index->IsTrusted() == true)
  2148. {
  2149. Trusted = true;
  2150. if (allowUnauth == false)
  2151. break;
  2152. }
  2153. else
  2154. seenUntrusted = true;
  2155. }
  2156. // "allow-unauthenticated" restores apts old fetching behaviour
  2157. // that means that e.g. unauthenticated file:// uris are higher
  2158. // priority than authenticated http:// uris
  2159. if (allowUnauth == true && seenUntrusted == true)
  2160. Trusted = false;
  2161. // Select a source
  2162. if (QueueNext() == false && _error->PendingError() == false)
  2163. _error->Error(_("Can't find a source to download version '%s' of '%s'"),
  2164. Version.VerStr(), Version.ParentPkg().FullName(false).c_str());
  2165. }
  2166. /*}}}*/
  2167. // AcqArchive::QueueNext - Queue the next file source /*{{{*/
  2168. // ---------------------------------------------------------------------
  2169. /* This queues the next available file version for download. It checks if
  2170. the archive is already available in the cache and stashs the MD5 for
  2171. checking later. */
  2172. bool pkgAcqArchive::QueueNext()
  2173. {
  2174. for (; Vf.end() == false; ++Vf)
  2175. {
  2176. // Ignore not source sources
  2177. if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
  2178. continue;
  2179. // Try to cross match against the source list
  2180. pkgIndexFile *Index;
  2181. if (Sources->FindIndex(Vf.File(),Index) == false)
  2182. continue;
  2183. // only try to get a trusted package from another source if that source
  2184. // is also trusted
  2185. if(Trusted && !Index->IsTrusted())
  2186. continue;
  2187. // Grab the text package record
  2188. pkgRecords::Parser &Parse = Recs->Lookup(Vf);
  2189. if (_error->PendingError() == true)
  2190. return false;
  2191. string PkgFile = Parse.FileName();
  2192. ExpectedHashes = Parse.Hashes();
  2193. if (PkgFile.empty() == true)
  2194. return _error->Error(_("The package index files are corrupted. No Filename: "
  2195. "field for package %s."),
  2196. Version.ParentPkg().Name());
  2197. Desc.URI = Index->ArchiveURI(PkgFile);
  2198. Desc.Description = Index->ArchiveInfo(Version);
  2199. Desc.Owner = this;
  2200. Desc.ShortDesc = Version.ParentPkg().FullName(true);
  2201. // See if we already have the file. (Legacy filenames)
  2202. FileSize = Version->Size;
  2203. string FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(PkgFile);
  2204. struct stat Buf;
  2205. if (stat(FinalFile.c_str(),&Buf) == 0)
  2206. {
  2207. // Make sure the size matches
  2208. if ((unsigned long long)Buf.st_size == Version->Size)
  2209. {
  2210. Complete = true;
  2211. Local = true;
  2212. Status = StatDone;
  2213. StoreFilename = DestFile = FinalFile;
  2214. return true;
  2215. }
  2216. /* Hmm, we have a file and its size does not match, this means it is
  2217. an old style mismatched arch */
  2218. unlink(FinalFile.c_str());
  2219. }
  2220. // Check it again using the new style output filenames
  2221. FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename);
  2222. if (stat(FinalFile.c_str(),&Buf) == 0)
  2223. {
  2224. // Make sure the size matches
  2225. if ((unsigned long long)Buf.st_size == Version->Size)
  2226. {
  2227. Complete = true;
  2228. Local = true;
  2229. Status = StatDone;
  2230. StoreFilename = DestFile = FinalFile;
  2231. return true;
  2232. }
  2233. /* Hmm, we have a file and its size does not match, this shouldn't
  2234. happen.. */
  2235. unlink(FinalFile.c_str());
  2236. }
  2237. DestFile = _config->FindDir("Dir::Cache::Archives") + "partial/" + flNotDir(StoreFilename);
  2238. // Check the destination file
  2239. if (stat(DestFile.c_str(),&Buf) == 0)
  2240. {
  2241. // Hmm, the partial file is too big, erase it
  2242. if ((unsigned long long)Buf.st_size > Version->Size)
  2243. unlink(DestFile.c_str());
  2244. else
  2245. {
  2246. PartialSize = Buf.st_size;
  2247. std::string SandboxUser = _config->Find("APT::Sandbox::User");
  2248. ChangeOwnerAndPermissionOfFile("pkgAcqArchive::QueueNext",DestFile.c_str(), SandboxUser.c_str(), "root", 0600);
  2249. }
  2250. }
  2251. // Disables download of archives - useful if no real installation follows,
  2252. // e.g. if we are just interested in proposed installation order
  2253. if (_config->FindB("Debug::pkgAcqArchive::NoQueue", false) == true)
  2254. {
  2255. Complete = true;
  2256. Local = true;
  2257. Status = StatDone;
  2258. StoreFilename = DestFile = FinalFile;
  2259. return true;
  2260. }
  2261. // Create the item
  2262. Local = false;
  2263. QueueURI(Desc);
  2264. ++Vf;
  2265. return true;
  2266. }
  2267. return false;
  2268. }
  2269. /*}}}*/
  2270. // AcqArchive::Done - Finished fetching /*{{{*/
  2271. // ---------------------------------------------------------------------
  2272. /* */
  2273. void pkgAcqArchive::Done(string Message,unsigned long long Size, HashStringList const &CalcHashes,
  2274. pkgAcquire::MethodConfig *Cfg)
  2275. {
  2276. Item::Done(Message, Size, CalcHashes, Cfg);
  2277. // Check the size
  2278. if (Size != Version->Size)
  2279. {
  2280. RenameOnError(SizeMismatch);
  2281. return;
  2282. }
  2283. // FIXME: could this empty() check impose *any* sort of security issue?
  2284. if(ExpectedHashes.usable() && ExpectedHashes != CalcHashes)
  2285. {
  2286. RenameOnError(HashSumMismatch);
  2287. printHashSumComparision(DestFile, ExpectedHashes, CalcHashes);
  2288. return;
  2289. }
  2290. // Grab the output filename
  2291. string FileName = LookupTag(Message,"Filename");
  2292. if (FileName.empty() == true)
  2293. {
  2294. Status = StatError;
  2295. ErrorText = "Method gave a blank filename";
  2296. return;
  2297. }
  2298. // Reference filename
  2299. if (FileName != DestFile)
  2300. {
  2301. StoreFilename = DestFile = FileName;
  2302. Local = true;
  2303. Complete = true;
  2304. return;
  2305. }
  2306. // Done, move it into position
  2307. string FinalFile = _config->FindDir("Dir::Cache::Archives");
  2308. FinalFile += flNotDir(StoreFilename);
  2309. Rename(DestFile,FinalFile);
  2310. ChangeOwnerAndPermissionOfFile("pkgAcqArchive::Done", FinalFile.c_str(), "root", "root", 0644);
  2311. StoreFilename = DestFile = FinalFile;
  2312. Complete = true;
  2313. }
  2314. /*}}}*/
  2315. // AcqArchive::Failed - Failure handler /*{{{*/
  2316. // ---------------------------------------------------------------------
  2317. /* Here we try other sources */
  2318. void pkgAcqArchive::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  2319. {
  2320. ErrorText = LookupTag(Message,"Message");
  2321. /* We don't really want to retry on failed media swaps, this prevents
  2322. that. An interesting observation is that permanent failures are not
  2323. recorded. */
  2324. if (Cnf->Removable == true &&
  2325. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  2326. {
  2327. // Vf = Version.FileList();
  2328. while (Vf.end() == false) ++Vf;
  2329. StoreFilename = string();
  2330. Item::Failed(Message,Cnf);
  2331. return;
  2332. }
  2333. if (QueueNext() == false)
  2334. {
  2335. // This is the retry counter
  2336. if (Retries != 0 &&
  2337. Cnf->LocalOnly == false &&
  2338. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  2339. {
  2340. Retries--;
  2341. Vf = Version.FileList();
  2342. if (QueueNext() == true)
  2343. return;
  2344. }
  2345. StoreFilename = string();
  2346. Item::Failed(Message,Cnf);
  2347. }
  2348. }
  2349. /*}}}*/
  2350. // AcqArchive::IsTrusted - Determine whether this archive comes from a trusted source /*{{{*/
  2351. // ---------------------------------------------------------------------
  2352. APT_PURE bool pkgAcqArchive::IsTrusted() const
  2353. {
  2354. return Trusted;
  2355. }
  2356. /*}}}*/
  2357. // AcqArchive::Finished - Fetching has finished, tidy up /*{{{*/
  2358. // ---------------------------------------------------------------------
  2359. /* */
  2360. void pkgAcqArchive::Finished()
  2361. {
  2362. if (Status == pkgAcquire::Item::StatDone &&
  2363. Complete == true)
  2364. return;
  2365. StoreFilename = string();
  2366. }
  2367. /*}}}*/
  2368. // AcqFile::pkgAcqFile - Constructor /*{{{*/
  2369. // ---------------------------------------------------------------------
  2370. /* The file is added to the queue */
  2371. pkgAcqFile::pkgAcqFile(pkgAcquire *Owner,string URI, HashStringList const &Hashes,
  2372. unsigned long long Size,string Dsc,string ShortDesc,
  2373. const string &DestDir, const string &DestFilename,
  2374. bool IsIndexFile) :
  2375. Item(Owner, Hashes), IsIndexFile(IsIndexFile)
  2376. {
  2377. Retries = _config->FindI("Acquire::Retries",0);
  2378. if(!DestFilename.empty())
  2379. DestFile = DestFilename;
  2380. else if(!DestDir.empty())
  2381. DestFile = DestDir + "/" + flNotDir(URI);
  2382. else
  2383. DestFile = flNotDir(URI);
  2384. // Create the item
  2385. Desc.URI = URI;
  2386. Desc.Description = Dsc;
  2387. Desc.Owner = this;
  2388. // Set the short description to the archive component
  2389. Desc.ShortDesc = ShortDesc;
  2390. // Get the transfer sizes
  2391. FileSize = Size;
  2392. struct stat Buf;
  2393. if (stat(DestFile.c_str(),&Buf) == 0)
  2394. {
  2395. // Hmm, the partial file is too big, erase it
  2396. if ((Size > 0) && (unsigned long long)Buf.st_size > Size)
  2397. unlink(DestFile.c_str());
  2398. else
  2399. {
  2400. PartialSize = Buf.st_size;
  2401. std::string SandboxUser = _config->Find("APT::Sandbox::User");
  2402. ChangeOwnerAndPermissionOfFile("pkgAcqFile", DestFile.c_str(), SandboxUser.c_str(), "root", 0600);
  2403. }
  2404. }
  2405. QueueURI(Desc);
  2406. }
  2407. /*}}}*/
  2408. // AcqFile::Done - Item downloaded OK /*{{{*/
  2409. // ---------------------------------------------------------------------
  2410. /* */
  2411. void pkgAcqFile::Done(string Message,unsigned long long Size,HashStringList const &CalcHashes,
  2412. pkgAcquire::MethodConfig *Cnf)
  2413. {
  2414. Item::Done(Message,Size,CalcHashes,Cnf);
  2415. // Check the hash
  2416. if(ExpectedHashes.usable() && ExpectedHashes != CalcHashes)
  2417. {
  2418. RenameOnError(HashSumMismatch);
  2419. printHashSumComparision(DestFile, ExpectedHashes, CalcHashes);
  2420. return;
  2421. }
  2422. string FileName = LookupTag(Message,"Filename");
  2423. if (FileName.empty() == true)
  2424. {
  2425. Status = StatError;
  2426. ErrorText = "Method gave a blank filename";
  2427. return;
  2428. }
  2429. Complete = true;
  2430. // The files timestamp matches
  2431. if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  2432. return;
  2433. // We have to copy it into place
  2434. if (FileName != DestFile)
  2435. {
  2436. Local = true;
  2437. if (_config->FindB("Acquire::Source-Symlinks",true) == false ||
  2438. Cnf->Removable == true)
  2439. {
  2440. Desc.URI = "copy:" + FileName;
  2441. QueueURI(Desc);
  2442. return;
  2443. }
  2444. // Erase the file if it is a symlink so we can overwrite it
  2445. struct stat St;
  2446. if (lstat(DestFile.c_str(),&St) == 0)
  2447. {
  2448. if (S_ISLNK(St.st_mode) != 0)
  2449. unlink(DestFile.c_str());
  2450. }
  2451. // Symlink the file
  2452. if (symlink(FileName.c_str(),DestFile.c_str()) != 0)
  2453. {
  2454. ErrorText = "Link to " + DestFile + " failure ";
  2455. Status = StatError;
  2456. Complete = false;
  2457. }
  2458. }
  2459. }
  2460. /*}}}*/
  2461. // AcqFile::Failed - Failure handler /*{{{*/
  2462. // ---------------------------------------------------------------------
  2463. /* Here we try other sources */
  2464. void pkgAcqFile::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  2465. {
  2466. ErrorText = LookupTag(Message,"Message");
  2467. // This is the retry counter
  2468. if (Retries != 0 &&
  2469. Cnf->LocalOnly == false &&
  2470. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  2471. {
  2472. Retries--;
  2473. QueueURI(Desc);
  2474. return;
  2475. }
  2476. Item::Failed(Message,Cnf);
  2477. }
  2478. /*}}}*/
  2479. // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
  2480. // ---------------------------------------------------------------------
  2481. /* The only header we use is the last-modified header. */
  2482. string pkgAcqFile::Custom600Headers() const
  2483. {
  2484. if (IsIndexFile)
  2485. return "\nIndex-File: true";
  2486. return "";
  2487. }
  2488. /*}}}*/