acquire-item.cc 72 KB

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