acquire-item.cc 62 KB

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