acquire-item.cc 132 KB

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