dpkgpm.cc 49 KB

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