dpkgpm.cc 50 KB

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