dpkgpm.cc 47 KB

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