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.
 
 
 
 
 
 

1175 lines
38 KiB

  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: writer.cc,v 1.14 2004/03/24 01:40:43 mdz Exp $
  4. /* ######################################################################
  5. Writer
  6. The file writer classes. These write various types of output, sources,
  7. packages and contents.
  8. ##################################################################### */
  9. /*}}}*/
  10. // Include Files /*{{{*/
  11. #include <config.h>
  12. #include <apt-pkg/configuration.h>
  13. #include <apt-pkg/deblistparser.h>
  14. #include <apt-pkg/error.h>
  15. #include <apt-pkg/fileutl.h>
  16. #include <apt-pkg/gpgv.h>
  17. #include <apt-pkg/hashes.h>
  18. #include <apt-pkg/md5.h>
  19. #include <apt-pkg/strutl.h>
  20. #include <apt-pkg/debfile.h>
  21. #include <apt-pkg/pkgcache.h>
  22. #include <apt-pkg/sha1.h>
  23. #include <apt-pkg/sha2.h>
  24. #include <apt-pkg/tagfile.h>
  25. #include <ctype.h>
  26. #include <fnmatch.h>
  27. #include <ftw.h>
  28. #include <locale.h>
  29. #include <string.h>
  30. #include <sys/stat.h>
  31. #include <sys/types.h>
  32. #include <unistd.h>
  33. #include <ctime>
  34. #include <iostream>
  35. #include <iomanip>
  36. #include <sstream>
  37. #include <memory>
  38. #include <utility>
  39. #include <algorithm>
  40. #include "apt-ftparchive.h"
  41. #include "writer.h"
  42. #include "cachedb.h"
  43. #include "multicompress.h"
  44. #include "byhash.h"
  45. #include <apti18n.h>
  46. /*}}}*/
  47. using namespace std;
  48. FTWScanner *FTWScanner::Owner;
  49. // ConfigToDoHashes - which hashes to generate /*{{{*/
  50. static void SingleConfigToDoHashes(unsigned int &DoHashes, std::string const &Conf, unsigned int const Flag)
  51. {
  52. if (_config->FindB(Conf, (DoHashes & Flag) == Flag) == true)
  53. DoHashes |= Flag;
  54. else
  55. DoHashes &= ~Flag;
  56. }
  57. static void ConfigToDoHashes(unsigned int &DoHashes, std::string const &Conf)
  58. {
  59. SingleConfigToDoHashes(DoHashes, Conf + "::MD5", Hashes::MD5SUM);
  60. SingleConfigToDoHashes(DoHashes, Conf + "::SHA1", Hashes::SHA1SUM);
  61. SingleConfigToDoHashes(DoHashes, Conf + "::SHA256", Hashes::SHA256SUM);
  62. SingleConfigToDoHashes(DoHashes, Conf + "::SHA512", Hashes::SHA512SUM);
  63. }
  64. /*}}}*/
  65. // FTWScanner::FTWScanner - Constructor /*{{{*/
  66. FTWScanner::FTWScanner(FileFd * const GivenOutput, string const &Arch, bool const IncludeArchAll)
  67. : Arch(Arch), IncludeArchAll(IncludeArchAll), DoHashes(~0)
  68. {
  69. if (GivenOutput == NULL)
  70. {
  71. Output = new FileFd;
  72. OwnsOutput = true;
  73. Output->OpenDescriptor(STDOUT_FILENO, FileFd::WriteOnly, false);
  74. }
  75. else
  76. {
  77. Output = GivenOutput;
  78. OwnsOutput = false;
  79. }
  80. ErrorPrinted = false;
  81. NoLinkAct = !_config->FindB("APT::FTPArchive::DeLinkAct",true);
  82. ConfigToDoHashes(DoHashes, "APT::FTPArchive");
  83. }
  84. /*}}}*/
  85. FTWScanner::~FTWScanner()
  86. {
  87. if (Output != NULL && OwnsOutput)
  88. delete Output;
  89. }
  90. // FTWScanner::Scanner - FTW Scanner /*{{{*/
  91. // ---------------------------------------------------------------------
  92. /* This is the FTW scanner, it processes each directory element in the
  93. directory tree. */
  94. int FTWScanner::ScannerFTW(const char *File,const struct stat * /*sb*/,int Flag)
  95. {
  96. if (Flag == FTW_DNR)
  97. {
  98. Owner->NewLine(1);
  99. ioprintf(c1out, _("W: Unable to read directory %s\n"), File);
  100. }
  101. if (Flag == FTW_NS)
  102. {
  103. Owner->NewLine(1);
  104. ioprintf(c1out, _("W: Unable to stat %s\n"), File);
  105. }
  106. if (Flag != FTW_F)
  107. return 0;
  108. return ScannerFile(File, true);
  109. }
  110. /*}}}*/
  111. // FTWScanner::ScannerFile - File Scanner /*{{{*/
  112. // ---------------------------------------------------------------------
  113. /* */
  114. int FTWScanner::ScannerFile(const char *File, bool const &ReadLink)
  115. {
  116. const char *LastComponent = strrchr(File, '/');
  117. char *RealPath = NULL;
  118. if (LastComponent == NULL)
  119. LastComponent = File;
  120. else
  121. LastComponent++;
  122. vector<string>::const_iterator I;
  123. for(I = Owner->Patterns.begin(); I != Owner->Patterns.end(); ++I)
  124. {
  125. if (fnmatch((*I).c_str(), LastComponent, 0) == 0)
  126. break;
  127. }
  128. if (I == Owner->Patterns.end())
  129. return 0;
  130. /* Process it. If the file is a link then resolve it into an absolute
  131. name.. This works best if the directory components the scanner are
  132. given are not links themselves. */
  133. char Jnk[2];
  134. Owner->OriginalPath = File;
  135. if (ReadLink &&
  136. readlink(File,Jnk,sizeof(Jnk)) != -1 &&
  137. (RealPath = realpath(File,NULL)) != 0)
  138. {
  139. Owner->DoPackage(RealPath);
  140. free(RealPath);
  141. }
  142. else
  143. Owner->DoPackage(File);
  144. if (_error->empty() == false)
  145. {
  146. // Print any errors or warnings found
  147. string Err;
  148. bool SeenPath = false;
  149. while (_error->empty() == false)
  150. {
  151. Owner->NewLine(1);
  152. bool const Type = _error->PopMessage(Err);
  153. if (Type == true)
  154. cerr << _("E: ") << Err << endl;
  155. else
  156. cerr << _("W: ") << Err << endl;
  157. if (Err.find(File) != string::npos)
  158. SeenPath = true;
  159. }
  160. if (SeenPath == false)
  161. cerr << _("E: Errors apply to file ") << "'" << File << "'" << endl;
  162. return 0;
  163. }
  164. return 0;
  165. }
  166. /*}}}*/
  167. // FTWScanner::RecursiveScan - Just scan a directory tree /*{{{*/
  168. // ---------------------------------------------------------------------
  169. /* */
  170. bool FTWScanner::RecursiveScan(string const &Dir)
  171. {
  172. char *RealPath = NULL;
  173. /* If noprefix is set then jam the scan root in, so we don't generate
  174. link followed paths out of control */
  175. if (InternalPrefix.empty() == true)
  176. {
  177. if ((RealPath = realpath(Dir.c_str(),NULL)) == 0)
  178. return _error->Errno("realpath",_("Failed to resolve %s"),Dir.c_str());
  179. InternalPrefix = RealPath;
  180. free(RealPath);
  181. }
  182. // Do recursive directory searching
  183. Owner = this;
  184. int const Res = ftw(Dir.c_str(),ScannerFTW,30);
  185. // Error treewalking?
  186. if (Res != 0)
  187. {
  188. if (_error->PendingError() == false)
  189. _error->Errno("ftw",_("Tree walking failed"));
  190. return false;
  191. }
  192. return true;
  193. }
  194. /*}}}*/
  195. // FTWScanner::LoadFileList - Load the file list from a file /*{{{*/
  196. // ---------------------------------------------------------------------
  197. /* This is an alternative to using FTW to locate files, it reads the list
  198. of files from another file. */
  199. bool FTWScanner::LoadFileList(string const &Dir, string const &File)
  200. {
  201. char *RealPath = NULL;
  202. /* If noprefix is set then jam the scan root in, so we don't generate
  203. link followed paths out of control */
  204. if (InternalPrefix.empty() == true)
  205. {
  206. if ((RealPath = realpath(Dir.c_str(),NULL)) == 0)
  207. return _error->Errno("realpath",_("Failed to resolve %s"),Dir.c_str());
  208. InternalPrefix = RealPath;
  209. free(RealPath);
  210. }
  211. Owner = this;
  212. FILE *List = fopen(File.c_str(),"r");
  213. if (List == 0)
  214. return _error->Errno("fopen",_("Failed to open %s"),File.c_str());
  215. /* We are a tad tricky here.. We prefix the buffer with the directory
  216. name, that way if we need a full path with just use line.. Sneaky and
  217. fully evil. */
  218. char Line[1000];
  219. char *FileStart;
  220. if (Dir.empty() == true || Dir.end()[-1] != '/')
  221. FileStart = Line + snprintf(Line,sizeof(Line),"%s/",Dir.c_str());
  222. else
  223. FileStart = Line + snprintf(Line,sizeof(Line),"%s",Dir.c_str());
  224. while (fgets(FileStart,sizeof(Line) - (FileStart - Line),List) != 0)
  225. {
  226. char *FileName = _strstrip(FileStart);
  227. if (FileName[0] == 0)
  228. continue;
  229. if (FileName[0] != '/')
  230. {
  231. if (FileName != FileStart)
  232. memmove(FileStart,FileName,strlen(FileStart));
  233. FileName = Line;
  234. }
  235. #if 0
  236. struct stat St;
  237. int Flag = FTW_F;
  238. if (stat(FileName,&St) != 0)
  239. Flag = FTW_NS;
  240. #endif
  241. if (ScannerFile(FileName, false) != 0)
  242. break;
  243. }
  244. fclose(List);
  245. return true;
  246. }
  247. /*}}}*/
  248. // FTWScanner::Delink - Delink symlinks /*{{{*/
  249. // ---------------------------------------------------------------------
  250. /* */
  251. bool FTWScanner::Delink(string &FileName,const char *OriginalPath,
  252. unsigned long long &DeLinkBytes,
  253. unsigned long long const &FileSize)
  254. {
  255. // See if this isn't an internaly prefix'd file name.
  256. if (InternalPrefix.empty() == false &&
  257. InternalPrefix.length() < FileName.length() &&
  258. stringcmp(FileName.begin(),FileName.begin() + InternalPrefix.length(),
  259. InternalPrefix.begin(),InternalPrefix.end()) != 0)
  260. {
  261. if (DeLinkLimit != 0 && DeLinkBytes/1024 < DeLinkLimit)
  262. {
  263. // Tidy up the display
  264. if (DeLinkBytes == 0)
  265. cout << endl;
  266. NewLine(1);
  267. ioprintf(c1out, _(" DeLink %s [%s]\n"), (OriginalPath + InternalPrefix.length()),
  268. SizeToStr(FileSize).c_str());
  269. c1out << flush;
  270. if (NoLinkAct == false)
  271. {
  272. char OldLink[400];
  273. if (readlink(OriginalPath,OldLink,sizeof(OldLink)) == -1)
  274. _error->Errno("readlink",_("Failed to readlink %s"),OriginalPath);
  275. else
  276. {
  277. if (RemoveFile("FTWScanner::Delink", OriginalPath))
  278. {
  279. if (link(FileName.c_str(),OriginalPath) != 0)
  280. {
  281. // Panic! Restore the symlink
  282. if (symlink(OldLink,OriginalPath) != 0)
  283. _error->Errno("symlink", "failed to restore symlink");
  284. return _error->Errno("link",_("*** Failed to link %s to %s"),
  285. FileName.c_str(),
  286. OriginalPath);
  287. }
  288. }
  289. }
  290. }
  291. DeLinkBytes += FileSize;
  292. if (DeLinkBytes/1024 >= DeLinkLimit)
  293. ioprintf(c1out, _(" DeLink limit of %sB hit.\n"), SizeToStr(DeLinkBytes).c_str());
  294. }
  295. FileName = OriginalPath;
  296. }
  297. return true;
  298. }
  299. /*}}}*/
  300. // FTWScanner::SetExts - Set extensions to support /*{{{*/
  301. // ---------------------------------------------------------------------
  302. /* */
  303. bool FTWScanner::SetExts(string const &Vals)
  304. {
  305. ClearPatterns();
  306. string::size_type Start = 0;
  307. while (Start <= Vals.length()-1)
  308. {
  309. string::size_type const Space = Vals.find(' ',Start);
  310. string::size_type const Length = ((Space == string::npos) ? Vals.length() : Space) - Start;
  311. if ( Arch.empty() == false )
  312. {
  313. AddPattern(string("*_") + Arch + Vals.substr(Start, Length));
  314. if (IncludeArchAll == true && Arch != "all")
  315. AddPattern(string("*_all") + Vals.substr(Start, Length));
  316. }
  317. else
  318. AddPattern(string("*") + Vals.substr(Start, Length));
  319. Start += Length + 1;
  320. }
  321. return true;
  322. }
  323. /*}}}*/
  324. // PackagesWriter::PackagesWriter - Constructor /*{{{*/
  325. // ---------------------------------------------------------------------
  326. /* */
  327. PackagesWriter::PackagesWriter(FileFd * const GivenOutput, TranslationWriter * const transWriter,
  328. string const &DB,string const &Overrides,string const &ExtOverrides,
  329. string const &Arch, bool const IncludeArchAll) :
  330. FTWScanner(GivenOutput, Arch, IncludeArchAll), Db(DB), Stats(Db.Stats), TransWriter(transWriter)
  331. {
  332. SetExts(".deb .udeb");
  333. DeLinkLimit = 0;
  334. // Process the command line options
  335. ConfigToDoHashes(DoHashes, "APT::FTPArchive::Packages");
  336. DoAlwaysStat = _config->FindB("APT::FTPArchive::AlwaysStat", false);
  337. DoContents = _config->FindB("APT::FTPArchive::Contents",true);
  338. NoOverride = _config->FindB("APT::FTPArchive::NoOverrideMsg",false);
  339. LongDescription = _config->FindB("APT::FTPArchive::LongDescription",true);
  340. if (Db.Loaded() == false)
  341. DoContents = false;
  342. // Read the override file
  343. if (Overrides.empty() == false && Over.ReadOverride(Overrides) == false)
  344. return;
  345. else
  346. NoOverride = true;
  347. if (ExtOverrides.empty() == false)
  348. Over.ReadExtraOverride(ExtOverrides);
  349. _error->DumpErrors();
  350. }
  351. /*}}}*/
  352. // PackagesWriter::DoPackage - Process a single package /*{{{*/
  353. // ---------------------------------------------------------------------
  354. /* This method takes a package and gets its control information and
  355. MD5, SHA1 and SHA256 then writes out a control record with the proper fields
  356. rewritten and the path/size/hash appended. */
  357. bool PackagesWriter::DoPackage(string FileName)
  358. {
  359. // Pull all the data we need form the DB
  360. if (Db.GetFileInfo(FileName,
  361. true, /* DoControl */
  362. DoContents,
  363. true, /* GenContentsOnly */
  364. false, /* DoSource */
  365. DoHashes, DoAlwaysStat) == false)
  366. {
  367. return false;
  368. }
  369. unsigned long long FileSize = Db.GetFileSize();
  370. if (Delink(FileName,OriginalPath,Stats.DeLinkBytes,FileSize) == false)
  371. return false;
  372. // Lookup the overide information
  373. pkgTagSection &Tags = Db.Control.Section;
  374. string Package = Tags.FindS("Package");
  375. string Architecture;
  376. // if we generate a Packages file for a given arch, we use it to
  377. // look for overrides. if we run in "simple" mode without the
  378. // "Architecures" variable in the config we use the architecure value
  379. // from the deb file
  380. if(Arch != "")
  381. Architecture = Arch;
  382. else
  383. Architecture = Tags.FindS("Architecture");
  384. unique_ptr<Override::Item> OverItem(Over.GetItem(Package,Architecture));
  385. if (Package.empty() == true)
  386. return _error->Error(_("Archive had no package field"));
  387. // If we need to do any rewriting of the header do it now..
  388. if (OverItem.get() == 0)
  389. {
  390. if (NoOverride == false)
  391. {
  392. NewLine(1);
  393. ioprintf(c1out, _(" %s has no override entry\n"), Package.c_str());
  394. }
  395. OverItem = unique_ptr<Override::Item>(new Override::Item);
  396. OverItem->FieldOverride["Section"] = Tags.FindS("Section");
  397. OverItem->Priority = Tags.FindS("Priority");
  398. }
  399. // Strip the DirStrip prefix from the FileName and add the PathPrefix
  400. string NewFileName;
  401. if (DirStrip.empty() == false &&
  402. FileName.length() > DirStrip.length() &&
  403. stringcmp(FileName.begin(),FileName.begin() + DirStrip.length(),
  404. DirStrip.begin(),DirStrip.end()) == 0)
  405. NewFileName = string(FileName.begin() + DirStrip.length(),FileName.end());
  406. else
  407. NewFileName = FileName;
  408. if (PathPrefix.empty() == false)
  409. NewFileName = flCombine(PathPrefix,NewFileName);
  410. /* Configuration says we don't want to include the long Description
  411. in the package file - instead we want to ship a separated file */
  412. string desc;
  413. if (LongDescription == false) {
  414. desc = Tags.FindS("Description").append("\n");
  415. OverItem->FieldOverride["Description"] = desc.substr(0, desc.find('\n')).c_str();
  416. }
  417. // This lists all the changes to the fields we are going to make.
  418. std::vector<pkgTagSection::Tag> Changes;
  419. std::string Size;
  420. strprintf(Size, "%llu", (unsigned long long) FileSize);
  421. Changes.push_back(pkgTagSection::Tag::Rewrite("Size", Size));
  422. for (HashStringList::const_iterator hs = Db.HashesList.begin(); hs != Db.HashesList.end(); ++hs)
  423. {
  424. if (hs->HashType() == "MD5Sum")
  425. Changes.push_back(pkgTagSection::Tag::Rewrite("MD5sum", hs->HashValue()));
  426. else if (hs->HashType() == "Checksum-FileSize")
  427. continue;
  428. else
  429. Changes.push_back(pkgTagSection::Tag::Rewrite(hs->HashType(), hs->HashValue()));
  430. }
  431. Changes.push_back(pkgTagSection::Tag::Rewrite("Filename", NewFileName));
  432. Changes.push_back(pkgTagSection::Tag::Rewrite("Priority", OverItem->Priority));
  433. Changes.push_back(pkgTagSection::Tag::Remove("Status"));
  434. Changes.push_back(pkgTagSection::Tag::Remove("Optional"));
  435. string DescriptionMd5;
  436. if (LongDescription == false) {
  437. MD5Summation descmd5;
  438. descmd5.Add(desc.c_str());
  439. DescriptionMd5 = descmd5.Result().Value();
  440. Changes.push_back(pkgTagSection::Tag::Rewrite("Description-md5", DescriptionMd5));
  441. if (TransWriter != NULL)
  442. TransWriter->DoPackage(Package, desc, DescriptionMd5);
  443. }
  444. // Rewrite the maintainer field if necessary
  445. bool MaintFailed;
  446. string NewMaint = OverItem->SwapMaint(Tags.FindS("Maintainer"),MaintFailed);
  447. if (MaintFailed == true)
  448. {
  449. if (NoOverride == false)
  450. {
  451. NewLine(1);
  452. ioprintf(c1out, _(" %s maintainer is %s not %s\n"),
  453. Package.c_str(), Tags.FindS("Maintainer").c_str(), OverItem->OldMaint.c_str());
  454. }
  455. }
  456. if (NewMaint.empty() == false)
  457. Changes.push_back(pkgTagSection::Tag::Rewrite("Maintainer", NewMaint));
  458. /* Get rid of the Optional tag. This is an ugly, ugly, ugly hack that
  459. dpkg-scanpackages does. Well sort of. dpkg-scanpackages just does renaming
  460. but dpkg does this append bit. So we do the append bit, at least that way the
  461. status file and package file will remain similar. There are other transforms
  462. but optional is the only legacy one still in use for some lazy reason. */
  463. string OptionalStr = Tags.FindS("Optional");
  464. if (OptionalStr.empty() == false)
  465. {
  466. if (Tags.FindS("Suggests").empty() == false)
  467. OptionalStr = Tags.FindS("Suggests") + ", " + OptionalStr;
  468. Changes.push_back(pkgTagSection::Tag::Rewrite("Suggests", OptionalStr));
  469. }
  470. for (map<string,string>::const_iterator I = OverItem->FieldOverride.begin();
  471. I != OverItem->FieldOverride.end(); ++I)
  472. Changes.push_back(pkgTagSection::Tag::Rewrite(I->first, I->second));
  473. // Rewrite and store the fields.
  474. if (Tags.Write(*Output, TFRewritePackageOrder, Changes) == false ||
  475. Output->Write("\n", 1) == false)
  476. return false;
  477. return Db.Finish();
  478. }
  479. /*}}}*/
  480. PackagesWriter::~PackagesWriter() /*{{{*/
  481. {
  482. }
  483. /*}}}*/
  484. // TranslationWriter::TranslationWriter - Constructor /*{{{*/
  485. // ---------------------------------------------------------------------
  486. /* Create a Translation-Master file for this Packages file */
  487. TranslationWriter::TranslationWriter(string const &File, string const &TransCompress,
  488. mode_t const &Permissions) : Comp(NULL), Output(NULL)
  489. {
  490. if (File.empty() == true)
  491. return;
  492. Comp = new MultiCompress(File, TransCompress, Permissions);
  493. Output = &Comp->Input;
  494. }
  495. /*}}}*/
  496. // TranslationWriter::DoPackage - Process a single package /*{{{*/
  497. // ---------------------------------------------------------------------
  498. /* Create a Translation-Master file for this Packages file */
  499. bool TranslationWriter::DoPackage(string const &Pkg, string const &Desc,
  500. string const &MD5)
  501. {
  502. if (Output == NULL)
  503. return true;
  504. // Different archs can include different versions and therefore
  505. // different descriptions - so we need to check for both name and md5.
  506. string const Record = Pkg + ":" + MD5;
  507. if (Included.find(Record) != Included.end())
  508. return true;
  509. std::string out;
  510. strprintf(out, "Package: %s\nDescription-md5: %s\nDescription-en: %s\n",
  511. Pkg.c_str(), MD5.c_str(), Desc.c_str());
  512. Output->Write(out.c_str(), out.length());
  513. Included.insert(Record);
  514. return true;
  515. }
  516. /*}}}*/
  517. // TranslationWriter::~TranslationWriter - Destructor /*{{{*/
  518. // ---------------------------------------------------------------------
  519. /* */
  520. TranslationWriter::~TranslationWriter()
  521. {
  522. if (Comp != NULL)
  523. delete Comp;
  524. }
  525. /*}}}*/
  526. // SourcesWriter::SourcesWriter - Constructor /*{{{*/
  527. // ---------------------------------------------------------------------
  528. /* */
  529. SourcesWriter::SourcesWriter(FileFd * const GivenOutput, string const &DB, string const &BOverrides,string const &SOverrides,
  530. string const &ExtOverrides) :
  531. FTWScanner(GivenOutput), Db(DB), Stats(Db.Stats)
  532. {
  533. AddPattern("*.dsc");
  534. DeLinkLimit = 0;
  535. Buffer = 0;
  536. BufSize = 0;
  537. // Process the command line options
  538. ConfigToDoHashes(DoHashes, "APT::FTPArchive::Sources");
  539. NoOverride = _config->FindB("APT::FTPArchive::NoOverrideMsg",false);
  540. DoAlwaysStat = _config->FindB("APT::FTPArchive::AlwaysStat", false);
  541. // Read the override file
  542. if (BOverrides.empty() == false && BOver.ReadOverride(BOverrides) == false)
  543. return;
  544. else
  545. NoOverride = true;
  546. // WTF?? The logic above: if we can't read binary overrides, don't even try
  547. // reading source overrides. if we can read binary overrides, then say there
  548. // are no overrides. THIS MAKES NO SENSE! -- ajt@d.o, 2006/02/28
  549. if (ExtOverrides.empty() == false)
  550. SOver.ReadExtraOverride(ExtOverrides);
  551. if (SOverrides.empty() == false && FileExists(SOverrides) == true)
  552. SOver.ReadOverride(SOverrides,true);
  553. }
  554. /*}}}*/
  555. // SourcesWriter::DoPackage - Process a single package /*{{{*/
  556. static std::string getDscHash(unsigned int const DoHashes,
  557. Hashes::SupportedHashes const DoIt, pkgTagSection &Tags, char const * const FieldName,
  558. HashString const * const Hash, unsigned long long Size, std::string const &FileName)
  559. {
  560. if ((DoHashes & DoIt) != DoIt || Tags.Exists(FieldName) == false || Hash == NULL)
  561. return "";
  562. std::ostringstream out;
  563. out << "\n " << Hash->HashValue() << " " << std::to_string(Size) << " " << FileName
  564. << "\n " << Tags.FindS(FieldName);
  565. return out.str();
  566. }
  567. bool SourcesWriter::DoPackage(string FileName)
  568. {
  569. // Pull all the data we need form the DB
  570. if (Db.GetFileInfo(FileName,
  571. false, /* DoControl */
  572. false, /* DoContents */
  573. false, /* GenContentsOnly */
  574. true, /* DoSource */
  575. DoHashes, DoAlwaysStat) == false)
  576. {
  577. return false;
  578. }
  579. // we need to perform a "write" here (this is what finish is doing)
  580. // because the call to Db.GetFileInfo() in the loop will change
  581. // the "db cursor"
  582. Db.Finish();
  583. pkgTagSection Tags;
  584. if (Tags.Scan(Db.Dsc.Data.c_str(), Db.Dsc.Data.length()) == false)
  585. return _error->Error("Could not find a record in the DSC '%s'",FileName.c_str());
  586. if (Tags.Exists("Source") == false)
  587. return _error->Error("Could not find a Source entry in the DSC '%s'",FileName.c_str());
  588. Tags.Trim();
  589. // Lookup the overide information, finding first the best priority.
  590. string BestPrio;
  591. string Bins = Tags.FindS("Binary");
  592. char Buffer[Bins.length() + 1];
  593. unique_ptr<Override::Item> OverItem(nullptr);
  594. if (Bins.empty() == false)
  595. {
  596. strcpy(Buffer,Bins.c_str());
  597. // Ignore too-long errors.
  598. char *BinList[400];
  599. TokSplitString(',',Buffer,BinList,sizeof(BinList)/sizeof(BinList[0]));
  600. // Look at all the binaries
  601. unsigned char BestPrioV = pkgCache::State::Extra;
  602. for (unsigned I = 0; BinList[I] != 0; I++)
  603. {
  604. unique_ptr<Override::Item> Itm(BOver.GetItem(BinList[I]));
  605. if (Itm.get() == 0)
  606. continue;
  607. unsigned char NewPrioV = debListParser::GetPrio(Itm->Priority);
  608. if (NewPrioV < BestPrioV || BestPrio.empty() == true)
  609. {
  610. BestPrioV = NewPrioV;
  611. BestPrio = Itm->Priority;
  612. }
  613. if (OverItem.get() == 0)
  614. OverItem = std::move(Itm);
  615. }
  616. }
  617. // If we need to do any rewriting of the header do it now..
  618. if (OverItem.get() == 0)
  619. {
  620. if (NoOverride == false)
  621. {
  622. NewLine(1);
  623. ioprintf(c1out, _(" %s has no override entry\n"), Tags.FindS("Source").c_str());
  624. }
  625. OverItem.reset(new Override::Item);
  626. }
  627. struct stat St;
  628. if (stat(FileName.c_str(), &St) != 0)
  629. return _error->Errno("fstat","Failed to stat %s",FileName.c_str());
  630. unique_ptr<Override::Item> SOverItem(SOver.GetItem(Tags.FindS("Source")));
  631. // const unique_ptr<Override::Item> autoSOverItem(SOverItem);
  632. if (SOverItem.get() == 0)
  633. {
  634. ioprintf(c1out, _(" %s has no source override entry\n"), Tags.FindS("Source").c_str());
  635. SOverItem = unique_ptr<Override::Item>(BOver.GetItem(Tags.FindS("Source")));
  636. if (SOverItem.get() == 0)
  637. {
  638. ioprintf(c1out, _(" %s has no binary override entry either\n"), Tags.FindS("Source").c_str());
  639. SOverItem = unique_ptr<Override::Item>(new Override::Item);
  640. *SOverItem = *OverItem;
  641. }
  642. }
  643. // Add the dsc to the files hash list
  644. string const strippedName = flNotDir(FileName);
  645. std::string const Files = getDscHash(DoHashes, Hashes::MD5SUM, Tags, "Files", Db.HashesList.find("MD5Sum"), St.st_size, strippedName);
  646. std::string ChecksumsSha1 = getDscHash(DoHashes, Hashes::SHA1SUM, Tags, "Checksums-Sha1", Db.HashesList.find("SHA1"), St.st_size, strippedName);
  647. std::string ChecksumsSha256 = getDscHash(DoHashes, Hashes::SHA256SUM, Tags, "Checksums-Sha256", Db.HashesList.find("SHA256"), St.st_size, strippedName);
  648. std::string ChecksumsSha512 = getDscHash(DoHashes, Hashes::SHA512SUM, Tags, "Checksums-Sha512", Db.HashesList.find("SHA512"), St.st_size, strippedName);
  649. // Strip the DirStrip prefix from the FileName and add the PathPrefix
  650. string NewFileName;
  651. if (DirStrip.empty() == false &&
  652. FileName.length() > DirStrip.length() &&
  653. stringcmp(DirStrip,OriginalPath,OriginalPath + DirStrip.length()) == 0)
  654. NewFileName = string(OriginalPath + DirStrip.length());
  655. else
  656. NewFileName = OriginalPath;
  657. if (PathPrefix.empty() == false)
  658. NewFileName = flCombine(PathPrefix,NewFileName);
  659. string Directory = flNotFile(OriginalPath);
  660. string Package = Tags.FindS("Source");
  661. // Perform operation over all of the files
  662. string ParseJnk;
  663. const char *C = Files.c_str();
  664. char *RealPath = NULL;
  665. for (;isspace(*C); C++);
  666. while (*C != 0)
  667. {
  668. // Parse each of the elements
  669. if (ParseQuoteWord(C,ParseJnk) == false ||
  670. ParseQuoteWord(C,ParseJnk) == false ||
  671. ParseQuoteWord(C,ParseJnk) == false)
  672. return _error->Error("Error parsing file record");
  673. string OriginalPath = Directory + ParseJnk;
  674. // Add missing hashes to source files
  675. if (((DoHashes & Hashes::SHA1SUM) == Hashes::SHA1SUM && !Tags.Exists("Checksums-Sha1")) ||
  676. ((DoHashes & Hashes::SHA256SUM) == Hashes::SHA256SUM && !Tags.Exists("Checksums-Sha256")) ||
  677. ((DoHashes & Hashes::SHA512SUM) == Hashes::SHA512SUM && !Tags.Exists("Checksums-Sha512")))
  678. {
  679. if (Db.GetFileInfo(OriginalPath,
  680. false, /* DoControl */
  681. false, /* DoContents */
  682. false, /* GenContentsOnly */
  683. false, /* DoSource */
  684. DoHashes,
  685. DoAlwaysStat) == false)
  686. {
  687. return _error->Error("Error getting file info");
  688. }
  689. for (HashStringList::const_iterator hs = Db.HashesList.begin(); hs != Db.HashesList.end(); ++hs)
  690. {
  691. if (hs->HashType() == "MD5Sum" || hs->HashType() == "Checksum-FileSize")
  692. continue;
  693. char const * fieldname;
  694. std::string * out;
  695. if (hs->HashType() == "SHA1")
  696. {
  697. fieldname = "Checksums-Sha1";
  698. out = &ChecksumsSha1;
  699. }
  700. else if (hs->HashType() == "SHA256")
  701. {
  702. fieldname = "Checksums-Sha256";
  703. out = &ChecksumsSha256;
  704. }
  705. else if (hs->HashType() == "SHA512")
  706. {
  707. fieldname = "Checksums-Sha512";
  708. out = &ChecksumsSha512;
  709. }
  710. else
  711. {
  712. _error->Warning("Ignoring unknown Checksumtype %s in SourcesWriter::DoPackages", hs->HashType().c_str());
  713. continue;
  714. }
  715. if (Tags.Exists(fieldname) == true)
  716. continue;
  717. std::ostringstream streamout;
  718. streamout << "\n " << hs->HashValue() << " " << std::to_string(Db.GetFileSize()) << " " << ParseJnk;
  719. out->append(streamout.str());
  720. }
  721. // write back the GetFileInfo() stats data
  722. Db.Finish();
  723. }
  724. // Perform the delinking operation
  725. char Jnk[2];
  726. if (readlink(OriginalPath.c_str(),Jnk,sizeof(Jnk)) != -1 &&
  727. (RealPath = realpath(OriginalPath.c_str(),NULL)) != 0)
  728. {
  729. string RP = RealPath;
  730. free(RealPath);
  731. if (Delink(RP,OriginalPath.c_str(),Stats.DeLinkBytes,St.st_size) == false)
  732. return false;
  733. }
  734. }
  735. Directory = flNotFile(NewFileName);
  736. if (Directory.length() > 2)
  737. Directory.erase(Directory.end()-1);
  738. // This lists all the changes to the fields we are going to make.
  739. // (5 hardcoded + checksums + maintainer + end marker)
  740. std::vector<pkgTagSection::Tag> Changes;
  741. Changes.push_back(pkgTagSection::Tag::Remove("Source"));
  742. Changes.push_back(pkgTagSection::Tag::Rewrite("Package", Package));
  743. if (Files.empty() == false)
  744. Changes.push_back(pkgTagSection::Tag::Rewrite("Files", Files));
  745. if (ChecksumsSha1.empty() == false)
  746. Changes.push_back(pkgTagSection::Tag::Rewrite("Checksums-Sha1", ChecksumsSha1));
  747. if (ChecksumsSha256.empty() == false)
  748. Changes.push_back(pkgTagSection::Tag::Rewrite("Checksums-Sha256", ChecksumsSha256));
  749. if (ChecksumsSha512.empty() == false)
  750. Changes.push_back(pkgTagSection::Tag::Rewrite("Checksums-Sha512", ChecksumsSha512));
  751. if (Directory != "./")
  752. Changes.push_back(pkgTagSection::Tag::Rewrite("Directory", Directory));
  753. Changes.push_back(pkgTagSection::Tag::Rewrite("Priority", BestPrio));
  754. Changes.push_back(pkgTagSection::Tag::Remove("Status"));
  755. // Rewrite the maintainer field if necessary
  756. bool MaintFailed;
  757. string NewMaint = OverItem->SwapMaint(Tags.FindS("Maintainer"), MaintFailed);
  758. if (MaintFailed == true)
  759. {
  760. if (NoOverride == false)
  761. {
  762. NewLine(1);
  763. ioprintf(c1out, _(" %s maintainer is %s not %s\n"), Package.c_str(),
  764. Tags.FindS("Maintainer").c_str(), OverItem->OldMaint.c_str());
  765. }
  766. }
  767. if (NewMaint.empty() == false)
  768. Changes.push_back(pkgTagSection::Tag::Rewrite("Maintainer", NewMaint.c_str()));
  769. for (map<string,string>::const_iterator I = SOverItem->FieldOverride.begin();
  770. I != SOverItem->FieldOverride.end(); ++I)
  771. Changes.push_back(pkgTagSection::Tag::Rewrite(I->first, I->second));
  772. // Rewrite and store the fields.
  773. if (Tags.Write(*Output, TFRewriteSourceOrder, Changes) == false ||
  774. Output->Write("\n", 1) == false)
  775. return false;
  776. Stats.Packages++;
  777. return true;
  778. }
  779. /*}}}*/
  780. // ContentsWriter::ContentsWriter - Constructor /*{{{*/
  781. // ---------------------------------------------------------------------
  782. /* */
  783. ContentsWriter::ContentsWriter(FileFd * const GivenOutput, string const &DB,
  784. string const &Arch, bool const IncludeArchAll) :
  785. FTWScanner(GivenOutput, Arch, IncludeArchAll), Db(DB), Stats(Db.Stats)
  786. {
  787. SetExts(".deb");
  788. }
  789. /*}}}*/
  790. // ContentsWriter::DoPackage - Process a single package /*{{{*/
  791. // ---------------------------------------------------------------------
  792. /* If Package is the empty string the control record will be parsed to
  793. determine what the package name is. */
  794. bool ContentsWriter::DoPackage(string FileName, string Package)
  795. {
  796. if (!Db.GetFileInfo(FileName,
  797. Package.empty(), /* DoControl */
  798. true, /* DoContents */
  799. false, /* GenContentsOnly */
  800. false, /* DoSource */
  801. 0, /* DoHashes */
  802. false /* checkMtime */))
  803. {
  804. return false;
  805. }
  806. // Parse the package name
  807. if (Package.empty() == true)
  808. {
  809. Package = Db.Control.Section.FindS("Package");
  810. }
  811. Db.Contents.Add(Gen,Package);
  812. return Db.Finish();
  813. }
  814. /*}}}*/
  815. // ContentsWriter::ReadFromPkgs - Read from a packages file /*{{{*/
  816. // ---------------------------------------------------------------------
  817. /* */
  818. bool ContentsWriter::ReadFromPkgs(string const &PkgFile,string const &PkgCompress)
  819. {
  820. MultiCompress Pkgs(PkgFile,PkgCompress,0,false);
  821. if (_error->PendingError() == true)
  822. return false;
  823. // Open the package file
  824. FileFd Fd;
  825. if (Pkgs.OpenOld(Fd) == false)
  826. return false;
  827. pkgTagFile Tags(&Fd);
  828. if (_error->PendingError() == true)
  829. return false;
  830. // Parse.
  831. pkgTagSection Section;
  832. while (Tags.Step(Section) == true)
  833. {
  834. string File = flCombine(Prefix,Section.FindS("FileName"));
  835. string Package = Section.FindS("Section");
  836. if (Package.empty() == false && Package.end()[-1] != '/')
  837. {
  838. Package += '/';
  839. Package += Section.FindS("Package");
  840. }
  841. else
  842. Package += Section.FindS("Package");
  843. DoPackage(File,Package);
  844. if (_error->empty() == false)
  845. {
  846. _error->Error("Errors apply to file '%s'",File.c_str());
  847. _error->DumpErrors();
  848. }
  849. }
  850. // Tidy the compressor
  851. Fd.Close();
  852. return true;
  853. }
  854. /*}}}*/
  855. // ReleaseWriter::ReleaseWriter - Constructor /*{{{*/
  856. // ---------------------------------------------------------------------
  857. /* */
  858. static std::string formatUTCDateTime(time_t const now)
  859. {
  860. bool const NumericTimezone = _config->FindB("APT::FTPArchive::Release::NumericTimezone", true);
  861. // TimeRFC1123 uses GMT to satisfy HTTP/1.1
  862. std::string datetime = TimeRFC1123(now, NumericTimezone);
  863. if (NumericTimezone == false)
  864. {
  865. auto const lastspace = datetime.rfind(' ');
  866. if (likely(lastspace != std::string::npos))
  867. datetime.replace(lastspace + 1, 3, "UTC");
  868. }
  869. return datetime;
  870. }
  871. ReleaseWriter::ReleaseWriter(FileFd * const GivenOutput, string const &/*DB*/) : FTWScanner(GivenOutput)
  872. {
  873. if (_config->FindB("APT::FTPArchive::Release::Default-Patterns", true) == true)
  874. {
  875. AddPattern("Packages");
  876. AddPattern("Packages.*");
  877. AddPattern("Translation-*");
  878. AddPattern("Sources");
  879. AddPattern("Sources.*");
  880. AddPattern("Release");
  881. AddPattern("Contents-*");
  882. AddPattern("Index");
  883. AddPattern("Index.*");
  884. AddPattern("icons-*.tar");
  885. AddPattern("icons-*.tar.*");
  886. AddPattern("Components-*.yml");
  887. AddPattern("Components-*.yml.*");
  888. AddPattern("md5sum.txt");
  889. }
  890. AddPatterns(_config->FindVector("APT::FTPArchive::Release::Patterns"));
  891. time_t const now = time(NULL);
  892. time_t const validuntil = now + _config->FindI("APT::FTPArchive::Release::ValidTime", 0);
  893. map<string,string> Fields;
  894. Fields["Origin"] = "";
  895. Fields["Label"] = "";
  896. Fields["Suite"] = "";
  897. Fields["Version"] = "";
  898. Fields["Codename"] = "";
  899. Fields["Date"] = formatUTCDateTime(now);
  900. if (validuntil != now)
  901. Fields["Valid-Until"] = formatUTCDateTime(validuntil);
  902. Fields["Architectures"] = "";
  903. Fields["Components"] = "";
  904. Fields["Description"] = "";
  905. Fields["Signed-By"] = "";
  906. if (_config->FindB("APT::FTPArchive::DoByHash", false) == true)
  907. Fields["Acquire-By-Hash"] = "true";
  908. for(map<string,string>::const_iterator I = Fields.begin();
  909. I != Fields.end();
  910. ++I)
  911. {
  912. string Config = string("APT::FTPArchive::Release::") + (*I).first;
  913. string Value = _config->Find(Config, (*I).second.c_str());
  914. if (Value == "")
  915. continue;
  916. std::string const out = I->first + ": " + Value + "\n";
  917. Output->Write(out.c_str(), out.length());
  918. }
  919. ConfigToDoHashes(DoHashes, "APT::FTPArchive::Release");
  920. }
  921. /*}}}*/
  922. // ReleaseWriter::DoPackage - Process a single package /*{{{*/
  923. // ---------------------------------------------------------------------
  924. bool ReleaseWriter::DoPackage(string FileName)
  925. {
  926. // Strip the DirStrip prefix from the FileName and add the PathPrefix
  927. string NewFileName;
  928. if (DirStrip.empty() == false &&
  929. FileName.length() > DirStrip.length() &&
  930. stringcmp(FileName.begin(),FileName.begin() + DirStrip.length(),
  931. DirStrip.begin(),DirStrip.end()) == 0)
  932. {
  933. NewFileName = string(FileName.begin() + DirStrip.length(),FileName.end());
  934. while (NewFileName[0] == '/')
  935. NewFileName = string(NewFileName.begin() + 1,NewFileName.end());
  936. }
  937. else
  938. NewFileName = FileName;
  939. if (PathPrefix.empty() == false)
  940. NewFileName = flCombine(PathPrefix,NewFileName);
  941. FileFd fd(FileName, FileFd::ReadOnly);
  942. if (!fd.IsOpen())
  943. {
  944. return false;
  945. }
  946. CheckSums[NewFileName].size = fd.Size();
  947. Hashes hs(DoHashes);
  948. hs.AddFD(fd);
  949. CheckSums[NewFileName].Hashes = hs.GetHashStringList();
  950. fd.Close();
  951. // FIXME: wrong layer in the code(?)
  952. // FIXME2: symlink instead of create a copy
  953. if (_config->FindB("APT::FTPArchive::DoByHash", false) == true)
  954. {
  955. std::string Input = FileName;
  956. HashStringList hsl = hs.GetHashStringList();
  957. for(HashStringList::const_iterator h = hsl.begin();
  958. h != hsl.end(); ++h)
  959. {
  960. if (!h->usable())
  961. continue;
  962. if (flNotDir(FileName) == "Release" || flNotDir(FileName) == "InRelease")
  963. continue;
  964. std::string ByHashOutputFile = GenByHashFilename(Input, *h);
  965. std::string ByHashOutputDir = flNotFile(ByHashOutputFile);
  966. if(!CreateDirectory(flNotFile(Input), ByHashOutputDir))
  967. return _error->Warning("can not create dir %s", flNotFile(ByHashOutputFile).c_str());
  968. // write new hashes
  969. FileFd In(Input, FileFd::ReadOnly);
  970. FileFd Out(ByHashOutputFile, FileFd::WriteEmpty);
  971. if(!CopyFile(In, Out))
  972. return _error->Warning("failed to copy %s %s", Input.c_str(), ByHashOutputFile.c_str());
  973. }
  974. }
  975. return true;
  976. }
  977. /*}}}*/
  978. // ReleaseWriter::Finish - Output the checksums /*{{{*/
  979. // ---------------------------------------------------------------------
  980. static void printChecksumTypeRecord(FileFd &Output, char const * const Type, map<string, ReleaseWriter::CheckSum> const &CheckSums)
  981. {
  982. {
  983. std::string out;
  984. strprintf(out, "%s:\n", Type);
  985. Output.Write(out.c_str(), out.length());
  986. }
  987. for(map<string,ReleaseWriter::CheckSum>::const_iterator I = CheckSums.begin();
  988. I != CheckSums.end(); ++I)
  989. {
  990. HashString const * const hs = I->second.Hashes.find(Type);
  991. if (hs == NULL)
  992. continue;
  993. std::string out;
  994. strprintf(out, " %s %16llu %s\n",
  995. hs->HashValue().c_str(),
  996. (*I).second.size,
  997. (*I).first.c_str());
  998. Output.Write(out.c_str(), out.length());
  999. }
  1000. }
  1001. void ReleaseWriter::Finish()
  1002. {
  1003. if ((DoHashes & Hashes::MD5SUM) == Hashes::MD5SUM)
  1004. printChecksumTypeRecord(*Output, "MD5Sum", CheckSums);
  1005. if ((DoHashes & Hashes::SHA1SUM) == Hashes::SHA1SUM)
  1006. printChecksumTypeRecord(*Output, "SHA1", CheckSums);
  1007. if ((DoHashes & Hashes::SHA256SUM) == Hashes::SHA256SUM)
  1008. printChecksumTypeRecord(*Output, "SHA256", CheckSums);
  1009. if ((DoHashes & Hashes::SHA512SUM) == Hashes::SHA512SUM)
  1010. printChecksumTypeRecord(*Output, "SHA512", CheckSums);
  1011. // go by-hash cleanup
  1012. map<string,ReleaseWriter::CheckSum>::const_iterator prev = CheckSums.begin();
  1013. if (_config->FindB("APT::FTPArchive::DoByHash", false) == true)
  1014. {
  1015. for(map<string,ReleaseWriter::CheckSum>::const_iterator I = CheckSums.begin();
  1016. I != CheckSums.end(); ++I)
  1017. {
  1018. if (I->first == "Release" || I->first == "InRelease")
  1019. continue;
  1020. // keep iterating until we find a new subdir
  1021. if(flNotFile(I->first) == flNotFile(prev->first))
  1022. continue;
  1023. // clean that subdir up
  1024. int keepFiles = _config->FindI("APT::FTPArchive::By-Hash-Keep", 3);
  1025. // calculate how many compressors are used (the amount of files
  1026. // in that subdir generated for this run)
  1027. keepFiles *= std::distance(prev, I);
  1028. prev = I;
  1029. HashStringList hsl = prev->second.Hashes;
  1030. for(HashStringList::const_iterator h = hsl.begin();
  1031. h != hsl.end(); ++h)
  1032. {
  1033. if (!h->usable())
  1034. continue;
  1035. std::string RealFilename = DirStrip+"/"+prev->first;
  1036. std::string ByHashOutputFile = GenByHashFilename(RealFilename, *h);
  1037. DeleteAllButMostRecent(flNotFile(ByHashOutputFile), keepFiles);
  1038. }
  1039. }
  1040. }
  1041. }