dpkgpm.cc 45 KB

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