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.
 
 
 
 
 
 

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