acquire-item.cc 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256
  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. #ifdef __GNUG__
  14. #pragma implementation "apt-pkg/acquire-item.h"
  15. #endif
  16. #include <apt-pkg/acquire-item.h>
  17. #include <apt-pkg/configuration.h>
  18. #include <apt-pkg/sourcelist.h>
  19. #include <apt-pkg/vendorlist.h>
  20. #include <apt-pkg/error.h>
  21. #include <apt-pkg/strutl.h>
  22. #include <apt-pkg/fileutl.h>
  23. #include <apt-pkg/md5.h>
  24. #include <apti18n.h>
  25. #include <sys/stat.h>
  26. #include <unistd.h>
  27. #include <errno.h>
  28. #include <string>
  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,
  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 && 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. // AcqIndex::AcqIndex - Constructor /*{{{*/
  173. // ---------------------------------------------------------------------
  174. /* The package file is added to the queue and a second class is
  175. instantiated to fetch the revision file */
  176. pkgAcqIndex::pkgAcqIndex(pkgAcquire *Owner,
  177. string URI,string URIDesc,string ShortDesc,
  178. string ExpectedMD5, string comprExt) :
  179. Item(Owner), RealURI(URI), ExpectedMD5(ExpectedMD5)
  180. {
  181. Decompression = false;
  182. Erase = false;
  183. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  184. DestFile += URItoFileName(URI);
  185. if(comprExt.empty())
  186. {
  187. // autoselect the compression method
  188. if(FileExists("/bin/bzip2"))
  189. CompressionExtension = ".bz2";
  190. else
  191. CompressionExtension = ".gz";
  192. } else {
  193. CompressionExtension = comprExt;
  194. }
  195. Desc.URI = URI + CompressionExtension;
  196. Desc.Description = URIDesc;
  197. Desc.Owner = this;
  198. Desc.ShortDesc = ShortDesc;
  199. QueueURI(Desc);
  200. }
  201. /*}}}*/
  202. // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
  203. // ---------------------------------------------------------------------
  204. /* The only header we use is the last-modified header. */
  205. string pkgAcqIndex::Custom600Headers()
  206. {
  207. string Final = _config->FindDir("Dir::State::lists");
  208. Final += URItoFileName(RealURI);
  209. struct stat Buf;
  210. if (stat(Final.c_str(),&Buf) != 0)
  211. return "\nIndex-File: true";
  212. return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  213. }
  214. /*}}}*/
  215. void pkgAcqIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  216. {
  217. // no .bz2 found, retry with .gz
  218. if(Desc.URI.substr(Desc.URI.size()-3) == "bz2") {
  219. Desc.URI = Desc.URI.substr(0,Desc.URI.size()-3) + "gz";
  220. // retry with a gzip one
  221. new pkgAcqIndex(Owner, RealURI, Desc.Description,Desc.ShortDesc,
  222. ExpectedMD5, string(".gz"));
  223. Status = StatDone;
  224. Complete = false;
  225. Dequeue();
  226. return;
  227. }
  228. // on decompression failure, remove bad versions in partial/
  229. if(Decompression && Erase) {
  230. string s = _config->FindDir("Dir::State::lists") + "partial/";
  231. s += URItoFileName(RealURI);
  232. unlink(s.c_str());
  233. }
  234. Item::Failed(Message,Cnf);
  235. }
  236. // AcqIndex::Done - Finished a fetch /*{{{*/
  237. // ---------------------------------------------------------------------
  238. /* This goes through a number of states.. On the initial fetch the
  239. method could possibly return an alternate filename which points
  240. to the uncompressed version of the file. If this is so the file
  241. is copied into the partial directory. In all other cases the file
  242. is decompressed with a gzip uri. */
  243. void pkgAcqIndex::Done(string Message,unsigned long Size,string MD5,
  244. pkgAcquire::MethodConfig *Cfg)
  245. {
  246. Item::Done(Message,Size,MD5,Cfg);
  247. if (Decompression == true)
  248. {
  249. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  250. {
  251. std::cerr << std::endl << RealURI << ": Computed MD5: " << MD5;
  252. std::cerr << " Expected MD5: " << ExpectedMD5 << std::endl;
  253. }
  254. if (MD5.empty())
  255. {
  256. MD5Summation sum;
  257. FileFd Fd(DestFile, FileFd::ReadOnly);
  258. sum.AddFD(Fd.Fd(), Fd.Size());
  259. Fd.Close();
  260. MD5 = (string)sum.Result();
  261. }
  262. if (!ExpectedMD5.empty() && MD5 != ExpectedMD5)
  263. {
  264. Status = StatAuthError;
  265. ErrorText = _("MD5Sum mismatch");
  266. Rename(DestFile,DestFile + ".FAILED");
  267. ReportMirrorFailure("HashChecksumFailure");
  268. return;
  269. }
  270. // Done, move it into position
  271. string FinalFile = _config->FindDir("Dir::State::lists");
  272. FinalFile += URItoFileName(RealURI);
  273. Rename(DestFile,FinalFile);
  274. chmod(FinalFile.c_str(),0644);
  275. /* We restore the original name to DestFile so that the clean operation
  276. will work OK */
  277. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  278. DestFile += URItoFileName(RealURI);
  279. // Remove the compressed version.
  280. if (Erase == true)
  281. unlink(DestFile.c_str());
  282. return;
  283. }
  284. Erase = false;
  285. Complete = true;
  286. // Handle the unzipd case
  287. string FileName = LookupTag(Message,"Alt-Filename");
  288. if (FileName.empty() == false)
  289. {
  290. // The files timestamp matches
  291. if (StringToBool(LookupTag(Message,"Alt-IMS-Hit"),false) == true)
  292. return;
  293. Decompression = true;
  294. Local = true;
  295. DestFile += ".decomp";
  296. Desc.URI = "copy:" + FileName;
  297. QueueURI(Desc);
  298. Mode = "copy";
  299. return;
  300. }
  301. FileName = LookupTag(Message,"Filename");
  302. if (FileName.empty() == true)
  303. {
  304. Status = StatError;
  305. ErrorText = "Method gave a blank filename";
  306. }
  307. // The files timestamp matches
  308. if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  309. return;
  310. if (FileName == DestFile)
  311. Erase = true;
  312. else
  313. Local = true;
  314. string compExt = Desc.URI.substr(Desc.URI.size()-3);
  315. char *decompProg;
  316. if(compExt == "bz2")
  317. decompProg = "bzip2";
  318. else if(compExt == ".gz")
  319. decompProg = "gzip";
  320. else {
  321. _error->Error("Unsupported extension: %s", compExt.c_str());
  322. return;
  323. }
  324. Decompression = true;
  325. DestFile += ".decomp";
  326. Desc.URI = string(decompProg) + ":" + FileName;
  327. QueueURI(Desc);
  328. Mode = decompProg;
  329. }
  330. // AcqIndexTrans::pkgAcqIndexTrans - Constructor /*{{{*/
  331. // ---------------------------------------------------------------------
  332. /* The Translation file is added to the queue */
  333. pkgAcqIndexTrans::pkgAcqIndexTrans(pkgAcquire *Owner,
  334. string URI,string URIDesc,string ShortDesc) :
  335. pkgAcqIndex(Owner, URI, URIDesc, ShortDesc, "", "")
  336. {
  337. }
  338. /*}}}*/
  339. // AcqIndexTrans::Failed - Silence failure messages for missing files /*{{{*/
  340. // ---------------------------------------------------------------------
  341. /* */
  342. void pkgAcqIndexTrans::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  343. {
  344. if (Cnf->LocalOnly == true ||
  345. StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
  346. {
  347. // Ignore this
  348. Status = StatDone;
  349. Complete = false;
  350. Dequeue();
  351. return;
  352. }
  353. Item::Failed(Message,Cnf);
  354. }
  355. /*}}}*/
  356. pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire *Owner,
  357. string URI,string URIDesc,string ShortDesc,
  358. string MetaIndexURI, string MetaIndexURIDesc,
  359. string MetaIndexShortDesc,
  360. const vector<IndexTarget*>* IndexTargets,
  361. indexRecords* MetaIndexParser) :
  362. Item(Owner), RealURI(URI), MetaIndexURI(MetaIndexURI),
  363. MetaIndexURIDesc(MetaIndexURIDesc), MetaIndexShortDesc(MetaIndexShortDesc),
  364. MetaIndexParser(MetaIndexParser), IndexTargets(IndexTargets)
  365. {
  366. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  367. DestFile += URItoFileName(URI);
  368. // remove any partial downloaded sig-file in partial/.
  369. // it may confuse proxies and is too small to warrant a
  370. // partial download anyway
  371. unlink(DestFile.c_str());
  372. // Create the item
  373. Desc.Description = URIDesc;
  374. Desc.Owner = this;
  375. Desc.ShortDesc = ShortDesc;
  376. Desc.URI = URI;
  377. string Final = _config->FindDir("Dir::State::lists");
  378. Final += URItoFileName(RealURI);
  379. struct stat Buf;
  380. if (stat(Final.c_str(),&Buf) == 0)
  381. {
  382. // File was already in place. It needs to be re-verified
  383. // because Release might have changed, so Move it into partial
  384. Rename(Final,DestFile);
  385. }
  386. QueueURI(Desc);
  387. }
  388. /*}}}*/
  389. // pkgAcqMetaSig::Custom600Headers - Insert custom request headers /*{{{*/
  390. // ---------------------------------------------------------------------
  391. /* The only header we use is the last-modified header. */
  392. string pkgAcqMetaSig::Custom600Headers()
  393. {
  394. struct stat Buf;
  395. if (stat(DestFile.c_str(),&Buf) != 0)
  396. return "\nIndex-File: true";
  397. return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  398. }
  399. void pkgAcqMetaSig::Done(string Message,unsigned long Size,string MD5,
  400. pkgAcquire::MethodConfig *Cfg)
  401. {
  402. Item::Done(Message,Size,MD5,Cfg);
  403. string FileName = LookupTag(Message,"Filename");
  404. if (FileName.empty() == true)
  405. {
  406. Status = StatError;
  407. ErrorText = "Method gave a blank filename";
  408. return;
  409. }
  410. if (FileName != DestFile)
  411. {
  412. // We have to copy it into place
  413. Local = true;
  414. Desc.URI = "copy:" + FileName;
  415. QueueURI(Desc);
  416. return;
  417. }
  418. Complete = true;
  419. // queue a pkgAcqMetaIndex to be verified against the sig we just retrieved
  420. new pkgAcqMetaIndex(Owner, MetaIndexURI, MetaIndexURIDesc, MetaIndexShortDesc,
  421. DestFile, IndexTargets, MetaIndexParser);
  422. }
  423. /*}}}*/
  424. void pkgAcqMetaSig::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  425. {
  426. string Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
  427. // if we get a network error we fail gracefully
  428. if(Status == StatTransientNetworkError)
  429. {
  430. Item::Failed(Message,Cnf);
  431. // move the sigfile back on network failures (and re-authenticated?)
  432. if(FileExists(DestFile))
  433. Rename(DestFile,Final);
  434. // set the status back to , Item::Failed likes to reset it
  435. Status = pkgAcquire::Item::StatTransientNetworkError;
  436. return;
  437. }
  438. // Delete any existing sigfile when the acquire failed
  439. unlink(Final.c_str());
  440. // queue a pkgAcqMetaIndex with no sigfile
  441. new pkgAcqMetaIndex(Owner, MetaIndexURI, MetaIndexURIDesc, MetaIndexShortDesc,
  442. "", IndexTargets, MetaIndexParser);
  443. if (Cnf->LocalOnly == true ||
  444. StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
  445. {
  446. // Ignore this
  447. Status = StatDone;
  448. Complete = false;
  449. Dequeue();
  450. return;
  451. }
  452. Item::Failed(Message,Cnf);
  453. }
  454. pkgAcqMetaIndex::pkgAcqMetaIndex(pkgAcquire *Owner,
  455. string URI,string URIDesc,string ShortDesc,
  456. string SigFile,
  457. const vector<struct IndexTarget*>* IndexTargets,
  458. indexRecords* MetaIndexParser) :
  459. Item(Owner), RealURI(URI), SigFile(SigFile), AuthPass(false),
  460. MetaIndexParser(MetaIndexParser), IndexTargets(IndexTargets), IMSHit(false)
  461. {
  462. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  463. DestFile += URItoFileName(URI);
  464. // Create the item
  465. Desc.Description = URIDesc;
  466. Desc.Owner = this;
  467. Desc.ShortDesc = ShortDesc;
  468. Desc.URI = URI;
  469. QueueURI(Desc);
  470. }
  471. /*}}}*/
  472. // pkgAcqMetaIndex::Custom600Headers - Insert custom request headers /*{{{*/
  473. // ---------------------------------------------------------------------
  474. /* The only header we use is the last-modified header. */
  475. string pkgAcqMetaIndex::Custom600Headers()
  476. {
  477. string Final = _config->FindDir("Dir::State::lists");
  478. Final += URItoFileName(RealURI);
  479. struct stat Buf;
  480. if (stat(Final.c_str(),&Buf) != 0)
  481. return "\nIndex-File: true";
  482. return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  483. }
  484. void pkgAcqMetaIndex::Done(string Message,unsigned long Size,string MD5,
  485. pkgAcquire::MethodConfig *Cfg)
  486. {
  487. Item::Done(Message,Size,MD5,Cfg);
  488. // MetaIndexes are done in two passes: one to download the
  489. // metaindex with an appropriate method, and a second to verify it
  490. // with the gpgv method
  491. if (AuthPass == true)
  492. {
  493. AuthDone(Message);
  494. }
  495. else
  496. {
  497. RetrievalDone(Message);
  498. if (!Complete)
  499. // Still more retrieving to do
  500. return;
  501. if (SigFile == "")
  502. {
  503. // There was no signature file, so we are finished. Download
  504. // the indexes without verification.
  505. QueueIndexes(false);
  506. }
  507. else
  508. {
  509. // There was a signature file, so pass it to gpgv for
  510. // verification
  511. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  512. std::cerr << "Metaindex acquired, queueing gpg verification ("
  513. << SigFile << "," << DestFile << ")\n";
  514. AuthPass = true;
  515. Desc.URI = "gpgv:" + SigFile;
  516. QueueURI(Desc);
  517. Mode = "gpgv";
  518. }
  519. }
  520. }
  521. void pkgAcqMetaIndex::RetrievalDone(string Message)
  522. {
  523. // We have just finished downloading a Release file (it is not
  524. // verified yet)
  525. string FileName = LookupTag(Message,"Filename");
  526. if (FileName.empty() == true)
  527. {
  528. Status = StatError;
  529. ErrorText = "Method gave a blank filename";
  530. return;
  531. }
  532. if (FileName != DestFile)
  533. {
  534. Local = true;
  535. Desc.URI = "copy:" + FileName;
  536. QueueURI(Desc);
  537. return;
  538. }
  539. // see if the download was a IMSHit
  540. IMSHit = StringToBool(LookupTag(Message,"IMS-Hit"),false);
  541. Complete = true;
  542. string FinalFile = _config->FindDir("Dir::State::lists");
  543. FinalFile += URItoFileName(RealURI);
  544. // The files timestamp matches
  545. if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == false)
  546. {
  547. // Move it into position
  548. Rename(DestFile,FinalFile);
  549. }
  550. DestFile = FinalFile;
  551. }
  552. void pkgAcqMetaIndex::AuthDone(string Message)
  553. {
  554. // At this point, the gpgv method has succeeded, so there is a
  555. // valid signature from a key in the trusted keyring. We
  556. // perform additional verification of its contents, and use them
  557. // to verify the indexes we are about to download
  558. if (!MetaIndexParser->Load(DestFile))
  559. {
  560. Status = StatAuthError;
  561. ErrorText = MetaIndexParser->ErrorText;
  562. return;
  563. }
  564. if (!VerifyVendor(Message))
  565. {
  566. return;
  567. }
  568. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  569. std::cerr << "Signature verification succeeded: "
  570. << DestFile << std::endl;
  571. // Download further indexes with verification
  572. QueueIndexes(true);
  573. // Done, move signature file into position
  574. string VerifiedSigFile = _config->FindDir("Dir::State::lists") +
  575. URItoFileName(RealURI) + ".gpg";
  576. Rename(SigFile,VerifiedSigFile);
  577. chmod(VerifiedSigFile.c_str(),0644);
  578. }
  579. void pkgAcqMetaIndex::QueueIndexes(bool verify)
  580. {
  581. for (vector <struct IndexTarget*>::const_iterator Target = IndexTargets->begin();
  582. Target != IndexTargets->end();
  583. Target++)
  584. {
  585. string ExpectedIndexMD5;
  586. if (verify)
  587. {
  588. const indexRecords::checkSum *Record = MetaIndexParser->Lookup((*Target)->MetaKey);
  589. if (!Record)
  590. {
  591. Status = StatAuthError;
  592. ErrorText = "Unable to find expected entry "
  593. + (*Target)->MetaKey + " in Meta-index file (malformed Release file?)";
  594. return;
  595. }
  596. ExpectedIndexMD5 = Record->MD5Hash;
  597. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  598. {
  599. std::cerr << "Queueing: " << (*Target)->URI << std::endl;
  600. std::cerr << "Expected MD5: " << ExpectedIndexMD5 << std::endl;
  601. }
  602. if (ExpectedIndexMD5.empty())
  603. {
  604. Status = StatAuthError;
  605. ErrorText = "Unable to find MD5 sum for "
  606. + (*Target)->MetaKey + " in Meta-index file";
  607. return;
  608. }
  609. }
  610. // Queue Packages file
  611. new pkgAcqIndex(Owner, (*Target)->URI, (*Target)->Description,
  612. (*Target)->ShortDesc, ExpectedIndexMD5);
  613. }
  614. }
  615. bool pkgAcqMetaIndex::VerifyVendor(string Message)
  616. {
  617. // // Maybe this should be made available from above so we don't have
  618. // // to read and parse it every time?
  619. // pkgVendorList List;
  620. // List.ReadMainList();
  621. // const Vendor* Vndr = NULL;
  622. // for (std::vector<string>::const_iterator I = GPGVOutput.begin(); I != GPGVOutput.end(); I++)
  623. // {
  624. // string::size_type pos = (*I).find("VALIDSIG ");
  625. // if (_config->FindB("Debug::Vendor", false))
  626. // std::cerr << "Looking for VALIDSIG in \"" << (*I) << "\": pos " << pos
  627. // << std::endl;
  628. // if (pos != std::string::npos)
  629. // {
  630. // string Fingerprint = (*I).substr(pos+sizeof("VALIDSIG"));
  631. // if (_config->FindB("Debug::Vendor", false))
  632. // std::cerr << "Looking for \"" << Fingerprint << "\" in vendor..." <<
  633. // std::endl;
  634. // Vndr = List.FindVendor(Fingerprint) != "";
  635. // if (Vndr != NULL);
  636. // break;
  637. // }
  638. // }
  639. string::size_type pos;
  640. // check for missing sigs (that where not fatal because otherwise we had
  641. // bombed earlier)
  642. string missingkeys;
  643. string msg = _("There is no public key available for the "
  644. "following key IDs:\n");
  645. pos = Message.find("NO_PUBKEY ");
  646. if (pos != std::string::npos)
  647. {
  648. string::size_type start = pos+strlen("NO_PUBKEY ");
  649. string Fingerprint = Message.substr(start, Message.find("\n")-start);
  650. missingkeys += (Fingerprint);
  651. }
  652. if(!missingkeys.empty())
  653. _error->Warning("%s", string(msg+missingkeys).c_str());
  654. string Transformed = MetaIndexParser->GetExpectedDist();
  655. if (Transformed == "../project/experimental")
  656. {
  657. Transformed = "experimental";
  658. }
  659. pos = Transformed.rfind('/');
  660. if (pos != string::npos)
  661. {
  662. Transformed = Transformed.substr(0, pos);
  663. }
  664. if (Transformed == ".")
  665. {
  666. Transformed = "";
  667. }
  668. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  669. {
  670. std::cerr << "Got Codename: " << MetaIndexParser->GetDist() << std::endl;
  671. std::cerr << "Expecting Dist: " << MetaIndexParser->GetExpectedDist() << std::endl;
  672. std::cerr << "Transformed Dist: " << Transformed << std::endl;
  673. }
  674. if (MetaIndexParser->CheckDist(Transformed) == false)
  675. {
  676. // This might become fatal one day
  677. // Status = StatAuthError;
  678. // ErrorText = "Conflicting distribution; expected "
  679. // + MetaIndexParser->GetExpectedDist() + " but got "
  680. // + MetaIndexParser->GetDist();
  681. // return false;
  682. if (!Transformed.empty())
  683. {
  684. _error->Warning("Conflicting distribution: %s (expected %s but got %s)",
  685. Desc.Description.c_str(),
  686. Transformed.c_str(),
  687. MetaIndexParser->GetDist().c_str());
  688. }
  689. }
  690. return true;
  691. }
  692. /*}}}*/
  693. // pkgAcqMetaIndex::Failed - no Release file present or no signature
  694. // file present /*{{{*/
  695. // ---------------------------------------------------------------------
  696. /* */
  697. void pkgAcqMetaIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  698. {
  699. if (AuthPass == true)
  700. {
  701. // if we fail the authentication but got the file via a IMS-Hit
  702. // this means that the file wasn't downloaded and that it might be
  703. // just stale (server problem, proxy etc). we delete what we have
  704. // queue it again without i-m-s
  705. // alternatively we could just unlink the file and let the user try again
  706. if (IMSHit)
  707. {
  708. Complete = false;
  709. Local = false;
  710. AuthPass = false;
  711. unlink(DestFile.c_str());
  712. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  713. DestFile += URItoFileName(RealURI);
  714. Desc.URI = RealURI;
  715. QueueURI(Desc);
  716. return;
  717. }
  718. // gpgv method failed
  719. ReportMirrorFailure("GPGFailure");
  720. _error->Warning("GPG error: %s: %s",
  721. Desc.Description.c_str(),
  722. LookupTag(Message,"Message").c_str());
  723. }
  724. // No Release file was present, or verification failed, so fall
  725. // back to queueing Packages files without verification
  726. QueueIndexes(false);
  727. }
  728. /*}}}*/
  729. // AcqArchive::AcqArchive - Constructor /*{{{*/
  730. // ---------------------------------------------------------------------
  731. /* This just sets up the initial fetch environment and queues the first
  732. possibilitiy */
  733. pkgAcqArchive::pkgAcqArchive(pkgAcquire *Owner,pkgSourceList *Sources,
  734. pkgRecords *Recs,pkgCache::VerIterator const &Version,
  735. string &StoreFilename) :
  736. Item(Owner), Version(Version), Sources(Sources), Recs(Recs),
  737. StoreFilename(StoreFilename), Vf(Version.FileList()),
  738. Trusted(false)
  739. {
  740. Retries = _config->FindI("Acquire::Retries",0);
  741. if (Version.Arch() == 0)
  742. {
  743. _error->Error(_("I wasn't able to locate a file for the %s package. "
  744. "This might mean you need to manually fix this package. "
  745. "(due to missing arch)"),
  746. Version.ParentPkg().Name());
  747. return;
  748. }
  749. /* We need to find a filename to determine the extension. We make the
  750. assumption here that all the available sources for this version share
  751. the same extension.. */
  752. // Skip not source sources, they do not have file fields.
  753. for (; Vf.end() == false; Vf++)
  754. {
  755. if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
  756. continue;
  757. break;
  758. }
  759. // Does not really matter here.. we are going to fail out below
  760. if (Vf.end() != true)
  761. {
  762. // If this fails to get a file name we will bomb out below.
  763. pkgRecords::Parser &Parse = Recs->Lookup(Vf);
  764. if (_error->PendingError() == true)
  765. return;
  766. // Generate the final file name as: package_version_arch.foo
  767. StoreFilename = QuoteString(Version.ParentPkg().Name(),"_:") + '_' +
  768. QuoteString(Version.VerStr(),"_:") + '_' +
  769. QuoteString(Version.Arch(),"_:.") +
  770. "." + flExtension(Parse.FileName());
  771. }
  772. // check if we have one trusted source for the package. if so, switch
  773. // to "TrustedOnly" mode
  774. for (pkgCache::VerFileIterator i = Version.FileList(); i.end() == false; i++)
  775. {
  776. pkgIndexFile *Index;
  777. if (Sources->FindIndex(i.File(),Index) == false)
  778. continue;
  779. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  780. {
  781. std::cerr << "Checking index: " << Index->Describe()
  782. << "(Trusted=" << Index->IsTrusted() << ")\n";
  783. }
  784. if (Index->IsTrusted()) {
  785. Trusted = true;
  786. break;
  787. }
  788. }
  789. // "allow-unauthenticated" restores apts old fetching behaviour
  790. // that means that e.g. unauthenticated file:// uris are higher
  791. // priority than authenticated http:// uris
  792. if (_config->FindB("APT::Get::AllowUnauthenticated",false) == true)
  793. Trusted = false;
  794. // Select a source
  795. if (QueueNext() == false && _error->PendingError() == false)
  796. _error->Error(_("I wasn't able to locate file for the %s package. "
  797. "This might mean you need to manually fix this package."),
  798. Version.ParentPkg().Name());
  799. }
  800. /*}}}*/
  801. // AcqArchive::QueueNext - Queue the next file source /*{{{*/
  802. // ---------------------------------------------------------------------
  803. /* This queues the next available file version for download. It checks if
  804. the archive is already available in the cache and stashs the MD5 for
  805. checking later. */
  806. bool pkgAcqArchive::QueueNext()
  807. {
  808. for (; Vf.end() == false; Vf++)
  809. {
  810. // Ignore not source sources
  811. if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
  812. continue;
  813. // Try to cross match against the source list
  814. pkgIndexFile *Index;
  815. if (Sources->FindIndex(Vf.File(),Index) == false)
  816. continue;
  817. // only try to get a trusted package from another source if that source
  818. // is also trusted
  819. if(Trusted && !Index->IsTrusted())
  820. continue;
  821. // Grab the text package record
  822. pkgRecords::Parser &Parse = Recs->Lookup(Vf);
  823. if (_error->PendingError() == true)
  824. return false;
  825. string PkgFile = Parse.FileName();
  826. MD5 = Parse.MD5Hash();
  827. if (PkgFile.empty() == true)
  828. return _error->Error(_("The package index files are corrupted. No Filename: "
  829. "field for package %s."),
  830. Version.ParentPkg().Name());
  831. Desc.URI = Index->ArchiveURI(PkgFile);
  832. Desc.Description = Index->ArchiveInfo(Version);
  833. Desc.Owner = this;
  834. Desc.ShortDesc = Version.ParentPkg().Name();
  835. // See if we already have the file. (Legacy filenames)
  836. FileSize = Version->Size;
  837. string FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(PkgFile);
  838. struct stat Buf;
  839. if (stat(FinalFile.c_str(),&Buf) == 0)
  840. {
  841. // Make sure the size matches
  842. if ((unsigned)Buf.st_size == Version->Size)
  843. {
  844. Complete = true;
  845. Local = true;
  846. Status = StatDone;
  847. StoreFilename = DestFile = FinalFile;
  848. return true;
  849. }
  850. /* Hmm, we have a file and its size does not match, this means it is
  851. an old style mismatched arch */
  852. unlink(FinalFile.c_str());
  853. }
  854. // Check it again using the new style output filenames
  855. FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename);
  856. if (stat(FinalFile.c_str(),&Buf) == 0)
  857. {
  858. // Make sure the size matches
  859. if ((unsigned)Buf.st_size == Version->Size)
  860. {
  861. Complete = true;
  862. Local = true;
  863. Status = StatDone;
  864. StoreFilename = DestFile = FinalFile;
  865. return true;
  866. }
  867. /* Hmm, we have a file and its size does not match, this shouldnt
  868. happen.. */
  869. unlink(FinalFile.c_str());
  870. }
  871. DestFile = _config->FindDir("Dir::Cache::Archives") + "partial/" + flNotDir(StoreFilename);
  872. // Check the destination file
  873. if (stat(DestFile.c_str(),&Buf) == 0)
  874. {
  875. // Hmm, the partial file is too big, erase it
  876. if ((unsigned)Buf.st_size > Version->Size)
  877. unlink(DestFile.c_str());
  878. else
  879. PartialSize = Buf.st_size;
  880. }
  881. // Create the item
  882. Local = false;
  883. Desc.URI = Index->ArchiveURI(PkgFile);
  884. Desc.Description = Index->ArchiveInfo(Version);
  885. Desc.Owner = this;
  886. Desc.ShortDesc = Version.ParentPkg().Name();
  887. QueueURI(Desc);
  888. Vf++;
  889. return true;
  890. }
  891. return false;
  892. }
  893. /*}}}*/
  894. // AcqArchive::Done - Finished fetching /*{{{*/
  895. // ---------------------------------------------------------------------
  896. /* */
  897. void pkgAcqArchive::Done(string Message,unsigned long Size,string Md5Hash,
  898. pkgAcquire::MethodConfig *Cfg)
  899. {
  900. Item::Done(Message,Size,Md5Hash,Cfg);
  901. // Check the size
  902. if (Size != Version->Size)
  903. {
  904. Status = StatError;
  905. ErrorText = _("Size mismatch");
  906. return;
  907. }
  908. // Check the md5
  909. if (Md5Hash.empty() == false && MD5.empty() == false)
  910. {
  911. if (Md5Hash != MD5)
  912. {
  913. Status = StatError;
  914. ErrorText = _("MD5Sum mismatch");
  915. if(FileExists(DestFile))
  916. Rename(DestFile,DestFile + ".FAILED");
  917. return;
  918. }
  919. }
  920. // Grab the output filename
  921. string FileName = LookupTag(Message,"Filename");
  922. if (FileName.empty() == true)
  923. {
  924. Status = StatError;
  925. ErrorText = "Method gave a blank filename";
  926. return;
  927. }
  928. Complete = true;
  929. // Reference filename
  930. if (FileName != DestFile)
  931. {
  932. StoreFilename = DestFile = FileName;
  933. Local = true;
  934. return;
  935. }
  936. // Done, move it into position
  937. string FinalFile = _config->FindDir("Dir::Cache::Archives");
  938. FinalFile += flNotDir(StoreFilename);
  939. Rename(DestFile,FinalFile);
  940. StoreFilename = DestFile = FinalFile;
  941. Complete = true;
  942. }
  943. /*}}}*/
  944. // AcqArchive::Failed - Failure handler /*{{{*/
  945. // ---------------------------------------------------------------------
  946. /* Here we try other sources */
  947. void pkgAcqArchive::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  948. {
  949. ErrorText = LookupTag(Message,"Message");
  950. /* We don't really want to retry on failed media swaps, this prevents
  951. that. An interesting observation is that permanent failures are not
  952. recorded. */
  953. if (Cnf->Removable == true &&
  954. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  955. {
  956. // Vf = Version.FileList();
  957. while (Vf.end() == false) Vf++;
  958. StoreFilename = string();
  959. Item::Failed(Message,Cnf);
  960. return;
  961. }
  962. if (QueueNext() == false)
  963. {
  964. // This is the retry counter
  965. if (Retries != 0 &&
  966. Cnf->LocalOnly == false &&
  967. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  968. {
  969. Retries--;
  970. Vf = Version.FileList();
  971. if (QueueNext() == true)
  972. return;
  973. }
  974. StoreFilename = string();
  975. Item::Failed(Message,Cnf);
  976. }
  977. }
  978. /*}}}*/
  979. // AcqArchive::IsTrusted - Determine whether this archive comes from a
  980. // trusted source /*{{{*/
  981. // ---------------------------------------------------------------------
  982. bool pkgAcqArchive::IsTrusted()
  983. {
  984. return Trusted;
  985. }
  986. // AcqArchive::Finished - Fetching has finished, tidy up /*{{{*/
  987. // ---------------------------------------------------------------------
  988. /* */
  989. void pkgAcqArchive::Finished()
  990. {
  991. if (Status == pkgAcquire::Item::StatDone &&
  992. Complete == true)
  993. return;
  994. StoreFilename = string();
  995. }
  996. /*}}}*/
  997. // AcqFile::pkgAcqFile - Constructor /*{{{*/
  998. // ---------------------------------------------------------------------
  999. /* The file is added to the queue */
  1000. pkgAcqFile::pkgAcqFile(pkgAcquire *Owner,string URI,string MD5,
  1001. unsigned long Size,string Dsc,string ShortDesc,
  1002. const string &DestDir, const string &DestFilename) :
  1003. Item(Owner), Md5Hash(MD5)
  1004. {
  1005. Retries = _config->FindI("Acquire::Retries",0);
  1006. if(!DestFilename.empty())
  1007. DestFile = DestFilename;
  1008. else if(!DestDir.empty())
  1009. DestFile = DestDir + "/" + flNotDir(URI);
  1010. else
  1011. DestFile = flNotDir(URI);
  1012. // Create the item
  1013. Desc.URI = URI;
  1014. Desc.Description = Dsc;
  1015. Desc.Owner = this;
  1016. // Set the short description to the archive component
  1017. Desc.ShortDesc = ShortDesc;
  1018. // Get the transfer sizes
  1019. FileSize = Size;
  1020. struct stat Buf;
  1021. if (stat(DestFile.c_str(),&Buf) == 0)
  1022. {
  1023. // Hmm, the partial file is too big, erase it
  1024. if ((unsigned)Buf.st_size > Size)
  1025. unlink(DestFile.c_str());
  1026. else
  1027. PartialSize = Buf.st_size;
  1028. }
  1029. QueueURI(Desc);
  1030. }
  1031. /*}}}*/
  1032. // AcqFile::Done - Item downloaded OK /*{{{*/
  1033. // ---------------------------------------------------------------------
  1034. /* */
  1035. void pkgAcqFile::Done(string Message,unsigned long Size,string MD5,
  1036. pkgAcquire::MethodConfig *Cnf)
  1037. {
  1038. // Check the md5
  1039. if (Md5Hash.empty() == false && MD5.empty() == false)
  1040. {
  1041. if (Md5Hash != MD5)
  1042. {
  1043. Status = StatError;
  1044. ErrorText = "MD5Sum mismatch";
  1045. Rename(DestFile,DestFile + ".FAILED");
  1046. return;
  1047. }
  1048. }
  1049. Item::Done(Message,Size,MD5,Cnf);
  1050. string FileName = LookupTag(Message,"Filename");
  1051. if (FileName.empty() == true)
  1052. {
  1053. Status = StatError;
  1054. ErrorText = "Method gave a blank filename";
  1055. return;
  1056. }
  1057. Complete = true;
  1058. // The files timestamp matches
  1059. if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  1060. return;
  1061. // We have to copy it into place
  1062. if (FileName != DestFile)
  1063. {
  1064. Local = true;
  1065. if (_config->FindB("Acquire::Source-Symlinks",true) == false ||
  1066. Cnf->Removable == true)
  1067. {
  1068. Desc.URI = "copy:" + FileName;
  1069. QueueURI(Desc);
  1070. return;
  1071. }
  1072. // Erase the file if it is a symlink so we can overwrite it
  1073. struct stat St;
  1074. if (lstat(DestFile.c_str(),&St) == 0)
  1075. {
  1076. if (S_ISLNK(St.st_mode) != 0)
  1077. unlink(DestFile.c_str());
  1078. }
  1079. // Symlink the file
  1080. if (symlink(FileName.c_str(),DestFile.c_str()) != 0)
  1081. {
  1082. ErrorText = "Link to " + DestFile + " failure ";
  1083. Status = StatError;
  1084. Complete = false;
  1085. }
  1086. }
  1087. }
  1088. /*}}}*/
  1089. // AcqFile::Failed - Failure handler /*{{{*/
  1090. // ---------------------------------------------------------------------
  1091. /* Here we try other sources */
  1092. void pkgAcqFile::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  1093. {
  1094. ErrorText = LookupTag(Message,"Message");
  1095. // This is the retry counter
  1096. if (Retries != 0 &&
  1097. Cnf->LocalOnly == false &&
  1098. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  1099. {
  1100. Retries--;
  1101. QueueURI(Desc);
  1102. return;
  1103. }
  1104. Item::Failed(Message,Cnf);
  1105. }
  1106. /*}}}*/