dpkgpm.cc 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358
  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 <apt-pkg/dpkgpm.h>
  10. #include <apt-pkg/error.h>
  11. #include <apt-pkg/configuration.h>
  12. #include <apt-pkg/depcache.h>
  13. #include <apt-pkg/pkgrecords.h>
  14. #include <apt-pkg/strutl.h>
  15. #include <apti18n.h>
  16. #include <apt-pkg/fileutl.h>
  17. #include <unistd.h>
  18. #include <stdlib.h>
  19. #include <fcntl.h>
  20. #include <sys/select.h>
  21. #include <sys/types.h>
  22. #include <sys/wait.h>
  23. #include <signal.h>
  24. #include <errno.h>
  25. #include <string.h>
  26. #include <stdio.h>
  27. #include <string.h>
  28. #include <algorithm>
  29. #include <sstream>
  30. #include <map>
  31. #include <termios.h>
  32. #include <unistd.h>
  33. #include <sys/ioctl.h>
  34. #include <pty.h>
  35. #include <config.h>
  36. #include <apti18n.h>
  37. /*}}}*/
  38. using namespace std;
  39. namespace
  40. {
  41. // Maps the dpkg "processing" info to human readable names. Entry 0
  42. // of each array is the key, entry 1 is the value.
  43. const std::pair<const char *, const char *> PackageProcessingOps[] = {
  44. std::make_pair("install", N_("Installing %s")),
  45. std::make_pair("configure", N_("Configuring %s")),
  46. std::make_pair("remove", N_("Removing %s")),
  47. std::make_pair("purge", N_("Completely removing %s")),
  48. std::make_pair("trigproc", N_("Running post-installation trigger %s"))
  49. };
  50. const std::pair<const char *, const char *> * const PackageProcessingOpsBegin = PackageProcessingOps;
  51. const std::pair<const char *, const char *> * const PackageProcessingOpsEnd = PackageProcessingOps + sizeof(PackageProcessingOps) / sizeof(PackageProcessingOps[0]);
  52. // Predicate to test whether an entry in the PackageProcessingOps
  53. // array matches a string.
  54. class MatchProcessingOp
  55. {
  56. const char *target;
  57. public:
  58. MatchProcessingOp(const char *the_target)
  59. : target(the_target)
  60. {
  61. }
  62. bool operator()(const std::pair<const char *, const char *> &pair) const
  63. {
  64. return strcmp(pair.first, target) == 0;
  65. }
  66. };
  67. }
  68. /* helper function to ionice the given PID
  69. there is no C header for ionice yet - just the syscall interface
  70. so we use the binary from util-linux
  71. */
  72. static bool
  73. ionice(int PID)
  74. {
  75. if (!FileExists("/usr/bin/ionice"))
  76. return false;
  77. pid_t Process = ExecFork();
  78. if (Process == 0)
  79. {
  80. char buf[32];
  81. snprintf(buf, sizeof(buf), "-p%d", PID);
  82. const char *Args[4];
  83. Args[0] = "/usr/bin/ionice";
  84. Args[1] = "-c3";
  85. Args[2] = buf;
  86. Args[3] = 0;
  87. execv(Args[0], (char **)Args);
  88. }
  89. return ExecWait(Process, "ionice");
  90. }
  91. // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
  92. // ---------------------------------------------------------------------
  93. /* */
  94. pkgDPkgPM::pkgDPkgPM(pkgDepCache *Cache)
  95. : pkgPackageManager(Cache), dpkgbuf_pos(0),
  96. term_out(NULL), PackagesDone(0), PackagesTotal(0), pkgFailures(0)
  97. {
  98. }
  99. /*}}}*/
  100. // DPkgPM::pkgDPkgPM - Destructor /*{{{*/
  101. // ---------------------------------------------------------------------
  102. /* */
  103. pkgDPkgPM::~pkgDPkgPM()
  104. {
  105. }
  106. /*}}}*/
  107. // DPkgPM::Install - Install a package /*{{{*/
  108. // ---------------------------------------------------------------------
  109. /* Add an install operation to the sequence list */
  110. bool pkgDPkgPM::Install(PkgIterator Pkg,string File)
  111. {
  112. if (File.empty() == true || Pkg.end() == true)
  113. return _error->Error("Internal Error, No file name for %s",Pkg.Name());
  114. List.push_back(Item(Item::Install,Pkg,File));
  115. return true;
  116. }
  117. /*}}}*/
  118. // DPkgPM::Configure - Configure a package /*{{{*/
  119. // ---------------------------------------------------------------------
  120. /* Add a configure operation to the sequence list */
  121. bool pkgDPkgPM::Configure(PkgIterator Pkg)
  122. {
  123. if (Pkg.end() == true)
  124. return false;
  125. List.push_back(Item(Item::Configure, Pkg));
  126. // Use triggers for config calls if we configure "smart"
  127. // as otherwise Pre-Depends will not be satisfied, see #526774
  128. if (_config->FindB("DPkg::TriggersPending", false) == true)
  129. List.push_back(Item(Item::TriggersPending, PkgIterator()));
  130. return true;
  131. }
  132. /*}}}*/
  133. // DPkgPM::Remove - Remove a package /*{{{*/
  134. // ---------------------------------------------------------------------
  135. /* Add a remove operation to the sequence list */
  136. bool pkgDPkgPM::Remove(PkgIterator Pkg,bool Purge)
  137. {
  138. if (Pkg.end() == true)
  139. return false;
  140. if (Purge == true)
  141. List.push_back(Item(Item::Purge,Pkg));
  142. else
  143. List.push_back(Item(Item::Remove,Pkg));
  144. return true;
  145. }
  146. /*}}}*/
  147. // DPkgPM::SendV2Pkgs - Send version 2 package info /*{{{*/
  148. // ---------------------------------------------------------------------
  149. /* This is part of the helper script communication interface, it sends
  150. very complete information down to the other end of the pipe.*/
  151. bool pkgDPkgPM::SendV2Pkgs(FILE *F)
  152. {
  153. fprintf(F,"VERSION 2\n");
  154. /* Write out all of the configuration directives by walking the
  155. configuration tree */
  156. const Configuration::Item *Top = _config->Tree(0);
  157. for (; Top != 0;)
  158. {
  159. if (Top->Value.empty() == false)
  160. {
  161. fprintf(F,"%s=%s\n",
  162. QuoteString(Top->FullTag(),"=\"\n").c_str(),
  163. QuoteString(Top->Value,"\n").c_str());
  164. }
  165. if (Top->Child != 0)
  166. {
  167. Top = Top->Child;
  168. continue;
  169. }
  170. while (Top != 0 && Top->Next == 0)
  171. Top = Top->Parent;
  172. if (Top != 0)
  173. Top = Top->Next;
  174. }
  175. fprintf(F,"\n");
  176. // Write out the package actions in order.
  177. for (vector<Item>::iterator I = List.begin(); I != List.end(); I++)
  178. {
  179. if(I->Pkg.end() == true)
  180. continue;
  181. pkgDepCache::StateCache &S = Cache[I->Pkg];
  182. fprintf(F,"%s ",I->Pkg.Name());
  183. // Current version
  184. if (I->Pkg->CurrentVer == 0)
  185. fprintf(F,"- ");
  186. else
  187. fprintf(F,"%s ",I->Pkg.CurrentVer().VerStr());
  188. // Show the compare operator
  189. // Target version
  190. if (S.InstallVer != 0)
  191. {
  192. int Comp = 2;
  193. if (I->Pkg->CurrentVer != 0)
  194. Comp = S.InstVerIter(Cache).CompareVer(I->Pkg.CurrentVer());
  195. if (Comp < 0)
  196. fprintf(F,"> ");
  197. if (Comp == 0)
  198. fprintf(F,"= ");
  199. if (Comp > 0)
  200. fprintf(F,"< ");
  201. fprintf(F,"%s ",S.InstVerIter(Cache).VerStr());
  202. }
  203. else
  204. fprintf(F,"> - ");
  205. // Show the filename/operation
  206. if (I->Op == Item::Install)
  207. {
  208. // No errors here..
  209. if (I->File[0] != '/')
  210. fprintf(F,"**ERROR**\n");
  211. else
  212. fprintf(F,"%s\n",I->File.c_str());
  213. }
  214. if (I->Op == Item::Configure)
  215. fprintf(F,"**CONFIGURE**\n");
  216. if (I->Op == Item::Remove ||
  217. I->Op == Item::Purge)
  218. fprintf(F,"**REMOVE**\n");
  219. if (ferror(F) != 0)
  220. return false;
  221. }
  222. return true;
  223. }
  224. /*}}}*/
  225. // DPkgPM::RunScriptsWithPkgs - Run scripts with package names on stdin /*{{{*/
  226. // ---------------------------------------------------------------------
  227. /* This looks for a list of scripts to run from the configuration file
  228. each one is run and is fed on standard input a list of all .deb files
  229. that are due to be installed. */
  230. bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf)
  231. {
  232. Configuration::Item const *Opts = _config->Tree(Cnf);
  233. if (Opts == 0 || Opts->Child == 0)
  234. return true;
  235. Opts = Opts->Child;
  236. unsigned int Count = 1;
  237. for (; Opts != 0; Opts = Opts->Next, Count++)
  238. {
  239. if (Opts->Value.empty() == true)
  240. continue;
  241. // Determine the protocol version
  242. string OptSec = Opts->Value;
  243. string::size_type Pos;
  244. if ((Pos = OptSec.find(' ')) == string::npos || Pos == 0)
  245. Pos = OptSec.length();
  246. OptSec = "DPkg::Tools::Options::" + string(Opts->Value.c_str(),Pos);
  247. unsigned int Version = _config->FindI(OptSec+"::Version",1);
  248. // Create the pipes
  249. int Pipes[2];
  250. if (pipe(Pipes) != 0)
  251. return _error->Errno("pipe","Failed to create IPC pipe to subprocess");
  252. SetCloseExec(Pipes[0],true);
  253. SetCloseExec(Pipes[1],true);
  254. // Purified Fork for running the script
  255. pid_t Process = ExecFork();
  256. if (Process == 0)
  257. {
  258. // Setup the FDs
  259. dup2(Pipes[0],STDIN_FILENO);
  260. SetCloseExec(STDOUT_FILENO,false);
  261. SetCloseExec(STDIN_FILENO,false);
  262. SetCloseExec(STDERR_FILENO,false);
  263. const char *Args[4];
  264. Args[0] = "/bin/sh";
  265. Args[1] = "-c";
  266. Args[2] = Opts->Value.c_str();
  267. Args[3] = 0;
  268. execv(Args[0],(char **)Args);
  269. _exit(100);
  270. }
  271. close(Pipes[0]);
  272. FILE *F = fdopen(Pipes[1],"w");
  273. if (F == 0)
  274. return _error->Errno("fdopen","Faild to open new FD");
  275. // Feed it the filenames.
  276. bool Die = false;
  277. if (Version <= 1)
  278. {
  279. for (vector<Item>::iterator I = List.begin(); I != List.end(); I++)
  280. {
  281. // Only deal with packages to be installed from .deb
  282. if (I->Op != Item::Install)
  283. continue;
  284. // No errors here..
  285. if (I->File[0] != '/')
  286. continue;
  287. /* Feed the filename of each package that is pending install
  288. into the pipe. */
  289. fprintf(F,"%s\n",I->File.c_str());
  290. if (ferror(F) != 0)
  291. {
  292. Die = true;
  293. break;
  294. }
  295. }
  296. }
  297. else
  298. Die = !SendV2Pkgs(F);
  299. fclose(F);
  300. // Clean up the sub process
  301. if (ExecWait(Process,Opts->Value.c_str()) == false)
  302. return _error->Error("Failure running script %s",Opts->Value.c_str());
  303. }
  304. return true;
  305. }
  306. /*}}}*/
  307. // DPkgPM::DoStdin - Read stdin and pass to slave pty /*{{{*/
  308. // ---------------------------------------------------------------------
  309. /*
  310. */
  311. void pkgDPkgPM::DoStdin(int master)
  312. {
  313. unsigned char input_buf[256] = {0,};
  314. ssize_t len = read(0, input_buf, sizeof(input_buf));
  315. if (len)
  316. write(master, input_buf, len);
  317. else
  318. stdin_is_dev_null = true;
  319. }
  320. /*}}}*/
  321. // DPkgPM::DoTerminalPty - Read the terminal pty and write log /*{{{*/
  322. // ---------------------------------------------------------------------
  323. /*
  324. * read the terminal pty and write log
  325. */
  326. void pkgDPkgPM::DoTerminalPty(int master)
  327. {
  328. unsigned char term_buf[1024] = {0,0, };
  329. ssize_t len=read(master, term_buf, sizeof(term_buf));
  330. if(len == -1 && errno == EIO)
  331. {
  332. // this happens when the child is about to exit, we
  333. // give it time to actually exit, otherwise we run
  334. // into a race
  335. usleep(500000);
  336. return;
  337. }
  338. if(len <= 0)
  339. return;
  340. write(1, term_buf, len);
  341. if(term_out)
  342. fwrite(term_buf, len, sizeof(char), term_out);
  343. }
  344. /*}}}*/
  345. // DPkgPM::ProcessDpkgStatusBuf /*{{{*/
  346. // ---------------------------------------------------------------------
  347. /*
  348. */
  349. void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd, char *line)
  350. {
  351. bool const Debug = _config->FindB("Debug::pkgDPkgProgressReporting",false);
  352. // the status we output
  353. ostringstream status;
  354. if (Debug == true)
  355. std::clog << "got from dpkg '" << line << "'" << std::endl;
  356. /* dpkg sends strings like this:
  357. 'status: <pkg>: <pkg qstate>'
  358. errors look like this:
  359. '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
  360. and conffile-prompt like this
  361. 'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
  362. Newer versions of dpkg sent also:
  363. 'processing: install: pkg'
  364. 'processing: configure: pkg'
  365. 'processing: remove: pkg'
  366. 'processing: purge: pkg' - but for apt is it a ignored "unknown" action
  367. 'processing: trigproc: trigger'
  368. */
  369. char* list[6];
  370. // dpkg sends multiline error messages sometimes (see
  371. // #374195 for a example. we should support this by
  372. // either patching dpkg to not send multiline over the
  373. // statusfd or by rewriting the code here to deal with
  374. // it. for now we just ignore it and not crash
  375. TokSplitString(':', line, list, sizeof(list)/sizeof(list[0]));
  376. if( list[0] == NULL || list[1] == NULL || list[2] == NULL)
  377. {
  378. if (Debug == true)
  379. std::clog << "ignoring line: not enough ':'" << std::endl;
  380. return;
  381. }
  382. const char* const pkg = list[1];
  383. const char* action = _strstrip(list[2]);
  384. // 'processing' from dpkg looks like
  385. // 'processing: action: pkg'
  386. if(strncmp(list[0], "processing", strlen("processing")) == 0)
  387. {
  388. char s[200];
  389. const char* const pkg_or_trigger = _strstrip(list[2]);
  390. action = _strstrip( list[1]);
  391. const std::pair<const char *, const char *> * const iter =
  392. std::find_if(PackageProcessingOpsBegin,
  393. PackageProcessingOpsEnd,
  394. MatchProcessingOp(action));
  395. if(iter == PackageProcessingOpsEnd)
  396. {
  397. if (Debug == true)
  398. std::clog << "ignoring unknown action: " << action << std::endl;
  399. return;
  400. }
  401. snprintf(s, sizeof(s), _(iter->second), pkg_or_trigger);
  402. status << "pmstatus:" << pkg_or_trigger
  403. << ":" << (PackagesDone/float(PackagesTotal)*100.0)
  404. << ":" << s
  405. << endl;
  406. if(OutStatusFd > 0)
  407. write(OutStatusFd, status.str().c_str(), status.str().size());
  408. if (Debug == true)
  409. std::clog << "send: '" << status.str() << "'" << endl;
  410. return;
  411. }
  412. if(strncmp(action,"error",strlen("error")) == 0)
  413. {
  414. // urgs, sometime has ":" in its error string so that we
  415. // end up with the error message split between list[3]
  416. // and list[4], e.g. the message:
  417. // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
  418. // concat them again
  419. if( list[4] != NULL )
  420. list[3][strlen(list[3])] = ':';
  421. status << "pmerror:" << list[1]
  422. << ":" << (PackagesDone/float(PackagesTotal)*100.0)
  423. << ":" << list[3]
  424. << endl;
  425. if(OutStatusFd > 0)
  426. write(OutStatusFd, status.str().c_str(), status.str().size());
  427. if (Debug == true)
  428. std::clog << "send: '" << status.str() << "'" << endl;
  429. pkgFailures++;
  430. WriteApportReport(list[1], list[3]);
  431. return;
  432. }
  433. else if(strncmp(action,"conffile",strlen("conffile")) == 0)
  434. {
  435. status << "pmconffile:" << list[1]
  436. << ":" << (PackagesDone/float(PackagesTotal)*100.0)
  437. << ":" << list[3]
  438. << endl;
  439. if(OutStatusFd > 0)
  440. write(OutStatusFd, status.str().c_str(), status.str().size());
  441. if (Debug == true)
  442. std::clog << "send: '" << status.str() << "'" << endl;
  443. return;
  444. }
  445. vector<struct DpkgState> const &states = PackageOps[pkg];
  446. const char *next_action = NULL;
  447. if(PackageOpsDone[pkg] < states.size())
  448. next_action = states[PackageOpsDone[pkg]].state;
  449. // check if the package moved to the next dpkg state
  450. if(next_action && (strcmp(action, next_action) == 0))
  451. {
  452. // only read the translation if there is actually a next
  453. // action
  454. const char *translation = _(states[PackageOpsDone[pkg]].str);
  455. char s[200];
  456. snprintf(s, sizeof(s), translation, pkg);
  457. // we moved from one dpkg state to a new one, report that
  458. PackageOpsDone[pkg]++;
  459. PackagesDone++;
  460. // build the status str
  461. status << "pmstatus:" << pkg
  462. << ":" << (PackagesDone/float(PackagesTotal)*100.0)
  463. << ":" << s
  464. << endl;
  465. if(OutStatusFd > 0)
  466. write(OutStatusFd, status.str().c_str(), status.str().size());
  467. if (Debug == true)
  468. std::clog << "send: '" << status.str() << "'" << endl;
  469. }
  470. if (Debug == true)
  471. std::clog << "(parsed from dpkg) pkg: " << pkg
  472. << " action: " << action << endl;
  473. }
  474. /*}}}*/
  475. // DPkgPM::DoDpkgStatusFd /*{{{*/
  476. // ---------------------------------------------------------------------
  477. /*
  478. */
  479. void pkgDPkgPM::DoDpkgStatusFd(int statusfd, int OutStatusFd)
  480. {
  481. char *p, *q;
  482. int len;
  483. len=read(statusfd, &dpkgbuf[dpkgbuf_pos], sizeof(dpkgbuf)-dpkgbuf_pos);
  484. dpkgbuf_pos += len;
  485. if(len <= 0)
  486. return;
  487. // process line by line if we have a buffer
  488. p = q = dpkgbuf;
  489. while((q=(char*)memchr(p, '\n', dpkgbuf+dpkgbuf_pos-p)) != NULL)
  490. {
  491. *q = 0;
  492. ProcessDpkgStatusLine(OutStatusFd, p);
  493. p=q+1; // continue with next line
  494. }
  495. // now move the unprocessed bits (after the final \n that is now a 0x0)
  496. // to the start and update dpkgbuf_pos
  497. p = (char*)memrchr(dpkgbuf, 0, dpkgbuf_pos);
  498. if(p == NULL)
  499. return;
  500. // we are interessted in the first char *after* 0x0
  501. p++;
  502. // move the unprocessed tail to the start and update pos
  503. memmove(dpkgbuf, p, p-dpkgbuf);
  504. dpkgbuf_pos = dpkgbuf+dpkgbuf_pos-p;
  505. }
  506. /*}}}*/
  507. // DPkgPM::WriteHistoryTag /*{{{*/
  508. void pkgDPkgPM::WriteHistoryTag(FILE *history_out, string tag, string value)
  509. {
  510. if (value.size() > 0)
  511. {
  512. // poor mans rstrip(", ")
  513. if (value[value.size()-2] == ',' && value[value.size()-1] == ' ')
  514. value.erase(value.size() - 2, 2);
  515. fprintf(history_out, "%s: %s\n", tag.c_str(), value.c_str());
  516. }
  517. } /*}}}*/
  518. // DPkgPM::OpenLog /*{{{*/
  519. bool pkgDPkgPM::OpenLog()
  520. {
  521. string logdir = _config->FindDir("Dir::Log");
  522. if(not FileExists(logdir))
  523. return _error->Error(_("Directory '%s' missing"), logdir.c_str());
  524. // get current time
  525. char timestr[200];
  526. time_t t = time(NULL);
  527. struct tm *tmp = localtime(&t);
  528. strftime(timestr, sizeof(timestr), "%F %T", tmp);
  529. // open terminal log
  530. string logfile_name = flCombine(logdir,
  531. _config->Find("Dir::Log::Terminal"));
  532. if (!logfile_name.empty())
  533. {
  534. term_out = fopen(logfile_name.c_str(),"a");
  535. if (term_out == NULL)
  536. return _error->WarningE(_("Could not open file '%s'"), logfile_name.c_str());
  537. chmod(logfile_name.c_str(), 0600);
  538. fprintf(term_out, "\nLog started: %s\n", timestr);
  539. }
  540. // write
  541. string history_name = flCombine(logdir,
  542. _config->Find("Dir::Log::History"));
  543. if (!history_name.empty())
  544. {
  545. FILE *history_out = fopen(history_name.c_str(),"a");
  546. chmod(history_name.c_str(), 0644);
  547. fprintf(history_out, "\nStart-Date: %s\n", timestr);
  548. string remove, purge, install, upgrade, downgrade;
  549. for (pkgCache::PkgIterator I = Cache.PkgBegin(); I.end() == false; I++)
  550. {
  551. if (Cache[I].NewInstall())
  552. install += I.Name() + string(" (") + Cache[I].CandVersion + string("), ");
  553. else if (Cache[I].Upgrade())
  554. upgrade += I.Name() + string(" (") + Cache[I].CurVersion + string(", ") + Cache[I].CandVersion + string("), ");
  555. else if (Cache[I].Downgrade())
  556. downgrade += I.Name() + string(" (") + Cache[I].CurVersion + string(", ") + Cache[I].CandVersion + string("), ");
  557. else if (Cache[I].Delete())
  558. {
  559. if ((Cache[I].iFlags & pkgDepCache::Purge) == pkgDepCache::Purge)
  560. purge += I.Name() + string(" (") + Cache[I].CurVersion + string("), ");
  561. else
  562. remove += I.Name() + string(" (") + Cache[I].CurVersion + string("), ");
  563. }
  564. }
  565. WriteHistoryTag(history_out, "Install", install);
  566. WriteHistoryTag(history_out, "Upgrade", upgrade);
  567. WriteHistoryTag(history_out, "Downgrade",downgrade);
  568. WriteHistoryTag(history_out, "Remove",remove);
  569. WriteHistoryTag(history_out, "Purge",purge);
  570. fclose(history_out);
  571. }
  572. return true;
  573. }
  574. /*}}}*/
  575. // DPkg::CloseLog /*{{{*/
  576. bool pkgDPkgPM::CloseLog()
  577. {
  578. char timestr[200];
  579. time_t t = time(NULL);
  580. struct tm *tmp = localtime(&t);
  581. strftime(timestr, sizeof(timestr), "%F %T", tmp);
  582. if(term_out)
  583. {
  584. fprintf(term_out, "Log ended: ");
  585. fprintf(term_out, "%s", timestr);
  586. fprintf(term_out, "\n");
  587. fclose(term_out);
  588. }
  589. term_out = NULL;
  590. string history_name = flCombine(_config->FindDir("Dir::Log"),
  591. _config->Find("Dir::Log::History"));
  592. if (!history_name.empty())
  593. {
  594. FILE *history_out = fopen(history_name.c_str(),"a");
  595. fprintf(history_out, "End-Date: %s\n", timestr);
  596. fclose(history_out);
  597. }
  598. return true;
  599. }
  600. /*}}}*/
  601. /*{{{*/
  602. // This implements a racy version of pselect for those architectures
  603. // that don't have a working implementation.
  604. // FIXME: Probably can be removed on Lenny+1
  605. static int racy_pselect(int nfds, fd_set *readfds, fd_set *writefds,
  606. fd_set *exceptfds, const struct timespec *timeout,
  607. const sigset_t *sigmask)
  608. {
  609. sigset_t origmask;
  610. struct timeval tv;
  611. int retval;
  612. tv.tv_sec = timeout->tv_sec;
  613. tv.tv_usec = timeout->tv_nsec/1000;
  614. sigprocmask(SIG_SETMASK, sigmask, &origmask);
  615. retval = select(nfds, readfds, writefds, exceptfds, &tv);
  616. sigprocmask(SIG_SETMASK, &origmask, 0);
  617. return retval;
  618. }
  619. /*}}}*/
  620. // DPkgPM::Go - Run the sequence /*{{{*/
  621. // ---------------------------------------------------------------------
  622. /* This globs the operations and calls dpkg
  623. *
  624. * If it is called with "OutStatusFd" set to a valid file descriptor
  625. * apt will report the install progress over this fd. It maps the
  626. * dpkg states a package goes through to human readable (and i10n-able)
  627. * names and calculates a percentage for each step.
  628. */
  629. bool pkgDPkgPM::Go(int OutStatusFd)
  630. {
  631. fd_set rfds;
  632. struct timespec tv;
  633. sigset_t sigmask;
  634. sigset_t original_sigmask;
  635. unsigned int const MaxArgs = _config->FindI("Dpkg::MaxArgs",8*1024);
  636. unsigned int const MaxArgBytes = _config->FindI("Dpkg::MaxArgBytes",32*1024);
  637. bool const NoTriggers = _config->FindB("DPkg::NoTriggers", false);
  638. if (RunScripts("DPkg::Pre-Invoke") == false)
  639. return false;
  640. if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
  641. return false;
  642. // support subpressing of triggers processing for special
  643. // cases like d-i that runs the triggers handling manually
  644. bool const SmartConf = (_config->Find("PackageManager::Configure", "all") != "all");
  645. bool const TriggersPending = _config->FindB("DPkg::TriggersPending", false);
  646. if (_config->FindB("DPkg::ConfigurePending", SmartConf) == true)
  647. List.push_back(Item(Item::ConfigurePending, PkgIterator()));
  648. // map the dpkg states to the operations that are performed
  649. // (this is sorted in the same way as Item::Ops)
  650. static const struct DpkgState DpkgStatesOpMap[][7] = {
  651. // Install operation
  652. {
  653. {"half-installed", N_("Preparing %s")},
  654. {"unpacked", N_("Unpacking %s") },
  655. {NULL, NULL}
  656. },
  657. // Configure operation
  658. {
  659. {"unpacked",N_("Preparing to configure %s") },
  660. {"half-configured", N_("Configuring %s") },
  661. { "installed", N_("Installed %s")},
  662. {NULL, NULL}
  663. },
  664. // Remove operation
  665. {
  666. {"half-configured", N_("Preparing for removal of %s")},
  667. {"half-installed", N_("Removing %s")},
  668. {"config-files", N_("Removed %s")},
  669. {NULL, NULL}
  670. },
  671. // Purge operation
  672. {
  673. {"config-files", N_("Preparing to completely remove %s")},
  674. {"not-installed", N_("Completely removed %s")},
  675. {NULL, NULL}
  676. },
  677. };
  678. // init the PackageOps map, go over the list of packages that
  679. // that will be [installed|configured|removed|purged] and add
  680. // them to the PackageOps map (the dpkg states it goes through)
  681. // and the PackageOpsTranslations (human readable strings)
  682. for (vector<Item>::const_iterator I = List.begin(); I != List.end();I++)
  683. {
  684. if((*I).Pkg.end() == true)
  685. continue;
  686. string const name = (*I).Pkg.Name();
  687. PackageOpsDone[name] = 0;
  688. for(int i=0; (DpkgStatesOpMap[(*I).Op][i]).state != NULL; i++)
  689. {
  690. PackageOps[name].push_back(DpkgStatesOpMap[(*I).Op][i]);
  691. PackagesTotal++;
  692. }
  693. }
  694. stdin_is_dev_null = false;
  695. // create log
  696. OpenLog();
  697. // this loop is runs once per operation
  698. for (vector<Item>::const_iterator I = List.begin(); I != List.end();)
  699. {
  700. // Do all actions with the same Op in one run
  701. vector<Item>::const_iterator J = I;
  702. if (TriggersPending == true)
  703. for (; J != List.end(); J++)
  704. {
  705. if (J->Op == I->Op)
  706. continue;
  707. if (J->Op != Item::TriggersPending)
  708. break;
  709. vector<Item>::const_iterator T = J + 1;
  710. if (T != List.end() && T->Op == I->Op)
  711. continue;
  712. break;
  713. }
  714. else
  715. for (; J != List.end() && J->Op == I->Op; J++)
  716. /* nothing */;
  717. // Generate the argument list
  718. const char *Args[MaxArgs + 50];
  719. // Now check if we are within the MaxArgs limit
  720. //
  721. // this code below is problematic, because it may happen that
  722. // the argument list is split in a way that A depends on B
  723. // and they are in the same "--configure A B" run
  724. // - with the split they may now be configured in different
  725. // runs
  726. if (J - I > (signed)MaxArgs)
  727. J = I + MaxArgs;
  728. unsigned int n = 0;
  729. unsigned long Size = 0;
  730. string const Tmp = _config->Find("Dir::Bin::dpkg","dpkg");
  731. Args[n++] = Tmp.c_str();
  732. Size += strlen(Args[n-1]);
  733. // Stick in any custom dpkg options
  734. Configuration::Item const *Opts = _config->Tree("DPkg::Options");
  735. if (Opts != 0)
  736. {
  737. Opts = Opts->Child;
  738. for (; Opts != 0; Opts = Opts->Next)
  739. {
  740. if (Opts->Value.empty() == true)
  741. continue;
  742. Args[n++] = Opts->Value.c_str();
  743. Size += Opts->Value.length();
  744. }
  745. }
  746. char status_fd_buf[20];
  747. int fd[2];
  748. pipe(fd);
  749. Args[n++] = "--status-fd";
  750. Size += strlen(Args[n-1]);
  751. snprintf(status_fd_buf,sizeof(status_fd_buf),"%i", fd[1]);
  752. Args[n++] = status_fd_buf;
  753. Size += strlen(Args[n-1]);
  754. switch (I->Op)
  755. {
  756. case Item::Remove:
  757. Args[n++] = "--force-depends";
  758. Size += strlen(Args[n-1]);
  759. Args[n++] = "--force-remove-essential";
  760. Size += strlen(Args[n-1]);
  761. Args[n++] = "--remove";
  762. Size += strlen(Args[n-1]);
  763. break;
  764. case Item::Purge:
  765. Args[n++] = "--force-depends";
  766. Size += strlen(Args[n-1]);
  767. Args[n++] = "--force-remove-essential";
  768. Size += strlen(Args[n-1]);
  769. Args[n++] = "--purge";
  770. Size += strlen(Args[n-1]);
  771. break;
  772. case Item::Configure:
  773. Args[n++] = "--configure";
  774. Size += strlen(Args[n-1]);
  775. break;
  776. case Item::ConfigurePending:
  777. Args[n++] = "--configure";
  778. Size += strlen(Args[n-1]);
  779. Args[n++] = "--pending";
  780. Size += strlen(Args[n-1]);
  781. break;
  782. case Item::TriggersPending:
  783. Args[n++] = "--triggers-only";
  784. Size += strlen(Args[n-1]);
  785. Args[n++] = "--pending";
  786. Size += strlen(Args[n-1]);
  787. break;
  788. case Item::Install:
  789. Args[n++] = "--unpack";
  790. Size += strlen(Args[n-1]);
  791. Args[n++] = "--auto-deconfigure";
  792. Size += strlen(Args[n-1]);
  793. break;
  794. }
  795. if (NoTriggers == true && I->Op != Item::TriggersPending &&
  796. I->Op != Item::ConfigurePending)
  797. {
  798. Args[n++] = "--no-triggers";
  799. Size += strlen(Args[n-1]);
  800. }
  801. // Write in the file or package names
  802. if (I->Op == Item::Install)
  803. {
  804. for (;I != J && Size < MaxArgBytes; I++)
  805. {
  806. if (I->File[0] != '/')
  807. return _error->Error("Internal Error, Pathname to install is not absolute '%s'",I->File.c_str());
  808. Args[n++] = I->File.c_str();
  809. Size += strlen(Args[n-1]);
  810. }
  811. }
  812. else
  813. {
  814. for (;I != J && Size < MaxArgBytes; I++)
  815. {
  816. if((*I).Pkg.end() == true)
  817. continue;
  818. Args[n++] = I->Pkg.Name();
  819. Size += strlen(Args[n-1]);
  820. }
  821. }
  822. Args[n] = 0;
  823. J = I;
  824. if (_config->FindB("Debug::pkgDPkgPM",false) == true)
  825. {
  826. for (unsigned int k = 0; k != n; k++)
  827. clog << Args[k] << ' ';
  828. clog << endl;
  829. continue;
  830. }
  831. cout << flush;
  832. clog << flush;
  833. cerr << flush;
  834. /* Mask off sig int/quit. We do this because dpkg also does when
  835. it forks scripts. What happens is that when you hit ctrl-c it sends
  836. it to all processes in the group. Since dpkg ignores the signal
  837. it doesn't die but we do! So we must also ignore it */
  838. sighandler_t old_SIGQUIT = signal(SIGQUIT,SIG_IGN);
  839. sighandler_t old_SIGINT = signal(SIGINT,SIG_IGN);
  840. // ignore SIGHUP as well (debian #463030)
  841. sighandler_t old_SIGHUP = signal(SIGHUP,SIG_IGN);
  842. struct termios tt;
  843. struct winsize win;
  844. int master = -1;
  845. int slave = -1;
  846. // if tcgetattr does not return zero there was a error
  847. // and we do not do any pty magic
  848. if (tcgetattr(0, &tt) == 0)
  849. {
  850. ioctl(0, TIOCGWINSZ, (char *)&win);
  851. if (openpty(&master, &slave, NULL, &tt, &win) < 0)
  852. {
  853. const char *s = _("Can not write log, openpty() "
  854. "failed (/dev/pts not mounted?)\n");
  855. fprintf(stderr, "%s",s);
  856. if(term_out)
  857. fprintf(term_out, "%s",s);
  858. master = slave = -1;
  859. } else {
  860. struct termios rtt;
  861. rtt = tt;
  862. cfmakeraw(&rtt);
  863. rtt.c_lflag &= ~ECHO;
  864. // block SIGTTOU during tcsetattr to prevent a hang if
  865. // the process is a member of the background process group
  866. // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
  867. sigemptyset(&sigmask);
  868. sigaddset(&sigmask, SIGTTOU);
  869. sigprocmask(SIG_BLOCK,&sigmask, &original_sigmask);
  870. tcsetattr(0, TCSAFLUSH, &rtt);
  871. sigprocmask(SIG_SETMASK, &original_sigmask, 0);
  872. }
  873. }
  874. // Fork dpkg
  875. pid_t Child;
  876. _config->Set("APT::Keep-Fds::",fd[1]);
  877. // send status information that we are about to fork dpkg
  878. if(OutStatusFd > 0) {
  879. ostringstream status;
  880. status << "pmstatus:dpkg-exec:"
  881. << (PackagesDone/float(PackagesTotal)*100.0)
  882. << ":" << _("Running dpkg")
  883. << endl;
  884. write(OutStatusFd, status.str().c_str(), status.str().size());
  885. }
  886. Child = ExecFork();
  887. // This is the child
  888. if (Child == 0)
  889. {
  890. if(slave >= 0 && master >= 0)
  891. {
  892. setsid();
  893. ioctl(slave, TIOCSCTTY, 0);
  894. close(master);
  895. dup2(slave, 0);
  896. dup2(slave, 1);
  897. dup2(slave, 2);
  898. close(slave);
  899. }
  900. close(fd[0]); // close the read end of the pipe
  901. if (_config->FindDir("DPkg::Chroot-Directory","/") != "/")
  902. {
  903. std::cerr << "Chrooting into "
  904. << _config->FindDir("DPkg::Chroot-Directory")
  905. << std::endl;
  906. if (chroot(_config->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
  907. _exit(100);
  908. }
  909. if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
  910. _exit(100);
  911. if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
  912. {
  913. int Flags,dummy;
  914. if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
  915. _exit(100);
  916. // Discard everything in stdin before forking dpkg
  917. if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
  918. _exit(100);
  919. while (read(STDIN_FILENO,&dummy,1) == 1);
  920. if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
  921. _exit(100);
  922. }
  923. /* No Job Control Stop Env is a magic dpkg var that prevents it
  924. from using sigstop */
  925. putenv((char *)"DPKG_NO_TSTP=yes");
  926. execvp(Args[0],(char **)Args);
  927. cerr << "Could not exec dpkg!" << endl;
  928. _exit(100);
  929. }
  930. // apply ionice
  931. if (_config->FindB("DPkg::UseIoNice", false) == true)
  932. ionice(Child);
  933. // clear the Keep-Fd again
  934. _config->Clear("APT::Keep-Fds",fd[1]);
  935. // Wait for dpkg
  936. int Status = 0;
  937. // we read from dpkg here
  938. int const _dpkgin = fd[0];
  939. close(fd[1]); // close the write end of the pipe
  940. if(slave > 0)
  941. close(slave);
  942. // setups fds
  943. sigemptyset(&sigmask);
  944. sigprocmask(SIG_BLOCK,&sigmask,&original_sigmask);
  945. // the result of the waitpid call
  946. int res;
  947. int select_ret;
  948. while ((res=waitpid(Child,&Status, WNOHANG)) != Child) {
  949. if(res < 0) {
  950. // FIXME: move this to a function or something, looks ugly here
  951. // error handling, waitpid returned -1
  952. if (errno == EINTR)
  953. continue;
  954. RunScripts("DPkg::Post-Invoke");
  955. // Restore sig int/quit
  956. signal(SIGQUIT,old_SIGQUIT);
  957. signal(SIGINT,old_SIGINT);
  958. signal(SIGHUP,old_SIGHUP);
  959. return _error->Errno("waitpid","Couldn't wait for subprocess");
  960. }
  961. // wait for input or output here
  962. FD_ZERO(&rfds);
  963. if (!stdin_is_dev_null)
  964. FD_SET(0, &rfds);
  965. FD_SET(_dpkgin, &rfds);
  966. if(master >= 0)
  967. FD_SET(master, &rfds);
  968. tv.tv_sec = 1;
  969. tv.tv_nsec = 0;
  970. select_ret = pselect(max(master, _dpkgin)+1, &rfds, NULL, NULL,
  971. &tv, &original_sigmask);
  972. if (select_ret < 0 && (errno == EINVAL || errno == ENOSYS))
  973. select_ret = racy_pselect(max(master, _dpkgin)+1, &rfds, NULL,
  974. NULL, &tv, &original_sigmask);
  975. if (select_ret == 0)
  976. continue;
  977. else if (select_ret < 0 && errno == EINTR)
  978. continue;
  979. else if (select_ret < 0)
  980. {
  981. perror("select() returned error");
  982. continue;
  983. }
  984. if(master >= 0 && FD_ISSET(master, &rfds))
  985. DoTerminalPty(master);
  986. if(master >= 0 && FD_ISSET(0, &rfds))
  987. DoStdin(master);
  988. if(FD_ISSET(_dpkgin, &rfds))
  989. DoDpkgStatusFd(_dpkgin, OutStatusFd);
  990. }
  991. close(_dpkgin);
  992. // Restore sig int/quit
  993. signal(SIGQUIT,old_SIGQUIT);
  994. signal(SIGINT,old_SIGINT);
  995. signal(SIGHUP,old_SIGHUP);
  996. if(master >= 0)
  997. {
  998. tcsetattr(0, TCSAFLUSH, &tt);
  999. close(master);
  1000. }
  1001. // Check for an error code.
  1002. if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
  1003. {
  1004. // if it was set to "keep-dpkg-runing" then we won't return
  1005. // here but keep the loop going and just report it as a error
  1006. // for later
  1007. bool const stopOnError = _config->FindB("Dpkg::StopOnError",true);
  1008. if(stopOnError)
  1009. RunScripts("DPkg::Post-Invoke");
  1010. string dpkg_error;
  1011. if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
  1012. strprintf(dpkg_error, "Sub-process %s received a segmentation fault.",Args[0]);
  1013. else if (WIFEXITED(Status) != 0)
  1014. strprintf(dpkg_error, "Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
  1015. else
  1016. strprintf(dpkg_error, "Sub-process %s exited unexpectedly",Args[0]);
  1017. if(dpkg_error.size() > 0)
  1018. {
  1019. _error->Error(dpkg_error.c_str());
  1020. string history_name = flCombine(_config->FindDir("Dir::Log"),
  1021. _config->Find("Dir::Log::History"));
  1022. if (!history_name.empty())
  1023. {
  1024. FILE *history_out = fopen(history_name.c_str(),"a");
  1025. fprintf(history_out, "Error: %s\n", dpkg_error.c_str());
  1026. fclose(history_out);
  1027. }
  1028. }
  1029. if(stopOnError)
  1030. {
  1031. CloseLog();
  1032. return false;
  1033. }
  1034. }
  1035. }
  1036. CloseLog();
  1037. if (RunScripts("DPkg::Post-Invoke") == false)
  1038. return false;
  1039. Cache.writeStateFile(NULL);
  1040. return true;
  1041. }
  1042. /*}}}*/
  1043. // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
  1044. // ---------------------------------------------------------------------
  1045. /* */
  1046. void pkgDPkgPM::Reset()
  1047. {
  1048. List.erase(List.begin(),List.end());
  1049. }
  1050. /*}}}*/
  1051. // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
  1052. // ---------------------------------------------------------------------
  1053. /* */
  1054. void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
  1055. {
  1056. string pkgname, reportfile, srcpkgname, pkgver, arch;
  1057. string::size_type pos;
  1058. FILE *report;
  1059. if (_config->FindB("Dpkg::ApportFailureReport",true) == false)
  1060. {
  1061. std::clog << "configured to not write apport reports" << std::endl;
  1062. return;
  1063. }
  1064. // only report the first errors
  1065. if(pkgFailures > _config->FindI("APT::Apport::MaxReports", 3))
  1066. {
  1067. std::clog << _("No apport report written because MaxReports is reached already") << std::endl;
  1068. return;
  1069. }
  1070. // check if its not a follow up error
  1071. const char *needle = dgettext("dpkg", "dependency problems - leaving unconfigured");
  1072. if(strstr(errormsg, needle) != NULL) {
  1073. std::clog << _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl;
  1074. return;
  1075. }
  1076. // do not report disk-full failures
  1077. if(strstr(errormsg, strerror(ENOSPC)) != NULL) {
  1078. std::clog << _("No apport report written because the error message indicates a disk full error") << std::endl;
  1079. return;
  1080. }
  1081. // do not report out-of-memory failures
  1082. if(strstr(errormsg, strerror(ENOMEM)) != NULL) {
  1083. std::clog << _("No apport report written because the error message indicates a out of memory error") << std::endl;
  1084. return;
  1085. }
  1086. // do not report dpkg I/O errors
  1087. // XXX - this message is localized, but this only matches the English version. This is better than nothing.
  1088. if(strstr(errormsg, "short read in buffer_copy (")) {
  1089. std::clog << _("No apport report written because the error message indicates a dpkg I/O error") << std::endl;
  1090. return;
  1091. }
  1092. // get the pkgname and reportfile
  1093. pkgname = flNotDir(pkgpath);
  1094. pos = pkgname.find('_');
  1095. if(pos != string::npos)
  1096. pkgname = pkgname.substr(0, pos);
  1097. // find the package versin and source package name
  1098. pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
  1099. if (Pkg.end() == true)
  1100. return;
  1101. pkgCache::VerIterator Ver = Cache.GetCandidateVer(Pkg);
  1102. if (Ver.end() == true)
  1103. return;
  1104. pkgver = Ver.VerStr() == NULL ? "unknown" : Ver.VerStr();
  1105. pkgRecords Recs(Cache);
  1106. pkgRecords::Parser &Parse = Recs.Lookup(Ver.FileList());
  1107. srcpkgname = Parse.SourcePkg();
  1108. if(srcpkgname.empty())
  1109. srcpkgname = pkgname;
  1110. // if the file exists already, we check:
  1111. // - if it was reported already (touched by apport).
  1112. // If not, we do nothing, otherwise
  1113. // we overwrite it. This is the same behaviour as apport
  1114. // - if we have a report with the same pkgversion already
  1115. // then we skip it
  1116. reportfile = flCombine("/var/crash",pkgname+".0.crash");
  1117. if(FileExists(reportfile))
  1118. {
  1119. struct stat buf;
  1120. char strbuf[255];
  1121. // check atime/mtime
  1122. stat(reportfile.c_str(), &buf);
  1123. if(buf.st_mtime > buf.st_atime)
  1124. return;
  1125. // check if the existing report is the same version
  1126. report = fopen(reportfile.c_str(),"r");
  1127. while(fgets(strbuf, sizeof(strbuf), report) != NULL)
  1128. {
  1129. if(strstr(strbuf,"Package:") == strbuf)
  1130. {
  1131. char pkgname[255], version[255];
  1132. if(sscanf(strbuf, "Package: %s %s", pkgname, version) == 2)
  1133. if(strcmp(pkgver.c_str(), version) == 0)
  1134. {
  1135. fclose(report);
  1136. return;
  1137. }
  1138. }
  1139. }
  1140. fclose(report);
  1141. }
  1142. // now write the report
  1143. arch = _config->Find("APT::Architecture");
  1144. report = fopen(reportfile.c_str(),"w");
  1145. if(report == NULL)
  1146. return;
  1147. if(_config->FindB("DPkgPM::InitialReportOnly",false) == true)
  1148. chmod(reportfile.c_str(), 0);
  1149. else
  1150. chmod(reportfile.c_str(), 0600);
  1151. fprintf(report, "ProblemType: Package\n");
  1152. fprintf(report, "Architecture: %s\n", arch.c_str());
  1153. time_t now = time(NULL);
  1154. fprintf(report, "Date: %s" , ctime(&now));
  1155. fprintf(report, "Package: %s %s\n", pkgname.c_str(), pkgver.c_str());
  1156. fprintf(report, "SourcePackage: %s\n", srcpkgname.c_str());
  1157. fprintf(report, "ErrorMessage:\n %s\n", errormsg);
  1158. // ensure that the log is flushed
  1159. if(term_out)
  1160. fflush(term_out);
  1161. // attach terminal log it if we have it
  1162. string logfile_name = _config->FindFile("Dir::Log::Terminal");
  1163. if (!logfile_name.empty())
  1164. {
  1165. FILE *log = NULL;
  1166. char buf[1024];
  1167. fprintf(report, "DpkgTerminalLog:\n");
  1168. log = fopen(logfile_name.c_str(),"r");
  1169. if(log != NULL)
  1170. {
  1171. while( fgets(buf, sizeof(buf), log) != NULL)
  1172. fprintf(report, " %s", buf);
  1173. fclose(log);
  1174. }
  1175. }
  1176. // log the ordering
  1177. const char *ops_str[] = {"Install", "Configure","Remove","Purge"};
  1178. fprintf(report, "AptOrdering:\n");
  1179. for (vector<Item>::iterator I = List.begin(); I != List.end(); I++)
  1180. fprintf(report, " %s: %s\n", (*I).Pkg.Name(), ops_str[(*I).Op]);
  1181. // attach dmesg log (to learn about segfaults)
  1182. if (FileExists("/bin/dmesg"))
  1183. {
  1184. FILE *log = NULL;
  1185. char buf[1024];
  1186. fprintf(report, "Dmesg:\n");
  1187. log = popen("/bin/dmesg","r");
  1188. if(log != NULL)
  1189. {
  1190. while( fgets(buf, sizeof(buf), log) != NULL)
  1191. fprintf(report, " %s", buf);
  1192. fclose(log);
  1193. }
  1194. }
  1195. // attach df -l log (to learn about filesystem status)
  1196. if (FileExists("/bin/df"))
  1197. {
  1198. FILE *log = NULL;
  1199. char buf[1024];
  1200. fprintf(report, "Df:\n");
  1201. log = popen("/bin/df -l","r");
  1202. if(log != NULL)
  1203. {
  1204. while( fgets(buf, sizeof(buf), log) != NULL)
  1205. fprintf(report, " %s", buf);
  1206. fclose(log);
  1207. }
  1208. }
  1209. fclose(report);
  1210. }
  1211. /*}}}*/