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.
 
 
 
 
 
 

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