acquire-item.cc 91 KB

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