writer.cc 32 KB

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