acquire-item.cc 90 KB

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