dpkgpm.cc 51 KB

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