acquire-item.cc 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: acquire-item.cc,v 1.46.2.9 2004/01/16 18:51:11 mdz Exp $
  4. /* ######################################################################
  5. Acquire Item - Item to acquire
  6. Each item can download to exactly one file at a time. This means you
  7. cannot create an item that fetches two uri's to two files at the same
  8. time. The pkgAcqIndex class creates a second class upon instantiation
  9. to fetch the other index files because of this.
  10. ##################################################################### */
  11. /*}}}*/
  12. // Include Files /*{{{*/
  13. #include <config.h>
  14. #include <apt-pkg/acquire-item.h>
  15. #include <apt-pkg/configuration.h>
  16. #include <apt-pkg/aptconfiguration.h>
  17. #include <apt-pkg/sourcelist.h>
  18. #include <apt-pkg/error.h>
  19. #include <apt-pkg/strutl.h>
  20. #include <apt-pkg/fileutl.h>
  21. #include <apt-pkg/sha1.h>
  22. #include <apt-pkg/tagfile.h>
  23. #include <apt-pkg/indexrecords.h>
  24. #include <apt-pkg/acquire.h>
  25. #include <apt-pkg/hashes.h>
  26. #include <apt-pkg/indexfile.h>
  27. #include <apt-pkg/pkgcache.h>
  28. #include <apt-pkg/cacheiterators.h>
  29. #include <apt-pkg/pkgrecords.h>
  30. #include <stddef.h>
  31. #include <stdlib.h>
  32. #include <string.h>
  33. #include <iostream>
  34. #include <vector>
  35. #include <sys/stat.h>
  36. #include <unistd.h>
  37. #include <errno.h>
  38. #include <string>
  39. #include <sstream>
  40. #include <stdio.h>
  41. #include <ctime>
  42. #include <apti18n.h>
  43. /*}}}*/
  44. using namespace std;
  45. static void printHashSumComparision(std::string const &URI, HashStringList const &Expected, HashStringList const &Actual) /*{{{*/
  46. {
  47. if (_config->FindB("Debug::Acquire::HashSumMismatch", false) == false)
  48. return;
  49. std::cerr << std::endl << URI << ":" << std::endl << " Expected Hash: " << std::endl;
  50. for (HashStringList::const_iterator hs = Expected.begin(); hs != Expected.end(); ++hs)
  51. std::cerr << "\t- " << hs->toStr() << std::endl;
  52. std::cerr << " Actual Hash: " << std::endl;
  53. for (HashStringList::const_iterator hs = Actual.begin(); hs != Actual.end(); ++hs)
  54. std::cerr << "\t- " << hs->toStr() << std::endl;
  55. }
  56. /*}}}*/
  57. static std::string GetPartialFileName(std::string const &file) /*{{{*/
  58. {
  59. std::string DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  60. DestFile += file;
  61. return DestFile;
  62. }
  63. /*}}}*/
  64. static std::string GetPartialFileNameFromURI(std::string const &uri) /*{{{*/
  65. {
  66. return GetPartialFileName(URItoFileName(uri));
  67. }
  68. /*}}}*/
  69. static std::string GetFinalFileNameFromURI(std::string const &uri) /*{{{*/
  70. {
  71. return _config->FindDir("Dir::State::lists") + URItoFileName(uri);
  72. }
  73. /*}}}*/
  74. static std::string GetCompressedFileName(std::string const &URI, std::string const &Name, std::string const &Ext) /*{{{*/
  75. {
  76. if (Ext.empty() || Ext == "uncompressed")
  77. return Name;
  78. // do not reverify cdrom sources as apt-cdrom may rewrite the Packages
  79. // file when its doing the indexcopy
  80. if (URI.substr(0,6) == "cdrom:")
  81. return Name;
  82. // adjust DestFile if its compressed on disk
  83. if (_config->FindB("Acquire::GzipIndexes",false) == true)
  84. return Name + '.' + Ext;
  85. return Name;
  86. }
  87. /*}}}*/
  88. static bool AllowInsecureRepositories(indexRecords const * const MetaIndexParser, pkgAcqMetaBase * const TransactionManager, pkgAcquire::Item * const I) /*{{{*/
  89. {
  90. if(MetaIndexParser->IsAlwaysTrusted() || _config->FindB("Acquire::AllowInsecureRepositories") == true)
  91. return true;
  92. _error->Error(_("Use --allow-insecure-repositories to force the update"));
  93. TransactionManager->AbortTransaction();
  94. I->Status = pkgAcquire::Item::StatError;
  95. return false;
  96. }
  97. /*}}}*/
  98. // Acquire::Item::Item - Constructor /*{{{*/
  99. APT_IGNORE_DEPRECATED_PUSH
  100. pkgAcquire::Item::Item(pkgAcquire *Owner,
  101. HashStringList const &ExpectedHashes,
  102. pkgAcqMetaBase *TransactionManager)
  103. : Owner(Owner), FileSize(0), PartialSize(0), Mode(0), ID(0), Complete(false),
  104. Local(false), QueueCounter(0), TransactionManager(TransactionManager),
  105. ExpectedAdditionalItems(0), ExpectedHashes(ExpectedHashes)
  106. {
  107. Owner->Add(this);
  108. Status = StatIdle;
  109. if(TransactionManager != NULL)
  110. TransactionManager->Add(this);
  111. }
  112. APT_IGNORE_DEPRECATED_POP
  113. /*}}}*/
  114. // Acquire::Item::~Item - Destructor /*{{{*/
  115. // ---------------------------------------------------------------------
  116. /* */
  117. pkgAcquire::Item::~Item()
  118. {
  119. Owner->Remove(this);
  120. }
  121. /*}}}*/
  122. // Acquire::Item::Failed - Item failed to download /*{{{*/
  123. // ---------------------------------------------------------------------
  124. /* We return to an idle state if there are still other queues that could
  125. fetch this object */
  126. void pkgAcquire::Item::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  127. {
  128. if(ErrorText.empty())
  129. ErrorText = LookupTag(Message,"Message");
  130. UsedMirror = LookupTag(Message,"UsedMirror");
  131. if (QueueCounter <= 1)
  132. {
  133. /* This indicates that the file is not available right now but might
  134. be sometime later. If we do a retry cycle then this should be
  135. retried [CDROMs] */
  136. if (Cnf != NULL && Cnf->LocalOnly == true &&
  137. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  138. {
  139. Status = StatIdle;
  140. Dequeue();
  141. return;
  142. }
  143. Status = StatError;
  144. Complete = false;
  145. Dequeue();
  146. }
  147. else
  148. Status = StatIdle;
  149. // check fail reason
  150. string const FailReason = LookupTag(Message, "FailReason");
  151. if(FailReason == "MaximumSizeExceeded")
  152. RenameOnError(MaximumSizeExceeded);
  153. // report mirror failure back to LP if we actually use a mirror
  154. if(FailReason.size() != 0)
  155. ReportMirrorFailure(FailReason);
  156. else
  157. ReportMirrorFailure(ErrorText);
  158. }
  159. /*}}}*/
  160. // Acquire::Item::Start - Item has begun to download /*{{{*/
  161. // ---------------------------------------------------------------------
  162. /* Stash status and the file size. Note that setting Complete means
  163. sub-phases of the acquire process such as decompresion are operating */
  164. void pkgAcquire::Item::Start(string /*Message*/,unsigned long long Size)
  165. {
  166. Status = StatFetching;
  167. ErrorText.clear();
  168. if (FileSize == 0 && Complete == false)
  169. FileSize = Size;
  170. }
  171. /*}}}*/
  172. // Acquire::Item::Done - Item downloaded OK /*{{{*/
  173. // ---------------------------------------------------------------------
  174. /* */
  175. void pkgAcquire::Item::Done(string Message,unsigned long long Size,HashStringList const &/*Hash*/,
  176. pkgAcquire::MethodConfig * /*Cnf*/)
  177. {
  178. // We just downloaded something..
  179. string FileName = LookupTag(Message,"Filename");
  180. UsedMirror = LookupTag(Message,"UsedMirror");
  181. if (Complete == false && !Local && FileName == DestFile)
  182. {
  183. if (Owner->Log != 0)
  184. Owner->Log->Fetched(Size,atoi(LookupTag(Message,"Resume-Point","0").c_str()));
  185. }
  186. if (FileSize == 0)
  187. FileSize= Size;
  188. Status = StatDone;
  189. ErrorText = string();
  190. Owner->Dequeue(this);
  191. }
  192. /*}}}*/
  193. // Acquire::Item::Rename - Rename a file /*{{{*/
  194. // ---------------------------------------------------------------------
  195. /* This helper function is used by a lot of item methods as their final
  196. step */
  197. bool pkgAcquire::Item::Rename(string From,string To)
  198. {
  199. if (rename(From.c_str(),To.c_str()) == 0)
  200. return true;
  201. std::string S;
  202. strprintf(S, _("rename failed, %s (%s -> %s)."), strerror(errno),
  203. From.c_str(),To.c_str());
  204. Status = StatError;
  205. ErrorText += S;
  206. return false;
  207. }
  208. /*}}}*/
  209. void pkgAcquire::Item::QueueURI(ItemDesc &Item) /*{{{*/
  210. {
  211. Owner->Enqueue(Item);
  212. }
  213. /*}}}*/
  214. void pkgAcquire::Item::Dequeue() /*{{{*/
  215. {
  216. Owner->Dequeue(this);
  217. }
  218. /*}}}*/
  219. bool pkgAcquire::Item::RenameOnError(pkgAcquire::Item::RenameOnErrorState const error)/*{{{*/
  220. {
  221. if (RealFileExists(DestFile))
  222. Rename(DestFile, DestFile + ".FAILED");
  223. switch (error)
  224. {
  225. case HashSumMismatch:
  226. ErrorText = _("Hash Sum mismatch");
  227. Status = StatAuthError;
  228. ReportMirrorFailure("HashChecksumFailure");
  229. break;
  230. case SizeMismatch:
  231. ErrorText = _("Size mismatch");
  232. Status = StatAuthError;
  233. ReportMirrorFailure("SizeFailure");
  234. break;
  235. case InvalidFormat:
  236. ErrorText = _("Invalid file format");
  237. Status = StatError;
  238. // do not report as usually its not the mirrors fault, but Portal/Proxy
  239. break;
  240. case SignatureError:
  241. ErrorText = _("Signature error");
  242. Status = StatError;
  243. break;
  244. case NotClearsigned:
  245. ErrorText = _("Does not start with a cleartext signature");
  246. Status = StatError;
  247. break;
  248. case MaximumSizeExceeded:
  249. // the method is expected to report a good error for this
  250. Status = StatError;
  251. break;
  252. }
  253. return false;
  254. }
  255. /*}}}*/
  256. void pkgAcquire::Item::SetActiveSubprocess(const std::string &subprocess)/*{{{*/
  257. {
  258. ActiveSubprocess = subprocess;
  259. APT_IGNORE_DEPRECATED(Mode = ActiveSubprocess.c_str();)
  260. }
  261. /*}}}*/
  262. // Acquire::Item::GetFinalFilename - Return the full final file path /*{{{*/
  263. std::string pkgAcquire::Item::GetFinalFilename() const
  264. {
  265. return GetFinalFileNameFromURI(Desc.URI);
  266. }
  267. /*}}}*/
  268. // Acquire::Item::ReportMirrorFailure /*{{{*/
  269. // ---------------------------------------------------------------------
  270. void pkgAcquire::Item::ReportMirrorFailure(string FailCode)
  271. {
  272. // we only act if a mirror was used at all
  273. if(UsedMirror.empty())
  274. return;
  275. #if 0
  276. std::cerr << "\nReportMirrorFailure: "
  277. << UsedMirror
  278. << " Uri: " << DescURI()
  279. << " FailCode: "
  280. << FailCode << std::endl;
  281. #endif
  282. string report = _config->Find("Methods::Mirror::ProblemReporting",
  283. "/usr/lib/apt/apt-report-mirror-failure");
  284. if(!FileExists(report))
  285. return;
  286. std::vector<char const*> Args;
  287. Args.push_back(report.c_str());
  288. Args.push_back(UsedMirror.c_str());
  289. Args.push_back(DescURI().c_str());
  290. Args.push_back(FailCode.c_str());
  291. Args.push_back(NULL);
  292. pid_t pid = ExecFork();
  293. if(pid < 0)
  294. {
  295. _error->Error("ReportMirrorFailure Fork failed");
  296. return;
  297. }
  298. else if(pid == 0)
  299. {
  300. execvp(Args[0], (char**)Args.data());
  301. std::cerr << "Could not exec " << Args[0] << std::endl;
  302. _exit(100);
  303. }
  304. if(!ExecWait(pid, "report-mirror-failure"))
  305. {
  306. _error->Warning("Couldn't report problem to '%s'",
  307. _config->Find("Methods::Mirror::ProblemReporting").c_str());
  308. }
  309. }
  310. /*}}}*/
  311. // AcqDiffIndex::AcqDiffIndex - Constructor /*{{{*/
  312. // ---------------------------------------------------------------------
  313. /* Get the DiffIndex file first and see if there are patches available
  314. * If so, create a pkgAcqIndexDiffs fetcher that will get and apply the
  315. * patches. If anything goes wrong in that process, it will fall back to
  316. * the original packages file
  317. */
  318. pkgAcqDiffIndex::pkgAcqDiffIndex(pkgAcquire *Owner,
  319. pkgAcqMetaBase *TransactionManager,
  320. IndexTarget const * const Target,
  321. HashStringList const &ExpectedHashes,
  322. indexRecords *MetaIndexParser)
  323. : pkgAcqBaseIndex(Owner, TransactionManager, Target, ExpectedHashes,
  324. MetaIndexParser), PackagesFileReadyInPartial(false)
  325. {
  326. Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
  327. RealURI = Target->URI;
  328. Desc.Owner = this;
  329. Desc.Description = Target->Description + ".diff/Index";
  330. Desc.ShortDesc = Target->ShortDesc;
  331. Desc.URI = Target->URI + ".diff/Index";
  332. DestFile = GetPartialFileNameFromURI(Desc.URI);
  333. if(Debug)
  334. std::clog << "pkgAcqDiffIndex: " << Desc.URI << std::endl;
  335. // look for the current package file
  336. CurrentPackagesFile = GetFinalFileNameFromURI(RealURI);
  337. // FIXME: this file:/ check is a hack to prevent fetching
  338. // from local sources. this is really silly, and
  339. // should be fixed cleanly as soon as possible
  340. if(!FileExists(CurrentPackagesFile) ||
  341. Desc.URI.substr(0,strlen("file:/")) == "file:/")
  342. {
  343. // we don't have a pkg file or we don't want to queue
  344. Failed("No index file, local or canceld by user", NULL);
  345. return;
  346. }
  347. if(Debug)
  348. std::clog << "pkgAcqDiffIndex::pkgAcqDiffIndex(): "
  349. << CurrentPackagesFile << std::endl;
  350. QueueURI(Desc);
  351. }
  352. /*}}}*/
  353. // Acquire::Item::GetFinalFilename - Return the full final file path /*{{{*/
  354. std::string pkgAcqDiffIndex::GetFinalFilename() const
  355. {
  356. // the logic we inherent from pkgAcqBaseIndex isn't what we need here
  357. return pkgAcquire::Item::GetFinalFilename();
  358. }
  359. /*}}}*/
  360. // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
  361. // ---------------------------------------------------------------------
  362. /* The only header we use is the last-modified header. */
  363. #if APT_PKG_ABI >= 413
  364. string pkgAcqDiffIndex::Custom600Headers() const
  365. #else
  366. string pkgAcqDiffIndex::Custom600Headers()
  367. #endif
  368. {
  369. string const Final = GetFinalFilename();
  370. if(Debug)
  371. std::clog << "Custom600Header-IMS: " << Final << std::endl;
  372. struct stat Buf;
  373. if (stat(Final.c_str(),&Buf) != 0)
  374. return "\nIndex-File: true";
  375. return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  376. }
  377. /*}}}*/
  378. bool pkgAcqDiffIndex::ParseDiffIndex(string IndexDiffFile) /*{{{*/
  379. {
  380. // failing here is fine: our caller will take care of trying to
  381. // get the complete file if patching fails
  382. if(Debug)
  383. std::clog << "pkgAcqDiffIndex::ParseIndexDiff() " << IndexDiffFile
  384. << std::endl;
  385. FileFd Fd(IndexDiffFile,FileFd::ReadOnly);
  386. pkgTagFile TF(&Fd);
  387. if (_error->PendingError() == true)
  388. return false;
  389. pkgTagSection Tags;
  390. if(unlikely(TF.Step(Tags) == false))
  391. return false;
  392. HashStringList ServerHashes;
  393. unsigned long long ServerSize = 0;
  394. for (char const * const * type = HashString::SupportedHashes(); *type != NULL; ++type)
  395. {
  396. std::string tagname = *type;
  397. tagname.append("-Current");
  398. std::string const tmp = Tags.FindS(tagname.c_str());
  399. if (tmp.empty() == true)
  400. continue;
  401. string hash;
  402. unsigned long long size;
  403. std::stringstream ss(tmp);
  404. ss >> hash >> size;
  405. if (unlikely(hash.empty() == true))
  406. continue;
  407. if (unlikely(ServerSize != 0 && ServerSize != size))
  408. continue;
  409. ServerHashes.push_back(HashString(*type, hash));
  410. ServerSize = size;
  411. }
  412. if (ServerHashes.usable() == false)
  413. {
  414. if (Debug == true)
  415. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": Did not find a good hashsum in the index" << std::endl;
  416. return false;
  417. }
  418. if (ServerHashes != HashSums())
  419. {
  420. if (Debug == true)
  421. {
  422. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": Index has different hashes than parser, probably older, so fail pdiffing" << std::endl;
  423. printHashSumComparision(CurrentPackagesFile, ServerHashes, HashSums());
  424. }
  425. return false;
  426. }
  427. if (ServerHashes.VerifyFile(CurrentPackagesFile) == true)
  428. {
  429. // we have the same sha1 as the server so we are done here
  430. if(Debug)
  431. std::clog << "pkgAcqDiffIndex: Package file " << CurrentPackagesFile << " is up-to-date" << std::endl;
  432. // list cleanup needs to know that this file as well as the already
  433. // present index is ours, so we create an empty diff to save it for us
  434. new pkgAcqIndexDiffs(Owner, TransactionManager, Target,
  435. ExpectedHashes, MetaIndexParser);
  436. return true;
  437. }
  438. FileFd fd(CurrentPackagesFile, FileFd::ReadOnly);
  439. Hashes LocalHashesCalc;
  440. LocalHashesCalc.AddFD(fd);
  441. HashStringList const LocalHashes = LocalHashesCalc.GetHashStringList();
  442. if(Debug)
  443. std::clog << "Server-Current: " << ServerHashes.find(NULL)->toStr() << " and we start at "
  444. << fd.Name() << " " << fd.FileSize() << " " << LocalHashes.find(NULL)->toStr() << std::endl;
  445. // parse all of (provided) history
  446. vector<DiffInfo> available_patches;
  447. bool firstAcceptedHashes = true;
  448. for (char const * const * type = HashString::SupportedHashes(); *type != NULL; ++type)
  449. {
  450. if (LocalHashes.find(*type) == NULL)
  451. continue;
  452. std::string tagname = *type;
  453. tagname.append("-History");
  454. std::string const tmp = Tags.FindS(tagname.c_str());
  455. if (tmp.empty() == true)
  456. continue;
  457. string hash, filename;
  458. unsigned long long size;
  459. std::stringstream ss(tmp);
  460. while (ss >> hash >> size >> filename)
  461. {
  462. if (unlikely(hash.empty() == true || filename.empty() == true))
  463. continue;
  464. // see if we have a record for this file already
  465. std::vector<DiffInfo>::iterator cur = available_patches.begin();
  466. for (; cur != available_patches.end(); ++cur)
  467. {
  468. if (cur->file != filename || unlikely(cur->result_size != size))
  469. continue;
  470. cur->result_hashes.push_back(HashString(*type, hash));
  471. break;
  472. }
  473. if (cur != available_patches.end())
  474. continue;
  475. if (firstAcceptedHashes == true)
  476. {
  477. DiffInfo next;
  478. next.file = filename;
  479. next.result_hashes.push_back(HashString(*type, hash));
  480. next.result_size = size;
  481. next.patch_size = 0;
  482. available_patches.push_back(next);
  483. }
  484. else
  485. {
  486. if (Debug == true)
  487. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": File " << filename
  488. << " wasn't in the list for the first parsed hash! (history)" << std::endl;
  489. break;
  490. }
  491. }
  492. firstAcceptedHashes = false;
  493. }
  494. if (unlikely(available_patches.empty() == true))
  495. {
  496. if (Debug)
  497. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": "
  498. << "Couldn't find any patches for the patch series." << std::endl;
  499. return false;
  500. }
  501. for (char const * const * type = HashString::SupportedHashes(); *type != NULL; ++type)
  502. {
  503. if (LocalHashes.find(*type) == NULL)
  504. continue;
  505. std::string tagname = *type;
  506. tagname.append("-Patches");
  507. std::string const tmp = Tags.FindS(tagname.c_str());
  508. if (tmp.empty() == true)
  509. continue;
  510. string hash, filename;
  511. unsigned long long size;
  512. std::stringstream ss(tmp);
  513. while (ss >> hash >> size >> filename)
  514. {
  515. if (unlikely(hash.empty() == true || filename.empty() == true))
  516. continue;
  517. // see if we have a record for this file already
  518. std::vector<DiffInfo>::iterator cur = available_patches.begin();
  519. for (; cur != available_patches.end(); ++cur)
  520. {
  521. if (cur->file != filename)
  522. continue;
  523. if (unlikely(cur->patch_size != 0 && cur->patch_size != size))
  524. continue;
  525. cur->patch_hashes.push_back(HashString(*type, hash));
  526. cur->patch_size = size;
  527. break;
  528. }
  529. if (cur != available_patches.end())
  530. continue;
  531. if (Debug == true)
  532. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": File " << filename
  533. << " wasn't in the list for the first parsed hash! (patches)" << std::endl;
  534. break;
  535. }
  536. }
  537. bool foundStart = false;
  538. for (std::vector<DiffInfo>::iterator cur = available_patches.begin();
  539. cur != available_patches.end(); ++cur)
  540. {
  541. if (LocalHashes != cur->result_hashes)
  542. continue;
  543. available_patches.erase(available_patches.begin(), cur);
  544. foundStart = true;
  545. break;
  546. }
  547. if (foundStart == false || unlikely(available_patches.empty() == true))
  548. {
  549. if (Debug)
  550. std::clog << "pkgAcqDiffIndex: " << IndexDiffFile << ": "
  551. << "Couldn't find the start of the patch series." << std::endl;
  552. return false;
  553. }
  554. // patching with too many files is rather slow compared to a fast download
  555. unsigned long const fileLimit = _config->FindI("Acquire::PDiffs::FileLimit", 0);
  556. if (fileLimit != 0 && fileLimit < available_patches.size())
  557. {
  558. if (Debug)
  559. std::clog << "Need " << available_patches.size() << " diffs (Limit is " << fileLimit
  560. << ") so fallback to complete download" << std::endl;
  561. return false;
  562. }
  563. // calculate the size of all patches we have to get
  564. // note that all sizes are uncompressed, while we download compressed files
  565. unsigned long long patchesSize = 0;
  566. for (std::vector<DiffInfo>::const_iterator cur = available_patches.begin();
  567. cur != available_patches.end(); ++cur)
  568. patchesSize += cur->patch_size;
  569. unsigned long long const sizeLimit = ServerSize * _config->FindI("Acquire::PDiffs::SizeLimit", 100);
  570. if (sizeLimit > 0 && (sizeLimit/100) < patchesSize)
  571. {
  572. if (Debug)
  573. std::clog << "Need " << patchesSize << " bytes (Limit is " << sizeLimit/100
  574. << ") so fallback to complete download" << std::endl;
  575. return false;
  576. }
  577. // FIXME: make this use the method
  578. PackagesFileReadyInPartial = true;
  579. std::string const Partial = GetPartialFileNameFromURI(RealURI);
  580. FileFd From(CurrentPackagesFile, FileFd::ReadOnly);
  581. FileFd To(Partial, FileFd::WriteEmpty);
  582. if(CopyFile(From, To) == false)
  583. return _error->Errno("CopyFile", "failed to copy");
  584. if(Debug)
  585. std::cerr << "Done copying " << CurrentPackagesFile
  586. << " -> " << Partial
  587. << std::endl;
  588. // we have something, queue the diffs
  589. string::size_type const last_space = Description.rfind(" ");
  590. if(last_space != string::npos)
  591. Description.erase(last_space, Description.size()-last_space);
  592. /* decide if we should download patches one by one or in one go:
  593. The first is good if the server merges patches, but many don't so client
  594. based merging can be attempt in which case the second is better.
  595. "bad things" will happen if patches are merged on the server,
  596. but client side merging is attempt as well */
  597. bool pdiff_merge = _config->FindB("Acquire::PDiffs::Merge", true);
  598. if (pdiff_merge == true)
  599. {
  600. // reprepro adds this flag if it has merged patches on the server
  601. std::string const precedence = Tags.FindS("X-Patch-Precedence");
  602. pdiff_merge = (precedence != "merged");
  603. }
  604. if (pdiff_merge == false)
  605. {
  606. new pkgAcqIndexDiffs(Owner, TransactionManager, Target, ExpectedHashes,
  607. MetaIndexParser, available_patches);
  608. }
  609. else
  610. {
  611. std::vector<pkgAcqIndexMergeDiffs*> *diffs = new std::vector<pkgAcqIndexMergeDiffs*>(available_patches.size());
  612. for(size_t i = 0; i < available_patches.size(); ++i)
  613. (*diffs)[i] = new pkgAcqIndexMergeDiffs(Owner, TransactionManager,
  614. Target,
  615. ExpectedHashes,
  616. MetaIndexParser,
  617. available_patches[i],
  618. diffs);
  619. }
  620. Complete = false;
  621. Status = StatDone;
  622. Dequeue();
  623. return true;
  624. }
  625. /*}}}*/
  626. void pkgAcqDiffIndex::Failed(string Message,pkgAcquire::MethodConfig * Cnf)/*{{{*/
  627. {
  628. Item::Failed(Message,Cnf);
  629. Status = StatDone;
  630. if(Debug)
  631. std::clog << "pkgAcqDiffIndex failed: " << Desc.URI << " with " << Message << std::endl
  632. << "Falling back to normal index file acquire" << std::endl;
  633. new pkgAcqIndex(Owner, TransactionManager, Target, ExpectedHashes, MetaIndexParser);
  634. }
  635. /*}}}*/
  636. void pkgAcqDiffIndex::Done(string Message,unsigned long long Size,HashStringList const &Hashes, /*{{{*/
  637. pkgAcquire::MethodConfig *Cnf)
  638. {
  639. if(Debug)
  640. std::clog << "pkgAcqDiffIndex::Done(): " << Desc.URI << std::endl;
  641. Item::Done(Message, Size, Hashes, Cnf);
  642. // verify the index target
  643. if(Target && Target->MetaKey != "" && MetaIndexParser && Hashes.usable())
  644. {
  645. std::string IndexMetaKey = Target->MetaKey + ".diff/Index";
  646. indexRecords::checkSum *Record = MetaIndexParser->Lookup(IndexMetaKey);
  647. if(Record && Record->Hashes.usable() && Hashes != Record->Hashes)
  648. {
  649. RenameOnError(HashSumMismatch);
  650. printHashSumComparision(RealURI, Record->Hashes, Hashes);
  651. Failed(Message, Cnf);
  652. return;
  653. }
  654. }
  655. string const FinalFile = GetFinalFilename();
  656. if(StringToBool(LookupTag(Message,"IMS-Hit"),false))
  657. DestFile = FinalFile;
  658. if(!ParseDiffIndex(DestFile))
  659. return Failed("Message: Couldn't parse pdiff index", Cnf);
  660. // queue for final move
  661. TransactionManager->TransactionStageCopy(this, DestFile, FinalFile);
  662. Complete = true;
  663. Status = StatDone;
  664. Dequeue();
  665. return;
  666. }
  667. /*}}}*/
  668. // AcqIndexDiffs::AcqIndexDiffs - Constructor /*{{{*/
  669. // ---------------------------------------------------------------------
  670. /* The package diff is added to the queue. one object is constructed
  671. * for each diff and the index
  672. */
  673. pkgAcqIndexDiffs::pkgAcqIndexDiffs(pkgAcquire *Owner,
  674. pkgAcqMetaBase *TransactionManager,
  675. struct IndexTarget const * const Target,
  676. HashStringList const &ExpectedHashes,
  677. indexRecords *MetaIndexParser,
  678. vector<DiffInfo> diffs)
  679. : pkgAcqBaseIndex(Owner, TransactionManager, Target, ExpectedHashes, MetaIndexParser),
  680. available_patches(diffs)
  681. {
  682. DestFile = GetPartialFileNameFromURI(Target->URI);
  683. Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
  684. RealURI = Target->URI;
  685. Desc.Owner = this;
  686. Description = Target->Description;
  687. Desc.ShortDesc = Target->ShortDesc;
  688. if(available_patches.empty() == true)
  689. {
  690. // we are done (yeah!), check hashes against the final file
  691. DestFile = GetFinalFileNameFromURI(Target->URI);
  692. Finish(true);
  693. }
  694. else
  695. {
  696. // get the next diff
  697. State = StateFetchDiff;
  698. QueueNextDiff();
  699. }
  700. }
  701. /*}}}*/
  702. void pkgAcqIndexDiffs::Failed(string Message,pkgAcquire::MethodConfig * Cnf)/*{{{*/
  703. {
  704. Item::Failed(Message,Cnf);
  705. Status = StatDone;
  706. if(Debug)
  707. std::clog << "pkgAcqIndexDiffs failed: " << Desc.URI << " with " << Message << std::endl
  708. << "Falling back to normal index file acquire" << std::endl;
  709. new pkgAcqIndex(Owner, TransactionManager, Target, ExpectedHashes, MetaIndexParser);
  710. Finish();
  711. }
  712. /*}}}*/
  713. // Finish - helper that cleans the item out of the fetcher queue /*{{{*/
  714. void pkgAcqIndexDiffs::Finish(bool allDone)
  715. {
  716. if(Debug)
  717. std::clog << "pkgAcqIndexDiffs::Finish(): "
  718. << allDone << " "
  719. << Desc.URI << std::endl;
  720. // we restore the original name, this is required, otherwise
  721. // the file will be cleaned
  722. if(allDone)
  723. {
  724. if(HashSums().usable() && !HashSums().VerifyFile(DestFile))
  725. {
  726. RenameOnError(HashSumMismatch);
  727. Dequeue();
  728. return;
  729. }
  730. TransactionManager->TransactionStageCopy(this, DestFile, GetFinalFilename());
  731. // this is for the "real" finish
  732. Complete = true;
  733. Status = StatDone;
  734. Dequeue();
  735. if(Debug)
  736. std::clog << "\n\nallDone: " << DestFile << "\n" << std::endl;
  737. return;
  738. }
  739. if(Debug)
  740. std::clog << "Finishing: " << Desc.URI << std::endl;
  741. Complete = false;
  742. Status = StatDone;
  743. Dequeue();
  744. return;
  745. }
  746. /*}}}*/
  747. bool pkgAcqIndexDiffs::QueueNextDiff() /*{{{*/
  748. {
  749. // calc sha1 of the just patched file
  750. std::string const FinalFile = GetPartialFileNameFromURI(RealURI);
  751. if(!FileExists(FinalFile))
  752. {
  753. Failed("Message: No FinalFile " + FinalFile + " available", NULL);
  754. return false;
  755. }
  756. FileFd fd(FinalFile, FileFd::ReadOnly);
  757. Hashes LocalHashesCalc;
  758. LocalHashesCalc.AddFD(fd);
  759. HashStringList const LocalHashes = LocalHashesCalc.GetHashStringList();
  760. if(Debug)
  761. std::clog << "QueueNextDiff: " << FinalFile << " (" << LocalHashes.find(NULL)->toStr() << ")" << std::endl;
  762. if (unlikely(LocalHashes.usable() == false || ExpectedHashes.usable() == false))
  763. {
  764. Failed("Local/Expected hashes are not usable", NULL);
  765. return false;
  766. }
  767. // final file reached before all patches are applied
  768. if(LocalHashes == ExpectedHashes)
  769. {
  770. Finish(true);
  771. return true;
  772. }
  773. // remove all patches until the next matching patch is found
  774. // this requires the Index file to be ordered
  775. for(vector<DiffInfo>::iterator I = available_patches.begin();
  776. available_patches.empty() == false &&
  777. I != available_patches.end() &&
  778. I->result_hashes != LocalHashes;
  779. ++I)
  780. {
  781. available_patches.erase(I);
  782. }
  783. // error checking and falling back if no patch was found
  784. if(available_patches.empty() == true)
  785. {
  786. Failed("No patches left to reach target", NULL);
  787. return false;
  788. }
  789. // queue the right diff
  790. Desc.URI = RealURI + ".diff/" + available_patches[0].file + ".gz";
  791. Desc.Description = Description + " " + available_patches[0].file + string(".pdiff");
  792. DestFile = GetPartialFileNameFromURI(RealURI + ".diff/" + available_patches[0].file);
  793. if(Debug)
  794. std::clog << "pkgAcqIndexDiffs::QueueNextDiff(): " << Desc.URI << std::endl;
  795. QueueURI(Desc);
  796. return true;
  797. }
  798. /*}}}*/
  799. void pkgAcqIndexDiffs::Done(string Message,unsigned long long Size, HashStringList const &Hashes, /*{{{*/
  800. pkgAcquire::MethodConfig *Cnf)
  801. {
  802. if(Debug)
  803. std::clog << "pkgAcqIndexDiffs::Done(): " << Desc.URI << std::endl;
  804. Item::Done(Message, Size, Hashes, Cnf);
  805. // FIXME: verify this download too before feeding it to rred
  806. std::string const FinalFile = GetPartialFileNameFromURI(RealURI);
  807. // success in downloading a diff, enter ApplyDiff state
  808. if(State == StateFetchDiff)
  809. {
  810. FileFd fd(DestFile, FileFd::ReadOnly, FileFd::Gzip);
  811. class Hashes LocalHashesCalc;
  812. LocalHashesCalc.AddFD(fd);
  813. HashStringList const LocalHashes = LocalHashesCalc.GetHashStringList();
  814. if (fd.Size() != available_patches[0].patch_size ||
  815. available_patches[0].patch_hashes != LocalHashes)
  816. {
  817. Failed("Patch has Size/Hashsum mismatch", NULL);
  818. return;
  819. }
  820. // rred excepts the patch as $FinalFile.ed
  821. Rename(DestFile,FinalFile+".ed");
  822. if(Debug)
  823. std::clog << "Sending to rred method: " << FinalFile << std::endl;
  824. State = StateApplyDiff;
  825. Local = true;
  826. Desc.URI = "rred:" + FinalFile;
  827. QueueURI(Desc);
  828. SetActiveSubprocess("rred");
  829. return;
  830. }
  831. // success in download/apply a diff, queue next (if needed)
  832. if(State == StateApplyDiff)
  833. {
  834. // remove the just applied patch
  835. available_patches.erase(available_patches.begin());
  836. unlink((FinalFile + ".ed").c_str());
  837. // move into place
  838. if(Debug)
  839. {
  840. std::clog << "Moving patched file in place: " << std::endl
  841. << DestFile << " -> " << FinalFile << std::endl;
  842. }
  843. Rename(DestFile,FinalFile);
  844. chmod(FinalFile.c_str(),0644);
  845. // see if there is more to download
  846. if(available_patches.empty() == false) {
  847. new pkgAcqIndexDiffs(Owner, TransactionManager, Target,
  848. ExpectedHashes, MetaIndexParser,
  849. available_patches);
  850. return Finish();
  851. } else
  852. // update
  853. DestFile = FinalFile;
  854. return Finish(true);
  855. }
  856. }
  857. /*}}}*/
  858. // AcqIndexMergeDiffs::AcqIndexMergeDiffs - Constructor /*{{{*/
  859. pkgAcqIndexMergeDiffs::pkgAcqIndexMergeDiffs(pkgAcquire *Owner,
  860. pkgAcqMetaBase *TransactionManager,
  861. struct IndexTarget const * const Target,
  862. HashStringList const &ExpectedHashes,
  863. indexRecords *MetaIndexParser,
  864. DiffInfo const &patch,
  865. std::vector<pkgAcqIndexMergeDiffs*> const * const allPatches)
  866. : pkgAcqBaseIndex(Owner, TransactionManager, Target, ExpectedHashes, MetaIndexParser),
  867. patch(patch), allPatches(allPatches), State(StateFetchDiff)
  868. {
  869. Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
  870. RealURI = Target->URI;
  871. Desc.Owner = this;
  872. Description = Target->Description;
  873. Desc.ShortDesc = Target->ShortDesc;
  874. Desc.URI = RealURI + ".diff/" + patch.file + ".gz";
  875. Desc.Description = Description + " " + patch.file + string(".pdiff");
  876. DestFile = GetPartialFileNameFromURI(RealURI + ".diff/" + patch.file);
  877. if(Debug)
  878. std::clog << "pkgAcqIndexMergeDiffs: " << Desc.URI << std::endl;
  879. QueueURI(Desc);
  880. }
  881. /*}}}*/
  882. void pkgAcqIndexMergeDiffs::Failed(string Message,pkgAcquire::MethodConfig * Cnf)/*{{{*/
  883. {
  884. if(Debug)
  885. std::clog << "pkgAcqIndexMergeDiffs failed: " << Desc.URI << " with " << Message << std::endl;
  886. Item::Failed(Message,Cnf);
  887. Status = StatDone;
  888. // check if we are the first to fail, otherwise we are done here
  889. State = StateDoneDiff;
  890. for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
  891. I != allPatches->end(); ++I)
  892. if ((*I)->State == StateErrorDiff)
  893. return;
  894. // first failure means we should fallback
  895. State = StateErrorDiff;
  896. std::clog << "Falling back to normal index file acquire" << std::endl;
  897. new pkgAcqIndex(Owner, TransactionManager, Target, ExpectedHashes, MetaIndexParser);
  898. }
  899. /*}}}*/
  900. void pkgAcqIndexMergeDiffs::Done(string Message,unsigned long long Size,HashStringList const &Hashes, /*{{{*/
  901. pkgAcquire::MethodConfig *Cnf)
  902. {
  903. if(Debug)
  904. std::clog << "pkgAcqIndexMergeDiffs::Done(): " << Desc.URI << std::endl;
  905. Item::Done(Message,Size,Hashes,Cnf);
  906. // FIXME: verify download before feeding it to rred
  907. string const FinalFile = GetPartialFileNameFromURI(RealURI);
  908. if (State == StateFetchDiff)
  909. {
  910. FileFd fd(DestFile, FileFd::ReadOnly, FileFd::Gzip);
  911. class Hashes LocalHashesCalc;
  912. LocalHashesCalc.AddFD(fd);
  913. HashStringList const LocalHashes = LocalHashesCalc.GetHashStringList();
  914. if (fd.Size() != patch.patch_size || patch.patch_hashes != LocalHashes)
  915. {
  916. Failed("Patch has Size/Hashsum mismatch", NULL);
  917. return;
  918. }
  919. // rred expects the patch as $FinalFile.ed.$patchname.gz
  920. Rename(DestFile, FinalFile + ".ed." + patch.file + ".gz");
  921. // check if this is the last completed diff
  922. State = StateDoneDiff;
  923. for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
  924. I != allPatches->end(); ++I)
  925. if ((*I)->State != StateDoneDiff)
  926. {
  927. if(Debug)
  928. std::clog << "Not the last done diff in the batch: " << Desc.URI << std::endl;
  929. return;
  930. }
  931. // this is the last completed diff, so we are ready to apply now
  932. State = StateApplyDiff;
  933. if(Debug)
  934. std::clog << "Sending to rred method: " << FinalFile << std::endl;
  935. Local = true;
  936. Desc.URI = "rred:" + FinalFile;
  937. QueueURI(Desc);
  938. SetActiveSubprocess("rred");
  939. return;
  940. }
  941. // success in download/apply all diffs, clean up
  942. else if (State == StateApplyDiff)
  943. {
  944. // see if we really got the expected file
  945. if(ExpectedHashes.usable() && !ExpectedHashes.VerifyFile(DestFile))
  946. {
  947. RenameOnError(HashSumMismatch);
  948. return;
  949. }
  950. // move the result into place
  951. std::string const FinalFile = GetFinalFilename();
  952. if(Debug)
  953. std::clog << "Queue patched file in place: " << std::endl
  954. << DestFile << " -> " << FinalFile << std::endl;
  955. // queue for copy by the transaction manager
  956. TransactionManager->TransactionStageCopy(this, DestFile, FinalFile);
  957. // ensure the ed's are gone regardless of list-cleanup
  958. for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
  959. I != allPatches->end(); ++I)
  960. {
  961. std::string const PartialFile = GetPartialFileNameFromURI(RealURI);
  962. std::string patch = PartialFile + ".ed." + (*I)->patch.file + ".gz";
  963. unlink(patch.c_str());
  964. }
  965. // all set and done
  966. Complete = true;
  967. if(Debug)
  968. std::clog << "allDone: " << DestFile << "\n" << std::endl;
  969. }
  970. }
  971. /*}}}*/
  972. // AcqBaseIndex::VerifyHashByMetaKey - verify hash for the given metakey /*{{{*/
  973. bool pkgAcqBaseIndex::VerifyHashByMetaKey(HashStringList const &Hashes)
  974. {
  975. if(MetaKey != "" && Hashes.usable())
  976. {
  977. indexRecords::checkSum *Record = MetaIndexParser->Lookup(MetaKey);
  978. if(Record && Record->Hashes.usable() && Hashes != Record->Hashes)
  979. {
  980. printHashSumComparision(RealURI, Record->Hashes, Hashes);
  981. return false;
  982. }
  983. }
  984. return true;
  985. }
  986. /*}}}*/
  987. // AcqBaseIndex::GetFinalFilename - Return the full final file path /*{{{*/
  988. std::string pkgAcqBaseIndex::GetFinalFilename() const
  989. {
  990. return GetFinalFileNameFromURI(RealURI);
  991. }
  992. /*}}}*/
  993. // AcqIndex::AcqIndex - Constructor /*{{{*/
  994. // ---------------------------------------------------------------------
  995. /* The package file is added to the queue and a second class is
  996. instantiated to fetch the revision file */
  997. pkgAcqIndex::pkgAcqIndex(pkgAcquire *Owner,
  998. string URI,string URIDesc,string ShortDesc,
  999. HashStringList const &ExpectedHash)
  1000. : pkgAcqBaseIndex(Owner, 0, NULL, ExpectedHash, NULL)
  1001. {
  1002. RealURI = URI;
  1003. AutoSelectCompression();
  1004. Init(URI, URIDesc, ShortDesc);
  1005. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1006. std::clog << "New pkgIndex with TransactionManager "
  1007. << TransactionManager << std::endl;
  1008. }
  1009. /*}}}*/
  1010. // AcqIndex::AcqIndex - Constructor /*{{{*/
  1011. pkgAcqIndex::pkgAcqIndex(pkgAcquire *Owner,
  1012. pkgAcqMetaBase *TransactionManager,
  1013. IndexTarget const *Target,
  1014. HashStringList const &ExpectedHash,
  1015. indexRecords *MetaIndexParser)
  1016. : pkgAcqBaseIndex(Owner, TransactionManager, Target, ExpectedHash,
  1017. MetaIndexParser)
  1018. {
  1019. RealURI = Target->URI;
  1020. // autoselect the compression method
  1021. AutoSelectCompression();
  1022. Init(Target->URI, Target->Description, Target->ShortDesc);
  1023. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1024. std::clog << "New pkgIndex with TransactionManager "
  1025. << TransactionManager << std::endl;
  1026. }
  1027. /*}}}*/
  1028. // AcqIndex::AutoSelectCompression - Select compression /*{{{*/
  1029. void pkgAcqIndex::AutoSelectCompression()
  1030. {
  1031. std::vector<std::string> types = APT::Configuration::getCompressionTypes();
  1032. CompressionExtensions = "";
  1033. if (ExpectedHashes.usable())
  1034. {
  1035. for (std::vector<std::string>::const_iterator t = types.begin();
  1036. t != types.end(); ++t)
  1037. {
  1038. std::string CompressedMetaKey = string(Target->MetaKey).append(".").append(*t);
  1039. if (*t == "uncompressed" ||
  1040. MetaIndexParser->Exists(CompressedMetaKey) == true)
  1041. CompressionExtensions.append(*t).append(" ");
  1042. }
  1043. }
  1044. else
  1045. {
  1046. for (std::vector<std::string>::const_iterator t = types.begin(); t != types.end(); ++t)
  1047. CompressionExtensions.append(*t).append(" ");
  1048. }
  1049. if (CompressionExtensions.empty() == false)
  1050. CompressionExtensions.erase(CompressionExtensions.end()-1);
  1051. }
  1052. /*}}}*/
  1053. // AcqIndex::Init - defered Constructor /*{{{*/
  1054. void pkgAcqIndex::Init(string const &URI, string const &URIDesc,
  1055. string const &ShortDesc)
  1056. {
  1057. Stage = STAGE_DOWNLOAD;
  1058. DestFile = GetPartialFileNameFromURI(URI);
  1059. CurrentCompressionExtension = CompressionExtensions.substr(0, CompressionExtensions.find(' '));
  1060. if (CurrentCompressionExtension == "uncompressed")
  1061. {
  1062. Desc.URI = URI;
  1063. if(Target)
  1064. MetaKey = string(Target->MetaKey);
  1065. }
  1066. else
  1067. {
  1068. Desc.URI = URI + '.' + CurrentCompressionExtension;
  1069. DestFile = DestFile + '.' + CurrentCompressionExtension;
  1070. if(Target)
  1071. MetaKey = string(Target->MetaKey) + '.' + CurrentCompressionExtension;
  1072. }
  1073. // load the filesize
  1074. if(MetaIndexParser)
  1075. {
  1076. indexRecords::checkSum *Record = MetaIndexParser->Lookup(MetaKey);
  1077. if(Record)
  1078. FileSize = Record->Size;
  1079. InitByHashIfNeeded(MetaKey);
  1080. }
  1081. Desc.Description = URIDesc;
  1082. Desc.Owner = this;
  1083. Desc.ShortDesc = ShortDesc;
  1084. QueueURI(Desc);
  1085. }
  1086. /*}}}*/
  1087. // AcqIndex::AdjustForByHash - modify URI for by-hash support /*{{{*/
  1088. void pkgAcqIndex::InitByHashIfNeeded(const std::string MetaKey)
  1089. {
  1090. // TODO:
  1091. // - (maybe?) add support for by-hash into the sources.list as flag
  1092. // - make apt-ftparchive generate the hashes (and expire?)
  1093. std::string HostKnob = "APT::Acquire::" + ::URI(Desc.URI).Host + "::By-Hash";
  1094. if(_config->FindB("APT::Acquire::By-Hash", false) == true ||
  1095. _config->FindB(HostKnob, false) == true ||
  1096. MetaIndexParser->GetSupportsAcquireByHash())
  1097. {
  1098. indexRecords::checkSum *Record = MetaIndexParser->Lookup(MetaKey);
  1099. if(Record)
  1100. {
  1101. // FIXME: should we really use the best hash here? or a fixed one?
  1102. const HashString *TargetHash = Record->Hashes.find("");
  1103. std::string ByHash = "/by-hash/" + TargetHash->HashType() + "/" + TargetHash->HashValue();
  1104. size_t trailing_slash = Desc.URI.find_last_of("/");
  1105. Desc.URI = Desc.URI.replace(
  1106. trailing_slash,
  1107. Desc.URI.substr(trailing_slash+1).size()+1,
  1108. ByHash);
  1109. } else {
  1110. _error->Warning(
  1111. "Fetching ByHash requested but can not find record for %s",
  1112. MetaKey.c_str());
  1113. }
  1114. }
  1115. }
  1116. /*}}}*/
  1117. // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
  1118. // ---------------------------------------------------------------------
  1119. /* The only header we use is the last-modified header. */
  1120. #if APT_PKG_ABI >= 413
  1121. string pkgAcqIndex::Custom600Headers() const
  1122. #else
  1123. string pkgAcqIndex::Custom600Headers()
  1124. #endif
  1125. {
  1126. string Final = GetFinalFilename();
  1127. string msg = "\nIndex-File: true";
  1128. struct stat Buf;
  1129. if (stat(Final.c_str(),&Buf) == 0)
  1130. msg += "\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  1131. if(Target->IsOptional())
  1132. msg += "\nFail-Ignore: true";
  1133. return msg;
  1134. }
  1135. /*}}}*/
  1136. // pkgAcqIndex::Failed - getting the indexfile failed /*{{{*/
  1137. void pkgAcqIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  1138. {
  1139. Item::Failed(Message,Cnf);
  1140. size_t const nextExt = CompressionExtensions.find(' ');
  1141. if (nextExt != std::string::npos)
  1142. {
  1143. CompressionExtensions = CompressionExtensions.substr(nextExt+1);
  1144. Init(RealURI, Desc.Description, Desc.ShortDesc);
  1145. Status = StatIdle;
  1146. return;
  1147. }
  1148. // on decompression failure, remove bad versions in partial/
  1149. if (Stage == STAGE_DECOMPRESS_AND_VERIFY)
  1150. {
  1151. unlink(EraseFileName.c_str());
  1152. }
  1153. Item::Failed(Message,Cnf);
  1154. if(Target->IsOptional() && ExpectedHashes.empty() && Stage == STAGE_DOWNLOAD)
  1155. Status = StatDone;
  1156. else
  1157. TransactionManager->AbortTransaction();
  1158. }
  1159. /*}}}*/
  1160. // pkgAcqIndex::GetFinalFilename - Return the full final file path /*{{{*/
  1161. std::string pkgAcqIndex::GetFinalFilename() const
  1162. {
  1163. std::string const FinalFile = GetFinalFileNameFromURI(RealURI);
  1164. return GetCompressedFileName(RealURI, FinalFile, CurrentCompressionExtension);
  1165. }
  1166. /*}}}*/
  1167. // AcqIndex::ReverifyAfterIMS - Reverify index after an ims-hit /*{{{*/
  1168. void pkgAcqIndex::ReverifyAfterIMS()
  1169. {
  1170. // update destfile to *not* include the compression extension when doing
  1171. // a reverify (as its uncompressed on disk already)
  1172. DestFile = GetCompressedFileName(RealURI, GetPartialFileNameFromURI(RealURI), CurrentCompressionExtension);
  1173. // copy FinalFile into partial/ so that we check the hash again
  1174. string FinalFile = GetFinalFilename();
  1175. Stage = STAGE_DECOMPRESS_AND_VERIFY;
  1176. Desc.URI = "copy:" + FinalFile;
  1177. QueueURI(Desc);
  1178. }
  1179. /*}}}*/
  1180. // AcqIndex::ValidateFile - Validate the content of the downloaded file /*{{{*/
  1181. bool pkgAcqIndex::ValidateFile(const std::string &FileName)
  1182. {
  1183. // FIXME: this can go away once we only ever download stuff that
  1184. // has a valid hash and we never do GET based probing
  1185. // FIXME2: this also leaks debian-isms into the code and should go therefore
  1186. /* Always validate the index file for correctness (all indexes must
  1187. * have a Package field) (LP: #346386) (Closes: #627642)
  1188. */
  1189. FileFd fd(FileName, FileFd::ReadOnly, FileFd::Extension);
  1190. // Only test for correctness if the content of the file is not empty
  1191. // (empty is ok)
  1192. if (fd.Size() > 0)
  1193. {
  1194. pkgTagSection sec;
  1195. pkgTagFile tag(&fd);
  1196. // all our current indexes have a field 'Package' in each section
  1197. if (_error->PendingError() == true ||
  1198. tag.Step(sec) == false ||
  1199. sec.Exists("Package") == false)
  1200. return false;
  1201. }
  1202. return true;
  1203. }
  1204. /*}}}*/
  1205. // AcqIndex::Done - Finished a fetch /*{{{*/
  1206. // ---------------------------------------------------------------------
  1207. /* This goes through a number of states.. On the initial fetch the
  1208. method could possibly return an alternate filename which points
  1209. to the uncompressed version of the file. If this is so the file
  1210. is copied into the partial directory. In all other cases the file
  1211. is decompressed with a compressed uri. */
  1212. void pkgAcqIndex::Done(string Message,
  1213. unsigned long long Size,
  1214. HashStringList const &Hashes,
  1215. pkgAcquire::MethodConfig *Cfg)
  1216. {
  1217. Item::Done(Message,Size,Hashes,Cfg);
  1218. switch(Stage)
  1219. {
  1220. case STAGE_DOWNLOAD:
  1221. StageDownloadDone(Message, Hashes, Cfg);
  1222. break;
  1223. case STAGE_DECOMPRESS_AND_VERIFY:
  1224. StageDecompressDone(Message, Hashes, Cfg);
  1225. break;
  1226. }
  1227. }
  1228. /*}}}*/
  1229. // AcqIndex::StageDownloadDone - Queue for decompress and verify /*{{{*/
  1230. void pkgAcqIndex::StageDownloadDone(string Message,
  1231. HashStringList const &Hashes,
  1232. pkgAcquire::MethodConfig *Cfg)
  1233. {
  1234. // First check if the calculcated Hash of the (compressed) downloaded
  1235. // file matches the hash we have in the MetaIndexRecords for this file
  1236. if(VerifyHashByMetaKey(Hashes) == false)
  1237. {
  1238. RenameOnError(HashSumMismatch);
  1239. Failed(Message, Cfg);
  1240. return;
  1241. }
  1242. Complete = true;
  1243. // Handle the unzipd case
  1244. string FileName = LookupTag(Message,"Alt-Filename");
  1245. if (FileName.empty() == false)
  1246. {
  1247. Stage = STAGE_DECOMPRESS_AND_VERIFY;
  1248. Local = true;
  1249. DestFile += ".decomp";
  1250. Desc.URI = "copy:" + FileName;
  1251. QueueURI(Desc);
  1252. SetActiveSubprocess("copy");
  1253. return;
  1254. }
  1255. FileName = LookupTag(Message,"Filename");
  1256. if (FileName.empty() == true)
  1257. {
  1258. Status = StatError;
  1259. ErrorText = "Method gave a blank filename";
  1260. }
  1261. // Methods like e.g. "file:" will give us a (compressed) FileName that is
  1262. // not the "DestFile" we set, in this case we uncompress from the local file
  1263. if (FileName != DestFile)
  1264. Local = true;
  1265. else
  1266. EraseFileName = FileName;
  1267. // we need to verify the file against the current Release file again
  1268. // on if-modfied-since hit to avoid a stale attack against us
  1269. if(StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  1270. {
  1271. // The files timestamp matches, reverify by copy into partial/
  1272. EraseFileName = "";
  1273. ReverifyAfterIMS();
  1274. return;
  1275. }
  1276. // If we have compressed indexes enabled, queue for hash verification
  1277. if (_config->FindB("Acquire::GzipIndexes",false))
  1278. {
  1279. DestFile = GetPartialFileNameFromURI(RealURI + '.' + CurrentCompressionExtension);
  1280. EraseFileName = "";
  1281. Stage = STAGE_DECOMPRESS_AND_VERIFY;
  1282. Desc.URI = "copy:" + FileName;
  1283. QueueURI(Desc);
  1284. SetActiveSubprocess("copy");
  1285. return;
  1286. }
  1287. // get the binary name for your used compression type
  1288. string decompProg;
  1289. if(CurrentCompressionExtension == "uncompressed")
  1290. decompProg = "copy";
  1291. else
  1292. decompProg = _config->Find(string("Acquire::CompressionTypes::").append(CurrentCompressionExtension),"");
  1293. if(decompProg.empty() == true)
  1294. {
  1295. _error->Error("Unsupported extension: %s", CurrentCompressionExtension.c_str());
  1296. return;
  1297. }
  1298. // queue uri for the next stage
  1299. Stage = STAGE_DECOMPRESS_AND_VERIFY;
  1300. DestFile += ".decomp";
  1301. Desc.URI = decompProg + ":" + FileName;
  1302. QueueURI(Desc);
  1303. SetActiveSubprocess(decompProg);
  1304. }
  1305. /*}}}*/
  1306. // pkgAcqIndex::StageDecompressDone - Final verification /*{{{*/
  1307. void pkgAcqIndex::StageDecompressDone(string Message,
  1308. HashStringList const &Hashes,
  1309. pkgAcquire::MethodConfig *Cfg)
  1310. {
  1311. if (ExpectedHashes.usable() && ExpectedHashes != Hashes)
  1312. {
  1313. Desc.URI = RealURI;
  1314. RenameOnError(HashSumMismatch);
  1315. printHashSumComparision(RealURI, ExpectedHashes, Hashes);
  1316. Failed(Message, Cfg);
  1317. return;
  1318. }
  1319. if(!ValidateFile(DestFile))
  1320. {
  1321. RenameOnError(InvalidFormat);
  1322. Failed(Message, Cfg);
  1323. return;
  1324. }
  1325. // remove the compressed version of the file
  1326. unlink(EraseFileName.c_str());
  1327. // Done, queue for rename on transaction finished
  1328. TransactionManager->TransactionStageCopy(this, DestFile, GetFinalFilename());
  1329. return;
  1330. }
  1331. /*}}}*/
  1332. // AcqMetaBase::Add - Add a item to the current Transaction /*{{{*/
  1333. void pkgAcqMetaBase::Add(Item *I)
  1334. {
  1335. Transaction.push_back(I);
  1336. }
  1337. /*}}}*/
  1338. // AcqMetaBase::AbortTransaction - Abort the current Transaction /*{{{*/
  1339. void pkgAcqMetaBase::AbortTransaction()
  1340. {
  1341. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1342. std::clog << "AbortTransaction: " << TransactionManager << std::endl;
  1343. // ensure the toplevel is in error state too
  1344. for (std::vector<Item*>::iterator I = Transaction.begin();
  1345. I != Transaction.end(); ++I)
  1346. {
  1347. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1348. std::clog << " Cancel: " << (*I)->DestFile << std::endl;
  1349. // the transaction will abort, so stop anything that is idle
  1350. if ((*I)->Status == pkgAcquire::Item::StatIdle)
  1351. {
  1352. (*I)->Status = pkgAcquire::Item::StatDone;
  1353. (*I)->Dequeue();
  1354. }
  1355. }
  1356. Transaction.clear();
  1357. }
  1358. /*}}}*/
  1359. // AcqMetaBase::TransactionHasError - Check for errors in Transaction /*{{{*/
  1360. bool pkgAcqMetaBase::TransactionHasError()
  1361. {
  1362. for (pkgAcquire::ItemIterator I = Transaction.begin();
  1363. I != Transaction.end(); ++I)
  1364. if((*I)->Status != pkgAcquire::Item::StatDone &&
  1365. (*I)->Status != pkgAcquire::Item::StatIdle)
  1366. return true;
  1367. return false;
  1368. }
  1369. /*}}}*/
  1370. // AcqMetaBase::CommitTransaction - Commit a transaction /*{{{*/
  1371. void pkgAcqMetaBase::CommitTransaction()
  1372. {
  1373. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1374. std::clog << "CommitTransaction: " << this << std::endl;
  1375. // move new files into place *and* remove files that are not
  1376. // part of the transaction but are still on disk
  1377. for (std::vector<Item*>::iterator I = Transaction.begin();
  1378. I != Transaction.end(); ++I)
  1379. {
  1380. if((*I)->PartialFile != "")
  1381. {
  1382. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1383. std::clog << "mv " << (*I)->PartialFile << " -> "<< (*I)->DestFile << " "
  1384. << (*I)->DescURI() << std::endl;
  1385. Rename((*I)->PartialFile, (*I)->DestFile);
  1386. } else {
  1387. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1388. std::clog << "rm "
  1389. << (*I)->DestFile
  1390. << " "
  1391. << (*I)->DescURI()
  1392. << std::endl;
  1393. unlink((*I)->DestFile.c_str());
  1394. }
  1395. // mark that this transaction is finished
  1396. (*I)->TransactionManager = 0;
  1397. }
  1398. Transaction.clear();
  1399. }
  1400. /*}}}*/
  1401. // AcqMetaBase::TransactionStageCopy - Stage a file for copying /*{{{*/
  1402. void pkgAcqMetaBase::TransactionStageCopy(Item *I,
  1403. const std::string &From,
  1404. const std::string &To)
  1405. {
  1406. I->PartialFile = From;
  1407. I->DestFile = To;
  1408. }
  1409. /*}}}*/
  1410. // AcqMetaBase::TransactionStageRemoval - Sage a file for removal /*{{{*/
  1411. void pkgAcqMetaBase::TransactionStageRemoval(Item *I,
  1412. const std::string &FinalFile)
  1413. {
  1414. I->PartialFile = "";
  1415. I->DestFile = FinalFile;
  1416. }
  1417. /*}}}*/
  1418. // AcqMetaBase::GenerateAuthWarning - Check gpg authentication error /*{{{*/
  1419. bool pkgAcqMetaBase::CheckStopAuthentication(const std::string &Message)
  1420. {
  1421. // FIXME: this entire function can do now that we disallow going to
  1422. // a unauthenticated state and can cleanly rollback
  1423. string const Final = GetFinalFilename();
  1424. if(FileExists(Final))
  1425. {
  1426. Status = StatTransientNetworkError;
  1427. _error->Warning(_("An error occurred during the signature "
  1428. "verification. The repository is not updated "
  1429. "and the previous index files will be used. "
  1430. "GPG error: %s: %s\n"),
  1431. Desc.Description.c_str(),
  1432. LookupTag(Message,"Message").c_str());
  1433. RunScripts("APT::Update::Auth-Failure");
  1434. return true;
  1435. } else if (LookupTag(Message,"Message").find("NODATA") != string::npos) {
  1436. /* Invalid signature file, reject (LP: #346386) (Closes: #627642) */
  1437. _error->Error(_("GPG error: %s: %s"),
  1438. Desc.Description.c_str(),
  1439. LookupTag(Message,"Message").c_str());
  1440. Status = StatError;
  1441. return true;
  1442. } else {
  1443. _error->Warning(_("GPG error: %s: %s"),
  1444. Desc.Description.c_str(),
  1445. LookupTag(Message,"Message").c_str());
  1446. }
  1447. // gpgv method failed
  1448. ReportMirrorFailure("GPGFailure");
  1449. return false;
  1450. }
  1451. /*}}}*/
  1452. // AcqMetaSig::AcqMetaSig - Constructor /*{{{*/
  1453. pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire *Owner,
  1454. pkgAcqMetaBase *TransactionManager,
  1455. string URI,string URIDesc,string ShortDesc,
  1456. string MetaIndexFile,
  1457. const vector<IndexTarget*>* IndexTargets,
  1458. indexRecords* MetaIndexParser) :
  1459. pkgAcqMetaBase(Owner, IndexTargets, MetaIndexParser, URI,
  1460. HashStringList(), TransactionManager),
  1461. MetaIndexFile(MetaIndexFile), URIDesc(URIDesc),
  1462. ShortDesc(ShortDesc)
  1463. {
  1464. DestFile = GetPartialFileNameFromURI(RealURI);
  1465. // remove any partial downloaded sig-file in partial/.
  1466. // it may confuse proxies and is too small to warrant a
  1467. // partial download anyway
  1468. unlink(DestFile.c_str());
  1469. // set the TransactionManager
  1470. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1471. std::clog << "New pkgAcqMetaSig with TransactionManager "
  1472. << TransactionManager << std::endl;
  1473. // Create the item
  1474. Desc.Description = URIDesc;
  1475. Desc.Owner = this;
  1476. Desc.ShortDesc = ShortDesc;
  1477. Desc.URI = URI;
  1478. QueueURI(Desc);
  1479. }
  1480. /*}}}*/
  1481. pkgAcqMetaSig::~pkgAcqMetaSig() /*{{{*/
  1482. {
  1483. }
  1484. /*}}}*/
  1485. // pkgAcqMetaSig::Done - The signature was downloaded/verified /*{{{*/
  1486. // ---------------------------------------------------------------------
  1487. /* The only header we use is the last-modified header. */
  1488. void pkgAcqMetaSig::Done(string Message,unsigned long long Size,
  1489. HashStringList const &Hashes,
  1490. pkgAcquire::MethodConfig *Cfg)
  1491. {
  1492. Item::Done(Message, Size, Hashes, Cfg);
  1493. if(AuthPass == false)
  1494. {
  1495. if(CheckDownloadDone(Message) == true)
  1496. {
  1497. // destfile will be modified to point to MetaIndexFile for the
  1498. // gpgv method, so we need to save it here
  1499. MetaIndexFileSignature = DestFile;
  1500. QueueForSignatureVerify(MetaIndexFile, MetaIndexFileSignature);
  1501. }
  1502. return;
  1503. }
  1504. else if(CheckAuthDone(Message) == true)
  1505. TransactionManager->TransactionStageCopy(this, MetaIndexFileSignature, GetFinalFilename());
  1506. }
  1507. /*}}}*/
  1508. void pkgAcqMetaSig::Failed(string Message,pkgAcquire::MethodConfig *Cnf)/*{{{*/
  1509. {
  1510. Item::Failed(Message,Cnf);
  1511. // check if we need to fail at this point
  1512. if (AuthPass == true && CheckStopAuthentication(Message))
  1513. return;
  1514. // FIXME: meh, this is not really elegant
  1515. string const Final = GetFinalFileNameFromURI(RealURI);
  1516. string const InReleaseURI = RealURI.replace(RealURI.rfind("Release.gpg"), 12,
  1517. "InRelease");
  1518. string const FinalInRelease = GetFinalFileNameFromURI(InReleaseURI);
  1519. if (RealFileExists(Final) || RealFileExists(FinalInRelease))
  1520. {
  1521. std::string downgrade_msg;
  1522. strprintf(downgrade_msg, _("The repository '%s' is no longer signed."),
  1523. URIDesc.c_str());
  1524. if(_config->FindB("Acquire::AllowDowngradeToInsecureRepositories"))
  1525. {
  1526. // meh, the users wants to take risks (we still mark the packages
  1527. // from this repository as unauthenticated)
  1528. _error->Warning("%s", downgrade_msg.c_str());
  1529. _error->Warning(_("This is normally not allowed, but the option "
  1530. "Acquire::AllowDowngradeToInsecureRepositories was "
  1531. "given to override it."));
  1532. Status = StatDone;
  1533. } else {
  1534. _error->Error("%s", downgrade_msg.c_str());
  1535. Rename(MetaIndexFile, MetaIndexFile+".FAILED");
  1536. Item::Failed("Message: " + downgrade_msg, Cnf);
  1537. TransactionManager->AbortTransaction();
  1538. return;
  1539. }
  1540. }
  1541. else
  1542. _error->Warning(_("The data from '%s' is not signed. Packages "
  1543. "from that repository can not be authenticated."),
  1544. URIDesc.c_str());
  1545. // this ensures that any file in the lists/ dir is removed by the
  1546. // transaction
  1547. DestFile = GetPartialFileNameFromURI(RealURI);
  1548. TransactionManager->TransactionStageRemoval(this, DestFile);
  1549. // only allow going further if the users explicitely wants it
  1550. if(AllowInsecureRepositories(MetaIndexParser, TransactionManager, this) == true)
  1551. {
  1552. // we parse the indexes here because at this point the user wanted
  1553. // a repository that may potentially harm him
  1554. MetaIndexParser->Load(MetaIndexFile);
  1555. if (!VerifyVendor(Message))
  1556. /* expired Release files are still a problem you need extra force for */;
  1557. else
  1558. QueueIndexes(true);
  1559. }
  1560. // FIXME: this is used often (e.g. in pkgAcqIndexTrans) so refactor
  1561. if (Cnf->LocalOnly == true ||
  1562. StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
  1563. {
  1564. // Ignore this
  1565. Status = StatDone;
  1566. }
  1567. }
  1568. /*}}}*/
  1569. pkgAcqMetaIndex::pkgAcqMetaIndex(pkgAcquire *Owner, /*{{{*/
  1570. pkgAcqMetaBase *TransactionManager,
  1571. string URI,string URIDesc,string ShortDesc,
  1572. string MetaIndexSigURI,string MetaIndexSigURIDesc, string MetaIndexSigShortDesc,
  1573. const vector<IndexTarget*>* IndexTargets,
  1574. indexRecords* MetaIndexParser) :
  1575. pkgAcqMetaBase(Owner, IndexTargets, MetaIndexParser, URI, HashStringList(),
  1576. TransactionManager),
  1577. URIDesc(URIDesc), ShortDesc(ShortDesc),
  1578. MetaIndexSigURI(MetaIndexSigURI), MetaIndexSigURIDesc(MetaIndexSigURIDesc),
  1579. MetaIndexSigShortDesc(MetaIndexSigShortDesc)
  1580. {
  1581. if(TransactionManager == NULL)
  1582. {
  1583. this->TransactionManager = this;
  1584. this->TransactionManager->Add(this);
  1585. }
  1586. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1587. std::clog << "New pkgAcqMetaIndex with TransactionManager "
  1588. << this->TransactionManager << std::endl;
  1589. Init(URIDesc, ShortDesc);
  1590. }
  1591. /*}}}*/
  1592. // pkgAcqMetaIndex::Init - Delayed constructor /*{{{*/
  1593. void pkgAcqMetaIndex::Init(std::string URIDesc, std::string ShortDesc)
  1594. {
  1595. DestFile = GetPartialFileNameFromURI(RealURI);
  1596. // Create the item
  1597. Desc.Description = URIDesc;
  1598. Desc.Owner = this;
  1599. Desc.ShortDesc = ShortDesc;
  1600. Desc.URI = RealURI;
  1601. // we expect more item
  1602. ExpectedAdditionalItems = IndexTargets->size();
  1603. QueueURI(Desc);
  1604. }
  1605. /*}}}*/
  1606. void pkgAcqMetaIndex::Done(string Message,unsigned long long Size, /*{{{*/
  1607. HashStringList const &Hashes,
  1608. pkgAcquire::MethodConfig *Cfg)
  1609. {
  1610. Item::Done(Message,Size,Hashes,Cfg);
  1611. if(CheckDownloadDone(Message))
  1612. {
  1613. // we have a Release file, now download the Signature, all further
  1614. // verify/queue for additional downloads will be done in the
  1615. // pkgAcqMetaSig::Done() code
  1616. std::string MetaIndexFile = DestFile;
  1617. new pkgAcqMetaSig(Owner, TransactionManager,
  1618. MetaIndexSigURI, MetaIndexSigURIDesc,
  1619. MetaIndexSigShortDesc, MetaIndexFile, IndexTargets,
  1620. MetaIndexParser);
  1621. TransactionManager->TransactionStageCopy(this, DestFile, GetFinalFilename());
  1622. }
  1623. }
  1624. /*}}}*/
  1625. bool pkgAcqMetaBase::CheckAuthDone(string Message) /*{{{*/
  1626. {
  1627. // At this point, the gpgv method has succeeded, so there is a
  1628. // valid signature from a key in the trusted keyring. We
  1629. // perform additional verification of its contents, and use them
  1630. // to verify the indexes we are about to download
  1631. if (!MetaIndexParser->Load(DestFile))
  1632. {
  1633. Status = StatAuthError;
  1634. ErrorText = MetaIndexParser->ErrorText;
  1635. return false;
  1636. }
  1637. if (!VerifyVendor(Message))
  1638. {
  1639. Status = StatAuthError;
  1640. return false;
  1641. }
  1642. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1643. std::cerr << "Signature verification succeeded: "
  1644. << DestFile << std::endl;
  1645. // Download further indexes with verification
  1646. //
  1647. // it would be really nice if we could simply do
  1648. // if (IMSHit == false) QueueIndexes(true)
  1649. // and skip the download if the Release file has not changed
  1650. // - but right now the list cleaner will needs to be tricked
  1651. // to not delete all our packages/source indexes in this case
  1652. QueueIndexes(true);
  1653. return true;
  1654. }
  1655. /*}}}*/
  1656. // pkgAcqMetaBase::Custom600Headers - Get header for AcqMetaBase /*{{{*/
  1657. // ---------------------------------------------------------------------
  1658. #if APT_PKG_ABI >= 413
  1659. string pkgAcqMetaBase::Custom600Headers() const
  1660. #else
  1661. string pkgAcqMetaBase::Custom600Headers()
  1662. #endif
  1663. {
  1664. std::string Header = "\nIndex-File: true";
  1665. std::string MaximumSize;
  1666. strprintf(MaximumSize, "\nMaximum-Size: %i",
  1667. _config->FindI("Acquire::MaxReleaseFileSize", 10*1000*1000));
  1668. Header += MaximumSize;
  1669. string const FinalFile = GetFinalFilename();
  1670. struct stat Buf;
  1671. if (stat(FinalFile.c_str(),&Buf) == 0)
  1672. Header += "\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  1673. return Header;
  1674. }
  1675. /*}}}*/
  1676. // pkgAcqMetaBase::GetFinalFilename - Return the full final file path /*{{{*/
  1677. std::string pkgAcqMetaBase::GetFinalFilename() const
  1678. {
  1679. return GetFinalFileNameFromURI(RealURI);
  1680. }
  1681. /*}}}*/
  1682. // pkgAcqMetaBase::QueueForSignatureVerify /*{{{*/
  1683. void pkgAcqMetaBase::QueueForSignatureVerify(const std::string &MetaIndexFile,
  1684. const std::string &MetaIndexFileSignature)
  1685. {
  1686. AuthPass = true;
  1687. Desc.URI = "gpgv:" + MetaIndexFileSignature;
  1688. DestFile = MetaIndexFile;
  1689. QueueURI(Desc);
  1690. SetActiveSubprocess("gpgv");
  1691. }
  1692. /*}}}*/
  1693. // pkgAcqMetaBase::CheckDownloadDone /*{{{*/
  1694. bool pkgAcqMetaBase::CheckDownloadDone(const std::string &Message)
  1695. {
  1696. // We have just finished downloading a Release file (it is not
  1697. // verified yet)
  1698. string FileName = LookupTag(Message,"Filename");
  1699. if (FileName.empty() == true)
  1700. {
  1701. Status = StatError;
  1702. ErrorText = "Method gave a blank filename";
  1703. return false;
  1704. }
  1705. if (FileName != DestFile)
  1706. {
  1707. Local = true;
  1708. Desc.URI = "copy:" + FileName;
  1709. QueueURI(Desc);
  1710. return false;
  1711. }
  1712. // make sure to verify against the right file on I-M-S hit
  1713. IMSHit = StringToBool(LookupTag(Message,"IMS-Hit"),false);
  1714. if(IMSHit)
  1715. DestFile = GetFinalFilename();
  1716. // set Item to complete as the remaining work is all local (verify etc)
  1717. Complete = true;
  1718. return true;
  1719. }
  1720. /*}}}*/
  1721. void pkgAcqMetaBase::QueueIndexes(bool verify) /*{{{*/
  1722. {
  1723. // at this point the real Items are loaded in the fetcher
  1724. ExpectedAdditionalItems = 0;
  1725. vector <struct IndexTarget*>::const_iterator Target;
  1726. for (Target = IndexTargets->begin();
  1727. Target != IndexTargets->end();
  1728. ++Target)
  1729. {
  1730. HashStringList ExpectedIndexHashes;
  1731. const indexRecords::checkSum *Record = MetaIndexParser->Lookup((*Target)->MetaKey);
  1732. // optional target that we do not have in the Release file are
  1733. // skipped
  1734. if (verify == true && Record == NULL && (*Target)->IsOptional())
  1735. continue;
  1736. // targets without a hash record are a error when verify is required
  1737. if (verify == true && Record == NULL)
  1738. {
  1739. Status = StatAuthError;
  1740. strprintf(ErrorText, _("Unable to find expected entry '%s' in Release file (Wrong sources.list entry or malformed file)"), (*Target)->MetaKey.c_str());
  1741. return;
  1742. }
  1743. if (Record)
  1744. ExpectedIndexHashes = Record->Hashes;
  1745. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1746. {
  1747. std::cerr << "Queueing: " << (*Target)->URI << std::endl
  1748. << "Expected Hash:" << std::endl;
  1749. for (HashStringList::const_iterator hs = ExpectedIndexHashes.begin(); hs != ExpectedIndexHashes.end(); ++hs)
  1750. std::cerr << "\t- " << hs->toStr() << std::endl;
  1751. std::cerr << "For: " << Record->MetaKeyFilename << std::endl;
  1752. }
  1753. if (verify == true && ExpectedIndexHashes.empty() == true)
  1754. {
  1755. Status = StatAuthError;
  1756. strprintf(ErrorText, _("Unable to find hash sum for '%s' in Release file"), (*Target)->MetaKey.c_str());
  1757. return;
  1758. }
  1759. /* Queue the Index file (Packages, Sources, Translation-$foo
  1760. (either diff or full packages files, depending
  1761. on the users option) - we also check if the PDiff Index file is listed
  1762. in the Meta-Index file. Ideal would be if pkgAcqDiffIndex would test this
  1763. instead, but passing the required info to it is to much hassle */
  1764. if(_config->FindB("Acquire::PDiffs",true) == true && (verify == false ||
  1765. MetaIndexParser->Exists((*Target)->MetaKey + ".diff/Index") == true))
  1766. new pkgAcqDiffIndex(Owner, TransactionManager, *Target, ExpectedIndexHashes, MetaIndexParser);
  1767. else
  1768. new pkgAcqIndex(Owner, TransactionManager, *Target, ExpectedIndexHashes, MetaIndexParser);
  1769. }
  1770. }
  1771. /*}}}*/
  1772. bool pkgAcqMetaBase::VerifyVendor(string Message) /*{{{*/
  1773. {
  1774. string::size_type pos;
  1775. // check for missing sigs (that where not fatal because otherwise we had
  1776. // bombed earlier)
  1777. string missingkeys;
  1778. string msg = _("There is no public key available for the "
  1779. "following key IDs:\n");
  1780. pos = Message.find("NO_PUBKEY ");
  1781. if (pos != std::string::npos)
  1782. {
  1783. string::size_type start = pos+strlen("NO_PUBKEY ");
  1784. string Fingerprint = Message.substr(start, Message.find("\n")-start);
  1785. missingkeys += (Fingerprint);
  1786. }
  1787. if(!missingkeys.empty())
  1788. _error->Warning("%s", (msg + missingkeys).c_str());
  1789. string Transformed = MetaIndexParser->GetExpectedDist();
  1790. if (Transformed == "../project/experimental")
  1791. {
  1792. Transformed = "experimental";
  1793. }
  1794. pos = Transformed.rfind('/');
  1795. if (pos != string::npos)
  1796. {
  1797. Transformed = Transformed.substr(0, pos);
  1798. }
  1799. if (Transformed == ".")
  1800. {
  1801. Transformed = "";
  1802. }
  1803. if (_config->FindB("Acquire::Check-Valid-Until", true) == true &&
  1804. MetaIndexParser->GetValidUntil() > 0) {
  1805. time_t const invalid_since = time(NULL) - MetaIndexParser->GetValidUntil();
  1806. if (invalid_since > 0)
  1807. {
  1808. std::string errmsg;
  1809. strprintf(errmsg,
  1810. // TRANSLATOR: The first %s is the URL of the bad Release file, the second is
  1811. // the time since then the file is invalid - formated in the same way as in
  1812. // the download progress display (e.g. 7d 3h 42min 1s)
  1813. _("Release file for %s is expired (invalid since %s). "
  1814. "Updates for this repository will not be applied."),
  1815. RealURI.c_str(), TimeToStr(invalid_since).c_str());
  1816. if (ErrorText.empty())
  1817. ErrorText = errmsg;
  1818. return _error->Error("%s", errmsg.c_str());
  1819. }
  1820. }
  1821. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1822. {
  1823. std::cerr << "Got Codename: " << MetaIndexParser->GetDist() << std::endl;
  1824. std::cerr << "Expecting Dist: " << MetaIndexParser->GetExpectedDist() << std::endl;
  1825. std::cerr << "Transformed Dist: " << Transformed << std::endl;
  1826. }
  1827. if (MetaIndexParser->CheckDist(Transformed) == false)
  1828. {
  1829. // This might become fatal one day
  1830. // Status = StatAuthError;
  1831. // ErrorText = "Conflicting distribution; expected "
  1832. // + MetaIndexParser->GetExpectedDist() + " but got "
  1833. // + MetaIndexParser->GetDist();
  1834. // return false;
  1835. if (!Transformed.empty())
  1836. {
  1837. _error->Warning(_("Conflicting distribution: %s (expected %s but got %s)"),
  1838. Desc.Description.c_str(),
  1839. Transformed.c_str(),
  1840. MetaIndexParser->GetDist().c_str());
  1841. }
  1842. }
  1843. return true;
  1844. }
  1845. /*}}}*/
  1846. // pkgAcqMetaIndex::Failed - no Release file present /*{{{*/
  1847. void pkgAcqMetaIndex::Failed(string Message,
  1848. pkgAcquire::MethodConfig * Cnf)
  1849. {
  1850. pkgAcquire::Item::Failed(Message, Cnf);
  1851. Status = StatDone;
  1852. _error->Warning(_("The repository '%s' does not have a Release file. "
  1853. "This is deprecated, please contact the owner of the "
  1854. "repository."), URIDesc.c_str());
  1855. // No Release file was present so fall
  1856. // back to queueing Packages files without verification
  1857. // only allow going further if the users explicitely wants it
  1858. if(AllowInsecureRepositories(MetaIndexParser, TransactionManager, this) == true)
  1859. {
  1860. // Done, queue for rename on transaction finished
  1861. if (FileExists(DestFile))
  1862. TransactionManager->TransactionStageCopy(this, DestFile, GetFinalFilename());
  1863. // queue without any kind of hashsum support
  1864. QueueIndexes(false);
  1865. }
  1866. }
  1867. /*}}}*/
  1868. void pkgAcqMetaIndex::Finished() /*{{{*/
  1869. {
  1870. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1871. std::clog << "Finished: " << DestFile <<std::endl;
  1872. if(TransactionManager != NULL &&
  1873. TransactionManager->TransactionHasError() == false)
  1874. TransactionManager->CommitTransaction();
  1875. }
  1876. /*}}}*/
  1877. pkgAcqMetaClearSig::pkgAcqMetaClearSig(pkgAcquire *Owner, /*{{{*/
  1878. string const &URI, string const &URIDesc, string const &ShortDesc,
  1879. string const &MetaIndexURI, string const &MetaIndexURIDesc, string const &MetaIndexShortDesc,
  1880. string const &MetaSigURI, string const &MetaSigURIDesc, string const &MetaSigShortDesc,
  1881. const vector<IndexTarget*>* IndexTargets,
  1882. indexRecords* MetaIndexParser) :
  1883. pkgAcqMetaIndex(Owner, NULL, URI, URIDesc, ShortDesc, MetaSigURI, MetaSigURIDesc,MetaSigShortDesc, IndexTargets, MetaIndexParser),
  1884. MetaIndexURI(MetaIndexURI), MetaIndexURIDesc(MetaIndexURIDesc), MetaIndexShortDesc(MetaIndexShortDesc),
  1885. MetaSigURI(MetaSigURI), MetaSigURIDesc(MetaSigURIDesc), MetaSigShortDesc(MetaSigShortDesc)
  1886. {
  1887. // index targets + (worst case:) Release/Release.gpg
  1888. ExpectedAdditionalItems = IndexTargets->size() + 2;
  1889. }
  1890. /*}}}*/
  1891. pkgAcqMetaClearSig::~pkgAcqMetaClearSig() /*{{{*/
  1892. {
  1893. }
  1894. /*}}}*/
  1895. // pkgAcqMetaClearSig::Custom600Headers - Insert custom request headers /*{{{*/
  1896. #if APT_PKG_ABI >= 413
  1897. string pkgAcqMetaClearSig::Custom600Headers() const
  1898. #else
  1899. string pkgAcqMetaClearSig::Custom600Headers()
  1900. #endif
  1901. {
  1902. string Header = pkgAcqMetaBase::Custom600Headers();
  1903. Header += "\nFail-Ignore: true";
  1904. return Header;
  1905. }
  1906. /*}}}*/
  1907. // pkgAcqMetaClearSig::Done - We got a file /*{{{*/
  1908. // ---------------------------------------------------------------------
  1909. void pkgAcqMetaClearSig::Done(std::string Message,unsigned long long Size,
  1910. HashStringList const &Hashes,
  1911. pkgAcquire::MethodConfig *Cnf)
  1912. {
  1913. Item::Done(Message, Size, Hashes, Cnf);
  1914. // if we expect a ClearTextSignature (InRelase), ensure that
  1915. // this is what we get and if not fail to queue a
  1916. // Release/Release.gpg, see #346386
  1917. if (FileExists(DestFile) && !StartsWithGPGClearTextSignature(DestFile))
  1918. {
  1919. pkgAcquire::Item::Failed(Message, Cnf);
  1920. RenameOnError(NotClearsigned);
  1921. TransactionManager->AbortTransaction();
  1922. return;
  1923. }
  1924. if(AuthPass == false)
  1925. {
  1926. if(CheckDownloadDone(Message) == true)
  1927. QueueForSignatureVerify(DestFile, DestFile);
  1928. return;
  1929. }
  1930. else if(CheckAuthDone(Message) == true)
  1931. TransactionManager->TransactionStageCopy(this, DestFile, GetFinalFilename());
  1932. }
  1933. /*}}}*/
  1934. void pkgAcqMetaClearSig::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
  1935. {
  1936. Item::Failed(Message, Cnf);
  1937. // we failed, we will not get additional items from this method
  1938. ExpectedAdditionalItems = 0;
  1939. if (AuthPass == false)
  1940. {
  1941. // Queue the 'old' InRelease file for removal if we try Release.gpg
  1942. // as otherwise the file will stay around and gives a false-auth
  1943. // impression (CVE-2012-0214)
  1944. TransactionManager->TransactionStageRemoval(this, GetFinalFilename());
  1945. Status = StatDone;
  1946. new pkgAcqMetaIndex(Owner, TransactionManager,
  1947. MetaIndexURI, MetaIndexURIDesc, MetaIndexShortDesc,
  1948. MetaSigURI, MetaSigURIDesc, MetaSigShortDesc,
  1949. IndexTargets, MetaIndexParser);
  1950. }
  1951. else
  1952. {
  1953. if(CheckStopAuthentication(Message))
  1954. return;
  1955. _error->Warning(_("The data from '%s' is not signed. Packages "
  1956. "from that repository can not be authenticated."),
  1957. URIDesc.c_str());
  1958. // No Release file was present, or verification failed, so fall
  1959. // back to queueing Packages files without verification
  1960. // only allow going further if the users explicitely wants it
  1961. if(AllowInsecureRepositories(MetaIndexParser, TransactionManager, this) == true)
  1962. {
  1963. Status = StatDone;
  1964. /* Always move the meta index, even if gpgv failed. This ensures
  1965. * that PackageFile objects are correctly filled in */
  1966. if (FileExists(DestFile))
  1967. {
  1968. string FinalFile = GetFinalFilename();
  1969. /* InRelease files become Release files, otherwise
  1970. * they would be considered as trusted later on */
  1971. RealURI = RealURI.replace(RealURI.rfind("InRelease"), 9,
  1972. "Release");
  1973. FinalFile = FinalFile.replace(FinalFile.rfind("InRelease"), 9,
  1974. "Release");
  1975. // Done, queue for rename on transaction finished
  1976. TransactionManager->TransactionStageCopy(this, DestFile, FinalFile);
  1977. }
  1978. QueueIndexes(false);
  1979. }
  1980. }
  1981. }
  1982. /*}}}*/
  1983. // AcqArchive::AcqArchive - Constructor /*{{{*/
  1984. // ---------------------------------------------------------------------
  1985. /* This just sets up the initial fetch environment and queues the first
  1986. possibilitiy */
  1987. pkgAcqArchive::pkgAcqArchive(pkgAcquire *Owner,pkgSourceList *Sources,
  1988. pkgRecords *Recs,pkgCache::VerIterator const &Version,
  1989. string &StoreFilename) :
  1990. Item(Owner, HashStringList()), Version(Version), Sources(Sources), Recs(Recs),
  1991. StoreFilename(StoreFilename), Vf(Version.FileList()),
  1992. Trusted(false)
  1993. {
  1994. Retries = _config->FindI("Acquire::Retries",0);
  1995. if (Version.Arch() == 0)
  1996. {
  1997. _error->Error(_("I wasn't able to locate a file for the %s package. "
  1998. "This might mean you need to manually fix this package. "
  1999. "(due to missing arch)"),
  2000. Version.ParentPkg().FullName().c_str());
  2001. return;
  2002. }
  2003. /* We need to find a filename to determine the extension. We make the
  2004. assumption here that all the available sources for this version share
  2005. the same extension.. */
  2006. // Skip not source sources, they do not have file fields.
  2007. for (; Vf.end() == false; ++Vf)
  2008. {
  2009. if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
  2010. continue;
  2011. break;
  2012. }
  2013. // Does not really matter here.. we are going to fail out below
  2014. if (Vf.end() != true)
  2015. {
  2016. // If this fails to get a file name we will bomb out below.
  2017. pkgRecords::Parser &Parse = Recs->Lookup(Vf);
  2018. if (_error->PendingError() == true)
  2019. return;
  2020. // Generate the final file name as: package_version_arch.foo
  2021. StoreFilename = QuoteString(Version.ParentPkg().Name(),"_:") + '_' +
  2022. QuoteString(Version.VerStr(),"_:") + '_' +
  2023. QuoteString(Version.Arch(),"_:.") +
  2024. "." + flExtension(Parse.FileName());
  2025. }
  2026. // check if we have one trusted source for the package. if so, switch
  2027. // to "TrustedOnly" mode - but only if not in AllowUnauthenticated mode
  2028. bool const allowUnauth = _config->FindB("APT::Get::AllowUnauthenticated", false);
  2029. bool const debugAuth = _config->FindB("Debug::pkgAcquire::Auth", false);
  2030. bool seenUntrusted = false;
  2031. for (pkgCache::VerFileIterator i = Version.FileList(); i.end() == false; ++i)
  2032. {
  2033. pkgIndexFile *Index;
  2034. if (Sources->FindIndex(i.File(),Index) == false)
  2035. continue;
  2036. if (debugAuth == true)
  2037. std::cerr << "Checking index: " << Index->Describe()
  2038. << "(Trusted=" << Index->IsTrusted() << ")" << std::endl;
  2039. if (Index->IsTrusted() == true)
  2040. {
  2041. Trusted = true;
  2042. if (allowUnauth == false)
  2043. break;
  2044. }
  2045. else
  2046. seenUntrusted = true;
  2047. }
  2048. // "allow-unauthenticated" restores apts old fetching behaviour
  2049. // that means that e.g. unauthenticated file:// uris are higher
  2050. // priority than authenticated http:// uris
  2051. if (allowUnauth == true && seenUntrusted == true)
  2052. Trusted = false;
  2053. // Select a source
  2054. if (QueueNext() == false && _error->PendingError() == false)
  2055. _error->Error(_("Can't find a source to download version '%s' of '%s'"),
  2056. Version.VerStr(), Version.ParentPkg().FullName(false).c_str());
  2057. }
  2058. /*}}}*/
  2059. // AcqArchive::QueueNext - Queue the next file source /*{{{*/
  2060. // ---------------------------------------------------------------------
  2061. /* This queues the next available file version for download. It checks if
  2062. the archive is already available in the cache and stashs the MD5 for
  2063. checking later. */
  2064. bool pkgAcqArchive::QueueNext()
  2065. {
  2066. for (; Vf.end() == false; ++Vf)
  2067. {
  2068. // Ignore not source sources
  2069. if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
  2070. continue;
  2071. // Try to cross match against the source list
  2072. pkgIndexFile *Index;
  2073. if (Sources->FindIndex(Vf.File(),Index) == false)
  2074. continue;
  2075. // only try to get a trusted package from another source if that source
  2076. // is also trusted
  2077. if(Trusted && !Index->IsTrusted())
  2078. continue;
  2079. // Grab the text package record
  2080. pkgRecords::Parser &Parse = Recs->Lookup(Vf);
  2081. if (_error->PendingError() == true)
  2082. return false;
  2083. string PkgFile = Parse.FileName();
  2084. ExpectedHashes = Parse.Hashes();
  2085. if (PkgFile.empty() == true)
  2086. return _error->Error(_("The package index files are corrupted. No Filename: "
  2087. "field for package %s."),
  2088. Version.ParentPkg().Name());
  2089. Desc.URI = Index->ArchiveURI(PkgFile);
  2090. Desc.Description = Index->ArchiveInfo(Version);
  2091. Desc.Owner = this;
  2092. Desc.ShortDesc = Version.ParentPkg().FullName(true);
  2093. // See if we already have the file. (Legacy filenames)
  2094. FileSize = Version->Size;
  2095. string FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(PkgFile);
  2096. struct stat Buf;
  2097. if (stat(FinalFile.c_str(),&Buf) == 0)
  2098. {
  2099. // Make sure the size matches
  2100. if ((unsigned long long)Buf.st_size == Version->Size)
  2101. {
  2102. Complete = true;
  2103. Local = true;
  2104. Status = StatDone;
  2105. StoreFilename = DestFile = FinalFile;
  2106. return true;
  2107. }
  2108. /* Hmm, we have a file and its size does not match, this means it is
  2109. an old style mismatched arch */
  2110. unlink(FinalFile.c_str());
  2111. }
  2112. // Check it again using the new style output filenames
  2113. FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename);
  2114. if (stat(FinalFile.c_str(),&Buf) == 0)
  2115. {
  2116. // Make sure the size matches
  2117. if ((unsigned long long)Buf.st_size == Version->Size)
  2118. {
  2119. Complete = true;
  2120. Local = true;
  2121. Status = StatDone;
  2122. StoreFilename = DestFile = FinalFile;
  2123. return true;
  2124. }
  2125. /* Hmm, we have a file and its size does not match, this shouldn't
  2126. happen.. */
  2127. unlink(FinalFile.c_str());
  2128. }
  2129. DestFile = _config->FindDir("Dir::Cache::Archives") + "partial/" + flNotDir(StoreFilename);
  2130. // Check the destination file
  2131. if (stat(DestFile.c_str(),&Buf) == 0)
  2132. {
  2133. // Hmm, the partial file is too big, erase it
  2134. if ((unsigned long long)Buf.st_size > Version->Size)
  2135. unlink(DestFile.c_str());
  2136. else
  2137. PartialSize = Buf.st_size;
  2138. }
  2139. // Disables download of archives - useful if no real installation follows,
  2140. // e.g. if we are just interested in proposed installation order
  2141. if (_config->FindB("Debug::pkgAcqArchive::NoQueue", false) == true)
  2142. {
  2143. Complete = true;
  2144. Local = true;
  2145. Status = StatDone;
  2146. StoreFilename = DestFile = FinalFile;
  2147. return true;
  2148. }
  2149. // Create the item
  2150. Local = false;
  2151. QueueURI(Desc);
  2152. ++Vf;
  2153. return true;
  2154. }
  2155. return false;
  2156. }
  2157. /*}}}*/
  2158. // AcqArchive::Done - Finished fetching /*{{{*/
  2159. // ---------------------------------------------------------------------
  2160. /* */
  2161. void pkgAcqArchive::Done(string Message,unsigned long long Size, HashStringList const &CalcHashes,
  2162. pkgAcquire::MethodConfig *Cfg)
  2163. {
  2164. Item::Done(Message, Size, CalcHashes, Cfg);
  2165. // Check the size
  2166. if (Size != Version->Size)
  2167. {
  2168. RenameOnError(SizeMismatch);
  2169. return;
  2170. }
  2171. // FIXME: could this empty() check impose *any* sort of security issue?
  2172. if(ExpectedHashes.usable() && ExpectedHashes != CalcHashes)
  2173. {
  2174. RenameOnError(HashSumMismatch);
  2175. printHashSumComparision(DestFile, ExpectedHashes, CalcHashes);
  2176. return;
  2177. }
  2178. // Grab the output filename
  2179. string FileName = LookupTag(Message,"Filename");
  2180. if (FileName.empty() == true)
  2181. {
  2182. Status = StatError;
  2183. ErrorText = "Method gave a blank filename";
  2184. return;
  2185. }
  2186. // Reference filename
  2187. if (FileName != DestFile)
  2188. {
  2189. StoreFilename = DestFile = FileName;
  2190. Local = true;
  2191. Complete = true;
  2192. return;
  2193. }
  2194. // Done, move it into position
  2195. string const FinalFile = GetFinalFilename();
  2196. Rename(DestFile,FinalFile);
  2197. StoreFilename = DestFile = FinalFile;
  2198. Complete = true;
  2199. }
  2200. /*}}}*/
  2201. // Acquire::Item::GetFinalFilename - Return the full final file path /*{{{*/
  2202. std::string pkgAcqArchive::GetFinalFilename() const
  2203. {
  2204. return _config->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename);
  2205. }
  2206. /*}}}*/
  2207. // AcqArchive::Failed - Failure handler /*{{{*/
  2208. // ---------------------------------------------------------------------
  2209. /* Here we try other sources */
  2210. void pkgAcqArchive::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  2211. {
  2212. Item::Failed(Message,Cnf);
  2213. /* We don't really want to retry on failed media swaps, this prevents
  2214. that. An interesting observation is that permanent failures are not
  2215. recorded. */
  2216. if (Cnf->Removable == true &&
  2217. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  2218. {
  2219. // Vf = Version.FileList();
  2220. while (Vf.end() == false) ++Vf;
  2221. StoreFilename = string();
  2222. return;
  2223. }
  2224. Status = StatIdle;
  2225. if (QueueNext() == false)
  2226. {
  2227. // This is the retry counter
  2228. if (Retries != 0 &&
  2229. Cnf->LocalOnly == false &&
  2230. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  2231. {
  2232. Retries--;
  2233. Vf = Version.FileList();
  2234. if (QueueNext() == true)
  2235. return;
  2236. }
  2237. StoreFilename = string();
  2238. Status = StatError;
  2239. }
  2240. }
  2241. /*}}}*/
  2242. // AcqArchive::IsTrusted - Determine whether this archive comes from a trusted source /*{{{*/
  2243. // ---------------------------------------------------------------------
  2244. #if APT_PKG_ABI >= 413
  2245. APT_PURE bool pkgAcqArchive::IsTrusted() const
  2246. #else
  2247. APT_PURE bool pkgAcqArchive::IsTrusted()
  2248. #endif
  2249. {
  2250. return Trusted;
  2251. }
  2252. /*}}}*/
  2253. // AcqArchive::Finished - Fetching has finished, tidy up /*{{{*/
  2254. // ---------------------------------------------------------------------
  2255. /* */
  2256. void pkgAcqArchive::Finished()
  2257. {
  2258. if (Status == pkgAcquire::Item::StatDone &&
  2259. Complete == true)
  2260. return;
  2261. StoreFilename = string();
  2262. }
  2263. /*}}}*/
  2264. // AcqFile::pkgAcqFile - Constructor /*{{{*/
  2265. // ---------------------------------------------------------------------
  2266. /* The file is added to the queue */
  2267. pkgAcqFile::pkgAcqFile(pkgAcquire *Owner,string URI, HashStringList const &Hashes,
  2268. unsigned long long Size,string Dsc,string ShortDesc,
  2269. const string &DestDir, const string &DestFilename,
  2270. bool IsIndexFile) :
  2271. Item(Owner, Hashes), IsIndexFile(IsIndexFile)
  2272. {
  2273. Retries = _config->FindI("Acquire::Retries",0);
  2274. if(!DestFilename.empty())
  2275. DestFile = DestFilename;
  2276. else if(!DestDir.empty())
  2277. DestFile = DestDir + "/" + flNotDir(URI);
  2278. else
  2279. DestFile = flNotDir(URI);
  2280. // Create the item
  2281. Desc.URI = URI;
  2282. Desc.Description = Dsc;
  2283. Desc.Owner = this;
  2284. // Set the short description to the archive component
  2285. Desc.ShortDesc = ShortDesc;
  2286. // Get the transfer sizes
  2287. FileSize = Size;
  2288. struct stat Buf;
  2289. if (stat(DestFile.c_str(),&Buf) == 0)
  2290. {
  2291. // Hmm, the partial file is too big, erase it
  2292. if ((Size > 0) && (unsigned long long)Buf.st_size > Size)
  2293. unlink(DestFile.c_str());
  2294. else
  2295. PartialSize = Buf.st_size;
  2296. }
  2297. QueueURI(Desc);
  2298. }
  2299. /*}}}*/
  2300. // AcqFile::Done - Item downloaded OK /*{{{*/
  2301. // ---------------------------------------------------------------------
  2302. /* */
  2303. void pkgAcqFile::Done(string Message,unsigned long long Size,HashStringList const &CalcHashes,
  2304. pkgAcquire::MethodConfig *Cnf)
  2305. {
  2306. Item::Done(Message,Size,CalcHashes,Cnf);
  2307. // Check the hash
  2308. if(ExpectedHashes.usable() && ExpectedHashes != CalcHashes)
  2309. {
  2310. RenameOnError(HashSumMismatch);
  2311. printHashSumComparision(DestFile, ExpectedHashes, CalcHashes);
  2312. return;
  2313. }
  2314. string FileName = LookupTag(Message,"Filename");
  2315. if (FileName.empty() == true)
  2316. {
  2317. Status = StatError;
  2318. ErrorText = "Method gave a blank filename";
  2319. return;
  2320. }
  2321. Complete = true;
  2322. // The files timestamp matches
  2323. if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  2324. return;
  2325. // We have to copy it into place
  2326. if (FileName != DestFile)
  2327. {
  2328. Local = true;
  2329. if (_config->FindB("Acquire::Source-Symlinks",true) == false ||
  2330. Cnf->Removable == true)
  2331. {
  2332. Desc.URI = "copy:" + FileName;
  2333. QueueURI(Desc);
  2334. return;
  2335. }
  2336. // Erase the file if it is a symlink so we can overwrite it
  2337. struct stat St;
  2338. if (lstat(DestFile.c_str(),&St) == 0)
  2339. {
  2340. if (S_ISLNK(St.st_mode) != 0)
  2341. unlink(DestFile.c_str());
  2342. }
  2343. // Symlink the file
  2344. if (symlink(FileName.c_str(),DestFile.c_str()) != 0)
  2345. {
  2346. _error->PushToStack();
  2347. _error->Errno("pkgAcqFile::Done", "Symlinking file %s failed", DestFile.c_str());
  2348. std::stringstream msg;
  2349. _error->DumpErrors(msg);
  2350. _error->RevertToStack();
  2351. ErrorText = msg.str();
  2352. Status = StatError;
  2353. Complete = false;
  2354. }
  2355. }
  2356. }
  2357. /*}}}*/
  2358. // AcqFile::Failed - Failure handler /*{{{*/
  2359. // ---------------------------------------------------------------------
  2360. /* Here we try other sources */
  2361. void pkgAcqFile::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  2362. {
  2363. Item::Failed(Message,Cnf);
  2364. // This is the retry counter
  2365. if (Retries != 0 &&
  2366. Cnf->LocalOnly == false &&
  2367. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  2368. {
  2369. --Retries;
  2370. QueueURI(Desc);
  2371. Status = StatIdle;
  2372. return;
  2373. }
  2374. }
  2375. /*}}}*/
  2376. // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
  2377. // ---------------------------------------------------------------------
  2378. /* The only header we use is the last-modified header. */
  2379. #if APT_PKG_ABI >= 413
  2380. string pkgAcqFile::Custom600Headers() const
  2381. #else
  2382. string pkgAcqFile::Custom600Headers()
  2383. #endif
  2384. {
  2385. if (IsIndexFile)
  2386. return "\nIndex-File: true";
  2387. return "";
  2388. }
  2389. /*}}}*/