dpkgpm.cc 53 KB

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