dpkgpm.cc 49 KB

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