writer.cc 36 KB

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