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