dpkgpm.cc 50 KB

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