acquire-item.cc 36 KB

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