acquire-item.cc 111 KB

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