dpkgpm.cc 46 KB

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