dpkgpm.cc 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447
  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 <apt-pkg/dpkgpm.h>
  10. #include <apt-pkg/error.h>
  11. #include <apt-pkg/configuration.h>
  12. #include <apt-pkg/depcache.h>
  13. #include <apt-pkg/pkgrecords.h>
  14. #include <apt-pkg/strutl.h>
  15. #include <apti18n.h>
  16. #include <apt-pkg/fileutl.h>
  17. #include <unistd.h>
  18. #include <stdlib.h>
  19. #include <fcntl.h>
  20. #include <sys/select.h>
  21. #include <sys/stat.h>
  22. #include <sys/types.h>
  23. #include <sys/wait.h>
  24. #include <signal.h>
  25. #include <errno.h>
  26. #include <string.h>
  27. #include <stdio.h>
  28. #include <string.h>
  29. #include <algorithm>
  30. #include <sstream>
  31. #include <map>
  32. #include <termios.h>
  33. #include <unistd.h>
  34. #include <sys/ioctl.h>
  35. #include <pty.h>
  36. #include <config.h>
  37. #include <apti18n.h>
  38. /*}}}*/
  39. using namespace std;
  40. namespace
  41. {
  42. // Maps the dpkg "processing" info to human readable names. Entry 0
  43. // of each array is the key, entry 1 is the value.
  44. const std::pair<const char *, const char *> PackageProcessingOps[] = {
  45. std::make_pair("install", N_("Installing %s")),
  46. std::make_pair("configure", N_("Configuring %s")),
  47. std::make_pair("remove", N_("Removing %s")),
  48. std::make_pair("purge", N_("Completely removing %s")),
  49. std::make_pair("disappear", N_("Noting disappearance of %s")),
  50. std::make_pair("trigproc", N_("Running post-installation trigger %s"))
  51. };
  52. const std::pair<const char *, const char *> * const PackageProcessingOpsBegin = PackageProcessingOps;
  53. const std::pair<const char *, const char *> * const PackageProcessingOpsEnd = PackageProcessingOps + sizeof(PackageProcessingOps) / sizeof(PackageProcessingOps[0]);
  54. // Predicate to test whether an entry in the PackageProcessingOps
  55. // array matches a string.
  56. class MatchProcessingOp
  57. {
  58. const char *target;
  59. public:
  60. MatchProcessingOp(const char *the_target)
  61. : target(the_target)
  62. {
  63. }
  64. bool operator()(const std::pair<const char *, const char *> &pair) const
  65. {
  66. return strcmp(pair.first, target) == 0;
  67. }
  68. };
  69. }
  70. /* helper function to ionice the given PID
  71. there is no C header for ionice yet - just the syscall interface
  72. so we use the binary from util-linux
  73. */
  74. static bool
  75. ionice(int PID)
  76. {
  77. if (!FileExists("/usr/bin/ionice"))
  78. return false;
  79. pid_t Process = ExecFork();
  80. if (Process == 0)
  81. {
  82. char buf[32];
  83. snprintf(buf, sizeof(buf), "-p%d", PID);
  84. const char *Args[4];
  85. Args[0] = "/usr/bin/ionice";
  86. Args[1] = "-c3";
  87. Args[2] = buf;
  88. Args[3] = 0;
  89. execv(Args[0], (char **)Args);
  90. }
  91. return ExecWait(Process, "ionice");
  92. }
  93. // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
  94. // ---------------------------------------------------------------------
  95. /* */
  96. pkgDPkgPM::pkgDPkgPM(pkgDepCache *Cache)
  97. : pkgPackageManager(Cache), dpkgbuf_pos(0),
  98. term_out(NULL), history_out(NULL), PackagesDone(0), PackagesTotal(0)
  99. {
  100. }
  101. /*}}}*/
  102. // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
  103. // ---------------------------------------------------------------------
  104. /* */
  105. pkgDPkgPM::~pkgDPkgPM()
  106. {
  107. }
  108. /*}}}*/
  109. // DPkgPM::Install - Install a package /*{{{*/
  110. // ---------------------------------------------------------------------
  111. /* Add an install operation to the sequence list */
  112. bool pkgDPkgPM::Install(PkgIterator Pkg,string File)
  113. {
  114. if (File.empty() == true || Pkg.end() == true)
  115. return _error->Error("Internal Error, No file name for %s",Pkg.Name());
  116. // If the filename string begins with DPkg::Chroot-Directory, return the
  117. // substr that is within the chroot so dpkg can access it.
  118. string const chrootdir = _config->FindDir("DPkg::Chroot-Directory","/");
  119. if (chrootdir != "/" && File.find(chrootdir) == 0)
  120. {
  121. size_t len = chrootdir.length();
  122. if (chrootdir.at(len - 1) == '/')
  123. len--;
  124. List.push_back(Item(Item::Install,Pkg,File.substr(len)));
  125. }
  126. else
  127. List.push_back(Item(Item::Install,Pkg,File));
  128. return true;
  129. }
  130. /*}}}*/
  131. // DPkgPM::Configure - Configure a package /*{{{*/
  132. // ---------------------------------------------------------------------
  133. /* Add a configure operation to the sequence list */
  134. bool pkgDPkgPM::Configure(PkgIterator Pkg)
  135. {
  136. if (Pkg.end() == true)
  137. return false;
  138. List.push_back(Item(Item::Configure, Pkg));
  139. // Use triggers for config calls if we configure "smart"
  140. // as otherwise Pre-Depends will not be satisfied, see #526774
  141. if (_config->FindB("DPkg::TriggersPending", false) == true)
  142. List.push_back(Item(Item::TriggersPending, PkgIterator()));
  143. return true;
  144. }
  145. /*}}}*/
  146. // DPkgPM::Remove - Remove a package /*{{{*/
  147. // ---------------------------------------------------------------------
  148. /* Add a remove operation to the sequence list */
  149. bool pkgDPkgPM::Remove(PkgIterator Pkg,bool Purge)
  150. {
  151. if (Pkg.end() == true)
  152. return false;
  153. if (Purge == true)
  154. List.push_back(Item(Item::Purge,Pkg));
  155. else
  156. List.push_back(Item(Item::Remove,Pkg));
  157. return true;
  158. }
  159. /*}}}*/
  160. // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
  161. // ---------------------------------------------------------------------
  162. /* This is part of the helper script communication interface, it sends
  163. very complete information down to the other end of the pipe.*/
  164. bool pkgDPkgPM::SendV2Pkgs(FILE *F)
  165. {
  166. fprintf(F,"VERSION 2\n");
  167. /* Write out all of the configuration directives by walking the
  168. configuration tree */
  169. const Configuration::Item *Top = _config->Tree(0);
  170. for (; Top != 0;)
  171. {
  172. if (Top->Value.empty() == false)
  173. {
  174. fprintf(F,"%s=%s\n",
  175. QuoteString(Top->FullTag(),"=\"\n").c_str(),
  176. QuoteString(Top->Value,"\n").c_str());
  177. }
  178. if (Top->Child != 0)
  179. {
  180. Top = Top->Child;
  181. continue;
  182. }
  183. while (Top != 0 && Top->Next == 0)
  184. Top = Top->Parent;
  185. if (Top != 0)
  186. Top = Top->Next;
  187. }
  188. fprintf(F,"\n");
  189. // Write out the package actions in order.
  190. for (vector<Item>::iterator I = List.begin(); I != List.end(); I++)
  191. {
  192. if(I->Pkg.end() == true)
  193. continue;
  194. pkgDepCache::StateCache &S = Cache[I->Pkg];
  195. fprintf(F,"%s ",I->Pkg.Name());
  196. // Current version
  197. if (I->Pkg->CurrentVer == 0)
  198. fprintf(F,"- ");
  199. else
  200. fprintf(F,"%s ",I->Pkg.CurrentVer().VerStr());
  201. // Show the compare operator
  202. // Target version
  203. if (S.InstallVer != 0)
  204. {
  205. int Comp = 2;
  206. if (I->Pkg->CurrentVer != 0)
  207. Comp = S.InstVerIter(Cache).CompareVer(I->Pkg.CurrentVer());
  208. if (Comp < 0)
  209. fprintf(F,"> ");
  210. if (Comp == 0)
  211. fprintf(F,"= ");
  212. if (Comp > 0)
  213. fprintf(F,"< ");
  214. fprintf(F,"%s ",S.InstVerIter(Cache).VerStr());
  215. }
  216. else
  217. fprintf(F,"> - ");
  218. // Show the filename/operation
  219. if (I->Op == Item::Install)
  220. {
  221. // No errors here..
  222. if (I->File[0] != '/')
  223. fprintf(F,"**ERROR**\n");
  224. else
  225. fprintf(F,"%s\n",I->File.c_str());
  226. }
  227. if (I->Op == Item::Configure)
  228. fprintf(F,"**CONFIGURE**\n");
  229. if (I->Op == Item::Remove ||
  230. I->Op == Item::Purge)
  231. fprintf(F,"**REMOVE**\n");
  232. if (ferror(F) != 0)
  233. return false;
  234. }
  235. return true;
  236. }
  237. /*}}}*/
  238. // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
  239. // ---------------------------------------------------------------------
  240. /* This looks for a list of scripts to run from the configuration file
  241. each one is run and is fed on standard input a list of all .deb files
  242. that are due to be installed. */
  243. bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf)
  244. {
  245. Configuration::Item const *Opts = _config->Tree(Cnf);
  246. if (Opts == 0 || Opts->Child == 0)
  247. return true;
  248. Opts = Opts->Child;
  249. unsigned int Count = 1;
  250. for (; Opts != 0; Opts = Opts->Next, Count++)
  251. {
  252. if (Opts->Value.empty() == true)
  253. continue;
  254. // Determine the protocol version
  255. string OptSec = Opts->Value;
  256. string::size_type Pos;
  257. if ((Pos = OptSec.find(' ')) == string::npos || Pos == 0)
  258. Pos = OptSec.length();
  259. OptSec = "DPkg::Tools::Options::" + string(Opts->Value.c_str(),Pos);
  260. unsigned int Version = _config->FindI(OptSec+"::Version",1);
  261. // Create the pipes
  262. int Pipes[2];
  263. if (pipe(Pipes) != 0)
  264. return _error->Errno("pipe","Failed to create IPC pipe to subprocess");
  265. SetCloseExec(Pipes[0],true);
  266. SetCloseExec(Pipes[1],true);
  267. // Purified Fork for running the script
  268. pid_t Process = ExecFork();
  269. if (Process == 0)
  270. {
  271. // Setup the FDs
  272. dup2(Pipes[0],STDIN_FILENO);
  273. SetCloseExec(STDOUT_FILENO,false);
  274. SetCloseExec(STDIN_FILENO,false);
  275. SetCloseExec(STDERR_FILENO,false);
  276. if (_config->FindDir("DPkg::Chroot-Directory","/") != "/")
  277. {
  278. std::cerr << "Chrooting into "
  279. << _config->FindDir("DPkg::Chroot-Directory")
  280. << std::endl;
  281. if (chroot(_config->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
  282. _exit(100);
  283. }
  284. const char *Args[4];
  285. Args[0] = "/bin/sh";
  286. Args[1] = "-c";
  287. Args[2] = Opts->Value.c_str();
  288. Args[3] = 0;
  289. execv(Args[0],(char **)Args);
  290. _exit(100);
  291. }
  292. close(Pipes[0]);
  293. FILE *F = fdopen(Pipes[1],"w");
  294. if (F == 0)
  295. return _error->Errno("fdopen","Faild to open new FD");
  296. // Feed it the filenames.
  297. if (Version <= 1)
  298. {
  299. for (vector<Item>::iterator I = List.begin(); I != List.end(); I++)
  300. {
  301. // Only deal with packages to be installed from .deb
  302. if (I->Op != Item::Install)
  303. continue;
  304. // No errors here..
  305. if (I->File[0] != '/')
  306. continue;
  307. /* Feed the filename of each package that is pending install
  308. into the pipe. */
  309. fprintf(F,"%s\n",I->File.c_str());
  310. if (ferror(F) != 0)
  311. break;
  312. }
  313. }
  314. else
  315. SendV2Pkgs(F);
  316. fclose(F);
  317. // Clean up the sub process
  318. if (ExecWait(Process,Opts->Value.c_str()) == false)
  319. return _error->Error("Failure running script %s",Opts->Value.c_str());
  320. }
  321. return true;
  322. }
  323. /*}}}*/
  324. // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
  325. // ---------------------------------------------------------------------
  326. /*
  327. */
  328. void pkgDPkgPM::DoStdin(int master)
  329. {
  330. unsigned char input_buf[256] = {0,};
  331. ssize_t len = read(0, input_buf, sizeof(input_buf));
  332. if (len)
  333. write(master, input_buf, len);
  334. else
  335. stdin_is_dev_null = true;
  336. }
  337. /*}}}*/
  338. // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
  339. // ---------------------------------------------------------------------
  340. /*
  341. * read the terminal pty and write log
  342. */
  343. void pkgDPkgPM::DoTerminalPty(int master)
  344. {
  345. unsigned char term_buf[1024] = {0,0, };
  346. ssize_t len=read(master, term_buf, sizeof(term_buf));
  347. if(len == -1 && errno == EIO)
  348. {
  349. // this happens when the child is about to exit, we
  350. // give it time to actually exit, otherwise we run
  351. // into a race
  352. usleep(500000);
  353. return;
  354. }
  355. if(len <= 0)
  356. return;
  357. write(1, term_buf, len);
  358. if(term_out)
  359. fwrite(term_buf, len, sizeof(char), term_out);
  360. }
  361. /*}}}*/
  362. // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
  363. // ---------------------------------------------------------------------
  364. /*
  365. */
  366. void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd, char *line)
  367. {
  368. bool const Debug = _config->FindB("Debug::pkgDPkgProgressReporting",false);
  369. // the status we output
  370. ostringstream status;
  371. if (Debug == true)
  372. std::clog << "got from dpkg '" << line << "'" << std::endl;
  373. /* dpkg sends strings like this:
  374. 'status: <pkg>: <pkg qstate>'
  375. errors look like this:
  376. '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
  377. and conffile-prompt like this
  378. 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
  379. Newer versions of dpkg sent also:
  380. 'processing: install: pkg'
  381. 'processing: configure: pkg'
  382. 'processing: remove: pkg'
  383. 'processing: purge: pkg'
  384. 'processing: disappear: pkg'
  385. 'processing: trigproc: trigger'
  386. */
  387. char* list[6];
  388. // dpkg sends multiline error messages sometimes (see
  389. // #374195 for a example. we should support this by
  390. // either patching dpkg to not send multiline over the
  391. // statusfd or by rewriting the code here to deal with
  392. // it. for now we just ignore it and not crash
  393. TokSplitString(':', line, list, sizeof(list)/sizeof(list[0]));
  394. if( list[0] == NULL || list[1] == NULL || list[2] == NULL)
  395. {
  396. if (Debug == true)
  397. std::clog << "ignoring line: not enough ':'" << std::endl;
  398. return;
  399. }
  400. const char* const pkg = list[1];
  401. const char* action = _strstrip(list[2]);
  402. // 'processing' from dpkg looks like
  403. // 'processing: action: pkg'
  404. if(strncmp(list[0], "processing", strlen("processing")) == 0)
  405. {
  406. char s[200];
  407. const char* const pkg_or_trigger = _strstrip(list[2]);
  408. action = _strstrip( list[1]);
  409. const std::pair<const char *, const char *> * const iter =
  410. std::find_if(PackageProcessingOpsBegin,
  411. PackageProcessingOpsEnd,
  412. MatchProcessingOp(action));
  413. if(iter == PackageProcessingOpsEnd)
  414. {
  415. if (Debug == true)
  416. std::clog << "ignoring unknown action: " << action << std::endl;
  417. return;
  418. }
  419. snprintf(s, sizeof(s), _(iter->second), pkg_or_trigger);
  420. status << "pmstatus:" << pkg_or_trigger
  421. << ":" << (PackagesDone/float(PackagesTotal)*100.0)
  422. << ":" << s
  423. << endl;
  424. if(OutStatusFd > 0)
  425. write(OutStatusFd, status.str().c_str(), status.str().size());
  426. if (Debug == true)
  427. std::clog << "send: '" << status.str() << "'" << endl;
  428. if (strncmp(action, "disappear", strlen("disappear")) == 0)
  429. handleDisappearAction(pkg_or_trigger);
  430. return;
  431. }
  432. if(strncmp(action,"error",strlen("error")) == 0)
  433. {
  434. // urgs, sometime has ":" in its error string so that we
  435. // end up with the error message split between list[3]
  436. // and list[4], e.g. the message:
  437. // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
  438. // concat them again
  439. if( list[4] != NULL )
  440. list[3][strlen(list[3])] = ':';
  441. status << "pmerror:" << list[1]
  442. << ":" << (PackagesDone/float(PackagesTotal)*100.0)
  443. << ":" << list[3]
  444. << endl;
  445. if(OutStatusFd > 0)
  446. write(OutStatusFd, status.str().c_str(), status.str().size());
  447. if (Debug == true)
  448. std::clog << "send: '" << status.str() << "'" << endl;
  449. pkgFailures++;
  450. WriteApportReport(list[1], list[3]);
  451. return;
  452. }
  453. else if(strncmp(action,"conffile",strlen("conffile")) == 0)
  454. {
  455. status << "pmconffile:" << list[1]
  456. << ":" << (PackagesDone/float(PackagesTotal)*100.0)
  457. << ":" << list[3]
  458. << endl;
  459. if(OutStatusFd > 0)
  460. write(OutStatusFd, status.str().c_str(), status.str().size());
  461. if (Debug == true)
  462. std::clog << "send: '" << status.str() << "'" << endl;
  463. return;
  464. }
  465. vector<struct DpkgState> const &states = PackageOps[pkg];
  466. const char *next_action = NULL;
  467. if(PackageOpsDone[pkg] < states.size())
  468. next_action = states[PackageOpsDone[pkg]].state;
  469. // check if the package moved to the next dpkg state
  470. if(next_action && (strcmp(action, next_action) == 0))
  471. {
  472. // only read the translation if there is actually a next
  473. // action
  474. const char *translation = _(states[PackageOpsDone[pkg]].str);
  475. char s[200];
  476. snprintf(s, sizeof(s), translation, pkg);
  477. // we moved from one dpkg state to a new one, report that
  478. PackageOpsDone[pkg]++;
  479. PackagesDone++;
  480. // build the status str
  481. status << "pmstatus:" << pkg
  482. << ":" << (PackagesDone/float(PackagesTotal)*100.0)
  483. << ":" << s
  484. << endl;
  485. if(OutStatusFd > 0)
  486. write(OutStatusFd, status.str().c_str(), status.str().size());
  487. if (Debug == true)
  488. std::clog << "send: '" << status.str() << "'" << endl;
  489. }
  490. if (Debug == true)
  491. std::clog << "(parsed from dpkg) pkg: " << pkg
  492. << " action: " << action << endl;
  493. }
  494. /*}}}*/
  495. // DPkgPM::handleDisappearAction /*{{{*/
  496. void pkgDPkgPM::handleDisappearAction(string const &pkgname)
  497. {
  498. // record the package name for display and stuff later
  499. disappearedPkgs.insert(pkgname);
  500. pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
  501. if (unlikely(Pkg.end() == true))
  502. return;
  503. // the disappeared package was auto-installed - nothing to do
  504. if ((Cache[Pkg].Flags & pkgCache::Flag::Auto) == pkgCache::Flag::Auto)
  505. return;
  506. pkgCache::VerIterator PkgVer = Cache[Pkg].InstVerIter(Cache);
  507. if (unlikely(PkgVer.end() == true))
  508. return;
  509. /* search in the list of dependencies for (Pre)Depends,
  510. check if this dependency has a Replaces on our package
  511. and if so transfer the manual installed flag to it */
  512. for (pkgCache::DepIterator Dep = PkgVer.DependsList(); Dep.end() != true; ++Dep)
  513. {
  514. if (Dep->Type != pkgCache::Dep::Depends &&
  515. Dep->Type != pkgCache::Dep::PreDepends)
  516. continue;
  517. pkgCache::PkgIterator Tar = Dep.TargetPkg();
  518. if (unlikely(Tar.end() == true))
  519. continue;
  520. // the package is already marked as manual
  521. if ((Cache[Tar].Flags & pkgCache::Flag::Auto) != pkgCache::Flag::Auto)
  522. continue;
  523. pkgCache::VerIterator TarVer = Cache[Tar].InstVerIter(Cache);
  524. if (TarVer.end() == true)
  525. continue;
  526. for (pkgCache::DepIterator Rep = TarVer.DependsList(); Rep.end() != true; ++Rep)
  527. {
  528. if (Rep->Type != pkgCache::Dep::Replaces)
  529. continue;
  530. if (Pkg != Rep.TargetPkg())
  531. continue;
  532. // okay, they are strongly connected - transfer manual-bit
  533. if (Debug == true)
  534. std::clog << "transfer manual-bit from disappeared »" << pkgname << "« to »" << Tar.FullName() << "«" << std::endl;
  535. Cache[Tar].Flags &= ~Flag::Auto;
  536. break;
  537. }
  538. }
  539. }
  540. /*}}}*/
  541. // DPkgPM::DoDpkgStatusFd /*{{{*/
  542. // ---------------------------------------------------------------------
  543. /*
  544. */
  545. void pkgDPkgPM::DoDpkgStatusFd(int statusfd, int OutStatusFd)
  546. {
  547. char *p, *q;
  548. int len;
  549. len=read(statusfd, &dpkgbuf[dpkgbuf_pos], sizeof(dpkgbuf)-dpkgbuf_pos);
  550. dpkgbuf_pos += len;
  551. if(len <= 0)
  552. return;
  553. // process line by line if we have a buffer
  554. p = q = dpkgbuf;
  555. while((q=(char*)memchr(p, '\n', dpkgbuf+dpkgbuf_pos-p)) != NULL)
  556. {
  557. *q = 0;
  558. ProcessDpkgStatusLine(OutStatusFd, p);
  559. p=q+1; // continue with next line
  560. }
  561. // now move the unprocessed bits (after the final \n that is now a 0x0)
  562. // to the start and update dpkgbuf_pos
  563. p = (char*)memrchr(dpkgbuf, 0, dpkgbuf_pos);
  564. if(p == NULL)
  565. return;
  566. // we are interessted in the first char *after* 0x0
  567. p++;
  568. // move the unprocessed tail to the start and update pos
  569. memmove(dpkgbuf, p, p-dpkgbuf);
  570. dpkgbuf_pos = dpkgbuf+dpkgbuf_pos-p;
  571. }
  572. /*}}}*/
  573. // DPkgPM::WriteHistoryTag /*{{{*/
  574. void pkgDPkgPM::WriteHistoryTag(string const &tag, string value)
  575. {
  576. size_t const length = value.length();
  577. if (length == 0)
  578. return;
  579. // poor mans rstrip(", ")
  580. if (value[length-2] == ',' && value[length-1] == ' ')
  581. value.erase(length - 2, 2);
  582. fprintf(history_out, "%s: %s\n", tag.c_str(), value.c_str());
  583. } /*}}}*/
  584. // DPkgPM::OpenLog /*{{{*/
  585. bool pkgDPkgPM::OpenLog()
  586. {
  587. string const logdir = _config->FindDir("Dir::Log");
  588. if(CreateAPTDirectoryIfNeeded(logdir, logdir) == false)
  589. // FIXME: use a better string after freeze
  590. return _error->Error(_("Directory '%s' missing"), logdir.c_str());
  591. // get current time
  592. char timestr[200];
  593. time_t const t = time(NULL);
  594. struct tm const * const tmp = localtime(&t);
  595. strftime(timestr, sizeof(timestr), "%F %T", tmp);
  596. // open terminal log
  597. string const logfile_name = flCombine(logdir,
  598. _config->Find("Dir::Log::Terminal"));
  599. if (!logfile_name.empty())
  600. {
  601. term_out = fopen(logfile_name.c_str(),"a");
  602. if (term_out == NULL)
  603. return _error->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name.c_str());
  604. setvbuf(term_out, NULL, _IONBF, 0);
  605. SetCloseExec(fileno(term_out), true);
  606. chmod(logfile_name.c_str(), 0600);
  607. fprintf(term_out, "\nLog started: %s\n", timestr);
  608. }
  609. // write your history
  610. string const history_name = flCombine(logdir,
  611. _config->Find("Dir::Log::History"));
  612. if (!history_name.empty())
  613. {
  614. history_out = fopen(history_name.c_str(),"a");
  615. if (history_out == NULL)
  616. return _error->WarningE("OpenLog", _("Could not open file '%s'"), history_name.c_str());
  617. chmod(history_name.c_str(), 0644);
  618. fprintf(history_out, "\nStart-Date: %s\n", timestr);
  619. string remove, purge, install, upgrade, downgrade;
  620. for (pkgCache::PkgIterator I = Cache.PkgBegin(); I.end() == false; I++)
  621. {
  622. if (Cache[I].NewInstall())
  623. {
  624. install += I.FullName(false) + string(" (") + Cache[I].CandVersion;
  625. if (Cache[I].Flags & pkgCache::Flag::Auto)
  626. install+= ", automatic";
  627. install += string("), ");
  628. }
  629. else if (Cache[I].Upgrade())
  630. upgrade += I.FullName(false) + string(" (") + Cache[I].CurVersion + string(", ") + Cache[I].CandVersion + string("), ");
  631. else if (Cache[I].Downgrade())
  632. downgrade += I.FullName(false) + string(" (") + Cache[I].CurVersion + string(", ") + Cache[I].CandVersion + string("), ");
  633. else if (Cache[I].Delete())
  634. {
  635. if ((Cache[I].iFlags & pkgDepCache::Purge) == pkgDepCache::Purge)
  636. purge += I.FullName(false) + string(" (") + Cache[I].CurVersion + string("), ");
  637. else
  638. remove += I.FullName(false) + string(" (") + Cache[I].CurVersion + string("), ");
  639. }
  640. }
  641. if (_config->Exists("Commandline::AsString") == true)
  642. WriteHistoryTag("Commandline", _config->Find("Commandline::AsString"));
  643. WriteHistoryTag("Install", install);
  644. WriteHistoryTag("Upgrade", upgrade);
  645. WriteHistoryTag("Downgrade",downgrade);
  646. WriteHistoryTag("Remove",remove);
  647. WriteHistoryTag("Purge",purge);
  648. fflush(history_out);
  649. }
  650. return true;
  651. }
  652. /*}}}*/
  653. // DPkg::CloseLog /*{{{*/
  654. bool pkgDPkgPM::CloseLog()
  655. {
  656. char timestr[200];
  657. time_t t = time(NULL);
  658. struct tm *tmp = localtime(&t);
  659. strftime(timestr, sizeof(timestr), "%F %T", tmp);
  660. if(term_out)
  661. {
  662. fprintf(term_out, "Log ended: ");
  663. fprintf(term_out, "%s", timestr);
  664. fprintf(term_out, "\n");
  665. fclose(term_out);
  666. }
  667. term_out = NULL;
  668. if(history_out)
  669. {
  670. if (disappearedPkgs.empty() == false)
  671. {
  672. string disappear;
  673. for (std::set<std::string>::const_iterator d = disappearedPkgs.begin();
  674. d != disappearedPkgs.end(); ++d)
  675. {
  676. pkgCache::PkgIterator P = Cache.FindPkg(*d);
  677. disappear.append(*d);
  678. if (P.end() == true)
  679. disappear.append(", ");
  680. else
  681. disappear.append(" (").append(Cache[P].CurVersion).append("), ");
  682. }
  683. WriteHistoryTag("Disappeared", disappear);
  684. }
  685. if (dpkg_error.empty() == false)
  686. fprintf(history_out, "Error: %s\n", dpkg_error.c_str());
  687. fprintf(history_out, "End-Date: %s\n", timestr);
  688. fclose(history_out);
  689. }
  690. history_out = NULL;
  691. return true;
  692. }
  693. /*}}}*/
  694. /*{{{*/
  695. // This implements a racy version of pselect for those architectures
  696. // that don't have a working implementation.
  697. // FIXME: Probably can be removed on Lenny+1
  698. static int racy_pselect(int nfds, fd_set *readfds, fd_set *writefds,
  699. fd_set *exceptfds, const struct timespec *timeout,
  700. const sigset_t *sigmask)
  701. {
  702. sigset_t origmask;
  703. struct timeval tv;
  704. int retval;
  705. tv.tv_sec = timeout->tv_sec;
  706. tv.tv_usec = timeout->tv_nsec/1000;
  707. sigprocmask(SIG_SETMASK, sigmask, &origmask);
  708. retval = select(nfds, readfds, writefds, exceptfds, &tv);
  709. sigprocmask(SIG_SETMASK, &origmask, 0);
  710. return retval;
  711. }
  712. /*}}}*/
  713. // DPkgPM::Go - Run the sequence /*{{{*/
  714. // ---------------------------------------------------------------------
  715. /* This globs the operations and calls dpkg
  716. *
  717. * If it is called with "OutStatusFd" set to a valid file descriptor
  718. * apt will report the install progress over this fd. It maps the
  719. * dpkg states a package goes through to human readable (and i10n-able)
  720. * names and calculates a percentage for each step.
  721. */
  722. bool pkgDPkgPM::Go(int OutStatusFd)
  723. {
  724. fd_set rfds;
  725. struct timespec tv;
  726. sigset_t sigmask;
  727. sigset_t original_sigmask;
  728. unsigned int const MaxArgs = _config->FindI("Dpkg::MaxArgs",8*1024);
  729. unsigned int const MaxArgBytes = _config->FindI("Dpkg::MaxArgBytes",32*1024);
  730. bool const NoTriggers = _config->FindB("DPkg::NoTriggers", false);
  731. if (RunScripts("DPkg::Pre-Invoke") == false)
  732. return false;
  733. if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
  734. return false;
  735. // support subpressing of triggers processing for special
  736. // cases like d-i that runs the triggers handling manually
  737. bool const SmartConf = (_config->Find("PackageManager::Configure", "all") != "all");
  738. bool const TriggersPending = _config->FindB("DPkg::TriggersPending", false);
  739. if (_config->FindB("DPkg::ConfigurePending", SmartConf) == true)
  740. List.push_back(Item(Item::ConfigurePending, PkgIterator()));
  741. // map the dpkg states to the operations that are performed
  742. // (this is sorted in the same way as Item::Ops)
  743. static const struct DpkgState DpkgStatesOpMap[][7] = {
  744. // Install operation
  745. {
  746. {"half-installed", N_("Preparing %s")},
  747. {"unpacked", N_("Unpacking %s") },
  748. {NULL, NULL}
  749. },
  750. // Configure operation
  751. {
  752. {"unpacked",N_("Preparing to configure %s") },
  753. {"half-configured", N_("Configuring %s") },
  754. { "installed", N_("Installed %s")},
  755. {NULL, NULL}
  756. },
  757. // Remove operation
  758. {
  759. {"half-configured", N_("Preparing for removal of %s")},
  760. {"half-installed", N_("Removing %s")},
  761. {"config-files", N_("Removed %s")},
  762. {NULL, NULL}
  763. },
  764. // Purge operation
  765. {
  766. {"config-files", N_("Preparing to completely remove %s")},
  767. {"not-installed", N_("Completely removed %s")},
  768. {NULL, NULL}
  769. },
  770. };
  771. // init the PackageOps map, go over the list of packages that
  772. // that will be [installed|configured|removed|purged] and add
  773. // them to the PackageOps map (the dpkg states it goes through)
  774. // and the PackageOpsTranslations (human readable strings)
  775. for (vector<Item>::const_iterator I = List.begin(); I != List.end();I++)
  776. {
  777. if((*I).Pkg.end() == true)
  778. continue;
  779. string const name = (*I).Pkg.Name();
  780. PackageOpsDone[name] = 0;
  781. for(int i=0; (DpkgStatesOpMap[(*I).Op][i]).state != NULL; i++)
  782. {
  783. PackageOps[name].push_back(DpkgStatesOpMap[(*I).Op][i]);
  784. PackagesTotal++;
  785. }
  786. }
  787. stdin_is_dev_null = false;
  788. // create log
  789. OpenLog();
  790. // this loop is runs once per operation
  791. for (vector<Item>::const_iterator I = List.begin(); I != List.end();)
  792. {
  793. // Do all actions with the same Op in one run
  794. vector<Item>::const_iterator J = I;
  795. if (TriggersPending == true)
  796. for (; J != List.end(); J++)
  797. {
  798. if (J->Op == I->Op)
  799. continue;
  800. if (J->Op != Item::TriggersPending)
  801. break;
  802. vector<Item>::const_iterator T = J + 1;
  803. if (T != List.end() && T->Op == I->Op)
  804. continue;
  805. break;
  806. }
  807. else
  808. for (; J != List.end() && J->Op == I->Op; J++)
  809. /* nothing */;
  810. // Generate the argument list
  811. const char *Args[MaxArgs + 50];
  812. // Now check if we are within the MaxArgs limit
  813. //
  814. // this code below is problematic, because it may happen that
  815. // the argument list is split in a way that A depends on B
  816. // and they are in the same "--configure A B" run
  817. // - with the split they may now be configured in different
  818. // runs
  819. if (J - I > (signed)MaxArgs)
  820. J = I + MaxArgs;
  821. unsigned int n = 0;
  822. unsigned long Size = 0;
  823. string const Tmp = _config->Find("Dir::Bin::dpkg","dpkg");
  824. Args[n++] = Tmp.c_str();
  825. Size += strlen(Args[n-1]);
  826. // Stick in any custom dpkg options
  827. Configuration::Item const *Opts = _config->Tree("DPkg::Options");
  828. if (Opts != 0)
  829. {
  830. Opts = Opts->Child;
  831. for (; Opts != 0; Opts = Opts->Next)
  832. {
  833. if (Opts->Value.empty() == true)
  834. continue;
  835. Args[n++] = Opts->Value.c_str();
  836. Size += Opts->Value.length();
  837. }
  838. }
  839. char status_fd_buf[20];
  840. int fd[2];
  841. pipe(fd);
  842. Args[n++] = "--status-fd";
  843. Size += strlen(Args[n-1]);
  844. snprintf(status_fd_buf,sizeof(status_fd_buf),"%i", fd[1]);
  845. Args[n++] = status_fd_buf;
  846. Size += strlen(Args[n-1]);
  847. switch (I->Op)
  848. {
  849. case Item::Remove:
  850. Args[n++] = "--force-depends";
  851. Size += strlen(Args[n-1]);
  852. Args[n++] = "--force-remove-essential";
  853. Size += strlen(Args[n-1]);
  854. Args[n++] = "--remove";
  855. Size += strlen(Args[n-1]);
  856. break;
  857. case Item::Purge:
  858. Args[n++] = "--force-depends";
  859. Size += strlen(Args[n-1]);
  860. Args[n++] = "--force-remove-essential";
  861. Size += strlen(Args[n-1]);
  862. Args[n++] = "--purge";
  863. Size += strlen(Args[n-1]);
  864. break;
  865. case Item::Configure:
  866. Args[n++] = "--configure";
  867. Size += strlen(Args[n-1]);
  868. break;
  869. case Item::ConfigurePending:
  870. Args[n++] = "--configure";
  871. Size += strlen(Args[n-1]);
  872. Args[n++] = "--pending";
  873. Size += strlen(Args[n-1]);
  874. break;
  875. case Item::TriggersPending:
  876. Args[n++] = "--triggers-only";
  877. Size += strlen(Args[n-1]);
  878. Args[n++] = "--pending";
  879. Size += strlen(Args[n-1]);
  880. break;
  881. case Item::Install:
  882. Args[n++] = "--unpack";
  883. Size += strlen(Args[n-1]);
  884. Args[n++] = "--auto-deconfigure";
  885. Size += strlen(Args[n-1]);
  886. break;
  887. }
  888. if (NoTriggers == true && I->Op != Item::TriggersPending &&
  889. I->Op != Item::ConfigurePending)
  890. {
  891. Args[n++] = "--no-triggers";
  892. Size += strlen(Args[n-1]);
  893. }
  894. // Write in the file or package names
  895. if (I->Op == Item::Install)
  896. {
  897. for (;I != J && Size < MaxArgBytes; I++)
  898. {
  899. if (I->File[0] != '/')
  900. return _error->Error("Internal Error, Pathname to install is not absolute '%s'",I->File.c_str());
  901. Args[n++] = I->File.c_str();
  902. Size += strlen(Args[n-1]);
  903. }
  904. }
  905. else
  906. {
  907. for (;I != J && Size < MaxArgBytes; I++)
  908. {
  909. if((*I).Pkg.end() == true)
  910. continue;
  911. if (I->Op == Item::Configure && disappearedPkgs.find(I->Pkg.Name()) != disappearedPkgs.end())
  912. continue;
  913. Args[n++] = I->Pkg.Name();
  914. Size += strlen(Args[n-1]);
  915. }
  916. }
  917. Args[n] = 0;
  918. J = I;
  919. if (_config->FindB("Debug::pkgDPkgPM",false) == true)
  920. {
  921. for (unsigned int k = 0; k != n; k++)
  922. clog << Args[k] << ' ';
  923. clog << endl;
  924. continue;
  925. }
  926. cout << flush;
  927. clog << flush;
  928. cerr << flush;
  929. /* Mask off sig int/quit. We do this because dpkg also does when
  930. it forks scripts. What happens is that when you hit ctrl-c it sends
  931. it to all processes in the group. Since dpkg ignores the signal
  932. it doesn't die but we do! So we must also ignore it */
  933. sighandler_t old_SIGQUIT = signal(SIGQUIT,SIG_IGN);
  934. sighandler_t old_SIGINT = signal(SIGINT,SIG_IGN);
  935. // ignore SIGHUP as well (debian #463030)
  936. sighandler_t old_SIGHUP = signal(SIGHUP,SIG_IGN);
  937. struct termios tt;
  938. struct winsize win;
  939. int master = -1;
  940. int slave = -1;
  941. // if tcgetattr does not return zero there was a error
  942. // and we do not do any pty magic
  943. if (tcgetattr(0, &tt) == 0)
  944. {
  945. ioctl(0, TIOCGWINSZ, (char *)&win);
  946. if (openpty(&master, &slave, NULL, &tt, &win) < 0)
  947. {
  948. const char *s = _("Can not write log, openpty() "
  949. "failed (/dev/pts not mounted?)\n");
  950. fprintf(stderr, "%s",s);
  951. if(term_out)
  952. fprintf(term_out, "%s",s);
  953. master = slave = -1;
  954. } else {
  955. struct termios rtt;
  956. rtt = tt;
  957. cfmakeraw(&rtt);
  958. rtt.c_lflag &= ~ECHO;
  959. rtt.c_lflag |= ISIG;
  960. // block SIGTTOU during tcsetattr to prevent a hang if
  961. // the process is a member of the background process group
  962. // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
  963. sigemptyset(&sigmask);
  964. sigaddset(&sigmask, SIGTTOU);
  965. sigprocmask(SIG_BLOCK,&sigmask, &original_sigmask);
  966. tcsetattr(0, TCSAFLUSH, &rtt);
  967. sigprocmask(SIG_SETMASK, &original_sigmask, 0);
  968. }
  969. }
  970. // Fork dpkg
  971. pid_t Child;
  972. _config->Set("APT::Keep-Fds::",fd[1]);
  973. // send status information that we are about to fork dpkg
  974. if(OutStatusFd > 0) {
  975. ostringstream status;
  976. status << "pmstatus:dpkg-exec:"
  977. << (PackagesDone/float(PackagesTotal)*100.0)
  978. << ":" << _("Running dpkg")
  979. << endl;
  980. write(OutStatusFd, status.str().c_str(), status.str().size());
  981. }
  982. Child = ExecFork();
  983. // This is the child
  984. if (Child == 0)
  985. {
  986. if(slave >= 0 && master >= 0)
  987. {
  988. setsid();
  989. ioctl(slave, TIOCSCTTY, 0);
  990. close(master);
  991. dup2(slave, 0);
  992. dup2(slave, 1);
  993. dup2(slave, 2);
  994. close(slave);
  995. }
  996. close(fd[0]); // close the read end of the pipe
  997. if (_config->FindDir("DPkg::Chroot-Directory","/") != "/")
  998. {
  999. std::cerr << "Chrooting into "
  1000. << _config->FindDir("DPkg::Chroot-Directory")
  1001. << std::endl;
  1002. if (chroot(_config->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
  1003. _exit(100);
  1004. }
  1005. if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
  1006. _exit(100);
  1007. if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
  1008. {
  1009. int Flags,dummy;
  1010. if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
  1011. _exit(100);
  1012. // Discard everything in stdin before forking dpkg
  1013. if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
  1014. _exit(100);
  1015. while (read(STDIN_FILENO,&dummy,1) == 1);
  1016. if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
  1017. _exit(100);
  1018. }
  1019. /* No Job Control Stop Env is a magic dpkg var that prevents it
  1020. from using sigstop */
  1021. putenv((char *)"DPKG_NO_TSTP=yes");
  1022. execvp(Args[0],(char **)Args);
  1023. cerr << "Could not exec dpkg!" << endl;
  1024. _exit(100);
  1025. }
  1026. // apply ionice
  1027. if (_config->FindB("DPkg::UseIoNice", false) == true)
  1028. ionice(Child);
  1029. // clear the Keep-Fd again
  1030. _config->Clear("APT::Keep-Fds",fd[1]);
  1031. // Wait for dpkg
  1032. int Status = 0;
  1033. // we read from dpkg here
  1034. int const _dpkgin = fd[0];
  1035. close(fd[1]); // close the write end of the pipe
  1036. if(slave > 0)
  1037. close(slave);
  1038. // setups fds
  1039. sigemptyset(&sigmask);
  1040. sigprocmask(SIG_BLOCK,&sigmask,&original_sigmask);
  1041. // the result of the waitpid call
  1042. int res;
  1043. int select_ret;
  1044. while ((res=waitpid(Child,&Status, WNOHANG)) != Child) {
  1045. if(res < 0) {
  1046. // FIXME: move this to a function or something, looks ugly here
  1047. // error handling, waitpid returned -1
  1048. if (errno == EINTR)
  1049. continue;
  1050. RunScripts("DPkg::Post-Invoke");
  1051. // Restore sig int/quit
  1052. signal(SIGQUIT,old_SIGQUIT);
  1053. signal(SIGINT,old_SIGINT);
  1054. signal(SIGHUP,old_SIGHUP);
  1055. return _error->Errno("waitpid","Couldn't wait for subprocess");
  1056. }
  1057. // wait for input or output here
  1058. FD_ZERO(&rfds);
  1059. if (master >= 0 && !stdin_is_dev_null)
  1060. FD_SET(0, &rfds);
  1061. FD_SET(_dpkgin, &rfds);
  1062. if(master >= 0)
  1063. FD_SET(master, &rfds);
  1064. tv.tv_sec = 1;
  1065. tv.tv_nsec = 0;
  1066. select_ret = pselect(max(master, _dpkgin)+1, &rfds, NULL, NULL,
  1067. &tv, &original_sigmask);
  1068. if (select_ret < 0 && (errno == EINVAL || errno == ENOSYS))
  1069. select_ret = racy_pselect(max(master, _dpkgin)+1, &rfds, NULL,
  1070. NULL, &tv, &original_sigmask);
  1071. if (select_ret == 0)
  1072. continue;
  1073. else if (select_ret < 0 && errno == EINTR)
  1074. continue;
  1075. else if (select_ret < 0)
  1076. {
  1077. perror("select() returned error");
  1078. continue;
  1079. }
  1080. if(master >= 0 && FD_ISSET(master, &rfds))
  1081. DoTerminalPty(master);
  1082. if(master >= 0 && FD_ISSET(0, &rfds))
  1083. DoStdin(master);
  1084. if(FD_ISSET(_dpkgin, &rfds))
  1085. DoDpkgStatusFd(_dpkgin, OutStatusFd);
  1086. }
  1087. close(_dpkgin);
  1088. // Restore sig int/quit
  1089. signal(SIGQUIT,old_SIGQUIT);
  1090. signal(SIGINT,old_SIGINT);
  1091. signal(SIGHUP,old_SIGHUP);
  1092. if(master >= 0)
  1093. {
  1094. tcsetattr(0, TCSAFLUSH, &tt);
  1095. close(master);
  1096. }
  1097. // Check for an error code.
  1098. if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
  1099. {
  1100. // if it was set to "keep-dpkg-runing" then we won't return
  1101. // here but keep the loop going and just report it as a error
  1102. // for later
  1103. bool const stopOnError = _config->FindB("Dpkg::StopOnError",true);
  1104. if(stopOnError)
  1105. RunScripts("DPkg::Post-Invoke");
  1106. if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
  1107. strprintf(dpkg_error, "Sub-process %s received a segmentation fault.",Args[0]);
  1108. else if (WIFEXITED(Status) != 0)
  1109. strprintf(dpkg_error, "Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
  1110. else
  1111. strprintf(dpkg_error, "Sub-process %s exited unexpectedly",Args[0]);
  1112. if(dpkg_error.size() > 0)
  1113. _error->Error("%s", dpkg_error.c_str());
  1114. if(stopOnError)
  1115. {
  1116. CloseLog();
  1117. return false;
  1118. }
  1119. }
  1120. }
  1121. CloseLog();
  1122. if (RunScripts("DPkg::Post-Invoke") == false)
  1123. return false;
  1124. Cache.writeStateFile(NULL);
  1125. return true;
  1126. }
  1127. /*}}}*/
  1128. // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
  1129. // ---------------------------------------------------------------------
  1130. /* */
  1131. void pkgDPkgPM::Reset()
  1132. {
  1133. List.erase(List.begin(),List.end());
  1134. }
  1135. /*}}}*/
  1136. // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
  1137. // ---------------------------------------------------------------------
  1138. /* */
  1139. void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
  1140. {
  1141. string pkgname, reportfile, srcpkgname, pkgver, arch;
  1142. string::size_type pos;
  1143. FILE *report;
  1144. if (_config->FindB("Dpkg::ApportFailureReport", false) == false)
  1145. {
  1146. std::clog << "configured to not write apport reports" << std::endl;
  1147. return;
  1148. }
  1149. // only report the first errors
  1150. if(pkgFailures > _config->FindI("APT::Apport::MaxReports", 3))
  1151. {
  1152. std::clog << _("No apport report written because MaxReports is reached already") << std::endl;
  1153. return;
  1154. }
  1155. // check if its not a follow up error
  1156. const char *needle = dgettext("dpkg", "dependency problems - leaving unconfigured");
  1157. if(strstr(errormsg, needle) != NULL) {
  1158. std::clog << _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl;
  1159. return;
  1160. }
  1161. // do not report disk-full failures
  1162. if(strstr(errormsg, strerror(ENOSPC)) != NULL) {
  1163. std::clog << _("No apport report written because the error message indicates a disk full error") << std::endl;
  1164. return;
  1165. }
  1166. // do not report out-of-memory failures
  1167. if(strstr(errormsg, strerror(ENOMEM)) != NULL) {
  1168. std::clog << _("No apport report written because the error message indicates a out of memory error") << std::endl;
  1169. return;
  1170. }
  1171. // do not report dpkg I/O errors
  1172. // XXX - this message is localized, but this only matches the English version. This is better than nothing.
  1173. if(strstr(errormsg, "short read in buffer_copy (")) {
  1174. std::clog << _("No apport report written because the error message indicates a dpkg I/O error") << std::endl;
  1175. return;
  1176. }
  1177. // get the pkgname and reportfile
  1178. pkgname = flNotDir(pkgpath);
  1179. pos = pkgname.find('_');
  1180. if(pos != string::npos)
  1181. pkgname = pkgname.substr(0, pos);
  1182. // find the package versin and source package name
  1183. pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
  1184. if (Pkg.end() == true)
  1185. return;
  1186. pkgCache::VerIterator Ver = Cache.GetCandidateVer(Pkg);
  1187. if (Ver.end() == true)
  1188. return;
  1189. pkgver = Ver.VerStr() == NULL ? "unknown" : Ver.VerStr();
  1190. pkgRecords Recs(Cache);
  1191. pkgRecords::Parser &Parse = Recs.Lookup(Ver.FileList());
  1192. srcpkgname = Parse.SourcePkg();
  1193. if(srcpkgname.empty())
  1194. srcpkgname = pkgname;
  1195. // if the file exists already, we check:
  1196. // - if it was reported already (touched by apport).
  1197. // If not, we do nothing, otherwise
  1198. // we overwrite it. This is the same behaviour as apport
  1199. // - if we have a report with the same pkgversion already
  1200. // then we skip it
  1201. reportfile = flCombine("/var/crash",pkgname+".0.crash");
  1202. if(FileExists(reportfile))
  1203. {
  1204. struct stat buf;
  1205. char strbuf[255];
  1206. // check atime/mtime
  1207. stat(reportfile.c_str(), &buf);
  1208. if(buf.st_mtime > buf.st_atime)
  1209. return;
  1210. // check if the existing report is the same version
  1211. report = fopen(reportfile.c_str(),"r");
  1212. while(fgets(strbuf, sizeof(strbuf), report) != NULL)
  1213. {
  1214. if(strstr(strbuf,"Package:") == strbuf)
  1215. {
  1216. char pkgname[255], version[255];
  1217. if(sscanf(strbuf, "Package: %s %s", pkgname, version) == 2)
  1218. if(strcmp(pkgver.c_str(), version) == 0)
  1219. {
  1220. fclose(report);
  1221. return;
  1222. }
  1223. }
  1224. }
  1225. fclose(report);
  1226. }
  1227. // now write the report
  1228. arch = _config->Find("APT::Architecture");
  1229. report = fopen(reportfile.c_str(),"w");
  1230. if(report == NULL)
  1231. return;
  1232. if(_config->FindB("DPkgPM::InitialReportOnly",false) == true)
  1233. chmod(reportfile.c_str(), 0);
  1234. else
  1235. chmod(reportfile.c_str(), 0600);
  1236. fprintf(report, "ProblemType: Package\n");
  1237. fprintf(report, "Architecture: %s\n", arch.c_str());
  1238. time_t now = time(NULL);
  1239. fprintf(report, "Date: %s" , ctime(&now));
  1240. fprintf(report, "Package: %s %s\n", pkgname.c_str(), pkgver.c_str());
  1241. fprintf(report, "SourcePackage: %s\n", srcpkgname.c_str());
  1242. fprintf(report, "ErrorMessage:\n %s\n", errormsg);
  1243. // ensure that the log is flushed
  1244. if(term_out)
  1245. fflush(term_out);
  1246. // attach terminal log it if we have it
  1247. string logfile_name = _config->FindFile("Dir::Log::Terminal");
  1248. if (!logfile_name.empty())
  1249. {
  1250. FILE *log = NULL;
  1251. char buf[1024];
  1252. fprintf(report, "DpkgTerminalLog:\n");
  1253. log = fopen(logfile_name.c_str(),"r");
  1254. if(log != NULL)
  1255. {
  1256. while( fgets(buf, sizeof(buf), log) != NULL)
  1257. fprintf(report, " %s", buf);
  1258. fclose(log);
  1259. }
  1260. }
  1261. // log the ordering
  1262. const char *ops_str[] = {"Install", "Configure","Remove","Purge"};
  1263. fprintf(report, "AptOrdering:\n");
  1264. for (vector<Item>::iterator I = List.begin(); I != List.end(); I++)
  1265. fprintf(report, " %s: %s\n", (*I).Pkg.Name(), ops_str[(*I).Op]);
  1266. // attach dmesg log (to learn about segfaults)
  1267. if (FileExists("/bin/dmesg"))
  1268. {
  1269. FILE *log = NULL;
  1270. char buf[1024];
  1271. fprintf(report, "Dmesg:\n");
  1272. log = popen("/bin/dmesg","r");
  1273. if(log != NULL)
  1274. {
  1275. while( fgets(buf, sizeof(buf), log) != NULL)
  1276. fprintf(report, " %s", buf);
  1277. pclose(log);
  1278. }
  1279. }
  1280. // attach df -l log (to learn about filesystem status)
  1281. if (FileExists("/bin/df"))
  1282. {
  1283. FILE *log = NULL;
  1284. char buf[1024];
  1285. fprintf(report, "Df:\n");
  1286. log = popen("/bin/df -l","r");
  1287. if(log != NULL)
  1288. {
  1289. while( fgets(buf, sizeof(buf), log) != NULL)
  1290. fprintf(report, " %s", buf);
  1291. pclose(log);
  1292. }
  1293. }
  1294. fclose(report);
  1295. }
  1296. /*}}}*/