indexcopy.cc 28 KB

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