acquire-item.cc 54 KB

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