dpkgpm.cc 49 KB

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