dpkgpm.cc 56 KB

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