acquire-item.cc 49 KB

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