acquire-item.cc 87 KB

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