indexcopy.cc 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: indexcopy.cc,v 1.10 2002/03/26 07:38:58 jgg Exp $
  4. /* ######################################################################
  5. Index Copying - Aid for copying and verifying the index files
  6. This class helps apt-cache reconstruct a damaged index files.
  7. ##################################################################### */
  8. /*}}}*/
  9. // Include Files /*{{{*/
  10. #include<config.h>
  11. #include <apt-pkg/error.h>
  12. #include <apt-pkg/progress.h>
  13. #include <apt-pkg/strutl.h>
  14. #include <apt-pkg/fileutl.h>
  15. #include <apt-pkg/aptconfiguration.h>
  16. #include <apt-pkg/configuration.h>
  17. #include <apt-pkg/tagfile.h>
  18. #include <apt-pkg/indexrecords.h>
  19. #include <apt-pkg/md5.h>
  20. #include <apt-pkg/cdrom.h>
  21. #include <iostream>
  22. #include <sstream>
  23. #include <unistd.h>
  24. #include <sys/stat.h>
  25. #include <sys/types.h>
  26. #include <fcntl.h>
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include "indexcopy.h"
  30. #include <apti18n.h>
  31. /*}}}*/
  32. using namespace std;
  33. // IndexCopy::CopyPackages - Copy the package files from the CD /*{{{*/
  34. // ---------------------------------------------------------------------
  35. /* */
  36. bool IndexCopy::CopyPackages(string CDROM,string Name,vector<string> &List,
  37. pkgCdromStatus *log)
  38. {
  39. OpProgress *Progress = NULL;
  40. if (List.empty() == true)
  41. return true;
  42. if(log)
  43. Progress = log->GetOpProgress();
  44. bool NoStat = _config->FindB("APT::CDROM::Fast",false);
  45. bool Debug = _config->FindB("Debug::aptcdrom",false);
  46. // Prepare the progress indicator
  47. off_t TotalSize = 0;
  48. std::vector<APT::Configuration::Compressor> const compressor = APT::Configuration::getCompressors();
  49. for (vector<string>::iterator I = List.begin(); I != List.end(); ++I)
  50. {
  51. struct stat Buf;
  52. bool found = false;
  53. std::string file = std::string(*I).append(GetFileName());
  54. for (std::vector<APT::Configuration::Compressor>::const_iterator c = compressor.begin();
  55. c != compressor.end(); ++c)
  56. {
  57. if (stat(std::string(file + c->Extension).c_str(), &Buf) != 0)
  58. continue;
  59. found = true;
  60. break;
  61. }
  62. if (found == false)
  63. return _error->Errno("stat", "Stat failed for %s", file.c_str());
  64. TotalSize += Buf.st_size;
  65. }
  66. off_t CurrentSize = 0;
  67. unsigned int NotFound = 0;
  68. unsigned int WrongSize = 0;
  69. unsigned int Packages = 0;
  70. for (vector<string>::iterator I = List.begin(); I != List.end(); ++I)
  71. {
  72. string OrigPath = string(*I,CDROM.length());
  73. // Open the package file
  74. FileFd Pkg(*I + GetFileName(), FileFd::ReadOnly, FileFd::Auto);
  75. off_t const FileSize = Pkg.Size();
  76. pkgTagFile Parser(&Pkg);
  77. if (_error->PendingError() == true)
  78. return false;
  79. // Open the output file
  80. char S[400];
  81. snprintf(S,sizeof(S),"cdrom:[%s]/%s%s",Name.c_str(),
  82. (*I).c_str() + CDROM.length(),GetFileName());
  83. string TargetF = _config->FindDir("Dir::State::lists") + "partial/";
  84. TargetF += URItoFileName(S);
  85. FileFd Target;
  86. if (_config->FindB("APT::CDROM::NoAct",false) == true)
  87. {
  88. TargetF = "/dev/null";
  89. Target.Open(TargetF,FileFd::WriteExists);
  90. } else {
  91. Target.Open(TargetF,FileFd::WriteAtomic);
  92. }
  93. FILE *TargetFl = fdopen(dup(Target.Fd()),"w");
  94. if (_error->PendingError() == true)
  95. return false;
  96. if (TargetFl == 0)
  97. return _error->Errno("fdopen","Failed to reopen fd");
  98. // Setup the progress meter
  99. if(Progress)
  100. Progress->OverallProgress(CurrentSize,TotalSize,FileSize,
  101. string("Reading ") + Type() + " Indexes");
  102. // Parse
  103. if(Progress)
  104. Progress->SubProgress(Pkg.Size());
  105. pkgTagSection Section;
  106. this->Section = &Section;
  107. string Prefix;
  108. unsigned long Hits = 0;
  109. unsigned long Chop = 0;
  110. while (Parser.Step(Section) == true)
  111. {
  112. if(Progress)
  113. Progress->Progress(Parser.Offset());
  114. string File;
  115. unsigned long long Size;
  116. if (GetFile(File,Size) == false)
  117. {
  118. fclose(TargetFl);
  119. return false;
  120. }
  121. if (Chop != 0)
  122. File = OrigPath + ChopDirs(File,Chop);
  123. // See if the file exists
  124. bool Mangled = false;
  125. if (NoStat == false || Hits < 10)
  126. {
  127. // Attempt to fix broken structure
  128. if (Hits == 0)
  129. {
  130. if (ReconstructPrefix(Prefix,OrigPath,CDROM,File) == false &&
  131. ReconstructChop(Chop,*I,File) == false)
  132. {
  133. if (Debug == true)
  134. clog << "Missed: " << File << endl;
  135. NotFound++;
  136. continue;
  137. }
  138. if (Chop != 0)
  139. File = OrigPath + ChopDirs(File,Chop);
  140. }
  141. // Get the size
  142. struct stat Buf;
  143. if (stat(string(CDROM + Prefix + File).c_str(),&Buf) != 0 ||
  144. Buf.st_size == 0)
  145. {
  146. // Attempt to fix busted symlink support for one instance
  147. string OrigFile = File;
  148. string::size_type Start = File.find("binary-");
  149. string::size_type End = File.find("/",Start+3);
  150. if (Start != string::npos && End != string::npos)
  151. {
  152. File.replace(Start,End-Start,"binary-all");
  153. Mangled = true;
  154. }
  155. if (Mangled == false ||
  156. stat(string(CDROM + Prefix + File).c_str(),&Buf) != 0)
  157. {
  158. if (Debug == true)
  159. clog << "Missed(2): " << OrigFile << endl;
  160. NotFound++;
  161. continue;
  162. }
  163. }
  164. // Size match
  165. if ((unsigned long long)Buf.st_size != Size)
  166. {
  167. if (Debug == true)
  168. clog << "Wrong Size: " << File << endl;
  169. WrongSize++;
  170. continue;
  171. }
  172. }
  173. Packages++;
  174. Hits++;
  175. if (RewriteEntry(TargetFl,File) == false)
  176. {
  177. fclose(TargetFl);
  178. return false;
  179. }
  180. }
  181. fclose(TargetFl);
  182. if (Debug == true)
  183. cout << " Processed by using Prefix '" << Prefix << "' and chop " << Chop << endl;
  184. if (_config->FindB("APT::CDROM::NoAct",false) == false)
  185. {
  186. // Move out of the partial directory
  187. Target.Close();
  188. string FinalF = _config->FindDir("Dir::State::lists");
  189. FinalF += URItoFileName(S);
  190. if (rename(TargetF.c_str(),FinalF.c_str()) != 0)
  191. return _error->Errno("rename","Failed to rename");
  192. }
  193. /* Mangle the source to be in the proper notation with
  194. prefix dist [component] */
  195. *I = string(*I,Prefix.length());
  196. ConvertToSourceList(CDROM,*I);
  197. *I = Prefix + ' ' + *I;
  198. CurrentSize += FileSize;
  199. }
  200. if(Progress)
  201. Progress->Done();
  202. // Some stats
  203. if(log) {
  204. stringstream msg;
  205. if(NotFound == 0 && WrongSize == 0)
  206. ioprintf(msg, _("Wrote %i records.\n"), Packages);
  207. else if (NotFound != 0 && WrongSize == 0)
  208. ioprintf(msg, _("Wrote %i records with %i missing files.\n"),
  209. Packages, NotFound);
  210. else if (NotFound == 0 && WrongSize != 0)
  211. ioprintf(msg, _("Wrote %i records with %i mismatched files\n"),
  212. Packages, WrongSize);
  213. if (NotFound != 0 && WrongSize != 0)
  214. ioprintf(msg, _("Wrote %i records with %i missing files and %i mismatched files\n"), Packages, NotFound, WrongSize);
  215. }
  216. if (Packages == 0)
  217. _error->Warning("No valid records were found.");
  218. if (NotFound + WrongSize > 10)
  219. _error->Warning("A lot of entries were discarded, something may be wrong.\n");
  220. return true;
  221. }
  222. /*}}}*/
  223. // IndexCopy::ChopDirs - Chop off the leading directory components /*{{{*/
  224. // ---------------------------------------------------------------------
  225. /* */
  226. string IndexCopy::ChopDirs(string Path,unsigned int Depth)
  227. {
  228. string::size_type I = 0;
  229. do
  230. {
  231. I = Path.find('/',I+1);
  232. Depth--;
  233. }
  234. while (I != string::npos && Depth != 0);
  235. if (I == string::npos)
  236. return string();
  237. return string(Path,I+1);
  238. }
  239. /*}}}*/
  240. // IndexCopy::ReconstructPrefix - Fix strange prefixing /*{{{*/
  241. // ---------------------------------------------------------------------
  242. /* This prepends dir components from the path to the package files to
  243. the path to the deb until it is found */
  244. bool IndexCopy::ReconstructPrefix(string &Prefix,string OrigPath,string CD,
  245. string File)
  246. {
  247. bool Debug = _config->FindB("Debug::aptcdrom",false);
  248. unsigned int Depth = 1;
  249. string MyPrefix = Prefix;
  250. while (1)
  251. {
  252. struct stat Buf;
  253. if (stat(string(CD + MyPrefix + File).c_str(),&Buf) != 0)
  254. {
  255. if (Debug == true)
  256. cout << "Failed, " << CD + MyPrefix + File << endl;
  257. if (GrabFirst(OrigPath,MyPrefix,Depth++) == true)
  258. continue;
  259. return false;
  260. }
  261. else
  262. {
  263. Prefix = MyPrefix;
  264. return true;
  265. }
  266. }
  267. return false;
  268. }
  269. /*}}}*/
  270. // IndexCopy::ReconstructChop - Fixes bad source paths /*{{{*/
  271. // ---------------------------------------------------------------------
  272. /* This removes path components from the filename and prepends the location
  273. of the package files until a file is found */
  274. bool IndexCopy::ReconstructChop(unsigned long &Chop,string Dir,string File)
  275. {
  276. // Attempt to reconstruct the filename
  277. unsigned long Depth = 0;
  278. while (1)
  279. {
  280. struct stat Buf;
  281. if (stat(string(Dir + File).c_str(),&Buf) != 0)
  282. {
  283. File = ChopDirs(File,1);
  284. Depth++;
  285. if (File.empty() == false)
  286. continue;
  287. return false;
  288. }
  289. else
  290. {
  291. Chop = Depth;
  292. return true;
  293. }
  294. }
  295. return false;
  296. }
  297. /*}}}*/
  298. // IndexCopy::ConvertToSourceList - Convert a Path to a sourcelist /*{{{*/
  299. // ---------------------------------------------------------------------
  300. /* We look for things in dists/ notation and convert them to
  301. <dist> <component> form otherwise it is left alone. This also strips
  302. the CD path.
  303. This implements a regex sort of like:
  304. (.*)/dists/([^/]*)/(.*)/binary-*
  305. ^ ^ ^- Component
  306. | |-------- Distribution
  307. |------------------- Path
  308. It was deciced to use only a single word for dist (rather than say
  309. unstable/non-us) to increase the chance that each CD gets a single
  310. line in sources.list.
  311. */
  312. void IndexCopy::ConvertToSourceList(string CD,string &Path)
  313. {
  314. char S[300];
  315. snprintf(S,sizeof(S),"binary-%s",_config->Find("Apt::Architecture").c_str());
  316. // Strip the cdrom base path
  317. Path = string(Path,CD.length());
  318. if (Path.empty() == true)
  319. Path = "/";
  320. // Too short to be a dists/ type
  321. if (Path.length() < strlen("dists/"))
  322. return;
  323. // Not a dists type.
  324. if (stringcmp(Path.c_str(),Path.c_str()+strlen("dists/"),"dists/") != 0)
  325. return;
  326. // Isolate the dist
  327. string::size_type Slash = strlen("dists/");
  328. string::size_type Slash2 = Path.find('/',Slash + 1);
  329. if (Slash2 == string::npos || Slash2 + 2 >= Path.length())
  330. return;
  331. string Dist = string(Path,Slash,Slash2 - Slash);
  332. // Isolate the component
  333. Slash = Slash2;
  334. for (unsigned I = 0; I != 10; I++)
  335. {
  336. Slash = Path.find('/',Slash+1);
  337. if (Slash == string::npos || Slash + 2 >= Path.length())
  338. return;
  339. string Comp = string(Path,Slash2+1,Slash - Slash2-1);
  340. // Verify the trailing binary- bit
  341. string::size_type BinSlash = Path.find('/',Slash + 1);
  342. if (Slash == string::npos)
  343. return;
  344. string Binary = string(Path,Slash+1,BinSlash - Slash-1);
  345. if (Binary != S && Binary != "source")
  346. continue;
  347. Path = Dist + ' ' + Comp;
  348. return;
  349. }
  350. }
  351. /*}}}*/
  352. // IndexCopy::GrabFirst - Return the first Depth path components /*{{{*/
  353. // ---------------------------------------------------------------------
  354. /* */
  355. bool IndexCopy::GrabFirst(string Path,string &To,unsigned int Depth)
  356. {
  357. string::size_type I = 0;
  358. do
  359. {
  360. I = Path.find('/',I+1);
  361. Depth--;
  362. }
  363. while (I != string::npos && Depth != 0);
  364. if (I == string::npos)
  365. return false;
  366. To = string(Path,0,I+1);
  367. return true;
  368. }
  369. /*}}}*/
  370. // PackageCopy::GetFile - Get the file information from the section /*{{{*/
  371. // ---------------------------------------------------------------------
  372. /* */
  373. bool PackageCopy::GetFile(string &File,unsigned long long &Size)
  374. {
  375. File = Section->FindS("Filename");
  376. Size = Section->FindI("Size");
  377. if (File.empty() || Size == 0)
  378. return _error->Error("Cannot find filename or size tag");
  379. return true;
  380. }
  381. /*}}}*/
  382. // PackageCopy::RewriteEntry - Rewrite the entry with a new filename /*{{{*/
  383. // ---------------------------------------------------------------------
  384. /* */
  385. bool PackageCopy::RewriteEntry(FILE *Target,string File)
  386. {
  387. TFRewriteData Changes[] = {{"Filename",File.c_str()},
  388. {}};
  389. if (TFRewrite(Target,*Section,TFRewritePackageOrder,Changes) == false)
  390. return false;
  391. fputc('\n',Target);
  392. return true;
  393. }
  394. /*}}}*/
  395. // SourceCopy::GetFile - Get the file information from the section /*{{{*/
  396. // ---------------------------------------------------------------------
  397. /* */
  398. bool SourceCopy::GetFile(string &File,unsigned long long &Size)
  399. {
  400. string Files = Section->FindS("Files");
  401. if (Files.empty() == true)
  402. return false;
  403. // Stash the / terminated directory prefix
  404. string Base = Section->FindS("Directory");
  405. if (Base.empty() == false && Base[Base.length()-1] != '/')
  406. Base += '/';
  407. // Read the first file triplet
  408. const char *C = Files.c_str();
  409. string sSize;
  410. string MD5Hash;
  411. // Parse each of the elements
  412. if (ParseQuoteWord(C,MD5Hash) == false ||
  413. ParseQuoteWord(C,sSize) == false ||
  414. ParseQuoteWord(C,File) == false)
  415. return _error->Error("Error parsing file record");
  416. // Parse the size and append the directory
  417. Size = strtoull(sSize.c_str(), NULL, 10);
  418. File = Base + File;
  419. return true;
  420. }
  421. /*}}}*/
  422. // SourceCopy::RewriteEntry - Rewrite the entry with a new filename /*{{{*/
  423. // ---------------------------------------------------------------------
  424. /* */
  425. bool SourceCopy::RewriteEntry(FILE *Target,string File)
  426. {
  427. string Dir(File,0,File.rfind('/'));
  428. TFRewriteData Changes[] = {{"Directory",Dir.c_str()},
  429. {}};
  430. if (TFRewrite(Target,*Section,TFRewriteSourceOrder,Changes) == false)
  431. return false;
  432. fputc('\n',Target);
  433. return true;
  434. }
  435. /*}}}*/
  436. // SigVerify::Verify - Verify a files md5sum against its metaindex /*{{{*/
  437. // ---------------------------------------------------------------------
  438. /* */
  439. bool SigVerify::Verify(string prefix, string file, indexRecords *MetaIndex)
  440. {
  441. const indexRecords::checkSum *Record = MetaIndex->Lookup(file);
  442. // we skip non-existing files in the verifcation to support a cdrom
  443. // with no Packages file (just a Package.gz), see LP: #255545
  444. // (non-existing files are not considered a error)
  445. if(!RealFileExists(prefix+file))
  446. {
  447. _error->Warning(_("Skipping nonexistent file %s"), string(prefix+file).c_str());
  448. return true;
  449. }
  450. if (!Record)
  451. {
  452. _error->Warning(_("Can't find authentication record for: %s"), file.c_str());
  453. return false;
  454. }
  455. if (!Record->Hash.VerifyFile(prefix+file))
  456. {
  457. _error->Warning(_("Hash mismatch for: %s"),file.c_str());
  458. return false;
  459. }
  460. if(_config->FindB("Debug::aptcdrom",false))
  461. {
  462. cout << "File: " << prefix+file << endl;
  463. cout << "Expected Hash " << Record->Hash.toStr() << endl;
  464. }
  465. return true;
  466. }
  467. /*}}}*/
  468. bool SigVerify::CopyMetaIndex(string CDROM, string CDName, /*{{{*/
  469. string prefix, string file)
  470. {
  471. char S[400];
  472. snprintf(S,sizeof(S),"cdrom:[%s]/%s%s",CDName.c_str(),
  473. (prefix).c_str() + CDROM.length(),file.c_str());
  474. string TargetF = _config->FindDir("Dir::State::lists");
  475. TargetF += URItoFileName(S);
  476. FileFd Target;
  477. FileFd Rel;
  478. Target.Open(TargetF,FileFd::WriteAtomic);
  479. Rel.Open(prefix + file,FileFd::ReadOnly);
  480. if (_error->PendingError() == true)
  481. return false;
  482. if (CopyFile(Rel,Target) == false)
  483. return false;
  484. return true;
  485. }
  486. /*}}}*/
  487. bool SigVerify::CopyAndVerify(string CDROM,string Name,vector<string> &SigList, /*{{{*/
  488. vector<string> PkgList,vector<string> SrcList)
  489. {
  490. if (SigList.empty() == true)
  491. return true;
  492. bool Debug = _config->FindB("Debug::aptcdrom",false);
  493. // Read all Release files
  494. for (vector<string>::iterator I = SigList.begin(); I != SigList.end(); ++I)
  495. {
  496. if(Debug)
  497. cout << "Signature verify for: " << *I << endl;
  498. indexRecords *MetaIndex = new indexRecords;
  499. string prefix = *I;
  500. string const releasegpg = *I+"Release.gpg";
  501. string const release = *I+"Release";
  502. string const inrelease = *I+"InRelease";
  503. bool useInRelease = true;
  504. // a Release.gpg without a Release should never happen
  505. if (RealFileExists(inrelease) == true)
  506. ;
  507. else if(RealFileExists(release) == false || RealFileExists(releasegpg) == false)
  508. {
  509. delete MetaIndex;
  510. continue;
  511. }
  512. else
  513. useInRelease = false;
  514. pid_t pid = ExecFork();
  515. if(pid < 0) {
  516. _error->Error("Fork failed");
  517. return false;
  518. }
  519. if(pid == 0)
  520. {
  521. if (useInRelease == true)
  522. RunGPGV(inrelease, inrelease);
  523. else
  524. RunGPGV(release, releasegpg);
  525. }
  526. if(!ExecWait(pid, "gpgv")) {
  527. _error->Warning("Signature verification failed for: %s",
  528. (useInRelease ? inrelease.c_str() : releasegpg.c_str()));
  529. // something went wrong, don't copy the Release.gpg
  530. // FIXME: delete any existing gpg file?
  531. continue;
  532. }
  533. // Open the Release file and add it to the MetaIndex
  534. if(!MetaIndex->Load(release))
  535. {
  536. _error->Error("%s",MetaIndex->ErrorText.c_str());
  537. return false;
  538. }
  539. // go over the Indexfiles and see if they verify
  540. // if so, remove them from our copy of the lists
  541. vector<string> keys = MetaIndex->MetaKeys();
  542. for (vector<string>::iterator I = keys.begin(); I != keys.end(); ++I)
  543. {
  544. if(!Verify(prefix,*I, MetaIndex)) {
  545. // something went wrong, don't copy the Release.gpg
  546. // FIXME: delete any existing gpg file?
  547. _error->Discard();
  548. continue;
  549. }
  550. }
  551. // we need a fresh one for the Release.gpg
  552. delete MetaIndex;
  553. // everything was fine, copy the Release and Release.gpg file
  554. if (useInRelease == true)
  555. CopyMetaIndex(CDROM, Name, prefix, "InRelease");
  556. else
  557. {
  558. CopyMetaIndex(CDROM, Name, prefix, "Release");
  559. CopyMetaIndex(CDROM, Name, prefix, "Release.gpg");
  560. }
  561. }
  562. return true;
  563. }
  564. /*}}}*/
  565. // SigVerify::RunGPGV - returns the command needed for verify /*{{{*/
  566. // ---------------------------------------------------------------------
  567. /* Generating the commandline for calling gpgv is somehow complicated as
  568. we need to add multiple keyrings and user supplied options. Also, as
  569. the cdrom code currently can not use the gpgv method we have two places
  570. these need to be done - so the place for this method is wrong but better
  571. than code duplication… */
  572. bool SigVerify::RunGPGV(std::string const &File, std::string const &FileGPG,
  573. int const &statusfd, int fd[2])
  574. {
  575. if (File == FileGPG)
  576. {
  577. #define SIGMSG "-----BEGIN PGP SIGNED MESSAGE-----\n"
  578. char buffer[sizeof(SIGMSG)];
  579. FILE* gpg = fopen(File.c_str(), "r");
  580. if (gpg == NULL)
  581. return _error->Errno("RunGPGV", _("Could not open file %s"), File.c_str());
  582. char const * const test = fgets(buffer, sizeof(buffer), gpg);
  583. fclose(gpg);
  584. if (test == NULL || strcmp(buffer, SIGMSG) != 0)
  585. return _error->Error(_("File %s doesn't start with a clearsigned message"), File.c_str());
  586. #undef SIGMSG
  587. }
  588. string const gpgvpath = _config->Find("Dir::Bin::gpg", "/usr/bin/gpgv");
  589. // FIXME: remove support for deprecated APT::GPGV setting
  590. string const trustedFile = _config->Find("APT::GPGV::TrustedKeyring", _config->FindFile("Dir::Etc::Trusted"));
  591. string const trustedPath = _config->FindDir("Dir::Etc::TrustedParts");
  592. bool const Debug = _config->FindB("Debug::Acquire::gpgv", false);
  593. if (Debug == true)
  594. {
  595. std::clog << "gpgv path: " << gpgvpath << std::endl;
  596. std::clog << "Keyring file: " << trustedFile << std::endl;
  597. std::clog << "Keyring path: " << trustedPath << std::endl;
  598. }
  599. std::vector<string> keyrings;
  600. if (DirectoryExists(trustedPath))
  601. keyrings = GetListOfFilesInDir(trustedPath, "gpg", false, true);
  602. if (RealFileExists(trustedFile) == true)
  603. keyrings.push_back(trustedFile);
  604. std::vector<const char *> Args;
  605. Args.reserve(30);
  606. if (keyrings.empty() == true)
  607. {
  608. // TRANSLATOR: %s is the trusted keyring parts directory
  609. return _error->Error(_("No keyring installed in %s."),
  610. _config->FindDir("Dir::Etc::TrustedParts").c_str());
  611. }
  612. Args.push_back(gpgvpath.c_str());
  613. Args.push_back("--ignore-time-conflict");
  614. if (statusfd != -1)
  615. {
  616. Args.push_back("--status-fd");
  617. char fd[10];
  618. snprintf(fd, sizeof(fd), "%i", statusfd);
  619. Args.push_back(fd);
  620. }
  621. for (vector<string>::const_iterator K = keyrings.begin();
  622. K != keyrings.end(); ++K)
  623. {
  624. Args.push_back("--keyring");
  625. Args.push_back(K->c_str());
  626. }
  627. Configuration::Item const *Opts;
  628. Opts = _config->Tree("Acquire::gpgv::Options");
  629. if (Opts != 0)
  630. {
  631. Opts = Opts->Child;
  632. for (; Opts != 0; Opts = Opts->Next)
  633. {
  634. if (Opts->Value.empty() == true)
  635. continue;
  636. Args.push_back(Opts->Value.c_str());
  637. }
  638. }
  639. Args.push_back(FileGPG.c_str());
  640. if (FileGPG != File)
  641. Args.push_back(File.c_str());
  642. Args.push_back(NULL);
  643. if (Debug == true)
  644. {
  645. std::clog << "Preparing to exec: " << gpgvpath;
  646. for (std::vector<const char *>::const_iterator a = Args.begin(); *a != NULL; ++a)
  647. std::clog << " " << *a;
  648. std::clog << std::endl;
  649. }
  650. if (statusfd != -1)
  651. {
  652. int const nullfd = open("/dev/null", O_RDONLY);
  653. close(fd[0]);
  654. // Redirect output to /dev/null; we read from the status fd
  655. dup2(nullfd, STDOUT_FILENO);
  656. dup2(nullfd, STDERR_FILENO);
  657. // Redirect the pipe to the status fd (3)
  658. dup2(fd[1], statusfd);
  659. putenv((char *)"LANG=");
  660. putenv((char *)"LC_ALL=");
  661. putenv((char *)"LC_MESSAGES=");
  662. }
  663. execvp(gpgvpath.c_str(), (char **) &Args[0]);
  664. return true;
  665. }
  666. /*}}}*/
  667. bool TranslationsCopy::CopyTranslations(string CDROM,string Name, /*{{{*/
  668. vector<string> &List, pkgCdromStatus *log)
  669. {
  670. OpProgress *Progress = NULL;
  671. if (List.empty() == true)
  672. return true;
  673. if(log)
  674. Progress = log->GetOpProgress();
  675. bool Debug = _config->FindB("Debug::aptcdrom",false);
  676. // Prepare the progress indicator
  677. off_t TotalSize = 0;
  678. std::vector<APT::Configuration::Compressor> const compressor = APT::Configuration::getCompressors();
  679. for (vector<string>::iterator I = List.begin(); I != List.end(); ++I)
  680. {
  681. struct stat Buf;
  682. bool found = false;
  683. std::string file = *I;
  684. for (std::vector<APT::Configuration::Compressor>::const_iterator c = compressor.begin();
  685. c != compressor.end(); ++c)
  686. {
  687. if (stat(std::string(file + c->Extension).c_str(), &Buf) != 0)
  688. continue;
  689. found = true;
  690. break;
  691. }
  692. if (found == false)
  693. return _error->Errno("stat", "Stat failed for %s", file.c_str());
  694. TotalSize += Buf.st_size;
  695. }
  696. off_t CurrentSize = 0;
  697. unsigned int NotFound = 0;
  698. unsigned int WrongSize = 0;
  699. unsigned int Packages = 0;
  700. for (vector<string>::iterator I = List.begin(); I != List.end(); ++I)
  701. {
  702. string OrigPath = string(*I,CDROM.length());
  703. // Open the package file
  704. FileFd Pkg(*I, FileFd::ReadOnly, FileFd::Auto);
  705. off_t const FileSize = Pkg.Size();
  706. pkgTagFile Parser(&Pkg);
  707. if (_error->PendingError() == true)
  708. return false;
  709. // Open the output file
  710. char S[400];
  711. snprintf(S,sizeof(S),"cdrom:[%s]/%s",Name.c_str(),
  712. (*I).c_str() + CDROM.length());
  713. string TargetF = _config->FindDir("Dir::State::lists") + "partial/";
  714. TargetF += URItoFileName(S);
  715. if (_config->FindB("APT::CDROM::NoAct",false) == true)
  716. TargetF = "/dev/null";
  717. FileFd Target(TargetF,FileFd::WriteAtomic);
  718. FILE *TargetFl = fdopen(dup(Target.Fd()),"w");
  719. if (_error->PendingError() == true)
  720. return false;
  721. if (TargetFl == 0)
  722. return _error->Errno("fdopen","Failed to reopen fd");
  723. // Setup the progress meter
  724. if(Progress)
  725. Progress->OverallProgress(CurrentSize,TotalSize,FileSize,
  726. string("Reading Translation Indexes"));
  727. // Parse
  728. if(Progress)
  729. Progress->SubProgress(Pkg.Size());
  730. pkgTagSection Section;
  731. this->Section = &Section;
  732. string Prefix;
  733. unsigned long Hits = 0;
  734. while (Parser.Step(Section) == true)
  735. {
  736. if(Progress)
  737. Progress->Progress(Parser.Offset());
  738. const char *Start;
  739. const char *Stop;
  740. Section.GetSection(Start,Stop);
  741. fwrite(Start,Stop-Start, 1, TargetFl);
  742. fputc('\n',TargetFl);
  743. Packages++;
  744. Hits++;
  745. }
  746. fclose(TargetFl);
  747. if (Debug == true)
  748. cout << " Processed by using Prefix '" << Prefix << "' and chop " << endl;
  749. if (_config->FindB("APT::CDROM::NoAct",false) == false)
  750. {
  751. // Move out of the partial directory
  752. Target.Close();
  753. string FinalF = _config->FindDir("Dir::State::lists");
  754. FinalF += URItoFileName(S);
  755. if (rename(TargetF.c_str(),FinalF.c_str()) != 0)
  756. return _error->Errno("rename","Failed to rename");
  757. }
  758. CurrentSize += FileSize;
  759. }
  760. if(Progress)
  761. Progress->Done();
  762. // Some stats
  763. if(log) {
  764. stringstream msg;
  765. if(NotFound == 0 && WrongSize == 0)
  766. ioprintf(msg, _("Wrote %i records.\n"), Packages);
  767. else if (NotFound != 0 && WrongSize == 0)
  768. ioprintf(msg, _("Wrote %i records with %i missing files.\n"),
  769. Packages, NotFound);
  770. else if (NotFound == 0 && WrongSize != 0)
  771. ioprintf(msg, _("Wrote %i records with %i mismatched files\n"),
  772. Packages, WrongSize);
  773. if (NotFound != 0 && WrongSize != 0)
  774. ioprintf(msg, _("Wrote %i records with %i missing files and %i mismatched files\n"), Packages, NotFound, WrongSize);
  775. }
  776. if (Packages == 0)
  777. _error->Warning("No valid records were found.");
  778. if (NotFound + WrongSize > 10)
  779. _error->Warning("A lot of entries were discarded, something may be wrong.\n");
  780. return true;
  781. }
  782. /*}}}*/