dpkgpm.cc 52 KB

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