acquire-item.cc 79 KB

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