dpkgpm.cc 49 KB

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