acquire-item.cc 104 KB

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