acquire-item.cc 89 KB

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