dpkgpm.cc 59 KB

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