dpkgpm.cc 46 KB

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