dpkgpm.cc 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691
  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(OutStatusFd > 0)
  574. FileFd::Write(OutStatusFd, status.str().c_str(), status.str().size());
  575. if (Debug == true)
  576. std::clog << "send: '" << status.str() << "'" << endl;
  577. }
  578. if (Debug == true)
  579. std::clog << "(parsed from dpkg) pkg: " << pkg
  580. << " action: " << action << endl;
  581. }
  582. /*}}}*/
  583. // DPkgPM::handleDisappearAction /*{{{*/
  584. void pkgDPkgPM::handleDisappearAction(string const &pkgname)
  585. {
  586. // record the package name for display and stuff later
  587. disappearedPkgs.insert(pkgname);
  588. pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
  589. if (unlikely(Pkg.end() == true))
  590. return;
  591. // the disappeared package was auto-installed - nothing to do
  592. if ((Cache[Pkg].Flags & pkgCache::Flag::Auto) == pkgCache::Flag::Auto)
  593. return;
  594. pkgCache::VerIterator PkgVer = Cache[Pkg].InstVerIter(Cache);
  595. if (unlikely(PkgVer.end() == true))
  596. return;
  597. /* search in the list of dependencies for (Pre)Depends,
  598. check if this dependency has a Replaces on our package
  599. and if so transfer the manual installed flag to it */
  600. for (pkgCache::DepIterator Dep = PkgVer.DependsList(); Dep.end() != true; ++Dep)
  601. {
  602. if (Dep->Type != pkgCache::Dep::Depends &&
  603. Dep->Type != pkgCache::Dep::PreDepends)
  604. continue;
  605. pkgCache::PkgIterator Tar = Dep.TargetPkg();
  606. if (unlikely(Tar.end() == true))
  607. continue;
  608. // the package is already marked as manual
  609. if ((Cache[Tar].Flags & pkgCache::Flag::Auto) != pkgCache::Flag::Auto)
  610. continue;
  611. pkgCache::VerIterator TarVer = Cache[Tar].InstVerIter(Cache);
  612. if (TarVer.end() == true)
  613. continue;
  614. for (pkgCache::DepIterator Rep = TarVer.DependsList(); Rep.end() != true; ++Rep)
  615. {
  616. if (Rep->Type != pkgCache::Dep::Replaces)
  617. continue;
  618. if (Pkg != Rep.TargetPkg())
  619. continue;
  620. // okay, they are strongly connected - transfer manual-bit
  621. if (Debug == true)
  622. std::clog << "transfer manual-bit from disappeared »" << pkgname << "« to »" << Tar.FullName() << "«" << std::endl;
  623. Cache[Tar].Flags &= ~Flag::Auto;
  624. break;
  625. }
  626. }
  627. }
  628. /*}}}*/
  629. // DPkgPM::DoDpkgStatusFd /*{{{*/
  630. // ---------------------------------------------------------------------
  631. /*
  632. */
  633. void pkgDPkgPM::DoDpkgStatusFd(int statusfd, int OutStatusFd)
  634. {
  635. char *p, *q;
  636. int len;
  637. len=read(statusfd, &d->dpkgbuf[d->dpkgbuf_pos], sizeof(d->dpkgbuf)-d->dpkgbuf_pos);
  638. d->dpkgbuf_pos += len;
  639. if(len <= 0)
  640. return;
  641. // process line by line if we have a buffer
  642. p = q = d->dpkgbuf;
  643. while((q=(char*)memchr(p, '\n', d->dpkgbuf+d->dpkgbuf_pos-p)) != NULL)
  644. {
  645. *q = 0;
  646. ProcessDpkgStatusLine(OutStatusFd, p);
  647. p=q+1; // continue with next line
  648. }
  649. // now move the unprocessed bits (after the final \n that is now a 0x0)
  650. // to the start and update d->dpkgbuf_pos
  651. p = (char*)memrchr(d->dpkgbuf, 0, d->dpkgbuf_pos);
  652. if(p == NULL)
  653. return;
  654. // we are interessted in the first char *after* 0x0
  655. p++;
  656. // move the unprocessed tail to the start and update pos
  657. memmove(d->dpkgbuf, p, p-d->dpkgbuf);
  658. d->dpkgbuf_pos = d->dpkgbuf+d->dpkgbuf_pos-p;
  659. }
  660. /*}}}*/
  661. // DPkgPM::WriteHistoryTag /*{{{*/
  662. void pkgDPkgPM::WriteHistoryTag(string const &tag, string value)
  663. {
  664. size_t const length = value.length();
  665. if (length == 0)
  666. return;
  667. // poor mans rstrip(", ")
  668. if (value[length-2] == ',' && value[length-1] == ' ')
  669. value.erase(length - 2, 2);
  670. fprintf(d->history_out, "%s: %s\n", tag.c_str(), value.c_str());
  671. } /*}}}*/
  672. // DPkgPM::OpenLog /*{{{*/
  673. bool pkgDPkgPM::OpenLog()
  674. {
  675. string const logdir = _config->FindDir("Dir::Log");
  676. if(CreateAPTDirectoryIfNeeded(logdir, logdir) == false)
  677. // FIXME: use a better string after freeze
  678. return _error->Error(_("Directory '%s' missing"), logdir.c_str());
  679. // get current time
  680. char timestr[200];
  681. time_t const t = time(NULL);
  682. struct tm const * const tmp = localtime(&t);
  683. strftime(timestr, sizeof(timestr), "%F %T", tmp);
  684. // open terminal log
  685. string const logfile_name = flCombine(logdir,
  686. _config->Find("Dir::Log::Terminal"));
  687. if (!logfile_name.empty())
  688. {
  689. d->term_out = fopen(logfile_name.c_str(),"a");
  690. if (d->term_out == NULL)
  691. return _error->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name.c_str());
  692. setvbuf(d->term_out, NULL, _IONBF, 0);
  693. SetCloseExec(fileno(d->term_out), true);
  694. if (getuid() == 0) // if we aren't root, we can't chown a file, so don't try it
  695. {
  696. struct passwd *pw = getpwnam("root");
  697. struct group *gr = getgrnam("adm");
  698. if (pw != NULL && gr != NULL && chown(logfile_name.c_str(), pw->pw_uid, gr->gr_gid) != 0)
  699. _error->WarningE("OpenLog", "chown to root:adm of file %s failed", logfile_name.c_str());
  700. }
  701. if (chmod(logfile_name.c_str(), 0640) != 0)
  702. _error->WarningE("OpenLog", "chmod 0640 of file %s failed", logfile_name.c_str());
  703. fprintf(d->term_out, "\nLog started: %s\n", timestr);
  704. }
  705. // write your history
  706. string const history_name = flCombine(logdir,
  707. _config->Find("Dir::Log::History"));
  708. if (!history_name.empty())
  709. {
  710. d->history_out = fopen(history_name.c_str(),"a");
  711. if (d->history_out == NULL)
  712. return _error->WarningE("OpenLog", _("Could not open file '%s'"), history_name.c_str());
  713. SetCloseExec(fileno(d->history_out), true);
  714. chmod(history_name.c_str(), 0644);
  715. fprintf(d->history_out, "\nStart-Date: %s\n", timestr);
  716. string remove, purge, install, reinstall, upgrade, downgrade;
  717. for (pkgCache::PkgIterator I = Cache.PkgBegin(); I.end() == false; ++I)
  718. {
  719. enum { CANDIDATE, CANDIDATE_AUTO, CURRENT_CANDIDATE, CURRENT } infostring;
  720. string *line = NULL;
  721. #define HISTORYINFO(X, Y) { line = &X; infostring = Y; }
  722. if (Cache[I].NewInstall() == true)
  723. HISTORYINFO(install, CANDIDATE_AUTO)
  724. else if (Cache[I].ReInstall() == true)
  725. HISTORYINFO(reinstall, CANDIDATE)
  726. else if (Cache[I].Upgrade() == true)
  727. HISTORYINFO(upgrade, CURRENT_CANDIDATE)
  728. else if (Cache[I].Downgrade() == true)
  729. HISTORYINFO(downgrade, CURRENT_CANDIDATE)
  730. else if (Cache[I].Delete() == true)
  731. HISTORYINFO((Cache[I].Purge() ? purge : remove), CURRENT)
  732. else
  733. continue;
  734. #undef HISTORYINFO
  735. line->append(I.FullName(false)).append(" (");
  736. switch (infostring) {
  737. case CANDIDATE: line->append(Cache[I].CandVersion); break;
  738. case CANDIDATE_AUTO:
  739. line->append(Cache[I].CandVersion);
  740. if ((Cache[I].Flags & pkgCache::Flag::Auto) == pkgCache::Flag::Auto)
  741. line->append(", automatic");
  742. break;
  743. case CURRENT_CANDIDATE: line->append(Cache[I].CurVersion).append(", ").append(Cache[I].CandVersion); break;
  744. case CURRENT: line->append(Cache[I].CurVersion); break;
  745. }
  746. line->append("), ");
  747. }
  748. if (_config->Exists("Commandline::AsString") == true)
  749. WriteHistoryTag("Commandline", _config->Find("Commandline::AsString"));
  750. WriteHistoryTag("Install", install);
  751. WriteHistoryTag("Reinstall", reinstall);
  752. WriteHistoryTag("Upgrade", upgrade);
  753. WriteHistoryTag("Downgrade",downgrade);
  754. WriteHistoryTag("Remove",remove);
  755. WriteHistoryTag("Purge",purge);
  756. fflush(d->history_out);
  757. }
  758. return true;
  759. }
  760. /*}}}*/
  761. // DPkg::CloseLog /*{{{*/
  762. bool pkgDPkgPM::CloseLog()
  763. {
  764. char timestr[200];
  765. time_t t = time(NULL);
  766. struct tm *tmp = localtime(&t);
  767. strftime(timestr, sizeof(timestr), "%F %T", tmp);
  768. if(d->term_out)
  769. {
  770. fprintf(d->term_out, "Log ended: ");
  771. fprintf(d->term_out, "%s", timestr);
  772. fprintf(d->term_out, "\n");
  773. fclose(d->term_out);
  774. }
  775. d->term_out = NULL;
  776. if(d->history_out)
  777. {
  778. if (disappearedPkgs.empty() == false)
  779. {
  780. string disappear;
  781. for (std::set<std::string>::const_iterator d = disappearedPkgs.begin();
  782. d != disappearedPkgs.end(); ++d)
  783. {
  784. pkgCache::PkgIterator P = Cache.FindPkg(*d);
  785. disappear.append(*d);
  786. if (P.end() == true)
  787. disappear.append(", ");
  788. else
  789. disappear.append(" (").append(Cache[P].CurVersion).append("), ");
  790. }
  791. WriteHistoryTag("Disappeared", disappear);
  792. }
  793. if (d->dpkg_error.empty() == false)
  794. fprintf(d->history_out, "Error: %s\n", d->dpkg_error.c_str());
  795. fprintf(d->history_out, "End-Date: %s\n", timestr);
  796. fclose(d->history_out);
  797. }
  798. d->history_out = NULL;
  799. return true;
  800. }
  801. /*}}}*/
  802. /*{{{*/
  803. // This implements a racy version of pselect for those architectures
  804. // that don't have a working implementation.
  805. // FIXME: Probably can be removed on Lenny+1
  806. static int racy_pselect(int nfds, fd_set *readfds, fd_set *writefds,
  807. fd_set *exceptfds, const struct timespec *timeout,
  808. const sigset_t *sigmask)
  809. {
  810. sigset_t origmask;
  811. struct timeval tv;
  812. int retval;
  813. tv.tv_sec = timeout->tv_sec;
  814. tv.tv_usec = timeout->tv_nsec/1000;
  815. sigprocmask(SIG_SETMASK, sigmask, &origmask);
  816. retval = select(nfds, readfds, writefds, exceptfds, &tv);
  817. sigprocmask(SIG_SETMASK, &origmask, 0);
  818. return retval;
  819. }
  820. /*}}}*/
  821. // DPkgPM::Go - Run the sequence /*{{{*/
  822. // ---------------------------------------------------------------------
  823. /* This globs the operations and calls dpkg
  824. *
  825. * If it is called with "OutStatusFd" set to a valid file descriptor
  826. * apt will report the install progress over this fd. It maps the
  827. * dpkg states a package goes through to human readable (and i10n-able)
  828. * names and calculates a percentage for each step.
  829. */
  830. bool pkgDPkgPM::Go(int OutStatusFd)
  831. {
  832. pkgPackageManager::SigINTStop = false;
  833. // Generate the base argument list for dpkg
  834. std::vector<const char *> Args;
  835. unsigned long StartSize = 0;
  836. string Tmp = _config->Find("Dir::Bin::dpkg","dpkg");
  837. {
  838. string const dpkgChrootDir = _config->FindDir("DPkg::Chroot-Directory", "/");
  839. size_t dpkgChrootLen = dpkgChrootDir.length();
  840. if (dpkgChrootDir != "/" && Tmp.find(dpkgChrootDir) == 0)
  841. {
  842. if (dpkgChrootDir[dpkgChrootLen - 1] == '/')
  843. --dpkgChrootLen;
  844. Tmp = Tmp.substr(dpkgChrootLen);
  845. }
  846. }
  847. Args.push_back(Tmp.c_str());
  848. StartSize += Tmp.length();
  849. // Stick in any custom dpkg options
  850. Configuration::Item const *Opts = _config->Tree("DPkg::Options");
  851. if (Opts != 0)
  852. {
  853. Opts = Opts->Child;
  854. for (; Opts != 0; Opts = Opts->Next)
  855. {
  856. if (Opts->Value.empty() == true)
  857. continue;
  858. Args.push_back(Opts->Value.c_str());
  859. StartSize += Opts->Value.length();
  860. }
  861. }
  862. size_t const BaseArgs = Args.size();
  863. // we need to detect if we can qualify packages with the architecture or not
  864. Args.push_back("--assert-multi-arch");
  865. Args.push_back(NULL);
  866. pid_t dpkgAssertMultiArch = ExecFork();
  867. if (dpkgAssertMultiArch == 0)
  868. {
  869. dpkgChrootDirectory();
  870. // redirect everything to the ultimate sink as we only need the exit-status
  871. int const nullfd = open("/dev/null", O_RDONLY);
  872. dup2(nullfd, STDIN_FILENO);
  873. dup2(nullfd, STDOUT_FILENO);
  874. dup2(nullfd, STDERR_FILENO);
  875. execvp(Args[0], (char**) &Args[0]);
  876. _error->WarningE("dpkgGo", "Can't detect if dpkg supports multi-arch!");
  877. _exit(2);
  878. }
  879. fd_set rfds;
  880. struct timespec tv;
  881. sigset_t sigmask;
  882. sigset_t original_sigmask;
  883. unsigned int const MaxArgs = _config->FindI("Dpkg::MaxArgs",8*1024);
  884. unsigned int const MaxArgBytes = _config->FindI("Dpkg::MaxArgBytes",32*1024);
  885. bool const NoTriggers = _config->FindB("DPkg::NoTriggers", false);
  886. if (RunScripts("DPkg::Pre-Invoke") == false)
  887. return false;
  888. if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
  889. return false;
  890. // support subpressing of triggers processing for special
  891. // cases like d-i that runs the triggers handling manually
  892. bool const SmartConf = (_config->Find("PackageManager::Configure", "all") != "all");
  893. bool const TriggersPending = _config->FindB("DPkg::TriggersPending", false);
  894. if (_config->FindB("DPkg::ConfigurePending", SmartConf) == true)
  895. List.push_back(Item(Item::ConfigurePending, PkgIterator()));
  896. // map the dpkg states to the operations that are performed
  897. // (this is sorted in the same way as Item::Ops)
  898. static const struct DpkgState DpkgStatesOpMap[][7] = {
  899. // Install operation
  900. {
  901. {"half-installed", N_("Preparing %s")},
  902. {"unpacked", N_("Unpacking %s") },
  903. {NULL, NULL}
  904. },
  905. // Configure operation
  906. {
  907. {"unpacked",N_("Preparing to configure %s") },
  908. {"half-configured", N_("Configuring %s") },
  909. { "installed", N_("Installed %s")},
  910. {NULL, NULL}
  911. },
  912. // Remove operation
  913. {
  914. {"half-configured", N_("Preparing for removal of %s")},
  915. {"half-installed", N_("Removing %s")},
  916. {"config-files", N_("Removed %s")},
  917. {NULL, NULL}
  918. },
  919. // Purge operation
  920. {
  921. {"config-files", N_("Preparing to completely remove %s")},
  922. {"not-installed", N_("Completely removed %s")},
  923. {NULL, NULL}
  924. },
  925. };
  926. // init the PackageOps map, go over the list of packages that
  927. // that will be [installed|configured|removed|purged] and add
  928. // them to the PackageOps map (the dpkg states it goes through)
  929. // and the PackageOpsTranslations (human readable strings)
  930. for (vector<Item>::const_iterator I = List.begin(); I != List.end(); ++I)
  931. {
  932. if((*I).Pkg.end() == true)
  933. continue;
  934. string const name = (*I).Pkg.Name();
  935. PackageOpsDone[name] = 0;
  936. for(int i=0; (DpkgStatesOpMap[(*I).Op][i]).state != NULL; ++i)
  937. {
  938. PackageOps[name].push_back(DpkgStatesOpMap[(*I).Op][i]);
  939. PackagesTotal++;
  940. }
  941. }
  942. d->stdin_is_dev_null = false;
  943. // create log
  944. OpenLog();
  945. bool dpkgMultiArch = false;
  946. if (dpkgAssertMultiArch > 0)
  947. {
  948. int Status = 0;
  949. while (waitpid(dpkgAssertMultiArch, &Status, 0) != dpkgAssertMultiArch)
  950. {
  951. if (errno == EINTR)
  952. continue;
  953. _error->WarningE("dpkgGo", _("Waited for %s but it wasn't there"), "dpkg --assert-multi-arch");
  954. break;
  955. }
  956. if (WIFEXITED(Status) == true && WEXITSTATUS(Status) == 0)
  957. dpkgMultiArch = true;
  958. }
  959. // this loop is runs once per operation
  960. for (vector<Item>::const_iterator I = List.begin(); I != List.end();)
  961. {
  962. // Do all actions with the same Op in one run
  963. vector<Item>::const_iterator J = I;
  964. if (TriggersPending == true)
  965. for (; J != List.end(); ++J)
  966. {
  967. if (J->Op == I->Op)
  968. continue;
  969. if (J->Op != Item::TriggersPending)
  970. break;
  971. vector<Item>::const_iterator T = J + 1;
  972. if (T != List.end() && T->Op == I->Op)
  973. continue;
  974. break;
  975. }
  976. else
  977. for (; J != List.end() && J->Op == I->Op; ++J)
  978. /* nothing */;
  979. // keep track of allocated strings for multiarch package names
  980. std::vector<char *> Packages;
  981. // start with the baseset of arguments
  982. unsigned long Size = StartSize;
  983. Args.erase(Args.begin() + BaseArgs, Args.end());
  984. // Now check if we are within the MaxArgs limit
  985. //
  986. // this code below is problematic, because it may happen that
  987. // the argument list is split in a way that A depends on B
  988. // and they are in the same "--configure A B" run
  989. // - with the split they may now be configured in different
  990. // runs, using Immediate-Configure-All can help prevent this.
  991. if (J - I > (signed)MaxArgs)
  992. {
  993. J = I + MaxArgs;
  994. unsigned long const size = MaxArgs + 10;
  995. Args.reserve(size);
  996. Packages.reserve(size);
  997. }
  998. else
  999. {
  1000. unsigned long const size = (J - I) + 10;
  1001. Args.reserve(size);
  1002. Packages.reserve(size);
  1003. }
  1004. int fd[2];
  1005. if (pipe(fd) != 0)
  1006. return _error->Errno("pipe","Failed to create IPC pipe to dpkg");
  1007. #define ADDARG(X) Args.push_back(X); Size += strlen(X)
  1008. #define ADDARGC(X) Args.push_back(X); Size += sizeof(X) - 1
  1009. ADDARGC("--status-fd");
  1010. char status_fd_buf[20];
  1011. snprintf(status_fd_buf,sizeof(status_fd_buf),"%i", fd[1]);
  1012. ADDARG(status_fd_buf);
  1013. unsigned long const Op = I->Op;
  1014. switch (I->Op)
  1015. {
  1016. case Item::Remove:
  1017. ADDARGC("--force-depends");
  1018. ADDARGC("--force-remove-essential");
  1019. ADDARGC("--remove");
  1020. break;
  1021. case Item::Purge:
  1022. ADDARGC("--force-depends");
  1023. ADDARGC("--force-remove-essential");
  1024. ADDARGC("--purge");
  1025. break;
  1026. case Item::Configure:
  1027. ADDARGC("--configure");
  1028. break;
  1029. case Item::ConfigurePending:
  1030. ADDARGC("--configure");
  1031. ADDARGC("--pending");
  1032. break;
  1033. case Item::TriggersPending:
  1034. ADDARGC("--triggers-only");
  1035. ADDARGC("--pending");
  1036. break;
  1037. case Item::Install:
  1038. ADDARGC("--unpack");
  1039. ADDARGC("--auto-deconfigure");
  1040. break;
  1041. }
  1042. if (NoTriggers == true && I->Op != Item::TriggersPending &&
  1043. I->Op != Item::ConfigurePending)
  1044. {
  1045. ADDARGC("--no-triggers");
  1046. }
  1047. #undef ADDARGC
  1048. // Write in the file or package names
  1049. if (I->Op == Item::Install)
  1050. {
  1051. for (;I != J && Size < MaxArgBytes; ++I)
  1052. {
  1053. if (I->File[0] != '/')
  1054. return _error->Error("Internal Error, Pathname to install is not absolute '%s'",I->File.c_str());
  1055. Args.push_back(I->File.c_str());
  1056. Size += I->File.length();
  1057. }
  1058. }
  1059. else
  1060. {
  1061. string const nativeArch = _config->Find("APT::Architecture");
  1062. unsigned long const oldSize = I->Op == Item::Configure ? Size : 0;
  1063. for (;I != J && Size < MaxArgBytes; ++I)
  1064. {
  1065. if((*I).Pkg.end() == true)
  1066. continue;
  1067. if (I->Op == Item::Configure && disappearedPkgs.find(I->Pkg.Name()) != disappearedPkgs.end())
  1068. continue;
  1069. // We keep this here to allow "smooth" transitions from e.g. multiarch dpkg/ubuntu to dpkg/debian
  1070. if (dpkgMultiArch == false && (I->Pkg.Arch() == nativeArch ||
  1071. strcmp(I->Pkg.Arch(), "all") == 0 ||
  1072. strcmp(I->Pkg.Arch(), "none") == 0))
  1073. {
  1074. char const * const name = I->Pkg.Name();
  1075. ADDARG(name);
  1076. }
  1077. else
  1078. {
  1079. pkgCache::VerIterator PkgVer;
  1080. std::string name = I->Pkg.Name();
  1081. if (Op == Item::Remove || Op == Item::Purge)
  1082. {
  1083. PkgVer = I->Pkg.CurrentVer();
  1084. if(PkgVer.end() == true)
  1085. PkgVer = FindNowVersion(I->Pkg);
  1086. }
  1087. else
  1088. PkgVer = Cache[I->Pkg].InstVerIter(Cache);
  1089. if (strcmp(I->Pkg.Arch(), "none") == 0)
  1090. ; // never arch-qualify a package without an arch
  1091. else if (PkgVer.end() == false)
  1092. name.append(":").append(PkgVer.Arch());
  1093. else
  1094. _error->Warning("Can not find PkgVer for '%s'", name.c_str());
  1095. char * const fullname = strdup(name.c_str());
  1096. Packages.push_back(fullname);
  1097. ADDARG(fullname);
  1098. }
  1099. }
  1100. // skip configure action if all sheduled packages disappeared
  1101. if (oldSize == Size)
  1102. continue;
  1103. }
  1104. #undef ADDARG
  1105. J = I;
  1106. if (_config->FindB("Debug::pkgDPkgPM",false) == true)
  1107. {
  1108. for (std::vector<const char *>::const_iterator a = Args.begin();
  1109. a != Args.end(); ++a)
  1110. clog << *a << ' ';
  1111. clog << endl;
  1112. continue;
  1113. }
  1114. Args.push_back(NULL);
  1115. cout << flush;
  1116. clog << flush;
  1117. cerr << flush;
  1118. /* Mask off sig int/quit. We do this because dpkg also does when
  1119. it forks scripts. What happens is that when you hit ctrl-c it sends
  1120. it to all processes in the group. Since dpkg ignores the signal
  1121. it doesn't die but we do! So we must also ignore it */
  1122. sighandler_t old_SIGQUIT = signal(SIGQUIT,SIG_IGN);
  1123. sighandler_t old_SIGINT = signal(SIGINT,SigINT);
  1124. // Check here for any SIGINT
  1125. if (pkgPackageManager::SigINTStop && (Op == Item::Remove || Op == Item::Purge || Op == Item::Install))
  1126. break;
  1127. // ignore SIGHUP as well (debian #463030)
  1128. sighandler_t old_SIGHUP = signal(SIGHUP,SIG_IGN);
  1129. struct termios tt;
  1130. struct winsize win;
  1131. int master = -1;
  1132. int slave = -1;
  1133. // if tcgetattr does not return zero there was a error
  1134. // and we do not do any pty magic
  1135. _error->PushToStack();
  1136. if (tcgetattr(STDOUT_FILENO, &tt) == 0)
  1137. {
  1138. ioctl(0, TIOCGWINSZ, (char *)&win);
  1139. if (openpty(&master, &slave, NULL, &tt, &win) < 0)
  1140. {
  1141. _error->Errno("openpty", _("Can not write log (%s)"), _("Is /dev/pts mounted?"));
  1142. master = slave = -1;
  1143. } else {
  1144. struct termios rtt;
  1145. rtt = tt;
  1146. cfmakeraw(&rtt);
  1147. rtt.c_lflag &= ~ECHO;
  1148. rtt.c_lflag |= ISIG;
  1149. // block SIGTTOU during tcsetattr to prevent a hang if
  1150. // the process is a member of the background process group
  1151. // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
  1152. sigemptyset(&sigmask);
  1153. sigaddset(&sigmask, SIGTTOU);
  1154. sigprocmask(SIG_BLOCK,&sigmask, &original_sigmask);
  1155. tcsetattr(0, TCSAFLUSH, &rtt);
  1156. sigprocmask(SIG_SETMASK, &original_sigmask, 0);
  1157. }
  1158. }
  1159. // complain only if stdout is either a terminal (but still failed) or is an invalid
  1160. // descriptor otherwise we would complain about redirection to e.g. /dev/null as well.
  1161. else if (isatty(STDOUT_FILENO) == 1 || errno == EBADF)
  1162. _error->Errno("tcgetattr", _("Can not write log (%s)"), _("Is stdout a terminal?"));
  1163. if (_error->PendingError() == true)
  1164. _error->DumpErrors(std::cerr);
  1165. _error->RevertToStack();
  1166. // Fork dpkg
  1167. pid_t Child;
  1168. _config->Set("APT::Keep-Fds::",fd[1]);
  1169. // send status information that we are about to fork dpkg
  1170. if(OutStatusFd > 0) {
  1171. ostringstream status;
  1172. status << "pmstatus:dpkg-exec:"
  1173. << (PackagesDone/float(PackagesTotal)*100.0)
  1174. << ":" << _("Running dpkg")
  1175. << endl;
  1176. FileFd::Write(OutStatusFd, status.str().c_str(), status.str().size());
  1177. }
  1178. Child = ExecFork();
  1179. // This is the child
  1180. if (Child == 0)
  1181. {
  1182. if(slave >= 0 && master >= 0)
  1183. {
  1184. setsid();
  1185. ioctl(slave, TIOCSCTTY, 0);
  1186. close(master);
  1187. dup2(slave, 0);
  1188. dup2(slave, 1);
  1189. dup2(slave, 2);
  1190. close(slave);
  1191. }
  1192. close(fd[0]); // close the read end of the pipe
  1193. dpkgChrootDirectory();
  1194. if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
  1195. _exit(100);
  1196. if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
  1197. {
  1198. int Flags,dummy;
  1199. if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
  1200. _exit(100);
  1201. // Discard everything in stdin before forking dpkg
  1202. if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
  1203. _exit(100);
  1204. while (read(STDIN_FILENO,&dummy,1) == 1);
  1205. if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
  1206. _exit(100);
  1207. }
  1208. /* No Job Control Stop Env is a magic dpkg var that prevents it
  1209. from using sigstop */
  1210. putenv((char *)"DPKG_NO_TSTP=yes");
  1211. execvp(Args[0], (char**) &Args[0]);
  1212. cerr << "Could not exec dpkg!" << endl;
  1213. _exit(100);
  1214. }
  1215. // apply ionice
  1216. if (_config->FindB("DPkg::UseIoNice", false) == true)
  1217. ionice(Child);
  1218. // clear the Keep-Fd again
  1219. _config->Clear("APT::Keep-Fds",fd[1]);
  1220. // Wait for dpkg
  1221. int Status = 0;
  1222. // we read from dpkg here
  1223. int const _dpkgin = fd[0];
  1224. close(fd[1]); // close the write end of the pipe
  1225. if(slave > 0)
  1226. close(slave);
  1227. // setups fds
  1228. sigemptyset(&sigmask);
  1229. sigprocmask(SIG_BLOCK,&sigmask,&original_sigmask);
  1230. /* free vectors (and therefore memory) as we don't need the included data anymore */
  1231. for (std::vector<char *>::const_iterator p = Packages.begin();
  1232. p != Packages.end(); ++p)
  1233. free(*p);
  1234. Packages.clear();
  1235. // the result of the waitpid call
  1236. int res;
  1237. int select_ret;
  1238. while ((res=waitpid(Child,&Status, WNOHANG)) != Child) {
  1239. if(res < 0) {
  1240. // FIXME: move this to a function or something, looks ugly here
  1241. // error handling, waitpid returned -1
  1242. if (errno == EINTR)
  1243. continue;
  1244. RunScripts("DPkg::Post-Invoke");
  1245. // Restore sig int/quit
  1246. signal(SIGQUIT,old_SIGQUIT);
  1247. signal(SIGINT,old_SIGINT);
  1248. signal(SIGHUP,old_SIGHUP);
  1249. return _error->Errno("waitpid","Couldn't wait for subprocess");
  1250. }
  1251. // wait for input or output here
  1252. FD_ZERO(&rfds);
  1253. if (master >= 0 && !d->stdin_is_dev_null)
  1254. FD_SET(0, &rfds);
  1255. FD_SET(_dpkgin, &rfds);
  1256. if(master >= 0)
  1257. FD_SET(master, &rfds);
  1258. tv.tv_sec = 1;
  1259. tv.tv_nsec = 0;
  1260. select_ret = pselect(max(master, _dpkgin)+1, &rfds, NULL, NULL,
  1261. &tv, &original_sigmask);
  1262. if (select_ret < 0 && (errno == EINVAL || errno == ENOSYS))
  1263. select_ret = racy_pselect(max(master, _dpkgin)+1, &rfds, NULL,
  1264. NULL, &tv, &original_sigmask);
  1265. if (select_ret == 0)
  1266. continue;
  1267. else if (select_ret < 0 && errno == EINTR)
  1268. continue;
  1269. else if (select_ret < 0)
  1270. {
  1271. perror("select() returned error");
  1272. continue;
  1273. }
  1274. if(master >= 0 && FD_ISSET(master, &rfds))
  1275. DoTerminalPty(master);
  1276. if(master >= 0 && FD_ISSET(0, &rfds))
  1277. DoStdin(master);
  1278. if(FD_ISSET(_dpkgin, &rfds))
  1279. DoDpkgStatusFd(_dpkgin, OutStatusFd);
  1280. }
  1281. close(_dpkgin);
  1282. // Restore sig int/quit
  1283. signal(SIGQUIT,old_SIGQUIT);
  1284. signal(SIGINT,old_SIGINT);
  1285. signal(SIGHUP,old_SIGHUP);
  1286. if(master >= 0)
  1287. {
  1288. tcsetattr(0, TCSAFLUSH, &tt);
  1289. close(master);
  1290. }
  1291. // Check for an error code.
  1292. if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
  1293. {
  1294. // if it was set to "keep-dpkg-runing" then we won't return
  1295. // here but keep the loop going and just report it as a error
  1296. // for later
  1297. bool const stopOnError = _config->FindB("Dpkg::StopOnError",true);
  1298. if(stopOnError)
  1299. RunScripts("DPkg::Post-Invoke");
  1300. if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
  1301. strprintf(d->dpkg_error, "Sub-process %s received a segmentation fault.",Args[0]);
  1302. else if (WIFEXITED(Status) != 0)
  1303. strprintf(d->dpkg_error, "Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
  1304. else
  1305. strprintf(d->dpkg_error, "Sub-process %s exited unexpectedly",Args[0]);
  1306. if(d->dpkg_error.size() > 0)
  1307. _error->Error("%s", d->dpkg_error.c_str());
  1308. if(stopOnError)
  1309. {
  1310. CloseLog();
  1311. return false;
  1312. }
  1313. }
  1314. }
  1315. CloseLog();
  1316. if (pkgPackageManager::SigINTStop)
  1317. _error->Warning(_("Operation was interrupted before it could finish"));
  1318. if (RunScripts("DPkg::Post-Invoke") == false)
  1319. return false;
  1320. if (_config->FindB("Debug::pkgDPkgPM",false) == false)
  1321. {
  1322. std::string const oldpkgcache = _config->FindFile("Dir::cache::pkgcache");
  1323. if (oldpkgcache.empty() == false && RealFileExists(oldpkgcache) == true &&
  1324. unlink(oldpkgcache.c_str()) == 0)
  1325. {
  1326. std::string const srcpkgcache = _config->FindFile("Dir::cache::srcpkgcache");
  1327. if (srcpkgcache.empty() == false && RealFileExists(srcpkgcache) == true)
  1328. {
  1329. _error->PushToStack();
  1330. pkgCacheFile CacheFile;
  1331. CacheFile.BuildCaches(NULL, true);
  1332. _error->RevertToStack();
  1333. }
  1334. }
  1335. }
  1336. Cache.writeStateFile(NULL);
  1337. return true;
  1338. }
  1339. void SigINT(int sig) {
  1340. pkgPackageManager::SigINTStop = true;
  1341. }
  1342. /*}}}*/
  1343. // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
  1344. // ---------------------------------------------------------------------
  1345. /* */
  1346. void pkgDPkgPM::Reset()
  1347. {
  1348. List.erase(List.begin(),List.end());
  1349. }
  1350. /*}}}*/
  1351. // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
  1352. // ---------------------------------------------------------------------
  1353. /* */
  1354. void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
  1355. {
  1356. // If apport doesn't exist or isn't installed do nothing
  1357. // This e.g. prevents messages in 'universes' without apport
  1358. pkgCache::PkgIterator apportPkg = Cache.FindPkg("apport");
  1359. if (apportPkg.end() == true || apportPkg->CurrentVer == 0)
  1360. return;
  1361. string pkgname, reportfile, srcpkgname, pkgver, arch;
  1362. string::size_type pos;
  1363. FILE *report;
  1364. if (_config->FindB("Dpkg::ApportFailureReport", false) == false)
  1365. {
  1366. std::clog << "configured to not write apport reports" << std::endl;
  1367. return;
  1368. }
  1369. // only report the first errors
  1370. if(pkgFailures > _config->FindI("APT::Apport::MaxReports", 3))
  1371. {
  1372. std::clog << _("No apport report written because MaxReports is reached already") << std::endl;
  1373. return;
  1374. }
  1375. // check if its not a follow up error
  1376. const char *needle = dgettext("dpkg", "dependency problems - leaving unconfigured");
  1377. if(strstr(errormsg, needle) != NULL) {
  1378. std::clog << _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl;
  1379. return;
  1380. }
  1381. // do not report disk-full failures
  1382. if(strstr(errormsg, strerror(ENOSPC)) != NULL) {
  1383. std::clog << _("No apport report written because the error message indicates a disk full error") << std::endl;
  1384. return;
  1385. }
  1386. // do not report out-of-memory failures
  1387. if(strstr(errormsg, strerror(ENOMEM)) != NULL) {
  1388. std::clog << _("No apport report written because the error message indicates a out of memory error") << std::endl;
  1389. return;
  1390. }
  1391. // do not report dpkg I/O errors
  1392. // XXX - this message is localized, but this only matches the English version. This is better than nothing.
  1393. if(strstr(errormsg, "short read in buffer_copy (")) {
  1394. std::clog << _("No apport report written because the error message indicates a dpkg I/O error") << std::endl;
  1395. return;
  1396. }
  1397. // get the pkgname and reportfile
  1398. pkgname = flNotDir(pkgpath);
  1399. pos = pkgname.find('_');
  1400. if(pos != string::npos)
  1401. pkgname = pkgname.substr(0, pos);
  1402. // find the package versin and source package name
  1403. pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
  1404. if (Pkg.end() == true)
  1405. return;
  1406. pkgCache::VerIterator Ver = Cache.GetCandidateVer(Pkg);
  1407. if (Ver.end() == true)
  1408. return;
  1409. pkgver = Ver.VerStr() == NULL ? "unknown" : Ver.VerStr();
  1410. pkgRecords Recs(Cache);
  1411. pkgRecords::Parser &Parse = Recs.Lookup(Ver.FileList());
  1412. srcpkgname = Parse.SourcePkg();
  1413. if(srcpkgname.empty())
  1414. srcpkgname = pkgname;
  1415. // if the file exists already, we check:
  1416. // - if it was reported already (touched by apport).
  1417. // If not, we do nothing, otherwise
  1418. // we overwrite it. This is the same behaviour as apport
  1419. // - if we have a report with the same pkgversion already
  1420. // then we skip it
  1421. reportfile = flCombine("/var/crash",pkgname+".0.crash");
  1422. if(FileExists(reportfile))
  1423. {
  1424. struct stat buf;
  1425. char strbuf[255];
  1426. // check atime/mtime
  1427. stat(reportfile.c_str(), &buf);
  1428. if(buf.st_mtime > buf.st_atime)
  1429. return;
  1430. // check if the existing report is the same version
  1431. report = fopen(reportfile.c_str(),"r");
  1432. while(fgets(strbuf, sizeof(strbuf), report) != NULL)
  1433. {
  1434. if(strstr(strbuf,"Package:") == strbuf)
  1435. {
  1436. char pkgname[255], version[255];
  1437. if(sscanf(strbuf, "Package: %254s %254s", pkgname, version) == 2)
  1438. if(strcmp(pkgver.c_str(), version) == 0)
  1439. {
  1440. fclose(report);
  1441. return;
  1442. }
  1443. }
  1444. }
  1445. fclose(report);
  1446. }
  1447. // now write the report
  1448. arch = _config->Find("APT::Architecture");
  1449. report = fopen(reportfile.c_str(),"w");
  1450. if(report == NULL)
  1451. return;
  1452. if(_config->FindB("DPkgPM::InitialReportOnly",false) == true)
  1453. chmod(reportfile.c_str(), 0);
  1454. else
  1455. chmod(reportfile.c_str(), 0600);
  1456. fprintf(report, "ProblemType: Package\n");
  1457. fprintf(report, "Architecture: %s\n", arch.c_str());
  1458. time_t now = time(NULL);
  1459. fprintf(report, "Date: %s" , ctime(&now));
  1460. fprintf(report, "Package: %s %s\n", pkgname.c_str(), pkgver.c_str());
  1461. fprintf(report, "SourcePackage: %s\n", srcpkgname.c_str());
  1462. fprintf(report, "ErrorMessage:\n %s\n", errormsg);
  1463. // ensure that the log is flushed
  1464. if(d->term_out)
  1465. fflush(d->term_out);
  1466. // attach terminal log it if we have it
  1467. string logfile_name = _config->FindFile("Dir::Log::Terminal");
  1468. if (!logfile_name.empty())
  1469. {
  1470. FILE *log = NULL;
  1471. fprintf(report, "DpkgTerminalLog:\n");
  1472. log = fopen(logfile_name.c_str(),"r");
  1473. if(log != NULL)
  1474. {
  1475. char buf[1024];
  1476. while( fgets(buf, sizeof(buf), log) != NULL)
  1477. fprintf(report, " %s", buf);
  1478. fclose(log);
  1479. }
  1480. }
  1481. // log the ordering
  1482. const char *ops_str[] = {"Install", "Configure","Remove","Purge"};
  1483. fprintf(report, "AptOrdering:\n");
  1484. for (vector<Item>::iterator I = List.begin(); I != List.end(); ++I)
  1485. if ((*I).Pkg != NULL)
  1486. fprintf(report, " %s: %s\n", (*I).Pkg.Name(), ops_str[(*I).Op]);
  1487. else
  1488. fprintf(report, " %s: %s\n", "NULL", ops_str[(*I).Op]);
  1489. // attach dmesg log (to learn about segfaults)
  1490. if (FileExists("/bin/dmesg"))
  1491. {
  1492. fprintf(report, "Dmesg:\n");
  1493. FILE *log = popen("/bin/dmesg","r");
  1494. if(log != NULL)
  1495. {
  1496. char buf[1024];
  1497. while( fgets(buf, sizeof(buf), log) != NULL)
  1498. fprintf(report, " %s", buf);
  1499. pclose(log);
  1500. }
  1501. }
  1502. // attach df -l log (to learn about filesystem status)
  1503. if (FileExists("/bin/df"))
  1504. {
  1505. fprintf(report, "Df:\n");
  1506. FILE *log = popen("/bin/df -l","r");
  1507. if(log != NULL)
  1508. {
  1509. char buf[1024];
  1510. while( fgets(buf, sizeof(buf), log) != NULL)
  1511. fprintf(report, " %s", buf);
  1512. pclose(log);
  1513. }
  1514. }
  1515. fclose(report);
  1516. }
  1517. /*}}}*/