acquire-item.cc 89 KB

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