acquire-item.cc 108 KB

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