dpkgpm.cc 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850
  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. // the status we output
  469. ostringstream status;
  470. if (Debug == true)
  471. std::clog << "got from dpkg '" << line << "'" << std::endl;
  472. /* dpkg sends strings like this:
  473. 'status: <pkg>: <pkg qstate>'
  474. 'status: <pkg>:<arch>: <pkg qstate>'
  475. errors look like this:
  476. '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
  477. and conffile-prompt like this
  478. 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
  479. Newer versions of dpkg sent also:
  480. 'processing: install: pkg'
  481. 'processing: configure: pkg'
  482. 'processing: remove: pkg'
  483. 'processing: purge: pkg'
  484. 'processing: disappear: pkg'
  485. 'processing: trigproc: trigger'
  486. */
  487. // we need to split on ": " (note the appended space) as the ':' is
  488. // part of the pkgname:arch information that dpkg sends
  489. //
  490. // A dpkg error message may contain additional ":" (like
  491. // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
  492. // so we need to ensure to not split too much
  493. std::vector<std::string> list = StringSplit(line, ": ", 4);
  494. if(list.size() < 3)
  495. {
  496. if (Debug == true)
  497. std::clog << "ignoring line: not enough ':'" << std::endl;
  498. return;
  499. }
  500. // build the (prefix, pkgname, action) tuple, position of this
  501. // is different for "processing" or "status" messages
  502. std::string prefix = APT::String::Strip(list[0]);
  503. std::string pkgname;
  504. std::string action_str;
  505. if (prefix == "processing")
  506. {
  507. pkgname = APT::String::Strip(list[2]);
  508. action_str = APT::String::Strip(list[1]);
  509. }
  510. else if (prefix == "status")
  511. {
  512. pkgname = APT::String::Strip(list[1]);
  513. action_str = APT::String::Strip(list[2]);
  514. } else {
  515. if (Debug == true)
  516. std::clog << "unknown prefix '" << prefix << "'" << std::endl;
  517. return;
  518. }
  519. // FIXME: fix indent once the progress-refactor branch is merged
  520. if (prefix == "status")
  521. {
  522. if(action_str == "error")
  523. {
  524. status << "pmerror:" << list[1]
  525. << ":" << (PackagesDone/float(PackagesTotal)*100.0)
  526. << ":" << list[3]
  527. << endl;
  528. if(OutStatusFd > 0)
  529. FileFd::Write(OutStatusFd, status.str().c_str(), status.str().size());
  530. if (Debug == true)
  531. std::clog << "send: '" << status.str() << "'" << endl;
  532. pkgFailures++;
  533. WriteApportReport(list[1].c_str(), list[3].c_str());
  534. return;
  535. }
  536. else if(action_str == "conffile")
  537. {
  538. status << "pmconffile:" << list[1]
  539. << ":" << (PackagesDone/float(PackagesTotal)*100.0)
  540. << ":" << list[3]
  541. << endl;
  542. if(OutStatusFd > 0)
  543. FileFd::Write(OutStatusFd, status.str().c_str(), status.str().size());
  544. if (Debug == true)
  545. std::clog << "send: '" << status.str() << "'" << endl;
  546. return;
  547. }
  548. }
  549. // dpkg does not send always send "pkgname:arch" so we add it here if needed
  550. if (pkgname.find(":") == std::string::npos)
  551. {
  552. // find the package in the group that is in a touched by dpkg
  553. // if there are multiple dpkg will send us a full pkgname:arch
  554. pkgCache::GrpIterator Grp = Cache.FindGrp(pkgname);
  555. if (Grp.end() == false)
  556. {
  557. pkgCache::PkgIterator P = Grp.PackageList();
  558. for (; P.end() != true; P = Grp.NextPkg(P))
  559. {
  560. if(Cache[P].Mode != pkgDepCache::ModeKeep)
  561. {
  562. pkgname = P.FullName();
  563. break;
  564. }
  565. }
  566. }
  567. }
  568. const char* const pkg = pkgname.c_str();
  569. const char* action = action_str.c_str();
  570. std::string short_pkgname = StringSplit(pkgname, ":")[0];
  571. std::string arch = "";
  572. if (pkgname.find(":") != string::npos)
  573. arch = StringSplit(pkgname, ":")[1];
  574. std::string i18n_pkgname = pkgname;
  575. if (arch.size() != 0)
  576. strprintf(i18n_pkgname, "%s (%s)", short_pkgname.c_str(), arch.c_str());
  577. // 'processing' from dpkg looks like
  578. // 'processing: action: pkg'
  579. if(prefix == "processing")
  580. {
  581. char s[200];
  582. const char* const pkg_or_trigger = list[2].c_str();
  583. action = list[1].c_str();
  584. const std::pair<const char *, const char *> * const iter =
  585. std::find_if(PackageProcessingOpsBegin,
  586. PackageProcessingOpsEnd,
  587. MatchProcessingOp(action));
  588. if(iter == PackageProcessingOpsEnd)
  589. {
  590. if (Debug == true)
  591. std::clog << "ignoring unknown action: " << action << std::endl;
  592. return;
  593. }
  594. snprintf(s, sizeof(s), _(iter->second), pkg_or_trigger);
  595. status << "pmstatus:" << pkg_or_trigger
  596. << ":" << (PackagesDone/float(PackagesTotal)*100.0)
  597. << ":" << s
  598. << endl;
  599. if(OutStatusFd > 0)
  600. FileFd::Write(OutStatusFd, status.str().c_str(), status.str().size());
  601. if (Debug == true)
  602. std::clog << "send: '" << status.str() << "'" << endl;
  603. if (strncmp(action, "disappear", strlen("disappear")) == 0)
  604. handleDisappearAction(pkg_or_trigger);
  605. return;
  606. }
  607. if (prefix == "status")
  608. {
  609. vector<struct DpkgState> const &states = PackageOps[pkg];
  610. const char *next_action = NULL;
  611. if(PackageOpsDone[pkg] < states.size())
  612. next_action = states[PackageOpsDone[pkg]].state;
  613. // check if the package moved to the next dpkg state
  614. if(next_action && (strcmp(action, next_action) == 0))
  615. {
  616. // only read the translation if there is actually a next
  617. // action
  618. const char *translation = _(states[PackageOpsDone[pkg]].str);
  619. char s[200];
  620. snprintf(s, sizeof(s), translation, short_pkgname.c_str());
  621. // we moved from one dpkg state to a new one, report that
  622. PackageOpsDone[pkg]++;
  623. PackagesDone++;
  624. // build the status str
  625. status << "pmstatus:" << short_pkgname
  626. << ":" << (PackagesDone/float(PackagesTotal)*100.0)
  627. << ":" << s
  628. << endl;
  629. if(_config->FindB("DPkgPM::Progress", false) == true)
  630. SendTerminalProgress(PackagesDone/float(PackagesTotal)*100.0);
  631. if(OutStatusFd > 0)
  632. FileFd::Write(OutStatusFd, status.str().c_str(), status.str().size());
  633. if (Debug == true)
  634. std::clog << "send: '" << status.str() << "'" << endl;
  635. }
  636. if (Debug == true)
  637. std::clog << "(parsed from dpkg) pkg: " << short_pkgname
  638. << " action: " << action << endl;
  639. }
  640. }
  641. /*}}}*/
  642. // DPkgPM::handleDisappearAction /*{{{*/
  643. void pkgDPkgPM::handleDisappearAction(string const &pkgname)
  644. {
  645. // record the package name for display and stuff later
  646. disappearedPkgs.insert(pkgname);
  647. pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
  648. if (unlikely(Pkg.end() == true))
  649. return;
  650. // the disappeared package was auto-installed - nothing to do
  651. if ((Cache[Pkg].Flags & pkgCache::Flag::Auto) == pkgCache::Flag::Auto)
  652. return;
  653. pkgCache::VerIterator PkgVer = Cache[Pkg].InstVerIter(Cache);
  654. if (unlikely(PkgVer.end() == true))
  655. return;
  656. /* search in the list of dependencies for (Pre)Depends,
  657. check if this dependency has a Replaces on our package
  658. and if so transfer the manual installed flag to it */
  659. for (pkgCache::DepIterator Dep = PkgVer.DependsList(); Dep.end() != true; ++Dep)
  660. {
  661. if (Dep->Type != pkgCache::Dep::Depends &&
  662. Dep->Type != pkgCache::Dep::PreDepends)
  663. continue;
  664. pkgCache::PkgIterator Tar = Dep.TargetPkg();
  665. if (unlikely(Tar.end() == true))
  666. continue;
  667. // the package is already marked as manual
  668. if ((Cache[Tar].Flags & pkgCache::Flag::Auto) != pkgCache::Flag::Auto)
  669. continue;
  670. pkgCache::VerIterator TarVer = Cache[Tar].InstVerIter(Cache);
  671. if (TarVer.end() == true)
  672. continue;
  673. for (pkgCache::DepIterator Rep = TarVer.DependsList(); Rep.end() != true; ++Rep)
  674. {
  675. if (Rep->Type != pkgCache::Dep::Replaces)
  676. continue;
  677. if (Pkg != Rep.TargetPkg())
  678. continue;
  679. // okay, they are strongly connected - transfer manual-bit
  680. if (Debug == true)
  681. std::clog << "transfer manual-bit from disappeared »" << pkgname << "« to »" << Tar.FullName() << "«" << std::endl;
  682. Cache[Tar].Flags &= ~Flag::Auto;
  683. break;
  684. }
  685. }
  686. }
  687. /*}}}*/
  688. // DPkgPM::DoDpkgStatusFd /*{{{*/
  689. // ---------------------------------------------------------------------
  690. /*
  691. */
  692. void pkgDPkgPM::DoDpkgStatusFd(int statusfd, int OutStatusFd)
  693. {
  694. char *p, *q;
  695. int len;
  696. len=read(statusfd, &d->dpkgbuf[d->dpkgbuf_pos], sizeof(d->dpkgbuf)-d->dpkgbuf_pos);
  697. d->dpkgbuf_pos += len;
  698. if(len <= 0)
  699. return;
  700. // process line by line if we have a buffer
  701. p = q = d->dpkgbuf;
  702. while((q=(char*)memchr(p, '\n', d->dpkgbuf+d->dpkgbuf_pos-p)) != NULL)
  703. {
  704. *q = 0;
  705. ProcessDpkgStatusLine(OutStatusFd, p);
  706. p=q+1; // continue with next line
  707. }
  708. // now move the unprocessed bits (after the final \n that is now a 0x0)
  709. // to the start and update d->dpkgbuf_pos
  710. p = (char*)memrchr(d->dpkgbuf, 0, d->dpkgbuf_pos);
  711. if(p == NULL)
  712. return;
  713. // we are interessted in the first char *after* 0x0
  714. p++;
  715. // move the unprocessed tail to the start and update pos
  716. memmove(d->dpkgbuf, p, p-d->dpkgbuf);
  717. d->dpkgbuf_pos = d->dpkgbuf+d->dpkgbuf_pos-p;
  718. }
  719. /*}}}*/
  720. // DPkgPM::WriteHistoryTag /*{{{*/
  721. void pkgDPkgPM::WriteHistoryTag(string const &tag, string value)
  722. {
  723. size_t const length = value.length();
  724. if (length == 0)
  725. return;
  726. // poor mans rstrip(", ")
  727. if (value[length-2] == ',' && value[length-1] == ' ')
  728. value.erase(length - 2, 2);
  729. fprintf(d->history_out, "%s: %s\n", tag.c_str(), value.c_str());
  730. } /*}}}*/
  731. // DPkgPM::OpenLog /*{{{*/
  732. bool pkgDPkgPM::OpenLog()
  733. {
  734. string const logdir = _config->FindDir("Dir::Log");
  735. if(CreateAPTDirectoryIfNeeded(logdir, logdir) == false)
  736. // FIXME: use a better string after freeze
  737. return _error->Error(_("Directory '%s' missing"), logdir.c_str());
  738. // get current time
  739. char timestr[200];
  740. time_t const t = time(NULL);
  741. struct tm const * const tmp = localtime(&t);
  742. strftime(timestr, sizeof(timestr), "%F %T", tmp);
  743. // open terminal log
  744. string const logfile_name = flCombine(logdir,
  745. _config->Find("Dir::Log::Terminal"));
  746. if (!logfile_name.empty())
  747. {
  748. d->term_out = fopen(logfile_name.c_str(),"a");
  749. if (d->term_out == NULL)
  750. return _error->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name.c_str());
  751. setvbuf(d->term_out, NULL, _IONBF, 0);
  752. SetCloseExec(fileno(d->term_out), true);
  753. if (getuid() == 0) // if we aren't root, we can't chown a file, so don't try it
  754. {
  755. struct passwd *pw = getpwnam("root");
  756. struct group *gr = getgrnam("adm");
  757. if (pw != NULL && gr != NULL && chown(logfile_name.c_str(), pw->pw_uid, gr->gr_gid) != 0)
  758. _error->WarningE("OpenLog", "chown to root:adm of file %s failed", logfile_name.c_str());
  759. }
  760. if (chmod(logfile_name.c_str(), 0640) != 0)
  761. _error->WarningE("OpenLog", "chmod 0640 of file %s failed", logfile_name.c_str());
  762. fprintf(d->term_out, "\nLog started: %s\n", timestr);
  763. }
  764. // write your history
  765. string const history_name = flCombine(logdir,
  766. _config->Find("Dir::Log::History"));
  767. if (!history_name.empty())
  768. {
  769. d->history_out = fopen(history_name.c_str(),"a");
  770. if (d->history_out == NULL)
  771. return _error->WarningE("OpenLog", _("Could not open file '%s'"), history_name.c_str());
  772. SetCloseExec(fileno(d->history_out), true);
  773. chmod(history_name.c_str(), 0644);
  774. fprintf(d->history_out, "\nStart-Date: %s\n", timestr);
  775. string remove, purge, install, reinstall, upgrade, downgrade;
  776. for (pkgCache::PkgIterator I = Cache.PkgBegin(); I.end() == false; ++I)
  777. {
  778. enum { CANDIDATE, CANDIDATE_AUTO, CURRENT_CANDIDATE, CURRENT } infostring;
  779. string *line = NULL;
  780. #define HISTORYINFO(X, Y) { line = &X; infostring = Y; }
  781. if (Cache[I].NewInstall() == true)
  782. HISTORYINFO(install, CANDIDATE_AUTO)
  783. else if (Cache[I].ReInstall() == true)
  784. HISTORYINFO(reinstall, CANDIDATE)
  785. else if (Cache[I].Upgrade() == true)
  786. HISTORYINFO(upgrade, CURRENT_CANDIDATE)
  787. else if (Cache[I].Downgrade() == true)
  788. HISTORYINFO(downgrade, CURRENT_CANDIDATE)
  789. else if (Cache[I].Delete() == true)
  790. HISTORYINFO((Cache[I].Purge() ? purge : remove), CURRENT)
  791. else
  792. continue;
  793. #undef HISTORYINFO
  794. line->append(I.FullName(false)).append(" (");
  795. switch (infostring) {
  796. case CANDIDATE: line->append(Cache[I].CandVersion); break;
  797. case CANDIDATE_AUTO:
  798. line->append(Cache[I].CandVersion);
  799. if ((Cache[I].Flags & pkgCache::Flag::Auto) == pkgCache::Flag::Auto)
  800. line->append(", automatic");
  801. break;
  802. case CURRENT_CANDIDATE: line->append(Cache[I].CurVersion).append(", ").append(Cache[I].CandVersion); break;
  803. case CURRENT: line->append(Cache[I].CurVersion); break;
  804. }
  805. line->append("), ");
  806. }
  807. if (_config->Exists("Commandline::AsString") == true)
  808. WriteHistoryTag("Commandline", _config->Find("Commandline::AsString"));
  809. WriteHistoryTag("Install", install);
  810. WriteHistoryTag("Reinstall", reinstall);
  811. WriteHistoryTag("Upgrade", upgrade);
  812. WriteHistoryTag("Downgrade",downgrade);
  813. WriteHistoryTag("Remove",remove);
  814. WriteHistoryTag("Purge",purge);
  815. fflush(d->history_out);
  816. }
  817. return true;
  818. }
  819. /*}}}*/
  820. // DPkg::CloseLog /*{{{*/
  821. bool pkgDPkgPM::CloseLog()
  822. {
  823. char timestr[200];
  824. time_t t = time(NULL);
  825. struct tm *tmp = localtime(&t);
  826. strftime(timestr, sizeof(timestr), "%F %T", tmp);
  827. if(d->term_out)
  828. {
  829. fprintf(d->term_out, "Log ended: ");
  830. fprintf(d->term_out, "%s", timestr);
  831. fprintf(d->term_out, "\n");
  832. fclose(d->term_out);
  833. }
  834. d->term_out = NULL;
  835. if(d->history_out)
  836. {
  837. if (disappearedPkgs.empty() == false)
  838. {
  839. string disappear;
  840. for (std::set<std::string>::const_iterator d = disappearedPkgs.begin();
  841. d != disappearedPkgs.end(); ++d)
  842. {
  843. pkgCache::PkgIterator P = Cache.FindPkg(*d);
  844. disappear.append(*d);
  845. if (P.end() == true)
  846. disappear.append(", ");
  847. else
  848. disappear.append(" (").append(Cache[P].CurVersion).append("), ");
  849. }
  850. WriteHistoryTag("Disappeared", disappear);
  851. }
  852. if (d->dpkg_error.empty() == false)
  853. fprintf(d->history_out, "Error: %s\n", d->dpkg_error.c_str());
  854. fprintf(d->history_out, "End-Date: %s\n", timestr);
  855. fclose(d->history_out);
  856. }
  857. d->history_out = NULL;
  858. return true;
  859. }
  860. /*}}}*/
  861. // DPkgPM::SendTerminalProgress /*{{{*/
  862. // ---------------------------------------------------------------------
  863. /* Send progress info to the terminal
  864. */
  865. void pkgDPkgPM::SendTerminalProgress(float percentage)
  866. {
  867. int reporting_steps = _config->FindI("DpkgPM::Reporting-Steps", 1);
  868. if(percentage < (d->last_reported_progress + reporting_steps))
  869. return;
  870. std::string progress_str;
  871. strprintf(progress_str, _("Progress: [%3i%%]"), (int)percentage);
  872. if (d->fancy_progress_output)
  873. {
  874. int row = d->nr_terminal_rows;
  875. static string save_cursor = "\033[s";
  876. static string restore_cursor = "\033[u";
  877. static string set_bg_color = "\033[42m"; // green
  878. static string set_fg_color = "\033[30m"; // black
  879. static string restore_bg = "\033[49m";
  880. static string restore_fg = "\033[39m";
  881. std::cout << save_cursor
  882. // move cursor position to last row
  883. << "\033[" << row << ";0f"
  884. << set_bg_color
  885. << set_fg_color
  886. << progress_str
  887. << restore_cursor
  888. << restore_bg
  889. << restore_fg;
  890. }
  891. else
  892. {
  893. std::cout << progress_str << "\r\n";
  894. }
  895. std::flush(std::cout);
  896. d->last_reported_progress = percentage;
  897. }
  898. /*}}}*/
  899. /*{{{*/
  900. // This implements a racy version of pselect for those architectures
  901. // that don't have a working implementation.
  902. // FIXME: Probably can be removed on Lenny+1
  903. static int racy_pselect(int nfds, fd_set *readfds, fd_set *writefds,
  904. fd_set *exceptfds, const struct timespec *timeout,
  905. const sigset_t *sigmask)
  906. {
  907. sigset_t origmask;
  908. struct timeval tv;
  909. int retval;
  910. tv.tv_sec = timeout->tv_sec;
  911. tv.tv_usec = timeout->tv_nsec/1000;
  912. sigprocmask(SIG_SETMASK, sigmask, &origmask);
  913. retval = select(nfds, readfds, writefds, exceptfds, &tv);
  914. sigprocmask(SIG_SETMASK, &origmask, 0);
  915. return retval;
  916. }
  917. /*}}}*/
  918. void pkgDPkgPM::SetupTerminalScrollArea(int nr_rows)
  919. {
  920. if(!d->fancy_progress_output)
  921. return;
  922. // scroll down a bit to avoid visual glitch when the screen
  923. // area shrinks by one row
  924. std::cout << "\n";
  925. // save cursor
  926. std::cout << "\033[s";
  927. // set scroll region (this will place the cursor in the top left)
  928. std::cout << "\033[1;" << nr_rows - 1 << "r";
  929. // restore cursor but ensure its inside the scrolling area
  930. std::cout << "\033[u";
  931. static const char *move_cursor_up = "\033[1A";
  932. std::cout << move_cursor_up;
  933. std::flush(std::cout);
  934. }
  935. void pkgDPkgPM::CleanupTerminal()
  936. {
  937. // reset scroll area
  938. SetupTerminalScrollArea(d->nr_terminal_rows + 1);
  939. if(d->fancy_progress_output)
  940. {
  941. // override the progress line (sledgehammer)
  942. static const char* clear_screen_below_cursor = "\033[J";
  943. std::cout << clear_screen_below_cursor;
  944. std::flush(std::cout);
  945. }
  946. }
  947. // DPkgPM::Go - Run the sequence /*{{{*/
  948. // ---------------------------------------------------------------------
  949. /* This globs the operations and calls dpkg
  950. *
  951. * If it is called with "OutStatusFd" set to a valid file descriptor
  952. * apt will report the install progress over this fd. It maps the
  953. * dpkg states a package goes through to human readable (and i10n-able)
  954. * names and calculates a percentage for each step.
  955. */
  956. bool pkgDPkgPM::Go(int OutStatusFd)
  957. {
  958. pkgPackageManager::SigINTStop = false;
  959. // Generate the base argument list for dpkg
  960. std::vector<const char *> Args;
  961. unsigned long StartSize = 0;
  962. string Tmp = _config->Find("Dir::Bin::dpkg","dpkg");
  963. {
  964. string const dpkgChrootDir = _config->FindDir("DPkg::Chroot-Directory", "/");
  965. size_t dpkgChrootLen = dpkgChrootDir.length();
  966. if (dpkgChrootDir != "/" && Tmp.find(dpkgChrootDir) == 0)
  967. {
  968. if (dpkgChrootDir[dpkgChrootLen - 1] == '/')
  969. --dpkgChrootLen;
  970. Tmp = Tmp.substr(dpkgChrootLen);
  971. }
  972. }
  973. Args.push_back(Tmp.c_str());
  974. StartSize += Tmp.length();
  975. // Stick in any custom dpkg options
  976. Configuration::Item const *Opts = _config->Tree("DPkg::Options");
  977. if (Opts != 0)
  978. {
  979. Opts = Opts->Child;
  980. for (; Opts != 0; Opts = Opts->Next)
  981. {
  982. if (Opts->Value.empty() == true)
  983. continue;
  984. Args.push_back(Opts->Value.c_str());
  985. StartSize += Opts->Value.length();
  986. }
  987. }
  988. size_t const BaseArgs = Args.size();
  989. // we need to detect if we can qualify packages with the architecture or not
  990. Args.push_back("--assert-multi-arch");
  991. Args.push_back(NULL);
  992. pid_t dpkgAssertMultiArch = ExecFork();
  993. if (dpkgAssertMultiArch == 0)
  994. {
  995. dpkgChrootDirectory();
  996. // redirect everything to the ultimate sink as we only need the exit-status
  997. int const nullfd = open("/dev/null", O_RDONLY);
  998. dup2(nullfd, STDIN_FILENO);
  999. dup2(nullfd, STDOUT_FILENO);
  1000. dup2(nullfd, STDERR_FILENO);
  1001. execvp(Args[0], (char**) &Args[0]);
  1002. _error->WarningE("dpkgGo", "Can't detect if dpkg supports multi-arch!");
  1003. _exit(2);
  1004. }
  1005. fd_set rfds;
  1006. struct timespec tv;
  1007. sigset_t sigmask;
  1008. sigset_t original_sigmask;
  1009. unsigned int const MaxArgs = _config->FindI("Dpkg::MaxArgs",8*1024);
  1010. unsigned int const MaxArgBytes = _config->FindI("Dpkg::MaxArgBytes",32*1024);
  1011. bool const NoTriggers = _config->FindB("DPkg::NoTriggers", false);
  1012. if (RunScripts("DPkg::Pre-Invoke") == false)
  1013. return false;
  1014. if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
  1015. return false;
  1016. // support subpressing of triggers processing for special
  1017. // cases like d-i that runs the triggers handling manually
  1018. bool const SmartConf = (_config->Find("PackageManager::Configure", "all") != "all");
  1019. bool const TriggersPending = _config->FindB("DPkg::TriggersPending", false);
  1020. if (_config->FindB("DPkg::ConfigurePending", SmartConf) == true)
  1021. List.push_back(Item(Item::ConfigurePending, PkgIterator()));
  1022. // map the dpkg states to the operations that are performed
  1023. // (this is sorted in the same way as Item::Ops)
  1024. static const struct DpkgState DpkgStatesOpMap[][7] = {
  1025. // Install operation
  1026. {
  1027. {"half-installed", N_("Preparing %s")},
  1028. {"unpacked", N_("Unpacking %s") },
  1029. {NULL, NULL}
  1030. },
  1031. // Configure operation
  1032. {
  1033. {"unpacked",N_("Preparing to configure %s") },
  1034. {"half-configured", N_("Configuring %s") },
  1035. { "installed", N_("Installed %s")},
  1036. {NULL, NULL}
  1037. },
  1038. // Remove operation
  1039. {
  1040. {"half-configured", N_("Preparing for removal of %s")},
  1041. {"half-installed", N_("Removing %s")},
  1042. {"config-files", N_("Removed %s")},
  1043. {NULL, NULL}
  1044. },
  1045. // Purge operation
  1046. {
  1047. {"config-files", N_("Preparing to completely remove %s")},
  1048. {"not-installed", N_("Completely removed %s")},
  1049. {NULL, NULL}
  1050. },
  1051. };
  1052. // init the PackageOps map, go over the list of packages that
  1053. // that will be [installed|configured|removed|purged] and add
  1054. // them to the PackageOps map (the dpkg states it goes through)
  1055. // and the PackageOpsTranslations (human readable strings)
  1056. for (vector<Item>::const_iterator I = List.begin(); I != List.end(); ++I)
  1057. {
  1058. if((*I).Pkg.end() == true)
  1059. continue;
  1060. string const name = (*I).Pkg.FullName();
  1061. PackageOpsDone[name] = 0;
  1062. for(int i=0; (DpkgStatesOpMap[(*I).Op][i]).state != NULL; ++i)
  1063. {
  1064. PackageOps[name].push_back(DpkgStatesOpMap[(*I).Op][i]);
  1065. PackagesTotal++;
  1066. }
  1067. }
  1068. d->stdin_is_dev_null = false;
  1069. // create log
  1070. OpenLog();
  1071. bool dpkgMultiArch = false;
  1072. if (dpkgAssertMultiArch > 0)
  1073. {
  1074. int Status = 0;
  1075. while (waitpid(dpkgAssertMultiArch, &Status, 0) != dpkgAssertMultiArch)
  1076. {
  1077. if (errno == EINTR)
  1078. continue;
  1079. _error->WarningE("dpkgGo", _("Waited for %s but it wasn't there"), "dpkg --assert-multi-arch");
  1080. break;
  1081. }
  1082. if (WIFEXITED(Status) == true && WEXITSTATUS(Status) == 0)
  1083. dpkgMultiArch = true;
  1084. }
  1085. // this loop is runs once per operation
  1086. for (vector<Item>::const_iterator I = List.begin(); I != List.end();)
  1087. {
  1088. // Do all actions with the same Op in one run
  1089. vector<Item>::const_iterator J = I;
  1090. if (TriggersPending == true)
  1091. for (; J != List.end(); ++J)
  1092. {
  1093. if (J->Op == I->Op)
  1094. continue;
  1095. if (J->Op != Item::TriggersPending)
  1096. break;
  1097. vector<Item>::const_iterator T = J + 1;
  1098. if (T != List.end() && T->Op == I->Op)
  1099. continue;
  1100. break;
  1101. }
  1102. else
  1103. for (; J != List.end() && J->Op == I->Op; ++J)
  1104. /* nothing */;
  1105. // keep track of allocated strings for multiarch package names
  1106. std::vector<char *> Packages;
  1107. // start with the baseset of arguments
  1108. unsigned long Size = StartSize;
  1109. Args.erase(Args.begin() + BaseArgs, Args.end());
  1110. // Now check if we are within the MaxArgs limit
  1111. //
  1112. // this code below is problematic, because it may happen that
  1113. // the argument list is split in a way that A depends on B
  1114. // and they are in the same "--configure A B" run
  1115. // - with the split they may now be configured in different
  1116. // runs, using Immediate-Configure-All can help prevent this.
  1117. if (J - I > (signed)MaxArgs)
  1118. {
  1119. J = I + MaxArgs;
  1120. unsigned long const size = MaxArgs + 10;
  1121. Args.reserve(size);
  1122. Packages.reserve(size);
  1123. }
  1124. else
  1125. {
  1126. unsigned long const size = (J - I) + 10;
  1127. Args.reserve(size);
  1128. Packages.reserve(size);
  1129. }
  1130. int fd[2];
  1131. if (pipe(fd) != 0)
  1132. return _error->Errno("pipe","Failed to create IPC pipe to dpkg");
  1133. #define ADDARG(X) Args.push_back(X); Size += strlen(X)
  1134. #define ADDARGC(X) Args.push_back(X); Size += sizeof(X) - 1
  1135. ADDARGC("--status-fd");
  1136. char status_fd_buf[20];
  1137. snprintf(status_fd_buf,sizeof(status_fd_buf),"%i", fd[1]);
  1138. ADDARG(status_fd_buf);
  1139. unsigned long const Op = I->Op;
  1140. switch (I->Op)
  1141. {
  1142. case Item::Remove:
  1143. ADDARGC("--force-depends");
  1144. ADDARGC("--force-remove-essential");
  1145. ADDARGC("--remove");
  1146. break;
  1147. case Item::Purge:
  1148. ADDARGC("--force-depends");
  1149. ADDARGC("--force-remove-essential");
  1150. ADDARGC("--purge");
  1151. break;
  1152. case Item::Configure:
  1153. ADDARGC("--configure");
  1154. break;
  1155. case Item::ConfigurePending:
  1156. ADDARGC("--configure");
  1157. ADDARGC("--pending");
  1158. break;
  1159. case Item::TriggersPending:
  1160. ADDARGC("--triggers-only");
  1161. ADDARGC("--pending");
  1162. break;
  1163. case Item::Install:
  1164. ADDARGC("--unpack");
  1165. ADDARGC("--auto-deconfigure");
  1166. break;
  1167. }
  1168. if (NoTriggers == true && I->Op != Item::TriggersPending &&
  1169. I->Op != Item::ConfigurePending)
  1170. {
  1171. ADDARGC("--no-triggers");
  1172. }
  1173. #undef ADDARGC
  1174. // Write in the file or package names
  1175. if (I->Op == Item::Install)
  1176. {
  1177. for (;I != J && Size < MaxArgBytes; ++I)
  1178. {
  1179. if (I->File[0] != '/')
  1180. return _error->Error("Internal Error, Pathname to install is not absolute '%s'",I->File.c_str());
  1181. Args.push_back(I->File.c_str());
  1182. Size += I->File.length();
  1183. }
  1184. }
  1185. else
  1186. {
  1187. string const nativeArch = _config->Find("APT::Architecture");
  1188. unsigned long const oldSize = I->Op == Item::Configure ? Size : 0;
  1189. for (;I != J && Size < MaxArgBytes; ++I)
  1190. {
  1191. if((*I).Pkg.end() == true)
  1192. continue;
  1193. if (I->Op == Item::Configure && disappearedPkgs.find(I->Pkg.Name()) != disappearedPkgs.end())
  1194. continue;
  1195. // We keep this here to allow "smooth" transitions from e.g. multiarch dpkg/ubuntu to dpkg/debian
  1196. if (dpkgMultiArch == false && (I->Pkg.Arch() == nativeArch ||
  1197. strcmp(I->Pkg.Arch(), "all") == 0 ||
  1198. strcmp(I->Pkg.Arch(), "none") == 0))
  1199. {
  1200. char const * const name = I->Pkg.Name();
  1201. ADDARG(name);
  1202. }
  1203. else
  1204. {
  1205. pkgCache::VerIterator PkgVer;
  1206. std::string name = I->Pkg.Name();
  1207. if (Op == Item::Remove || Op == Item::Purge)
  1208. {
  1209. PkgVer = I->Pkg.CurrentVer();
  1210. if(PkgVer.end() == true)
  1211. PkgVer = FindNowVersion(I->Pkg);
  1212. }
  1213. else
  1214. PkgVer = Cache[I->Pkg].InstVerIter(Cache);
  1215. if (strcmp(I->Pkg.Arch(), "none") == 0)
  1216. ; // never arch-qualify a package without an arch
  1217. else if (PkgVer.end() == false)
  1218. name.append(":").append(PkgVer.Arch());
  1219. else
  1220. _error->Warning("Can not find PkgVer for '%s'", name.c_str());
  1221. char * const fullname = strdup(name.c_str());
  1222. Packages.push_back(fullname);
  1223. ADDARG(fullname);
  1224. }
  1225. }
  1226. // skip configure action if all sheduled packages disappeared
  1227. if (oldSize == Size)
  1228. continue;
  1229. }
  1230. #undef ADDARG
  1231. J = I;
  1232. if (_config->FindB("Debug::pkgDPkgPM",false) == true)
  1233. {
  1234. for (std::vector<const char *>::const_iterator a = Args.begin();
  1235. a != Args.end(); ++a)
  1236. clog << *a << ' ';
  1237. clog << endl;
  1238. continue;
  1239. }
  1240. Args.push_back(NULL);
  1241. cout << flush;
  1242. clog << flush;
  1243. cerr << flush;
  1244. /* Mask off sig int/quit. We do this because dpkg also does when
  1245. it forks scripts. What happens is that when you hit ctrl-c it sends
  1246. it to all processes in the group. Since dpkg ignores the signal
  1247. it doesn't die but we do! So we must also ignore it */
  1248. sighandler_t old_SIGQUIT = signal(SIGQUIT,SIG_IGN);
  1249. sighandler_t old_SIGINT = signal(SIGINT,SigINT);
  1250. // Check here for any SIGINT
  1251. if (pkgPackageManager::SigINTStop && (Op == Item::Remove || Op == Item::Purge || Op == Item::Install))
  1252. break;
  1253. // ignore SIGHUP as well (debian #463030)
  1254. sighandler_t old_SIGHUP = signal(SIGHUP,SIG_IGN);
  1255. struct termios tt;
  1256. struct winsize win;
  1257. int master = -1;
  1258. int slave = -1;
  1259. // if tcgetattr does not return zero there was a error
  1260. // and we do not do any pty magic
  1261. _error->PushToStack();
  1262. if (tcgetattr(STDOUT_FILENO, &tt) == 0)
  1263. {
  1264. ioctl(1, TIOCGWINSZ, (char *)&win);
  1265. d->nr_terminal_rows = win.ws_row;
  1266. if (openpty(&master, &slave, NULL, &tt, &win) < 0)
  1267. {
  1268. _error->Errno("openpty", _("Can not write log (%s)"), _("Is /dev/pts mounted?"));
  1269. master = slave = -1;
  1270. } else {
  1271. struct termios rtt;
  1272. rtt = tt;
  1273. cfmakeraw(&rtt);
  1274. rtt.c_lflag &= ~ECHO;
  1275. rtt.c_lflag |= ISIG;
  1276. // block SIGTTOU during tcsetattr to prevent a hang if
  1277. // the process is a member of the background process group
  1278. // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
  1279. sigemptyset(&sigmask);
  1280. sigaddset(&sigmask, SIGTTOU);
  1281. sigprocmask(SIG_BLOCK,&sigmask, &original_sigmask);
  1282. tcsetattr(0, TCSAFLUSH, &rtt);
  1283. sigprocmask(SIG_SETMASK, &original_sigmask, 0);
  1284. }
  1285. }
  1286. // complain only if stdout is either a terminal (but still failed) or is an invalid
  1287. // descriptor otherwise we would complain about redirection to e.g. /dev/null as well.
  1288. else if (isatty(STDOUT_FILENO) == 1 || errno == EBADF)
  1289. _error->Errno("tcgetattr", _("Can not write log (%s)"), _("Is stdout a terminal?"));
  1290. if (_error->PendingError() == true)
  1291. _error->DumpErrors(std::cerr);
  1292. _error->RevertToStack();
  1293. // Fork dpkg
  1294. pid_t Child;
  1295. _config->Set("APT::Keep-Fds::",fd[1]);
  1296. // send status information that we are about to fork dpkg
  1297. if(OutStatusFd > 0) {
  1298. ostringstream status;
  1299. status << "pmstatus:dpkg-exec:"
  1300. << (PackagesDone/float(PackagesTotal)*100.0)
  1301. << ":" << _("Running dpkg")
  1302. << endl;
  1303. FileFd::Write(OutStatusFd, status.str().c_str(), status.str().size());
  1304. }
  1305. Child = ExecFork();
  1306. // This is the child
  1307. if (Child == 0)
  1308. {
  1309. if(slave >= 0 && master >= 0)
  1310. {
  1311. setsid();
  1312. ioctl(slave, TIOCSCTTY, 0);
  1313. close(master);
  1314. dup2(slave, 0);
  1315. dup2(slave, 1);
  1316. dup2(slave, 2);
  1317. close(slave);
  1318. }
  1319. close(fd[0]); // close the read end of the pipe
  1320. dpkgChrootDirectory();
  1321. if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
  1322. _exit(100);
  1323. if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
  1324. {
  1325. int Flags,dummy;
  1326. if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
  1327. _exit(100);
  1328. // Discard everything in stdin before forking dpkg
  1329. if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
  1330. _exit(100);
  1331. while (read(STDIN_FILENO,&dummy,1) == 1);
  1332. if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
  1333. _exit(100);
  1334. }
  1335. // setup terminal
  1336. SetupTerminalScrollArea(d->nr_terminal_rows);
  1337. SendTerminalProgress(PackagesDone/float(PackagesTotal)*100.0);
  1338. /* No Job Control Stop Env is a magic dpkg var that prevents it
  1339. from using sigstop */
  1340. putenv((char *)"DPKG_NO_TSTP=yes");
  1341. execvp(Args[0], (char**) &Args[0]);
  1342. cerr << "Could not exec dpkg!" << endl;
  1343. _exit(100);
  1344. }
  1345. // apply ionice
  1346. if (_config->FindB("DPkg::UseIoNice", false) == true)
  1347. ionice(Child);
  1348. // clear the Keep-Fd again
  1349. _config->Clear("APT::Keep-Fds",fd[1]);
  1350. // Wait for dpkg
  1351. int Status = 0;
  1352. // we read from dpkg here
  1353. int const _dpkgin = fd[0];
  1354. close(fd[1]); // close the write end of the pipe
  1355. if(slave > 0)
  1356. close(slave);
  1357. // setups fds
  1358. sigemptyset(&sigmask);
  1359. sigprocmask(SIG_BLOCK,&sigmask,&original_sigmask);
  1360. /* free vectors (and therefore memory) as we don't need the included data anymore */
  1361. for (std::vector<char *>::const_iterator p = Packages.begin();
  1362. p != Packages.end(); ++p)
  1363. free(*p);
  1364. Packages.clear();
  1365. // the result of the waitpid call
  1366. int res;
  1367. int select_ret;
  1368. while ((res=waitpid(Child,&Status, WNOHANG)) != Child) {
  1369. if(res < 0) {
  1370. // FIXME: move this to a function or something, looks ugly here
  1371. // error handling, waitpid returned -1
  1372. if (errno == EINTR)
  1373. continue;
  1374. RunScripts("DPkg::Post-Invoke");
  1375. // Restore sig int/quit
  1376. signal(SIGQUIT,old_SIGQUIT);
  1377. signal(SIGINT,old_SIGINT);
  1378. signal(SIGHUP,old_SIGHUP);
  1379. return _error->Errno("waitpid","Couldn't wait for subprocess");
  1380. }
  1381. // wait for input or output here
  1382. FD_ZERO(&rfds);
  1383. if (master >= 0 && !d->stdin_is_dev_null)
  1384. FD_SET(0, &rfds);
  1385. FD_SET(_dpkgin, &rfds);
  1386. if(master >= 0)
  1387. FD_SET(master, &rfds);
  1388. tv.tv_sec = 1;
  1389. tv.tv_nsec = 0;
  1390. select_ret = pselect(max(master, _dpkgin)+1, &rfds, NULL, NULL,
  1391. &tv, &original_sigmask);
  1392. if (select_ret < 0 && (errno == EINVAL || errno == ENOSYS))
  1393. select_ret = racy_pselect(max(master, _dpkgin)+1, &rfds, NULL,
  1394. NULL, &tv, &original_sigmask);
  1395. if (select_ret == 0)
  1396. continue;
  1397. else if (select_ret < 0 && errno == EINTR)
  1398. continue;
  1399. else if (select_ret < 0)
  1400. {
  1401. perror("select() returned error");
  1402. continue;
  1403. }
  1404. if(master >= 0 && FD_ISSET(master, &rfds))
  1405. DoTerminalPty(master);
  1406. if(master >= 0 && FD_ISSET(0, &rfds))
  1407. DoStdin(master);
  1408. if(FD_ISSET(_dpkgin, &rfds))
  1409. DoDpkgStatusFd(_dpkgin, OutStatusFd);
  1410. }
  1411. close(_dpkgin);
  1412. // Restore sig int/quit
  1413. signal(SIGQUIT,old_SIGQUIT);
  1414. signal(SIGINT,old_SIGINT);
  1415. signal(SIGHUP,old_SIGHUP);
  1416. if(master >= 0)
  1417. {
  1418. tcsetattr(0, TCSAFLUSH, &tt);
  1419. close(master);
  1420. }
  1421. // Check for an error code.
  1422. if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
  1423. {
  1424. // if it was set to "keep-dpkg-runing" then we won't return
  1425. // here but keep the loop going and just report it as a error
  1426. // for later
  1427. bool const stopOnError = _config->FindB("Dpkg::StopOnError",true);
  1428. if(stopOnError)
  1429. RunScripts("DPkg::Post-Invoke");
  1430. if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
  1431. strprintf(d->dpkg_error, "Sub-process %s received a segmentation fault.",Args[0]);
  1432. else if (WIFEXITED(Status) != 0)
  1433. strprintf(d->dpkg_error, "Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
  1434. else
  1435. strprintf(d->dpkg_error, "Sub-process %s exited unexpectedly",Args[0]);
  1436. if(d->dpkg_error.size() > 0)
  1437. _error->Error("%s", d->dpkg_error.c_str());
  1438. if(stopOnError)
  1439. {
  1440. CloseLog();
  1441. CleanupTerminal();
  1442. return false;
  1443. }
  1444. }
  1445. }
  1446. CloseLog();
  1447. // dpkg is done at this point
  1448. if(_config->FindB("DPkgPM::Progress", false) == true)
  1449. SendTerminalProgress(100);
  1450. CleanupTerminal();
  1451. if (pkgPackageManager::SigINTStop)
  1452. _error->Warning(_("Operation was interrupted before it could finish"));
  1453. if (RunScripts("DPkg::Post-Invoke") == false)
  1454. return false;
  1455. if (_config->FindB("Debug::pkgDPkgPM",false) == false)
  1456. {
  1457. std::string const oldpkgcache = _config->FindFile("Dir::cache::pkgcache");
  1458. if (oldpkgcache.empty() == false && RealFileExists(oldpkgcache) == true &&
  1459. unlink(oldpkgcache.c_str()) == 0)
  1460. {
  1461. std::string const srcpkgcache = _config->FindFile("Dir::cache::srcpkgcache");
  1462. if (srcpkgcache.empty() == false && RealFileExists(srcpkgcache) == true)
  1463. {
  1464. _error->PushToStack();
  1465. pkgCacheFile CacheFile;
  1466. CacheFile.BuildCaches(NULL, true);
  1467. _error->RevertToStack();
  1468. }
  1469. }
  1470. }
  1471. Cache.writeStateFile(NULL);
  1472. return true;
  1473. }
  1474. void SigINT(int sig) {
  1475. pkgPackageManager::SigINTStop = true;
  1476. }
  1477. /*}}}*/
  1478. // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
  1479. // ---------------------------------------------------------------------
  1480. /* */
  1481. void pkgDPkgPM::Reset()
  1482. {
  1483. List.erase(List.begin(),List.end());
  1484. }
  1485. /*}}}*/
  1486. // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
  1487. // ---------------------------------------------------------------------
  1488. /* */
  1489. void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
  1490. {
  1491. // If apport doesn't exist or isn't installed do nothing
  1492. // This e.g. prevents messages in 'universes' without apport
  1493. pkgCache::PkgIterator apportPkg = Cache.FindPkg("apport");
  1494. if (apportPkg.end() == true || apportPkg->CurrentVer == 0)
  1495. return;
  1496. string pkgname, reportfile, srcpkgname, pkgver, arch;
  1497. string::size_type pos;
  1498. FILE *report;
  1499. if (_config->FindB("Dpkg::ApportFailureReport", false) == false)
  1500. {
  1501. std::clog << "configured to not write apport reports" << std::endl;
  1502. return;
  1503. }
  1504. // only report the first errors
  1505. if(pkgFailures > _config->FindI("APT::Apport::MaxReports", 3))
  1506. {
  1507. std::clog << _("No apport report written because MaxReports is reached already") << std::endl;
  1508. return;
  1509. }
  1510. // check if its not a follow up error
  1511. const char *needle = dgettext("dpkg", "dependency problems - leaving unconfigured");
  1512. if(strstr(errormsg, needle) != NULL) {
  1513. std::clog << _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl;
  1514. return;
  1515. }
  1516. // do not report disk-full failures
  1517. if(strstr(errormsg, strerror(ENOSPC)) != NULL) {
  1518. std::clog << _("No apport report written because the error message indicates a disk full error") << std::endl;
  1519. return;
  1520. }
  1521. // do not report out-of-memory failures
  1522. if(strstr(errormsg, strerror(ENOMEM)) != NULL) {
  1523. std::clog << _("No apport report written because the error message indicates a out of memory error") << std::endl;
  1524. return;
  1525. }
  1526. // do not report dpkg I/O errors
  1527. // XXX - this message is localized, but this only matches the English version. This is better than nothing.
  1528. if(strstr(errormsg, "short read in buffer_copy (")) {
  1529. std::clog << _("No apport report written because the error message indicates a dpkg I/O error") << std::endl;
  1530. return;
  1531. }
  1532. // get the pkgname and reportfile
  1533. pkgname = flNotDir(pkgpath);
  1534. pos = pkgname.find('_');
  1535. if(pos != string::npos)
  1536. pkgname = pkgname.substr(0, pos);
  1537. // find the package versin and source package name
  1538. pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
  1539. if (Pkg.end() == true)
  1540. return;
  1541. pkgCache::VerIterator Ver = Cache.GetCandidateVer(Pkg);
  1542. if (Ver.end() == true)
  1543. return;
  1544. pkgver = Ver.VerStr() == NULL ? "unknown" : Ver.VerStr();
  1545. pkgRecords Recs(Cache);
  1546. pkgRecords::Parser &Parse = Recs.Lookup(Ver.FileList());
  1547. srcpkgname = Parse.SourcePkg();
  1548. if(srcpkgname.empty())
  1549. srcpkgname = pkgname;
  1550. // if the file exists already, we check:
  1551. // - if it was reported already (touched by apport).
  1552. // If not, we do nothing, otherwise
  1553. // we overwrite it. This is the same behaviour as apport
  1554. // - if we have a report with the same pkgversion already
  1555. // then we skip it
  1556. reportfile = flCombine("/var/crash",pkgname+".0.crash");
  1557. if(FileExists(reportfile))
  1558. {
  1559. struct stat buf;
  1560. char strbuf[255];
  1561. // check atime/mtime
  1562. stat(reportfile.c_str(), &buf);
  1563. if(buf.st_mtime > buf.st_atime)
  1564. return;
  1565. // check if the existing report is the same version
  1566. report = fopen(reportfile.c_str(),"r");
  1567. while(fgets(strbuf, sizeof(strbuf), report) != NULL)
  1568. {
  1569. if(strstr(strbuf,"Package:") == strbuf)
  1570. {
  1571. char pkgname[255], version[255];
  1572. if(sscanf(strbuf, "Package: %254s %254s", pkgname, version) == 2)
  1573. if(strcmp(pkgver.c_str(), version) == 0)
  1574. {
  1575. fclose(report);
  1576. return;
  1577. }
  1578. }
  1579. }
  1580. fclose(report);
  1581. }
  1582. // now write the report
  1583. arch = _config->Find("APT::Architecture");
  1584. report = fopen(reportfile.c_str(),"w");
  1585. if(report == NULL)
  1586. return;
  1587. if(_config->FindB("DPkgPM::InitialReportOnly",false) == true)
  1588. chmod(reportfile.c_str(), 0);
  1589. else
  1590. chmod(reportfile.c_str(), 0600);
  1591. fprintf(report, "ProblemType: Package\n");
  1592. fprintf(report, "Architecture: %s\n", arch.c_str());
  1593. time_t now = time(NULL);
  1594. fprintf(report, "Date: %s" , ctime(&now));
  1595. fprintf(report, "Package: %s %s\n", pkgname.c_str(), pkgver.c_str());
  1596. fprintf(report, "SourcePackage: %s\n", srcpkgname.c_str());
  1597. fprintf(report, "ErrorMessage:\n %s\n", errormsg);
  1598. // ensure that the log is flushed
  1599. if(d->term_out)
  1600. fflush(d->term_out);
  1601. // attach terminal log it if we have it
  1602. string logfile_name = _config->FindFile("Dir::Log::Terminal");
  1603. if (!logfile_name.empty())
  1604. {
  1605. FILE *log = NULL;
  1606. fprintf(report, "DpkgTerminalLog:\n");
  1607. log = fopen(logfile_name.c_str(),"r");
  1608. if(log != NULL)
  1609. {
  1610. char buf[1024];
  1611. while( fgets(buf, sizeof(buf), log) != NULL)
  1612. fprintf(report, " %s", buf);
  1613. fclose(log);
  1614. }
  1615. }
  1616. // log the ordering
  1617. const char *ops_str[] = {"Install", "Configure","Remove","Purge"};
  1618. fprintf(report, "AptOrdering:\n");
  1619. for (vector<Item>::iterator I = List.begin(); I != List.end(); ++I)
  1620. if ((*I).Pkg != NULL)
  1621. fprintf(report, " %s: %s\n", (*I).Pkg.Name(), ops_str[(*I).Op]);
  1622. else
  1623. fprintf(report, " %s: %s\n", "NULL", ops_str[(*I).Op]);
  1624. // attach dmesg log (to learn about segfaults)
  1625. if (FileExists("/bin/dmesg"))
  1626. {
  1627. fprintf(report, "Dmesg:\n");
  1628. FILE *log = popen("/bin/dmesg","r");
  1629. if(log != NULL)
  1630. {
  1631. char buf[1024];
  1632. while( fgets(buf, sizeof(buf), log) != NULL)
  1633. fprintf(report, " %s", buf);
  1634. pclose(log);
  1635. }
  1636. }
  1637. // attach df -l log (to learn about filesystem status)
  1638. if (FileExists("/bin/df"))
  1639. {
  1640. fprintf(report, "Df:\n");
  1641. FILE *log = popen("/bin/df -l","r");
  1642. if(log != NULL)
  1643. {
  1644. char buf[1024];
  1645. while( fgets(buf, sizeof(buf), log) != NULL)
  1646. fprintf(report, " %s", buf);
  1647. pclose(log);
  1648. }
  1649. }
  1650. fclose(report);
  1651. }
  1652. /*}}}*/