acquire-item.cc 80 KB

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