acquire-item.cc 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075
  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 <apt-pkg/acquire-item.h>
  14. #include <apt-pkg/configuration.h>
  15. #include <apt-pkg/aptconfiguration.h>
  16. #include <apt-pkg/sourcelist.h>
  17. #include <apt-pkg/error.h>
  18. #include <apt-pkg/strutl.h>
  19. #include <apt-pkg/fileutl.h>
  20. #include <apt-pkg/md5.h>
  21. #include <apt-pkg/sha1.h>
  22. #include <apt-pkg/tagfile.h>
  23. #include <apti18n.h>
  24. #include <sys/stat.h>
  25. #include <unistd.h>
  26. #include <errno.h>
  27. #include <string>
  28. #include <sstream>
  29. #include <stdio.h>
  30. #include <ctime>
  31. /*}}}*/
  32. using namespace std;
  33. // Acquire::Item::Item - Constructor /*{{{*/
  34. // ---------------------------------------------------------------------
  35. /* */
  36. pkgAcquire::Item::Item(pkgAcquire *Owner) : Owner(Owner), FileSize(0),
  37. PartialSize(0), Mode(0), ID(0), Complete(false),
  38. Local(false), QueueCounter(0)
  39. {
  40. Owner->Add(this);
  41. Status = StatIdle;
  42. }
  43. /*}}}*/
  44. // Acquire::Item::~Item - Destructor /*{{{*/
  45. // ---------------------------------------------------------------------
  46. /* */
  47. pkgAcquire::Item::~Item()
  48. {
  49. Owner->Remove(this);
  50. }
  51. /*}}}*/
  52. // Acquire::Item::Failed - Item failed to download /*{{{*/
  53. // ---------------------------------------------------------------------
  54. /* We return to an idle state if there are still other queues that could
  55. fetch this object */
  56. void pkgAcquire::Item::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  57. {
  58. Status = StatIdle;
  59. ErrorText = LookupTag(Message,"Message");
  60. UsedMirror = LookupTag(Message,"UsedMirror");
  61. if (QueueCounter <= 1)
  62. {
  63. /* This indicates that the file is not available right now but might
  64. be sometime later. If we do a retry cycle then this should be
  65. retried [CDROMs] */
  66. if (Cnf->LocalOnly == true &&
  67. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  68. {
  69. Status = StatIdle;
  70. Dequeue();
  71. return;
  72. }
  73. Status = StatError;
  74. Dequeue();
  75. }
  76. // report mirror failure back to LP if we actually use a mirror
  77. string FailReason = LookupTag(Message, "FailReason");
  78. if(FailReason.size() != 0)
  79. ReportMirrorFailure(FailReason);
  80. else
  81. ReportMirrorFailure(ErrorText);
  82. }
  83. /*}}}*/
  84. // Acquire::Item::Start - Item has begun to download /*{{{*/
  85. // ---------------------------------------------------------------------
  86. /* Stash status and the file size. Note that setting Complete means
  87. sub-phases of the acquire process such as decompresion are operating */
  88. void pkgAcquire::Item::Start(string /*Message*/,unsigned long Size)
  89. {
  90. Status = StatFetching;
  91. if (FileSize == 0 && Complete == false)
  92. FileSize = Size;
  93. }
  94. /*}}}*/
  95. // Acquire::Item::Done - Item downloaded OK /*{{{*/
  96. // ---------------------------------------------------------------------
  97. /* */
  98. void pkgAcquire::Item::Done(string Message,unsigned long Size,string Hash,
  99. pkgAcquire::MethodConfig *Cnf)
  100. {
  101. // We just downloaded something..
  102. string FileName = LookupTag(Message,"Filename");
  103. UsedMirror = LookupTag(Message,"UsedMirror");
  104. if (Complete == false && !Local && FileName == DestFile)
  105. {
  106. if (Owner->Log != 0)
  107. Owner->Log->Fetched(Size,atoi(LookupTag(Message,"Resume-Point","0").c_str()));
  108. }
  109. if (FileSize == 0)
  110. FileSize= Size;
  111. Status = StatDone;
  112. ErrorText = string();
  113. Owner->Dequeue(this);
  114. }
  115. /*}}}*/
  116. // Acquire::Item::Rename - Rename a file /*{{{*/
  117. // ---------------------------------------------------------------------
  118. /* This helper function is used by alot of item methods as thier final
  119. step */
  120. void pkgAcquire::Item::Rename(string From,string To)
  121. {
  122. if (rename(From.c_str(),To.c_str()) != 0)
  123. {
  124. char S[300];
  125. snprintf(S,sizeof(S),_("rename failed, %s (%s -> %s)."),strerror(errno),
  126. From.c_str(),To.c_str());
  127. Status = StatError;
  128. ErrorText = S;
  129. }
  130. }
  131. /*}}}*/
  132. // Acquire::Item::ReportMirrorFailure /*{{{*/
  133. // ---------------------------------------------------------------------
  134. void pkgAcquire::Item::ReportMirrorFailure(string FailCode)
  135. {
  136. // we only act if a mirror was used at all
  137. if(UsedMirror.empty())
  138. return;
  139. #if 0
  140. std::cerr << "\nReportMirrorFailure: "
  141. << UsedMirror
  142. << " Uri: " << DescURI()
  143. << " FailCode: "
  144. << FailCode << std::endl;
  145. #endif
  146. const char *Args[40];
  147. unsigned int i = 0;
  148. string report = _config->Find("Methods::Mirror::ProblemReporting",
  149. "/usr/lib/apt/apt-report-mirror-failure");
  150. if(!FileExists(report))
  151. return;
  152. Args[i++] = report.c_str();
  153. Args[i++] = UsedMirror.c_str();
  154. Args[i++] = DescURI().c_str();
  155. Args[i++] = FailCode.c_str();
  156. Args[i++] = NULL;
  157. pid_t pid = ExecFork();
  158. if(pid < 0)
  159. {
  160. _error->Error("ReportMirrorFailure Fork failed");
  161. return;
  162. }
  163. else if(pid == 0)
  164. {
  165. execvp(Args[0], (char**)Args);
  166. std::cerr << "Could not exec " << Args[0] << std::endl;
  167. _exit(100);
  168. }
  169. if(!ExecWait(pid, "report-mirror-failure"))
  170. {
  171. _error->Warning("Couldn't report problem to '%s'",
  172. _config->Find("Methods::Mirror::ProblemReporting").c_str());
  173. }
  174. }
  175. /*}}}*/
  176. // AcqSubIndex::AcqSubIndex - Constructor /*{{{*/
  177. // ---------------------------------------------------------------------
  178. /* Get the Index file first and see if there are languages available
  179. * If so, create a pkgAcqIndexTrans for the found language(s).
  180. */
  181. pkgAcqSubIndex::pkgAcqSubIndex(pkgAcquire *Owner, string const &URI,
  182. string const &URIDesc, string const &ShortDesc,
  183. HashString const &ExpectedHash)
  184. : Item(Owner), ExpectedHash(ExpectedHash)
  185. {
  186. Debug = _config->FindB("Debug::pkgAcquire::SubIndex",false);
  187. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  188. DestFile += URItoFileName(URI);
  189. Desc.URI = URI;
  190. Desc.Description = URIDesc;
  191. Desc.Owner = this;
  192. Desc.ShortDesc = ShortDesc;
  193. QueueURI(Desc);
  194. if(Debug)
  195. std::clog << "pkgAcqSubIndex: " << Desc.URI << std::endl;
  196. }
  197. /*}}}*/
  198. // AcqSubIndex::Custom600Headers - Insert custom request headers /*{{{*/
  199. // ---------------------------------------------------------------------
  200. /* The only header we use is the last-modified header. */
  201. string pkgAcqSubIndex::Custom600Headers()
  202. {
  203. string Final = _config->FindDir("Dir::State::lists");
  204. Final += URItoFileName(Desc.URI);
  205. struct stat Buf;
  206. if (stat(Final.c_str(),&Buf) != 0)
  207. return "\nIndex-File: true\nFail-Ignore: true\n";
  208. return "\nIndex-File: true\nFail-Ignore: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  209. }
  210. /*}}}*/
  211. void pkgAcqSubIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
  212. {
  213. if(Debug)
  214. std::clog << "pkgAcqSubIndex failed: " << Desc.URI << std::endl;
  215. Complete = false;
  216. Status = StatDone;
  217. Dequeue();
  218. // No good Index is provided, so try guessing
  219. std::vector<std::string> langs = APT::Configuration::getLanguages(true);
  220. for (std::vector<std::string>::const_iterator l = langs.begin();
  221. l != langs.end(); ++l)
  222. {
  223. if (*l == "none") continue;
  224. string const file = "Translation-" + *l;
  225. new pkgAcqIndexTrans(Owner, Desc.URI.substr(0, Desc.URI.rfind('/')+1).append(file),
  226. Desc.Description.erase(Desc.Description.rfind(' ')+1).append(file),
  227. file);
  228. }
  229. }
  230. /*}}}*/
  231. void pkgAcqSubIndex::Done(string Message,unsigned long Size,string Md5Hash, /*{{{*/
  232. pkgAcquire::MethodConfig *Cnf)
  233. {
  234. if(Debug)
  235. std::clog << "pkgAcqSubIndex::Done(): " << Desc.URI << std::endl;
  236. string FileName = LookupTag(Message,"Filename");
  237. if (FileName.empty() == true)
  238. {
  239. Status = StatError;
  240. ErrorText = "Method gave a blank filename";
  241. return;
  242. }
  243. if (FileName != DestFile)
  244. {
  245. Local = true;
  246. Desc.URI = "copy:" + FileName;
  247. QueueURI(Desc);
  248. return;
  249. }
  250. Item::Done(Message,Size,Md5Hash,Cnf);
  251. string FinalFile = _config->FindDir("Dir::State::lists")+URItoFileName(Desc.URI);
  252. /* Downloaded invalid transindex => Error (LP: #346386) (Closes: #195301) */
  253. indexRecords SubIndexParser;
  254. if (FileExists(DestFile) == true && !SubIndexParser.Load(DestFile)) {
  255. Status = StatError;
  256. ErrorText = SubIndexParser.ErrorText;
  257. return;
  258. }
  259. // sucess in downloading the index
  260. // rename the index
  261. if(Debug)
  262. std::clog << "Renaming: " << DestFile << " -> " << FinalFile << std::endl;
  263. Rename(DestFile,FinalFile);
  264. chmod(FinalFile.c_str(),0644);
  265. DestFile = FinalFile;
  266. if(ParseIndex(DestFile) == false)
  267. return Failed("", NULL);
  268. Complete = true;
  269. Status = StatDone;
  270. Dequeue();
  271. return;
  272. }
  273. /*}}}*/
  274. bool pkgAcqSubIndex::ParseIndex(string const &IndexFile) /*{{{*/
  275. {
  276. indexRecords SubIndexParser;
  277. if (FileExists(IndexFile) == false || SubIndexParser.Load(IndexFile) == false)
  278. return false;
  279. std::vector<std::string> lang = APT::Configuration::getLanguages(true);
  280. for (std::vector<std::string>::const_iterator l = lang.begin();
  281. l != lang.end(); ++l)
  282. {
  283. if (*l == "none")
  284. continue;
  285. string file = "Translation-" + *l;
  286. indexRecords::checkSum const *Record = SubIndexParser.Lookup(file);
  287. HashString expected;
  288. if (Record == NULL)
  289. {
  290. // FIXME: the Index file provided by debian currently only includes bz2 records
  291. Record = SubIndexParser.Lookup(file + ".bz2");
  292. if (Record == NULL)
  293. continue;
  294. }
  295. else
  296. {
  297. expected = Record->Hash;
  298. if (expected.empty() == true)
  299. continue;
  300. }
  301. IndexTarget target;
  302. target.Description = Desc.Description.erase(Desc.Description.rfind(' ')+1).append(file);
  303. target.MetaKey = file;
  304. target.ShortDesc = file;
  305. target.URI = Desc.URI.substr(0, Desc.URI.rfind('/')+1).append(file);
  306. new pkgAcqIndexTrans(Owner, &target, expected, &SubIndexParser);
  307. }
  308. return true;
  309. }
  310. /*}}}*/
  311. // AcqDiffIndex::AcqDiffIndex - Constructor /*{{{*/
  312. // ---------------------------------------------------------------------
  313. /* Get the DiffIndex file first and see if there are patches availabe
  314. * If so, create a pkgAcqIndexDiffs fetcher that will get and apply the
  315. * patches. If anything goes wrong in that process, it will fall back to
  316. * the original packages file
  317. */
  318. pkgAcqDiffIndex::pkgAcqDiffIndex(pkgAcquire *Owner,
  319. string URI,string URIDesc,string ShortDesc,
  320. HashString ExpectedHash)
  321. : Item(Owner), RealURI(URI), ExpectedHash(ExpectedHash),
  322. Description(URIDesc)
  323. {
  324. Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
  325. Desc.Description = URIDesc + "/DiffIndex";
  326. Desc.Owner = this;
  327. Desc.ShortDesc = ShortDesc;
  328. Desc.URI = URI + ".diff/Index";
  329. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  330. DestFile += URItoFileName(URI) + string(".DiffIndex");
  331. if(Debug)
  332. std::clog << "pkgAcqDiffIndex: " << Desc.URI << std::endl;
  333. // look for the current package file
  334. CurrentPackagesFile = _config->FindDir("Dir::State::lists");
  335. CurrentPackagesFile += URItoFileName(RealURI);
  336. // FIXME: this file:/ check is a hack to prevent fetching
  337. // from local sources. this is really silly, and
  338. // should be fixed cleanly as soon as possible
  339. if(!FileExists(CurrentPackagesFile) ||
  340. Desc.URI.substr(0,strlen("file:/")) == "file:/")
  341. {
  342. // we don't have a pkg file or we don't want to queue
  343. if(Debug)
  344. std::clog << "No index file, local or canceld by user" << std::endl;
  345. Failed("", NULL);
  346. return;
  347. }
  348. if(Debug)
  349. std::clog << "pkgAcqIndexDiffs::pkgAcqIndexDiffs(): "
  350. << CurrentPackagesFile << std::endl;
  351. QueueURI(Desc);
  352. }
  353. /*}}}*/
  354. // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
  355. // ---------------------------------------------------------------------
  356. /* The only header we use is the last-modified header. */
  357. string pkgAcqDiffIndex::Custom600Headers()
  358. {
  359. string Final = _config->FindDir("Dir::State::lists");
  360. Final += URItoFileName(RealURI) + string(".IndexDiff");
  361. if(Debug)
  362. std::clog << "Custom600Header-IMS: " << Final << std::endl;
  363. struct stat Buf;
  364. if (stat(Final.c_str(),&Buf) != 0)
  365. return "\nIndex-File: true";
  366. return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  367. }
  368. /*}}}*/
  369. bool pkgAcqDiffIndex::ParseDiffIndex(string IndexDiffFile) /*{{{*/
  370. {
  371. if(Debug)
  372. std::clog << "pkgAcqIndexDiffs::ParseIndexDiff() " << IndexDiffFile
  373. << std::endl;
  374. pkgTagSection Tags;
  375. string ServerSha1;
  376. vector<DiffInfo> available_patches;
  377. FileFd Fd(IndexDiffFile,FileFd::ReadOnly);
  378. pkgTagFile TF(&Fd);
  379. if (_error->PendingError() == true)
  380. return false;
  381. if(TF.Step(Tags) == true)
  382. {
  383. bool found = false;
  384. DiffInfo d;
  385. string size;
  386. string const tmp = Tags.FindS("SHA1-Current");
  387. std::stringstream ss(tmp);
  388. ss >> ServerSha1 >> size;
  389. unsigned long const ServerSize = atol(size.c_str());
  390. FileFd fd(CurrentPackagesFile, FileFd::ReadOnly);
  391. SHA1Summation SHA1;
  392. SHA1.AddFD(fd.Fd(), fd.Size());
  393. string const local_sha1 = SHA1.Result();
  394. if(local_sha1 == ServerSha1)
  395. {
  396. // we have the same sha1 as the server
  397. if(Debug)
  398. std::clog << "Package file is up-to-date" << std::endl;
  399. // set found to true, this will queue a pkgAcqIndexDiffs with
  400. // a empty availabe_patches
  401. found = true;
  402. }
  403. else
  404. {
  405. if(Debug)
  406. std::clog << "SHA1-Current: " << ServerSha1 << " and we start at "<< fd.Name() << " " << fd.Size() << " " << local_sha1 << std::endl;
  407. // check the historie and see what patches we need
  408. string const history = Tags.FindS("SHA1-History");
  409. std::stringstream hist(history);
  410. while(hist >> d.sha1 >> size >> d.file)
  411. {
  412. // read until the first match is found
  413. // from that point on, we probably need all diffs
  414. if(d.sha1 == local_sha1)
  415. found=true;
  416. else if (found == false)
  417. continue;
  418. if(Debug)
  419. std::clog << "Need to get diff: " << d.file << std::endl;
  420. available_patches.push_back(d);
  421. }
  422. if (available_patches.empty() == false)
  423. {
  424. // patching with too many files is rather slow compared to a fast download
  425. unsigned long const fileLimit = _config->FindI("Acquire::PDiffs::FileLimit", 0);
  426. if (fileLimit != 0 && fileLimit < available_patches.size())
  427. {
  428. if (Debug)
  429. std::clog << "Need " << available_patches.size() << " diffs (Limit is " << fileLimit
  430. << ") so fallback to complete download" << std::endl;
  431. return false;
  432. }
  433. // see if the patches are too big
  434. found = false; // it was true and it will be true again at the end
  435. d = *available_patches.begin();
  436. string const firstPatch = d.file;
  437. unsigned long patchesSize = 0;
  438. std::stringstream patches(Tags.FindS("SHA1-Patches"));
  439. while(patches >> d.sha1 >> size >> d.file)
  440. {
  441. if (firstPatch == d.file)
  442. found = true;
  443. else if (found == false)
  444. continue;
  445. patchesSize += atol(size.c_str());
  446. }
  447. unsigned long const sizeLimit = ServerSize * _config->FindI("Acquire::PDiffs::SizeLimit", 100);
  448. if (sizeLimit > 0 && (sizeLimit/100) < patchesSize)
  449. {
  450. if (Debug)
  451. std::clog << "Need " << patchesSize << " bytes (Limit is " << sizeLimit/100
  452. << ") so fallback to complete download" << std::endl;
  453. return false;
  454. }
  455. }
  456. }
  457. // we have something, queue the next diff
  458. if(found)
  459. {
  460. // queue the diffs
  461. string::size_type const last_space = Description.rfind(" ");
  462. if(last_space != string::npos)
  463. Description.erase(last_space, Description.size()-last_space);
  464. new pkgAcqIndexDiffs(Owner, RealURI, Description, Desc.ShortDesc,
  465. ExpectedHash, ServerSha1, available_patches);
  466. Complete = false;
  467. Status = StatDone;
  468. Dequeue();
  469. return true;
  470. }
  471. }
  472. // Nothing found, report and return false
  473. // Failing here is ok, if we return false later, the full
  474. // IndexFile is queued
  475. if(Debug)
  476. std::clog << "Can't find a patch in the index file" << std::endl;
  477. return false;
  478. }
  479. /*}}}*/
  480. void pkgAcqDiffIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
  481. {
  482. if(Debug)
  483. std::clog << "pkgAcqDiffIndex failed: " << Desc.URI << std::endl
  484. << "Falling back to normal index file aquire" << std::endl;
  485. new pkgAcqIndex(Owner, RealURI, Description, Desc.ShortDesc,
  486. ExpectedHash);
  487. Complete = false;
  488. Status = StatDone;
  489. Dequeue();
  490. }
  491. /*}}}*/
  492. void pkgAcqDiffIndex::Done(string Message,unsigned long Size,string Md5Hash, /*{{{*/
  493. pkgAcquire::MethodConfig *Cnf)
  494. {
  495. if(Debug)
  496. std::clog << "pkgAcqDiffIndex::Done(): " << Desc.URI << std::endl;
  497. Item::Done(Message,Size,Md5Hash,Cnf);
  498. string FinalFile;
  499. FinalFile = _config->FindDir("Dir::State::lists")+URItoFileName(RealURI);
  500. // sucess in downloading the index
  501. // rename the index
  502. FinalFile += string(".IndexDiff");
  503. if(Debug)
  504. std::clog << "Renaming: " << DestFile << " -> " << FinalFile
  505. << std::endl;
  506. Rename(DestFile,FinalFile);
  507. chmod(FinalFile.c_str(),0644);
  508. DestFile = FinalFile;
  509. if(!ParseDiffIndex(DestFile))
  510. return Failed("", NULL);
  511. Complete = true;
  512. Status = StatDone;
  513. Dequeue();
  514. return;
  515. }
  516. /*}}}*/
  517. // AcqIndexDiffs::AcqIndexDiffs - Constructor /*{{{*/
  518. // ---------------------------------------------------------------------
  519. /* The package diff is added to the queue. one object is constructed
  520. * for each diff and the index
  521. */
  522. pkgAcqIndexDiffs::pkgAcqIndexDiffs(pkgAcquire *Owner,
  523. string URI,string URIDesc,string ShortDesc,
  524. HashString ExpectedHash,
  525. string ServerSha1,
  526. vector<DiffInfo> diffs)
  527. : Item(Owner), RealURI(URI), ExpectedHash(ExpectedHash),
  528. available_patches(diffs), ServerSha1(ServerSha1)
  529. {
  530. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  531. DestFile += URItoFileName(URI);
  532. Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
  533. Description = URIDesc;
  534. Desc.Owner = this;
  535. Desc.ShortDesc = ShortDesc;
  536. if(available_patches.size() == 0)
  537. {
  538. // we are done (yeah!)
  539. Finish(true);
  540. }
  541. else
  542. {
  543. // get the next diff
  544. State = StateFetchDiff;
  545. QueueNextDiff();
  546. }
  547. }
  548. /*}}}*/
  549. void pkgAcqIndexDiffs::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
  550. {
  551. if(Debug)
  552. std::clog << "pkgAcqIndexDiffs failed: " << Desc.URI << std::endl
  553. << "Falling back to normal index file aquire" << std::endl;
  554. new pkgAcqIndex(Owner, RealURI, Description,Desc.ShortDesc,
  555. ExpectedHash);
  556. Finish();
  557. }
  558. /*}}}*/
  559. // Finish - helper that cleans the item out of the fetcher queue /*{{{*/
  560. void pkgAcqIndexDiffs::Finish(bool allDone)
  561. {
  562. // we restore the original name, this is required, otherwise
  563. // the file will be cleaned
  564. if(allDone)
  565. {
  566. DestFile = _config->FindDir("Dir::State::lists");
  567. DestFile += URItoFileName(RealURI);
  568. if(!ExpectedHash.empty() && !ExpectedHash.VerifyFile(DestFile))
  569. {
  570. Status = StatAuthError;
  571. ErrorText = _("MD5Sum mismatch");
  572. Rename(DestFile,DestFile + ".FAILED");
  573. Dequeue();
  574. return;
  575. }
  576. // this is for the "real" finish
  577. Complete = true;
  578. Status = StatDone;
  579. Dequeue();
  580. if(Debug)
  581. std::clog << "\n\nallDone: " << DestFile << "\n" << std::endl;
  582. return;
  583. }
  584. if(Debug)
  585. std::clog << "Finishing: " << Desc.URI << std::endl;
  586. Complete = false;
  587. Status = StatDone;
  588. Dequeue();
  589. return;
  590. }
  591. /*}}}*/
  592. bool pkgAcqIndexDiffs::QueueNextDiff() /*{{{*/
  593. {
  594. // calc sha1 of the just patched file
  595. string FinalFile = _config->FindDir("Dir::State::lists");
  596. FinalFile += URItoFileName(RealURI);
  597. FileFd fd(FinalFile, FileFd::ReadOnly);
  598. SHA1Summation SHA1;
  599. SHA1.AddFD(fd.Fd(), fd.Size());
  600. string local_sha1 = string(SHA1.Result());
  601. if(Debug)
  602. std::clog << "QueueNextDiff: "
  603. << FinalFile << " (" << local_sha1 << ")"<<std::endl;
  604. // final file reached before all patches are applied
  605. if(local_sha1 == ServerSha1)
  606. {
  607. Finish(true);
  608. return true;
  609. }
  610. // remove all patches until the next matching patch is found
  611. // this requires the Index file to be ordered
  612. for(vector<DiffInfo>::iterator I=available_patches.begin();
  613. available_patches.size() > 0 &&
  614. I != available_patches.end() &&
  615. (*I).sha1 != local_sha1;
  616. I++)
  617. {
  618. available_patches.erase(I);
  619. }
  620. // error checking and falling back if no patch was found
  621. if(available_patches.size() == 0)
  622. {
  623. Failed("", NULL);
  624. return false;
  625. }
  626. // queue the right diff
  627. Desc.URI = string(RealURI) + ".diff/" + available_patches[0].file + ".gz";
  628. Desc.Description = Description + " " + available_patches[0].file + string(".pdiff");
  629. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  630. DestFile += URItoFileName(RealURI + ".diff/" + available_patches[0].file);
  631. if(Debug)
  632. std::clog << "pkgAcqIndexDiffs::QueueNextDiff(): " << Desc.URI << std::endl;
  633. QueueURI(Desc);
  634. return true;
  635. }
  636. /*}}}*/
  637. void pkgAcqIndexDiffs::Done(string Message,unsigned long Size,string Md5Hash, /*{{{*/
  638. pkgAcquire::MethodConfig *Cnf)
  639. {
  640. if(Debug)
  641. std::clog << "pkgAcqIndexDiffs::Done(): " << Desc.URI << std::endl;
  642. Item::Done(Message,Size,Md5Hash,Cnf);
  643. string FinalFile;
  644. FinalFile = _config->FindDir("Dir::State::lists")+URItoFileName(RealURI);
  645. // sucess in downloading a diff, enter ApplyDiff state
  646. if(State == StateFetchDiff)
  647. {
  648. // rred excepts the patch as $FinalFile.ed
  649. Rename(DestFile,FinalFile+".ed");
  650. if(Debug)
  651. std::clog << "Sending to rred method: " << FinalFile << std::endl;
  652. State = StateApplyDiff;
  653. Local = true;
  654. Desc.URI = "rred:" + FinalFile;
  655. QueueURI(Desc);
  656. Mode = "rred";
  657. return;
  658. }
  659. // success in download/apply a diff, queue next (if needed)
  660. if(State == StateApplyDiff)
  661. {
  662. // remove the just applied patch
  663. available_patches.erase(available_patches.begin());
  664. // move into place
  665. if(Debug)
  666. {
  667. std::clog << "Moving patched file in place: " << std::endl
  668. << DestFile << " -> " << FinalFile << std::endl;
  669. }
  670. Rename(DestFile,FinalFile);
  671. chmod(FinalFile.c_str(),0644);
  672. // see if there is more to download
  673. if(available_patches.size() > 0) {
  674. new pkgAcqIndexDiffs(Owner, RealURI, Description, Desc.ShortDesc,
  675. ExpectedHash, ServerSha1, available_patches);
  676. return Finish();
  677. } else
  678. return Finish(true);
  679. }
  680. }
  681. /*}}}*/
  682. // AcqIndex::AcqIndex - Constructor /*{{{*/
  683. // ---------------------------------------------------------------------
  684. /* The package file is added to the queue and a second class is
  685. instantiated to fetch the revision file */
  686. pkgAcqIndex::pkgAcqIndex(pkgAcquire *Owner,
  687. string URI,string URIDesc,string ShortDesc,
  688. HashString ExpectedHash, string comprExt)
  689. : Item(Owner), RealURI(URI), ExpectedHash(ExpectedHash)
  690. {
  691. if(comprExt.empty() == true)
  692. {
  693. // autoselect the compression method
  694. std::vector<std::string> types = APT::Configuration::getCompressionTypes();
  695. for (std::vector<std::string>::const_iterator t = types.begin(); t != types.end(); ++t)
  696. comprExt.append(*t).append(" ");
  697. if (comprExt.empty() == false)
  698. comprExt.erase(comprExt.end()-1);
  699. }
  700. CompressionExtension = comprExt;
  701. Init(URI, URIDesc, ShortDesc);
  702. }
  703. pkgAcqIndex::pkgAcqIndex(pkgAcquire *Owner, IndexTarget const *Target,
  704. HashString const &ExpectedHash, indexRecords const *MetaIndexParser)
  705. : Item(Owner), RealURI(Target->URI), ExpectedHash(ExpectedHash)
  706. {
  707. // autoselect the compression method
  708. std::vector<std::string> types = APT::Configuration::getCompressionTypes();
  709. CompressionExtension = "";
  710. if (ExpectedHash.empty() == false)
  711. {
  712. for (std::vector<std::string>::const_iterator t = types.begin(); t != types.end(); ++t)
  713. if (*t == "uncompressed" || MetaIndexParser->Exists(string(Target->MetaKey).append(".").append(*t)) == true)
  714. CompressionExtension.append(*t).append(" ");
  715. }
  716. else
  717. {
  718. for (std::vector<std::string>::const_iterator t = types.begin(); t != types.end(); ++t)
  719. CompressionExtension.append(*t).append(" ");
  720. }
  721. if (CompressionExtension.empty() == false)
  722. CompressionExtension.erase(CompressionExtension.end()-1);
  723. Init(Target->URI, Target->Description, Target->ShortDesc);
  724. }
  725. /*}}}*/
  726. // AcqIndex::Init - defered Constructor /*{{{*/
  727. void pkgAcqIndex::Init(string const &URI, string const &URIDesc, string const &ShortDesc) {
  728. Decompression = false;
  729. Erase = false;
  730. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  731. DestFile += URItoFileName(URI);
  732. std::string const comprExt = CompressionExtension.substr(0, CompressionExtension.find(' '));
  733. if (comprExt == "uncompressed")
  734. Desc.URI = URI;
  735. else
  736. Desc.URI = URI + '.' + comprExt;
  737. Desc.Description = URIDesc;
  738. Desc.Owner = this;
  739. Desc.ShortDesc = ShortDesc;
  740. QueueURI(Desc);
  741. }
  742. /*}}}*/
  743. // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
  744. // ---------------------------------------------------------------------
  745. /* The only header we use is the last-modified header. */
  746. string pkgAcqIndex::Custom600Headers()
  747. {
  748. string Final = _config->FindDir("Dir::State::lists");
  749. Final += URItoFileName(RealURI);
  750. if (_config->FindB("Acquire::GzipIndexes",false))
  751. Final += ".gz";
  752. string msg = "\nIndex-File: true";
  753. // FIXME: this really should use "IndexTarget::IsOptional()" but that
  754. // seems to be difficult without breaking ABI
  755. if (ShortDesc().find("Translation") != 0)
  756. msg += "\nFail-Ignore: true";
  757. struct stat Buf;
  758. if (stat(Final.c_str(),&Buf) == 0)
  759. msg += "\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  760. return msg;
  761. }
  762. /*}}}*/
  763. void pkgAcqIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
  764. {
  765. size_t const nextExt = CompressionExtension.find(' ');
  766. if (nextExt != std::string::npos)
  767. {
  768. CompressionExtension = CompressionExtension.substr(nextExt+1);
  769. Init(RealURI, Desc.Description, Desc.ShortDesc);
  770. return;
  771. }
  772. // on decompression failure, remove bad versions in partial/
  773. if (Decompression && Erase) {
  774. string s = _config->FindDir("Dir::State::lists") + "partial/";
  775. s.append(URItoFileName(RealURI));
  776. unlink(s.c_str());
  777. }
  778. Item::Failed(Message,Cnf);
  779. }
  780. /*}}}*/
  781. // AcqIndex::Done - Finished a fetch /*{{{*/
  782. // ---------------------------------------------------------------------
  783. /* This goes through a number of states.. On the initial fetch the
  784. method could possibly return an alternate filename which points
  785. to the uncompressed version of the file. If this is so the file
  786. is copied into the partial directory. In all other cases the file
  787. is decompressed with a gzip uri. */
  788. void pkgAcqIndex::Done(string Message,unsigned long Size,string Hash,
  789. pkgAcquire::MethodConfig *Cfg)
  790. {
  791. Item::Done(Message,Size,Hash,Cfg);
  792. if (Decompression == true)
  793. {
  794. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  795. {
  796. std::cerr << std::endl << RealURI << ": Computed Hash: " << Hash;
  797. std::cerr << " Expected Hash: " << ExpectedHash.toStr() << std::endl;
  798. }
  799. if (!ExpectedHash.empty() && ExpectedHash.toStr() != Hash)
  800. {
  801. Status = StatAuthError;
  802. ErrorText = _("Hash Sum mismatch");
  803. Rename(DestFile,DestFile + ".FAILED");
  804. ReportMirrorFailure("HashChecksumFailure");
  805. return;
  806. }
  807. /* Verify the index file for correctness (all indexes must
  808. * have a Package field) (LP: #346386) (Closes: #195301) */
  809. {
  810. FileFd fd(DestFile, FileFd::ReadOnly);
  811. pkgTagSection sec;
  812. pkgTagFile tag(&fd);
  813. if (_error->PendingError() || !tag.Step(sec)) {
  814. Status = StatError;
  815. _error->DumpErrors();
  816. Rename(DestFile,DestFile + ".FAILED");
  817. return;
  818. } else if (!sec.Exists("Package")) {
  819. Status = StatError;
  820. ErrorText = ("Encountered a section with no Package: header");
  821. Rename(DestFile,DestFile + ".FAILED");
  822. return;
  823. }
  824. }
  825. // Done, move it into position
  826. string FinalFile = _config->FindDir("Dir::State::lists");
  827. FinalFile += URItoFileName(RealURI);
  828. Rename(DestFile,FinalFile);
  829. chmod(FinalFile.c_str(),0644);
  830. /* We restore the original name to DestFile so that the clean operation
  831. will work OK */
  832. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  833. DestFile += URItoFileName(RealURI);
  834. // Remove the compressed version.
  835. if (Erase == true)
  836. unlink(DestFile.c_str());
  837. return;
  838. }
  839. Erase = false;
  840. Complete = true;
  841. // Handle the unzipd case
  842. string FileName = LookupTag(Message,"Alt-Filename");
  843. if (FileName.empty() == false)
  844. {
  845. // The files timestamp matches
  846. if (StringToBool(LookupTag(Message,"Alt-IMS-Hit"),false) == true)
  847. return;
  848. Decompression = true;
  849. Local = true;
  850. DestFile += ".decomp";
  851. Desc.URI = "copy:" + FileName;
  852. QueueURI(Desc);
  853. Mode = "copy";
  854. return;
  855. }
  856. FileName = LookupTag(Message,"Filename");
  857. if (FileName.empty() == true)
  858. {
  859. Status = StatError;
  860. ErrorText = "Method gave a blank filename";
  861. }
  862. std::string const compExt = CompressionExtension.substr(0, CompressionExtension.find(' '));
  863. // The files timestamp matches
  864. if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == true) {
  865. if (_config->FindB("Acquire::GzipIndexes",false) && compExt == "gz")
  866. // Update DestFile for .gz suffix so that the clean operation keeps it
  867. DestFile += ".gz";
  868. return;
  869. }
  870. if (FileName == DestFile)
  871. Erase = true;
  872. else
  873. Local = true;
  874. string decompProg;
  875. // If we enable compressed indexes and already have gzip, keep it
  876. if (_config->FindB("Acquire::GzipIndexes",false) && compExt == "gz" && !Local) {
  877. string FinalFile = _config->FindDir("Dir::State::lists");
  878. FinalFile += URItoFileName(RealURI) + ".gz";
  879. Rename(DestFile,FinalFile);
  880. chmod(FinalFile.c_str(),0644);
  881. // Update DestFile for .gz suffix so that the clean operation keeps it
  882. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  883. DestFile += URItoFileName(RealURI) + ".gz";
  884. return;
  885. }
  886. // get the binary name for your used compression type
  887. decompProg = _config->Find(string("Acquire::CompressionTypes::").append(compExt),"");
  888. if(decompProg.empty() == false);
  889. else if(compExt == "uncompressed")
  890. decompProg = "copy";
  891. else {
  892. _error->Error("Unsupported extension: %s", compExt.c_str());
  893. return;
  894. }
  895. Decompression = true;
  896. DestFile += ".decomp";
  897. Desc.URI = decompProg + ":" + FileName;
  898. QueueURI(Desc);
  899. Mode = decompProg.c_str();
  900. }
  901. /*}}}*/
  902. // AcqIndexTrans::pkgAcqIndexTrans - Constructor /*{{{*/
  903. // ---------------------------------------------------------------------
  904. /* The Translation file is added to the queue */
  905. pkgAcqIndexTrans::pkgAcqIndexTrans(pkgAcquire *Owner,
  906. string URI,string URIDesc,string ShortDesc)
  907. : pkgAcqIndex(Owner, URI, URIDesc, ShortDesc, HashString(), "")
  908. {
  909. }
  910. pkgAcqIndexTrans::pkgAcqIndexTrans(pkgAcquire *Owner, IndexTarget const *Target,
  911. HashString const &ExpectedHash, indexRecords const *MetaIndexParser)
  912. : pkgAcqIndex(Owner, Target, ExpectedHash, MetaIndexParser)
  913. {
  914. }
  915. /*}}}*/
  916. // AcqIndexTrans::Custom600Headers - Insert custom request headers /*{{{*/
  917. // ---------------------------------------------------------------------
  918. string pkgAcqIndexTrans::Custom600Headers()
  919. {
  920. string Final = _config->FindDir("Dir::State::lists");
  921. Final += URItoFileName(RealURI);
  922. struct stat Buf;
  923. if (stat(Final.c_str(),&Buf) != 0)
  924. return "\nFail-Ignore: true\nIndex-File: true";
  925. return "\nFail-Ignore: true\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  926. }
  927. /*}}}*/
  928. // AcqIndexTrans::Failed - Silence failure messages for missing files /*{{{*/
  929. // ---------------------------------------------------------------------
  930. /* */
  931. void pkgAcqIndexTrans::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  932. {
  933. size_t const nextExt = CompressionExtension.find(' ');
  934. if (nextExt != std::string::npos)
  935. {
  936. CompressionExtension = CompressionExtension.substr(nextExt+1);
  937. Init(RealURI, Desc.Description, Desc.ShortDesc);
  938. Status = StatIdle;
  939. return;
  940. }
  941. if (Cnf->LocalOnly == true ||
  942. StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
  943. {
  944. // Ignore this
  945. Status = StatDone;
  946. Complete = false;
  947. Dequeue();
  948. return;
  949. }
  950. Item::Failed(Message,Cnf);
  951. }
  952. /*}}}*/
  953. pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire *Owner, /*{{{*/
  954. string URI,string URIDesc,string ShortDesc,
  955. string MetaIndexURI, string MetaIndexURIDesc,
  956. string MetaIndexShortDesc,
  957. const vector<IndexTarget*>* IndexTargets,
  958. indexRecords* MetaIndexParser) :
  959. Item(Owner), RealURI(URI), MetaIndexURI(MetaIndexURI),
  960. MetaIndexURIDesc(MetaIndexURIDesc), MetaIndexShortDesc(MetaIndexShortDesc),
  961. MetaIndexParser(MetaIndexParser), IndexTargets(IndexTargets)
  962. {
  963. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  964. DestFile += URItoFileName(URI);
  965. // remove any partial downloaded sig-file in partial/.
  966. // it may confuse proxies and is too small to warrant a
  967. // partial download anyway
  968. unlink(DestFile.c_str());
  969. // Create the item
  970. Desc.Description = URIDesc;
  971. Desc.Owner = this;
  972. Desc.ShortDesc = ShortDesc;
  973. Desc.URI = URI;
  974. string Final = _config->FindDir("Dir::State::lists");
  975. Final += URItoFileName(RealURI);
  976. struct stat Buf;
  977. if (stat(Final.c_str(),&Buf) == 0)
  978. {
  979. // File was already in place. It needs to be re-downloaded/verified
  980. // because Release might have changed, we do give it a differnt
  981. // name than DestFile because otherwise the http method will
  982. // send If-Range requests and there are too many broken servers
  983. // out there that do not understand them
  984. LastGoodSig = DestFile+".reverify";
  985. Rename(Final,LastGoodSig);
  986. }
  987. QueueURI(Desc);
  988. }
  989. /*}}}*/
  990. // pkgAcqMetaSig::Custom600Headers - Insert custom request headers /*{{{*/
  991. // ---------------------------------------------------------------------
  992. /* The only header we use is the last-modified header. */
  993. string pkgAcqMetaSig::Custom600Headers()
  994. {
  995. struct stat Buf;
  996. if (stat(LastGoodSig.c_str(),&Buf) != 0)
  997. return "\nIndex-File: true";
  998. return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  999. }
  1000. void pkgAcqMetaSig::Done(string Message,unsigned long Size,string MD5,
  1001. pkgAcquire::MethodConfig *Cfg)
  1002. {
  1003. Item::Done(Message,Size,MD5,Cfg);
  1004. string FileName = LookupTag(Message,"Filename");
  1005. if (FileName.empty() == true)
  1006. {
  1007. Status = StatError;
  1008. ErrorText = "Method gave a blank filename";
  1009. return;
  1010. }
  1011. if (FileName != DestFile)
  1012. {
  1013. // We have to copy it into place
  1014. Local = true;
  1015. Desc.URI = "copy:" + FileName;
  1016. QueueURI(Desc);
  1017. return;
  1018. }
  1019. Complete = true;
  1020. // put the last known good file back on i-m-s hit (it will
  1021. // be re-verified again)
  1022. // Else do nothing, we have the new file in DestFile then
  1023. if(StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  1024. Rename(LastGoodSig, DestFile);
  1025. // queue a pkgAcqMetaIndex to be verified against the sig we just retrieved
  1026. new pkgAcqMetaIndex(Owner, MetaIndexURI, MetaIndexURIDesc,
  1027. MetaIndexShortDesc, DestFile, IndexTargets,
  1028. MetaIndexParser);
  1029. }
  1030. /*}}}*/
  1031. void pkgAcqMetaSig::Failed(string Message,pkgAcquire::MethodConfig *Cnf)/*{{{*/
  1032. {
  1033. string Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
  1034. // if we get a network error we fail gracefully
  1035. if(Status == StatTransientNetworkError)
  1036. {
  1037. Item::Failed(Message,Cnf);
  1038. // move the sigfile back on transient network failures
  1039. if(FileExists(LastGoodSig))
  1040. Rename(LastGoodSig,Final);
  1041. // set the status back to , Item::Failed likes to reset it
  1042. Status = pkgAcquire::Item::StatTransientNetworkError;
  1043. return;
  1044. }
  1045. // Delete any existing sigfile when the acquire failed
  1046. unlink(Final.c_str());
  1047. // queue a pkgAcqMetaIndex with no sigfile
  1048. new pkgAcqMetaIndex(Owner, MetaIndexURI, MetaIndexURIDesc, MetaIndexShortDesc,
  1049. "", IndexTargets, MetaIndexParser);
  1050. if (Cnf->LocalOnly == true ||
  1051. StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
  1052. {
  1053. // Ignore this
  1054. Status = StatDone;
  1055. Complete = false;
  1056. Dequeue();
  1057. return;
  1058. }
  1059. Item::Failed(Message,Cnf);
  1060. }
  1061. /*}}}*/
  1062. pkgAcqMetaIndex::pkgAcqMetaIndex(pkgAcquire *Owner, /*{{{*/
  1063. string URI,string URIDesc,string ShortDesc,
  1064. string SigFile,
  1065. const vector<struct IndexTarget*>* IndexTargets,
  1066. indexRecords* MetaIndexParser) :
  1067. Item(Owner), RealURI(URI), SigFile(SigFile), IndexTargets(IndexTargets),
  1068. MetaIndexParser(MetaIndexParser), AuthPass(false), IMSHit(false)
  1069. {
  1070. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  1071. DestFile += URItoFileName(URI);
  1072. // Create the item
  1073. Desc.Description = URIDesc;
  1074. Desc.Owner = this;
  1075. Desc.ShortDesc = ShortDesc;
  1076. Desc.URI = URI;
  1077. QueueURI(Desc);
  1078. }
  1079. /*}}}*/
  1080. // pkgAcqMetaIndex::Custom600Headers - Insert custom request headers /*{{{*/
  1081. // ---------------------------------------------------------------------
  1082. /* The only header we use is the last-modified header. */
  1083. string pkgAcqMetaIndex::Custom600Headers()
  1084. {
  1085. string Final = _config->FindDir("Dir::State::lists");
  1086. Final += URItoFileName(RealURI);
  1087. struct stat Buf;
  1088. if (stat(Final.c_str(),&Buf) != 0)
  1089. return "\nIndex-File: true";
  1090. return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  1091. }
  1092. /*}}}*/
  1093. void pkgAcqMetaIndex::Done(string Message,unsigned long Size,string Hash, /*{{{*/
  1094. pkgAcquire::MethodConfig *Cfg)
  1095. {
  1096. Item::Done(Message,Size,Hash,Cfg);
  1097. // MetaIndexes are done in two passes: one to download the
  1098. // metaindex with an appropriate method, and a second to verify it
  1099. // with the gpgv method
  1100. if (AuthPass == true)
  1101. {
  1102. AuthDone(Message);
  1103. // all cool, move Release file into place
  1104. Complete = true;
  1105. }
  1106. else
  1107. {
  1108. RetrievalDone(Message);
  1109. if (!Complete)
  1110. // Still more retrieving to do
  1111. return;
  1112. if (SigFile == "")
  1113. {
  1114. // There was no signature file, so we are finished. Download
  1115. // the indexes without verification.
  1116. QueueIndexes(false);
  1117. }
  1118. else
  1119. {
  1120. // There was a signature file, so pass it to gpgv for
  1121. // verification
  1122. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1123. std::cerr << "Metaindex acquired, queueing gpg verification ("
  1124. << SigFile << "," << DestFile << ")\n";
  1125. AuthPass = true;
  1126. Desc.URI = "gpgv:" + SigFile;
  1127. QueueURI(Desc);
  1128. Mode = "gpgv";
  1129. return;
  1130. }
  1131. }
  1132. if (Complete == true)
  1133. {
  1134. string FinalFile = _config->FindDir("Dir::State::lists");
  1135. FinalFile += URItoFileName(RealURI);
  1136. if (SigFile == DestFile)
  1137. SigFile = FinalFile;
  1138. Rename(DestFile,FinalFile);
  1139. chmod(FinalFile.c_str(),0644);
  1140. DestFile = FinalFile;
  1141. }
  1142. }
  1143. /*}}}*/
  1144. void pkgAcqMetaIndex::RetrievalDone(string Message) /*{{{*/
  1145. {
  1146. // We have just finished downloading a Release file (it is not
  1147. // verified yet)
  1148. string FileName = LookupTag(Message,"Filename");
  1149. if (FileName.empty() == true)
  1150. {
  1151. Status = StatError;
  1152. ErrorText = "Method gave a blank filename";
  1153. return;
  1154. }
  1155. if (FileName != DestFile)
  1156. {
  1157. Local = true;
  1158. Desc.URI = "copy:" + FileName;
  1159. QueueURI(Desc);
  1160. return;
  1161. }
  1162. // make sure to verify against the right file on I-M-S hit
  1163. IMSHit = StringToBool(LookupTag(Message,"IMS-Hit"),false);
  1164. if(IMSHit)
  1165. {
  1166. string FinalFile = _config->FindDir("Dir::State::lists");
  1167. FinalFile += URItoFileName(RealURI);
  1168. if (SigFile == DestFile)
  1169. SigFile = FinalFile;
  1170. DestFile = FinalFile;
  1171. }
  1172. Complete = true;
  1173. }
  1174. /*}}}*/
  1175. void pkgAcqMetaIndex::AuthDone(string Message) /*{{{*/
  1176. {
  1177. // At this point, the gpgv method has succeeded, so there is a
  1178. // valid signature from a key in the trusted keyring. We
  1179. // perform additional verification of its contents, and use them
  1180. // to verify the indexes we are about to download
  1181. if (!MetaIndexParser->Load(DestFile))
  1182. {
  1183. Status = StatAuthError;
  1184. ErrorText = MetaIndexParser->ErrorText;
  1185. return;
  1186. }
  1187. if (!VerifyVendor(Message))
  1188. {
  1189. return;
  1190. }
  1191. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1192. std::cerr << "Signature verification succeeded: "
  1193. << DestFile << std::endl;
  1194. // Download further indexes with verification
  1195. QueueIndexes(true);
  1196. // is it a clearsigned MetaIndex file?
  1197. if (DestFile == SigFile)
  1198. return;
  1199. // Done, move signature file into position
  1200. string VerifiedSigFile = _config->FindDir("Dir::State::lists") +
  1201. URItoFileName(RealURI) + ".gpg";
  1202. Rename(SigFile,VerifiedSigFile);
  1203. chmod(VerifiedSigFile.c_str(),0644);
  1204. }
  1205. /*}}}*/
  1206. void pkgAcqMetaIndex::QueueIndexes(bool verify) /*{{{*/
  1207. {
  1208. #if 0
  1209. /* Reject invalid, existing Release files (LP: #346386) (Closes: #195301)
  1210. * FIXME: Disabled; it breaks unsigned repositories without hashes */
  1211. if (!verify && FileExists(DestFile) && !MetaIndexParser->Load(DestFile))
  1212. {
  1213. Status = StatError;
  1214. ErrorText = MetaIndexParser->ErrorText;
  1215. return;
  1216. }
  1217. #endif
  1218. for (vector <struct IndexTarget*>::const_iterator Target = IndexTargets->begin();
  1219. Target != IndexTargets->end();
  1220. Target++)
  1221. {
  1222. HashString ExpectedIndexHash;
  1223. if (verify)
  1224. {
  1225. const indexRecords::checkSum *Record = MetaIndexParser->Lookup((*Target)->MetaKey);
  1226. if (Record == NULL)
  1227. {
  1228. if ((*Target)->IsOptional() == false)
  1229. {
  1230. Status = StatAuthError;
  1231. strprintf(ErrorText, _("Unable to find expected entry '%s' in Release file (Wrong sources.list entry or malformed file)"), (*Target)->MetaKey.c_str());
  1232. return;
  1233. }
  1234. }
  1235. else
  1236. {
  1237. ExpectedIndexHash = Record->Hash;
  1238. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1239. {
  1240. std::cerr << "Queueing: " << (*Target)->URI << std::endl;
  1241. std::cerr << "Expected Hash: " << ExpectedIndexHash.toStr() << std::endl;
  1242. }
  1243. if (ExpectedIndexHash.empty() == true && (*Target)->IsOptional() == false)
  1244. {
  1245. Status = StatAuthError;
  1246. strprintf(ErrorText, _("Unable to find hash sum for '%s' in Release file"), (*Target)->MetaKey.c_str());
  1247. return;
  1248. }
  1249. }
  1250. }
  1251. if ((*Target)->IsOptional() == true)
  1252. {
  1253. if ((*Target)->IsSubIndex() == true)
  1254. new pkgAcqSubIndex(Owner, (*Target)->URI, (*Target)->Description,
  1255. (*Target)->ShortDesc, ExpectedIndexHash);
  1256. else
  1257. new pkgAcqIndexTrans(Owner, *Target, ExpectedIndexHash, MetaIndexParser);
  1258. continue;
  1259. }
  1260. /* Queue Packages file (either diff or full packages files, depending
  1261. on the users option) - we also check if the PDiff Index file is listed
  1262. in the Meta-Index file. Ideal would be if pkgAcqDiffIndex would test this
  1263. instead, but passing the required info to it is to much hassle */
  1264. if(_config->FindB("Acquire::PDiffs",true) == true && (verify == false ||
  1265. MetaIndexParser->Exists(string((*Target)->MetaKey).append(".diff/Index")) == true))
  1266. new pkgAcqDiffIndex(Owner, (*Target)->URI, (*Target)->Description,
  1267. (*Target)->ShortDesc, ExpectedIndexHash);
  1268. else
  1269. new pkgAcqIndex(Owner, *Target, ExpectedIndexHash, MetaIndexParser);
  1270. }
  1271. }
  1272. /*}}}*/
  1273. bool pkgAcqMetaIndex::VerifyVendor(string Message) /*{{{*/
  1274. {
  1275. string::size_type pos;
  1276. // check for missing sigs (that where not fatal because otherwise we had
  1277. // bombed earlier)
  1278. string missingkeys;
  1279. string msg = _("There is no public key available for the "
  1280. "following key IDs:\n");
  1281. pos = Message.find("NO_PUBKEY ");
  1282. if (pos != std::string::npos)
  1283. {
  1284. string::size_type start = pos+strlen("NO_PUBKEY ");
  1285. string Fingerprint = Message.substr(start, Message.find("\n")-start);
  1286. missingkeys += (Fingerprint);
  1287. }
  1288. if(!missingkeys.empty())
  1289. _error->Warning("%s", string(msg+missingkeys).c_str());
  1290. string Transformed = MetaIndexParser->GetExpectedDist();
  1291. if (Transformed == "../project/experimental")
  1292. {
  1293. Transformed = "experimental";
  1294. }
  1295. pos = Transformed.rfind('/');
  1296. if (pos != string::npos)
  1297. {
  1298. Transformed = Transformed.substr(0, pos);
  1299. }
  1300. if (Transformed == ".")
  1301. {
  1302. Transformed = "";
  1303. }
  1304. if (_config->FindB("Acquire::Check-Valid-Until", true) == true &&
  1305. MetaIndexParser->GetValidUntil() > 0) {
  1306. time_t const invalid_since = time(NULL) - MetaIndexParser->GetValidUntil();
  1307. if (invalid_since > 0)
  1308. // TRANSLATOR: The first %s is the URL of the bad Release file, the second is
  1309. // the time since then the file is invalid - formated in the same way as in
  1310. // the download progress display (e.g. 7d 3h 42min 1s)
  1311. return _error->Error(_("Release file expired, ignoring %s (invalid since %s)"),
  1312. RealURI.c_str(), TimeToStr(invalid_since).c_str());
  1313. }
  1314. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1315. {
  1316. std::cerr << "Got Codename: " << MetaIndexParser->GetDist() << std::endl;
  1317. std::cerr << "Expecting Dist: " << MetaIndexParser->GetExpectedDist() << std::endl;
  1318. std::cerr << "Transformed Dist: " << Transformed << std::endl;
  1319. }
  1320. if (MetaIndexParser->CheckDist(Transformed) == false)
  1321. {
  1322. // This might become fatal one day
  1323. // Status = StatAuthError;
  1324. // ErrorText = "Conflicting distribution; expected "
  1325. // + MetaIndexParser->GetExpectedDist() + " but got "
  1326. // + MetaIndexParser->GetDist();
  1327. // return false;
  1328. if (!Transformed.empty())
  1329. {
  1330. _error->Warning(_("Conflicting distribution: %s (expected %s but got %s)"),
  1331. Desc.Description.c_str(),
  1332. Transformed.c_str(),
  1333. MetaIndexParser->GetDist().c_str());
  1334. }
  1335. }
  1336. return true;
  1337. }
  1338. /*}}}*/
  1339. // pkgAcqMetaIndex::Failed - no Release file present or no signature file present /*{{{*/
  1340. // ---------------------------------------------------------------------
  1341. /* */
  1342. void pkgAcqMetaIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  1343. {
  1344. if (AuthPass == true)
  1345. {
  1346. // gpgv method failed, if we have a good signature
  1347. string LastGoodSigFile = _config->FindDir("Dir::State::lists");
  1348. if (DestFile == SigFile)
  1349. LastGoodSigFile.append(URItoFileName(RealURI));
  1350. else
  1351. LastGoodSigFile.append("partial/").append(URItoFileName(RealURI)).append(".gpg.reverify");
  1352. if(FileExists(LastGoodSigFile))
  1353. {
  1354. if (DestFile != SigFile)
  1355. {
  1356. string VerifiedSigFile = _config->FindDir("Dir::State::lists") +
  1357. URItoFileName(RealURI) + ".gpg";
  1358. Rename(LastGoodSigFile,VerifiedSigFile);
  1359. }
  1360. Status = StatTransientNetworkError;
  1361. _error->Warning(_("A error occurred during the signature "
  1362. "verification. The repository is not updated "
  1363. "and the previous index files will be used. "
  1364. "GPG error: %s: %s\n"),
  1365. Desc.Description.c_str(),
  1366. LookupTag(Message,"Message").c_str());
  1367. RunScripts("APT::Update::Auth-Failure");
  1368. return;
  1369. } else if (LookupTag(Message,"Message").find("NODATA") != string::npos) {
  1370. /* Invalid signature file, reject (LP: #346386) (Closes: #195301) */
  1371. _error->Error(_("GPG error: %s: %s"),
  1372. Desc.Description.c_str(),
  1373. LookupTag(Message,"Message").c_str());
  1374. return;
  1375. } else {
  1376. _error->Warning(_("GPG error: %s: %s"),
  1377. Desc.Description.c_str(),
  1378. LookupTag(Message,"Message").c_str());
  1379. }
  1380. // gpgv method failed
  1381. ReportMirrorFailure("GPGFailure");
  1382. }
  1383. /* Always move the meta index, even if gpgv failed. This ensures
  1384. * that PackageFile objects are correctly filled in */
  1385. if (FileExists(DestFile)) {
  1386. string FinalFile = _config->FindDir("Dir::State::lists");
  1387. FinalFile += URItoFileName(RealURI);
  1388. /* InRelease files become Release files, otherwise
  1389. * they would be considered as trusted later on */
  1390. if (SigFile == DestFile) {
  1391. RealURI = RealURI.replace(RealURI.rfind("InRelease"), 9,
  1392. "Release");
  1393. FinalFile = FinalFile.replace(FinalFile.rfind("InRelease"), 9,
  1394. "Release");
  1395. SigFile = FinalFile;
  1396. }
  1397. Rename(DestFile,FinalFile);
  1398. chmod(FinalFile.c_str(),0644);
  1399. DestFile = FinalFile;
  1400. }
  1401. // No Release file was present, or verification failed, so fall
  1402. // back to queueing Packages files without verification
  1403. QueueIndexes(false);
  1404. }
  1405. /*}}}*/
  1406. pkgAcqMetaClearSig::pkgAcqMetaClearSig(pkgAcquire *Owner, /*{{{*/
  1407. string const &URI, string const &URIDesc, string const &ShortDesc,
  1408. string const &MetaIndexURI, string const &MetaIndexURIDesc, string const &MetaIndexShortDesc,
  1409. string const &MetaSigURI, string const &MetaSigURIDesc, string const &MetaSigShortDesc,
  1410. const vector<struct IndexTarget*>* IndexTargets,
  1411. indexRecords* MetaIndexParser) :
  1412. pkgAcqMetaIndex(Owner, URI, URIDesc, ShortDesc, "", IndexTargets, MetaIndexParser),
  1413. MetaIndexURI(MetaIndexURI), MetaIndexURIDesc(MetaIndexURIDesc), MetaIndexShortDesc(MetaIndexShortDesc),
  1414. MetaSigURI(MetaSigURI), MetaSigURIDesc(MetaSigURIDesc), MetaSigShortDesc(MetaSigShortDesc)
  1415. {
  1416. SigFile = DestFile;
  1417. }
  1418. /*}}}*/
  1419. // pkgAcqMetaClearSig::Custom600Headers - Insert custom request headers /*{{{*/
  1420. // ---------------------------------------------------------------------
  1421. // FIXME: this can go away once the InRelease file is used widely
  1422. string pkgAcqMetaClearSig::Custom600Headers()
  1423. {
  1424. string Final = _config->FindDir("Dir::State::lists");
  1425. Final += URItoFileName(RealURI);
  1426. struct stat Buf;
  1427. if (stat(Final.c_str(),&Buf) != 0)
  1428. return "\nIndex-File: true\nFail-Ignore: true\n";
  1429. return "\nIndex-File: true\nFail-Ignore: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  1430. }
  1431. /*}}}*/
  1432. void pkgAcqMetaClearSig::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
  1433. {
  1434. if (AuthPass == false)
  1435. {
  1436. new pkgAcqMetaSig(Owner,
  1437. MetaSigURI, MetaSigURIDesc, MetaSigShortDesc,
  1438. MetaIndexURI, MetaIndexURIDesc, MetaIndexShortDesc,
  1439. IndexTargets, MetaIndexParser);
  1440. if (Cnf->LocalOnly == true ||
  1441. StringToBool(LookupTag(Message, "Transient-Failure"), false) == false)
  1442. Dequeue();
  1443. }
  1444. else
  1445. pkgAcqMetaIndex::Failed(Message, Cnf);
  1446. }
  1447. /*}}}*/
  1448. // AcqArchive::AcqArchive - Constructor /*{{{*/
  1449. // ---------------------------------------------------------------------
  1450. /* This just sets up the initial fetch environment and queues the first
  1451. possibilitiy */
  1452. pkgAcqArchive::pkgAcqArchive(pkgAcquire *Owner,pkgSourceList *Sources,
  1453. pkgRecords *Recs,pkgCache::VerIterator const &Version,
  1454. string &StoreFilename) :
  1455. Item(Owner), Version(Version), Sources(Sources), Recs(Recs),
  1456. StoreFilename(StoreFilename), Vf(Version.FileList()),
  1457. Trusted(false)
  1458. {
  1459. Retries = _config->FindI("Acquire::Retries",0);
  1460. if (Version.Arch() == 0)
  1461. {
  1462. _error->Error(_("I wasn't able to locate a file for the %s package. "
  1463. "This might mean you need to manually fix this package. "
  1464. "(due to missing arch)"),
  1465. Version.ParentPkg().Name());
  1466. return;
  1467. }
  1468. /* We need to find a filename to determine the extension. We make the
  1469. assumption here that all the available sources for this version share
  1470. the same extension.. */
  1471. // Skip not source sources, they do not have file fields.
  1472. for (; Vf.end() == false; Vf++)
  1473. {
  1474. if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
  1475. continue;
  1476. break;
  1477. }
  1478. // Does not really matter here.. we are going to fail out below
  1479. if (Vf.end() != true)
  1480. {
  1481. // If this fails to get a file name we will bomb out below.
  1482. pkgRecords::Parser &Parse = Recs->Lookup(Vf);
  1483. if (_error->PendingError() == true)
  1484. return;
  1485. // Generate the final file name as: package_version_arch.foo
  1486. StoreFilename = QuoteString(Version.ParentPkg().Name(),"_:") + '_' +
  1487. QuoteString(Version.VerStr(),"_:") + '_' +
  1488. QuoteString(Version.Arch(),"_:.") +
  1489. "." + flExtension(Parse.FileName());
  1490. }
  1491. // check if we have one trusted source for the package. if so, switch
  1492. // to "TrustedOnly" mode
  1493. for (pkgCache::VerFileIterator i = Version.FileList(); i.end() == false; i++)
  1494. {
  1495. pkgIndexFile *Index;
  1496. if (Sources->FindIndex(i.File(),Index) == false)
  1497. continue;
  1498. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1499. {
  1500. std::cerr << "Checking index: " << Index->Describe()
  1501. << "(Trusted=" << Index->IsTrusted() << ")\n";
  1502. }
  1503. if (Index->IsTrusted()) {
  1504. Trusted = true;
  1505. break;
  1506. }
  1507. }
  1508. // "allow-unauthenticated" restores apts old fetching behaviour
  1509. // that means that e.g. unauthenticated file:// uris are higher
  1510. // priority than authenticated http:// uris
  1511. if (_config->FindB("APT::Get::AllowUnauthenticated",false) == true)
  1512. Trusted = false;
  1513. // Select a source
  1514. if (QueueNext() == false && _error->PendingError() == false)
  1515. _error->Error(_("I wasn't able to locate a file for the %s package. "
  1516. "This might mean you need to manually fix this package."),
  1517. Version.ParentPkg().Name());
  1518. }
  1519. /*}}}*/
  1520. // AcqArchive::QueueNext - Queue the next file source /*{{{*/
  1521. // ---------------------------------------------------------------------
  1522. /* This queues the next available file version for download. It checks if
  1523. the archive is already available in the cache and stashs the MD5 for
  1524. checking later. */
  1525. bool pkgAcqArchive::QueueNext()
  1526. {
  1527. string const ForceHash = _config->Find("Acquire::ForceHash");
  1528. for (; Vf.end() == false; Vf++)
  1529. {
  1530. // Ignore not source sources
  1531. if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
  1532. continue;
  1533. // Try to cross match against the source list
  1534. pkgIndexFile *Index;
  1535. if (Sources->FindIndex(Vf.File(),Index) == false)
  1536. continue;
  1537. // only try to get a trusted package from another source if that source
  1538. // is also trusted
  1539. if(Trusted && !Index->IsTrusted())
  1540. continue;
  1541. // Grab the text package record
  1542. pkgRecords::Parser &Parse = Recs->Lookup(Vf);
  1543. if (_error->PendingError() == true)
  1544. return false;
  1545. string PkgFile = Parse.FileName();
  1546. if (ForceHash.empty() == false)
  1547. {
  1548. if(stringcasecmp(ForceHash, "sha256") == 0)
  1549. ExpectedHash = HashString("SHA256", Parse.SHA256Hash());
  1550. else if (stringcasecmp(ForceHash, "sha1") == 0)
  1551. ExpectedHash = HashString("SHA1", Parse.SHA1Hash());
  1552. else
  1553. ExpectedHash = HashString("MD5Sum", Parse.MD5Hash());
  1554. }
  1555. else
  1556. {
  1557. string Hash;
  1558. if ((Hash = Parse.SHA256Hash()).empty() == false)
  1559. ExpectedHash = HashString("SHA256", Hash);
  1560. else if ((Hash = Parse.SHA1Hash()).empty() == false)
  1561. ExpectedHash = HashString("SHA1", Hash);
  1562. else
  1563. ExpectedHash = HashString("MD5Sum", Parse.MD5Hash());
  1564. }
  1565. if (PkgFile.empty() == true)
  1566. return _error->Error(_("The package index files are corrupted. No Filename: "
  1567. "field for package %s."),
  1568. Version.ParentPkg().Name());
  1569. Desc.URI = Index->ArchiveURI(PkgFile);
  1570. Desc.Description = Index->ArchiveInfo(Version);
  1571. Desc.Owner = this;
  1572. Desc.ShortDesc = Version.ParentPkg().Name();
  1573. // See if we already have the file. (Legacy filenames)
  1574. FileSize = Version->Size;
  1575. string FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(PkgFile);
  1576. struct stat Buf;
  1577. if (stat(FinalFile.c_str(),&Buf) == 0)
  1578. {
  1579. // Make sure the size matches
  1580. if ((unsigned)Buf.st_size == Version->Size)
  1581. {
  1582. Complete = true;
  1583. Local = true;
  1584. Status = StatDone;
  1585. StoreFilename = DestFile = FinalFile;
  1586. return true;
  1587. }
  1588. /* Hmm, we have a file and its size does not match, this means it is
  1589. an old style mismatched arch */
  1590. unlink(FinalFile.c_str());
  1591. }
  1592. // Check it again using the new style output filenames
  1593. FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename);
  1594. if (stat(FinalFile.c_str(),&Buf) == 0)
  1595. {
  1596. // Make sure the size matches
  1597. if ((unsigned)Buf.st_size == Version->Size)
  1598. {
  1599. Complete = true;
  1600. Local = true;
  1601. Status = StatDone;
  1602. StoreFilename = DestFile = FinalFile;
  1603. return true;
  1604. }
  1605. /* Hmm, we have a file and its size does not match, this shouldnt
  1606. happen.. */
  1607. unlink(FinalFile.c_str());
  1608. }
  1609. DestFile = _config->FindDir("Dir::Cache::Archives") + "partial/" + flNotDir(StoreFilename);
  1610. // Check the destination file
  1611. if (stat(DestFile.c_str(),&Buf) == 0)
  1612. {
  1613. // Hmm, the partial file is too big, erase it
  1614. if ((unsigned)Buf.st_size > Version->Size)
  1615. unlink(DestFile.c_str());
  1616. else
  1617. PartialSize = Buf.st_size;
  1618. }
  1619. // Create the item
  1620. Local = false;
  1621. Desc.URI = Index->ArchiveURI(PkgFile);
  1622. Desc.Description = Index->ArchiveInfo(Version);
  1623. Desc.Owner = this;
  1624. Desc.ShortDesc = Version.ParentPkg().Name();
  1625. QueueURI(Desc);
  1626. Vf++;
  1627. return true;
  1628. }
  1629. return false;
  1630. }
  1631. /*}}}*/
  1632. // AcqArchive::Done - Finished fetching /*{{{*/
  1633. // ---------------------------------------------------------------------
  1634. /* */
  1635. void pkgAcqArchive::Done(string Message,unsigned long Size,string CalcHash,
  1636. pkgAcquire::MethodConfig *Cfg)
  1637. {
  1638. Item::Done(Message,Size,CalcHash,Cfg);
  1639. // Check the size
  1640. if (Size != Version->Size)
  1641. {
  1642. Status = StatError;
  1643. ErrorText = _("Size mismatch");
  1644. return;
  1645. }
  1646. // Check the hash
  1647. if(ExpectedHash.toStr() != CalcHash)
  1648. {
  1649. Status = StatError;
  1650. ErrorText = _("Hash Sum mismatch");
  1651. if(FileExists(DestFile))
  1652. Rename(DestFile,DestFile + ".FAILED");
  1653. return;
  1654. }
  1655. // Grab the output filename
  1656. string FileName = LookupTag(Message,"Filename");
  1657. if (FileName.empty() == true)
  1658. {
  1659. Status = StatError;
  1660. ErrorText = "Method gave a blank filename";
  1661. return;
  1662. }
  1663. Complete = true;
  1664. // Reference filename
  1665. if (FileName != DestFile)
  1666. {
  1667. StoreFilename = DestFile = FileName;
  1668. Local = true;
  1669. return;
  1670. }
  1671. // Done, move it into position
  1672. string FinalFile = _config->FindDir("Dir::Cache::Archives");
  1673. FinalFile += flNotDir(StoreFilename);
  1674. Rename(DestFile,FinalFile);
  1675. StoreFilename = DestFile = FinalFile;
  1676. Complete = true;
  1677. }
  1678. /*}}}*/
  1679. // AcqArchive::Failed - Failure handler /*{{{*/
  1680. // ---------------------------------------------------------------------
  1681. /* Here we try other sources */
  1682. void pkgAcqArchive::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  1683. {
  1684. ErrorText = LookupTag(Message,"Message");
  1685. /* We don't really want to retry on failed media swaps, this prevents
  1686. that. An interesting observation is that permanent failures are not
  1687. recorded. */
  1688. if (Cnf->Removable == true &&
  1689. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  1690. {
  1691. // Vf = Version.FileList();
  1692. while (Vf.end() == false) Vf++;
  1693. StoreFilename = string();
  1694. Item::Failed(Message,Cnf);
  1695. return;
  1696. }
  1697. if (QueueNext() == false)
  1698. {
  1699. // This is the retry counter
  1700. if (Retries != 0 &&
  1701. Cnf->LocalOnly == false &&
  1702. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  1703. {
  1704. Retries--;
  1705. Vf = Version.FileList();
  1706. if (QueueNext() == true)
  1707. return;
  1708. }
  1709. StoreFilename = string();
  1710. Item::Failed(Message,Cnf);
  1711. }
  1712. }
  1713. /*}}}*/
  1714. // AcqArchive::IsTrusted - Determine whether this archive comes from a trusted source /*{{{*/
  1715. // ---------------------------------------------------------------------
  1716. bool pkgAcqArchive::IsTrusted()
  1717. {
  1718. return Trusted;
  1719. }
  1720. /*}}}*/
  1721. // AcqArchive::Finished - Fetching has finished, tidy up /*{{{*/
  1722. // ---------------------------------------------------------------------
  1723. /* */
  1724. void pkgAcqArchive::Finished()
  1725. {
  1726. if (Status == pkgAcquire::Item::StatDone &&
  1727. Complete == true)
  1728. return;
  1729. StoreFilename = string();
  1730. }
  1731. /*}}}*/
  1732. // AcqFile::pkgAcqFile - Constructor /*{{{*/
  1733. // ---------------------------------------------------------------------
  1734. /* The file is added to the queue */
  1735. pkgAcqFile::pkgAcqFile(pkgAcquire *Owner,string URI,string Hash,
  1736. unsigned long Size,string Dsc,string ShortDesc,
  1737. const string &DestDir, const string &DestFilename,
  1738. bool IsIndexFile) :
  1739. Item(Owner), ExpectedHash(Hash), IsIndexFile(IsIndexFile)
  1740. {
  1741. Retries = _config->FindI("Acquire::Retries",0);
  1742. if(!DestFilename.empty())
  1743. DestFile = DestFilename;
  1744. else if(!DestDir.empty())
  1745. DestFile = DestDir + "/" + flNotDir(URI);
  1746. else
  1747. DestFile = flNotDir(URI);
  1748. // Create the item
  1749. Desc.URI = URI;
  1750. Desc.Description = Dsc;
  1751. Desc.Owner = this;
  1752. // Set the short description to the archive component
  1753. Desc.ShortDesc = ShortDesc;
  1754. // Get the transfer sizes
  1755. FileSize = Size;
  1756. struct stat Buf;
  1757. if (stat(DestFile.c_str(),&Buf) == 0)
  1758. {
  1759. // Hmm, the partial file is too big, erase it
  1760. if ((unsigned)Buf.st_size > Size)
  1761. unlink(DestFile.c_str());
  1762. else
  1763. PartialSize = Buf.st_size;
  1764. }
  1765. QueueURI(Desc);
  1766. }
  1767. /*}}}*/
  1768. // AcqFile::Done - Item downloaded OK /*{{{*/
  1769. // ---------------------------------------------------------------------
  1770. /* */
  1771. void pkgAcqFile::Done(string Message,unsigned long Size,string CalcHash,
  1772. pkgAcquire::MethodConfig *Cnf)
  1773. {
  1774. Item::Done(Message,Size,CalcHash,Cnf);
  1775. // Check the hash
  1776. if(!ExpectedHash.empty() && ExpectedHash.toStr() != CalcHash)
  1777. {
  1778. Status = StatError;
  1779. ErrorText = _("Hash Sum mismatch");
  1780. Rename(DestFile,DestFile + ".FAILED");
  1781. return;
  1782. }
  1783. string FileName = LookupTag(Message,"Filename");
  1784. if (FileName.empty() == true)
  1785. {
  1786. Status = StatError;
  1787. ErrorText = "Method gave a blank filename";
  1788. return;
  1789. }
  1790. Complete = true;
  1791. // The files timestamp matches
  1792. if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  1793. return;
  1794. // We have to copy it into place
  1795. if (FileName != DestFile)
  1796. {
  1797. Local = true;
  1798. if (_config->FindB("Acquire::Source-Symlinks",true) == false ||
  1799. Cnf->Removable == true)
  1800. {
  1801. Desc.URI = "copy:" + FileName;
  1802. QueueURI(Desc);
  1803. return;
  1804. }
  1805. // Erase the file if it is a symlink so we can overwrite it
  1806. struct stat St;
  1807. if (lstat(DestFile.c_str(),&St) == 0)
  1808. {
  1809. if (S_ISLNK(St.st_mode) != 0)
  1810. unlink(DestFile.c_str());
  1811. }
  1812. // Symlink the file
  1813. if (symlink(FileName.c_str(),DestFile.c_str()) != 0)
  1814. {
  1815. ErrorText = "Link to " + DestFile + " failure ";
  1816. Status = StatError;
  1817. Complete = false;
  1818. }
  1819. }
  1820. }
  1821. /*}}}*/
  1822. // AcqFile::Failed - Failure handler /*{{{*/
  1823. // ---------------------------------------------------------------------
  1824. /* Here we try other sources */
  1825. void pkgAcqFile::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  1826. {
  1827. ErrorText = LookupTag(Message,"Message");
  1828. // This is the retry counter
  1829. if (Retries != 0 &&
  1830. Cnf->LocalOnly == false &&
  1831. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  1832. {
  1833. Retries--;
  1834. QueueURI(Desc);
  1835. return;
  1836. }
  1837. Item::Failed(Message,Cnf);
  1838. }
  1839. /*}}}*/
  1840. // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
  1841. // ---------------------------------------------------------------------
  1842. /* The only header we use is the last-modified header. */
  1843. string pkgAcqFile::Custom600Headers()
  1844. {
  1845. if (IsIndexFile)
  1846. return "\nIndex-File: true";
  1847. return "";
  1848. }
  1849. /*}}}*/
  1850. bool IndexTarget::IsOptional() const {
  1851. if (strncmp(ShortDesc.c_str(), "Translation", 11) != 0)
  1852. return false;
  1853. return true;
  1854. }
  1855. bool IndexTarget::IsSubIndex() const {
  1856. if (ShortDesc != "TranslationIndex")
  1857. return false;
  1858. return true;
  1859. }