You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1937 lines
59 KiB

  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: dpkgpm.cc,v 1.28 2004/01/27 02:25:01 mdz Exp $
  4. /* ######################################################################
  5. DPKG Package Manager - Provide an interface to dpkg
  6. ##################################################################### */
  7. /*}}}*/
  8. // Includes /*{{{*/
  9. #include <config.h>
  10. #include <apt-pkg/cachefile.h>
  11. #include <apt-pkg/configuration.h>
  12. #include <apt-pkg/depcache.h>
  13. #include <apt-pkg/dpkgpm.h>
  14. #include <apt-pkg/error.h>
  15. #include <apt-pkg/fileutl.h>
  16. #include <apt-pkg/install-progress.h>
  17. #include <apt-pkg/packagemanager.h>
  18. #include <apt-pkg/pkgrecords.h>
  19. #include <apt-pkg/strutl.h>
  20. #include <apt-pkg/cacheiterators.h>
  21. #include <apt-pkg/macros.h>
  22. #include <apt-pkg/pkgcache.h>
  23. #include <errno.h>
  24. #include <fcntl.h>
  25. #include <grp.h>
  26. #include <pty.h>
  27. #include <pwd.h>
  28. #include <signal.h>
  29. #include <stddef.h>
  30. #include <stdio.h>
  31. #include <stdlib.h>
  32. #include <sys/ioctl.h>
  33. #include <sys/select.h>
  34. #include <sys/stat.h>
  35. #include <sys/time.h>
  36. #include <sys/wait.h>
  37. #include <termios.h>
  38. #include <time.h>
  39. #include <unistd.h>
  40. #include <algorithm>
  41. #include <cstring>
  42. #include <iostream>
  43. #include <map>
  44. #include <set>
  45. #include <string>
  46. #include <utility>
  47. #include <vector>
  48. #include <apti18n.h>
  49. /*}}}*/
  50. using namespace std;
  51. APT_PURE static unsigned int
  52. EnvironmentSize()
  53. {
  54. unsigned int size = 0;
  55. char **envp = environ;
  56. while (*envp != NULL)
  57. size += strlen (*envp++) + 1;
  58. return size;
  59. }
  60. class pkgDPkgPMPrivate
  61. {
  62. public:
  63. pkgDPkgPMPrivate() : stdin_is_dev_null(false), dpkgbuf_pos(0),
  64. term_out(NULL), history_out(NULL),
  65. progress(NULL), tt_is_valid(false), master(-1),
  66. slave(NULL), protect_slave_from_dying(-1)
  67. {
  68. dpkgbuf[0] = '\0';
  69. }
  70. ~pkgDPkgPMPrivate()
  71. {
  72. }
  73. bool stdin_is_dev_null;
  74. // the buffer we use for the dpkg status-fd reading
  75. char dpkgbuf[1024];
  76. int dpkgbuf_pos;
  77. FILE *term_out;
  78. FILE *history_out;
  79. string dpkg_error;
  80. APT::Progress::PackageManager *progress;
  81. // pty stuff
  82. struct termios tt;
  83. bool tt_is_valid;
  84. int master;
  85. char * slave;
  86. int protect_slave_from_dying;
  87. // signals
  88. sigset_t sigmask;
  89. sigset_t original_sigmask;
  90. };
  91. namespace
  92. {
  93. // Maps the dpkg "processing" info to human readable names. Entry 0
  94. // of each array is the key, entry 1 is the value.
  95. const std::pair<const char *, const char *> PackageProcessingOps[] = {
  96. std::make_pair("install", N_("Installing %s")),
  97. std::make_pair("configure", N_("Configuring %s")),
  98. std::make_pair("remove", N_("Removing %s")),
  99. std::make_pair("purge", N_("Completely removing %s")),
  100. std::make_pair("disappear", N_("Noting disappearance of %s")),
  101. std::make_pair("trigproc", N_("Running post-installation trigger %s"))
  102. };
  103. const std::pair<const char *, const char *> * const PackageProcessingOpsBegin = PackageProcessingOps;
  104. const std::pair<const char *, const char *> * const PackageProcessingOpsEnd = PackageProcessingOps + sizeof(PackageProcessingOps) / sizeof(PackageProcessingOps[0]);
  105. // Predicate to test whether an entry in the PackageProcessingOps
  106. // array matches a string.
  107. class MatchProcessingOp
  108. {
  109. const char *target;
  110. public:
  111. MatchProcessingOp(const char *the_target)
  112. : target(the_target)
  113. {
  114. }
  115. bool operator()(const std::pair<const char *, const char *> &pair) const
  116. {
  117. return strcmp(pair.first, target) == 0;
  118. }
  119. };
  120. }
  121. /* helper function to ionice the given PID
  122. there is no C header for ionice yet - just the syscall interface
  123. so we use the binary from util-linux
  124. */
  125. static bool
  126. ionice(int PID)
  127. {
  128. if (!FileExists("/usr/bin/ionice"))
  129. return false;
  130. pid_t Process = ExecFork();
  131. if (Process == 0)
  132. {
  133. char buf[32];
  134. snprintf(buf, sizeof(buf), "-p%d", PID);
  135. const char *Args[4];
  136. Args[0] = "/usr/bin/ionice";
  137. Args[1] = "-c3";
  138. Args[2] = buf;
  139. Args[3] = 0;
  140. execv(Args[0], (char **)Args);
  141. }
  142. return ExecWait(Process, "ionice");
  143. }
  144. static std::string getDpkgExecutable()
  145. {
  146. string Tmp = _config->Find("Dir::Bin::dpkg","dpkg");
  147. string const dpkgChrootDir = _config->FindDir("DPkg::Chroot-Directory", "/");
  148. size_t dpkgChrootLen = dpkgChrootDir.length();
  149. if (dpkgChrootDir != "/" && Tmp.find(dpkgChrootDir) == 0)
  150. {
  151. if (dpkgChrootDir[dpkgChrootLen - 1] == '/')
  152. --dpkgChrootLen;
  153. Tmp = Tmp.substr(dpkgChrootLen);
  154. }
  155. return Tmp;
  156. }
  157. // dpkgChrootDirectory - chrooting for dpkg if needed /*{{{*/
  158. static void dpkgChrootDirectory()
  159. {
  160. std::string const chrootDir = _config->FindDir("DPkg::Chroot-Directory");
  161. if (chrootDir == "/")
  162. return;
  163. std::cerr << "Chrooting into " << chrootDir << std::endl;
  164. if (chroot(chrootDir.c_str()) != 0)
  165. _exit(100);
  166. if (chdir("/") != 0)
  167. _exit(100);
  168. }
  169. /*}}}*/
  170. // FindNowVersion - Helper to find a Version in "now" state /*{{{*/
  171. // ---------------------------------------------------------------------
  172. /* This is helpful when a package is no longer installed but has residual
  173. * config files
  174. */
  175. static
  176. pkgCache::VerIterator FindNowVersion(const pkgCache::PkgIterator &Pkg)
  177. {
  178. pkgCache::VerIterator Ver;
  179. for (Ver = Pkg.VersionList(); Ver.end() == false; ++Ver)
  180. {
  181. pkgCache::VerFileIterator Vf = Ver.FileList();
  182. pkgCache::PkgFileIterator F = Vf.File();
  183. for (F = Vf.File(); F.end() == false; ++F)
  184. {
  185. if (F && F.Archive())
  186. {
  187. if (strcmp(F.Archive(), "now"))
  188. return Ver;
  189. }
  190. }
  191. }
  192. return Ver;
  193. }
  194. /*}}}*/
  195. // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
  196. // ---------------------------------------------------------------------
  197. /* */
  198. pkgDPkgPM::pkgDPkgPM(pkgDepCache *Cache)
  199. : pkgPackageManager(Cache), pkgFailures(0), PackagesDone(0), PackagesTotal(0)
  200. {
  201. d = new pkgDPkgPMPrivate();
  202. }
  203. /*}}}*/
  204. // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
  205. // ---------------------------------------------------------------------
  206. /* */
  207. pkgDPkgPM::~pkgDPkgPM()
  208. {
  209. delete d;
  210. }
  211. /*}}}*/
  212. // DPkgPM::Install - Install a package /*{{{*/
  213. // ---------------------------------------------------------------------
  214. /* Add an install operation to the sequence list */
  215. bool pkgDPkgPM::Install(PkgIterator Pkg,string File)
  216. {
  217. if (File.empty() == true || Pkg.end() == true)
  218. return _error->Error("Internal Error, No file name for %s",Pkg.FullName().c_str());
  219. // If the filename string begins with DPkg::Chroot-Directory, return the
  220. // substr that is within the chroot so dpkg can access it.
  221. string const chrootdir = _config->FindDir("DPkg::Chroot-Directory","/");
  222. if (chrootdir != "/" && File.find(chrootdir) == 0)
  223. {
  224. size_t len = chrootdir.length();
  225. if (chrootdir.at(len - 1) == '/')
  226. len--;
  227. List.push_back(Item(Item::Install,Pkg,File.substr(len)));
  228. }
  229. else
  230. List.push_back(Item(Item::Install,Pkg,File));
  231. return true;
  232. }
  233. /*}}}*/
  234. // DPkgPM::Configure - Configure a package /*{{{*/
  235. // ---------------------------------------------------------------------
  236. /* Add a configure operation to the sequence list */
  237. bool pkgDPkgPM::Configure(PkgIterator Pkg)
  238. {
  239. if (Pkg.end() == true)
  240. return false;
  241. List.push_back(Item(Item::Configure, Pkg));
  242. // Use triggers for config calls if we configure "smart"
  243. // as otherwise Pre-Depends will not be satisfied, see #526774
  244. if (_config->FindB("DPkg::TriggersPending", false) == true)
  245. List.push_back(Item(Item::TriggersPending, PkgIterator()));
  246. return true;
  247. }
  248. /*}}}*/
  249. // DPkgPM::Remove - Remove a package /*{{{*/
  250. // ---------------------------------------------------------------------
  251. /* Add a remove operation to the sequence list */
  252. bool pkgDPkgPM::Remove(PkgIterator Pkg,bool Purge)
  253. {
  254. if (Pkg.end() == true)
  255. return false;
  256. if (Purge == true)
  257. List.push_back(Item(Item::Purge,Pkg));
  258. else
  259. List.push_back(Item(Item::Remove,Pkg));
  260. return true;
  261. }
  262. /*}}}*/
  263. // DPkgPM::SendPkgInfo - Send info for install-pkgs hook /*{{{*/
  264. // ---------------------------------------------------------------------
  265. /* This is part of the helper script communication interface, it sends
  266. very complete information down to the other end of the pipe.*/
  267. bool pkgDPkgPM::SendV2Pkgs(FILE *F)
  268. {
  269. return SendPkgsInfo(F, 2);
  270. }
  271. bool pkgDPkgPM::SendPkgsInfo(FILE * const F, unsigned int const &Version)
  272. {
  273. // This version of APT supports only v3, so don't sent higher versions
  274. if (Version <= 3)
  275. fprintf(F,"VERSION %u\n", Version);
  276. else
  277. fprintf(F,"VERSION 3\n");
  278. /* Write out all of the configuration directives by walking the
  279. configuration tree */
  280. const Configuration::Item *Top = _config->Tree(0);
  281. for (; Top != 0;)
  282. {
  283. if (Top->Value.empty() == false)
  284. {
  285. fprintf(F,"%s=%s\n",
  286. QuoteString(Top->FullTag(),"=\"\n").c_str(),
  287. QuoteString(Top->Value,"\n").c_str());
  288. }
  289. if (Top->Child != 0)
  290. {
  291. Top = Top->Child;
  292. continue;
  293. }
  294. while (Top != 0 && Top->Next == 0)
  295. Top = Top->Parent;
  296. if (Top != 0)
  297. Top = Top->Next;
  298. }
  299. fprintf(F,"\n");
  300. // Write out the package actions in order.
  301. for (vector<Item>::iterator I = List.begin(); I != List.end(); ++I)
  302. {
  303. if(I->Pkg.end() == true)
  304. continue;
  305. pkgDepCache::StateCache &S = Cache[I->Pkg];
  306. fprintf(F,"%s ",I->Pkg.Name());
  307. // Current version which we are going to replace
  308. pkgCache::VerIterator CurVer = I->Pkg.CurrentVer();
  309. if (CurVer.end() == true && (I->Op == Item::Remove || I->Op == Item::Purge))
  310. CurVer = FindNowVersion(I->Pkg);
  311. if (CurVer.end() == true)
  312. {
  313. if (Version <= 2)
  314. fprintf(F, "- ");
  315. else
  316. fprintf(F, "- - none ");
  317. }
  318. else
  319. {
  320. fprintf(F, "%s ", CurVer.VerStr());
  321. if (Version >= 3)
  322. fprintf(F, "%s %s ", CurVer.Arch(), CurVer.MultiArchType());
  323. }
  324. // Show the compare operator between current and install version
  325. if (S.InstallVer != 0)
  326. {
  327. pkgCache::VerIterator const InstVer = S.InstVerIter(Cache);
  328. int Comp = 2;
  329. if (CurVer.end() == false)
  330. Comp = InstVer.CompareVer(CurVer);
  331. if (Comp < 0)
  332. fprintf(F,"> ");
  333. else if (Comp == 0)
  334. fprintf(F,"= ");
  335. else if (Comp > 0)
  336. fprintf(F,"< ");
  337. fprintf(F, "%s ", InstVer.VerStr());
  338. if (Version >= 3)
  339. fprintf(F, "%s %s ", InstVer.Arch(), InstVer.MultiArchType());
  340. }
  341. else
  342. {
  343. if (Version <= 2)
  344. fprintf(F, "> - ");
  345. else
  346. fprintf(F, "> - - none ");
  347. }
  348. // Show the filename/operation
  349. if (I->Op == Item::Install)
  350. {
  351. // No errors here..
  352. if (I->File[0] != '/')
  353. fprintf(F,"**ERROR**\n");
  354. else
  355. fprintf(F,"%s\n",I->File.c_str());
  356. }
  357. else if (I->Op == Item::Configure)
  358. fprintf(F,"**CONFIGURE**\n");
  359. else if (I->Op == Item::Remove ||
  360. I->Op == Item::Purge)
  361. fprintf(F,"**REMOVE**\n");
  362. if (ferror(F) != 0)
  363. return false;
  364. }
  365. return true;
  366. }
  367. /*}}}*/
  368. // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
  369. // ---------------------------------------------------------------------
  370. /* This looks for a list of scripts to run from the configuration file
  371. each one is run and is fed on standard input a list of all .deb files
  372. that are due to be installed. */
  373. bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf)
  374. {
  375. bool result = true;
  376. Configuration::Item const *Opts = _config->Tree(Cnf);
  377. if (Opts == 0 || Opts->Child == 0)
  378. return true;
  379. Opts = Opts->Child;
  380. sighandler_t old_sigpipe = signal(SIGPIPE, SIG_IGN);
  381. unsigned int Count = 1;
  382. for (; Opts != 0; Opts = Opts->Next, Count++)
  383. {
  384. if (Opts->Value.empty() == true)
  385. continue;
  386. if(_config->FindB("Debug::RunScripts", false) == true)
  387. std::clog << "Running external script with list of all .deb file: '"
  388. << Opts->Value << "'" << std::endl;
  389. // Determine the protocol version
  390. string OptSec = Opts->Value;
  391. string::size_type Pos;
  392. if ((Pos = OptSec.find(' ')) == string::npos || Pos == 0)
  393. Pos = OptSec.length();
  394. OptSec = "DPkg::Tools::Options::" + string(Opts->Value.c_str(),Pos);
  395. unsigned int Version = _config->FindI(OptSec+"::Version",1);
  396. unsigned int InfoFD = _config->FindI(OptSec + "::InfoFD", STDIN_FILENO);
  397. // Create the pipes
  398. std::set<int> KeepFDs;
  399. MergeKeepFdsFromConfiguration(KeepFDs);
  400. int Pipes[2];
  401. if (pipe(Pipes) != 0) {
  402. result = _error->Errno("pipe","Failed to create IPC pipe to subprocess");
  403. break;
  404. }
  405. if (InfoFD != (unsigned)Pipes[0])
  406. SetCloseExec(Pipes[0],true);
  407. else
  408. KeepFDs.insert(Pipes[0]);
  409. SetCloseExec(Pipes[1],true);
  410. // Purified Fork for running the script
  411. pid_t Process = ExecFork(KeepFDs);
  412. if (Process == 0)
  413. {
  414. // Setup the FDs
  415. dup2(Pipes[0], InfoFD);
  416. SetCloseExec(STDOUT_FILENO,false);
  417. SetCloseExec(STDIN_FILENO,false);
  418. SetCloseExec(STDERR_FILENO,false);
  419. string hookfd;
  420. strprintf(hookfd, "%d", InfoFD);
  421. setenv("APT_HOOK_INFO_FD", hookfd.c_str(), 1);
  422. dpkgChrootDirectory();
  423. const char *Args[4];
  424. Args[0] = "/bin/sh";
  425. Args[1] = "-c";
  426. Args[2] = Opts->Value.c_str();
  427. Args[3] = 0;
  428. execv(Args[0],(char **)Args);
  429. _exit(100);
  430. }
  431. close(Pipes[0]);
  432. FILE *F = fdopen(Pipes[1],"w");
  433. if (F == 0) {
  434. result = _error->Errno("fdopen","Faild to open new FD");
  435. break;
  436. }
  437. // Feed it the filenames.
  438. if (Version <= 1)
  439. {
  440. for (vector<Item>::iterator I = List.begin(); I != List.end(); ++I)
  441. {
  442. // Only deal with packages to be installed from .deb
  443. if (I->Op != Item::Install)
  444. continue;
  445. // No errors here..
  446. if (I->File[0] != '/')
  447. continue;
  448. /* Feed the filename of each package that is pending install
  449. into the pipe. */
  450. fprintf(F,"%s\n",I->File.c_str());
  451. if (ferror(F) != 0)
  452. break;
  453. }
  454. }
  455. else
  456. SendPkgsInfo(F, Version);
  457. fclose(F);
  458. // Clean up the sub process
  459. if (ExecWait(Process,Opts->Value.c_str()) == false) {
  460. result = _error->Error("Failure running script %s",Opts->Value.c_str());
  461. break;
  462. }
  463. }
  464. signal(SIGPIPE, old_sigpipe);
  465. return result;
  466. }
  467. /*}}}*/
  468. // DPkgPM::DoStdin - Read stdin and pass to master pty /*{{{*/
  469. // ---------------------------------------------------------------------
  470. /*
  471. */
  472. void pkgDPkgPM::DoStdin(int master)
  473. {
  474. unsigned char input_buf[256] = {0,};
  475. ssize_t len = read(0, input_buf, sizeof(input_buf));
  476. if (len)
  477. FileFd::Write(master, input_buf, len);
  478. else
  479. d->stdin_is_dev_null = true;
  480. }
  481. /*}}}*/
  482. // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
  483. // ---------------------------------------------------------------------
  484. /*
  485. * read the terminal pty and write log
  486. */
  487. void pkgDPkgPM::DoTerminalPty(int master)
  488. {
  489. unsigned char term_buf[1024] = {0,0, };
  490. ssize_t len=read(master, term_buf, sizeof(term_buf));
  491. if(len == -1 && errno == EIO)
  492. {
  493. // this happens when the child is about to exit, we
  494. // give it time to actually exit, otherwise we run
  495. // into a race so we sleep for half a second.
  496. struct timespec sleepfor = { 0, 500000000 };
  497. nanosleep(&sleepfor, NULL);
  498. return;
  499. }
  500. if(len <= 0)
  501. return;
  502. FileFd::Write(1, term_buf, len);
  503. if(d->term_out)
  504. fwrite(term_buf, len, sizeof(char), d->term_out);
  505. }
  506. /*}}}*/
  507. // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
  508. // ---------------------------------------------------------------------
  509. /*
  510. */
  511. void pkgDPkgPM::ProcessDpkgStatusLine(char *line)
  512. {
  513. bool const Debug = _config->FindB("Debug::pkgDPkgProgressReporting",false);
  514. if (Debug == true)
  515. std::clog << "got from dpkg '" << line << "'" << std::endl;
  516. /* dpkg sends strings like this:
  517. 'status: <pkg>: <pkg qstate>'
  518. 'status: <pkg>:<arch>: <pkg qstate>'
  519. 'processing: {install,upgrade,configure,remove,purge,disappear,trigproc}: pkg'
  520. 'processing: {install,upgrade,configure,remove,purge,disappear,trigproc}: trigger'
  521. */
  522. // we need to split on ": " (note the appended space) as the ':' is
  523. // part of the pkgname:arch information that dpkg sends
  524. //
  525. // A dpkg error message may contain additional ":" (like
  526. // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
  527. // so we need to ensure to not split too much
  528. std::vector<std::string> list = StringSplit(line, ": ", 4);
  529. if(list.size() < 3)
  530. {
  531. if (Debug == true)
  532. std::clog << "ignoring line: not enough ':'" << std::endl;
  533. return;
  534. }
  535. // build the (prefix, pkgname, action) tuple, position of this
  536. // is different for "processing" or "status" messages
  537. std::string prefix = APT::String::Strip(list[0]);
  538. std::string pkgname;
  539. std::string action;
  540. // "processing" has the form "processing: action: pkg or trigger"
  541. // with action = ["install", "upgrade", "configure", "remove", "purge",
  542. // "disappear", "trigproc"]
  543. if (prefix == "processing")
  544. {
  545. pkgname = APT::String::Strip(list[2]);
  546. action = APT::String::Strip(list[1]);
  547. // we don't care for the difference (as dpkg doesn't really either)
  548. if (action == "upgrade")
  549. action = "install";
  550. }
  551. // "status" has the form: "status: pkg: state"
  552. // with state in ["half-installed", "unpacked", "half-configured",
  553. // "installed", "config-files", "not-installed"]
  554. else if (prefix == "status")
  555. {
  556. pkgname = APT::String::Strip(list[1]);
  557. action = APT::String::Strip(list[2]);
  558. } else {
  559. if (Debug == true)
  560. std::clog << "unknown prefix '" << prefix << "'" << std::endl;
  561. return;
  562. }
  563. /* handle the special cases first:
  564. errors look like this:
  565. 'status: /var/cache/apt/archives/krecipes_0.8.1-0ubuntu1_i386.deb : error : trying to overwrite `/usr/share/doc/kde/HTML/en/krecipes/krectip.png', which is also in package krecipes-data
  566. and conffile-prompt like this
  567. 'status:/etc/compiz.conf/compiz.conf : conffile-prompt: 'current-conffile' 'new-conffile' useredited distedited
  568. */
  569. if (prefix == "status")
  570. {
  571. if(action == "error")
  572. {
  573. d->progress->Error(pkgname, PackagesDone, PackagesTotal,
  574. list[3]);
  575. pkgFailures++;
  576. WriteApportReport(pkgname.c_str(), list[3].c_str());
  577. return;
  578. }
  579. else if(action == "conffile-prompt")
  580. {
  581. d->progress->ConffilePrompt(pkgname, PackagesDone, PackagesTotal,
  582. list[3]);
  583. return;
  584. }
  585. }
  586. // at this point we know that we should have a valid pkgname, so build all
  587. // the info from it
  588. // dpkg does not always send "pkgname:arch" so we add it here if needed
  589. if (pkgname.find(":") == std::string::npos)
  590. {
  591. // find the package in the group that is touched by dpkg
  592. // if there are multiple pkgs dpkg would send us a full pkgname:arch
  593. pkgCache::GrpIterator Grp = Cache.FindGrp(pkgname);
  594. if (Grp.end() == false)
  595. {
  596. pkgCache::PkgIterator P = Grp.PackageList();
  597. for (; P.end() != true; P = Grp.NextPkg(P))
  598. {
  599. if(Cache[P].Keep() == false || Cache[P].ReInstall() == true)
  600. {
  601. pkgname = P.FullName();
  602. break;
  603. }
  604. }
  605. }
  606. }
  607. const char* const pkg = pkgname.c_str();
  608. std::string short_pkgname = StringSplit(pkgname, ":")[0];
  609. std::string arch = "";
  610. if (pkgname.find(":") != string::npos)
  611. arch = StringSplit(pkgname, ":")[1];
  612. std::string i18n_pkgname = pkgname;
  613. if (arch.size() != 0)
  614. strprintf(i18n_pkgname, "%s (%s)", short_pkgname.c_str(), arch.c_str());
  615. // 'processing' from dpkg looks like
  616. // 'processing: action: pkg'
  617. if(prefix == "processing")
  618. {
  619. const std::pair<const char *, const char *> * const iter =
  620. std::find_if(PackageProcessingOpsBegin,
  621. PackageProcessingOpsEnd,
  622. MatchProcessingOp(action.c_str()));
  623. if(iter == PackageProcessingOpsEnd)
  624. {
  625. if (Debug == true)
  626. std::clog << "ignoring unknown action: " << action << std::endl;
  627. return;
  628. }
  629. std::string msg;
  630. strprintf(msg, _(iter->second), i18n_pkgname.c_str());
  631. d->progress->StatusChanged(pkgname, PackagesDone, PackagesTotal, msg);
  632. // FIXME: this needs a muliarch testcase
  633. // FIXME2: is "pkgname" here reliable with dpkg only sending us
  634. // short pkgnames?
  635. if (action == "disappear")
  636. handleDisappearAction(pkgname);
  637. return;
  638. }
  639. if (prefix == "status")
  640. {
  641. vector<struct DpkgState> const &states = PackageOps[pkg];
  642. if(PackageOpsDone[pkg] < states.size())
  643. {
  644. char const * const next_action = states[PackageOpsDone[pkg]].state;
  645. if (next_action && Debug == true)
  646. std::clog << "(parsed from dpkg) pkg: " << short_pkgname
  647. << " action: " << action << " (expected: '" << next_action << "' "
  648. << PackageOpsDone[pkg] << " of " << states.size() << ")" << endl;
  649. // check if the package moved to the next dpkg state
  650. if(next_action && (action == next_action))
  651. {
  652. // only read the translation if there is actually a next action
  653. char const * const translation = _(states[PackageOpsDone[pkg]].str);
  654. // we moved from one dpkg state to a new one, report that
  655. ++PackageOpsDone[pkg];
  656. ++PackagesDone;
  657. std::string msg;
  658. strprintf(msg, translation, i18n_pkgname.c_str());
  659. d->progress->StatusChanged(pkgname, PackagesDone, PackagesTotal, msg);
  660. }
  661. }
  662. }
  663. }
  664. /*}}}*/
  665. // DPkgPM::handleDisappearAction /*{{{*/
  666. void pkgDPkgPM::handleDisappearAction(string const &pkgname)
  667. {
  668. pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
  669. if (unlikely(Pkg.end() == true))
  670. return;
  671. // record the package name for display and stuff later
  672. disappearedPkgs.insert(Pkg.FullName(true));
  673. // the disappeared package was auto-installed - nothing to do
  674. if ((Cache[Pkg].Flags & pkgCache::Flag::Auto) == pkgCache::Flag::Auto)
  675. return;
  676. pkgCache::VerIterator PkgVer = Cache[Pkg].InstVerIter(Cache);
  677. if (unlikely(PkgVer.end() == true))
  678. return;
  679. /* search in the list of dependencies for (Pre)Depends,
  680. check if this dependency has a Replaces on our package
  681. and if so transfer the manual installed flag to it */
  682. for (pkgCache::DepIterator Dep = PkgVer.DependsList(); Dep.end() != true; ++Dep)
  683. {
  684. if (Dep->Type != pkgCache::Dep::Depends &&
  685. Dep->Type != pkgCache::Dep::PreDepends)
  686. continue;
  687. pkgCache::PkgIterator Tar = Dep.TargetPkg();
  688. if (unlikely(Tar.end() == true))
  689. continue;
  690. // the package is already marked as manual
  691. if ((Cache[Tar].Flags & pkgCache::Flag::Auto) != pkgCache::Flag::Auto)
  692. continue;
  693. pkgCache::VerIterator TarVer = Cache[Tar].InstVerIter(Cache);
  694. if (TarVer.end() == true)
  695. continue;
  696. for (pkgCache::DepIterator Rep = TarVer.DependsList(); Rep.end() != true; ++Rep)
  697. {
  698. if (Rep->Type != pkgCache::Dep::Replaces)
  699. continue;
  700. if (Pkg != Rep.TargetPkg())
  701. continue;
  702. // okay, they are strongly connected - transfer manual-bit
  703. if (Debug == true)
  704. std::clog << "transfer manual-bit from disappeared »" << pkgname << "« to »" << Tar.FullName() << "«" << std::endl;
  705. Cache[Tar].Flags &= ~Flag::Auto;
  706. break;
  707. }
  708. }
  709. }
  710. /*}}}*/
  711. // DPkgPM::DoDpkgStatusFd /*{{{*/
  712. // ---------------------------------------------------------------------
  713. /*
  714. */
  715. void pkgDPkgPM::DoDpkgStatusFd(int statusfd)
  716. {
  717. char *p, *q;
  718. int len;
  719. len=read(statusfd, &d->dpkgbuf[d->dpkgbuf_pos], sizeof(d->dpkgbuf)-d->dpkgbuf_pos);
  720. d->dpkgbuf_pos += len;
  721. if(len <= 0)
  722. return;
  723. // process line by line if we have a buffer
  724. p = q = d->dpkgbuf;
  725. while((q=(char*)memchr(p, '\n', d->dpkgbuf+d->dpkgbuf_pos-p)) != NULL)
  726. {
  727. *q = 0;
  728. ProcessDpkgStatusLine(p);
  729. p=q+1; // continue with next line
  730. }
  731. // now move the unprocessed bits (after the final \n that is now a 0x0)
  732. // to the start and update d->dpkgbuf_pos
  733. p = (char*)memrchr(d->dpkgbuf, 0, d->dpkgbuf_pos);
  734. if(p == NULL)
  735. return;
  736. // we are interessted in the first char *after* 0x0
  737. p++;
  738. // move the unprocessed tail to the start and update pos
  739. memmove(d->dpkgbuf, p, p-d->dpkgbuf);
  740. d->dpkgbuf_pos = d->dpkgbuf+d->dpkgbuf_pos-p;
  741. }
  742. /*}}}*/
  743. // DPkgPM::WriteHistoryTag /*{{{*/
  744. void pkgDPkgPM::WriteHistoryTag(string const &tag, string value)
  745. {
  746. size_t const length = value.length();
  747. if (length == 0)
  748. return;
  749. // poor mans rstrip(", ")
  750. if (value[length-2] == ',' && value[length-1] == ' ')
  751. value.erase(length - 2, 2);
  752. fprintf(d->history_out, "%s: %s\n", tag.c_str(), value.c_str());
  753. } /*}}}*/
  754. // DPkgPM::OpenLog /*{{{*/
  755. bool pkgDPkgPM::OpenLog()
  756. {
  757. string const logdir = _config->FindDir("Dir::Log");
  758. if(CreateAPTDirectoryIfNeeded(logdir, logdir) == false)
  759. // FIXME: use a better string after freeze
  760. return _error->Error(_("Directory '%s' missing"), logdir.c_str());
  761. // get current time
  762. char timestr[200];
  763. time_t const t = time(NULL);
  764. struct tm const * const tmp = localtime(&t);
  765. strftime(timestr, sizeof(timestr), "%F %T", tmp);
  766. // open terminal log
  767. string const logfile_name = flCombine(logdir,
  768. _config->Find("Dir::Log::Terminal"));
  769. if (!logfile_name.empty())
  770. {
  771. d->term_out = fopen(logfile_name.c_str(),"a");
  772. if (d->term_out == NULL)
  773. return _error->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name.c_str());
  774. setvbuf(d->term_out, NULL, _IONBF, 0);
  775. SetCloseExec(fileno(d->term_out), true);
  776. if (getuid() == 0) // if we aren't root, we can't chown a file, so don't try it
  777. {
  778. struct passwd *pw = getpwnam("root");
  779. struct group *gr = getgrnam("adm");
  780. if (pw != NULL && gr != NULL && chown(logfile_name.c_str(), pw->pw_uid, gr->gr_gid) != 0)
  781. _error->WarningE("OpenLog", "chown to root:adm of file %s failed", logfile_name.c_str());
  782. }
  783. if (chmod(logfile_name.c_str(), 0640) != 0)
  784. _error->WarningE("OpenLog", "chmod 0640 of file %s failed", logfile_name.c_str());
  785. fprintf(d->term_out, "\nLog started: %s\n", timestr);
  786. }
  787. // write your history
  788. string const history_name = flCombine(logdir,
  789. _config->Find("Dir::Log::History"));
  790. if (!history_name.empty())
  791. {
  792. d->history_out = fopen(history_name.c_str(),"a");
  793. if (d->history_out == NULL)
  794. return _error->WarningE("OpenLog", _("Could not open file '%s'"), history_name.c_str());
  795. SetCloseExec(fileno(d->history_out), true);
  796. chmod(history_name.c_str(), 0644);
  797. fprintf(d->history_out, "\nStart-Date: %s\n", timestr);
  798. string remove, purge, install, reinstall, upgrade, downgrade;
  799. for (pkgCache::PkgIterator I = Cache.PkgBegin(); I.end() == false; ++I)
  800. {
  801. enum { CANDIDATE, CANDIDATE_AUTO, CURRENT_CANDIDATE, CURRENT } infostring;
  802. string *line = NULL;
  803. #define HISTORYINFO(X, Y) { line = &X; infostring = Y; }
  804. if (Cache[I].NewInstall() == true)
  805. HISTORYINFO(install, CANDIDATE_AUTO)
  806. else if (Cache[I].ReInstall() == true)
  807. HISTORYINFO(reinstall, CANDIDATE)
  808. else if (Cache[I].Upgrade() == true)
  809. HISTORYINFO(upgrade, CURRENT_CANDIDATE)
  810. else if (Cache[I].Downgrade() == true)
  811. HISTORYINFO(downgrade, CURRENT_CANDIDATE)
  812. else if (Cache[I].Delete() == true)
  813. HISTORYINFO((Cache[I].Purge() ? purge : remove), CURRENT)
  814. else
  815. continue;
  816. #undef HISTORYINFO
  817. line->append(I.FullName(false)).append(" (");
  818. switch (infostring) {
  819. case CANDIDATE: line->append(Cache[I].CandVersion); break;
  820. case CANDIDATE_AUTO:
  821. line->append(Cache[I].CandVersion);
  822. if ((Cache[I].Flags & pkgCache::Flag::Auto) == pkgCache::Flag::Auto)
  823. line->append(", automatic");
  824. break;
  825. case CURRENT_CANDIDATE: line->append(Cache[I].CurVersion).append(", ").append(Cache[I].CandVersion); break;
  826. case CURRENT: line->append(Cache[I].CurVersion); break;
  827. }
  828. line->append("), ");
  829. }
  830. if (_config->Exists("Commandline::AsString") == true)
  831. WriteHistoryTag("Commandline", _config->Find("Commandline::AsString"));
  832. WriteHistoryTag("Install", install);
  833. WriteHistoryTag("Reinstall", reinstall);
  834. WriteHistoryTag("Upgrade", upgrade);
  835. WriteHistoryTag("Downgrade",downgrade);
  836. WriteHistoryTag("Remove",remove);
  837. WriteHistoryTag("Purge",purge);
  838. fflush(d->history_out);
  839. }
  840. return true;
  841. }
  842. /*}}}*/
  843. // DPkg::CloseLog /*{{{*/
  844. bool pkgDPkgPM::CloseLog()
  845. {
  846. char timestr[200];
  847. time_t t = time(NULL);
  848. struct tm *tmp = localtime(&t);
  849. strftime(timestr, sizeof(timestr), "%F %T", tmp);
  850. if(d->term_out)
  851. {
  852. fprintf(d->term_out, "Log ended: ");
  853. fprintf(d->term_out, "%s", timestr);
  854. fprintf(d->term_out, "\n");
  855. fclose(d->term_out);
  856. }
  857. d->term_out = NULL;
  858. if(d->history_out)
  859. {
  860. if (disappearedPkgs.empty() == false)
  861. {
  862. string disappear;
  863. for (std::set<std::string>::const_iterator d = disappearedPkgs.begin();
  864. d != disappearedPkgs.end(); ++d)
  865. {
  866. pkgCache::PkgIterator P = Cache.FindPkg(*d);
  867. disappear.append(*d);
  868. if (P.end() == true)
  869. disappear.append(", ");
  870. else
  871. disappear.append(" (").append(Cache[P].CurVersion).append("), ");
  872. }
  873. WriteHistoryTag("Disappeared", disappear);
  874. }
  875. if (d->dpkg_error.empty() == false)
  876. fprintf(d->history_out, "Error: %s\n", d->dpkg_error.c_str());
  877. fprintf(d->history_out, "End-Date: %s\n", timestr);
  878. fclose(d->history_out);
  879. }
  880. d->history_out = NULL;
  881. return true;
  882. }
  883. /*}}}*/
  884. /*}}}*/
  885. /*{{{*/
  886. // This implements a racy version of pselect for those architectures
  887. // that don't have a working implementation.
  888. // FIXME: Probably can be removed on Lenny+1
  889. static int racy_pselect(int nfds, fd_set *readfds, fd_set *writefds,
  890. fd_set *exceptfds, const struct timespec *timeout,
  891. const sigset_t *sigmask)
  892. {
  893. sigset_t origmask;
  894. struct timeval tv;
  895. int retval;
  896. tv.tv_sec = timeout->tv_sec;
  897. tv.tv_usec = timeout->tv_nsec/1000;
  898. sigprocmask(SIG_SETMASK, sigmask, &origmask);
  899. retval = select(nfds, readfds, writefds, exceptfds, &tv);
  900. sigprocmask(SIG_SETMASK, &origmask, 0);
  901. return retval;
  902. }
  903. /*}}}*/
  904. // DPkgPM::BuildPackagesProgressMap /*{{{*/
  905. void pkgDPkgPM::BuildPackagesProgressMap()
  906. {
  907. // map the dpkg states to the operations that are performed
  908. // (this is sorted in the same way as Item::Ops)
  909. static const struct DpkgState DpkgStatesOpMap[][7] = {
  910. // Install operation
  911. {
  912. {"half-installed", N_("Preparing %s")},
  913. {"unpacked", N_("Unpacking %s") },
  914. {NULL, NULL}
  915. },
  916. // Configure operation
  917. {
  918. {"unpacked",N_("Preparing to configure %s") },
  919. {"half-configured", N_("Configuring %s") },
  920. { "installed", N_("Installed %s")},
  921. {NULL, NULL}
  922. },
  923. // Remove operation
  924. {
  925. {"half-configured", N_("Preparing for removal of %s")},
  926. {"half-installed", N_("Removing %s")},
  927. {"config-files", N_("Removed %s")},
  928. {NULL, NULL}
  929. },
  930. // Purge operation
  931. {
  932. {"config-files", N_("Preparing to completely remove %s")},
  933. {"not-installed", N_("Completely removed %s")},
  934. {NULL, NULL}
  935. },
  936. };
  937. // init the PackageOps map, go over the list of packages that
  938. // that will be [installed|configured|removed|purged] and add
  939. // them to the PackageOps map (the dpkg states it goes through)
  940. // and the PackageOpsTranslations (human readable strings)
  941. for (vector<Item>::const_iterator I = List.begin(); I != List.end(); ++I)
  942. {
  943. if((*I).Pkg.end() == true)
  944. continue;
  945. string const name = (*I).Pkg.FullName();
  946. PackageOpsDone[name] = 0;
  947. for(int i=0; (DpkgStatesOpMap[(*I).Op][i]).state != NULL; ++i)
  948. {
  949. PackageOps[name].push_back(DpkgStatesOpMap[(*I).Op][i]);
  950. PackagesTotal++;
  951. }
  952. }
  953. /* one extra: We don't want the progress bar to reach 100%, especially not
  954. if we call dpkg --configure --pending and process a bunch of triggers
  955. while showing 100%. Also, spindown takes a while, so never reaching 100%
  956. is way more correct than reaching 100% while still doing stuff even if
  957. doing it this way is slightly bending the rules */
  958. ++PackagesTotal;
  959. }
  960. /*}}}*/
  961. #if (APT_PKG_MAJOR >= 4 && APT_PKG_MINOR < 13)
  962. bool pkgDPkgPM::Go(int StatusFd)
  963. {
  964. APT::Progress::PackageManager *progress = NULL;
  965. if (StatusFd == -1)
  966. progress = APT::Progress::PackageManagerProgressFactory();
  967. else
  968. progress = new APT::Progress::PackageManagerProgressFd(StatusFd);
  969. return GoNoABIBreak(progress);
  970. }
  971. #endif
  972. void pkgDPkgPM::StartPtyMagic()
  973. {
  974. if (_config->FindB("Dpkg::Use-Pty", true) == false)
  975. {
  976. d->master = -1;
  977. if (d->slave != NULL)
  978. free(d->slave);
  979. d->slave = NULL;
  980. return;
  981. }
  982. _error->PushToStack();
  983. d->master = posix_openpt(O_RDWR | O_NOCTTY);
  984. if (d->master == -1)
  985. _error->Errno("posix_openpt", _("Can not write log (%s)"), _("Is /dev/pts mounted?"));
  986. else if (unlockpt(d->master) == -1)
  987. _error->Errno("unlockpt", "Unlocking the slave of master fd %d failed!", d->master);
  988. else
  989. {
  990. char const * const slave_name = ptsname(d->master);
  991. if (slave_name == NULL)
  992. _error->Errno("ptsname", "Getting name for slave of master fd %d failed!", d->master);
  993. else
  994. {
  995. d->slave = strdup(slave_name);
  996. if (d->slave == NULL)
  997. _error->Errno("strdup", "Copying name %s for slave of master fd %d failed!", slave_name, d->master);
  998. else if (grantpt(d->master) == -1)
  999. _error->Errno("grantpt", "Granting access to slave %s based on master fd %d failed!", slave_name, d->master);
  1000. else if (tcgetattr(STDIN_FILENO, &d->tt) == 0)
  1001. {
  1002. d->tt_is_valid = true;
  1003. struct termios raw_tt;
  1004. // copy window size of stdout if its a 'good' terminal
  1005. if (tcgetattr(STDOUT_FILENO, &raw_tt) == 0)
  1006. {
  1007. struct winsize win;
  1008. if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) < 0)
  1009. _error->Errno("ioctl", "Getting TIOCGWINSZ from stdout failed!");
  1010. if (ioctl(d->master, TIOCSWINSZ, &win) < 0)
  1011. _error->Errno("ioctl", "Setting TIOCSWINSZ for master fd %d failed!", d->master);
  1012. }
  1013. if (tcsetattr(d->master, TCSANOW, &d->tt) == -1)
  1014. _error->Errno("tcsetattr", "Setting in Start via TCSANOW for master fd %d failed!", d->master);
  1015. raw_tt = d->tt;
  1016. cfmakeraw(&raw_tt);
  1017. raw_tt.c_lflag &= ~ECHO;
  1018. raw_tt.c_lflag |= ISIG;
  1019. // block SIGTTOU during tcsetattr to prevent a hang if
  1020. // the process is a member of the background process group
  1021. // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
  1022. sigemptyset(&d->sigmask);
  1023. sigaddset(&d->sigmask, SIGTTOU);
  1024. sigprocmask(SIG_BLOCK,&d->sigmask, &d->original_sigmask);
  1025. if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw_tt) == -1)
  1026. _error->Errno("tcsetattr", "Setting in Start via TCSAFLUSH for stdin failed!");
  1027. sigprocmask(SIG_SETMASK, &d->original_sigmask, NULL);
  1028. }
  1029. if (d->slave != NULL)
  1030. {
  1031. /* on linux, closing (and later reopening) all references to the slave
  1032. makes the slave a death end, so we open it here to have one open all
  1033. the time. We could use this fd in SetupSlavePtyMagic() for linux, but
  1034. on kfreebsd we get an incorrect ("step like") output then while it has
  1035. no problem with closing all references… so to avoid platform specific
  1036. code here we combine both and be happy once more */
  1037. d->protect_slave_from_dying = open(d->slave, O_RDWR | O_CLOEXEC | O_NOCTTY);
  1038. }
  1039. }
  1040. }
  1041. if (_error->PendingError() == true)
  1042. {
  1043. if (d->master != -1)
  1044. {
  1045. close(d->master);
  1046. d->master = -1;
  1047. }
  1048. if (d->slave != NULL)
  1049. {
  1050. free(d->slave);
  1051. d->slave = NULL;
  1052. }
  1053. _error->DumpErrors(std::cerr);
  1054. }
  1055. _error->RevertToStack();
  1056. }
  1057. void pkgDPkgPM::SetupSlavePtyMagic()
  1058. {
  1059. if(d->master == -1 || d->slave == NULL)
  1060. return;
  1061. if (close(d->master) == -1)
  1062. _error->FatalE("close", "Closing master %d in child failed!", d->master);
  1063. d->master = -1;
  1064. if (setsid() == -1)
  1065. _error->FatalE("setsid", "Starting a new session for child failed!");
  1066. int const slaveFd = open(d->slave, O_RDWR | O_NOCTTY);
  1067. if (slaveFd == -1)
  1068. _error->FatalE("open", _("Can not write log (%s)"), _("Is /dev/pts mounted?"));
  1069. else if (ioctl(slaveFd, TIOCSCTTY, 0) < 0)
  1070. _error->FatalE("ioctl", "Setting TIOCSCTTY for slave fd %d failed!", slaveFd);
  1071. else
  1072. {
  1073. for (unsigned short i = 0; i < 3; ++i)
  1074. if (dup2(slaveFd, i) == -1)
  1075. _error->FatalE("dup2", "Dupping %d to %d in child failed!", slaveFd, i);
  1076. if (d->tt_is_valid == true && tcsetattr(STDIN_FILENO, TCSANOW, &d->tt) < 0)
  1077. _error->FatalE("tcsetattr", "Setting in Setup via TCSANOW for slave fd %d failed!", slaveFd);
  1078. }
  1079. if (slaveFd != -1)
  1080. close(slaveFd);
  1081. }
  1082. void pkgDPkgPM::StopPtyMagic()
  1083. {
  1084. if (d->slave != NULL)
  1085. free(d->slave);
  1086. d->slave = NULL;
  1087. if (d->protect_slave_from_dying != -1)
  1088. {
  1089. close(d->protect_slave_from_dying);
  1090. d->protect_slave_from_dying = -1;
  1091. }
  1092. if(d->master >= 0)
  1093. {
  1094. if (d->tt_is_valid == true && tcsetattr(STDIN_FILENO, TCSAFLUSH, &d->tt) == -1)
  1095. _error->FatalE("tcsetattr", "Setting in Stop via TCSAFLUSH for stdin failed!");
  1096. close(d->master);
  1097. d->master = -1;
  1098. }
  1099. }
  1100. // DPkgPM::Go - Run the sequence /*{{{*/
  1101. // ---------------------------------------------------------------------
  1102. /* This globs the operations and calls dpkg
  1103. *
  1104. * If it is called with a progress object apt will report the install
  1105. * progress to this object. It maps the dpkg states a package goes
  1106. * through to human readable (and i10n-able)
  1107. * names and calculates a percentage for each step.
  1108. */
  1109. #if (APT_PKG_MAJOR >= 4 && APT_PKG_MINOR >= 13)
  1110. bool pkgDPkgPM::Go(APT::Progress::PackageManager *progress)
  1111. #else
  1112. bool pkgDPkgPM::GoNoABIBreak(APT::Progress::PackageManager *progress)
  1113. #endif
  1114. {
  1115. pkgPackageManager::SigINTStop = false;
  1116. d->progress = progress;
  1117. // Generate the base argument list for dpkg
  1118. unsigned long StartSize = 0;
  1119. std::vector<const char *> Args;
  1120. std::string DpkgExecutable = getDpkgExecutable();
  1121. Args.push_back(DpkgExecutable.c_str());
  1122. StartSize += DpkgExecutable.length();
  1123. // Stick in any custom dpkg options
  1124. Configuration::Item const *Opts = _config->Tree("DPkg::Options");
  1125. if (Opts != 0)
  1126. {
  1127. Opts = Opts->Child;
  1128. for (; Opts != 0; Opts = Opts->Next)
  1129. {
  1130. if (Opts->Value.empty() == true)
  1131. continue;
  1132. Args.push_back(Opts->Value.c_str());
  1133. StartSize += Opts->Value.length();
  1134. }
  1135. }
  1136. size_t const BaseArgs = Args.size();
  1137. // we need to detect if we can qualify packages with the architecture or not
  1138. Args.push_back("--assert-multi-arch");
  1139. Args.push_back(NULL);
  1140. pid_t dpkgAssertMultiArch = ExecFork();
  1141. if (dpkgAssertMultiArch == 0)
  1142. {
  1143. dpkgChrootDirectory();
  1144. // redirect everything to the ultimate sink as we only need the exit-status
  1145. int const nullfd = open("/dev/null", O_RDONLY);
  1146. dup2(nullfd, STDIN_FILENO);
  1147. dup2(nullfd, STDOUT_FILENO);
  1148. dup2(nullfd, STDERR_FILENO);
  1149. execvp(Args[0], (char**) &Args[0]);
  1150. _error->WarningE("dpkgGo", "Can't detect if dpkg supports multi-arch!");
  1151. _exit(2);
  1152. }
  1153. fd_set rfds;
  1154. struct timespec tv;
  1155. // FIXME: do we really need this limit when we have MaxArgBytes?
  1156. unsigned int const MaxArgs = _config->FindI("Dpkg::MaxArgs",32*1024);
  1157. // try to figure out the max environment size
  1158. int OSArgMax = sysconf(_SC_ARG_MAX);
  1159. if(OSArgMax < 0)
  1160. OSArgMax = 32*1024;
  1161. OSArgMax -= EnvironmentSize() - 2*1024;
  1162. unsigned int const MaxArgBytes = _config->FindI("Dpkg::MaxArgBytes", OSArgMax);
  1163. bool const NoTriggers = _config->FindB("DPkg::NoTriggers", false);
  1164. if (RunScripts("DPkg::Pre-Invoke") == false)
  1165. return false;
  1166. if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
  1167. return false;
  1168. // support subpressing of triggers processing for special
  1169. // cases like d-i that runs the triggers handling manually
  1170. bool const TriggersPending = _config->FindB("DPkg::TriggersPending", false);
  1171. if (_config->FindB("DPkg::ConfigurePending", true) == true)
  1172. List.push_back(Item(Item::ConfigurePending, PkgIterator()));
  1173. // for the progress
  1174. BuildPackagesProgressMap();
  1175. d->stdin_is_dev_null = false;
  1176. // create log
  1177. OpenLog();
  1178. bool dpkgMultiArch = false;
  1179. if (dpkgAssertMultiArch > 0)
  1180. {
  1181. int Status = 0;
  1182. while (waitpid(dpkgAssertMultiArch, &Status, 0) != dpkgAssertMultiArch)
  1183. {
  1184. if (errno == EINTR)
  1185. continue;
  1186. _error->WarningE("dpkgGo", _("Waited for %s but it wasn't there"), "dpkg --assert-multi-arch");
  1187. break;
  1188. }
  1189. if (WIFEXITED(Status) == true && WEXITSTATUS(Status) == 0)
  1190. dpkgMultiArch = true;
  1191. }
  1192. // start pty magic before the loop
  1193. StartPtyMagic();
  1194. // Tell the progress that its starting and fork dpkg
  1195. d->progress->Start(d->master);
  1196. // this loop is runs once per dpkg operation
  1197. vector<Item>::const_iterator I = List.begin();
  1198. while (I != List.end())
  1199. {
  1200. // Do all actions with the same Op in one run
  1201. vector<Item>::const_iterator J = I;
  1202. if (TriggersPending == true)
  1203. for (; J != List.end(); ++J)
  1204. {
  1205. if (J->Op == I->Op)
  1206. continue;
  1207. if (J->Op != Item::TriggersPending)
  1208. break;
  1209. vector<Item>::const_iterator T = J + 1;
  1210. if (T != List.end() && T->Op == I->Op)
  1211. continue;
  1212. break;
  1213. }
  1214. else
  1215. for (; J != List.end() && J->Op == I->Op; ++J)
  1216. /* nothing */;
  1217. // keep track of allocated strings for multiarch package names
  1218. std::vector<char *> Packages;
  1219. // start with the baseset of arguments
  1220. unsigned long Size = StartSize;
  1221. Args.erase(Args.begin() + BaseArgs, Args.end());
  1222. // Now check if we are within the MaxArgs limit
  1223. //
  1224. // this code below is problematic, because it may happen that
  1225. // the argument list is split in a way that A depends on B
  1226. // and they are in the same "--configure A B" run
  1227. // - with the split they may now be configured in different
  1228. // runs, using Immediate-Configure-All can help prevent this.
  1229. if (J - I > (signed)MaxArgs)
  1230. {
  1231. J = I + MaxArgs;
  1232. unsigned long const size = MaxArgs + 10;
  1233. Args.reserve(size);
  1234. Packages.reserve(size);
  1235. }
  1236. else
  1237. {
  1238. unsigned long const size = (J - I) + 10;
  1239. Args.reserve(size);
  1240. Packages.reserve(size);
  1241. }
  1242. int fd[2];
  1243. if (pipe(fd) != 0)
  1244. return _error->Errno("pipe","Failed to create IPC pipe to dpkg");
  1245. #define ADDARG(X) Args.push_back(X); Size += strlen(X)
  1246. #define ADDARGC(X) Args.push_back(X); Size += sizeof(X) - 1
  1247. ADDARGC("--status-fd");
  1248. char status_fd_buf[20];
  1249. snprintf(status_fd_buf,sizeof(status_fd_buf),"%i", fd[1]);
  1250. ADDARG(status_fd_buf);
  1251. unsigned long const Op = I->Op;
  1252. switch (I->Op)
  1253. {
  1254. case Item::Remove:
  1255. ADDARGC("--force-depends");
  1256. ADDARGC("--force-remove-essential");
  1257. ADDARGC("--remove");
  1258. break;
  1259. case Item::Purge:
  1260. ADDARGC("--force-depends");
  1261. ADDARGC("--force-remove-essential");
  1262. ADDARGC("--purge");
  1263. break;
  1264. case Item::Configure:
  1265. ADDARGC("--configure");
  1266. break;
  1267. case Item::ConfigurePending:
  1268. ADDARGC("--configure");
  1269. ADDARGC("--pending");
  1270. break;
  1271. case Item::TriggersPending:
  1272. ADDARGC("--triggers-only");
  1273. ADDARGC("--pending");
  1274. break;
  1275. case Item::Install:
  1276. ADDARGC("--unpack");
  1277. ADDARGC("--auto-deconfigure");
  1278. break;
  1279. }
  1280. if (NoTriggers == true && I->Op != Item::TriggersPending &&
  1281. I->Op != Item::ConfigurePending)
  1282. {
  1283. ADDARGC("--no-triggers");
  1284. }
  1285. #undef ADDARGC
  1286. // Write in the file or package names
  1287. if (I->Op == Item::Install)
  1288. {
  1289. for (;I != J && Size < MaxArgBytes; ++I)
  1290. {
  1291. if (I->File[0] != '/')
  1292. return _error->Error("Internal Error, Pathname to install is not absolute '%s'",I->File.c_str());
  1293. Args.push_back(I->File.c_str());
  1294. Size += I->File.length();
  1295. }
  1296. }
  1297. else
  1298. {
  1299. string const nativeArch = _config->Find("APT::Architecture");
  1300. unsigned long const oldSize = I->Op == Item::Configure ? Size : 0;
  1301. for (;I != J && Size < MaxArgBytes; ++I)
  1302. {
  1303. if((*I).Pkg.end() == true)
  1304. continue;
  1305. if (I->Op == Item::Configure && disappearedPkgs.find(I->Pkg.FullName(true)) != disappearedPkgs.end())
  1306. continue;
  1307. // We keep this here to allow "smooth" transitions from e.g. multiarch dpkg/ubuntu to dpkg/debian
  1308. if (dpkgMultiArch == false && (I->Pkg.Arch() == nativeArch ||
  1309. strcmp(I->Pkg.Arch(), "all") == 0 ||
  1310. strcmp(I->Pkg.Arch(), "none") == 0))
  1311. {
  1312. char const * const name = I->Pkg.Name();
  1313. ADDARG(name);
  1314. }
  1315. else
  1316. {
  1317. pkgCache::VerIterator PkgVer;
  1318. std::string name = I->Pkg.Name();
  1319. if (Op == Item::Remove || Op == Item::Purge)
  1320. {
  1321. PkgVer = I->Pkg.CurrentVer();
  1322. if(PkgVer.end() == true)
  1323. PkgVer = FindNowVersion(I->Pkg);
  1324. }
  1325. else
  1326. PkgVer = Cache[I->Pkg].InstVerIter(Cache);
  1327. if (strcmp(I->Pkg.Arch(), "none") == 0)
  1328. ; // never arch-qualify a package without an arch
  1329. else if (PkgVer.end() == false)
  1330. name.append(":").append(PkgVer.Arch());
  1331. else
  1332. _error->Warning("Can not find PkgVer for '%s'", name.c_str());
  1333. char * const fullname = strdup(name.c_str());
  1334. Packages.push_back(fullname);
  1335. ADDARG(fullname);
  1336. }
  1337. }
  1338. // skip configure action if all sheduled packages disappeared
  1339. if (oldSize == Size)
  1340. continue;
  1341. }
  1342. #undef ADDARG
  1343. J = I;
  1344. if (_config->FindB("Debug::pkgDPkgPM",false) == true)
  1345. {
  1346. for (std::vector<const char *>::const_iterator a = Args.begin();
  1347. a != Args.end(); ++a)
  1348. clog << *a << ' ';
  1349. clog << endl;
  1350. continue;
  1351. }
  1352. Args.push_back(NULL);
  1353. cout << flush;
  1354. clog << flush;
  1355. cerr << flush;
  1356. /* Mask off sig int/quit. We do this because dpkg also does when
  1357. it forks scripts. What happens is that when you hit ctrl-c it sends
  1358. it to all processes in the group. Since dpkg ignores the signal
  1359. it doesn't die but we do! So we must also ignore it */
  1360. sighandler_t old_SIGQUIT = signal(SIGQUIT,SIG_IGN);
  1361. sighandler_t old_SIGINT = signal(SIGINT,SigINT);
  1362. // Check here for any SIGINT
  1363. if (pkgPackageManager::SigINTStop && (Op == Item::Remove || Op == Item::Purge || Op == Item::Install))
  1364. break;
  1365. // ignore SIGHUP as well (debian #463030)
  1366. sighandler_t old_SIGHUP = signal(SIGHUP,SIG_IGN);
  1367. // now run dpkg
  1368. d->progress->StartDpkg();
  1369. std::set<int> KeepFDs;
  1370. KeepFDs.insert(fd[1]);
  1371. MergeKeepFdsFromConfiguration(KeepFDs);
  1372. pid_t Child = ExecFork(KeepFDs);
  1373. if (Child == 0)
  1374. {
  1375. // This is the child
  1376. SetupSlavePtyMagic();
  1377. close(fd[0]); // close the read end of the pipe
  1378. dpkgChrootDirectory();
  1379. if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
  1380. _exit(100);
  1381. if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
  1382. {
  1383. int Flags;
  1384. int dummy = 0;
  1385. if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
  1386. _exit(100);
  1387. // Discard everything in stdin before forking dpkg
  1388. if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
  1389. _exit(100);
  1390. while (read(STDIN_FILENO,&dummy,1) == 1);
  1391. if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
  1392. _exit(100);
  1393. }
  1394. /* No Job Control Stop Env is a magic dpkg var that prevents it
  1395. from using sigstop */
  1396. putenv((char *)"DPKG_NO_TSTP=yes");
  1397. execvp(Args[0], (char**) &Args[0]);
  1398. cerr << "Could not exec dpkg!" << endl;
  1399. _exit(100);
  1400. }
  1401. // apply ionice
  1402. if (_config->FindB("DPkg::UseIoNice", false) == true)
  1403. ionice(Child);
  1404. // Wait for dpkg
  1405. int Status = 0;
  1406. // we read from dpkg here
  1407. int const _dpkgin = fd[0];
  1408. close(fd[1]); // close the write end of the pipe
  1409. // setups fds
  1410. sigemptyset(&d->sigmask);
  1411. sigprocmask(SIG_BLOCK,&d->sigmask,&d->original_sigmask);
  1412. /* free vectors (and therefore memory) as we don't need the included data anymore */
  1413. for (std::vector<char *>::const_iterator p = Packages.begin();
  1414. p != Packages.end(); ++p)
  1415. free(*p);
  1416. Packages.clear();
  1417. // the result of the waitpid call
  1418. int res;
  1419. int select_ret;
  1420. while ((res=waitpid(Child,&Status, WNOHANG)) != Child) {
  1421. if(res < 0) {
  1422. // FIXME: move this to a function or something, looks ugly here
  1423. // error handling, waitpid returned -1
  1424. if (errno == EINTR)
  1425. continue;
  1426. RunScripts("DPkg::Post-Invoke");
  1427. // Restore sig int/quit
  1428. signal(SIGQUIT,old_SIGQUIT);
  1429. signal(SIGINT,old_SIGINT);
  1430. signal(SIGHUP,old_SIGHUP);
  1431. return _error->Errno("waitpid","Couldn't wait for subprocess");
  1432. }
  1433. // wait for input or output here
  1434. FD_ZERO(&rfds);
  1435. if (d->master >= 0 && !d->stdin_is_dev_null)
  1436. FD_SET(0, &rfds);
  1437. FD_SET(_dpkgin, &rfds);
  1438. if(d->master >= 0)
  1439. FD_SET(d->master, &rfds);
  1440. tv.tv_sec = 0;
  1441. tv.tv_nsec = d->progress->GetPulseInterval();
  1442. select_ret = pselect(max(d->master, _dpkgin)+1, &rfds, NULL, NULL,
  1443. &tv, &d->original_sigmask);
  1444. if (select_ret < 0 && (errno == EINVAL || errno == ENOSYS))
  1445. select_ret = racy_pselect(max(d->master, _dpkgin)+1, &rfds, NULL,
  1446. NULL, &tv, &d->original_sigmask);
  1447. d->progress->Pulse();
  1448. if (select_ret == 0)
  1449. continue;
  1450. else if (select_ret < 0 && errno == EINTR)
  1451. continue;
  1452. else if (select_ret < 0)
  1453. {
  1454. perror("select() returned error");
  1455. continue;
  1456. }
  1457. if(d->master >= 0 && FD_ISSET(d->master, &rfds))
  1458. DoTerminalPty(d->master);
  1459. if(d->master >= 0 && FD_ISSET(0, &rfds))
  1460. DoStdin(d->master);
  1461. if(FD_ISSET(_dpkgin, &rfds))
  1462. DoDpkgStatusFd(_dpkgin);
  1463. }
  1464. close(_dpkgin);
  1465. // Restore sig int/quit
  1466. signal(SIGQUIT,old_SIGQUIT);
  1467. signal(SIGINT,old_SIGINT);
  1468. signal(SIGHUP,old_SIGHUP);
  1469. // Check for an error code.
  1470. if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
  1471. {
  1472. // if it was set to "keep-dpkg-runing" then we won't return
  1473. // here but keep the loop going and just report it as a error
  1474. // for later
  1475. bool const stopOnError = _config->FindB("Dpkg::StopOnError",true);
  1476. if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
  1477. strprintf(d->dpkg_error, "Sub-process %s received a segmentation fault.",Args[0]);
  1478. else if (WIFEXITED(Status) != 0)
  1479. strprintf(d->dpkg_error, "Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
  1480. else
  1481. strprintf(d->dpkg_error, "Sub-process %s exited unexpectedly",Args[0]);
  1482. _error->Error("%s", d->dpkg_error.c_str());
  1483. if(stopOnError)
  1484. break;
  1485. }
  1486. }
  1487. // dpkg is done at this point
  1488. d->progress->Stop();
  1489. StopPtyMagic();
  1490. CloseLog();
  1491. if (pkgPackageManager::SigINTStop)
  1492. _error->Warning(_("Operation was interrupted before it could finish"));
  1493. if (RunScripts("DPkg::Post-Invoke") == false)
  1494. return false;
  1495. if (_config->FindB("Debug::pkgDPkgPM",false) == false)
  1496. {
  1497. std::string const oldpkgcache = _config->FindFile("Dir::cache::pkgcache");
  1498. if (oldpkgcache.empty() == false && RealFileExists(oldpkgcache) == true &&
  1499. unlink(oldpkgcache.c_str()) == 0)
  1500. {
  1501. std::string const srcpkgcache = _config->FindFile("Dir::cache::srcpkgcache");
  1502. if (srcpkgcache.empty() == false && RealFileExists(srcpkgcache) == true)
  1503. {
  1504. _error->PushToStack();
  1505. pkgCacheFile CacheFile;
  1506. CacheFile.BuildCaches(NULL, true);
  1507. _error->RevertToStack();
  1508. }
  1509. }
  1510. }
  1511. Cache.writeStateFile(NULL);
  1512. return d->dpkg_error.empty();
  1513. }
  1514. void SigINT(int /*sig*/) {
  1515. pkgPackageManager::SigINTStop = true;
  1516. }
  1517. /*}}}*/
  1518. // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
  1519. // ---------------------------------------------------------------------
  1520. /* */
  1521. void pkgDPkgPM::Reset()
  1522. {
  1523. List.erase(List.begin(),List.end());
  1524. }
  1525. /*}}}*/
  1526. // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
  1527. // ---------------------------------------------------------------------
  1528. /* */
  1529. void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
  1530. {
  1531. // If apport doesn't exist or isn't installed do nothing
  1532. // This e.g. prevents messages in 'universes' without apport
  1533. pkgCache::PkgIterator apportPkg = Cache.FindPkg("apport");
  1534. if (apportPkg.end() == true || apportPkg->CurrentVer == 0)
  1535. return;
  1536. string pkgname, reportfile, srcpkgname, pkgver, arch;
  1537. string::size_type pos;
  1538. FILE *report;
  1539. if (_config->FindB("Dpkg::ApportFailureReport", true) == false)
  1540. {
  1541. std::clog << "configured to not write apport reports" << std::endl;
  1542. return;
  1543. }
  1544. // only report the first errors
  1545. if(pkgFailures > _config->FindI("APT::Apport::MaxReports", 3))
  1546. {
  1547. std::clog << _("No apport report written because MaxReports is reached already") << std::endl;
  1548. return;
  1549. }
  1550. // check if its not a follow up error
  1551. const char *needle = dgettext("dpkg", "dependency problems - leaving unconfigured");
  1552. if(strstr(errormsg, needle) != NULL) {
  1553. std::clog << _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl;
  1554. return;
  1555. }
  1556. // do not report disk-full failures
  1557. if(strstr(errormsg, strerror(ENOSPC)) != NULL) {
  1558. std::clog << _("No apport report written because the error message indicates a disk full error") << std::endl;
  1559. return;
  1560. }
  1561. // do not report out-of-memory failures
  1562. if(strstr(errormsg, strerror(ENOMEM)) != NULL ||
  1563. strstr(errormsg, "failed to allocate memory") != NULL) {
  1564. std::clog << _("No apport report written because the error message indicates a out of memory error") << std::endl;
  1565. return;
  1566. }
  1567. // do not report bugs regarding inaccessible local files
  1568. if(strstr(errormsg, strerror(ENOENT)) != NULL ||
  1569. strstr(errormsg, "cannot access archive") != NULL) {
  1570. std::clog << _("No apport report written because the error message indicates an issue on the local system") << std::endl;
  1571. return;
  1572. }
  1573. // do not report errors encountered when decompressing packages
  1574. if(strstr(errormsg, "--fsys-tarfile returned error exit status 2") != NULL) {
  1575. std::clog << _("No apport report written because the error message indicates an issue on the local system") << std::endl;
  1576. return;
  1577. }
  1578. // do not report dpkg I/O errors, this is a format string, so we compare
  1579. // the prefix and the suffix of the error with the dpkg error message
  1580. vector<string> io_errors;
  1581. io_errors.push_back(string("failed to read"));
  1582. io_errors.push_back(string("failed to write"));
  1583. io_errors.push_back(string("failed to seek"));
  1584. io_errors.push_back(string("unexpected end of file or stream"));
  1585. for (vector<string>::iterator I = io_errors.begin(); I != io_errors.end(); ++I)
  1586. {
  1587. vector<string> list = VectorizeString(dgettext("dpkg", (*I).c_str()), '%');
  1588. if (list.size() > 1) {
  1589. // we need to split %s, VectorizeString only allows char so we need
  1590. // to kill the "s" manually
  1591. if (list[1].size() > 1) {
  1592. list[1].erase(0, 1);
  1593. if(strstr(errormsg, list[0].c_str()) &&
  1594. strstr(errormsg, list[1].c_str())) {
  1595. std::clog << _("No apport report written because the error message indicates a dpkg I/O error") << std::endl;
  1596. return;
  1597. }
  1598. }
  1599. }
  1600. }
  1601. // get the pkgname and reportfile
  1602. pkgname = flNotDir(pkgpath);
  1603. pos = pkgname.find('_');
  1604. if(pos != string::npos)
  1605. pkgname = pkgname.substr(0, pos);
  1606. // find the package versin and source package name
  1607. pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
  1608. if (Pkg.end() == true)
  1609. return;
  1610. pkgCache::VerIterator Ver = Cache.GetCandidateVer(Pkg);
  1611. if (Ver.end() == true)
  1612. return;
  1613. pkgver = Ver.VerStr() == NULL ? "unknown" : Ver.VerStr();
  1614. pkgRecords Recs(Cache);
  1615. pkgRecords::Parser &Parse = Recs.Lookup(Ver.FileList());
  1616. srcpkgname = Parse.SourcePkg();
  1617. if(srcpkgname.empty())
  1618. srcpkgname = pkgname;
  1619. // if the file exists already, we check:
  1620. // - if it was reported already (touched by apport).
  1621. // If not, we do nothing, otherwise
  1622. // we overwrite it. This is the same behaviour as apport
  1623. // - if we have a report with the same pkgversion already
  1624. // then we skip it
  1625. reportfile = flCombine("/var/crash",pkgname+".0.crash");
  1626. if(FileExists(reportfile))
  1627. {
  1628. struct stat buf;
  1629. char strbuf[255];
  1630. // check atime/mtime
  1631. stat(reportfile.c_str(), &buf);
  1632. if(buf.st_mtime > buf.st_atime)
  1633. return;
  1634. // check if the existing report is the same version
  1635. report = fopen(reportfile.c_str(),"r");
  1636. while(fgets(strbuf, sizeof(strbuf), report) != NULL)
  1637. {
  1638. if(strstr(strbuf,"Package:") == strbuf)
  1639. {
  1640. char pkgname[255], version[255];
  1641. if(sscanf(strbuf, "Package: %254s %254s", pkgname, version) == 2)
  1642. if(strcmp(pkgver.c_str(), version) == 0)
  1643. {
  1644. fclose(report);
  1645. return;
  1646. }
  1647. }
  1648. }
  1649. fclose(report);
  1650. }
  1651. // now write the report
  1652. arch = _config->Find("APT::Architecture");
  1653. report = fopen(reportfile.c_str(),"w");
  1654. if(report == NULL)
  1655. return;
  1656. if(_config->FindB("DPkgPM::InitialReportOnly",false) == true)
  1657. chmod(reportfile.c_str(), 0);
  1658. else
  1659. chmod(reportfile.c_str(), 0600);
  1660. fprintf(report, "ProblemType: Package\n");
  1661. fprintf(report, "Architecture: %s\n", arch.c_str());
  1662. time_t now = time(NULL);
  1663. fprintf(report, "Date: %s" , ctime(&now));
  1664. fprintf(report, "Package: %s %s\n", pkgname.c_str(), pkgver.c_str());
  1665. fprintf(report, "SourcePackage: %s\n", srcpkgname.c_str());
  1666. fprintf(report, "ErrorMessage:\n %s\n", errormsg);
  1667. // ensure that the log is flushed
  1668. if(d->term_out)
  1669. fflush(d->term_out);
  1670. // attach terminal log it if we have it
  1671. string logfile_name = _config->FindFile("Dir::Log::Terminal");
  1672. if (!logfile_name.empty())
  1673. {
  1674. FILE *log = NULL;
  1675. fprintf(report, "DpkgTerminalLog:\n");
  1676. log = fopen(logfile_name.c_str(),"r");
  1677. if(log != NULL)
  1678. {
  1679. char buf[1024];
  1680. while( fgets(buf, sizeof(buf), log) != NULL)
  1681. fprintf(report, " %s", buf);
  1682. fprintf(report, " \n");
  1683. fclose(log);
  1684. }
  1685. }
  1686. // attach history log it if we have it
  1687. string histfile_name = _config->FindFile("Dir::Log::History");
  1688. if (!histfile_name.empty())
  1689. {
  1690. fprintf(report, "DpkgHistoryLog:\n");
  1691. FILE* log = fopen(histfile_name.c_str(),"r");
  1692. if(log != NULL)
  1693. {
  1694. char buf[1024];
  1695. while( fgets(buf, sizeof(buf), log) != NULL)
  1696. fprintf(report, " %s", buf);
  1697. fclose(log);
  1698. }
  1699. }
  1700. // log the ordering
  1701. const char *ops_str[] = {"Install", "Configure","Remove","Purge"};
  1702. fprintf(report, "AptOrdering:\n");
  1703. for (vector<Item>::iterator I = List.begin(); I != List.end(); ++I)
  1704. if ((*I).Pkg != NULL)
  1705. fprintf(report, " %s: %s\n", (*I).Pkg.Name(), ops_str[(*I).Op]);
  1706. else
  1707. fprintf(report, " %s: %s\n", "NULL", ops_str[(*I).Op]);
  1708. // attach dmesg log (to learn about segfaults)
  1709. if (FileExists("/bin/dmesg"))
  1710. {
  1711. fprintf(report, "Dmesg:\n");
  1712. FILE *log = popen("/bin/dmesg","r");
  1713. if(log != NULL)
  1714. {
  1715. char buf[1024];
  1716. while( fgets(buf, sizeof(buf), log) != NULL)
  1717. fprintf(report, " %s", buf);
  1718. pclose(log);
  1719. }
  1720. }
  1721. // attach df -l log (to learn about filesystem status)
  1722. if (FileExists("/bin/df"))
  1723. {
  1724. fprintf(report, "Df:\n");
  1725. FILE *log = popen("/bin/df -l","r");
  1726. if(log != NULL)
  1727. {
  1728. char buf[1024];
  1729. while( fgets(buf, sizeof(buf), log) != NULL)
  1730. fprintf(report, " %s", buf);
  1731. pclose(log);
  1732. }
  1733. }
  1734. fclose(report);
  1735. }
  1736. /*}}}*/