dpkgpm.cc 52 KB

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