acquire-item.cc 91 KB

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