dpkgpm.cc 50 KB

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