dpkgpm.cc 48 KB

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