acquire-item.cc 81 KB

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