writer.cc 35 KB

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