You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1792 lines
55 KiB

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