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.
 
 
 
 
 
 

2293 lines
72 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 <config.h>
  14. #include <apt-pkg/acquire-item.h>
  15. #include <apt-pkg/configuration.h>
  16. #include <apt-pkg/aptconfiguration.h>
  17. #include <apt-pkg/sourcelist.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 <apt-pkg/indexrecords.h>
  25. #include <apt-pkg/metaindex.h>
  26. #include <sys/stat.h>
  27. #include <unistd.h>
  28. #include <errno.h>
  29. #include <string>
  30. #include <sstream>
  31. #include <stdio.h>
  32. #include <ctime>
  33. #include <apti18n.h>
  34. /*}}}*/
  35. using namespace std;
  36. // Acquire::Item::Item - Constructor /*{{{*/
  37. // ---------------------------------------------------------------------
  38. /* */
  39. pkgAcquire::Item::Item(pkgAcquire *Owner) : Owner(Owner), FileSize(0),
  40. PartialSize(0), Mode(0), ID(0), Complete(false),
  41. Local(false), QueueCounter(0)
  42. {
  43. Owner->Add(this);
  44. Status = StatIdle;
  45. }
  46. /*}}}*/
  47. // Acquire::Item::~Item - Destructor /*{{{*/
  48. // ---------------------------------------------------------------------
  49. /* */
  50. pkgAcquire::Item::~Item()
  51. {
  52. Owner->Remove(this);
  53. }
  54. /*}}}*/
  55. // Acquire::Item::Failed - Item failed to download /*{{{*/
  56. // ---------------------------------------------------------------------
  57. /* We return to an idle state if there are still other queues that could
  58. fetch this object */
  59. void pkgAcquire::Item::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  60. {
  61. Status = StatIdle;
  62. ErrorText = LookupTag(Message,"Message");
  63. UsedMirror = LookupTag(Message,"UsedMirror");
  64. if (QueueCounter <= 1)
  65. {
  66. /* This indicates that the file is not available right now but might
  67. be sometime later. If we do a retry cycle then this should be
  68. retried [CDROMs] */
  69. if (Cnf->LocalOnly == true &&
  70. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  71. {
  72. Status = StatIdle;
  73. Dequeue();
  74. return;
  75. }
  76. Status = StatError;
  77. Dequeue();
  78. }
  79. // report mirror failure back to LP if we actually use a mirror
  80. string FailReason = LookupTag(Message, "FailReason");
  81. if(FailReason.size() != 0)
  82. ReportMirrorFailure(FailReason);
  83. else
  84. ReportMirrorFailure(ErrorText);
  85. }
  86. /*}}}*/
  87. // Acquire::Item::Start - Item has begun to download /*{{{*/
  88. // ---------------------------------------------------------------------
  89. /* Stash status and the file size. Note that setting Complete means
  90. sub-phases of the acquire process such as decompresion are operating */
  91. void pkgAcquire::Item::Start(string /*Message*/,unsigned long long Size)
  92. {
  93. Status = StatFetching;
  94. if (FileSize == 0 && Complete == false)
  95. FileSize = Size;
  96. }
  97. /*}}}*/
  98. // Acquire::Item::Done - Item downloaded OK /*{{{*/
  99. // ---------------------------------------------------------------------
  100. /* */
  101. void pkgAcquire::Item::Done(string Message,unsigned long long Size,string Hash,
  102. pkgAcquire::MethodConfig *Cnf)
  103. {
  104. // We just downloaded something..
  105. string FileName = LookupTag(Message,"Filename");
  106. UsedMirror = LookupTag(Message,"UsedMirror");
  107. if (Complete == false && !Local && FileName == DestFile)
  108. {
  109. if (Owner->Log != 0)
  110. Owner->Log->Fetched(Size,atoi(LookupTag(Message,"Resume-Point","0").c_str()));
  111. }
  112. if (FileSize == 0)
  113. FileSize= Size;
  114. Status = StatDone;
  115. ErrorText = string();
  116. Owner->Dequeue(this);
  117. }
  118. /*}}}*/
  119. // Acquire::Item::Rename - Rename a file /*{{{*/
  120. // ---------------------------------------------------------------------
  121. /* This helper function is used by alot of item methods as thier final
  122. step */
  123. void pkgAcquire::Item::Rename(string From,string To)
  124. {
  125. if (rename(From.c_str(),To.c_str()) != 0)
  126. {
  127. char S[300];
  128. snprintf(S,sizeof(S),_("rename failed, %s (%s -> %s)."),strerror(errno),
  129. From.c_str(),To.c_str());
  130. Status = StatError;
  131. ErrorText = S;
  132. }
  133. }
  134. /*}}}*/
  135. bool pkgAcquire::Item::RenameOnError(pkgAcquire::Item::RenameOnErrorState const error)/*{{{*/
  136. {
  137. if(FileExists(DestFile))
  138. Rename(DestFile, DestFile + ".FAILED");
  139. switch (error)
  140. {
  141. case HashSumMismatch:
  142. ErrorText = _("Hash Sum mismatch");
  143. Status = StatAuthError;
  144. ReportMirrorFailure("HashChecksumFailure");
  145. break;
  146. case SizeMismatch:
  147. ErrorText = _("Size mismatch");
  148. Status = StatAuthError;
  149. ReportMirrorFailure("SizeFailure");
  150. break;
  151. case InvalidFormat:
  152. ErrorText = _("Invalid file format");
  153. Status = StatError;
  154. // do not report as usually its not the mirrors fault, but Portal/Proxy
  155. break;
  156. }
  157. return false;
  158. }
  159. /*}}}*/
  160. // Acquire::Item::ReportMirrorFailure /*{{{*/
  161. // ---------------------------------------------------------------------
  162. void pkgAcquire::Item::ReportMirrorFailure(string FailCode)
  163. {
  164. // we only act if a mirror was used at all
  165. if(UsedMirror.empty())
  166. return;
  167. #if 0
  168. std::cerr << "\nReportMirrorFailure: "
  169. << UsedMirror
  170. << " Uri: " << DescURI()
  171. << " FailCode: "
  172. << FailCode << std::endl;
  173. #endif
  174. const char *Args[40];
  175. unsigned int i = 0;
  176. string report = _config->Find("Methods::Mirror::ProblemReporting",
  177. "/usr/lib/apt/apt-report-mirror-failure");
  178. if(!FileExists(report))
  179. return;
  180. Args[i++] = report.c_str();
  181. Args[i++] = UsedMirror.c_str();
  182. Args[i++] = DescURI().c_str();
  183. Args[i++] = FailCode.c_str();
  184. Args[i++] = NULL;
  185. pid_t pid = ExecFork();
  186. if(pid < 0)
  187. {
  188. _error->Error("ReportMirrorFailure Fork failed");
  189. return;
  190. }
  191. else if(pid == 0)
  192. {
  193. execvp(Args[0], (char**)Args);
  194. std::cerr << "Could not exec " << Args[0] << std::endl;
  195. _exit(100);
  196. }
  197. if(!ExecWait(pid, "report-mirror-failure"))
  198. {
  199. _error->Warning("Couldn't report problem to '%s'",
  200. _config->Find("Methods::Mirror::ProblemReporting").c_str());
  201. }
  202. }
  203. /*}}}*/
  204. // AcqSubIndex::AcqSubIndex - Constructor /*{{{*/
  205. // ---------------------------------------------------------------------
  206. /* Get a sub-index file based on checksums from a 'master' file and
  207. possibly query additional files */
  208. pkgAcqSubIndex::pkgAcqSubIndex(pkgAcquire *Owner, string const &URI,
  209. string const &URIDesc, string const &ShortDesc,
  210. HashString const &ExpectedHash)
  211. : Item(Owner), ExpectedHash(ExpectedHash)
  212. {
  213. /* XXX: Beware: Currently this class does nothing (of value) anymore ! */
  214. Debug = _config->FindB("Debug::pkgAcquire::SubIndex",false);
  215. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  216. DestFile += URItoFileName(URI);
  217. Desc.URI = URI;
  218. Desc.Description = URIDesc;
  219. Desc.Owner = this;
  220. Desc.ShortDesc = ShortDesc;
  221. QueueURI(Desc);
  222. if(Debug)
  223. std::clog << "pkgAcqSubIndex: " << Desc.URI << std::endl;
  224. }
  225. /*}}}*/
  226. // AcqSubIndex::Custom600Headers - Insert custom request headers /*{{{*/
  227. // ---------------------------------------------------------------------
  228. /* The only header we use is the last-modified header. */
  229. string pkgAcqSubIndex::Custom600Headers()
  230. {
  231. string Final = _config->FindDir("Dir::State::lists");
  232. Final += URItoFileName(Desc.URI);
  233. struct stat Buf;
  234. if (stat(Final.c_str(),&Buf) != 0)
  235. return "\nIndex-File: true\nFail-Ignore: true\n";
  236. return "\nIndex-File: true\nFail-Ignore: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  237. }
  238. /*}}}*/
  239. void pkgAcqSubIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
  240. {
  241. if(Debug)
  242. std::clog << "pkgAcqSubIndex failed: " << Desc.URI << std::endl;
  243. Complete = false;
  244. Status = StatDone;
  245. Dequeue();
  246. // No good Index is provided
  247. }
  248. /*}}}*/
  249. void pkgAcqSubIndex::Done(string Message,unsigned long long Size,string Md5Hash, /*{{{*/
  250. pkgAcquire::MethodConfig *Cnf)
  251. {
  252. if(Debug)
  253. std::clog << "pkgAcqSubIndex::Done(): " << Desc.URI << std::endl;
  254. string FileName = LookupTag(Message,"Filename");
  255. if (FileName.empty() == true)
  256. {
  257. Status = StatError;
  258. ErrorText = "Method gave a blank filename";
  259. return;
  260. }
  261. if (FileName != DestFile)
  262. {
  263. Local = true;
  264. Desc.URI = "copy:" + FileName;
  265. QueueURI(Desc);
  266. return;
  267. }
  268. Item::Done(Message,Size,Md5Hash,Cnf);
  269. string FinalFile = _config->FindDir("Dir::State::lists")+URItoFileName(Desc.URI);
  270. /* Downloaded invalid transindex => Error (LP: #346386) (Closes: #627642) */
  271. indexRecords SubIndexParser;
  272. if (FileExists(DestFile) == true && !SubIndexParser.Load(DestFile)) {
  273. Status = StatError;
  274. ErrorText = SubIndexParser.ErrorText;
  275. return;
  276. }
  277. // sucess in downloading the index
  278. // rename the index
  279. if(Debug)
  280. std::clog << "Renaming: " << DestFile << " -> " << FinalFile << std::endl;
  281. Rename(DestFile,FinalFile);
  282. chmod(FinalFile.c_str(),0644);
  283. DestFile = FinalFile;
  284. if(ParseIndex(DestFile) == false)
  285. return Failed("", NULL);
  286. Complete = true;
  287. Status = StatDone;
  288. Dequeue();
  289. return;
  290. }
  291. /*}}}*/
  292. bool pkgAcqSubIndex::ParseIndex(string const &IndexFile) /*{{{*/
  293. {
  294. indexRecords SubIndexParser;
  295. if (FileExists(IndexFile) == false || SubIndexParser.Load(IndexFile) == false)
  296. return false;
  297. // so something with the downloaded index
  298. return true;
  299. }
  300. /*}}}*/
  301. // AcqDiffIndex::AcqDiffIndex - Constructor /*{{{*/
  302. // ---------------------------------------------------------------------
  303. /* Get the DiffIndex file first and see if there are patches availabe
  304. * If so, create a pkgAcqIndexDiffs fetcher that will get and apply the
  305. * patches. If anything goes wrong in that process, it will fall back to
  306. * the original packages file
  307. */
  308. pkgAcqDiffIndex::pkgAcqDiffIndex(pkgAcquire *Owner,
  309. string URI,string URIDesc,string ShortDesc,
  310. HashString ExpectedHash)
  311. : Item(Owner), RealURI(URI), ExpectedHash(ExpectedHash),
  312. Description(URIDesc)
  313. {
  314. Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
  315. Desc.Description = URIDesc + "/DiffIndex";
  316. Desc.Owner = this;
  317. Desc.ShortDesc = ShortDesc;
  318. Desc.URI = URI + ".diff/Index";
  319. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  320. DestFile += URItoFileName(URI) + string(".DiffIndex");
  321. if(Debug)
  322. std::clog << "pkgAcqDiffIndex: " << Desc.URI << std::endl;
  323. // look for the current package file
  324. CurrentPackagesFile = _config->FindDir("Dir::State::lists");
  325. CurrentPackagesFile += URItoFileName(RealURI);
  326. // FIXME: this file:/ check is a hack to prevent fetching
  327. // from local sources. this is really silly, and
  328. // should be fixed cleanly as soon as possible
  329. if(!FileExists(CurrentPackagesFile) ||
  330. Desc.URI.substr(0,strlen("file:/")) == "file:/")
  331. {
  332. // we don't have a pkg file or we don't want to queue
  333. if(Debug)
  334. std::clog << "No index file, local or canceld by user" << std::endl;
  335. Failed("", NULL);
  336. return;
  337. }
  338. if(Debug)
  339. std::clog << "pkgAcqDiffIndex::pkgAcqDiffIndex(): "
  340. << CurrentPackagesFile << std::endl;
  341. QueueURI(Desc);
  342. }
  343. /*}}}*/
  344. // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
  345. // ---------------------------------------------------------------------
  346. /* The only header we use is the last-modified header. */
  347. string pkgAcqDiffIndex::Custom600Headers()
  348. {
  349. string Final = _config->FindDir("Dir::State::lists");
  350. Final += URItoFileName(RealURI) + string(".IndexDiff");
  351. if(Debug)
  352. std::clog << "Custom600Header-IMS: " << Final << std::endl;
  353. struct stat Buf;
  354. if (stat(Final.c_str(),&Buf) != 0)
  355. return "\nIndex-File: true";
  356. return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  357. }
  358. /*}}}*/
  359. bool pkgAcqDiffIndex::ParseDiffIndex(string IndexDiffFile) /*{{{*/
  360. {
  361. if(Debug)
  362. std::clog << "pkgAcqDiffIndex::ParseIndexDiff() " << IndexDiffFile
  363. << std::endl;
  364. pkgTagSection Tags;
  365. string ServerSha1;
  366. vector<DiffInfo> available_patches;
  367. FileFd Fd(IndexDiffFile,FileFd::ReadOnly);
  368. pkgTagFile TF(&Fd);
  369. if (_error->PendingError() == true)
  370. return false;
  371. if(TF.Step(Tags) == true)
  372. {
  373. bool found = false;
  374. DiffInfo d;
  375. string size;
  376. string const tmp = Tags.FindS("SHA1-Current");
  377. std::stringstream ss(tmp);
  378. ss >> ServerSha1 >> size;
  379. unsigned long const ServerSize = atol(size.c_str());
  380. FileFd fd(CurrentPackagesFile, FileFd::ReadOnly);
  381. SHA1Summation SHA1;
  382. SHA1.AddFD(fd);
  383. string const local_sha1 = SHA1.Result();
  384. if(local_sha1 == ServerSha1)
  385. {
  386. // we have the same sha1 as the server so we are done here
  387. if(Debug)
  388. std::clog << "Package file is up-to-date" << std::endl;
  389. // list cleanup needs to know that this file as well as the already
  390. // present index is ours, so we create an empty diff to save it for us
  391. new pkgAcqIndexDiffs(Owner, RealURI, Description, Desc.ShortDesc,
  392. ExpectedHash, ServerSha1, available_patches);
  393. return true;
  394. }
  395. else
  396. {
  397. if(Debug)
  398. std::clog << "SHA1-Current: " << ServerSha1 << " and we start at "<< fd.Name() << " " << fd.Size() << " " << local_sha1 << std::endl;
  399. // check the historie and see what patches we need
  400. string const history = Tags.FindS("SHA1-History");
  401. std::stringstream hist(history);
  402. while(hist >> d.sha1 >> size >> d.file)
  403. {
  404. // read until the first match is found
  405. // from that point on, we probably need all diffs
  406. if(d.sha1 == local_sha1)
  407. found=true;
  408. else if (found == false)
  409. continue;
  410. if(Debug)
  411. std::clog << "Need to get diff: " << d.file << std::endl;
  412. available_patches.push_back(d);
  413. }
  414. if (available_patches.empty() == false)
  415. {
  416. // patching with too many files is rather slow compared to a fast download
  417. unsigned long const fileLimit = _config->FindI("Acquire::PDiffs::FileLimit", 0);
  418. if (fileLimit != 0 && fileLimit < available_patches.size())
  419. {
  420. if (Debug)
  421. std::clog << "Need " << available_patches.size() << " diffs (Limit is " << fileLimit
  422. << ") so fallback to complete download" << std::endl;
  423. return false;
  424. }
  425. // see if the patches are too big
  426. found = false; // it was true and it will be true again at the end
  427. d = *available_patches.begin();
  428. string const firstPatch = d.file;
  429. unsigned long patchesSize = 0;
  430. std::stringstream patches(Tags.FindS("SHA1-Patches"));
  431. while(patches >> d.sha1 >> size >> d.file)
  432. {
  433. if (firstPatch == d.file)
  434. found = true;
  435. else if (found == false)
  436. continue;
  437. patchesSize += atol(size.c_str());
  438. }
  439. unsigned long const sizeLimit = ServerSize * _config->FindI("Acquire::PDiffs::SizeLimit", 100);
  440. if (sizeLimit > 0 && (sizeLimit/100) < patchesSize)
  441. {
  442. if (Debug)
  443. std::clog << "Need " << patchesSize << " bytes (Limit is " << sizeLimit/100
  444. << ") so fallback to complete download" << std::endl;
  445. return false;
  446. }
  447. }
  448. }
  449. // we have something, queue the next diff
  450. if(found)
  451. {
  452. // queue the diffs
  453. string::size_type const last_space = Description.rfind(" ");
  454. if(last_space != string::npos)
  455. Description.erase(last_space, Description.size()-last_space);
  456. /* decide if we should download patches one by one or in one go:
  457. The first is good if the server merges patches, but many don't so client
  458. based merging can be attempt in which case the second is better.
  459. "bad things" will happen if patches are merged on the server,
  460. but client side merging is attempt as well */
  461. bool pdiff_merge = _config->FindB("Acquire::PDiffs::Merge", true);
  462. if (pdiff_merge == true)
  463. {
  464. // reprepro adds this flag if it has merged patches on the server
  465. std::string const precedence = Tags.FindS("X-Patch-Precedence");
  466. pdiff_merge = (precedence != "merged");
  467. }
  468. if (pdiff_merge == false)
  469. new pkgAcqIndexDiffs(Owner, RealURI, Description, Desc.ShortDesc,
  470. ExpectedHash, ServerSha1, available_patches);
  471. else
  472. {
  473. std::vector<pkgAcqIndexMergeDiffs*> *diffs = new std::vector<pkgAcqIndexMergeDiffs*>(available_patches.size());
  474. for(size_t i = 0; i < available_patches.size(); ++i)
  475. (*diffs)[i] = new pkgAcqIndexMergeDiffs(Owner, RealURI, Description, Desc.ShortDesc, ExpectedHash,
  476. available_patches[i], diffs);
  477. }
  478. Complete = false;
  479. Status = StatDone;
  480. Dequeue();
  481. return true;
  482. }
  483. }
  484. // Nothing found, report and return false
  485. // Failing here is ok, if we return false later, the full
  486. // IndexFile is queued
  487. if(Debug)
  488. std::clog << "Can't find a patch in the index file" << std::endl;
  489. return false;
  490. }
  491. /*}}}*/
  492. void pkgAcqDiffIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
  493. {
  494. if(Debug)
  495. std::clog << "pkgAcqDiffIndex failed: " << Desc.URI << std::endl
  496. << "Falling back to normal index file aquire" << std::endl;
  497. new pkgAcqIndex(Owner, RealURI, Description, Desc.ShortDesc,
  498. ExpectedHash);
  499. Complete = false;
  500. Status = StatDone;
  501. Dequeue();
  502. }
  503. /*}}}*/
  504. void pkgAcqDiffIndex::Done(string Message,unsigned long long Size,string Md5Hash, /*{{{*/
  505. pkgAcquire::MethodConfig *Cnf)
  506. {
  507. if(Debug)
  508. std::clog << "pkgAcqDiffIndex::Done(): " << Desc.URI << std::endl;
  509. Item::Done(Message,Size,Md5Hash,Cnf);
  510. string FinalFile;
  511. FinalFile = _config->FindDir("Dir::State::lists")+URItoFileName(RealURI);
  512. // sucess in downloading the index
  513. // rename the index
  514. FinalFile += string(".IndexDiff");
  515. if(Debug)
  516. std::clog << "Renaming: " << DestFile << " -> " << FinalFile
  517. << std::endl;
  518. Rename(DestFile,FinalFile);
  519. chmod(FinalFile.c_str(),0644);
  520. DestFile = FinalFile;
  521. if(!ParseDiffIndex(DestFile))
  522. return Failed("", NULL);
  523. Complete = true;
  524. Status = StatDone;
  525. Dequeue();
  526. return;
  527. }
  528. /*}}}*/
  529. // AcqIndexDiffs::AcqIndexDiffs - Constructor /*{{{*/
  530. // ---------------------------------------------------------------------
  531. /* The package diff is added to the queue. one object is constructed
  532. * for each diff and the index
  533. */
  534. pkgAcqIndexDiffs::pkgAcqIndexDiffs(pkgAcquire *Owner,
  535. string URI,string URIDesc,string ShortDesc,
  536. HashString ExpectedHash,
  537. string ServerSha1,
  538. vector<DiffInfo> diffs)
  539. : Item(Owner), RealURI(URI), ExpectedHash(ExpectedHash),
  540. available_patches(diffs), ServerSha1(ServerSha1)
  541. {
  542. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  543. DestFile += URItoFileName(URI);
  544. Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
  545. Description = URIDesc;
  546. Desc.Owner = this;
  547. Desc.ShortDesc = ShortDesc;
  548. if(available_patches.empty() == true)
  549. {
  550. // we are done (yeah!)
  551. Finish(true);
  552. }
  553. else
  554. {
  555. // get the next diff
  556. State = StateFetchDiff;
  557. QueueNextDiff();
  558. }
  559. }
  560. /*}}}*/
  561. void pkgAcqIndexDiffs::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
  562. {
  563. if(Debug)
  564. std::clog << "pkgAcqIndexDiffs failed: " << Desc.URI << std::endl
  565. << "Falling back to normal index file aquire" << std::endl;
  566. new pkgAcqIndex(Owner, RealURI, Description,Desc.ShortDesc,
  567. ExpectedHash);
  568. Finish();
  569. }
  570. /*}}}*/
  571. // Finish - helper that cleans the item out of the fetcher queue /*{{{*/
  572. void pkgAcqIndexDiffs::Finish(bool allDone)
  573. {
  574. // we restore the original name, this is required, otherwise
  575. // the file will be cleaned
  576. if(allDone)
  577. {
  578. DestFile = _config->FindDir("Dir::State::lists");
  579. DestFile += URItoFileName(RealURI);
  580. if(!ExpectedHash.empty() && !ExpectedHash.VerifyFile(DestFile))
  581. {
  582. RenameOnError(HashSumMismatch);
  583. Dequeue();
  584. return;
  585. }
  586. // this is for the "real" finish
  587. Complete = true;
  588. Status = StatDone;
  589. Dequeue();
  590. if(Debug)
  591. std::clog << "\n\nallDone: " << DestFile << "\n" << std::endl;
  592. return;
  593. }
  594. if(Debug)
  595. std::clog << "Finishing: " << Desc.URI << std::endl;
  596. Complete = false;
  597. Status = StatDone;
  598. Dequeue();
  599. return;
  600. }
  601. /*}}}*/
  602. bool pkgAcqIndexDiffs::QueueNextDiff() /*{{{*/
  603. {
  604. // calc sha1 of the just patched file
  605. string FinalFile = _config->FindDir("Dir::State::lists");
  606. FinalFile += URItoFileName(RealURI);
  607. FileFd fd(FinalFile, FileFd::ReadOnly);
  608. SHA1Summation SHA1;
  609. SHA1.AddFD(fd);
  610. string local_sha1 = string(SHA1.Result());
  611. if(Debug)
  612. std::clog << "QueueNextDiff: "
  613. << FinalFile << " (" << local_sha1 << ")"<<std::endl;
  614. // final file reached before all patches are applied
  615. if(local_sha1 == ServerSha1)
  616. {
  617. Finish(true);
  618. return true;
  619. }
  620. // remove all patches until the next matching patch is found
  621. // this requires the Index file to be ordered
  622. for(vector<DiffInfo>::iterator I=available_patches.begin();
  623. available_patches.empty() == false &&
  624. I != available_patches.end() &&
  625. I->sha1 != local_sha1;
  626. ++I)
  627. {
  628. available_patches.erase(I);
  629. }
  630. // error checking and falling back if no patch was found
  631. if(available_patches.empty() == true)
  632. {
  633. Failed("", NULL);
  634. return false;
  635. }
  636. // queue the right diff
  637. Desc.URI = string(RealURI) + ".diff/" + available_patches[0].file + ".gz";
  638. Desc.Description = Description + " " + available_patches[0].file + string(".pdiff");
  639. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  640. DestFile += URItoFileName(RealURI + ".diff/" + available_patches[0].file);
  641. if(Debug)
  642. std::clog << "pkgAcqIndexDiffs::QueueNextDiff(): " << Desc.URI << std::endl;
  643. QueueURI(Desc);
  644. return true;
  645. }
  646. /*}}}*/
  647. void pkgAcqIndexDiffs::Done(string Message,unsigned long long Size,string Md5Hash, /*{{{*/
  648. pkgAcquire::MethodConfig *Cnf)
  649. {
  650. if(Debug)
  651. std::clog << "pkgAcqIndexDiffs::Done(): " << Desc.URI << std::endl;
  652. Item::Done(Message,Size,Md5Hash,Cnf);
  653. string FinalFile;
  654. FinalFile = _config->FindDir("Dir::State::lists")+URItoFileName(RealURI);
  655. // sucess in downloading a diff, enter ApplyDiff state
  656. if(State == StateFetchDiff)
  657. {
  658. // rred excepts the patch as $FinalFile.ed
  659. Rename(DestFile,FinalFile+".ed");
  660. if(Debug)
  661. std::clog << "Sending to rred method: " << FinalFile << std::endl;
  662. State = StateApplyDiff;
  663. Local = true;
  664. Desc.URI = "rred:" + FinalFile;
  665. QueueURI(Desc);
  666. Mode = "rred";
  667. return;
  668. }
  669. // success in download/apply a diff, queue next (if needed)
  670. if(State == StateApplyDiff)
  671. {
  672. // remove the just applied patch
  673. available_patches.erase(available_patches.begin());
  674. // move into place
  675. if(Debug)
  676. {
  677. std::clog << "Moving patched file in place: " << std::endl
  678. << DestFile << " -> " << FinalFile << std::endl;
  679. }
  680. Rename(DestFile,FinalFile);
  681. chmod(FinalFile.c_str(),0644);
  682. // see if there is more to download
  683. if(available_patches.empty() == false) {
  684. new pkgAcqIndexDiffs(Owner, RealURI, Description, Desc.ShortDesc,
  685. ExpectedHash, ServerSha1, available_patches);
  686. return Finish();
  687. } else
  688. return Finish(true);
  689. }
  690. }
  691. /*}}}*/
  692. // AcqIndexMergeDiffs::AcqIndexMergeDiffs - Constructor /*{{{*/
  693. pkgAcqIndexMergeDiffs::pkgAcqIndexMergeDiffs(pkgAcquire *Owner,
  694. string const &URI, string const &URIDesc,
  695. string const &ShortDesc, HashString const &ExpectedHash,
  696. DiffInfo const &patch,
  697. std::vector<pkgAcqIndexMergeDiffs*> const * const allPatches)
  698. : Item(Owner), RealURI(URI), ExpectedHash(ExpectedHash),
  699. patch(patch),allPatches(allPatches), State(StateFetchDiff)
  700. {
  701. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  702. DestFile += URItoFileName(URI);
  703. Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
  704. Description = URIDesc;
  705. Desc.Owner = this;
  706. Desc.ShortDesc = ShortDesc;
  707. Desc.URI = string(RealURI) + ".diff/" + patch.file + ".gz";
  708. Desc.Description = Description + " " + patch.file + string(".pdiff");
  709. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  710. DestFile += URItoFileName(RealURI + ".diff/" + patch.file);
  711. if(Debug)
  712. std::clog << "pkgAcqIndexMergeDiffs: " << Desc.URI << std::endl;
  713. QueueURI(Desc);
  714. }
  715. /*}}}*/
  716. void pkgAcqIndexMergeDiffs::Failed(string Message,pkgAcquire::MethodConfig *Cnf)/*{{{*/
  717. {
  718. if(Debug)
  719. std::clog << "pkgAcqIndexMergeDiffs failed: " << Desc.URI << " with " << Message << std::endl;
  720. Complete = false;
  721. Status = StatDone;
  722. Dequeue();
  723. // check if we are the first to fail, otherwise we are done here
  724. State = StateDoneDiff;
  725. for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
  726. I != allPatches->end(); ++I)
  727. if ((*I)->State == StateErrorDiff)
  728. return;
  729. // first failure means we should fallback
  730. State = StateErrorDiff;
  731. std::clog << "Falling back to normal index file aquire" << std::endl;
  732. new pkgAcqIndex(Owner, RealURI, Description,Desc.ShortDesc,
  733. ExpectedHash);
  734. }
  735. /*}}}*/
  736. void pkgAcqIndexMergeDiffs::Done(string Message,unsigned long long Size,string Md5Hash, /*{{{*/
  737. pkgAcquire::MethodConfig *Cnf)
  738. {
  739. if(Debug)
  740. std::clog << "pkgAcqIndexMergeDiffs::Done(): " << Desc.URI << std::endl;
  741. Item::Done(Message,Size,Md5Hash,Cnf);
  742. string const FinalFile = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
  743. if (State == StateFetchDiff)
  744. {
  745. // rred expects the patch as $FinalFile.ed.$patchname.gz
  746. Rename(DestFile, FinalFile + ".ed." + patch.file + ".gz");
  747. // check if this is the last completed diff
  748. State = StateDoneDiff;
  749. for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
  750. I != allPatches->end(); ++I)
  751. if ((*I)->State != StateDoneDiff)
  752. {
  753. if(Debug)
  754. std::clog << "Not the last done diff in the batch: " << Desc.URI << std::endl;
  755. return;
  756. }
  757. // this is the last completed diff, so we are ready to apply now
  758. State = StateApplyDiff;
  759. if(Debug)
  760. std::clog << "Sending to rred method: " << FinalFile << std::endl;
  761. Local = true;
  762. Desc.URI = "rred:" + FinalFile;
  763. QueueURI(Desc);
  764. Mode = "rred";
  765. return;
  766. }
  767. // success in download/apply all diffs, clean up
  768. else if (State == StateApplyDiff)
  769. {
  770. // see if we really got the expected file
  771. if(!ExpectedHash.empty() && !ExpectedHash.VerifyFile(DestFile))
  772. {
  773. RenameOnError(HashSumMismatch);
  774. return;
  775. }
  776. // move the result into place
  777. if(Debug)
  778. std::clog << "Moving patched file in place: " << std::endl
  779. << DestFile << " -> " << FinalFile << std::endl;
  780. Rename(DestFile, FinalFile);
  781. chmod(FinalFile.c_str(), 0644);
  782. // otherwise lists cleanup will eat the file
  783. DestFile = FinalFile;
  784. // all set and done
  785. Complete = true;
  786. if(Debug)
  787. std::clog << "allDone: " << DestFile << "\n" << std::endl;
  788. }
  789. }
  790. /*}}}*/
  791. // AcqIndex::AcqIndex - Constructor /*{{{*/
  792. // ---------------------------------------------------------------------
  793. /* The package file is added to the queue and a second class is
  794. instantiated to fetch the revision file */
  795. pkgAcqIndex::pkgAcqIndex(pkgAcquire *Owner,
  796. string URI,string URIDesc,string ShortDesc,
  797. HashString ExpectedHash, string comprExt)
  798. : Item(Owner), RealURI(URI), ExpectedHash(ExpectedHash)
  799. {
  800. if(comprExt.empty() == true)
  801. {
  802. // autoselect the compression method
  803. std::vector<std::string> types = APT::Configuration::getCompressionTypes();
  804. for (std::vector<std::string>::const_iterator t = types.begin(); t != types.end(); ++t)
  805. comprExt.append(*t).append(" ");
  806. if (comprExt.empty() == false)
  807. comprExt.erase(comprExt.end()-1);
  808. }
  809. CompressionExtension = comprExt;
  810. Init(URI, URIDesc, ShortDesc);
  811. }
  812. pkgAcqIndex::pkgAcqIndex(pkgAcquire *Owner, IndexTarget const *Target,
  813. HashString const &ExpectedHash, indexRecords const *MetaIndexParser)
  814. : Item(Owner), RealURI(Target->URI), ExpectedHash(ExpectedHash)
  815. {
  816. // autoselect the compression method
  817. std::vector<std::string> types = APT::Configuration::getCompressionTypes();
  818. CompressionExtension = "";
  819. if (ExpectedHash.empty() == false)
  820. {
  821. for (std::vector<std::string>::const_iterator t = types.begin(); t != types.end(); ++t)
  822. if (*t == "uncompressed" || MetaIndexParser->Exists(string(Target->MetaKey).append(".").append(*t)) == true)
  823. CompressionExtension.append(*t).append(" ");
  824. }
  825. else
  826. {
  827. for (std::vector<std::string>::const_iterator t = types.begin(); t != types.end(); ++t)
  828. CompressionExtension.append(*t).append(" ");
  829. }
  830. if (CompressionExtension.empty() == false)
  831. CompressionExtension.erase(CompressionExtension.end()-1);
  832. // only verify non-optional targets, see acquire-item.h for a FIXME
  833. // to make this more flexible
  834. if (Target->IsOptional())
  835. Verify = false;
  836. else
  837. Verify = true;
  838. Init(Target->URI, Target->Description, Target->ShortDesc);
  839. }
  840. /*}}}*/
  841. // AcqIndex::Init - defered Constructor /*{{{*/
  842. void pkgAcqIndex::Init(string const &URI, string const &URIDesc, string const &ShortDesc) {
  843. Decompression = false;
  844. Erase = false;
  845. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  846. DestFile += URItoFileName(URI);
  847. std::string const comprExt = CompressionExtension.substr(0, CompressionExtension.find(' '));
  848. if (comprExt == "uncompressed")
  849. Desc.URI = URI;
  850. else
  851. Desc.URI = URI + '.' + comprExt;
  852. Desc.Description = URIDesc;
  853. Desc.Owner = this;
  854. Desc.ShortDesc = ShortDesc;
  855. QueueURI(Desc);
  856. }
  857. /*}}}*/
  858. // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
  859. // ---------------------------------------------------------------------
  860. /* The only header we use is the last-modified header. */
  861. string pkgAcqIndex::Custom600Headers()
  862. {
  863. string Final = _config->FindDir("Dir::State::lists");
  864. Final += URItoFileName(RealURI);
  865. if (_config->FindB("Acquire::GzipIndexes",false))
  866. Final += ".gz";
  867. string msg = "\nIndex-File: true";
  868. // FIXME: this really should use "IndexTarget::IsOptional()" but that
  869. // seems to be difficult without breaking ABI
  870. if (ShortDesc().find("Translation") != 0)
  871. msg += "\nFail-Ignore: true";
  872. struct stat Buf;
  873. if (stat(Final.c_str(),&Buf) == 0)
  874. msg += "\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  875. return msg;
  876. }
  877. /*}}}*/
  878. void pkgAcqIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
  879. {
  880. size_t const nextExt = CompressionExtension.find(' ');
  881. if (nextExt != std::string::npos)
  882. {
  883. CompressionExtension = CompressionExtension.substr(nextExt+1);
  884. Init(RealURI, Desc.Description, Desc.ShortDesc);
  885. return;
  886. }
  887. // on decompression failure, remove bad versions in partial/
  888. if (Decompression && Erase) {
  889. string s = _config->FindDir("Dir::State::lists") + "partial/";
  890. s.append(URItoFileName(RealURI));
  891. unlink(s.c_str());
  892. }
  893. Item::Failed(Message,Cnf);
  894. }
  895. /*}}}*/
  896. // AcqIndex::Done - Finished a fetch /*{{{*/
  897. // ---------------------------------------------------------------------
  898. /* This goes through a number of states.. On the initial fetch the
  899. method could possibly return an alternate filename which points
  900. to the uncompressed version of the file. If this is so the file
  901. is copied into the partial directory. In all other cases the file
  902. is decompressed with a gzip uri. */
  903. void pkgAcqIndex::Done(string Message,unsigned long long Size,string Hash,
  904. pkgAcquire::MethodConfig *Cfg)
  905. {
  906. Item::Done(Message,Size,Hash,Cfg);
  907. if (Decompression == true)
  908. {
  909. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  910. {
  911. std::cerr << std::endl << RealURI << ": Computed Hash: " << Hash;
  912. std::cerr << " Expected Hash: " << ExpectedHash.toStr() << std::endl;
  913. }
  914. if (!ExpectedHash.empty() && ExpectedHash.toStr() != Hash)
  915. {
  916. RenameOnError(HashSumMismatch);
  917. return;
  918. }
  919. /* Verify the index file for correctness (all indexes must
  920. * have a Package field) (LP: #346386) (Closes: #627642) */
  921. if (Verify == true)
  922. {
  923. FileFd fd(DestFile, FileFd::ReadOnly);
  924. // Only test for correctness if the file is not empty (empty is ok)
  925. if (fd.FileSize() > 0)
  926. {
  927. pkgTagSection sec;
  928. pkgTagFile tag(&fd);
  929. // all our current indexes have a field 'Package' in each section
  930. if (_error->PendingError() == true || tag.Step(sec) == false || sec.Exists("Package") == false)
  931. {
  932. RenameOnError(InvalidFormat);
  933. return;
  934. }
  935. }
  936. }
  937. // Done, move it into position
  938. string FinalFile = _config->FindDir("Dir::State::lists");
  939. FinalFile += URItoFileName(RealURI);
  940. Rename(DestFile,FinalFile);
  941. chmod(FinalFile.c_str(),0644);
  942. /* We restore the original name to DestFile so that the clean operation
  943. will work OK */
  944. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  945. DestFile += URItoFileName(RealURI);
  946. // Remove the compressed version.
  947. if (Erase == true)
  948. unlink(DestFile.c_str());
  949. return;
  950. }
  951. Erase = false;
  952. Complete = true;
  953. // Handle the unzipd case
  954. string FileName = LookupTag(Message,"Alt-Filename");
  955. if (FileName.empty() == false)
  956. {
  957. // The files timestamp matches
  958. if (StringToBool(LookupTag(Message,"Alt-IMS-Hit"),false) == true)
  959. return;
  960. Decompression = true;
  961. Local = true;
  962. DestFile += ".decomp";
  963. Desc.URI = "copy:" + FileName;
  964. QueueURI(Desc);
  965. Mode = "copy";
  966. return;
  967. }
  968. FileName = LookupTag(Message,"Filename");
  969. if (FileName.empty() == true)
  970. {
  971. Status = StatError;
  972. ErrorText = "Method gave a blank filename";
  973. }
  974. std::string const compExt = CompressionExtension.substr(0, CompressionExtension.find(' '));
  975. // The files timestamp matches
  976. if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == true) {
  977. if (_config->FindB("Acquire::GzipIndexes",false) && compExt == "gz")
  978. // Update DestFile for .gz suffix so that the clean operation keeps it
  979. DestFile += ".gz";
  980. return;
  981. }
  982. if (FileName == DestFile)
  983. Erase = true;
  984. else
  985. Local = true;
  986. string decompProg;
  987. // If we enable compressed indexes and already have gzip, keep it
  988. if (_config->FindB("Acquire::GzipIndexes",false) && compExt == "gz" && !Local) {
  989. string FinalFile = _config->FindDir("Dir::State::lists");
  990. FinalFile += URItoFileName(RealURI) + ".gz";
  991. Rename(DestFile,FinalFile);
  992. chmod(FinalFile.c_str(),0644);
  993. // Update DestFile for .gz suffix so that the clean operation keeps it
  994. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  995. DestFile += URItoFileName(RealURI) + ".gz";
  996. return;
  997. }
  998. // get the binary name for your used compression type
  999. decompProg = _config->Find(string("Acquire::CompressionTypes::").append(compExt),"");
  1000. if(decompProg.empty() == false);
  1001. else if(compExt == "uncompressed")
  1002. decompProg = "copy";
  1003. else {
  1004. _error->Error("Unsupported extension: %s", compExt.c_str());
  1005. return;
  1006. }
  1007. Decompression = true;
  1008. DestFile += ".decomp";
  1009. Desc.URI = decompProg + ":" + FileName;
  1010. QueueURI(Desc);
  1011. // FIXME: this points to a c++ string that goes out of scope
  1012. Mode = decompProg.c_str();
  1013. }
  1014. /*}}}*/
  1015. // AcqIndexTrans::pkgAcqIndexTrans - Constructor /*{{{*/
  1016. // ---------------------------------------------------------------------
  1017. /* The Translation file is added to the queue */
  1018. pkgAcqIndexTrans::pkgAcqIndexTrans(pkgAcquire *Owner,
  1019. string URI,string URIDesc,string ShortDesc)
  1020. : pkgAcqIndex(Owner, URI, URIDesc, ShortDesc, HashString(), "")
  1021. {
  1022. }
  1023. pkgAcqIndexTrans::pkgAcqIndexTrans(pkgAcquire *Owner, IndexTarget const *Target,
  1024. HashString const &ExpectedHash, indexRecords const *MetaIndexParser)
  1025. : pkgAcqIndex(Owner, Target, ExpectedHash, MetaIndexParser)
  1026. {
  1027. }
  1028. /*}}}*/
  1029. // AcqIndexTrans::Custom600Headers - Insert custom request headers /*{{{*/
  1030. // ---------------------------------------------------------------------
  1031. string pkgAcqIndexTrans::Custom600Headers()
  1032. {
  1033. string Final = _config->FindDir("Dir::State::lists");
  1034. Final += URItoFileName(RealURI);
  1035. struct stat Buf;
  1036. if (stat(Final.c_str(),&Buf) != 0)
  1037. return "\nFail-Ignore: true\nIndex-File: true";
  1038. return "\nFail-Ignore: true\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  1039. }
  1040. /*}}}*/
  1041. // AcqIndexTrans::Failed - Silence failure messages for missing files /*{{{*/
  1042. // ---------------------------------------------------------------------
  1043. /* */
  1044. void pkgAcqIndexTrans::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  1045. {
  1046. size_t const nextExt = CompressionExtension.find(' ');
  1047. if (nextExt != std::string::npos)
  1048. {
  1049. CompressionExtension = CompressionExtension.substr(nextExt+1);
  1050. Init(RealURI, Desc.Description, Desc.ShortDesc);
  1051. Status = StatIdle;
  1052. return;
  1053. }
  1054. if (Cnf->LocalOnly == true ||
  1055. StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
  1056. {
  1057. // Ignore this
  1058. Status = StatDone;
  1059. Complete = false;
  1060. Dequeue();
  1061. return;
  1062. }
  1063. Item::Failed(Message,Cnf);
  1064. }
  1065. /*}}}*/
  1066. pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire *Owner, /*{{{*/
  1067. string URI,string URIDesc,string ShortDesc,
  1068. string MetaIndexURI, string MetaIndexURIDesc,
  1069. string MetaIndexShortDesc,
  1070. const vector<IndexTarget*>* IndexTargets,
  1071. indexRecords* MetaIndexParser) :
  1072. Item(Owner), RealURI(URI), MetaIndexURI(MetaIndexURI),
  1073. MetaIndexURIDesc(MetaIndexURIDesc), MetaIndexShortDesc(MetaIndexShortDesc),
  1074. MetaIndexParser(MetaIndexParser), IndexTargets(IndexTargets)
  1075. {
  1076. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  1077. DestFile += URItoFileName(URI);
  1078. // remove any partial downloaded sig-file in partial/.
  1079. // it may confuse proxies and is too small to warrant a
  1080. // partial download anyway
  1081. unlink(DestFile.c_str());
  1082. // Create the item
  1083. Desc.Description = URIDesc;
  1084. Desc.Owner = this;
  1085. Desc.ShortDesc = ShortDesc;
  1086. Desc.URI = URI;
  1087. string Final = _config->FindDir("Dir::State::lists");
  1088. Final += URItoFileName(RealURI);
  1089. if (RealFileExists(Final) == true)
  1090. {
  1091. // File was already in place. It needs to be re-downloaded/verified
  1092. // because Release might have changed, we do give it a differnt
  1093. // name than DestFile because otherwise the http method will
  1094. // send If-Range requests and there are too many broken servers
  1095. // out there that do not understand them
  1096. LastGoodSig = DestFile+".reverify";
  1097. Rename(Final,LastGoodSig);
  1098. }
  1099. QueueURI(Desc);
  1100. }
  1101. /*}}}*/
  1102. pkgAcqMetaSig::~pkgAcqMetaSig() /*{{{*/
  1103. {
  1104. // if the file was never queued undo file-changes done in the constructor
  1105. if (QueueCounter == 1 && Status == StatIdle && FileSize == 0 && Complete == false &&
  1106. LastGoodSig.empty() == false)
  1107. {
  1108. string const Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
  1109. if (RealFileExists(Final) == false && RealFileExists(LastGoodSig) == true)
  1110. Rename(LastGoodSig, Final);
  1111. }
  1112. }
  1113. /*}}}*/
  1114. // pkgAcqMetaSig::Custom600Headers - Insert custom request headers /*{{{*/
  1115. // ---------------------------------------------------------------------
  1116. /* The only header we use is the last-modified header. */
  1117. string pkgAcqMetaSig::Custom600Headers()
  1118. {
  1119. struct stat Buf;
  1120. if (stat(LastGoodSig.c_str(),&Buf) != 0)
  1121. return "\nIndex-File: true";
  1122. return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  1123. }
  1124. void pkgAcqMetaSig::Done(string Message,unsigned long long Size,string MD5,
  1125. pkgAcquire::MethodConfig *Cfg)
  1126. {
  1127. Item::Done(Message,Size,MD5,Cfg);
  1128. string FileName = LookupTag(Message,"Filename");
  1129. if (FileName.empty() == true)
  1130. {
  1131. Status = StatError;
  1132. ErrorText = "Method gave a blank filename";
  1133. return;
  1134. }
  1135. if (FileName != DestFile)
  1136. {
  1137. // We have to copy it into place
  1138. Local = true;
  1139. Desc.URI = "copy:" + FileName;
  1140. QueueURI(Desc);
  1141. return;
  1142. }
  1143. Complete = true;
  1144. // put the last known good file back on i-m-s hit (it will
  1145. // be re-verified again)
  1146. // Else do nothing, we have the new file in DestFile then
  1147. if(StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  1148. Rename(LastGoodSig, DestFile);
  1149. // queue a pkgAcqMetaIndex to be verified against the sig we just retrieved
  1150. new pkgAcqMetaIndex(Owner, MetaIndexURI, MetaIndexURIDesc,
  1151. MetaIndexShortDesc, DestFile, IndexTargets,
  1152. MetaIndexParser);
  1153. }
  1154. /*}}}*/
  1155. void pkgAcqMetaSig::Failed(string Message,pkgAcquire::MethodConfig *Cnf)/*{{{*/
  1156. {
  1157. string Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
  1158. // if we get a network error we fail gracefully
  1159. if(Status == StatTransientNetworkError)
  1160. {
  1161. Item::Failed(Message,Cnf);
  1162. // move the sigfile back on transient network failures
  1163. if(FileExists(LastGoodSig))
  1164. Rename(LastGoodSig,Final);
  1165. // set the status back to , Item::Failed likes to reset it
  1166. Status = pkgAcquire::Item::StatTransientNetworkError;
  1167. return;
  1168. }
  1169. // Delete any existing sigfile when the acquire failed
  1170. unlink(Final.c_str());
  1171. // queue a pkgAcqMetaIndex with no sigfile
  1172. new pkgAcqMetaIndex(Owner, MetaIndexURI, MetaIndexURIDesc, MetaIndexShortDesc,
  1173. "", IndexTargets, MetaIndexParser);
  1174. if (Cnf->LocalOnly == true ||
  1175. StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
  1176. {
  1177. // Ignore this
  1178. Status = StatDone;
  1179. Complete = false;
  1180. Dequeue();
  1181. return;
  1182. }
  1183. Item::Failed(Message,Cnf);
  1184. }
  1185. /*}}}*/
  1186. pkgAcqMetaIndex::pkgAcqMetaIndex(pkgAcquire *Owner, /*{{{*/
  1187. string URI,string URIDesc,string ShortDesc,
  1188. string SigFile,
  1189. const vector<struct IndexTarget*>* IndexTargets,
  1190. indexRecords* MetaIndexParser) :
  1191. Item(Owner), RealURI(URI), SigFile(SigFile), IndexTargets(IndexTargets),
  1192. MetaIndexParser(MetaIndexParser), AuthPass(false), IMSHit(false)
  1193. {
  1194. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  1195. DestFile += URItoFileName(URI);
  1196. // Create the item
  1197. Desc.Description = URIDesc;
  1198. Desc.Owner = this;
  1199. Desc.ShortDesc = ShortDesc;
  1200. Desc.URI = URI;
  1201. QueueURI(Desc);
  1202. }
  1203. /*}}}*/
  1204. // pkgAcqMetaIndex::Custom600Headers - Insert custom request headers /*{{{*/
  1205. // ---------------------------------------------------------------------
  1206. /* The only header we use is the last-modified header. */
  1207. string pkgAcqMetaIndex::Custom600Headers()
  1208. {
  1209. string Final = _config->FindDir("Dir::State::lists");
  1210. Final += URItoFileName(RealURI);
  1211. struct stat Buf;
  1212. if (stat(Final.c_str(),&Buf) != 0)
  1213. return "\nIndex-File: true";
  1214. return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  1215. }
  1216. /*}}}*/
  1217. void pkgAcqMetaIndex::Done(string Message,unsigned long long Size,string Hash, /*{{{*/
  1218. pkgAcquire::MethodConfig *Cfg)
  1219. {
  1220. Item::Done(Message,Size,Hash,Cfg);
  1221. // MetaIndexes are done in two passes: one to download the
  1222. // metaindex with an appropriate method, and a second to verify it
  1223. // with the gpgv method
  1224. if (AuthPass == true)
  1225. {
  1226. AuthDone(Message);
  1227. // all cool, move Release file into place
  1228. Complete = true;
  1229. }
  1230. else
  1231. {
  1232. RetrievalDone(Message);
  1233. if (!Complete)
  1234. // Still more retrieving to do
  1235. return;
  1236. if (SigFile == "")
  1237. {
  1238. // There was no signature file, so we are finished. Download
  1239. // the indexes and do only hashsum verification if possible
  1240. MetaIndexParser->Load(DestFile);
  1241. QueueIndexes(false);
  1242. }
  1243. else
  1244. {
  1245. // There was a signature file, so pass it to gpgv for
  1246. // verification
  1247. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1248. std::cerr << "Metaindex acquired, queueing gpg verification ("
  1249. << SigFile << "," << DestFile << ")\n";
  1250. AuthPass = true;
  1251. Desc.URI = "gpgv:" + SigFile;
  1252. QueueURI(Desc);
  1253. Mode = "gpgv";
  1254. return;
  1255. }
  1256. }
  1257. if (Complete == true)
  1258. {
  1259. string FinalFile = _config->FindDir("Dir::State::lists");
  1260. FinalFile += URItoFileName(RealURI);
  1261. if (SigFile == DestFile)
  1262. SigFile = FinalFile;
  1263. Rename(DestFile,FinalFile);
  1264. chmod(FinalFile.c_str(),0644);
  1265. DestFile = FinalFile;
  1266. }
  1267. }
  1268. /*}}}*/
  1269. void pkgAcqMetaIndex::RetrievalDone(string Message) /*{{{*/
  1270. {
  1271. // We have just finished downloading a Release file (it is not
  1272. // verified yet)
  1273. string FileName = LookupTag(Message,"Filename");
  1274. if (FileName.empty() == true)
  1275. {
  1276. Status = StatError;
  1277. ErrorText = "Method gave a blank filename";
  1278. return;
  1279. }
  1280. if (FileName != DestFile)
  1281. {
  1282. Local = true;
  1283. Desc.URI = "copy:" + FileName;
  1284. QueueURI(Desc);
  1285. return;
  1286. }
  1287. // make sure to verify against the right file on I-M-S hit
  1288. IMSHit = StringToBool(LookupTag(Message,"IMS-Hit"),false);
  1289. if(IMSHit)
  1290. {
  1291. string FinalFile = _config->FindDir("Dir::State::lists");
  1292. FinalFile += URItoFileName(RealURI);
  1293. if (SigFile == DestFile)
  1294. {
  1295. SigFile = FinalFile;
  1296. // constructor of pkgAcqMetaClearSig moved it out of the way,
  1297. // now move it back in on IMS hit for the 'old' file
  1298. string const OldClearSig = DestFile + ".reverify";
  1299. if (RealFileExists(OldClearSig) == true)
  1300. Rename(OldClearSig, FinalFile);
  1301. }
  1302. DestFile = FinalFile;
  1303. }
  1304. Complete = true;
  1305. }
  1306. /*}}}*/
  1307. void pkgAcqMetaIndex::AuthDone(string Message) /*{{{*/
  1308. {
  1309. // At this point, the gpgv method has succeeded, so there is a
  1310. // valid signature from a key in the trusted keyring. We
  1311. // perform additional verification of its contents, and use them
  1312. // to verify the indexes we are about to download
  1313. if (!MetaIndexParser->Load(DestFile))
  1314. {
  1315. Status = StatAuthError;
  1316. ErrorText = MetaIndexParser->ErrorText;
  1317. return;
  1318. }
  1319. if (!VerifyVendor(Message))
  1320. {
  1321. return;
  1322. }
  1323. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1324. std::cerr << "Signature verification succeeded: "
  1325. << DestFile << std::endl;
  1326. // Download further indexes with verification
  1327. QueueIndexes(true);
  1328. // is it a clearsigned MetaIndex file?
  1329. if (DestFile == SigFile)
  1330. return;
  1331. // Done, move signature file into position
  1332. string VerifiedSigFile = _config->FindDir("Dir::State::lists") +
  1333. URItoFileName(RealURI) + ".gpg";
  1334. Rename(SigFile,VerifiedSigFile);
  1335. chmod(VerifiedSigFile.c_str(),0644);
  1336. }
  1337. /*}}}*/
  1338. void pkgAcqMetaIndex::QueueIndexes(bool verify) /*{{{*/
  1339. {
  1340. #if 0
  1341. /* Reject invalid, existing Release files (LP: #346386) (Closes: #627642)
  1342. * FIXME: Disabled; it breaks unsigned repositories without hashes */
  1343. if (!verify && FileExists(DestFile) && !MetaIndexParser->Load(DestFile))
  1344. {
  1345. Status = StatError;
  1346. ErrorText = MetaIndexParser->ErrorText;
  1347. return;
  1348. }
  1349. #endif
  1350. bool transInRelease = false;
  1351. {
  1352. std::vector<std::string> const keys = MetaIndexParser->MetaKeys();
  1353. for (std::vector<std::string>::const_iterator k = keys.begin(); k != keys.end(); ++k)
  1354. // FIXME: Feels wrong to check for hardcoded string here, but what should we do elseā€¦
  1355. if (k->find("Translation-") != std::string::npos)
  1356. {
  1357. transInRelease = true;
  1358. break;
  1359. }
  1360. }
  1361. for (vector <struct IndexTarget*>::const_iterator Target = IndexTargets->begin();
  1362. Target != IndexTargets->end();
  1363. ++Target)
  1364. {
  1365. HashString ExpectedIndexHash;
  1366. const indexRecords::checkSum *Record = MetaIndexParser->Lookup((*Target)->MetaKey);
  1367. bool compressedAvailable = false;
  1368. if (Record == NULL)
  1369. {
  1370. if ((*Target)->IsOptional() == true)
  1371. {
  1372. std::vector<std::string> types = APT::Configuration::getCompressionTypes();
  1373. for (std::vector<std::string>::const_iterator t = types.begin(); t != types.end(); ++t)
  1374. if (MetaIndexParser->Exists(string((*Target)->MetaKey).append(".").append(*t)) == true)
  1375. {
  1376. compressedAvailable = true;
  1377. break;
  1378. }
  1379. }
  1380. else if (verify == true)
  1381. {
  1382. Status = StatAuthError;
  1383. strprintf(ErrorText, _("Unable to find expected entry '%s' in Release file (Wrong sources.list entry or malformed file)"), (*Target)->MetaKey.c_str());
  1384. return;
  1385. }
  1386. }
  1387. else
  1388. {
  1389. ExpectedIndexHash = Record->Hash;
  1390. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1391. {
  1392. std::cerr << "Queueing: " << (*Target)->URI << std::endl;
  1393. std::cerr << "Expected Hash: " << ExpectedIndexHash.toStr() << std::endl;
  1394. std::cerr << "For: " << Record->MetaKeyFilename << std::endl;
  1395. }
  1396. if (verify == true && ExpectedIndexHash.empty() == true && (*Target)->IsOptional() == false)
  1397. {
  1398. Status = StatAuthError;
  1399. strprintf(ErrorText, _("Unable to find hash sum for '%s' in Release file"), (*Target)->MetaKey.c_str());
  1400. return;
  1401. }
  1402. }
  1403. if ((*Target)->IsOptional() == true)
  1404. {
  1405. if ((*Target)->IsSubIndex() == true)
  1406. new pkgAcqSubIndex(Owner, (*Target)->URI, (*Target)->Description,
  1407. (*Target)->ShortDesc, ExpectedIndexHash);
  1408. else if (transInRelease == false || Record != NULL || compressedAvailable == true)
  1409. {
  1410. if (_config->FindB("Acquire::PDiffs",true) == true && transInRelease == true &&
  1411. MetaIndexParser->Exists(string((*Target)->MetaKey).append(".diff/Index")) == true)
  1412. new pkgAcqDiffIndex(Owner, (*Target)->URI, (*Target)->Description,
  1413. (*Target)->ShortDesc, ExpectedIndexHash);
  1414. else
  1415. new pkgAcqIndexTrans(Owner, *Target, ExpectedIndexHash, MetaIndexParser);
  1416. }
  1417. continue;
  1418. }
  1419. /* Queue Packages file (either diff or full packages files, depending
  1420. on the users option) - we also check if the PDiff Index file is listed
  1421. in the Meta-Index file. Ideal would be if pkgAcqDiffIndex would test this
  1422. instead, but passing the required info to it is to much hassle */
  1423. if(_config->FindB("Acquire::PDiffs",true) == true && (verify == false ||
  1424. MetaIndexParser->Exists(string((*Target)->MetaKey).append(".diff/Index")) == true))
  1425. new pkgAcqDiffIndex(Owner, (*Target)->URI, (*Target)->Description,
  1426. (*Target)->ShortDesc, ExpectedIndexHash);
  1427. else
  1428. new pkgAcqIndex(Owner, *Target, ExpectedIndexHash, MetaIndexParser);
  1429. }
  1430. }
  1431. /*}}}*/
  1432. bool pkgAcqMetaIndex::VerifyVendor(string Message) /*{{{*/
  1433. {
  1434. string::size_type pos;
  1435. // check for missing sigs (that where not fatal because otherwise we had
  1436. // bombed earlier)
  1437. string missingkeys;
  1438. string msg = _("There is no public key available for the "
  1439. "following key IDs:\n");
  1440. pos = Message.find("NO_PUBKEY ");
  1441. if (pos != std::string::npos)
  1442. {
  1443. string::size_type start = pos+strlen("NO_PUBKEY ");
  1444. string Fingerprint = Message.substr(start, Message.find("\n")-start);
  1445. missingkeys += (Fingerprint);
  1446. }
  1447. if(!missingkeys.empty())
  1448. _error->Warning("%s", string(msg+missingkeys).c_str());
  1449. string Transformed = MetaIndexParser->GetExpectedDist();
  1450. if (Transformed == "../project/experimental")
  1451. {
  1452. Transformed = "experimental";
  1453. }
  1454. pos = Transformed.rfind('/');
  1455. if (pos != string::npos)
  1456. {
  1457. Transformed = Transformed.substr(0, pos);
  1458. }
  1459. if (Transformed == ".")
  1460. {
  1461. Transformed = "";
  1462. }
  1463. if (_config->FindB("Acquire::Check-Valid-Until", true) == true &&
  1464. MetaIndexParser->GetValidUntil() > 0) {
  1465. time_t const invalid_since = time(NULL) - MetaIndexParser->GetValidUntil();
  1466. if (invalid_since > 0)
  1467. // TRANSLATOR: The first %s is the URL of the bad Release file, the second is
  1468. // the time since then the file is invalid - formated in the same way as in
  1469. // the download progress display (e.g. 7d 3h 42min 1s)
  1470. return _error->Error(
  1471. _("Release file for %s is expired (invalid since %s). "
  1472. "Updates for this repository will not be applied."),
  1473. RealURI.c_str(), TimeToStr(invalid_since).c_str());
  1474. }
  1475. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1476. {
  1477. std::cerr << "Got Codename: " << MetaIndexParser->GetDist() << std::endl;
  1478. std::cerr << "Expecting Dist: " << MetaIndexParser->GetExpectedDist() << std::endl;
  1479. std::cerr << "Transformed Dist: " << Transformed << std::endl;
  1480. }
  1481. if (MetaIndexParser->CheckDist(Transformed) == false)
  1482. {
  1483. // This might become fatal one day
  1484. // Status = StatAuthError;
  1485. // ErrorText = "Conflicting distribution; expected "
  1486. // + MetaIndexParser->GetExpectedDist() + " but got "
  1487. // + MetaIndexParser->GetDist();
  1488. // return false;
  1489. if (!Transformed.empty())
  1490. {
  1491. _error->Warning(_("Conflicting distribution: %s (expected %s but got %s)"),
  1492. Desc.Description.c_str(),
  1493. Transformed.c_str(),
  1494. MetaIndexParser->GetDist().c_str());
  1495. }
  1496. }
  1497. return true;
  1498. }
  1499. /*}}}*/
  1500. // pkgAcqMetaIndex::Failed - no Release file present or no signature file present /*{{{*/
  1501. // ---------------------------------------------------------------------
  1502. /* */
  1503. void pkgAcqMetaIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  1504. {
  1505. if (AuthPass == true)
  1506. {
  1507. // gpgv method failed, if we have a good signature
  1508. string LastGoodSigFile = _config->FindDir("Dir::State::lists").append("partial/").append(URItoFileName(RealURI));
  1509. if (DestFile != SigFile)
  1510. LastGoodSigFile.append(".gpg");
  1511. LastGoodSigFile.append(".reverify");
  1512. if(FileExists(LastGoodSigFile))
  1513. {
  1514. string VerifiedSigFile = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
  1515. if (DestFile != SigFile)
  1516. VerifiedSigFile.append(".gpg");
  1517. Rename(LastGoodSigFile, VerifiedSigFile);
  1518. Status = StatTransientNetworkError;
  1519. _error->Warning(_("An error occurred during the signature "
  1520. "verification. The repository is not updated "
  1521. "and the previous index files will be used. "
  1522. "GPG error: %s: %s\n"),
  1523. Desc.Description.c_str(),
  1524. LookupTag(Message,"Message").c_str());
  1525. RunScripts("APT::Update::Auth-Failure");
  1526. return;
  1527. } else if (LookupTag(Message,"Message").find("NODATA") != string::npos) {
  1528. /* Invalid signature file, reject (LP: #346386) (Closes: #627642) */
  1529. _error->Error(_("GPG error: %s: %s"),
  1530. Desc.Description.c_str(),
  1531. LookupTag(Message,"Message").c_str());
  1532. return;
  1533. } else {
  1534. _error->Warning(_("GPG error: %s: %s"),
  1535. Desc.Description.c_str(),
  1536. LookupTag(Message,"Message").c_str());
  1537. }
  1538. // gpgv method failed
  1539. ReportMirrorFailure("GPGFailure");
  1540. }
  1541. /* Always move the meta index, even if gpgv failed. This ensures
  1542. * that PackageFile objects are correctly filled in */
  1543. if (FileExists(DestFile)) {
  1544. string FinalFile = _config->FindDir("Dir::State::lists");
  1545. FinalFile += URItoFileName(RealURI);
  1546. /* InRelease files become Release files, otherwise
  1547. * they would be considered as trusted later on */
  1548. if (SigFile == DestFile) {
  1549. RealURI = RealURI.replace(RealURI.rfind("InRelease"), 9,
  1550. "Release");
  1551. FinalFile = FinalFile.replace(FinalFile.rfind("InRelease"), 9,
  1552. "Release");
  1553. SigFile = FinalFile;
  1554. }
  1555. Rename(DestFile,FinalFile);
  1556. chmod(FinalFile.c_str(),0644);
  1557. DestFile = FinalFile;
  1558. }
  1559. // No Release file was present, or verification failed, so fall
  1560. // back to queueing Packages files without verification
  1561. QueueIndexes(false);
  1562. }
  1563. /*}}}*/
  1564. pkgAcqMetaClearSig::pkgAcqMetaClearSig(pkgAcquire *Owner, /*{{{*/
  1565. string const &URI, string const &URIDesc, string const &ShortDesc,
  1566. string const &MetaIndexURI, string const &MetaIndexURIDesc, string const &MetaIndexShortDesc,
  1567. string const &MetaSigURI, string const &MetaSigURIDesc, string const &MetaSigShortDesc,
  1568. const vector<struct IndexTarget*>* IndexTargets,
  1569. indexRecords* MetaIndexParser) :
  1570. pkgAcqMetaIndex(Owner, URI, URIDesc, ShortDesc, "", IndexTargets, MetaIndexParser),
  1571. MetaIndexURI(MetaIndexURI), MetaIndexURIDesc(MetaIndexURIDesc), MetaIndexShortDesc(MetaIndexShortDesc),
  1572. MetaSigURI(MetaSigURI), MetaSigURIDesc(MetaSigURIDesc), MetaSigShortDesc(MetaSigShortDesc)
  1573. {
  1574. SigFile = DestFile;
  1575. // keep the old InRelease around in case of transistent network errors
  1576. string const Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
  1577. if (RealFileExists(Final) == true)
  1578. {
  1579. string const LastGoodSig = DestFile + ".reverify";
  1580. Rename(Final,LastGoodSig);
  1581. }
  1582. }
  1583. /*}}}*/
  1584. pkgAcqMetaClearSig::~pkgAcqMetaClearSig() /*{{{*/
  1585. {
  1586. // if the file was never queued undo file-changes done in the constructor
  1587. if (QueueCounter == 1 && Status == StatIdle && FileSize == 0 && Complete == false)
  1588. {
  1589. string const Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
  1590. string const LastGoodSig = DestFile + ".reverify";
  1591. if (RealFileExists(Final) == false && RealFileExists(LastGoodSig) == true)
  1592. Rename(LastGoodSig, Final);
  1593. }
  1594. }
  1595. /*}}}*/
  1596. // pkgAcqMetaClearSig::Custom600Headers - Insert custom request headers /*{{{*/
  1597. // ---------------------------------------------------------------------
  1598. // FIXME: this can go away once the InRelease file is used widely
  1599. string pkgAcqMetaClearSig::Custom600Headers()
  1600. {
  1601. string Final = _config->FindDir("Dir::State::lists");
  1602. Final += URItoFileName(RealURI);
  1603. struct stat Buf;
  1604. if (stat(Final.c_str(),&Buf) != 0)
  1605. {
  1606. Final = DestFile + ".reverify";
  1607. if (stat(Final.c_str(),&Buf) != 0)
  1608. return "\nIndex-File: true\nFail-Ignore: true\n";
  1609. }
  1610. return "\nIndex-File: true\nFail-Ignore: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  1611. }
  1612. /*}}}*/
  1613. void pkgAcqMetaClearSig::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
  1614. {
  1615. if (AuthPass == false)
  1616. {
  1617. // Remove the 'old' InRelease file if we try Release.gpg now as otherwise
  1618. // the file will stay around and gives a false-auth impression (CVE-2012-0214)
  1619. string FinalFile = _config->FindDir("Dir::State::lists");
  1620. FinalFile.append(URItoFileName(RealURI));
  1621. if (FileExists(FinalFile))
  1622. unlink(FinalFile.c_str());
  1623. new pkgAcqMetaSig(Owner,
  1624. MetaSigURI, MetaSigURIDesc, MetaSigShortDesc,
  1625. MetaIndexURI, MetaIndexURIDesc, MetaIndexShortDesc,
  1626. IndexTargets, MetaIndexParser);
  1627. if (Cnf->LocalOnly == true ||
  1628. StringToBool(LookupTag(Message, "Transient-Failure"), false) == false)
  1629. Dequeue();
  1630. }
  1631. else
  1632. pkgAcqMetaIndex::Failed(Message, Cnf);
  1633. }
  1634. /*}}}*/
  1635. // AcqArchive::AcqArchive - Constructor /*{{{*/
  1636. // ---------------------------------------------------------------------
  1637. /* This just sets up the initial fetch environment and queues the first
  1638. possibilitiy */
  1639. pkgAcqArchive::pkgAcqArchive(pkgAcquire *Owner,pkgSourceList *Sources,
  1640. pkgRecords *Recs,pkgCache::VerIterator const &Version,
  1641. string &StoreFilename) :
  1642. Item(Owner), Version(Version), Sources(Sources), Recs(Recs),
  1643. StoreFilename(StoreFilename), Vf(Version.FileList()),
  1644. Trusted(false)
  1645. {
  1646. Retries = _config->FindI("Acquire::Retries",0);
  1647. if (Version.Arch() == 0)
  1648. {
  1649. _error->Error(_("I wasn't able to locate a file for the %s package. "
  1650. "This might mean you need to manually fix this package. "
  1651. "(due to missing arch)"),
  1652. Version.ParentPkg().Name());
  1653. return;
  1654. }
  1655. /* We need to find a filename to determine the extension. We make the
  1656. assumption here that all the available sources for this version share
  1657. the same extension.. */
  1658. // Skip not source sources, they do not have file fields.
  1659. for (; Vf.end() == false; ++Vf)
  1660. {
  1661. if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
  1662. continue;
  1663. break;
  1664. }
  1665. // Does not really matter here.. we are going to fail out below
  1666. if (Vf.end() != true)
  1667. {
  1668. // If this fails to get a file name we will bomb out below.
  1669. pkgRecords::Parser &Parse = Recs->Lookup(Vf);
  1670. if (_error->PendingError() == true)
  1671. return;
  1672. // Generate the final file name as: package_version_arch.foo
  1673. StoreFilename = QuoteString(Version.ParentPkg().Name(),"_:") + '_' +
  1674. QuoteString(Version.VerStr(),"_:") + '_' +
  1675. QuoteString(Version.Arch(),"_:.") +
  1676. "." + flExtension(Parse.FileName());
  1677. }
  1678. // check if we have one trusted source for the package. if so, switch
  1679. // to "TrustedOnly" mode - but only if not in AllowUnauthenticated mode
  1680. bool const allowUnauth = _config->FindB("APT::Get::AllowUnauthenticated", false);
  1681. bool const debugAuth = _config->FindB("Debug::pkgAcquire::Auth", false);
  1682. bool seenUntrusted = false;
  1683. for (pkgCache::VerFileIterator i = Version.FileList(); i.end() == false; ++i)
  1684. {
  1685. pkgIndexFile *Index;
  1686. if (Sources->FindIndex(i.File(),Index) == false)
  1687. continue;
  1688. if (debugAuth == true)
  1689. std::cerr << "Checking index: " << Index->Describe()
  1690. << "(Trusted=" << Index->IsTrusted() << ")" << std::endl;
  1691. if (Index->IsTrusted() == true)
  1692. {
  1693. Trusted = true;
  1694. if (allowUnauth == false)
  1695. break;
  1696. }
  1697. else
  1698. seenUntrusted = true;
  1699. }
  1700. // "allow-unauthenticated" restores apts old fetching behaviour
  1701. // that means that e.g. unauthenticated file:// uris are higher
  1702. // priority than authenticated http:// uris
  1703. if (allowUnauth == true && seenUntrusted == true)
  1704. Trusted = false;
  1705. // Select a source
  1706. if (QueueNext() == false && _error->PendingError() == false)
  1707. _error->Error(_("Can't find a source to download version '%s' of '%s'"),
  1708. Version.VerStr(), Version.ParentPkg().FullName(false).c_str());
  1709. }
  1710. /*}}}*/
  1711. // AcqArchive::QueueNext - Queue the next file source /*{{{*/
  1712. // ---------------------------------------------------------------------
  1713. /* This queues the next available file version for download. It checks if
  1714. the archive is already available in the cache and stashs the MD5 for
  1715. checking later. */
  1716. bool pkgAcqArchive::QueueNext()
  1717. {
  1718. string const ForceHash = _config->Find("Acquire::ForceHash");
  1719. for (; Vf.end() == false; ++Vf)
  1720. {
  1721. // Ignore not source sources
  1722. if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
  1723. continue;
  1724. // Try to cross match against the source list
  1725. pkgIndexFile *Index;
  1726. if (Sources->FindIndex(Vf.File(),Index) == false)
  1727. continue;
  1728. // only try to get a trusted package from another source if that source
  1729. // is also trusted
  1730. if(Trusted && !Index->IsTrusted())
  1731. continue;
  1732. // Grab the text package record
  1733. pkgRecords::Parser &Parse = Recs->Lookup(Vf);
  1734. if (_error->PendingError() == true)
  1735. return false;
  1736. string PkgFile = Parse.FileName();
  1737. if (ForceHash.empty() == false)
  1738. {
  1739. if(stringcasecmp(ForceHash, "sha512") == 0)
  1740. ExpectedHash = HashString("SHA512", Parse.SHA512Hash());
  1741. else if(stringcasecmp(ForceHash, "sha256") == 0)
  1742. ExpectedHash = HashString("SHA256", Parse.SHA256Hash());
  1743. else if (stringcasecmp(ForceHash, "sha1") == 0)
  1744. ExpectedHash = HashString("SHA1", Parse.SHA1Hash());
  1745. else
  1746. ExpectedHash = HashString("MD5Sum", Parse.MD5Hash());
  1747. }
  1748. else
  1749. {
  1750. string Hash;
  1751. if ((Hash = Parse.SHA512Hash()).empty() == false)
  1752. ExpectedHash = HashString("SHA512", Hash);
  1753. else if ((Hash = Parse.SHA256Hash()).empty() == false)
  1754. ExpectedHash = HashString("SHA256", Hash);
  1755. else if ((Hash = Parse.SHA1Hash()).empty() == false)
  1756. ExpectedHash = HashString("SHA1", Hash);
  1757. else
  1758. ExpectedHash = HashString("MD5Sum", Parse.MD5Hash());
  1759. }
  1760. if (PkgFile.empty() == true)
  1761. return _error->Error(_("The package index files are corrupted. No Filename: "
  1762. "field for package %s."),
  1763. Version.ParentPkg().Name());
  1764. Desc.URI = Index->ArchiveURI(PkgFile);
  1765. Desc.Description = Index->ArchiveInfo(Version);
  1766. Desc.Owner = this;
  1767. Desc.ShortDesc = Version.ParentPkg().Name();
  1768. // See if we already have the file. (Legacy filenames)
  1769. FileSize = Version->Size;
  1770. string FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(PkgFile);
  1771. struct stat Buf;
  1772. if (stat(FinalFile.c_str(),&Buf) == 0)
  1773. {
  1774. // Make sure the size matches
  1775. if ((unsigned long long)Buf.st_size == Version->Size)
  1776. {
  1777. Complete = true;
  1778. Local = true;
  1779. Status = StatDone;
  1780. StoreFilename = DestFile = FinalFile;
  1781. return true;
  1782. }
  1783. /* Hmm, we have a file and its size does not match, this means it is
  1784. an old style mismatched arch */
  1785. unlink(FinalFile.c_str());
  1786. }
  1787. // Check it again using the new style output filenames
  1788. FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename);
  1789. if (stat(FinalFile.c_str(),&Buf) == 0)
  1790. {
  1791. // Make sure the size matches
  1792. if ((unsigned long long)Buf.st_size == Version->Size)
  1793. {
  1794. Complete = true;
  1795. Local = true;
  1796. Status = StatDone;
  1797. StoreFilename = DestFile = FinalFile;
  1798. return true;
  1799. }
  1800. /* Hmm, we have a file and its size does not match, this shouldnt
  1801. happen.. */
  1802. unlink(FinalFile.c_str());
  1803. }
  1804. DestFile = _config->FindDir("Dir::Cache::Archives") + "partial/" + flNotDir(StoreFilename);
  1805. // Check the destination file
  1806. if (stat(DestFile.c_str(),&Buf) == 0)
  1807. {
  1808. // Hmm, the partial file is too big, erase it
  1809. if ((unsigned long long)Buf.st_size > Version->Size)
  1810. unlink(DestFile.c_str());
  1811. else
  1812. PartialSize = Buf.st_size;
  1813. }
  1814. // Disables download of archives - useful if no real installation follows,
  1815. // e.g. if we are just interested in proposed installation order
  1816. if (_config->FindB("Debug::pkgAcqArchive::NoQueue", false) == true)
  1817. {
  1818. Complete = true;
  1819. Local = true;
  1820. Status = StatDone;
  1821. StoreFilename = DestFile = FinalFile;
  1822. return true;
  1823. }
  1824. // Create the item
  1825. Local = false;
  1826. Desc.URI = Index->ArchiveURI(PkgFile);
  1827. Desc.Description = Index->ArchiveInfo(Version);
  1828. Desc.Owner = this;
  1829. Desc.ShortDesc = Version.ParentPkg().Name();
  1830. QueueURI(Desc);
  1831. ++Vf;
  1832. return true;
  1833. }
  1834. return false;
  1835. }
  1836. /*}}}*/
  1837. // AcqArchive::Done - Finished fetching /*{{{*/
  1838. // ---------------------------------------------------------------------
  1839. /* */
  1840. void pkgAcqArchive::Done(string Message,unsigned long long Size,string CalcHash,
  1841. pkgAcquire::MethodConfig *Cfg)
  1842. {
  1843. Item::Done(Message,Size,CalcHash,Cfg);
  1844. // Check the size
  1845. if (Size != Version->Size)
  1846. {
  1847. RenameOnError(SizeMismatch);
  1848. return;
  1849. }
  1850. // Check the hash
  1851. if(ExpectedHash.toStr() != CalcHash)
  1852. {
  1853. RenameOnError(HashSumMismatch);
  1854. return;
  1855. }
  1856. // Grab the output filename
  1857. string FileName = LookupTag(Message,"Filename");
  1858. if (FileName.empty() == true)
  1859. {
  1860. Status = StatError;
  1861. ErrorText = "Method gave a blank filename";
  1862. return;
  1863. }
  1864. Complete = true;
  1865. // Reference filename
  1866. if (FileName != DestFile)
  1867. {
  1868. StoreFilename = DestFile = FileName;
  1869. Local = true;
  1870. return;
  1871. }
  1872. // Done, move it into position
  1873. string FinalFile = _config->FindDir("Dir::Cache::Archives");
  1874. FinalFile += flNotDir(StoreFilename);
  1875. Rename(DestFile,FinalFile);
  1876. StoreFilename = DestFile = FinalFile;
  1877. Complete = true;
  1878. }
  1879. /*}}}*/
  1880. // AcqArchive::Failed - Failure handler /*{{{*/
  1881. // ---------------------------------------------------------------------
  1882. /* Here we try other sources */
  1883. void pkgAcqArchive::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  1884. {
  1885. ErrorText = LookupTag(Message,"Message");
  1886. /* We don't really want to retry on failed media swaps, this prevents
  1887. that. An interesting observation is that permanent failures are not
  1888. recorded. */
  1889. if (Cnf->Removable == true &&
  1890. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  1891. {
  1892. // Vf = Version.FileList();
  1893. while (Vf.end() == false) ++Vf;
  1894. StoreFilename = string();
  1895. Item::Failed(Message,Cnf);
  1896. return;
  1897. }
  1898. if (QueueNext() == false)
  1899. {
  1900. // This is the retry counter
  1901. if (Retries != 0 &&
  1902. Cnf->LocalOnly == false &&
  1903. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  1904. {
  1905. Retries--;
  1906. Vf = Version.FileList();
  1907. if (QueueNext() == true)
  1908. return;
  1909. }
  1910. StoreFilename = string();
  1911. Item::Failed(Message,Cnf);
  1912. }
  1913. }
  1914. /*}}}*/
  1915. // AcqArchive::IsTrusted - Determine whether this archive comes from a trusted source /*{{{*/
  1916. // ---------------------------------------------------------------------
  1917. bool pkgAcqArchive::IsTrusted()
  1918. {
  1919. return Trusted;
  1920. }
  1921. /*}}}*/
  1922. // AcqArchive::Finished - Fetching has finished, tidy up /*{{{*/
  1923. // ---------------------------------------------------------------------
  1924. /* */
  1925. void pkgAcqArchive::Finished()
  1926. {
  1927. if (Status == pkgAcquire::Item::StatDone &&
  1928. Complete == true)
  1929. return;
  1930. StoreFilename = string();
  1931. }
  1932. /*}}}*/
  1933. // AcqFile::pkgAcqFile - Constructor /*{{{*/
  1934. // ---------------------------------------------------------------------
  1935. /* The file is added to the queue */
  1936. pkgAcqFile::pkgAcqFile(pkgAcquire *Owner,string URI,string Hash,
  1937. unsigned long long Size,string Dsc,string ShortDesc,
  1938. const string &DestDir, const string &DestFilename,
  1939. bool IsIndexFile) :
  1940. Item(Owner), ExpectedHash(Hash), IsIndexFile(IsIndexFile)
  1941. {
  1942. Retries = _config->FindI("Acquire::Retries",0);
  1943. if(!DestFilename.empty())
  1944. DestFile = DestFilename;
  1945. else if(!DestDir.empty())
  1946. DestFile = DestDir + "/" + flNotDir(URI);
  1947. else
  1948. DestFile = flNotDir(URI);
  1949. // Create the item
  1950. Desc.URI = URI;
  1951. Desc.Description = Dsc;
  1952. Desc.Owner = this;
  1953. // Set the short description to the archive component
  1954. Desc.ShortDesc = ShortDesc;
  1955. // Get the transfer sizes
  1956. FileSize = Size;
  1957. struct stat Buf;
  1958. if (stat(DestFile.c_str(),&Buf) == 0)
  1959. {
  1960. // Hmm, the partial file is too big, erase it
  1961. if ((unsigned long long)Buf.st_size > Size)
  1962. unlink(DestFile.c_str());
  1963. else
  1964. PartialSize = Buf.st_size;
  1965. }
  1966. QueueURI(Desc);
  1967. }
  1968. /*}}}*/
  1969. // AcqFile::Done - Item downloaded OK /*{{{*/
  1970. // ---------------------------------------------------------------------
  1971. /* */
  1972. void pkgAcqFile::Done(string Message,unsigned long long Size,string CalcHash,
  1973. pkgAcquire::MethodConfig *Cnf)
  1974. {
  1975. Item::Done(Message,Size,CalcHash,Cnf);
  1976. // Check the hash
  1977. if(!ExpectedHash.empty() && ExpectedHash.toStr() != CalcHash)
  1978. {
  1979. RenameOnError(HashSumMismatch);
  1980. return;
  1981. }
  1982. string FileName = LookupTag(Message,"Filename");
  1983. if (FileName.empty() == true)
  1984. {
  1985. Status = StatError;
  1986. ErrorText = "Method gave a blank filename";
  1987. return;
  1988. }
  1989. Complete = true;
  1990. // The files timestamp matches
  1991. if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  1992. return;
  1993. // We have to copy it into place
  1994. if (FileName != DestFile)
  1995. {
  1996. Local = true;
  1997. if (_config->FindB("Acquire::Source-Symlinks",true) == false ||
  1998. Cnf->Removable == true)
  1999. {
  2000. Desc.URI = "copy:" + FileName;
  2001. QueueURI(Desc);
  2002. return;
  2003. }
  2004. // Erase the file if it is a symlink so we can overwrite it
  2005. struct stat St;
  2006. if (lstat(DestFile.c_str(),&St) == 0)
  2007. {
  2008. if (S_ISLNK(St.st_mode) != 0)
  2009. unlink(DestFile.c_str());
  2010. }
  2011. // Symlink the file
  2012. if (symlink(FileName.c_str(),DestFile.c_str()) != 0)
  2013. {
  2014. ErrorText = "Link to " + DestFile + " failure ";
  2015. Status = StatError;
  2016. Complete = false;
  2017. }
  2018. }
  2019. }
  2020. /*}}}*/
  2021. // AcqFile::Failed - Failure handler /*{{{*/
  2022. // ---------------------------------------------------------------------
  2023. /* Here we try other sources */
  2024. void pkgAcqFile::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  2025. {
  2026. ErrorText = LookupTag(Message,"Message");
  2027. // This is the retry counter
  2028. if (Retries != 0 &&
  2029. Cnf->LocalOnly == false &&
  2030. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  2031. {
  2032. Retries--;
  2033. QueueURI(Desc);
  2034. return;
  2035. }
  2036. Item::Failed(Message,Cnf);
  2037. }
  2038. /*}}}*/
  2039. // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
  2040. // ---------------------------------------------------------------------
  2041. /* The only header we use is the last-modified header. */
  2042. string pkgAcqFile::Custom600Headers()
  2043. {
  2044. if (IsIndexFile)
  2045. return "\nIndex-File: true";
  2046. return "";
  2047. }
  2048. /*}}}*/