indexcopy.cc 26 KB

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