acquire-item.cc 130 KB

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