dpkgpm.cc 49 KB

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