dpkgpm.cc 43 KB

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