indexcopy.cc 28 KB

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