dpkgpm.cc 53 KB

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