dpkgpm.cc 57 KB

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