acquire-item.cc 116 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434
  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/tagfile.h>
  22. #include <apt-pkg/metaindex.h>
  23. #include <apt-pkg/acquire.h>
  24. #include <apt-pkg/hashes.h>
  25. #include <apt-pkg/indexfile.h>
  26. #include <apt-pkg/pkgcache.h>
  27. #include <apt-pkg/cacheiterators.h>
  28. #include <apt-pkg/pkgrecords.h>
  29. #include <apt-pkg/gpgv.h>
  30. #include <algorithm>
  31. #include <stddef.h>
  32. #include <stdlib.h>
  33. #include <string.h>
  34. #include <iostream>
  35. #include <vector>
  36. #include <sys/stat.h>
  37. #include <unistd.h>
  38. #include <errno.h>
  39. #include <string>
  40. #include <stdio.h>
  41. #include <ctime>
  42. #include <sstream>
  43. #include <apti18n.h>
  44. /*}}}*/
  45. using namespace std;
  46. static void printHashSumComparision(std::string const &URI, HashStringList const &Expected, HashStringList const &Actual) /*{{{*/
  47. {
  48. if (_config->FindB("Debug::Acquire::HashSumMismatch", false) == false)
  49. return;
  50. std::cerr << std::endl << URI << ":" << std::endl << " Expected Hash: " << std::endl;
  51. for (HashStringList::const_iterator hs = Expected.begin(); hs != Expected.end(); ++hs)
  52. std::cerr << "\t- " << hs->toStr() << std::endl;
  53. std::cerr << " Actual Hash: " << std::endl;
  54. for (HashStringList::const_iterator hs = Actual.begin(); hs != Actual.end(); ++hs)
  55. std::cerr << "\t- " << hs->toStr() << std::endl;
  56. }
  57. /*}}}*/
  58. static std::string GetPartialFileName(std::string const &file) /*{{{*/
  59. {
  60. std::string DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  61. DestFile += file;
  62. return DestFile;
  63. }
  64. /*}}}*/
  65. static std::string GetPartialFileNameFromURI(std::string const &uri) /*{{{*/
  66. {
  67. return GetPartialFileName(URItoFileName(uri));
  68. }
  69. /*}}}*/
  70. static std::string GetFinalFileNameFromURI(std::string const &uri) /*{{{*/
  71. {
  72. return _config->FindDir("Dir::State::lists") + URItoFileName(uri);
  73. }
  74. /*}}}*/
  75. static std::string GetKeepCompressedFileName(std::string file, IndexTarget const &Target)/*{{{*/
  76. {
  77. if (Target.KeepCompressed == false)
  78. return file;
  79. std::string const KeepCompressedAs = Target.Option(IndexTarget::KEEPCOMPRESSEDAS);
  80. if (KeepCompressedAs.empty() == false)
  81. {
  82. std::string const ext = KeepCompressedAs.substr(0, KeepCompressedAs.find(' '));
  83. if (ext != "uncompressed")
  84. file.append(".").append(ext);
  85. }
  86. return file;
  87. }
  88. /*}}}*/
  89. static std::string GetMergeDiffsPatchFileName(std::string const &Final, std::string const &Patch)/*{{{*/
  90. {
  91. // rred expects the patch as $FinalFile.ed.$patchname.gz
  92. return Final + ".ed." + Patch + ".gz";
  93. }
  94. /*}}}*/
  95. static std::string GetDiffsPatchFileName(std::string const &Final) /*{{{*/
  96. {
  97. // rred expects the patch as $FinalFile.ed
  98. return Final + ".ed";
  99. }
  100. /*}}}*/
  101. static std::string GetExistingFilename(std::string const &File) /*{{{*/
  102. {
  103. if (RealFileExists(File))
  104. return File;
  105. for (auto const &type : APT::Configuration::getCompressorExtensions())
  106. {
  107. std::string const Final = File + type;
  108. if (RealFileExists(Final))
  109. return Final;
  110. }
  111. return "";
  112. }
  113. /*}}}*/
  114. static bool MessageInsecureRepository(bool const isError, std::string const &msg)/*{{{*/
  115. {
  116. if (isError)
  117. {
  118. _error->Error("%s", msg.c_str());
  119. _error->Notice("%s", _("Updating from such a repository can't be done securely, and is therefore disabled by default."));
  120. }
  121. else
  122. {
  123. _error->Warning("%s", msg.c_str());
  124. _error->Notice("%s", _("Data from such a repository can't be authenticated and is therefore potentially dangerous to use."));
  125. }
  126. _error->Notice("%s", _("See apt-secure(8) manpage for repository creation and user configuration details."));
  127. return false;
  128. }
  129. static bool MessageInsecureRepository(bool const isError, char const * const msg, std::string const &repo)
  130. {
  131. std::string m;
  132. strprintf(m, msg, repo.c_str());
  133. return MessageInsecureRepository(isError, m);
  134. }
  135. /*}}}*/
  136. static bool AllowInsecureRepositories(char const * const msg, std::string const &repo,/*{{{*/
  137. metaIndex const * const MetaIndexParser, pkgAcqMetaClearSig * const TransactionManager, pkgAcquire::Item * const I)
  138. {
  139. if(MetaIndexParser->GetTrusted() == metaIndex::TRI_YES)
  140. return true;
  141. if (_config->FindB("Acquire::AllowInsecureRepositories") == true)
  142. {
  143. MessageInsecureRepository(false, msg, repo);
  144. return true;
  145. }
  146. MessageInsecureRepository(true, msg, repo);
  147. TransactionManager->AbortTransaction();
  148. I->Status = pkgAcquire::Item::StatError;
  149. return false;
  150. }
  151. /*}}}*/
  152. static HashStringList GetExpectedHashesFromFor(metaIndex * const Parser, std::string const &MetaKey)/*{{{*/
  153. {
  154. if (Parser == NULL)
  155. return HashStringList();
  156. metaIndex::checkSum * const R = Parser->Lookup(MetaKey);
  157. if (R == NULL)
  158. return HashStringList();
  159. return R->Hashes;
  160. }
  161. /*}}}*/
  162. // all ::HashesRequired and ::GetExpectedHashes implementations /*{{{*/
  163. /* ::GetExpectedHashes is abstract and has to be implemented by all subclasses.
  164. It is best to implement it as broadly as possible, while ::HashesRequired defaults
  165. to true and should be as restrictive as possible for false cases. Note that if
  166. a hash is returned by ::GetExpectedHashes it must match. Only if it doesn't
  167. ::HashesRequired is called to evaluate if its okay to have no hashes. */
  168. APT_CONST bool pkgAcqTransactionItem::HashesRequired() const
  169. {
  170. /* signed repositories obviously have a parser and good hashes.
  171. unsigned repositories, too, as even if we can't trust them for security,
  172. we can at least trust them for integrity of the download itself.
  173. Only repositories without a Release file can (obviously) not have
  174. hashes – and they are very uncommon and strongly discouraged */
  175. return TransactionManager->MetaIndexParser != NULL &&
  176. TransactionManager->MetaIndexParser->GetLoadedSuccessfully() == metaIndex::TRI_YES;
  177. }
  178. HashStringList pkgAcqTransactionItem::GetExpectedHashes() const
  179. {
  180. return GetExpectedHashesFor(GetMetaKey());
  181. }
  182. APT_CONST bool pkgAcqMetaBase::HashesRequired() const
  183. {
  184. // Release and co have no hashes 'by design'.
  185. return false;
  186. }
  187. HashStringList pkgAcqMetaBase::GetExpectedHashes() const
  188. {
  189. return HashStringList();
  190. }
  191. APT_CONST bool pkgAcqIndexDiffs::HashesRequired() const
  192. {
  193. /* We don't always have the diff of the downloaded pdiff file.
  194. What we have for sure is hashes for the uncompressed file,
  195. but rred uncompresses them on the fly while parsing, so not handled here.
  196. Hashes are (also) checked while searching for (next) patch to apply. */
  197. if (State == StateFetchDiff)
  198. return available_patches[0].download_hashes.empty() == false;
  199. return false;
  200. }
  201. HashStringList pkgAcqIndexDiffs::GetExpectedHashes() const
  202. {
  203. if (State == StateFetchDiff)
  204. return available_patches[0].download_hashes;
  205. return HashStringList();
  206. }
  207. APT_CONST bool pkgAcqIndexMergeDiffs::HashesRequired() const
  208. {
  209. /* @see #pkgAcqIndexDiffs::HashesRequired, with the difference that
  210. we can check the rred result after all patches are applied as
  211. we know the expected result rather than potentially apply more patches */
  212. if (State == StateFetchDiff)
  213. return patch.download_hashes.empty() == false;
  214. return State == StateApplyDiff;
  215. }
  216. HashStringList pkgAcqIndexMergeDiffs::GetExpectedHashes() const
  217. {
  218. if (State == StateFetchDiff)
  219. return patch.download_hashes;
  220. else if (State == StateApplyDiff)
  221. return GetExpectedHashesFor(Target.MetaKey);
  222. return HashStringList();
  223. }
  224. APT_CONST bool pkgAcqArchive::HashesRequired() const
  225. {
  226. return LocalSource == false;
  227. }
  228. HashStringList pkgAcqArchive::GetExpectedHashes() const
  229. {
  230. // figured out while parsing the records
  231. return ExpectedHashes;
  232. }
  233. APT_CONST bool pkgAcqFile::HashesRequired() const
  234. {
  235. // supplied as parameter at creation time, so the caller decides
  236. return ExpectedHashes.usable();
  237. }
  238. HashStringList pkgAcqFile::GetExpectedHashes() const
  239. {
  240. return ExpectedHashes;
  241. }
  242. /*}}}*/
  243. // Acquire::Item::QueueURI and specialisations from child classes /*{{{*/
  244. bool pkgAcquire::Item::QueueURI(pkgAcquire::ItemDesc &Item)
  245. {
  246. Owner->Enqueue(Item);
  247. return true;
  248. }
  249. /* The idea here is that an item isn't queued if it exists on disk and the
  250. transition manager was a hit as this means that the files it contains
  251. the checksums for can't be updated either (or they are and we are asking
  252. for a hashsum mismatch to happen which helps nobody) */
  253. bool pkgAcqTransactionItem::QueueURI(pkgAcquire::ItemDesc &Item)
  254. {
  255. std::string const FinalFile = GetFinalFilename();
  256. if (TransactionManager != NULL && TransactionManager->IMSHit == true &&
  257. FileExists(FinalFile) == true)
  258. {
  259. PartialFile = DestFile = FinalFile;
  260. Status = StatDone;
  261. return false;
  262. }
  263. return pkgAcquire::Item::QueueURI(Item);
  264. }
  265. /* The transition manager InRelease itself (or its older sisters-in-law
  266. Release & Release.gpg) is always queued as this allows us to rerun gpgv
  267. on it to verify that we aren't stalled with old files */
  268. bool pkgAcqMetaBase::QueueURI(pkgAcquire::ItemDesc &Item)
  269. {
  270. return pkgAcquire::Item::QueueURI(Item);
  271. }
  272. /* the Diff/Index needs to queue also the up-to-date complete index file
  273. to ensure that the list cleaner isn't eating it */
  274. bool pkgAcqDiffIndex::QueueURI(pkgAcquire::ItemDesc &Item)
  275. {
  276. if (pkgAcqTransactionItem::QueueURI(Item) == true)
  277. return true;
  278. QueueOnIMSHit();
  279. return false;
  280. }
  281. /*}}}*/
  282. // Acquire::Item::GetFinalFilename and specialisations for child classes /*{{{*/
  283. std::string pkgAcquire::Item::GetFinalFilename() const
  284. {
  285. return GetFinalFileNameFromURI(Desc.URI);
  286. }
  287. std::string pkgAcqDiffIndex::GetFinalFilename() const
  288. {
  289. // the logic we inherent from pkgAcqBaseIndex isn't what we need here
  290. return pkgAcquire::Item::GetFinalFilename();
  291. }
  292. std::string pkgAcqIndex::GetFinalFilename() const
  293. {
  294. std::string const FinalFile = GetFinalFileNameFromURI(Target.URI);
  295. return GetKeepCompressedFileName(FinalFile, Target);
  296. }
  297. std::string pkgAcqMetaSig::GetFinalFilename() const
  298. {
  299. return GetFinalFileNameFromURI(Target.URI);
  300. }
  301. std::string pkgAcqBaseIndex::GetFinalFilename() const
  302. {
  303. return GetFinalFileNameFromURI(Target.URI);
  304. }
  305. std::string pkgAcqMetaBase::GetFinalFilename() const
  306. {
  307. return GetFinalFileNameFromURI(Target.URI);
  308. }
  309. std::string pkgAcqArchive::GetFinalFilename() const
  310. {
  311. return _config->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename);
  312. }
  313. /*}}}*/
  314. // pkgAcqTransactionItem::GetMetaKey and specialisations for child classes /*{{{*/
  315. std::string pkgAcqTransactionItem::GetMetaKey() const
  316. {
  317. return Target.MetaKey;
  318. }
  319. std::string pkgAcqIndex::GetMetaKey() const
  320. {
  321. if (Stage == STAGE_DECOMPRESS_AND_VERIFY || CurrentCompressionExtension == "uncompressed")
  322. return Target.MetaKey;
  323. return Target.MetaKey + "." + CurrentCompressionExtension;
  324. }
  325. std::string pkgAcqDiffIndex::GetMetaKey() const
  326. {
  327. return Target.MetaKey + ".diff/Index";
  328. }
  329. /*}}}*/
  330. //pkgAcqTransactionItem::TransactionState and specialisations for child classes /*{{{*/
  331. bool pkgAcqTransactionItem::TransactionState(TransactionStates const state)
  332. {
  333. bool const Debug = _config->FindB("Debug::Acquire::Transaction", false);
  334. switch(state)
  335. {
  336. case TransactionAbort:
  337. if(Debug == true)
  338. std::clog << " Cancel: " << DestFile << std::endl;
  339. if (Status == pkgAcquire::Item::StatIdle)
  340. {
  341. Status = pkgAcquire::Item::StatDone;
  342. Dequeue();
  343. }
  344. break;
  345. case TransactionCommit:
  346. if(PartialFile.empty() == false)
  347. {
  348. bool sameFile = (PartialFile == DestFile);
  349. // we use symlinks on IMS-Hit to avoid copies
  350. if (RealFileExists(DestFile))
  351. {
  352. struct stat Buf;
  353. if (lstat(PartialFile.c_str(), &Buf) != -1)
  354. {
  355. if (S_ISLNK(Buf.st_mode) && Buf.st_size > 0)
  356. {
  357. char partial[Buf.st_size + 1];
  358. ssize_t const sp = readlink(PartialFile.c_str(), partial, Buf.st_size);
  359. if (sp == -1)
  360. _error->Errno("pkgAcqTransactionItem::TransactionState-sp", _("Failed to readlink %s"), PartialFile.c_str());
  361. else
  362. {
  363. partial[sp] = '\0';
  364. sameFile = (DestFile == partial);
  365. }
  366. }
  367. }
  368. else
  369. _error->Errno("pkgAcqTransactionItem::TransactionState-stat", _("Failed to stat %s"), PartialFile.c_str());
  370. }
  371. if (sameFile == false)
  372. {
  373. // ensure that even without lists-cleanup all compressions are nuked
  374. std::string FinalFile = GetFinalFileNameFromURI(Target.URI);
  375. if (FileExists(FinalFile))
  376. {
  377. if(Debug == true)
  378. std::clog << "rm " << FinalFile << " # " << DescURI() << std::endl;
  379. if (RemoveFile("TransactionStates-Cleanup", FinalFile) == false)
  380. return false;
  381. }
  382. for (auto const &ext: APT::Configuration::getCompressorExtensions())
  383. {
  384. auto const Final = FinalFile + ext;
  385. if (FileExists(Final))
  386. {
  387. if(Debug == true)
  388. std::clog << "rm " << Final << " # " << DescURI() << std::endl;
  389. if (RemoveFile("TransactionStates-Cleanup", Final) == false)
  390. return false;
  391. }
  392. }
  393. if(Debug == true)
  394. std::clog << "mv " << PartialFile << " -> "<< DestFile << " # " << DescURI() << std::endl;
  395. if (Rename(PartialFile, DestFile) == false)
  396. return false;
  397. }
  398. else if(Debug == true)
  399. std::clog << "keep " << PartialFile << " # " << DescURI() << std::endl;
  400. } else {
  401. if(Debug == true)
  402. std::clog << "rm " << DestFile << " # " << DescURI() << std::endl;
  403. if (RemoveFile("TransactionCommit", DestFile) == false)
  404. return false;
  405. }
  406. break;
  407. }
  408. return true;
  409. }
  410. bool pkgAcqMetaBase::TransactionState(TransactionStates const state)
  411. {
  412. // Do not remove InRelease on IMSHit of Release.gpg [yes, this is very edgecasey]
  413. if (TransactionManager->IMSHit == false)
  414. return pkgAcqTransactionItem::TransactionState(state);
  415. return true;
  416. }
  417. bool pkgAcqIndex::TransactionState(TransactionStates const state)
  418. {
  419. if (pkgAcqTransactionItem::TransactionState(state) == false)
  420. return false;
  421. switch (state)
  422. {
  423. case TransactionAbort:
  424. if (Stage == STAGE_DECOMPRESS_AND_VERIFY)
  425. {
  426. // keep the compressed file, but drop the decompressed
  427. EraseFileName.clear();
  428. if (PartialFile.empty() == false && flExtension(PartialFile) != CurrentCompressionExtension)
  429. RemoveFile("TransactionAbort", PartialFile);
  430. }
  431. break;
  432. case TransactionCommit:
  433. if (EraseFileName.empty() == false)
  434. RemoveFile("TransactionCommit", EraseFileName);
  435. break;
  436. }
  437. return true;
  438. }
  439. bool pkgAcqDiffIndex::TransactionState(TransactionStates const state)
  440. {
  441. if (pkgAcqTransactionItem::TransactionState(state) == false)
  442. return false;
  443. switch (state)
  444. {
  445. case TransactionCommit:
  446. break;
  447. case TransactionAbort:
  448. std::string const Partial = GetPartialFileNameFromURI(Target.URI);
  449. RemoveFile("TransactionAbort", Partial);
  450. break;
  451. }
  452. return true;
  453. }
  454. /*}}}*/
  455. class APT_HIDDEN NoActionItem : public pkgAcquire::Item /*{{{*/
  456. /* The sole purpose of this class is having an item which does nothing to
  457. reach its done state to prevent cleanup deleting the mentioned file.
  458. Handy in cases in which we know we have the file already, like IMS-Hits. */
  459. {
  460. IndexTarget const Target;
  461. public:
  462. virtual std::string DescURI() const APT_OVERRIDE {return Target.URI;};
  463. virtual HashStringList GetExpectedHashes() const APT_OVERRIDE {return HashStringList();};
  464. NoActionItem(pkgAcquire * const Owner, IndexTarget const &Target) :
  465. pkgAcquire::Item(Owner), Target(Target)
  466. {
  467. Status = StatDone;
  468. DestFile = GetFinalFileNameFromURI(Target.URI);
  469. }
  470. NoActionItem(pkgAcquire * const Owner, IndexTarget const &Target, std::string const &FinalFile) :
  471. pkgAcquire::Item(Owner), Target(Target)
  472. {
  473. Status = StatDone;
  474. DestFile = FinalFile;
  475. }
  476. };
  477. /*}}}*/
  478. // Acquire::Item::Item - Constructor /*{{{*/
  479. APT_IGNORE_DEPRECATED_PUSH
  480. pkgAcquire::Item::Item(pkgAcquire * const owner) :
  481. FileSize(0), PartialSize(0), Mode(0), ID(0), Complete(false), Local(false),
  482. QueueCounter(0), ExpectedAdditionalItems(0), Owner(owner), d(NULL)
  483. {
  484. Owner->Add(this);
  485. Status = StatIdle;
  486. }
  487. APT_IGNORE_DEPRECATED_POP
  488. /*}}}*/
  489. // Acquire::Item::~Item - Destructor /*{{{*/
  490. pkgAcquire::Item::~Item()
  491. {
  492. Owner->Remove(this);
  493. }
  494. /*}}}*/
  495. std::string pkgAcquire::Item::Custom600Headers() const /*{{{*/
  496. {
  497. return std::string();
  498. }
  499. /*}}}*/
  500. std::string pkgAcquire::Item::ShortDesc() const /*{{{*/
  501. {
  502. return DescURI();
  503. }
  504. /*}}}*/
  505. APT_CONST void pkgAcquire::Item::Finished() /*{{{*/
  506. {
  507. }
  508. /*}}}*/
  509. APT_PURE pkgAcquire * pkgAcquire::Item::GetOwner() const /*{{{*/
  510. {
  511. return Owner;
  512. }
  513. /*}}}*/
  514. APT_CONST pkgAcquire::ItemDesc &pkgAcquire::Item::GetItemDesc() /*{{{*/
  515. {
  516. return Desc;
  517. }
  518. /*}}}*/
  519. APT_CONST bool pkgAcquire::Item::IsTrusted() const /*{{{*/
  520. {
  521. return false;
  522. }
  523. /*}}}*/
  524. // Acquire::Item::Failed - Item failed to download /*{{{*/
  525. // ---------------------------------------------------------------------
  526. /* We return to an idle state if there are still other queues that could
  527. fetch this object */
  528. void pkgAcquire::Item::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)
  529. {
  530. if(ErrorText.empty())
  531. ErrorText = LookupTag(Message,"Message");
  532. if (QueueCounter <= 1)
  533. {
  534. /* This indicates that the file is not available right now but might
  535. be sometime later. If we do a retry cycle then this should be
  536. retried [CDROMs] */
  537. if (Cnf != NULL && Cnf->LocalOnly == true &&
  538. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  539. {
  540. Status = StatIdle;
  541. Dequeue();
  542. return;
  543. }
  544. switch (Status)
  545. {
  546. case StatIdle:
  547. case StatFetching:
  548. case StatDone:
  549. Status = StatError;
  550. break;
  551. case StatAuthError:
  552. case StatError:
  553. case StatTransientNetworkError:
  554. break;
  555. }
  556. Complete = false;
  557. Dequeue();
  558. }
  559. string const FailReason = LookupTag(Message, "FailReason");
  560. if (FailReason == "MaximumSizeExceeded")
  561. RenameOnError(MaximumSizeExceeded);
  562. else if (Status == StatAuthError)
  563. RenameOnError(HashSumMismatch);
  564. // report mirror failure back to LP if we actually use a mirror
  565. if (FailReason.empty() == false)
  566. ReportMirrorFailure(FailReason);
  567. else
  568. ReportMirrorFailure(ErrorText);
  569. if (QueueCounter > 1)
  570. Status = StatIdle;
  571. }
  572. /*}}}*/
  573. // Acquire::Item::Start - Item has begun to download /*{{{*/
  574. // ---------------------------------------------------------------------
  575. /* Stash status and the file size. Note that setting Complete means
  576. sub-phases of the acquire process such as decompresion are operating */
  577. void pkgAcquire::Item::Start(string const &/*Message*/, unsigned long long const Size)
  578. {
  579. Status = StatFetching;
  580. ErrorText.clear();
  581. if (FileSize == 0 && Complete == false)
  582. FileSize = Size;
  583. }
  584. /*}}}*/
  585. // Acquire::Item::VerifyDone - check if Item was downloaded OK /*{{{*/
  586. /* Note that hash-verification is 'hardcoded' in acquire-worker and has
  587. * already passed if this method is called. */
  588. bool pkgAcquire::Item::VerifyDone(std::string const &Message,
  589. pkgAcquire::MethodConfig const * const /*Cnf*/)
  590. {
  591. std::string const FileName = LookupTag(Message,"Filename");
  592. if (FileName.empty() == true)
  593. {
  594. Status = StatError;
  595. ErrorText = "Method gave a blank filename";
  596. return false;
  597. }
  598. return true;
  599. }
  600. /*}}}*/
  601. // Acquire::Item::Done - Item downloaded OK /*{{{*/
  602. void pkgAcquire::Item::Done(string const &/*Message*/, HashStringList const &Hashes,
  603. pkgAcquire::MethodConfig const * const /*Cnf*/)
  604. {
  605. // We just downloaded something..
  606. if (FileSize == 0)
  607. {
  608. unsigned long long const downloadedSize = Hashes.FileSize();
  609. if (downloadedSize != 0)
  610. {
  611. FileSize = downloadedSize;
  612. }
  613. }
  614. Status = StatDone;
  615. ErrorText = string();
  616. Owner->Dequeue(this);
  617. }
  618. /*}}}*/
  619. // Acquire::Item::Rename - Rename a file /*{{{*/
  620. // ---------------------------------------------------------------------
  621. /* This helper function is used by a lot of item methods as their final
  622. step */
  623. bool pkgAcquire::Item::Rename(string const &From,string const &To)
  624. {
  625. if (From == To || rename(From.c_str(),To.c_str()) == 0)
  626. return true;
  627. std::string S;
  628. strprintf(S, _("rename failed, %s (%s -> %s)."), strerror(errno),
  629. From.c_str(),To.c_str());
  630. Status = StatError;
  631. if (ErrorText.empty())
  632. ErrorText = S;
  633. else
  634. ErrorText = ErrorText + ": " + S;
  635. return false;
  636. }
  637. /*}}}*/
  638. void pkgAcquire::Item::Dequeue() /*{{{*/
  639. {
  640. Owner->Dequeue(this);
  641. }
  642. /*}}}*/
  643. bool pkgAcquire::Item::RenameOnError(pkgAcquire::Item::RenameOnErrorState const error)/*{{{*/
  644. {
  645. if (RealFileExists(DestFile))
  646. Rename(DestFile, DestFile + ".FAILED");
  647. std::string errtext;
  648. switch (error)
  649. {
  650. case HashSumMismatch:
  651. errtext = _("Hash Sum mismatch");
  652. Status = StatAuthError;
  653. ReportMirrorFailure("HashChecksumFailure");
  654. break;
  655. case SizeMismatch:
  656. errtext = _("Size mismatch");
  657. Status = StatAuthError;
  658. ReportMirrorFailure("SizeFailure");
  659. break;
  660. case InvalidFormat:
  661. errtext = _("Invalid file format");
  662. Status = StatError;
  663. // do not report as usually its not the mirrors fault, but Portal/Proxy
  664. break;
  665. case SignatureError:
  666. errtext = _("Signature error");
  667. Status = StatError;
  668. break;
  669. case NotClearsigned:
  670. strprintf(errtext, _("Clearsigned file isn't valid, got '%s' (does the network require authentication?)"), "NOSPLIT");
  671. Status = StatAuthError;
  672. break;
  673. case MaximumSizeExceeded:
  674. // the method is expected to report a good error for this
  675. Status = StatError;
  676. break;
  677. case PDiffError:
  678. // no handling here, done by callers
  679. break;
  680. }
  681. if (ErrorText.empty())
  682. ErrorText = errtext;
  683. return false;
  684. }
  685. /*}}}*/
  686. void pkgAcquire::Item::SetActiveSubprocess(const std::string &subprocess)/*{{{*/
  687. {
  688. ActiveSubprocess = subprocess;
  689. APT_IGNORE_DEPRECATED(Mode = ActiveSubprocess.c_str();)
  690. }
  691. /*}}}*/
  692. // Acquire::Item::ReportMirrorFailure /*{{{*/
  693. void pkgAcquire::Item::ReportMirrorFailure(string const &FailCode)
  694. {
  695. // we only act if a mirror was used at all
  696. if(UsedMirror.empty())
  697. return;
  698. #if 0
  699. std::cerr << "\nReportMirrorFailure: "
  700. << UsedMirror
  701. << " Uri: " << DescURI()
  702. << " FailCode: "
  703. << FailCode << std::endl;
  704. #endif
  705. string report = _config->Find("Methods::Mirror::ProblemReporting",
  706. "/usr/lib/apt/apt-report-mirror-failure");
  707. if(!FileExists(report))
  708. return;
  709. std::vector<char const*> Args;
  710. Args.push_back(report.c_str());
  711. Args.push_back(UsedMirror.c_str());
  712. Args.push_back(DescURI().c_str());
  713. Args.push_back(FailCode.c_str());
  714. Args.push_back(NULL);
  715. pid_t pid = ExecFork();
  716. if(pid < 0)
  717. {
  718. _error->Error("ReportMirrorFailure Fork failed");
  719. return;
  720. }
  721. else if(pid == 0)
  722. {
  723. execvp(Args[0], (char**)Args.data());
  724. std::cerr << "Could not exec " << Args[0] << std::endl;
  725. _exit(100);
  726. }
  727. if(!ExecWait(pid, "report-mirror-failure"))
  728. {
  729. _error->Warning("Couldn't report problem to '%s'",
  730. _config->Find("Methods::Mirror::ProblemReporting").c_str());
  731. }
  732. }
  733. /*}}}*/
  734. std::string pkgAcquire::Item::HashSum() const /*{{{*/
  735. {
  736. HashStringList const hashes = GetExpectedHashes();
  737. HashString const * const hs = hashes.find(NULL);
  738. return hs != NULL ? hs->toStr() : "";
  739. }
  740. /*}}}*/
  741. pkgAcqTransactionItem::pkgAcqTransactionItem(pkgAcquire * const Owner, /*{{{*/
  742. pkgAcqMetaClearSig * const transactionManager, IndexTarget const &target) :
  743. pkgAcquire::Item(Owner), d(NULL), Target(target), TransactionManager(transactionManager)
  744. {
  745. if (TransactionManager != this)
  746. TransactionManager->Add(this);
  747. }
  748. /*}}}*/
  749. pkgAcqTransactionItem::~pkgAcqTransactionItem() /*{{{*/
  750. {
  751. }
  752. /*}}}*/
  753. HashStringList pkgAcqTransactionItem::GetExpectedHashesFor(std::string const &MetaKey) const /*{{{*/
  754. {
  755. return GetExpectedHashesFromFor(TransactionManager->MetaIndexParser, MetaKey);
  756. }
  757. /*}}}*/
  758. // AcqMetaBase - Constructor /*{{{*/
  759. pkgAcqMetaBase::pkgAcqMetaBase(pkgAcquire * const Owner,
  760. pkgAcqMetaClearSig * const TransactionManager,
  761. std::vector<IndexTarget> const &IndexTargets,
  762. IndexTarget const &DataTarget)
  763. : pkgAcqTransactionItem(Owner, TransactionManager, DataTarget), d(NULL),
  764. IndexTargets(IndexTargets),
  765. AuthPass(false), IMSHit(false)
  766. {
  767. }
  768. /*}}}*/
  769. // AcqMetaBase::Add - Add a item to the current Transaction /*{{{*/
  770. void pkgAcqMetaBase::Add(pkgAcqTransactionItem * const I)
  771. {
  772. Transaction.push_back(I);
  773. }
  774. /*}}}*/
  775. // AcqMetaBase::AbortTransaction - Abort the current Transaction /*{{{*/
  776. void pkgAcqMetaBase::AbortTransaction()
  777. {
  778. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  779. std::clog << "AbortTransaction: " << TransactionManager << std::endl;
  780. // ensure the toplevel is in error state too
  781. for (std::vector<pkgAcqTransactionItem*>::iterator I = Transaction.begin();
  782. I != Transaction.end(); ++I)
  783. {
  784. (*I)->TransactionState(TransactionAbort);
  785. }
  786. Transaction.clear();
  787. }
  788. /*}}}*/
  789. // AcqMetaBase::TransactionHasError - Check for errors in Transaction /*{{{*/
  790. APT_PURE bool pkgAcqMetaBase::TransactionHasError() const
  791. {
  792. for (std::vector<pkgAcqTransactionItem*>::const_iterator I = Transaction.begin();
  793. I != Transaction.end(); ++I)
  794. {
  795. switch((*I)->Status) {
  796. case StatDone: break;
  797. case StatIdle: break;
  798. case StatAuthError: return true;
  799. case StatError: return true;
  800. case StatTransientNetworkError: return true;
  801. case StatFetching: break;
  802. }
  803. }
  804. return false;
  805. }
  806. /*}}}*/
  807. // AcqMetaBase::CommitTransaction - Commit a transaction /*{{{*/
  808. void pkgAcqMetaBase::CommitTransaction()
  809. {
  810. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  811. std::clog << "CommitTransaction: " << this << std::endl;
  812. // move new files into place *and* remove files that are not
  813. // part of the transaction but are still on disk
  814. for (std::vector<pkgAcqTransactionItem*>::iterator I = Transaction.begin();
  815. I != Transaction.end(); ++I)
  816. {
  817. (*I)->TransactionState(TransactionCommit);
  818. }
  819. Transaction.clear();
  820. }
  821. /*}}}*/
  822. // AcqMetaBase::TransactionStageCopy - Stage a file for copying /*{{{*/
  823. void pkgAcqMetaBase::TransactionStageCopy(pkgAcqTransactionItem * const I,
  824. const std::string &From,
  825. const std::string &To)
  826. {
  827. I->PartialFile = From;
  828. I->DestFile = To;
  829. }
  830. /*}}}*/
  831. // AcqMetaBase::TransactionStageRemoval - Stage a file for removal /*{{{*/
  832. void pkgAcqMetaBase::TransactionStageRemoval(pkgAcqTransactionItem * const I,
  833. const std::string &FinalFile)
  834. {
  835. I->PartialFile = "";
  836. I->DestFile = FinalFile;
  837. }
  838. /*}}}*/
  839. // AcqMetaBase::GenerateAuthWarning - Check gpg authentication error /*{{{*/
  840. bool pkgAcqMetaBase::CheckStopAuthentication(pkgAcquire::Item * const I, const std::string &Message)
  841. {
  842. // FIXME: this entire function can do now that we disallow going to
  843. // a unauthenticated state and can cleanly rollback
  844. string const Final = I->GetFinalFilename();
  845. if(FileExists(Final))
  846. {
  847. I->Status = StatTransientNetworkError;
  848. _error->Warning(_("An error occurred during the signature "
  849. "verification. The repository is not updated "
  850. "and the previous index files will be used. "
  851. "GPG error: %s: %s"),
  852. Desc.Description.c_str(),
  853. LookupTag(Message,"Message").c_str());
  854. RunScripts("APT::Update::Auth-Failure");
  855. return true;
  856. } else if (LookupTag(Message,"Message").find("NODATA") != string::npos) {
  857. /* Invalid signature file, reject (LP: #346386) (Closes: #627642) */
  858. _error->Error(_("GPG error: %s: %s"),
  859. Desc.Description.c_str(),
  860. LookupTag(Message,"Message").c_str());
  861. I->Status = StatAuthError;
  862. return true;
  863. } else {
  864. _error->Warning(_("GPG error: %s: %s"),
  865. Desc.Description.c_str(),
  866. LookupTag(Message,"Message").c_str());
  867. }
  868. // gpgv method failed
  869. ReportMirrorFailure("GPGFailure");
  870. return false;
  871. }
  872. /*}}}*/
  873. // AcqMetaBase::Custom600Headers - Get header for AcqMetaBase /*{{{*/
  874. // ---------------------------------------------------------------------
  875. string pkgAcqMetaBase::Custom600Headers() const
  876. {
  877. std::string Header = "\nIndex-File: true";
  878. std::string MaximumSize;
  879. strprintf(MaximumSize, "\nMaximum-Size: %i",
  880. _config->FindI("Acquire::MaxReleaseFileSize", 10*1000*1000));
  881. Header += MaximumSize;
  882. string const FinalFile = GetFinalFilename();
  883. struct stat Buf;
  884. if (stat(FinalFile.c_str(),&Buf) == 0)
  885. Header += "\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  886. return Header;
  887. }
  888. /*}}}*/
  889. // AcqMetaBase::QueueForSignatureVerify /*{{{*/
  890. void pkgAcqMetaBase::QueueForSignatureVerify(pkgAcqTransactionItem * const I, std::string const &File, std::string const &Signature)
  891. {
  892. AuthPass = true;
  893. I->Desc.URI = "gpgv:" + Signature;
  894. I->DestFile = File;
  895. QueueURI(I->Desc);
  896. I->SetActiveSubprocess("gpgv");
  897. }
  898. /*}}}*/
  899. // AcqMetaBase::CheckDownloadDone /*{{{*/
  900. bool pkgAcqMetaBase::CheckDownloadDone(pkgAcqTransactionItem * const I, const std::string &Message, HashStringList const &Hashes) const
  901. {
  902. // We have just finished downloading a Release file (it is not
  903. // verified yet)
  904. std::string const FileName = LookupTag(Message,"Filename");
  905. if (FileName != I->DestFile && RealFileExists(I->DestFile) == false)
  906. {
  907. I->Local = true;
  908. I->Desc.URI = "copy:" + FileName;
  909. I->QueueURI(I->Desc);
  910. return false;
  911. }
  912. // make sure to verify against the right file on I-M-S hit
  913. bool IMSHit = StringToBool(LookupTag(Message,"IMS-Hit"), false);
  914. if (IMSHit == false && Hashes.usable())
  915. {
  916. // detect IMS-Hits servers haven't detected by Hash comparison
  917. std::string const FinalFile = I->GetFinalFilename();
  918. if (RealFileExists(FinalFile) && Hashes.VerifyFile(FinalFile) == true)
  919. {
  920. IMSHit = true;
  921. RemoveFile("CheckDownloadDone", I->DestFile);
  922. }
  923. }
  924. if(IMSHit == true)
  925. {
  926. // for simplicity, the transaction manager is always InRelease
  927. // even if it doesn't exist.
  928. if (TransactionManager != NULL)
  929. TransactionManager->IMSHit = true;
  930. I->PartialFile = I->DestFile = I->GetFinalFilename();
  931. }
  932. // set Item to complete as the remaining work is all local (verify etc)
  933. I->Complete = true;
  934. return true;
  935. }
  936. /*}}}*/
  937. bool pkgAcqMetaBase::CheckAuthDone(string const &Message) /*{{{*/
  938. {
  939. // At this point, the gpgv method has succeeded, so there is a
  940. // valid signature from a key in the trusted keyring. We
  941. // perform additional verification of its contents, and use them
  942. // to verify the indexes we are about to download
  943. if (TransactionManager->IMSHit == false)
  944. {
  945. // open the last (In)Release if we have it
  946. std::string const FinalFile = GetFinalFilename();
  947. std::string FinalRelease;
  948. std::string FinalInRelease;
  949. if (APT::String::Endswith(FinalFile, "InRelease"))
  950. {
  951. FinalInRelease = FinalFile;
  952. FinalRelease = FinalFile.substr(0, FinalFile.length() - strlen("InRelease")) + "Release";
  953. }
  954. else
  955. {
  956. FinalInRelease = FinalFile.substr(0, FinalFile.length() - strlen("Release")) + "InRelease";
  957. FinalRelease = FinalFile;
  958. }
  959. if (RealFileExists(FinalInRelease) || RealFileExists(FinalRelease))
  960. {
  961. TransactionManager->LastMetaIndexParser = TransactionManager->MetaIndexParser->UnloadedClone();
  962. if (TransactionManager->LastMetaIndexParser != NULL)
  963. {
  964. _error->PushToStack();
  965. if (RealFileExists(FinalInRelease))
  966. TransactionManager->LastMetaIndexParser->Load(FinalInRelease, NULL);
  967. else
  968. TransactionManager->LastMetaIndexParser->Load(FinalRelease, NULL);
  969. // its unlikely to happen, but if what we have is bad ignore it
  970. if (_error->PendingError())
  971. {
  972. delete TransactionManager->LastMetaIndexParser;
  973. TransactionManager->LastMetaIndexParser = NULL;
  974. }
  975. _error->RevertToStack();
  976. }
  977. }
  978. }
  979. if (TransactionManager->MetaIndexParser->Load(DestFile, &ErrorText) == false)
  980. {
  981. Status = StatAuthError;
  982. return false;
  983. }
  984. if (!VerifyVendor(Message))
  985. {
  986. Status = StatAuthError;
  987. return false;
  988. }
  989. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  990. std::cerr << "Signature verification succeeded: "
  991. << DestFile << std::endl;
  992. // Download further indexes with verification
  993. QueueIndexes(true);
  994. return true;
  995. }
  996. /*}}}*/
  997. void pkgAcqMetaBase::QueueIndexes(bool const verify) /*{{{*/
  998. {
  999. // at this point the real Items are loaded in the fetcher
  1000. ExpectedAdditionalItems = 0;
  1001. bool metaBaseSupportsByHash = false;
  1002. if (TransactionManager != NULL && TransactionManager->MetaIndexParser != NULL)
  1003. metaBaseSupportsByHash = TransactionManager->MetaIndexParser->GetSupportsAcquireByHash();
  1004. for (std::vector <IndexTarget>::iterator Target = IndexTargets.begin();
  1005. Target != IndexTargets.end();
  1006. ++Target)
  1007. {
  1008. // all is an implementation detail. Users shouldn't use this as arch
  1009. // We need this support trickery here as e.g. Debian has binary-all files already,
  1010. // but arch:all packages are still in the arch:any files, so we would waste precious
  1011. // download time, bandwidth and diskspace for nothing, BUT Debian doesn't feature all
  1012. // in the set of supported architectures, so we can filter based on this property rather
  1013. // than invent an entirely new flag we would need to carry for all of eternity.
  1014. if (Target->Option(IndexTarget::ARCHITECTURE) == "all")
  1015. {
  1016. if (TransactionManager->MetaIndexParser->IsArchitectureSupported("all") == false)
  1017. continue;
  1018. if (TransactionManager->MetaIndexParser->IsArchitectureAllSupportedFor(*Target) == false)
  1019. continue;
  1020. }
  1021. bool trypdiff = Target->OptionBool(IndexTarget::PDIFFS);
  1022. if (verify == true)
  1023. {
  1024. if (TransactionManager->MetaIndexParser->Exists(Target->MetaKey) == false)
  1025. {
  1026. // optional targets that we do not have in the Release file are skipped
  1027. if (Target->IsOptional)
  1028. continue;
  1029. std::string const &arch = Target->Option(IndexTarget::ARCHITECTURE);
  1030. if (arch.empty() == false)
  1031. {
  1032. if (TransactionManager->MetaIndexParser->IsArchitectureSupported(arch) == false)
  1033. {
  1034. _error->Notice(_("Skipping acquire of configured file '%s' as repository '%s' doesn't support architecture '%s'"),
  1035. Target->MetaKey.c_str(), TransactionManager->Target.Description.c_str(), arch.c_str());
  1036. continue;
  1037. }
  1038. // if the architecture is officially supported but currently no packages for it available,
  1039. // ignore silently as this is pretty much the same as just shipping an empty file.
  1040. // if we don't know which architectures are supported, we do NOT ignore it to notify user about this
  1041. if (TransactionManager->MetaIndexParser->IsArchitectureSupported("*undefined*") == false)
  1042. continue;
  1043. }
  1044. Status = StatAuthError;
  1045. strprintf(ErrorText, _("Unable to find expected entry '%s' in Release file (Wrong sources.list entry or malformed file)"), Target->MetaKey.c_str());
  1046. return;
  1047. }
  1048. else
  1049. {
  1050. auto const hashes = GetExpectedHashesFor(Target->MetaKey);
  1051. if (hashes.usable() == false && hashes.empty() == false)
  1052. {
  1053. _error->Warning(_("Skipping acquire of configured file '%s' as repository '%s' provides only weak security information for it"),
  1054. Target->MetaKey.c_str(), TransactionManager->Target.Description.c_str());
  1055. continue;
  1056. }
  1057. }
  1058. // autoselect the compression method
  1059. std::vector<std::string> types = VectorizeString(Target->Option(IndexTarget::COMPRESSIONTYPES), ' ');
  1060. types.erase(std::remove_if(types.begin(), types.end(), [&](std::string const &t) {
  1061. if (t == "uncompressed")
  1062. return TransactionManager->MetaIndexParser->Exists(Target->MetaKey) == false;
  1063. std::string const MetaKey = Target->MetaKey + "." + t;
  1064. return TransactionManager->MetaIndexParser->Exists(MetaKey) == false;
  1065. }), types.end());
  1066. if (types.empty() == false)
  1067. {
  1068. std::ostringstream os;
  1069. // add the special compressiontype byhash first if supported
  1070. std::string const useByHashConf = Target->Option(IndexTarget::BY_HASH);
  1071. bool useByHash = false;
  1072. if(useByHashConf == "force")
  1073. useByHash = true;
  1074. else
  1075. useByHash = StringToBool(useByHashConf) == true && metaBaseSupportsByHash;
  1076. if (useByHash == true)
  1077. os << "by-hash ";
  1078. std::copy(types.begin(), types.end()-1, std::ostream_iterator<std::string>(os, " "));
  1079. os << *types.rbegin();
  1080. Target->Options["COMPRESSIONTYPES"] = os.str();
  1081. }
  1082. else
  1083. Target->Options["COMPRESSIONTYPES"].clear();
  1084. std::string filename = GetExistingFilename(GetFinalFileNameFromURI(Target->URI));
  1085. if (filename.empty() == false)
  1086. {
  1087. // if the Release file is a hit and we have an index it must be the current one
  1088. if (TransactionManager->IMSHit == true)
  1089. ;
  1090. else if (TransactionManager->LastMetaIndexParser != NULL)
  1091. {
  1092. // see if the file changed since the last Release file
  1093. // we use the uncompressed files as we might compress differently compared to the server,
  1094. // so the hashes might not match, even if they contain the same data.
  1095. HashStringList const newFile = GetExpectedHashesFromFor(TransactionManager->MetaIndexParser, Target->MetaKey);
  1096. HashStringList const oldFile = GetExpectedHashesFromFor(TransactionManager->LastMetaIndexParser, Target->MetaKey);
  1097. if (newFile != oldFile)
  1098. filename.clear();
  1099. }
  1100. else
  1101. filename.clear();
  1102. }
  1103. else
  1104. trypdiff = false; // no file to patch
  1105. if (filename.empty() == false)
  1106. {
  1107. new NoActionItem(Owner, *Target, filename);
  1108. std::string const idxfilename = GetFinalFileNameFromURI(Target->URI + ".diff/Index");
  1109. if (FileExists(idxfilename))
  1110. new NoActionItem(Owner, *Target, idxfilename);
  1111. continue;
  1112. }
  1113. // check if we have patches available
  1114. trypdiff &= TransactionManager->MetaIndexParser->Exists(Target->MetaKey + ".diff/Index");
  1115. }
  1116. else
  1117. {
  1118. // if we have no file to patch, no point in trying
  1119. trypdiff &= (GetExistingFilename(GetFinalFileNameFromURI(Target->URI)).empty() == false);
  1120. }
  1121. // no point in patching from local sources
  1122. if (trypdiff)
  1123. {
  1124. std::string const proto = Target->URI.substr(0, strlen("file:/"));
  1125. if (proto == "file:/" || proto == "copy:/" || proto == "cdrom:")
  1126. trypdiff = false;
  1127. }
  1128. // Queue the Index file (Packages, Sources, Translation-$foo, …)
  1129. if (trypdiff)
  1130. new pkgAcqDiffIndex(Owner, TransactionManager, *Target);
  1131. else
  1132. new pkgAcqIndex(Owner, TransactionManager, *Target);
  1133. }
  1134. }
  1135. /*}}}*/
  1136. bool pkgAcqMetaBase::VerifyVendor(string const &Message) /*{{{*/
  1137. {
  1138. string::size_type pos;
  1139. // check for missing sigs (that where not fatal because otherwise we had
  1140. // bombed earlier)
  1141. string missingkeys;
  1142. string msg = _("There is no public key available for the "
  1143. "following key IDs:\n");
  1144. pos = Message.find("NO_PUBKEY ");
  1145. if (pos != std::string::npos)
  1146. {
  1147. string::size_type start = pos+strlen("NO_PUBKEY ");
  1148. string Fingerprint = Message.substr(start, Message.find("\n")-start);
  1149. missingkeys += (Fingerprint);
  1150. }
  1151. if(!missingkeys.empty())
  1152. _error->Warning("%s", (msg + missingkeys).c_str());
  1153. string Transformed = TransactionManager->MetaIndexParser->GetExpectedDist();
  1154. if (Transformed == "../project/experimental")
  1155. {
  1156. Transformed = "experimental";
  1157. }
  1158. pos = Transformed.rfind('/');
  1159. if (pos != string::npos)
  1160. {
  1161. Transformed = Transformed.substr(0, pos);
  1162. }
  1163. if (Transformed == ".")
  1164. {
  1165. Transformed = "";
  1166. }
  1167. if (TransactionManager->MetaIndexParser->GetValidUntil() > 0)
  1168. {
  1169. time_t const invalid_since = time(NULL) - TransactionManager->MetaIndexParser->GetValidUntil();
  1170. if (invalid_since > 0)
  1171. {
  1172. std::string errmsg;
  1173. strprintf(errmsg,
  1174. // TRANSLATOR: The first %s is the URL of the bad Release file, the second is
  1175. // the time since then the file is invalid - formatted in the same way as in
  1176. // the download progress display (e.g. 7d 3h 42min 1s)
  1177. _("Release file for %s is expired (invalid since %s). "
  1178. "Updates for this repository will not be applied."),
  1179. Target.URI.c_str(), TimeToStr(invalid_since).c_str());
  1180. if (ErrorText.empty())
  1181. ErrorText = errmsg;
  1182. return _error->Error("%s", errmsg.c_str());
  1183. }
  1184. }
  1185. /* Did we get a file older than what we have? This is a last minute IMS hit and doubles
  1186. as a prevention of downgrading us to older (still valid) files */
  1187. if (TransactionManager->IMSHit == false && TransactionManager->LastMetaIndexParser != NULL &&
  1188. TransactionManager->LastMetaIndexParser->GetDate() > TransactionManager->MetaIndexParser->GetDate())
  1189. {
  1190. TransactionManager->IMSHit = true;
  1191. RemoveFile("VerifyVendor", DestFile);
  1192. PartialFile = DestFile = GetFinalFilename();
  1193. // load the 'old' file in the 'new' one instead of flipping pointers as
  1194. // the new one isn't owned by us, while the old one is so cleanup would be confused.
  1195. TransactionManager->MetaIndexParser->swapLoad(TransactionManager->LastMetaIndexParser);
  1196. delete TransactionManager->LastMetaIndexParser;
  1197. TransactionManager->LastMetaIndexParser = NULL;
  1198. }
  1199. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1200. {
  1201. std::cerr << "Got Codename: " << TransactionManager->MetaIndexParser->GetCodename() << std::endl;
  1202. std::cerr << "Expecting Dist: " << TransactionManager->MetaIndexParser->GetExpectedDist() << std::endl;
  1203. std::cerr << "Transformed Dist: " << Transformed << std::endl;
  1204. }
  1205. if (TransactionManager->MetaIndexParser->CheckDist(Transformed) == false)
  1206. {
  1207. // This might become fatal one day
  1208. // Status = StatAuthError;
  1209. // ErrorText = "Conflicting distribution; expected "
  1210. // + MetaIndexParser->GetExpectedDist() + " but got "
  1211. // + MetaIndexParser->GetCodename();
  1212. // return false;
  1213. if (!Transformed.empty())
  1214. {
  1215. _error->Warning(_("Conflicting distribution: %s (expected %s but got %s)"),
  1216. Desc.Description.c_str(),
  1217. Transformed.c_str(),
  1218. TransactionManager->MetaIndexParser->GetCodename().c_str());
  1219. }
  1220. }
  1221. return true;
  1222. }
  1223. /*}}}*/
  1224. pkgAcqMetaBase::~pkgAcqMetaBase()
  1225. {
  1226. }
  1227. pkgAcqMetaClearSig::pkgAcqMetaClearSig(pkgAcquire * const Owner, /*{{{*/
  1228. IndexTarget const &ClearsignedTarget,
  1229. IndexTarget const &DetachedDataTarget, IndexTarget const &DetachedSigTarget,
  1230. std::vector<IndexTarget> const &IndexTargets,
  1231. metaIndex * const MetaIndexParser) :
  1232. pkgAcqMetaIndex(Owner, this, ClearsignedTarget, DetachedSigTarget, IndexTargets),
  1233. d(NULL), ClearsignedTarget(ClearsignedTarget),
  1234. DetachedDataTarget(DetachedDataTarget),
  1235. MetaIndexParser(MetaIndexParser), LastMetaIndexParser(NULL)
  1236. {
  1237. // index targets + (worst case:) Release/Release.gpg
  1238. ExpectedAdditionalItems = IndexTargets.size() + 2;
  1239. TransactionManager->Add(this);
  1240. }
  1241. /*}}}*/
  1242. pkgAcqMetaClearSig::~pkgAcqMetaClearSig() /*{{{*/
  1243. {
  1244. if (LastMetaIndexParser != NULL)
  1245. delete LastMetaIndexParser;
  1246. }
  1247. /*}}}*/
  1248. // pkgAcqMetaClearSig::Custom600Headers - Insert custom request headers /*{{{*/
  1249. string pkgAcqMetaClearSig::Custom600Headers() const
  1250. {
  1251. string Header = pkgAcqMetaBase::Custom600Headers();
  1252. Header += "\nFail-Ignore: true";
  1253. std::string const key = TransactionManager->MetaIndexParser->GetSignedBy();
  1254. if (key.empty() == false)
  1255. Header += "\nSigned-By: " + key;
  1256. return Header;
  1257. }
  1258. /*}}}*/
  1259. bool pkgAcqMetaClearSig::VerifyDone(std::string const &Message, /*{{{*/
  1260. pkgAcquire::MethodConfig const * const Cnf)
  1261. {
  1262. Item::VerifyDone(Message, Cnf);
  1263. if (FileExists(DestFile) && !StartsWithGPGClearTextSignature(DestFile))
  1264. return RenameOnError(NotClearsigned);
  1265. return true;
  1266. }
  1267. /*}}}*/
  1268. // pkgAcqMetaClearSig::Done - We got a file /*{{{*/
  1269. void pkgAcqMetaClearSig::Done(std::string const &Message,
  1270. HashStringList const &Hashes,
  1271. pkgAcquire::MethodConfig const * const Cnf)
  1272. {
  1273. Item::Done(Message, Hashes, Cnf);
  1274. if(AuthPass == false)
  1275. {
  1276. if(CheckDownloadDone(this, Message, Hashes) == true)
  1277. QueueForSignatureVerify(this, DestFile, DestFile);
  1278. return;
  1279. }
  1280. else if(CheckAuthDone(Message) == true)
  1281. {
  1282. if (TransactionManager->IMSHit == false)
  1283. TransactionManager->TransactionStageCopy(this, DestFile, GetFinalFilename());
  1284. else if (RealFileExists(GetFinalFilename()) == false)
  1285. {
  1286. // We got an InRelease file IMSHit, but we haven't one, which means
  1287. // we had a valid Release/Release.gpg combo stepping in, which we have
  1288. // to 'acquire' now to ensure list cleanup isn't removing them
  1289. new NoActionItem(Owner, DetachedDataTarget);
  1290. new NoActionItem(Owner, DetachedSigTarget);
  1291. }
  1292. }
  1293. }
  1294. /*}}}*/
  1295. void pkgAcqMetaClearSig::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf) /*{{{*/
  1296. {
  1297. Item::Failed(Message, Cnf);
  1298. // we failed, we will not get additional items from this method
  1299. ExpectedAdditionalItems = 0;
  1300. if (AuthPass == false)
  1301. {
  1302. if (Status == StatAuthError || Status == StatTransientNetworkError)
  1303. {
  1304. // if we expected a ClearTextSignature (InRelease) but got a network
  1305. // error or got a file, but it wasn't valid, we end up here (see VerifyDone).
  1306. // As these is usually called by web-portals we do not try Release/Release.gpg
  1307. // as this is gonna fail anyway and instead abort our try (LP#346386)
  1308. TransactionManager->AbortTransaction();
  1309. return;
  1310. }
  1311. // Queue the 'old' InRelease file for removal if we try Release.gpg
  1312. // as otherwise the file will stay around and gives a false-auth
  1313. // impression (CVE-2012-0214)
  1314. TransactionManager->TransactionStageRemoval(this, GetFinalFilename());
  1315. Status = StatDone;
  1316. new pkgAcqMetaIndex(Owner, TransactionManager, DetachedDataTarget, DetachedSigTarget, IndexTargets);
  1317. }
  1318. else
  1319. {
  1320. if(CheckStopAuthentication(this, Message))
  1321. return;
  1322. // No Release file was present, or verification failed, so fall
  1323. // back to queueing Packages files without verification
  1324. // only allow going further if the user explicitly wants it
  1325. if(AllowInsecureRepositories(_("The repository '%s' is not signed."), ClearsignedTarget.Description, TransactionManager->MetaIndexParser, TransactionManager, this) == true)
  1326. {
  1327. Status = StatDone;
  1328. /* InRelease files become Release files, otherwise
  1329. * they would be considered as trusted later on */
  1330. string const FinalRelease = GetFinalFileNameFromURI(DetachedDataTarget.URI);
  1331. string const PartialRelease = GetPartialFileNameFromURI(DetachedDataTarget.URI);
  1332. string const FinalReleasegpg = GetFinalFileNameFromURI(DetachedSigTarget.URI);
  1333. string const FinalInRelease = GetFinalFilename();
  1334. Rename(DestFile, PartialRelease);
  1335. TransactionManager->TransactionStageCopy(this, PartialRelease, FinalRelease);
  1336. if (RealFileExists(FinalReleasegpg) || RealFileExists(FinalInRelease))
  1337. {
  1338. // open the last Release if we have it
  1339. if (TransactionManager->IMSHit == false)
  1340. {
  1341. TransactionManager->LastMetaIndexParser = TransactionManager->MetaIndexParser->UnloadedClone();
  1342. if (TransactionManager->LastMetaIndexParser != NULL)
  1343. {
  1344. _error->PushToStack();
  1345. if (RealFileExists(FinalInRelease))
  1346. TransactionManager->LastMetaIndexParser->Load(FinalInRelease, NULL);
  1347. else
  1348. TransactionManager->LastMetaIndexParser->Load(FinalRelease, NULL);
  1349. // its unlikely to happen, but if what we have is bad ignore it
  1350. if (_error->PendingError())
  1351. {
  1352. delete TransactionManager->LastMetaIndexParser;
  1353. TransactionManager->LastMetaIndexParser = NULL;
  1354. }
  1355. _error->RevertToStack();
  1356. }
  1357. }
  1358. }
  1359. // we parse the indexes here because at this point the user wanted
  1360. // a repository that may potentially harm him
  1361. if (TransactionManager->MetaIndexParser->Load(PartialRelease, &ErrorText) == false || VerifyVendor(Message) == false)
  1362. /* expired Release files are still a problem you need extra force for */;
  1363. else
  1364. QueueIndexes(true);
  1365. }
  1366. }
  1367. }
  1368. /*}}}*/
  1369. pkgAcqMetaIndex::pkgAcqMetaIndex(pkgAcquire * const Owner, /*{{{*/
  1370. pkgAcqMetaClearSig * const TransactionManager,
  1371. IndexTarget const &DataTarget,
  1372. IndexTarget const &DetachedSigTarget,
  1373. vector<IndexTarget> const &IndexTargets) :
  1374. pkgAcqMetaBase(Owner, TransactionManager, IndexTargets, DataTarget), d(NULL),
  1375. DetachedSigTarget(DetachedSigTarget)
  1376. {
  1377. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1378. std::clog << "New pkgAcqMetaIndex with TransactionManager "
  1379. << this->TransactionManager << std::endl;
  1380. DestFile = GetPartialFileNameFromURI(DataTarget.URI);
  1381. // Create the item
  1382. Desc.Description = DataTarget.Description;
  1383. Desc.Owner = this;
  1384. Desc.ShortDesc = DataTarget.ShortDesc;
  1385. Desc.URI = DataTarget.URI;
  1386. // we expect more item
  1387. ExpectedAdditionalItems = IndexTargets.size();
  1388. QueueURI(Desc);
  1389. }
  1390. /*}}}*/
  1391. void pkgAcqMetaIndex::Done(string const &Message, /*{{{*/
  1392. HashStringList const &Hashes,
  1393. pkgAcquire::MethodConfig const * const Cfg)
  1394. {
  1395. Item::Done(Message,Hashes,Cfg);
  1396. if(CheckDownloadDone(this, Message, Hashes))
  1397. {
  1398. // we have a Release file, now download the Signature, all further
  1399. // verify/queue for additional downloads will be done in the
  1400. // pkgAcqMetaSig::Done() code
  1401. new pkgAcqMetaSig(Owner, TransactionManager, DetachedSigTarget, this);
  1402. }
  1403. }
  1404. /*}}}*/
  1405. // pkgAcqMetaIndex::Failed - no Release file present /*{{{*/
  1406. void pkgAcqMetaIndex::Failed(string const &Message,
  1407. pkgAcquire::MethodConfig const * const Cnf)
  1408. {
  1409. pkgAcquire::Item::Failed(Message, Cnf);
  1410. Status = StatDone;
  1411. // No Release file was present so fall
  1412. // back to queueing Packages files without verification
  1413. // only allow going further if the user explicitly wants it
  1414. if(AllowInsecureRepositories(_("The repository '%s' does not have a Release file."), Target.Description, TransactionManager->MetaIndexParser, TransactionManager, this) == true)
  1415. {
  1416. // ensure old Release files are removed
  1417. TransactionManager->TransactionStageRemoval(this, GetFinalFilename());
  1418. // queue without any kind of hashsum support
  1419. QueueIndexes(false);
  1420. }
  1421. }
  1422. /*}}}*/
  1423. void pkgAcqMetaIndex::Finished() /*{{{*/
  1424. {
  1425. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1426. std::clog << "Finished: " << DestFile <<std::endl;
  1427. if(TransactionManager != NULL &&
  1428. TransactionManager->TransactionHasError() == false)
  1429. TransactionManager->CommitTransaction();
  1430. }
  1431. /*}}}*/
  1432. std::string pkgAcqMetaIndex::DescURI() const /*{{{*/
  1433. {
  1434. return Target.URI;
  1435. }
  1436. /*}}}*/
  1437. pkgAcqMetaIndex::~pkgAcqMetaIndex() {}
  1438. // AcqMetaSig::AcqMetaSig - Constructor /*{{{*/
  1439. pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire * const Owner,
  1440. pkgAcqMetaClearSig * const TransactionManager,
  1441. IndexTarget const &Target,
  1442. pkgAcqMetaIndex * const MetaIndex) :
  1443. pkgAcqTransactionItem(Owner, TransactionManager, Target), d(NULL), MetaIndex(MetaIndex)
  1444. {
  1445. DestFile = GetPartialFileNameFromURI(Target.URI);
  1446. // remove any partial downloaded sig-file in partial/.
  1447. // it may confuse proxies and is too small to warrant a
  1448. // partial download anyway
  1449. RemoveFile("pkgAcqMetaSig", DestFile);
  1450. // set the TransactionManager
  1451. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1452. std::clog << "New pkgAcqMetaSig with TransactionManager "
  1453. << TransactionManager << std::endl;
  1454. // Create the item
  1455. Desc.Description = Target.Description;
  1456. Desc.Owner = this;
  1457. Desc.ShortDesc = Target.ShortDesc;
  1458. Desc.URI = Target.URI;
  1459. // If we got a hit for Release, we will get one for Release.gpg too (or obscure errors),
  1460. // so we skip the download step and go instantly to verification
  1461. if (TransactionManager->IMSHit == true && RealFileExists(GetFinalFilename()))
  1462. {
  1463. Complete = true;
  1464. Status = StatDone;
  1465. PartialFile = DestFile = GetFinalFilename();
  1466. MetaIndexFileSignature = DestFile;
  1467. MetaIndex->QueueForSignatureVerify(this, MetaIndex->DestFile, DestFile);
  1468. }
  1469. else
  1470. QueueURI(Desc);
  1471. }
  1472. /*}}}*/
  1473. pkgAcqMetaSig::~pkgAcqMetaSig() /*{{{*/
  1474. {
  1475. }
  1476. /*}}}*/
  1477. // pkgAcqMetaSig::Custom600Headers - Insert custom request headers /*{{{*/
  1478. std::string pkgAcqMetaSig::Custom600Headers() const
  1479. {
  1480. std::string Header = pkgAcqTransactionItem::Custom600Headers();
  1481. std::string const key = TransactionManager->MetaIndexParser->GetSignedBy();
  1482. if (key.empty() == false)
  1483. Header += "\nSigned-By: " + key;
  1484. return Header;
  1485. }
  1486. /*}}}*/
  1487. // AcqMetaSig::Done - The signature was downloaded/verified /*{{{*/
  1488. void pkgAcqMetaSig::Done(string const &Message, HashStringList const &Hashes,
  1489. pkgAcquire::MethodConfig const * const Cfg)
  1490. {
  1491. if (MetaIndexFileSignature.empty() == false)
  1492. {
  1493. DestFile = MetaIndexFileSignature;
  1494. MetaIndexFileSignature.clear();
  1495. }
  1496. Item::Done(Message, Hashes, Cfg);
  1497. if(MetaIndex->AuthPass == false)
  1498. {
  1499. if(MetaIndex->CheckDownloadDone(this, Message, Hashes) == true)
  1500. {
  1501. // destfile will be modified to point to MetaIndexFile for the
  1502. // gpgv method, so we need to save it here
  1503. MetaIndexFileSignature = DestFile;
  1504. MetaIndex->QueueForSignatureVerify(this, MetaIndex->DestFile, DestFile);
  1505. }
  1506. return;
  1507. }
  1508. else if(MetaIndex->CheckAuthDone(Message) == true)
  1509. {
  1510. if (TransactionManager->IMSHit == false)
  1511. {
  1512. TransactionManager->TransactionStageCopy(this, DestFile, GetFinalFilename());
  1513. TransactionManager->TransactionStageCopy(MetaIndex, MetaIndex->DestFile, MetaIndex->GetFinalFilename());
  1514. }
  1515. }
  1516. }
  1517. /*}}}*/
  1518. void pkgAcqMetaSig::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)/*{{{*/
  1519. {
  1520. Item::Failed(Message,Cnf);
  1521. // check if we need to fail at this point
  1522. if (MetaIndex->AuthPass == true && MetaIndex->CheckStopAuthentication(this, Message))
  1523. return;
  1524. string const FinalRelease = MetaIndex->GetFinalFilename();
  1525. string const FinalReleasegpg = GetFinalFilename();
  1526. string const FinalInRelease = TransactionManager->GetFinalFilename();
  1527. if (RealFileExists(FinalReleasegpg) || RealFileExists(FinalInRelease))
  1528. {
  1529. std::string downgrade_msg;
  1530. strprintf(downgrade_msg, _("The repository '%s' is no longer signed."),
  1531. MetaIndex->Target.Description.c_str());
  1532. if(_config->FindB("Acquire::AllowDowngradeToInsecureRepositories"))
  1533. {
  1534. // meh, the users wants to take risks (we still mark the packages
  1535. // from this repository as unauthenticated)
  1536. _error->Warning("%s", downgrade_msg.c_str());
  1537. _error->Warning(_("This is normally not allowed, but the option "
  1538. "Acquire::AllowDowngradeToInsecureRepositories was "
  1539. "given to override it."));
  1540. Status = StatDone;
  1541. } else {
  1542. MessageInsecureRepository(true, downgrade_msg);
  1543. if (TransactionManager->IMSHit == false)
  1544. Rename(MetaIndex->DestFile, MetaIndex->DestFile + ".FAILED");
  1545. Item::Failed("Message: " + downgrade_msg, Cnf);
  1546. TransactionManager->AbortTransaction();
  1547. return;
  1548. }
  1549. }
  1550. // ensures that a Release.gpg file in the lists/ is removed by the transaction
  1551. TransactionManager->TransactionStageRemoval(this, DestFile);
  1552. // only allow going further if the user explicitly wants it
  1553. if (AllowInsecureRepositories(_("The repository '%s' is not signed."), MetaIndex->Target.Description, TransactionManager->MetaIndexParser, TransactionManager, this) == true)
  1554. {
  1555. if (RealFileExists(FinalReleasegpg) || RealFileExists(FinalInRelease))
  1556. {
  1557. // open the last Release if we have it
  1558. if (TransactionManager->IMSHit == false)
  1559. {
  1560. TransactionManager->LastMetaIndexParser = TransactionManager->MetaIndexParser->UnloadedClone();
  1561. if (TransactionManager->LastMetaIndexParser != NULL)
  1562. {
  1563. _error->PushToStack();
  1564. if (RealFileExists(FinalInRelease))
  1565. TransactionManager->LastMetaIndexParser->Load(FinalInRelease, NULL);
  1566. else
  1567. TransactionManager->LastMetaIndexParser->Load(FinalRelease, NULL);
  1568. // its unlikely to happen, but if what we have is bad ignore it
  1569. if (_error->PendingError())
  1570. {
  1571. delete TransactionManager->LastMetaIndexParser;
  1572. TransactionManager->LastMetaIndexParser = NULL;
  1573. }
  1574. _error->RevertToStack();
  1575. }
  1576. }
  1577. }
  1578. // we parse the indexes here because at this point the user wanted
  1579. // a repository that may potentially harm him
  1580. bool const GoodLoad = TransactionManager->MetaIndexParser->Load(MetaIndex->DestFile, &ErrorText);
  1581. if (MetaIndex->VerifyVendor(Message) == false)
  1582. /* expired Release files are still a problem you need extra force for */;
  1583. else
  1584. MetaIndex->QueueIndexes(GoodLoad);
  1585. TransactionManager->TransactionStageCopy(MetaIndex, MetaIndex->DestFile, MetaIndex->GetFinalFilename());
  1586. }
  1587. // FIXME: this is used often (e.g. in pkgAcqIndexTrans) so refactor
  1588. if (Cnf->LocalOnly == true ||
  1589. StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
  1590. {
  1591. // Ignore this
  1592. Status = StatDone;
  1593. }
  1594. }
  1595. /*}}}*/
  1596. // AcqBaseIndex - Constructor /*{{{*/
  1597. pkgAcqBaseIndex::pkgAcqBaseIndex(pkgAcquire * const Owner,
  1598. pkgAcqMetaClearSig * const TransactionManager,
  1599. IndexTarget const &Target)
  1600. : pkgAcqTransactionItem(Owner, TransactionManager, Target), d(NULL)
  1601. {
  1602. }
  1603. /*}}}*/
  1604. pkgAcqBaseIndex::~pkgAcqBaseIndex() {}
  1605. // AcqDiffIndex::AcqDiffIndex - Constructor /*{{{*/
  1606. // ---------------------------------------------------------------------
  1607. /* Get the DiffIndex file first and see if there are patches available
  1608. * If so, create a pkgAcqIndexDiffs fetcher that will get and apply the
  1609. * patches. If anything goes wrong in that process, it will fall back to
  1610. * the original packages file
  1611. */
  1612. pkgAcqDiffIndex::pkgAcqDiffIndex(pkgAcquire * const Owner,
  1613. pkgAcqMetaClearSig * const TransactionManager,
  1614. IndexTarget const &Target)
  1615. : pkgAcqBaseIndex(Owner, TransactionManager, Target), d(NULL), diffs(NULL)
  1616. {
  1617. Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
  1618. Desc.Owner = this;
  1619. Desc.Description = Target.Description + ".diff/Index";
  1620. Desc.ShortDesc = Target.ShortDesc;
  1621. Desc.URI = Target.URI + ".diff/Index";
  1622. DestFile = GetPartialFileNameFromURI(Desc.URI);
  1623. if(Debug)
  1624. std::clog << "pkgAcqDiffIndex: " << Desc.URI << std::endl;
  1625. QueueURI(Desc);
  1626. }
  1627. /*}}}*/
  1628. // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
  1629. // ---------------------------------------------------------------------
  1630. /* The only header we use is the last-modified header. */
  1631. string pkgAcqDiffIndex::Custom600Headers() const
  1632. {
  1633. if (TransactionManager->LastMetaIndexParser != NULL)
  1634. return "\nIndex-File: true";
  1635. string const Final = GetFinalFilename();
  1636. if(Debug)
  1637. std::clog << "Custom600Header-IMS: " << Final << std::endl;
  1638. struct stat Buf;
  1639. if (stat(Final.c_str(),&Buf) != 0)
  1640. return "\nIndex-File: true";
  1641. return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  1642. }
  1643. /*}}}*/
  1644. void pkgAcqDiffIndex::QueueOnIMSHit() const /*{{{*/
  1645. {
  1646. // list cleanup needs to know that this file as well as the already
  1647. // present index is ours, so we create an empty diff to save it for us
  1648. new pkgAcqIndexDiffs(Owner, TransactionManager, Target);
  1649. }
  1650. /*}}}*/
  1651. bool pkgAcqDiffIndex::ParseDiffIndex(string const &IndexDiffFile) /*{{{*/
  1652. {
  1653. // failing here is fine: our caller will take care of trying to
  1654. // get the complete file if patching fails
  1655. if(Debug)
  1656. std::clog << "pkgAcqDiffIndex::ParseIndexDiff() " << IndexDiffFile
  1657. << std::endl;
  1658. FileFd Fd(IndexDiffFile,FileFd::ReadOnly);
  1659. pkgTagFile TF(&Fd);
  1660. if (Fd.IsOpen() == false || Fd.Failed())
  1661. return false;
  1662. pkgTagSection Tags;
  1663. if(unlikely(TF.Step(Tags) == false))
  1664. return false;
  1665. HashStringList ServerHashes;
  1666. unsigned long long ServerSize = 0;
  1667. for (char const * const * type = HashString::SupportedHashes(); *type != NULL; ++type)
  1668. {
  1669. std::string tagname = *type;
  1670. tagname.append("-Current");
  1671. std::string const tmp = Tags.FindS(tagname.c_str());
  1672. if (tmp.empty() == true)
  1673. continue;
  1674. string hash;
  1675. unsigned long long size;
  1676. std::stringstream ss(tmp);
  1677. ss >> hash >> size;
  1678. if (unlikely(hash.empty() == true))
  1679. continue;
  1680. if (unlikely(ServerSize != 0 && ServerSize != size))
  1681. continue;
  1682. ServerHashes.push_back(HashString(*type, hash));
  1683. ServerSize = size;
  1684. }
  1685. if (ServerHashes.usable() == false)
  1686. {
  1687. if (Debug == true)
  1688. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": Did not find a good hashsum in the index" << std::endl;
  1689. return false;
  1690. }
  1691. std::string const CurrentPackagesFile = GetFinalFileNameFromURI(Target.URI);
  1692. HashStringList const TargetFileHashes = GetExpectedHashesFor(Target.MetaKey);
  1693. if (TargetFileHashes.usable() == false || ServerHashes != TargetFileHashes)
  1694. {
  1695. if (Debug == true)
  1696. {
  1697. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": Index has different hashes than parser, probably older, so fail pdiffing" << std::endl;
  1698. printHashSumComparision(CurrentPackagesFile, ServerHashes, TargetFileHashes);
  1699. }
  1700. return false;
  1701. }
  1702. HashStringList LocalHashes;
  1703. // try avoiding calculating the hash here as this is costly
  1704. if (TransactionManager->LastMetaIndexParser != NULL)
  1705. LocalHashes = GetExpectedHashesFromFor(TransactionManager->LastMetaIndexParser, Target.MetaKey);
  1706. if (LocalHashes.usable() == false)
  1707. {
  1708. FileFd fd(CurrentPackagesFile, FileFd::ReadOnly, FileFd::Auto);
  1709. Hashes LocalHashesCalc(ServerHashes);
  1710. LocalHashesCalc.AddFD(fd);
  1711. LocalHashes = LocalHashesCalc.GetHashStringList();
  1712. }
  1713. if (ServerHashes == LocalHashes)
  1714. {
  1715. // we have the same sha1 as the server so we are done here
  1716. if(Debug)
  1717. std::clog << "pkgAcqDiffIndex: Package file " << CurrentPackagesFile << " is up-to-date" << std::endl;
  1718. QueueOnIMSHit();
  1719. return true;
  1720. }
  1721. if(Debug)
  1722. std::clog << "Server-Current: " << ServerHashes.find(NULL)->toStr() << " and we start at "
  1723. << CurrentPackagesFile << " " << LocalHashes.FileSize() << " " << LocalHashes.find(NULL)->toStr() << std::endl;
  1724. // historically, older hashes have more info than newer ones, so start
  1725. // collecting with older ones first to avoid implementing complicated
  1726. // information merging techniques… a failure is after all always
  1727. // recoverable with a complete file and hashes aren't changed that often.
  1728. std::vector<char const *> types;
  1729. for (char const * const * type = HashString::SupportedHashes(); *type != NULL; ++type)
  1730. types.push_back(*type);
  1731. // parse all of (provided) history
  1732. vector<DiffInfo> available_patches;
  1733. bool firstAcceptedHashes = true;
  1734. for (auto type = types.crbegin(); type != types.crend(); ++type)
  1735. {
  1736. if (LocalHashes.find(*type) == NULL)
  1737. continue;
  1738. std::string tagname = *type;
  1739. tagname.append("-History");
  1740. std::string const tmp = Tags.FindS(tagname.c_str());
  1741. if (tmp.empty() == true)
  1742. continue;
  1743. string hash, filename;
  1744. unsigned long long size;
  1745. std::stringstream ss(tmp);
  1746. while (ss >> hash >> size >> filename)
  1747. {
  1748. if (unlikely(hash.empty() == true || filename.empty() == true))
  1749. continue;
  1750. // see if we have a record for this file already
  1751. std::vector<DiffInfo>::iterator cur = available_patches.begin();
  1752. for (; cur != available_patches.end(); ++cur)
  1753. {
  1754. if (cur->file != filename)
  1755. continue;
  1756. cur->result_hashes.push_back(HashString(*type, hash));
  1757. break;
  1758. }
  1759. if (cur != available_patches.end())
  1760. continue;
  1761. if (firstAcceptedHashes == true)
  1762. {
  1763. DiffInfo next;
  1764. next.file = filename;
  1765. next.result_hashes.push_back(HashString(*type, hash));
  1766. next.result_hashes.FileSize(size);
  1767. available_patches.push_back(next);
  1768. }
  1769. else
  1770. {
  1771. if (Debug == true)
  1772. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": File " << filename
  1773. << " wasn't in the list for the first parsed hash! (history)" << std::endl;
  1774. break;
  1775. }
  1776. }
  1777. firstAcceptedHashes = false;
  1778. }
  1779. if (unlikely(available_patches.empty() == true))
  1780. {
  1781. if (Debug)
  1782. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": "
  1783. << "Couldn't find any patches for the patch series." << std::endl;
  1784. return false;
  1785. }
  1786. for (auto type = types.crbegin(); type != types.crend(); ++type)
  1787. {
  1788. if (LocalHashes.find(*type) == NULL)
  1789. continue;
  1790. std::string tagname = *type;
  1791. tagname.append("-Patches");
  1792. std::string const tmp = Tags.FindS(tagname.c_str());
  1793. if (tmp.empty() == true)
  1794. continue;
  1795. string hash, filename;
  1796. unsigned long long size;
  1797. std::stringstream ss(tmp);
  1798. while (ss >> hash >> size >> filename)
  1799. {
  1800. if (unlikely(hash.empty() == true || filename.empty() == true))
  1801. continue;
  1802. // see if we have a record for this file already
  1803. std::vector<DiffInfo>::iterator cur = available_patches.begin();
  1804. for (; cur != available_patches.end(); ++cur)
  1805. {
  1806. if (cur->file != filename)
  1807. continue;
  1808. if (cur->patch_hashes.empty())
  1809. cur->patch_hashes.FileSize(size);
  1810. cur->patch_hashes.push_back(HashString(*type, hash));
  1811. break;
  1812. }
  1813. if (cur != available_patches.end())
  1814. continue;
  1815. if (Debug == true)
  1816. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": File " << filename
  1817. << " wasn't in the list for the first parsed hash! (patches)" << std::endl;
  1818. break;
  1819. }
  1820. }
  1821. for (auto type = types.crbegin(); type != types.crend(); ++type)
  1822. {
  1823. std::string tagname = *type;
  1824. tagname.append("-Download");
  1825. std::string const tmp = Tags.FindS(tagname.c_str());
  1826. if (tmp.empty() == true)
  1827. continue;
  1828. string hash, filename;
  1829. unsigned long long size;
  1830. std::stringstream ss(tmp);
  1831. // FIXME: all of pdiff supports only .gz compressed patches
  1832. while (ss >> hash >> size >> filename)
  1833. {
  1834. if (unlikely(hash.empty() == true || filename.empty() == true))
  1835. continue;
  1836. if (unlikely(APT::String::Endswith(filename, ".gz") == false))
  1837. continue;
  1838. filename.erase(filename.length() - 3);
  1839. // see if we have a record for this file already
  1840. std::vector<DiffInfo>::iterator cur = available_patches.begin();
  1841. for (; cur != available_patches.end(); ++cur)
  1842. {
  1843. if (cur->file != filename)
  1844. continue;
  1845. if (cur->download_hashes.empty())
  1846. cur->download_hashes.FileSize(size);
  1847. cur->download_hashes.push_back(HashString(*type, hash));
  1848. break;
  1849. }
  1850. if (cur != available_patches.end())
  1851. continue;
  1852. if (Debug == true)
  1853. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": File " << filename
  1854. << " wasn't in the list for the first parsed hash! (download)" << std::endl;
  1855. break;
  1856. }
  1857. }
  1858. bool foundStart = false;
  1859. for (std::vector<DiffInfo>::iterator cur = available_patches.begin();
  1860. cur != available_patches.end(); ++cur)
  1861. {
  1862. if (LocalHashes != cur->result_hashes)
  1863. continue;
  1864. available_patches.erase(available_patches.begin(), cur);
  1865. foundStart = true;
  1866. break;
  1867. }
  1868. if (foundStart == false || unlikely(available_patches.empty() == true))
  1869. {
  1870. if (Debug)
  1871. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": "
  1872. << "Couldn't find the start of the patch series." << std::endl;
  1873. return false;
  1874. }
  1875. // patching with too many files is rather slow compared to a fast download
  1876. unsigned long const fileLimit = _config->FindI("Acquire::PDiffs::FileLimit", 0);
  1877. if (fileLimit != 0 && fileLimit < available_patches.size())
  1878. {
  1879. if (Debug)
  1880. std::clog << "Need " << available_patches.size() << " diffs (Limit is " << fileLimit
  1881. << ") so fallback to complete download" << std::endl;
  1882. return false;
  1883. }
  1884. // calculate the size of all patches we have to get
  1885. unsigned short const sizeLimitPercent = _config->FindI("Acquire::PDiffs::SizeLimit", 100);
  1886. if (sizeLimitPercent > 0 && TransactionManager->MetaIndexParser != nullptr)
  1887. {
  1888. // compressed case
  1889. unsigned long long downloadSize = std::accumulate(available_patches.begin(),
  1890. available_patches.end(), 0llu, [](unsigned long long const T, DiffInfo const &I) {
  1891. return T + I.download_hashes.FileSize();
  1892. });
  1893. if (downloadSize != 0)
  1894. {
  1895. unsigned long long downloadSizeIdx = 0;
  1896. auto const types = VectorizeString(Target.Option(IndexTarget::COMPRESSIONTYPES), ' ');
  1897. for (auto const &t : types)
  1898. {
  1899. std::string MetaKey = Target.MetaKey;
  1900. if (t != "uncompressed")
  1901. MetaKey += '.' + t;
  1902. HashStringList const hsl = GetExpectedHashesFor(MetaKey);
  1903. if (unlikely(hsl.usable() == false))
  1904. continue;
  1905. downloadSizeIdx = hsl.FileSize();
  1906. break;
  1907. }
  1908. unsigned long long const sizeLimit = downloadSizeIdx * sizeLimitPercent;
  1909. if ((sizeLimit/100) < downloadSize)
  1910. {
  1911. if (Debug)
  1912. std::clog << "Need " << downloadSize << " compressed bytes (Limit is " << (sizeLimit/100) << ", "
  1913. << "original is " << downloadSizeIdx << ") so fallback to complete download" << std::endl;
  1914. return false;
  1915. }
  1916. }
  1917. // uncompressed case
  1918. downloadSize = std::accumulate(available_patches.begin(),
  1919. available_patches.end(), 0llu, [](unsigned long long const T, DiffInfo const &I) {
  1920. return T + I.patch_hashes.FileSize();
  1921. });
  1922. if (downloadSize != 0)
  1923. {
  1924. unsigned long long const downloadSizeIdx = ServerSize;
  1925. unsigned long long const sizeLimit = downloadSizeIdx * sizeLimitPercent;
  1926. if ((sizeLimit/100) < downloadSize)
  1927. {
  1928. if (Debug)
  1929. std::clog << "Need " << downloadSize << " uncompressed bytes (Limit is " << (sizeLimit/100) << ", "
  1930. << "original is " << downloadSizeIdx << ") so fallback to complete download" << std::endl;
  1931. return false;
  1932. }
  1933. }
  1934. }
  1935. // we have something, queue the diffs
  1936. string::size_type const last_space = Description.rfind(" ");
  1937. if(last_space != string::npos)
  1938. Description.erase(last_space, Description.size()-last_space);
  1939. /* decide if we should download patches one by one or in one go:
  1940. The first is good if the server merges patches, but many don't so client
  1941. based merging can be attempt in which case the second is better.
  1942. "bad things" will happen if patches are merged on the server,
  1943. but client side merging is attempt as well */
  1944. bool pdiff_merge = _config->FindB("Acquire::PDiffs::Merge", true);
  1945. if (pdiff_merge == true)
  1946. {
  1947. // reprepro adds this flag if it has merged patches on the server
  1948. std::string const precedence = Tags.FindS("X-Patch-Precedence");
  1949. pdiff_merge = (precedence != "merged");
  1950. }
  1951. // clean the plate
  1952. {
  1953. std::string const Final = GetExistingFilename(CurrentPackagesFile);
  1954. if (unlikely(Final.empty())) // because we wouldn't be called in such a case
  1955. return false;
  1956. std::string const PartialFile = GetPartialFileNameFromURI(Target.URI);
  1957. if (FileExists(PartialFile) && RemoveFile("Bootstrap-linking", PartialFile) == false)
  1958. {
  1959. if (Debug)
  1960. std::clog << "Bootstrap-linking for patching " << CurrentPackagesFile
  1961. << " by removing stale " << PartialFile << " failed!" << std::endl;
  1962. return false;
  1963. }
  1964. for (auto const &ext : APT::Configuration::getCompressorExtensions())
  1965. {
  1966. std::string const Partial = PartialFile + ext;
  1967. if (FileExists(Partial) && RemoveFile("Bootstrap-linking", Partial) == false)
  1968. {
  1969. if (Debug)
  1970. std::clog << "Bootstrap-linking for patching " << CurrentPackagesFile
  1971. << " by removing stale " << Partial << " failed!" << std::endl;
  1972. return false;
  1973. }
  1974. }
  1975. std::string const Ext = Final.substr(CurrentPackagesFile.length());
  1976. std::string const Partial = PartialFile + Ext;
  1977. if (symlink(Final.c_str(), Partial.c_str()) != 0)
  1978. {
  1979. if (Debug)
  1980. std::clog << "Bootstrap-linking for patching " << CurrentPackagesFile
  1981. << " by linking " << Final << " to " << Partial << " failed!" << std::endl;
  1982. return false;
  1983. }
  1984. }
  1985. if (pdiff_merge == false)
  1986. new pkgAcqIndexDiffs(Owner, TransactionManager, Target, available_patches);
  1987. else
  1988. {
  1989. diffs = new std::vector<pkgAcqIndexMergeDiffs*>(available_patches.size());
  1990. for(size_t i = 0; i < available_patches.size(); ++i)
  1991. (*diffs)[i] = new pkgAcqIndexMergeDiffs(Owner, TransactionManager,
  1992. Target,
  1993. available_patches[i],
  1994. diffs);
  1995. }
  1996. Complete = false;
  1997. Status = StatDone;
  1998. Dequeue();
  1999. return true;
  2000. }
  2001. /*}}}*/
  2002. void pkgAcqDiffIndex::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)/*{{{*/
  2003. {
  2004. Item::Failed(Message,Cnf);
  2005. Status = StatDone;
  2006. if(Debug)
  2007. std::clog << "pkgAcqDiffIndex failed: " << Desc.URI << " with " << Message << std::endl
  2008. << "Falling back to normal index file acquire" << std::endl;
  2009. new pkgAcqIndex(Owner, TransactionManager, Target);
  2010. }
  2011. /*}}}*/
  2012. void pkgAcqDiffIndex::Done(string const &Message,HashStringList const &Hashes, /*{{{*/
  2013. pkgAcquire::MethodConfig const * const Cnf)
  2014. {
  2015. if(Debug)
  2016. std::clog << "pkgAcqDiffIndex::Done(): " << Desc.URI << std::endl;
  2017. Item::Done(Message, Hashes, Cnf);
  2018. string const FinalFile = GetFinalFilename();
  2019. if(StringToBool(LookupTag(Message,"IMS-Hit"),false))
  2020. DestFile = FinalFile;
  2021. if(ParseDiffIndex(DestFile) == false)
  2022. {
  2023. Failed("Message: Couldn't parse pdiff index", Cnf);
  2024. // queue for final move - this should happen even if we fail
  2025. // while parsing (e.g. on sizelimit) and download the complete file.
  2026. TransactionManager->TransactionStageCopy(this, DestFile, FinalFile);
  2027. return;
  2028. }
  2029. TransactionManager->TransactionStageCopy(this, DestFile, FinalFile);
  2030. Complete = true;
  2031. Status = StatDone;
  2032. Dequeue();
  2033. return;
  2034. }
  2035. /*}}}*/
  2036. pkgAcqDiffIndex::~pkgAcqDiffIndex()
  2037. {
  2038. if (diffs != NULL)
  2039. delete diffs;
  2040. }
  2041. // AcqIndexDiffs::AcqIndexDiffs - Constructor /*{{{*/
  2042. // ---------------------------------------------------------------------
  2043. /* The package diff is added to the queue. one object is constructed
  2044. * for each diff and the index
  2045. */
  2046. pkgAcqIndexDiffs::pkgAcqIndexDiffs(pkgAcquire * const Owner,
  2047. pkgAcqMetaClearSig * const TransactionManager,
  2048. IndexTarget const &Target,
  2049. vector<DiffInfo> const &diffs)
  2050. : pkgAcqBaseIndex(Owner, TransactionManager, Target), d(NULL),
  2051. available_patches(diffs)
  2052. {
  2053. DestFile = GetKeepCompressedFileName(GetPartialFileNameFromURI(Target.URI), Target);
  2054. Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
  2055. Desc.Owner = this;
  2056. Description = Target.Description;
  2057. Desc.ShortDesc = Target.ShortDesc;
  2058. if(available_patches.empty() == true)
  2059. {
  2060. // we are done (yeah!), check hashes against the final file
  2061. DestFile = GetKeepCompressedFileName(GetFinalFileNameFromURI(Target.URI), Target);
  2062. Finish(true);
  2063. }
  2064. else
  2065. {
  2066. State = StateFetchDiff;
  2067. QueueNextDiff();
  2068. }
  2069. }
  2070. /*}}}*/
  2071. void pkgAcqIndexDiffs::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)/*{{{*/
  2072. {
  2073. Item::Failed(Message,Cnf);
  2074. Status = StatDone;
  2075. DestFile = GetKeepCompressedFileName(GetPartialFileNameFromURI(Target.URI), Target);
  2076. if(Debug)
  2077. std::clog << "pkgAcqIndexDiffs failed: " << Desc.URI << " with " << Message << std::endl
  2078. << "Falling back to normal index file acquire " << std::endl;
  2079. RenameOnError(PDiffError);
  2080. std::string const patchname = GetDiffsPatchFileName(DestFile);
  2081. if (RealFileExists(patchname))
  2082. Rename(patchname, patchname + ".FAILED");
  2083. std::string const UnpatchedFile = GetExistingFilename(GetPartialFileNameFromURI(Target.URI));
  2084. if (UnpatchedFile.empty() == false && FileExists(UnpatchedFile))
  2085. Rename(UnpatchedFile, UnpatchedFile + ".FAILED");
  2086. new pkgAcqIndex(Owner, TransactionManager, Target);
  2087. Finish();
  2088. }
  2089. /*}}}*/
  2090. // Finish - helper that cleans the item out of the fetcher queue /*{{{*/
  2091. void pkgAcqIndexDiffs::Finish(bool allDone)
  2092. {
  2093. if(Debug)
  2094. std::clog << "pkgAcqIndexDiffs::Finish(): "
  2095. << allDone << " "
  2096. << Desc.URI << std::endl;
  2097. // we restore the original name, this is required, otherwise
  2098. // the file will be cleaned
  2099. if(allDone)
  2100. {
  2101. std::string const Final = GetKeepCompressedFileName(GetFinalFilename(), Target);
  2102. TransactionManager->TransactionStageCopy(this, DestFile, Final);
  2103. // this is for the "real" finish
  2104. Complete = true;
  2105. Status = StatDone;
  2106. Dequeue();
  2107. if(Debug)
  2108. std::clog << "\n\nallDone: " << DestFile << "\n" << std::endl;
  2109. return;
  2110. }
  2111. else
  2112. DestFile.clear();
  2113. if(Debug)
  2114. std::clog << "Finishing: " << Desc.URI << std::endl;
  2115. Complete = false;
  2116. Status = StatDone;
  2117. Dequeue();
  2118. return;
  2119. }
  2120. /*}}}*/
  2121. bool pkgAcqIndexDiffs::QueueNextDiff() /*{{{*/
  2122. {
  2123. // calc sha1 of the just patched file
  2124. std::string const PartialFile = GetExistingFilename(GetPartialFileNameFromURI(Target.URI));
  2125. if(unlikely(PartialFile.empty()))
  2126. {
  2127. Failed("Message: The file " + GetPartialFileNameFromURI(Target.URI) + " isn't available", NULL);
  2128. return false;
  2129. }
  2130. FileFd fd(PartialFile, FileFd::ReadOnly, FileFd::Extension);
  2131. Hashes LocalHashesCalc;
  2132. LocalHashesCalc.AddFD(fd);
  2133. HashStringList const LocalHashes = LocalHashesCalc.GetHashStringList();
  2134. if(Debug)
  2135. std::clog << "QueueNextDiff: " << PartialFile << " (" << LocalHashes.find(NULL)->toStr() << ")" << std::endl;
  2136. HashStringList const TargetFileHashes = GetExpectedHashesFor(Target.MetaKey);
  2137. if (unlikely(LocalHashes.usable() == false || TargetFileHashes.usable() == false))
  2138. {
  2139. Failed("Local/Expected hashes are not usable for " + PartialFile, NULL);
  2140. return false;
  2141. }
  2142. // final file reached before all patches are applied
  2143. if(LocalHashes == TargetFileHashes)
  2144. {
  2145. Finish(true);
  2146. return true;
  2147. }
  2148. // remove all patches until the next matching patch is found
  2149. // this requires the Index file to be ordered
  2150. available_patches.erase(available_patches.begin(),
  2151. std::find_if(available_patches.begin(), available_patches.end(), [&](DiffInfo const &I) {
  2152. return I.result_hashes == LocalHashes;
  2153. }));
  2154. // error checking and falling back if no patch was found
  2155. if(available_patches.empty() == true)
  2156. {
  2157. Failed("No patches left to reach target for " + PartialFile, NULL);
  2158. return false;
  2159. }
  2160. // queue the right diff
  2161. Desc.URI = Target.URI + ".diff/" + available_patches[0].file + ".gz";
  2162. Desc.Description = Description + " " + available_patches[0].file + string(".pdiff");
  2163. DestFile = GetKeepCompressedFileName(GetPartialFileNameFromURI(Target.URI + ".diff/" + available_patches[0].file), Target);
  2164. if(Debug)
  2165. std::clog << "pkgAcqIndexDiffs::QueueNextDiff(): " << Desc.URI << std::endl;
  2166. QueueURI(Desc);
  2167. return true;
  2168. }
  2169. /*}}}*/
  2170. void pkgAcqIndexDiffs::Done(string const &Message, HashStringList const &Hashes, /*{{{*/
  2171. pkgAcquire::MethodConfig const * const Cnf)
  2172. {
  2173. if (Debug)
  2174. std::clog << "pkgAcqIndexDiffs::Done(): " << Desc.URI << std::endl;
  2175. Item::Done(Message, Hashes, Cnf);
  2176. std::string const UncompressedUnpatchedFile = GetPartialFileNameFromURI(Target.URI);
  2177. std::string const UnpatchedFile = GetExistingFilename(UncompressedUnpatchedFile);
  2178. std::string const PatchFile = GetDiffsPatchFileName(UnpatchedFile);
  2179. std::string const PatchedFile = GetKeepCompressedFileName(UncompressedUnpatchedFile, Target);
  2180. switch (State)
  2181. {
  2182. // success in downloading a diff, enter ApplyDiff state
  2183. case StateFetchDiff:
  2184. Rename(DestFile, PatchFile);
  2185. DestFile = GetKeepCompressedFileName(UncompressedUnpatchedFile + "-patched", Target);
  2186. if(Debug)
  2187. std::clog << "Sending to rred method: " << UnpatchedFile << std::endl;
  2188. State = StateApplyDiff;
  2189. Local = true;
  2190. Desc.URI = "rred:" + UnpatchedFile;
  2191. QueueURI(Desc);
  2192. SetActiveSubprocess("rred");
  2193. return;
  2194. // success in download/apply a diff, queue next (if needed)
  2195. case StateApplyDiff:
  2196. // remove the just applied patch and base file
  2197. available_patches.erase(available_patches.begin());
  2198. RemoveFile("pkgAcqIndexDiffs::Done", PatchFile);
  2199. RemoveFile("pkgAcqIndexDiffs::Done", UnpatchedFile);
  2200. if(Debug)
  2201. std::clog << "Moving patched file in place: " << std::endl
  2202. << DestFile << " -> " << PatchedFile << std::endl;
  2203. Rename(DestFile, PatchedFile);
  2204. // see if there is more to download
  2205. if(available_patches.empty() == false)
  2206. {
  2207. new pkgAcqIndexDiffs(Owner, TransactionManager, Target, available_patches);
  2208. Finish();
  2209. } else {
  2210. DestFile = PatchedFile;
  2211. Finish(true);
  2212. }
  2213. return;
  2214. }
  2215. }
  2216. /*}}}*/
  2217. std::string pkgAcqIndexDiffs::Custom600Headers() const /*{{{*/
  2218. {
  2219. if(State != StateApplyDiff)
  2220. return pkgAcqBaseIndex::Custom600Headers();
  2221. std::ostringstream patchhashes;
  2222. HashStringList const ExpectedHashes = available_patches[0].patch_hashes;
  2223. for (HashStringList::const_iterator hs = ExpectedHashes.begin(); hs != ExpectedHashes.end(); ++hs)
  2224. patchhashes << "\nPatch-0-" << hs->HashType() << "-Hash: " << hs->HashValue();
  2225. patchhashes << pkgAcqBaseIndex::Custom600Headers();
  2226. return patchhashes.str();
  2227. }
  2228. /*}}}*/
  2229. pkgAcqIndexDiffs::~pkgAcqIndexDiffs() {}
  2230. // AcqIndexMergeDiffs::AcqIndexMergeDiffs - Constructor /*{{{*/
  2231. pkgAcqIndexMergeDiffs::pkgAcqIndexMergeDiffs(pkgAcquire * const Owner,
  2232. pkgAcqMetaClearSig * const TransactionManager,
  2233. IndexTarget const &Target,
  2234. DiffInfo const &patch,
  2235. std::vector<pkgAcqIndexMergeDiffs*> const * const allPatches)
  2236. : pkgAcqBaseIndex(Owner, TransactionManager, Target), d(NULL),
  2237. patch(patch), allPatches(allPatches), State(StateFetchDiff)
  2238. {
  2239. Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
  2240. Desc.Owner = this;
  2241. Description = Target.Description;
  2242. Desc.ShortDesc = Target.ShortDesc;
  2243. Desc.URI = Target.URI + ".diff/" + patch.file + ".gz";
  2244. Desc.Description = Description + " " + patch.file + ".pdiff";
  2245. DestFile = GetPartialFileNameFromURI(Desc.URI);
  2246. if(Debug)
  2247. std::clog << "pkgAcqIndexMergeDiffs: " << Desc.URI << std::endl;
  2248. QueueURI(Desc);
  2249. }
  2250. /*}}}*/
  2251. void pkgAcqIndexMergeDiffs::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)/*{{{*/
  2252. {
  2253. if(Debug)
  2254. std::clog << "pkgAcqIndexMergeDiffs failed: " << Desc.URI << " with " << Message << std::endl;
  2255. Item::Failed(Message,Cnf);
  2256. Status = StatDone;
  2257. // check if we are the first to fail, otherwise we are done here
  2258. State = StateDoneDiff;
  2259. for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
  2260. I != allPatches->end(); ++I)
  2261. if ((*I)->State == StateErrorDiff)
  2262. return;
  2263. // first failure means we should fallback
  2264. State = StateErrorDiff;
  2265. if (Debug)
  2266. std::clog << "Falling back to normal index file acquire" << std::endl;
  2267. RenameOnError(PDiffError);
  2268. std::string const patchname = GetPartialFileNameFromURI(Desc.URI);
  2269. if (RealFileExists(patchname))
  2270. Rename(patchname, patchname + ".FAILED");
  2271. std::string const UnpatchedFile = GetExistingFilename(GetPartialFileNameFromURI(Target.URI));
  2272. if (UnpatchedFile.empty() == false && FileExists(UnpatchedFile))
  2273. Rename(UnpatchedFile, UnpatchedFile + ".FAILED");
  2274. DestFile.clear();
  2275. new pkgAcqIndex(Owner, TransactionManager, Target);
  2276. }
  2277. /*}}}*/
  2278. void pkgAcqIndexMergeDiffs::Done(string const &Message, HashStringList const &Hashes, /*{{{*/
  2279. pkgAcquire::MethodConfig const * const Cnf)
  2280. {
  2281. if(Debug)
  2282. std::clog << "pkgAcqIndexMergeDiffs::Done(): " << Desc.URI << std::endl;
  2283. Item::Done(Message, Hashes, Cnf);
  2284. std::string const UncompressedUnpatchedFile = GetPartialFileNameFromURI(Target.URI);
  2285. std::string const UnpatchedFile = GetExistingFilename(UncompressedUnpatchedFile);
  2286. std::string const PatchFile = GetMergeDiffsPatchFileName(UnpatchedFile, patch.file);
  2287. std::string const PatchedFile = GetKeepCompressedFileName(UncompressedUnpatchedFile, Target);
  2288. switch (State)
  2289. {
  2290. case StateFetchDiff:
  2291. Rename(DestFile, PatchFile);
  2292. // check if this is the last completed diff
  2293. State = StateDoneDiff;
  2294. for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
  2295. I != allPatches->end(); ++I)
  2296. if ((*I)->State != StateDoneDiff)
  2297. {
  2298. if(Debug)
  2299. std::clog << "Not the last done diff in the batch: " << Desc.URI << std::endl;
  2300. return;
  2301. }
  2302. // this is the last completed diff, so we are ready to apply now
  2303. DestFile = GetKeepCompressedFileName(UncompressedUnpatchedFile + "-patched", Target);
  2304. if(Debug)
  2305. std::clog << "Sending to rred method: " << UnpatchedFile << std::endl;
  2306. State = StateApplyDiff;
  2307. Local = true;
  2308. Desc.URI = "rred:" + UnpatchedFile;
  2309. QueueURI(Desc);
  2310. SetActiveSubprocess("rred");
  2311. return;
  2312. case StateApplyDiff:
  2313. // success in download & apply all diffs, finialize and clean up
  2314. if(Debug)
  2315. std::clog << "Queue patched file in place: " << std::endl
  2316. << DestFile << " -> " << PatchedFile << std::endl;
  2317. // queue for copy by the transaction manager
  2318. TransactionManager->TransactionStageCopy(this, DestFile, GetKeepCompressedFileName(GetFinalFilename(), Target));
  2319. // ensure the ed's are gone regardless of list-cleanup
  2320. for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
  2321. I != allPatches->end(); ++I)
  2322. RemoveFile("pkgAcqIndexMergeDiffs::Done", GetMergeDiffsPatchFileName(UnpatchedFile, (*I)->patch.file));
  2323. RemoveFile("pkgAcqIndexMergeDiffs::Done", UnpatchedFile);
  2324. // all set and done
  2325. Complete = true;
  2326. if(Debug)
  2327. std::clog << "allDone: " << DestFile << "\n" << std::endl;
  2328. return;
  2329. case StateDoneDiff: _error->Fatal("Done called for %s which is in an invalid Done state", PatchFile.c_str()); break;
  2330. case StateErrorDiff: _error->Fatal("Done called for %s which is in an invalid Error state", PatchFile.c_str()); break;
  2331. }
  2332. }
  2333. /*}}}*/
  2334. std::string pkgAcqIndexMergeDiffs::Custom600Headers() const /*{{{*/
  2335. {
  2336. if(State != StateApplyDiff)
  2337. return pkgAcqBaseIndex::Custom600Headers();
  2338. std::ostringstream patchhashes;
  2339. unsigned int seen_patches = 0;
  2340. for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
  2341. I != allPatches->end(); ++I)
  2342. {
  2343. HashStringList const ExpectedHashes = (*I)->patch.patch_hashes;
  2344. for (HashStringList::const_iterator hs = ExpectedHashes.begin(); hs != ExpectedHashes.end(); ++hs)
  2345. patchhashes << "\nPatch-" << seen_patches << "-" << hs->HashType() << "-Hash: " << hs->HashValue();
  2346. ++seen_patches;
  2347. }
  2348. patchhashes << pkgAcqBaseIndex::Custom600Headers();
  2349. return patchhashes.str();
  2350. }
  2351. /*}}}*/
  2352. pkgAcqIndexMergeDiffs::~pkgAcqIndexMergeDiffs() {}
  2353. // AcqIndex::AcqIndex - Constructor /*{{{*/
  2354. pkgAcqIndex::pkgAcqIndex(pkgAcquire * const Owner,
  2355. pkgAcqMetaClearSig * const TransactionManager,
  2356. IndexTarget const &Target)
  2357. : pkgAcqBaseIndex(Owner, TransactionManager, Target), d(NULL), Stage(STAGE_DOWNLOAD),
  2358. CompressionExtensions(Target.Option(IndexTarget::COMPRESSIONTYPES))
  2359. {
  2360. Init(Target.URI, Target.Description, Target.ShortDesc);
  2361. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  2362. std::clog << "New pkgIndex with TransactionManager "
  2363. << TransactionManager << std::endl;
  2364. }
  2365. /*}}}*/
  2366. // AcqIndex::Init - defered Constructor /*{{{*/
  2367. static void NextCompressionExtension(std::string &CurrentCompressionExtension, std::string &CompressionExtensions, bool const preview)
  2368. {
  2369. size_t const nextExt = CompressionExtensions.find(' ');
  2370. if (nextExt == std::string::npos)
  2371. {
  2372. CurrentCompressionExtension = CompressionExtensions;
  2373. if (preview == false)
  2374. CompressionExtensions.clear();
  2375. }
  2376. else
  2377. {
  2378. CurrentCompressionExtension = CompressionExtensions.substr(0, nextExt);
  2379. if (preview == false)
  2380. CompressionExtensions = CompressionExtensions.substr(nextExt+1);
  2381. }
  2382. }
  2383. void pkgAcqIndex::Init(string const &URI, string const &URIDesc,
  2384. string const &ShortDesc)
  2385. {
  2386. Stage = STAGE_DOWNLOAD;
  2387. DestFile = GetPartialFileNameFromURI(URI);
  2388. NextCompressionExtension(CurrentCompressionExtension, CompressionExtensions, false);
  2389. if (CurrentCompressionExtension == "uncompressed")
  2390. {
  2391. Desc.URI = URI;
  2392. }
  2393. else if (CurrentCompressionExtension == "by-hash")
  2394. {
  2395. NextCompressionExtension(CurrentCompressionExtension, CompressionExtensions, true);
  2396. if(unlikely(TransactionManager->MetaIndexParser == NULL || CurrentCompressionExtension.empty()))
  2397. return;
  2398. if (CurrentCompressionExtension != "uncompressed")
  2399. {
  2400. Desc.URI = URI + '.' + CurrentCompressionExtension;
  2401. DestFile = DestFile + '.' + CurrentCompressionExtension;
  2402. }
  2403. HashStringList const Hashes = GetExpectedHashes();
  2404. HashString const * const TargetHash = Hashes.find(NULL);
  2405. if (unlikely(TargetHash == nullptr))
  2406. return;
  2407. std::string const ByHash = "/by-hash/" + TargetHash->HashType() + "/" + TargetHash->HashValue();
  2408. size_t const trailing_slash = Desc.URI.find_last_of("/");
  2409. if (unlikely(trailing_slash == std::string::npos))
  2410. return;
  2411. Desc.URI = Desc.URI.replace(
  2412. trailing_slash,
  2413. Desc.URI.substr(trailing_slash+1).size()+1,
  2414. ByHash);
  2415. }
  2416. else if (unlikely(CurrentCompressionExtension.empty()))
  2417. return;
  2418. else
  2419. {
  2420. Desc.URI = URI + '.' + CurrentCompressionExtension;
  2421. DestFile = DestFile + '.' + CurrentCompressionExtension;
  2422. }
  2423. Desc.Description = URIDesc;
  2424. Desc.Owner = this;
  2425. Desc.ShortDesc = ShortDesc;
  2426. QueueURI(Desc);
  2427. }
  2428. /*}}}*/
  2429. // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
  2430. // ---------------------------------------------------------------------
  2431. /* The only header we use is the last-modified header. */
  2432. string pkgAcqIndex::Custom600Headers() const
  2433. {
  2434. string msg = "\nIndex-File: true";
  2435. if (TransactionManager->LastMetaIndexParser == NULL)
  2436. {
  2437. std::string const Final = GetFinalFilename();
  2438. struct stat Buf;
  2439. if (stat(Final.c_str(),&Buf) == 0)
  2440. msg += "\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  2441. }
  2442. if(Target.IsOptional)
  2443. msg += "\nFail-Ignore: true";
  2444. return msg;
  2445. }
  2446. /*}}}*/
  2447. // AcqIndex::Failed - getting the indexfile failed /*{{{*/
  2448. void pkgAcqIndex::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)
  2449. {
  2450. Item::Failed(Message,Cnf);
  2451. // authorisation matches will not be fixed by other compression types
  2452. if (Status != StatAuthError)
  2453. {
  2454. if (CompressionExtensions.empty() == false)
  2455. {
  2456. Init(Target.URI, Desc.Description, Desc.ShortDesc);
  2457. Status = StatIdle;
  2458. return;
  2459. }
  2460. }
  2461. if(Target.IsOptional && GetExpectedHashes().empty() && Stage == STAGE_DOWNLOAD)
  2462. Status = StatDone;
  2463. else
  2464. TransactionManager->AbortTransaction();
  2465. }
  2466. /*}}}*/
  2467. // AcqIndex::Done - Finished a fetch /*{{{*/
  2468. // ---------------------------------------------------------------------
  2469. /* This goes through a number of states.. On the initial fetch the
  2470. method could possibly return an alternate filename which points
  2471. to the uncompressed version of the file. If this is so the file
  2472. is copied into the partial directory. In all other cases the file
  2473. is decompressed with a compressed uri. */
  2474. void pkgAcqIndex::Done(string const &Message,
  2475. HashStringList const &Hashes,
  2476. pkgAcquire::MethodConfig const * const Cfg)
  2477. {
  2478. Item::Done(Message,Hashes,Cfg);
  2479. switch(Stage)
  2480. {
  2481. case STAGE_DOWNLOAD:
  2482. StageDownloadDone(Message);
  2483. break;
  2484. case STAGE_DECOMPRESS_AND_VERIFY:
  2485. StageDecompressDone();
  2486. break;
  2487. }
  2488. }
  2489. /*}}}*/
  2490. // AcqIndex::StageDownloadDone - Queue for decompress and verify /*{{{*/
  2491. void pkgAcqIndex::StageDownloadDone(string const &Message)
  2492. {
  2493. Local = true;
  2494. Complete = true;
  2495. std::string const AltFilename = LookupTag(Message,"Alt-Filename");
  2496. std::string Filename = LookupTag(Message,"Filename");
  2497. // we need to verify the file against the current Release file again
  2498. // on if-modfied-since hit to avoid a stale attack against us
  2499. if(StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  2500. {
  2501. // copy FinalFile into partial/ so that we check the hash again
  2502. string const FinalFile = GetExistingFilename(GetFinalFileNameFromURI(Target.URI));
  2503. if (symlink(FinalFile.c_str(), DestFile.c_str()) != 0)
  2504. _error->WarningE("pkgAcqIndex::StageDownloadDone", "Symlinking final file %s back to %s failed", FinalFile.c_str(), DestFile.c_str());
  2505. else
  2506. {
  2507. EraseFileName = DestFile;
  2508. Filename = DestFile;
  2509. }
  2510. Stage = STAGE_DECOMPRESS_AND_VERIFY;
  2511. Desc.URI = "store:" + Filename;
  2512. QueueURI(Desc);
  2513. SetActiveSubprocess(::URI(Desc.URI).Access);
  2514. return;
  2515. }
  2516. // methods like file:// give us an alternative (uncompressed) file
  2517. else if (Target.KeepCompressed == false && AltFilename.empty() == false)
  2518. {
  2519. if (CurrentCompressionExtension != "uncompressed")
  2520. DestFile.erase(DestFile.length() - (CurrentCompressionExtension.length() + 1));
  2521. Filename = AltFilename;
  2522. }
  2523. // Methods like e.g. "file:" will give us a (compressed) FileName that is
  2524. // not the "DestFile" we set, in this case we uncompress from the local file
  2525. else if (Filename != DestFile && RealFileExists(DestFile) == false)
  2526. {
  2527. // symlinking ensures that the filename can be used for compression detection
  2528. // that is e.g. needed for by-hash which has no extension over file
  2529. if (symlink(Filename.c_str(),DestFile.c_str()) != 0)
  2530. _error->WarningE("pkgAcqIndex::StageDownloadDone", "Symlinking file %s to %s failed", Filename.c_str(), DestFile.c_str());
  2531. else
  2532. {
  2533. EraseFileName = DestFile;
  2534. Filename = DestFile;
  2535. }
  2536. }
  2537. Stage = STAGE_DECOMPRESS_AND_VERIFY;
  2538. DestFile = GetKeepCompressedFileName(GetPartialFileNameFromURI(Target.URI), Target);
  2539. if (Filename != DestFile && flExtension(Filename) == flExtension(DestFile))
  2540. Desc.URI = "copy:" + Filename;
  2541. else
  2542. Desc.URI = "store:" + Filename;
  2543. if (DestFile == Filename)
  2544. {
  2545. if (CurrentCompressionExtension == "uncompressed")
  2546. return StageDecompressDone();
  2547. DestFile = "/dev/null";
  2548. }
  2549. if (EraseFileName.empty())
  2550. EraseFileName = Filename;
  2551. // queue uri for the next stage
  2552. QueueURI(Desc);
  2553. SetActiveSubprocess(::URI(Desc.URI).Access);
  2554. }
  2555. /*}}}*/
  2556. // AcqIndex::StageDecompressDone - Final verification /*{{{*/
  2557. void pkgAcqIndex::StageDecompressDone()
  2558. {
  2559. if (DestFile == "/dev/null")
  2560. DestFile = GetKeepCompressedFileName(GetPartialFileNameFromURI(Target.URI), Target);
  2561. // Done, queue for rename on transaction finished
  2562. TransactionManager->TransactionStageCopy(this, DestFile, GetFinalFilename());
  2563. }
  2564. /*}}}*/
  2565. pkgAcqIndex::~pkgAcqIndex() {}
  2566. // AcqArchive::AcqArchive - Constructor /*{{{*/
  2567. // ---------------------------------------------------------------------
  2568. /* This just sets up the initial fetch environment and queues the first
  2569. possibilitiy */
  2570. pkgAcqArchive::pkgAcqArchive(pkgAcquire * const Owner,pkgSourceList * const Sources,
  2571. pkgRecords * const Recs,pkgCache::VerIterator const &Version,
  2572. string &StoreFilename) :
  2573. Item(Owner), d(NULL), LocalSource(false), Version(Version), Sources(Sources), Recs(Recs),
  2574. StoreFilename(StoreFilename), Vf(Version.FileList()),
  2575. Trusted(false)
  2576. {
  2577. Retries = _config->FindI("Acquire::Retries",0);
  2578. if (Version.Arch() == 0)
  2579. {
  2580. _error->Error(_("I wasn't able to locate a file for the %s package. "
  2581. "This might mean you need to manually fix this package. "
  2582. "(due to missing arch)"),
  2583. Version.ParentPkg().FullName().c_str());
  2584. return;
  2585. }
  2586. /* We need to find a filename to determine the extension. We make the
  2587. assumption here that all the available sources for this version share
  2588. the same extension.. */
  2589. // Skip not source sources, they do not have file fields.
  2590. for (; Vf.end() == false; ++Vf)
  2591. {
  2592. if (Vf.File().Flagged(pkgCache::Flag::NotSource))
  2593. continue;
  2594. break;
  2595. }
  2596. // Does not really matter here.. we are going to fail out below
  2597. if (Vf.end() != true)
  2598. {
  2599. // If this fails to get a file name we will bomb out below.
  2600. pkgRecords::Parser &Parse = Recs->Lookup(Vf);
  2601. if (_error->PendingError() == true)
  2602. return;
  2603. // Generate the final file name as: package_version_arch.foo
  2604. StoreFilename = QuoteString(Version.ParentPkg().Name(),"_:") + '_' +
  2605. QuoteString(Version.VerStr(),"_:") + '_' +
  2606. QuoteString(Version.Arch(),"_:.") +
  2607. "." + flExtension(Parse.FileName());
  2608. }
  2609. // check if we have one trusted source for the package. if so, switch
  2610. // to "TrustedOnly" mode - but only if not in AllowUnauthenticated mode
  2611. bool const allowUnauth = _config->FindB("APT::Get::AllowUnauthenticated", false);
  2612. bool const debugAuth = _config->FindB("Debug::pkgAcquire::Auth", false);
  2613. bool seenUntrusted = false;
  2614. for (pkgCache::VerFileIterator i = Version.FileList(); i.end() == false; ++i)
  2615. {
  2616. pkgIndexFile *Index;
  2617. if (Sources->FindIndex(i.File(),Index) == false)
  2618. continue;
  2619. if (debugAuth == true)
  2620. std::cerr << "Checking index: " << Index->Describe()
  2621. << "(Trusted=" << Index->IsTrusted() << ")" << std::endl;
  2622. if (Index->IsTrusted() == true)
  2623. {
  2624. Trusted = true;
  2625. if (allowUnauth == false)
  2626. break;
  2627. }
  2628. else
  2629. seenUntrusted = true;
  2630. }
  2631. // "allow-unauthenticated" restores apts old fetching behaviour
  2632. // that means that e.g. unauthenticated file:// uris are higher
  2633. // priority than authenticated http:// uris
  2634. if (allowUnauth == true && seenUntrusted == true)
  2635. Trusted = false;
  2636. // Select a source
  2637. if (QueueNext() == false && _error->PendingError() == false)
  2638. _error->Error(_("Can't find a source to download version '%s' of '%s'"),
  2639. Version.VerStr(), Version.ParentPkg().FullName(false).c_str());
  2640. }
  2641. /*}}}*/
  2642. // AcqArchive::QueueNext - Queue the next file source /*{{{*/
  2643. // ---------------------------------------------------------------------
  2644. /* This queues the next available file version for download. It checks if
  2645. the archive is already available in the cache and stashs the MD5 for
  2646. checking later. */
  2647. bool pkgAcqArchive::QueueNext()
  2648. {
  2649. for (; Vf.end() == false; ++Vf)
  2650. {
  2651. pkgCache::PkgFileIterator const PkgF = Vf.File();
  2652. // Ignore not source sources
  2653. if (PkgF.Flagged(pkgCache::Flag::NotSource))
  2654. continue;
  2655. // Try to cross match against the source list
  2656. pkgIndexFile *Index;
  2657. if (Sources->FindIndex(PkgF, Index) == false)
  2658. continue;
  2659. LocalSource = PkgF.Flagged(pkgCache::Flag::LocalSource);
  2660. // only try to get a trusted package from another source if that source
  2661. // is also trusted
  2662. if(Trusted && !Index->IsTrusted())
  2663. continue;
  2664. // Grab the text package record
  2665. pkgRecords::Parser &Parse = Recs->Lookup(Vf);
  2666. if (_error->PendingError() == true)
  2667. return false;
  2668. string PkgFile = Parse.FileName();
  2669. ExpectedHashes = Parse.Hashes();
  2670. if (PkgFile.empty() == true)
  2671. return _error->Error(_("The package index files are corrupted. No Filename: "
  2672. "field for package %s."),
  2673. Version.ParentPkg().Name());
  2674. Desc.URI = Index->ArchiveURI(PkgFile);
  2675. Desc.Description = Index->ArchiveInfo(Version);
  2676. Desc.Owner = this;
  2677. Desc.ShortDesc = Version.ParentPkg().FullName(true);
  2678. // See if we already have the file. (Legacy filenames)
  2679. FileSize = Version->Size;
  2680. string FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(PkgFile);
  2681. struct stat Buf;
  2682. if (stat(FinalFile.c_str(),&Buf) == 0)
  2683. {
  2684. // Make sure the size matches
  2685. if ((unsigned long long)Buf.st_size == Version->Size)
  2686. {
  2687. Complete = true;
  2688. Local = true;
  2689. Status = StatDone;
  2690. StoreFilename = DestFile = FinalFile;
  2691. return true;
  2692. }
  2693. /* Hmm, we have a file and its size does not match, this means it is
  2694. an old style mismatched arch */
  2695. RemoveFile("pkgAcqArchive::QueueNext", FinalFile);
  2696. }
  2697. // Check it again using the new style output filenames
  2698. FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename);
  2699. if (stat(FinalFile.c_str(),&Buf) == 0)
  2700. {
  2701. // Make sure the size matches
  2702. if ((unsigned long long)Buf.st_size == Version->Size)
  2703. {
  2704. Complete = true;
  2705. Local = true;
  2706. Status = StatDone;
  2707. StoreFilename = DestFile = FinalFile;
  2708. return true;
  2709. }
  2710. /* Hmm, we have a file and its size does not match, this shouldn't
  2711. happen.. */
  2712. RemoveFile("pkgAcqArchive::QueueNext", FinalFile);
  2713. }
  2714. DestFile = _config->FindDir("Dir::Cache::Archives") + "partial/" + flNotDir(StoreFilename);
  2715. // Check the destination file
  2716. if (stat(DestFile.c_str(),&Buf) == 0)
  2717. {
  2718. // Hmm, the partial file is too big, erase it
  2719. if ((unsigned long long)Buf.st_size > Version->Size)
  2720. RemoveFile("pkgAcqArchive::QueueNext", DestFile);
  2721. else
  2722. PartialSize = Buf.st_size;
  2723. }
  2724. // Disables download of archives - useful if no real installation follows,
  2725. // e.g. if we are just interested in proposed installation order
  2726. if (_config->FindB("Debug::pkgAcqArchive::NoQueue", false) == true)
  2727. {
  2728. Complete = true;
  2729. Local = true;
  2730. Status = StatDone;
  2731. StoreFilename = DestFile = FinalFile;
  2732. return true;
  2733. }
  2734. // Create the item
  2735. Local = false;
  2736. QueueURI(Desc);
  2737. ++Vf;
  2738. return true;
  2739. }
  2740. return false;
  2741. }
  2742. /*}}}*/
  2743. // AcqArchive::Done - Finished fetching /*{{{*/
  2744. // ---------------------------------------------------------------------
  2745. /* */
  2746. void pkgAcqArchive::Done(string const &Message, HashStringList const &Hashes,
  2747. pkgAcquire::MethodConfig const * const Cfg)
  2748. {
  2749. Item::Done(Message, Hashes, Cfg);
  2750. // Grab the output filename
  2751. std::string const FileName = LookupTag(Message,"Filename");
  2752. if (DestFile != FileName && RealFileExists(DestFile) == false)
  2753. {
  2754. StoreFilename = DestFile = FileName;
  2755. Local = true;
  2756. Complete = true;
  2757. return;
  2758. }
  2759. // Done, move it into position
  2760. string const FinalFile = GetFinalFilename();
  2761. Rename(DestFile,FinalFile);
  2762. StoreFilename = DestFile = FinalFile;
  2763. Complete = true;
  2764. }
  2765. /*}}}*/
  2766. // AcqArchive::Failed - Failure handler /*{{{*/
  2767. // ---------------------------------------------------------------------
  2768. /* Here we try other sources */
  2769. void pkgAcqArchive::Failed(string const &Message,pkgAcquire::MethodConfig const * const Cnf)
  2770. {
  2771. Item::Failed(Message,Cnf);
  2772. /* We don't really want to retry on failed media swaps, this prevents
  2773. that. An interesting observation is that permanent failures are not
  2774. recorded. */
  2775. if (Cnf->Removable == true &&
  2776. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  2777. {
  2778. // Vf = Version.FileList();
  2779. while (Vf.end() == false) ++Vf;
  2780. StoreFilename = string();
  2781. return;
  2782. }
  2783. Status = StatIdle;
  2784. if (QueueNext() == false)
  2785. {
  2786. // This is the retry counter
  2787. if (Retries != 0 &&
  2788. Cnf->LocalOnly == false &&
  2789. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  2790. {
  2791. Retries--;
  2792. Vf = Version.FileList();
  2793. if (QueueNext() == true)
  2794. return;
  2795. }
  2796. StoreFilename = string();
  2797. Status = StatError;
  2798. }
  2799. }
  2800. /*}}}*/
  2801. APT_PURE bool pkgAcqArchive::IsTrusted() const /*{{{*/
  2802. {
  2803. return Trusted;
  2804. }
  2805. /*}}}*/
  2806. void pkgAcqArchive::Finished() /*{{{*/
  2807. {
  2808. if (Status == pkgAcquire::Item::StatDone &&
  2809. Complete == true)
  2810. return;
  2811. StoreFilename = string();
  2812. }
  2813. /*}}}*/
  2814. std::string pkgAcqArchive::DescURI() const /*{{{*/
  2815. {
  2816. return Desc.URI;
  2817. }
  2818. /*}}}*/
  2819. std::string pkgAcqArchive::ShortDesc() const /*{{{*/
  2820. {
  2821. return Desc.ShortDesc;
  2822. }
  2823. /*}}}*/
  2824. pkgAcqArchive::~pkgAcqArchive() {}
  2825. // AcqChangelog::pkgAcqChangelog - Constructors /*{{{*/
  2826. class pkgAcqChangelog::Private
  2827. {
  2828. public:
  2829. std::string FinalFile;
  2830. };
  2831. pkgAcqChangelog::pkgAcqChangelog(pkgAcquire * const Owner, pkgCache::VerIterator const &Ver,
  2832. std::string const &DestDir, std::string const &DestFilename) :
  2833. pkgAcquire::Item(Owner), d(new pkgAcqChangelog::Private()), SrcName(Ver.SourcePkgName()), SrcVersion(Ver.SourceVerStr())
  2834. {
  2835. Desc.URI = URI(Ver);
  2836. Init(DestDir, DestFilename);
  2837. }
  2838. // some parameters are char* here as they come likely from char* interfaces – which can also return NULL
  2839. pkgAcqChangelog::pkgAcqChangelog(pkgAcquire * const Owner, pkgCache::RlsFileIterator const &RlsFile,
  2840. char const * const Component, char const * const SrcName, char const * const SrcVersion,
  2841. const string &DestDir, const string &DestFilename) :
  2842. pkgAcquire::Item(Owner), d(new pkgAcqChangelog::Private()), SrcName(SrcName), SrcVersion(SrcVersion)
  2843. {
  2844. Desc.URI = URI(RlsFile, Component, SrcName, SrcVersion);
  2845. Init(DestDir, DestFilename);
  2846. }
  2847. pkgAcqChangelog::pkgAcqChangelog(pkgAcquire * const Owner,
  2848. std::string const &URI, char const * const SrcName, char const * const SrcVersion,
  2849. const string &DestDir, const string &DestFilename) :
  2850. pkgAcquire::Item(Owner), d(new pkgAcqChangelog::Private()), SrcName(SrcName), SrcVersion(SrcVersion)
  2851. {
  2852. Desc.URI = URI;
  2853. Init(DestDir, DestFilename);
  2854. }
  2855. void pkgAcqChangelog::Init(std::string const &DestDir, std::string const &DestFilename)
  2856. {
  2857. if (Desc.URI.empty())
  2858. {
  2859. Status = StatError;
  2860. // TRANSLATOR: %s=%s is sourcename=sourceversion, e.g. apt=1.1
  2861. strprintf(ErrorText, _("Changelog unavailable for %s=%s"), SrcName.c_str(), SrcVersion.c_str());
  2862. // Let the error message print something sensible rather than "Failed to fetch /"
  2863. if (DestFilename.empty())
  2864. DestFile = SrcName + ".changelog";
  2865. else
  2866. DestFile = DestFilename;
  2867. Desc.URI = "changelog:/" + DestFile;
  2868. return;
  2869. }
  2870. std::string DestFileName;
  2871. if (DestFilename.empty())
  2872. DestFileName = flCombine(DestFile, SrcName + ".changelog");
  2873. else
  2874. DestFileName = flCombine(DestFile, DestFilename);
  2875. std::string const SandboxUser = _config->Find("APT::Sandbox::User");
  2876. std::string const systemTemp = GetTempDir(SandboxUser);
  2877. char tmpname[1000];
  2878. snprintf(tmpname, sizeof(tmpname), "%s/apt-changelog-XXXXXX", systemTemp.c_str());
  2879. if (NULL == mkdtemp(tmpname))
  2880. {
  2881. _error->Errno("mkdtemp", "mkdtemp failed in changelog acquire of %s %s", SrcName.c_str(), SrcVersion.c_str());
  2882. Status = StatError;
  2883. return;
  2884. }
  2885. TemporaryDirectory = tmpname;
  2886. ChangeOwnerAndPermissionOfFile("Item::QueueURI", TemporaryDirectory.c_str(),
  2887. SandboxUser.c_str(), "root", 0700);
  2888. DestFile = flCombine(TemporaryDirectory, DestFileName);
  2889. if (DestDir.empty() == false)
  2890. d->FinalFile = flCombine(DestDir, DestFileName);
  2891. Desc.ShortDesc = "Changelog";
  2892. strprintf(Desc.Description, "%s %s %s Changelog", URI::SiteOnly(Desc.URI).c_str(), SrcName.c_str(), SrcVersion.c_str());
  2893. Desc.Owner = this;
  2894. QueueURI(Desc);
  2895. }
  2896. /*}}}*/
  2897. std::string pkgAcqChangelog::URI(pkgCache::VerIterator const &Ver) /*{{{*/
  2898. {
  2899. std::string const confOnline = "Acquire::Changelogs::AlwaysOnline";
  2900. bool AlwaysOnline = _config->FindB(confOnline, false);
  2901. if (AlwaysOnline == false)
  2902. for (pkgCache::VerFileIterator VF = Ver.FileList(); VF.end() == false; ++VF)
  2903. {
  2904. pkgCache::PkgFileIterator const PF = VF.File();
  2905. if (PF.Flagged(pkgCache::Flag::NotSource) || PF->Release == 0)
  2906. continue;
  2907. pkgCache::RlsFileIterator const RF = PF.ReleaseFile();
  2908. if (RF->Origin != 0 && _config->FindB(confOnline + "::Origin::" + RF.Origin(), false))
  2909. {
  2910. AlwaysOnline = true;
  2911. break;
  2912. }
  2913. }
  2914. if (AlwaysOnline == false)
  2915. {
  2916. pkgCache::PkgIterator const Pkg = Ver.ParentPkg();
  2917. if (Pkg->CurrentVer != 0 && Pkg.CurrentVer() == Ver)
  2918. {
  2919. std::string const basename = std::string("/usr/share/doc/") + Pkg.Name() + "/changelog";
  2920. std::string const debianname = basename + ".Debian";
  2921. if (FileExists(debianname))
  2922. return "copy://" + debianname;
  2923. else if (FileExists(debianname + ".gz"))
  2924. return "gzip://" + debianname + ".gz";
  2925. else if (FileExists(basename))
  2926. return "copy://" + basename;
  2927. else if (FileExists(basename + ".gz"))
  2928. return "gzip://" + basename + ".gz";
  2929. }
  2930. }
  2931. char const * const SrcName = Ver.SourcePkgName();
  2932. char const * const SrcVersion = Ver.SourceVerStr();
  2933. // find the first source for this version which promises a changelog
  2934. for (pkgCache::VerFileIterator VF = Ver.FileList(); VF.end() == false; ++VF)
  2935. {
  2936. pkgCache::PkgFileIterator const PF = VF.File();
  2937. if (PF.Flagged(pkgCache::Flag::NotSource) || PF->Release == 0)
  2938. continue;
  2939. pkgCache::RlsFileIterator const RF = PF.ReleaseFile();
  2940. std::string const uri = URI(RF, PF.Component(), SrcName, SrcVersion);
  2941. if (uri.empty())
  2942. continue;
  2943. return uri;
  2944. }
  2945. return "";
  2946. }
  2947. std::string pkgAcqChangelog::URITemplate(pkgCache::RlsFileIterator const &Rls)
  2948. {
  2949. if (Rls.end() == true || (Rls->Label == 0 && Rls->Origin == 0))
  2950. return "";
  2951. std::string const serverConfig = "Acquire::Changelogs::URI";
  2952. std::string server;
  2953. #define APT_EMPTY_SERVER \
  2954. if (server.empty() == false) \
  2955. { \
  2956. if (server != "no") \
  2957. return server; \
  2958. return ""; \
  2959. }
  2960. #define APT_CHECK_SERVER(X, Y) \
  2961. if (Rls->X != 0) \
  2962. { \
  2963. std::string const specialServerConfig = serverConfig + "::" + Y + #X + "::" + Rls.X(); \
  2964. server = _config->Find(specialServerConfig); \
  2965. APT_EMPTY_SERVER \
  2966. }
  2967. // this way e.g. Debian-Security can fallback to Debian
  2968. APT_CHECK_SERVER(Label, "Override::")
  2969. APT_CHECK_SERVER(Origin, "Override::")
  2970. if (RealFileExists(Rls.FileName()))
  2971. {
  2972. _error->PushToStack();
  2973. FileFd rf;
  2974. /* This can be costly. A caller wanting to get millions of URIs might
  2975. want to do this on its own once and use Override settings.
  2976. We don't do this here as Origin/Label are not as unique as they
  2977. should be so this could produce request order-dependent anomalies */
  2978. if (OpenMaybeClearSignedFile(Rls.FileName(), rf) == true)
  2979. {
  2980. pkgTagFile TagFile(&rf, rf.Size());
  2981. pkgTagSection Section;
  2982. if (TagFile.Step(Section) == true)
  2983. server = Section.FindS("Changelogs");
  2984. }
  2985. _error->RevertToStack();
  2986. APT_EMPTY_SERVER
  2987. }
  2988. APT_CHECK_SERVER(Label, "")
  2989. APT_CHECK_SERVER(Origin, "")
  2990. #undef APT_CHECK_SERVER
  2991. #undef APT_EMPTY_SERVER
  2992. return "";
  2993. }
  2994. std::string pkgAcqChangelog::URI(pkgCache::RlsFileIterator const &Rls,
  2995. char const * const Component, char const * const SrcName,
  2996. char const * const SrcVersion)
  2997. {
  2998. return URI(URITemplate(Rls), Component, SrcName, SrcVersion);
  2999. }
  3000. std::string pkgAcqChangelog::URI(std::string const &Template,
  3001. char const * const Component, char const * const SrcName,
  3002. char const * const SrcVersion)
  3003. {
  3004. if (Template.find("@CHANGEPATH@") == std::string::npos)
  3005. return "";
  3006. // the path is: COMPONENT/SRC/SRCNAME/SRCNAME_SRCVER, e.g. main/a/apt/1.1 or contrib/liba/libapt/2.0
  3007. std::string Src = SrcName;
  3008. std::string path = APT::String::Startswith(SrcName, "lib") ? Src.substr(0, 4) : Src.substr(0,1);
  3009. path.append("/").append(Src).append("/");
  3010. path.append(Src).append("_").append(StripEpoch(SrcVersion));
  3011. // we omit component for releases without one (= flat-style repositories)
  3012. if (Component != NULL && strlen(Component) != 0)
  3013. path = std::string(Component) + "/" + path;
  3014. return SubstVar(Template, "@CHANGEPATH@", path);
  3015. }
  3016. /*}}}*/
  3017. // AcqChangelog::Failed - Failure handler /*{{{*/
  3018. void pkgAcqChangelog::Failed(string const &Message, pkgAcquire::MethodConfig const * const Cnf)
  3019. {
  3020. Item::Failed(Message,Cnf);
  3021. std::string errText;
  3022. // TRANSLATOR: %s=%s is sourcename=sourceversion, e.g. apt=1.1
  3023. strprintf(errText, _("Changelog unavailable for %s=%s"), SrcName.c_str(), SrcVersion.c_str());
  3024. // Error is probably something techy like 404 Not Found
  3025. if (ErrorText.empty())
  3026. ErrorText = errText;
  3027. else
  3028. ErrorText = errText + " (" + ErrorText + ")";
  3029. return;
  3030. }
  3031. /*}}}*/
  3032. // AcqChangelog::Done - Item downloaded OK /*{{{*/
  3033. void pkgAcqChangelog::Done(string const &Message,HashStringList const &CalcHashes,
  3034. pkgAcquire::MethodConfig const * const Cnf)
  3035. {
  3036. Item::Done(Message,CalcHashes,Cnf);
  3037. if (d->FinalFile.empty() == false)
  3038. Rename(DestFile, d->FinalFile);
  3039. Complete = true;
  3040. }
  3041. /*}}}*/
  3042. pkgAcqChangelog::~pkgAcqChangelog() /*{{{*/
  3043. {
  3044. if (TemporaryDirectory.empty() == false)
  3045. {
  3046. RemoveFile("~pkgAcqChangelog", DestFile);
  3047. rmdir(TemporaryDirectory.c_str());
  3048. }
  3049. delete d;
  3050. }
  3051. /*}}}*/
  3052. // AcqFile::pkgAcqFile - Constructor /*{{{*/
  3053. pkgAcqFile::pkgAcqFile(pkgAcquire * const Owner,string const &URI, HashStringList const &Hashes,
  3054. unsigned long long const Size,string const &Dsc,string const &ShortDesc,
  3055. const string &DestDir, const string &DestFilename,
  3056. bool const IsIndexFile) :
  3057. Item(Owner), d(NULL), IsIndexFile(IsIndexFile), ExpectedHashes(Hashes)
  3058. {
  3059. Retries = _config->FindI("Acquire::Retries",0);
  3060. if(!DestFilename.empty())
  3061. DestFile = DestFilename;
  3062. else if(!DestDir.empty())
  3063. DestFile = DestDir + "/" + flNotDir(URI);
  3064. else
  3065. DestFile = flNotDir(URI);
  3066. // Create the item
  3067. Desc.URI = URI;
  3068. Desc.Description = Dsc;
  3069. Desc.Owner = this;
  3070. // Set the short description to the archive component
  3071. Desc.ShortDesc = ShortDesc;
  3072. // Get the transfer sizes
  3073. FileSize = Size;
  3074. struct stat Buf;
  3075. if (stat(DestFile.c_str(),&Buf) == 0)
  3076. {
  3077. // Hmm, the partial file is too big, erase it
  3078. if ((Size > 0) && (unsigned long long)Buf.st_size > Size)
  3079. RemoveFile("pkgAcqFile", DestFile);
  3080. else
  3081. PartialSize = Buf.st_size;
  3082. }
  3083. QueueURI(Desc);
  3084. }
  3085. /*}}}*/
  3086. // AcqFile::Done - Item downloaded OK /*{{{*/
  3087. void pkgAcqFile::Done(string const &Message,HashStringList const &CalcHashes,
  3088. pkgAcquire::MethodConfig const * const Cnf)
  3089. {
  3090. Item::Done(Message,CalcHashes,Cnf);
  3091. std::string const FileName = LookupTag(Message,"Filename");
  3092. Complete = true;
  3093. // The files timestamp matches
  3094. if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  3095. return;
  3096. // We have to copy it into place
  3097. if (RealFileExists(DestFile.c_str()) == false)
  3098. {
  3099. Local = true;
  3100. if (_config->FindB("Acquire::Source-Symlinks",true) == false ||
  3101. Cnf->Removable == true)
  3102. {
  3103. Desc.URI = "copy:" + FileName;
  3104. QueueURI(Desc);
  3105. return;
  3106. }
  3107. // Erase the file if it is a symlink so we can overwrite it
  3108. struct stat St;
  3109. if (lstat(DestFile.c_str(),&St) == 0)
  3110. {
  3111. if (S_ISLNK(St.st_mode) != 0)
  3112. RemoveFile("pkgAcqFile::Done", DestFile);
  3113. }
  3114. // Symlink the file
  3115. if (symlink(FileName.c_str(),DestFile.c_str()) != 0)
  3116. {
  3117. _error->PushToStack();
  3118. _error->Errno("pkgAcqFile::Done", "Symlinking file %s failed", DestFile.c_str());
  3119. std::stringstream msg;
  3120. _error->DumpErrors(msg, GlobalError::DEBUG, false);
  3121. _error->RevertToStack();
  3122. ErrorText = msg.str();
  3123. Status = StatError;
  3124. Complete = false;
  3125. }
  3126. }
  3127. }
  3128. /*}}}*/
  3129. // AcqFile::Failed - Failure handler /*{{{*/
  3130. // ---------------------------------------------------------------------
  3131. /* Here we try other sources */
  3132. void pkgAcqFile::Failed(string const &Message, pkgAcquire::MethodConfig const * const Cnf)
  3133. {
  3134. Item::Failed(Message,Cnf);
  3135. // This is the retry counter
  3136. if (Retries != 0 &&
  3137. Cnf->LocalOnly == false &&
  3138. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  3139. {
  3140. --Retries;
  3141. QueueURI(Desc);
  3142. Status = StatIdle;
  3143. return;
  3144. }
  3145. }
  3146. /*}}}*/
  3147. string pkgAcqFile::Custom600Headers() const /*{{{*/
  3148. {
  3149. if (IsIndexFile)
  3150. return "\nIndex-File: true";
  3151. return "";
  3152. }
  3153. /*}}}*/
  3154. pkgAcqFile::~pkgAcqFile() {}