indexcopy.cc 27 KB

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