dpkgpm.cc 52 KB

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