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