acquire-item.cc 73 KB

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