dpkgpm.cc 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891
  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/debsystem.h>
  15. #include <apt-pkg/error.h>
  16. #include <apt-pkg/fileutl.h>
  17. #include <apt-pkg/install-progress.h>
  18. #include <apt-pkg/packagemanager.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 <pwd.h>
  27. #include <signal.h>
  28. #include <stddef.h>
  29. #include <stdio.h>
  30. #include <stdlib.h>
  31. #include <sys/ioctl.h>
  32. #include <sys/select.h>
  33. #include <sys/stat.h>
  34. #include <sys/time.h>
  35. #include <sys/wait.h>
  36. #include <termios.h>
  37. #include <time.h>
  38. #include <unistd.h>
  39. #include <algorithm>
  40. #include <cstring>
  41. #include <iostream>
  42. #include <map>
  43. #include <set>
  44. #include <string>
  45. #include <utility>
  46. #include <vector>
  47. #include <sstream>
  48. #include <apti18n.h>
  49. /*}}}*/
  50. using namespace std;
  51. APT_PURE static string
  52. AptHistoryRequestingUser()
  53. {
  54. const char* EnvKeys[]{"SUDO_UID", "PKEXEC_UID", "PACKAGEKIT_CALLER_UID"};
  55. for (const auto &Key: EnvKeys)
  56. {
  57. if (getenv(Key) != nullptr)
  58. {
  59. int uid = atoi(getenv(Key));
  60. if (uid > 0) {
  61. struct passwd pwd;
  62. struct passwd *result;
  63. char buf[255];
  64. if (getpwuid_r(uid, &pwd, buf, sizeof(buf), &result) == 0 && result != NULL) {
  65. std::string res;
  66. strprintf(res, "%s (%d)", pwd.pw_name, uid);
  67. return res;
  68. }
  69. }
  70. }
  71. }
  72. return "";
  73. }
  74. APT_PURE static unsigned int
  75. EnvironmentSize()
  76. {
  77. unsigned int size = 0;
  78. char **envp = environ;
  79. while (*envp != NULL)
  80. size += strlen (*envp++) + 1;
  81. return size;
  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. namespace
  117. {
  118. // Maps the dpkg "processing" info to human readable names. Entry 0
  119. // of each array is the key, entry 1 is the value.
  120. const std::pair<const char *, const char *> PackageProcessingOps[] = {
  121. std::make_pair("install", N_("Installing %s")),
  122. std::make_pair("configure", N_("Configuring %s")),
  123. std::make_pair("remove", N_("Removing %s")),
  124. std::make_pair("purge", N_("Completely removing %s")),
  125. std::make_pair("disappear", N_("Noting disappearance of %s")),
  126. std::make_pair("trigproc", N_("Running post-installation trigger %s"))
  127. };
  128. const std::pair<const char *, const char *> * const PackageProcessingOpsBegin = PackageProcessingOps;
  129. const std::pair<const char *, const char *> * const PackageProcessingOpsEnd = PackageProcessingOps + sizeof(PackageProcessingOps) / sizeof(PackageProcessingOps[0]);
  130. // Predicate to test whether an entry in the PackageProcessingOps
  131. // array matches a string.
  132. class MatchProcessingOp
  133. {
  134. const char *target;
  135. public:
  136. explicit MatchProcessingOp(const char *the_target)
  137. : target(the_target)
  138. {
  139. }
  140. bool operator()(const std::pair<const char *, const char *> &pair) const
  141. {
  142. return strcmp(pair.first, target) == 0;
  143. }
  144. };
  145. }
  146. /* helper function to ionice the given PID
  147. there is no C header for ionice yet - just the syscall interface
  148. so we use the binary from util-linux
  149. */
  150. static bool
  151. ionice(int PID)
  152. {
  153. if (!FileExists("/usr/bin/ionice"))
  154. return false;
  155. pid_t Process = ExecFork();
  156. if (Process == 0)
  157. {
  158. char buf[32];
  159. snprintf(buf, sizeof(buf), "-p%d", PID);
  160. const char *Args[4];
  161. Args[0] = "/usr/bin/ionice";
  162. Args[1] = "-c3";
  163. Args[2] = buf;
  164. Args[3] = 0;
  165. execv(Args[0], (char **)Args);
  166. }
  167. return ExecWait(Process, "ionice");
  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","Faild 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. // ---------------------------------------------------------------------
  501. /*
  502. */
  503. void pkgDPkgPM::ProcessDpkgStatusLine(char *line)
  504. {
  505. bool const Debug = _config->FindB("Debug::pkgDPkgProgressReporting",false);
  506. if (Debug == true)
  507. std::clog << "got from dpkg '" << line << "'" << std::endl;
  508. /* dpkg sends strings like this:
  509. 'status: <pkg>: <pkg qstate>'
  510. 'status: <pkg>:<arch>: <pkg qstate>'
  511. 'processing: {install,upgrade,configure,remove,purge,disappear,trigproc}: pkg'
  512. 'processing: {install,upgrade,configure,remove,purge,disappear,trigproc}: trigger'
  513. */
  514. // we need to split on ": " (note the appended space) as the ':' is
  515. // part of the pkgname:arch information that dpkg sends
  516. //
  517. // A dpkg error message may contain additional ":" (like
  518. // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
  519. // so we need to ensure to not split too much
  520. std::vector<std::string> list = StringSplit(line, ": ", 4);
  521. if(list.size() < 3)
  522. {
  523. if (Debug == true)
  524. std::clog << "ignoring line: not enough ':'" << std::endl;
  525. return;
  526. }
  527. // build the (prefix, pkgname, action) tuple, position of this
  528. // is different for "processing" or "status" messages
  529. std::string prefix = APT::String::Strip(list[0]);
  530. std::string pkgname;
  531. std::string action;
  532. // "processing" has the form "processing: action: pkg or trigger"
  533. // with action = ["install", "upgrade", "configure", "remove", "purge",
  534. // "disappear", "trigproc"]
  535. if (prefix == "processing")
  536. {
  537. pkgname = APT::String::Strip(list[2]);
  538. action = APT::String::Strip(list[1]);
  539. // we don't care for the difference (as dpkg doesn't really either)
  540. if (action == "upgrade")
  541. action = "install";
  542. }
  543. // "status" has the form: "status: pkg: state"
  544. // with state in ["half-installed", "unpacked", "half-configured",
  545. // "installed", "config-files", "not-installed"]
  546. else if (prefix == "status")
  547. {
  548. pkgname = APT::String::Strip(list[1]);
  549. action = APT::String::Strip(list[2]);
  550. } else {
  551. if (Debug == true)
  552. std::clog << "unknown prefix '" << prefix << "'" << std::endl;
  553. return;
  554. }
  555. /* handle the special cases first:
  556. errors look like this:
  557. '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
  558. and conffile-prompt like this
  559. 'status:/etc/compiz.conf/compiz.conf : conffile-prompt: 'current-conffile' 'new-conffile' useredited distedited
  560. */
  561. if (prefix == "status")
  562. {
  563. if(action == "error")
  564. {
  565. d->progress->Error(pkgname, PackagesDone, PackagesTotal,
  566. list[3]);
  567. pkgFailures++;
  568. WriteApportReport(pkgname.c_str(), list[3].c_str());
  569. return;
  570. }
  571. else if(action == "conffile-prompt")
  572. {
  573. d->progress->ConffilePrompt(pkgname, PackagesDone, PackagesTotal,
  574. list[3]);
  575. return;
  576. }
  577. }
  578. // at this point we know that we should have a valid pkgname, so build all
  579. // the info from it
  580. // dpkg does not always send "pkgname:arch" so we add it here if needed
  581. if (pkgname.find(":") == std::string::npos)
  582. {
  583. // find the package in the group that is touched by dpkg
  584. // if there are multiple pkgs dpkg would send us a full pkgname:arch
  585. pkgCache::GrpIterator Grp = Cache.FindGrp(pkgname);
  586. if (Grp.end() == false)
  587. {
  588. pkgCache::PkgIterator P = Grp.PackageList();
  589. for (; P.end() != true; P = Grp.NextPkg(P))
  590. {
  591. if(Cache[P].Keep() == false || Cache[P].ReInstall() == true)
  592. {
  593. pkgname = P.FullName();
  594. break;
  595. }
  596. }
  597. }
  598. }
  599. const char* const pkg = pkgname.c_str();
  600. std::string short_pkgname = StringSplit(pkgname, ":")[0];
  601. std::string arch = "";
  602. if (pkgname.find(":") != string::npos)
  603. arch = StringSplit(pkgname, ":")[1];
  604. std::string i18n_pkgname = pkgname;
  605. if (arch.size() != 0)
  606. strprintf(i18n_pkgname, "%s (%s)", short_pkgname.c_str(), arch.c_str());
  607. // 'processing' from dpkg looks like
  608. // 'processing: action: pkg'
  609. if(prefix == "processing")
  610. {
  611. const std::pair<const char *, const char *> * const iter =
  612. std::find_if(PackageProcessingOpsBegin,
  613. PackageProcessingOpsEnd,
  614. MatchProcessingOp(action.c_str()));
  615. if(iter == PackageProcessingOpsEnd)
  616. {
  617. if (Debug == true)
  618. std::clog << "ignoring unknown action: " << action << std::endl;
  619. return;
  620. }
  621. std::string msg;
  622. strprintf(msg, _(iter->second), i18n_pkgname.c_str());
  623. d->progress->StatusChanged(pkgname, PackagesDone, PackagesTotal, msg);
  624. // FIXME: this needs a muliarch testcase
  625. // FIXME2: is "pkgname" here reliable with dpkg only sending us
  626. // short pkgnames?
  627. if (action == "disappear")
  628. handleDisappearAction(pkgname);
  629. return;
  630. }
  631. if (prefix == "status")
  632. {
  633. vector<struct DpkgState> const &states = PackageOps[pkg];
  634. if(PackageOpsDone[pkg] < states.size())
  635. {
  636. char const * const next_action = states[PackageOpsDone[pkg]].state;
  637. if (next_action && Debug == true)
  638. std::clog << "(parsed from dpkg) pkg: " << short_pkgname
  639. << " action: " << action << " (expected: '" << next_action << "' "
  640. << PackageOpsDone[pkg] << " of " << states.size() << ")" << endl;
  641. // check if the package moved to the next dpkg state
  642. if(next_action && (action == next_action))
  643. {
  644. // only read the translation if there is actually a next action
  645. char const * const translation = _(states[PackageOpsDone[pkg]].str);
  646. // we moved from one dpkg state to a new one, report that
  647. ++PackageOpsDone[pkg];
  648. ++PackagesDone;
  649. std::string msg;
  650. strprintf(msg, translation, i18n_pkgname.c_str());
  651. d->progress->StatusChanged(pkgname, PackagesDone, PackagesTotal, msg);
  652. }
  653. }
  654. }
  655. }
  656. /*}}}*/
  657. // DPkgPM::handleDisappearAction /*{{{*/
  658. void pkgDPkgPM::handleDisappearAction(string const &pkgname)
  659. {
  660. pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
  661. if (unlikely(Pkg.end() == true))
  662. return;
  663. // record the package name for display and stuff later
  664. disappearedPkgs.insert(Pkg.FullName(true));
  665. // the disappeared package was auto-installed - nothing to do
  666. if ((Cache[Pkg].Flags & pkgCache::Flag::Auto) == pkgCache::Flag::Auto)
  667. return;
  668. pkgCache::VerIterator PkgVer = Cache[Pkg].InstVerIter(Cache);
  669. if (unlikely(PkgVer.end() == true))
  670. return;
  671. /* search in the list of dependencies for (Pre)Depends,
  672. check if this dependency has a Replaces on our package
  673. and if so transfer the manual installed flag to it */
  674. for (pkgCache::DepIterator Dep = PkgVer.DependsList(); Dep.end() != true; ++Dep)
  675. {
  676. if (Dep->Type != pkgCache::Dep::Depends &&
  677. Dep->Type != pkgCache::Dep::PreDepends)
  678. continue;
  679. pkgCache::PkgIterator Tar = Dep.TargetPkg();
  680. if (unlikely(Tar.end() == true))
  681. continue;
  682. // the package is already marked as manual
  683. if ((Cache[Tar].Flags & pkgCache::Flag::Auto) != pkgCache::Flag::Auto)
  684. continue;
  685. pkgCache::VerIterator TarVer = Cache[Tar].InstVerIter(Cache);
  686. if (TarVer.end() == true)
  687. continue;
  688. for (pkgCache::DepIterator Rep = TarVer.DependsList(); Rep.end() != true; ++Rep)
  689. {
  690. if (Rep->Type != pkgCache::Dep::Replaces)
  691. continue;
  692. if (Pkg != Rep.TargetPkg())
  693. continue;
  694. // okay, they are strongly connected - transfer manual-bit
  695. if (Debug == true)
  696. std::clog << "transfer manual-bit from disappeared »" << pkgname << "« to »" << Tar.FullName() << "«" << std::endl;
  697. Cache[Tar].Flags &= ~Flag::Auto;
  698. break;
  699. }
  700. }
  701. }
  702. /*}}}*/
  703. // DPkgPM::DoDpkgStatusFd /*{{{*/
  704. void pkgDPkgPM::DoDpkgStatusFd(int statusfd)
  705. {
  706. ssize_t const len = read(statusfd, &d->dpkgbuf[d->dpkgbuf_pos],
  707. (sizeof(d->dpkgbuf)/sizeof(d->dpkgbuf[0])) - d->dpkgbuf_pos);
  708. if(len <= 0)
  709. return;
  710. d->dpkgbuf_pos += (len / sizeof(d->dpkgbuf[0]));
  711. // process line by line from the buffer
  712. char *p = d->dpkgbuf, *q = nullptr;
  713. while((q=(char*)memchr(p, '\n', (d->dpkgbuf + d->dpkgbuf_pos) - p)) != nullptr)
  714. {
  715. *q = '\0';
  716. ProcessDpkgStatusLine(p);
  717. p = q + 1; // continue with next line
  718. }
  719. // check if we stripped the buffer clean
  720. if (p > (d->dpkgbuf + d->dpkgbuf_pos))
  721. {
  722. d->dpkgbuf_pos = 0;
  723. return;
  724. }
  725. // otherwise move the unprocessed tail to the start and update pos
  726. memmove(d->dpkgbuf, p, (p - d->dpkgbuf));
  727. d->dpkgbuf_pos = (d->dpkgbuf + d->dpkgbuf_pos) - p;
  728. }
  729. /*}}}*/
  730. // DPkgPM::WriteHistoryTag /*{{{*/
  731. void pkgDPkgPM::WriteHistoryTag(string const &tag, string value)
  732. {
  733. size_t const length = value.length();
  734. if (length == 0)
  735. return;
  736. // poor mans rstrip(", ")
  737. if (value[length-2] == ',' && value[length-1] == ' ')
  738. value.erase(length - 2, 2);
  739. fprintf(d->history_out, "%s: %s\n", tag.c_str(), value.c_str());
  740. } /*}}}*/
  741. // DPkgPM::OpenLog /*{{{*/
  742. bool pkgDPkgPM::OpenLog()
  743. {
  744. string const logdir = _config->FindDir("Dir::Log");
  745. if(CreateAPTDirectoryIfNeeded(logdir, logdir) == false)
  746. // FIXME: use a better string after freeze
  747. return _error->Error(_("Directory '%s' missing"), logdir.c_str());
  748. // get current time
  749. char timestr[200];
  750. time_t const t = time(NULL);
  751. struct tm tm_buf;
  752. struct tm const * const tmp = localtime_r(&t, &tm_buf);
  753. strftime(timestr, sizeof(timestr), "%F %T", tmp);
  754. // open terminal log
  755. string const logfile_name = flCombine(logdir,
  756. _config->Find("Dir::Log::Terminal"));
  757. if (!logfile_name.empty())
  758. {
  759. d->term_out = fopen(logfile_name.c_str(),"a");
  760. if (d->term_out == NULL)
  761. return _error->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name.c_str());
  762. setvbuf(d->term_out, NULL, _IONBF, 0);
  763. SetCloseExec(fileno(d->term_out), true);
  764. if (getuid() == 0) // if we aren't root, we can't chown a file, so don't try it
  765. {
  766. struct passwd *pw = getpwnam("root");
  767. struct group *gr = getgrnam("adm");
  768. if (pw != NULL && gr != NULL && chown(logfile_name.c_str(), pw->pw_uid, gr->gr_gid) != 0)
  769. _error->WarningE("OpenLog", "chown to root:adm of file %s failed", logfile_name.c_str());
  770. }
  771. if (chmod(logfile_name.c_str(), 0640) != 0)
  772. _error->WarningE("OpenLog", "chmod 0640 of file %s failed", logfile_name.c_str());
  773. fprintf(d->term_out, "\nLog started: %s\n", timestr);
  774. }
  775. // write your history
  776. string const history_name = flCombine(logdir,
  777. _config->Find("Dir::Log::History"));
  778. if (!history_name.empty())
  779. {
  780. d->history_out = fopen(history_name.c_str(),"a");
  781. if (d->history_out == NULL)
  782. return _error->WarningE("OpenLog", _("Could not open file '%s'"), history_name.c_str());
  783. SetCloseExec(fileno(d->history_out), true);
  784. chmod(history_name.c_str(), 0644);
  785. fprintf(d->history_out, "\nStart-Date: %s\n", timestr);
  786. string remove, purge, install, reinstall, upgrade, downgrade;
  787. for (pkgCache::PkgIterator I = Cache.PkgBegin(); I.end() == false; ++I)
  788. {
  789. enum { CANDIDATE, CANDIDATE_AUTO, CURRENT_CANDIDATE, CURRENT } infostring;
  790. string *line = NULL;
  791. #define HISTORYINFO(X, Y) { line = &X; infostring = Y; }
  792. if (Cache[I].NewInstall() == true)
  793. HISTORYINFO(install, CANDIDATE_AUTO)
  794. else if (Cache[I].ReInstall() == true)
  795. HISTORYINFO(reinstall, CANDIDATE)
  796. else if (Cache[I].Upgrade() == true)
  797. HISTORYINFO(upgrade, CURRENT_CANDIDATE)
  798. else if (Cache[I].Downgrade() == true)
  799. HISTORYINFO(downgrade, CURRENT_CANDIDATE)
  800. else if (Cache[I].Delete() == true)
  801. HISTORYINFO((Cache[I].Purge() ? purge : remove), CURRENT)
  802. else
  803. continue;
  804. #undef HISTORYINFO
  805. line->append(I.FullName(false)).append(" (");
  806. switch (infostring) {
  807. case CANDIDATE: line->append(Cache[I].CandVersion); break;
  808. case CANDIDATE_AUTO:
  809. line->append(Cache[I].CandVersion);
  810. if ((Cache[I].Flags & pkgCache::Flag::Auto) == pkgCache::Flag::Auto)
  811. line->append(", automatic");
  812. break;
  813. case CURRENT_CANDIDATE: line->append(Cache[I].CurVersion).append(", ").append(Cache[I].CandVersion); break;
  814. case CURRENT: line->append(Cache[I].CurVersion); break;
  815. }
  816. line->append("), ");
  817. }
  818. if (_config->Exists("Commandline::AsString") == true)
  819. WriteHistoryTag("Commandline", _config->Find("Commandline::AsString"));
  820. std::string RequestingUser = AptHistoryRequestingUser();
  821. if (RequestingUser != "")
  822. WriteHistoryTag("Requested-By", RequestingUser);
  823. WriteHistoryTag("Install", install);
  824. WriteHistoryTag("Reinstall", reinstall);
  825. WriteHistoryTag("Upgrade", upgrade);
  826. WriteHistoryTag("Downgrade",downgrade);
  827. WriteHistoryTag("Remove",remove);
  828. WriteHistoryTag("Purge",purge);
  829. fflush(d->history_out);
  830. }
  831. return true;
  832. }
  833. /*}}}*/
  834. // DPkg::CloseLog /*{{{*/
  835. bool pkgDPkgPM::CloseLog()
  836. {
  837. char timestr[200];
  838. time_t t = time(NULL);
  839. struct tm tm_buf;
  840. struct tm *tmp = localtime_r(&t, &tm_buf);
  841. strftime(timestr, sizeof(timestr), "%F %T", tmp);
  842. if(d->term_out)
  843. {
  844. fprintf(d->term_out, "Log ended: ");
  845. fprintf(d->term_out, "%s", timestr);
  846. fprintf(d->term_out, "\n");
  847. fclose(d->term_out);
  848. }
  849. d->term_out = NULL;
  850. if(d->history_out)
  851. {
  852. if (disappearedPkgs.empty() == false)
  853. {
  854. string disappear;
  855. for (std::set<std::string>::const_iterator d = disappearedPkgs.begin();
  856. d != disappearedPkgs.end(); ++d)
  857. {
  858. pkgCache::PkgIterator P = Cache.FindPkg(*d);
  859. disappear.append(*d);
  860. if (P.end() == true)
  861. disappear.append(", ");
  862. else
  863. disappear.append(" (").append(Cache[P].CurVersion).append("), ");
  864. }
  865. WriteHistoryTag("Disappeared", disappear);
  866. }
  867. if (d->dpkg_error.empty() == false)
  868. fprintf(d->history_out, "Error: %s\n", d->dpkg_error.c_str());
  869. fprintf(d->history_out, "End-Date: %s\n", timestr);
  870. fclose(d->history_out);
  871. }
  872. d->history_out = NULL;
  873. return true;
  874. }
  875. /*}}}*/
  876. /*}}}*/
  877. /*{{{*/
  878. // This implements a racy version of pselect for those architectures
  879. // that don't have a working implementation.
  880. // FIXME: Probably can be removed on Lenny+1
  881. static int racy_pselect(int nfds, fd_set *readfds, fd_set *writefds,
  882. fd_set *exceptfds, const struct timespec *timeout,
  883. const sigset_t *sigmask)
  884. {
  885. sigset_t origmask;
  886. struct timeval tv;
  887. int retval;
  888. tv.tv_sec = timeout->tv_sec;
  889. tv.tv_usec = timeout->tv_nsec/1000;
  890. sigprocmask(SIG_SETMASK, sigmask, &origmask);
  891. retval = select(nfds, readfds, writefds, exceptfds, &tv);
  892. sigprocmask(SIG_SETMASK, &origmask, 0);
  893. return retval;
  894. }
  895. /*}}}*/
  896. // DPkgPM::BuildPackagesProgressMap /*{{{*/
  897. void pkgDPkgPM::BuildPackagesProgressMap()
  898. {
  899. // map the dpkg states to the operations that are performed
  900. // (this is sorted in the same way as Item::Ops)
  901. static const struct DpkgState DpkgStatesOpMap[][7] = {
  902. // Install operation
  903. {
  904. {"half-installed", N_("Preparing %s")},
  905. {"unpacked", N_("Unpacking %s") },
  906. {NULL, NULL}
  907. },
  908. // Configure operation
  909. {
  910. {"unpacked",N_("Preparing to configure %s") },
  911. {"half-configured", N_("Configuring %s") },
  912. { "installed", N_("Installed %s")},
  913. {NULL, NULL}
  914. },
  915. // Remove operation
  916. {
  917. {"half-configured", N_("Preparing for removal of %s")},
  918. {"half-installed", N_("Removing %s")},
  919. {"config-files", N_("Removed %s")},
  920. {NULL, NULL}
  921. },
  922. // Purge operation
  923. {
  924. {"config-files", N_("Preparing to completely remove %s")},
  925. {"not-installed", N_("Completely removed %s")},
  926. {NULL, NULL}
  927. },
  928. };
  929. // init the PackageOps map, go over the list of packages that
  930. // that will be [installed|configured|removed|purged] and add
  931. // them to the PackageOps map (the dpkg states it goes through)
  932. // and the PackageOpsTranslations (human readable strings)
  933. for (vector<Item>::const_iterator I = List.begin(); I != List.end(); ++I)
  934. {
  935. if((*I).Pkg.end() == true)
  936. continue;
  937. string const name = (*I).Pkg.FullName();
  938. PackageOpsDone[name] = 0;
  939. for(int i=0; (DpkgStatesOpMap[(*I).Op][i]).state != NULL; ++i)
  940. {
  941. PackageOps[name].push_back(DpkgStatesOpMap[(*I).Op][i]);
  942. PackagesTotal++;
  943. }
  944. }
  945. /* one extra: We don't want the progress bar to reach 100%, especially not
  946. if we call dpkg --configure --pending and process a bunch of triggers
  947. while showing 100%. Also, spindown takes a while, so never reaching 100%
  948. is way more correct than reaching 100% while still doing stuff even if
  949. doing it this way is slightly bending the rules */
  950. ++PackagesTotal;
  951. }
  952. /*}}}*/
  953. bool pkgDPkgPM::Go(int StatusFd)
  954. {
  955. APT::Progress::PackageManager *progress = NULL;
  956. if (StatusFd == -1)
  957. progress = APT::Progress::PackageManagerProgressFactory();
  958. else
  959. progress = new APT::Progress::PackageManagerProgressFd(StatusFd);
  960. return Go(progress);
  961. }
  962. void pkgDPkgPM::StartPtyMagic()
  963. {
  964. if (_config->FindB("Dpkg::Use-Pty", true) == false)
  965. {
  966. d->master = -1;
  967. if (d->slave != NULL)
  968. free(d->slave);
  969. d->slave = NULL;
  970. return;
  971. }
  972. if (isatty(STDIN_FILENO) == 0)
  973. d->direct_stdin = true;
  974. _error->PushToStack();
  975. d->master = posix_openpt(O_RDWR | O_NOCTTY);
  976. if (d->master == -1)
  977. _error->Errno("posix_openpt", _("Can not write log (%s)"), _("Is /dev/pts mounted?"));
  978. else if (unlockpt(d->master) == -1)
  979. _error->Errno("unlockpt", "Unlocking the slave of master fd %d failed!", d->master);
  980. else
  981. {
  982. #ifdef HAVE_PTS_NAME_R
  983. char slave_name[64]; // 64 is used by bionic
  984. if (ptsname_r(d->master, slave_name, sizeof(slave_name)) != 0)
  985. #else
  986. char const * const slave_name = ptsname(d->master);
  987. if (slave_name == NULL)
  988. #endif
  989. _error->Errno("ptsname", "Getting name for slave of master fd %d failed!", d->master);
  990. else
  991. {
  992. d->slave = strdup(slave_name);
  993. if (d->slave == NULL)
  994. _error->Errno("strdup", "Copying name %s for slave of master fd %d failed!", slave_name, d->master);
  995. else if (grantpt(d->master) == -1)
  996. _error->Errno("grantpt", "Granting access to slave %s based on master fd %d failed!", slave_name, d->master);
  997. else if (tcgetattr(STDIN_FILENO, &d->tt) == 0)
  998. {
  999. d->tt_is_valid = true;
  1000. struct termios raw_tt;
  1001. // copy window size of stdout if its a 'good' terminal
  1002. if (tcgetattr(STDOUT_FILENO, &raw_tt) == 0)
  1003. {
  1004. struct winsize win;
  1005. if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) < 0)
  1006. _error->Errno("ioctl", "Getting TIOCGWINSZ from stdout failed!");
  1007. if (ioctl(d->master, TIOCSWINSZ, &win) < 0)
  1008. _error->Errno("ioctl", "Setting TIOCSWINSZ for master fd %d failed!", d->master);
  1009. }
  1010. if (tcsetattr(d->master, TCSANOW, &d->tt) == -1)
  1011. _error->Errno("tcsetattr", "Setting in Start via TCSANOW for master fd %d failed!", d->master);
  1012. raw_tt = d->tt;
  1013. cfmakeraw(&raw_tt);
  1014. raw_tt.c_lflag &= ~ECHO;
  1015. raw_tt.c_lflag |= ISIG;
  1016. // block SIGTTOU during tcsetattr to prevent a hang if
  1017. // the process is a member of the background process group
  1018. // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
  1019. sigemptyset(&d->sigmask);
  1020. sigaddset(&d->sigmask, SIGTTOU);
  1021. sigprocmask(SIG_BLOCK,&d->sigmask, &d->original_sigmask);
  1022. if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw_tt) == -1)
  1023. _error->Errno("tcsetattr", "Setting in Start via TCSAFLUSH for stdin failed!");
  1024. sigprocmask(SIG_SETMASK, &d->original_sigmask, NULL);
  1025. }
  1026. if (d->slave != NULL)
  1027. {
  1028. /* on linux, closing (and later reopening) all references to the slave
  1029. makes the slave a death end, so we open it here to have one open all
  1030. the time. We could use this fd in SetupSlavePtyMagic() for linux, but
  1031. on kfreebsd we get an incorrect ("step like") output then while it has
  1032. no problem with closing all references… so to avoid platform specific
  1033. code here we combine both and be happy once more */
  1034. d->protect_slave_from_dying = open(d->slave, O_RDWR | O_CLOEXEC | O_NOCTTY);
  1035. }
  1036. }
  1037. }
  1038. if (_error->PendingError() == true)
  1039. {
  1040. if (d->master != -1)
  1041. {
  1042. close(d->master);
  1043. d->master = -1;
  1044. }
  1045. if (d->slave != NULL)
  1046. {
  1047. free(d->slave);
  1048. d->slave = NULL;
  1049. }
  1050. _error->DumpErrors(std::cerr, GlobalError::DEBUG, false);
  1051. }
  1052. _error->RevertToStack();
  1053. }
  1054. void pkgDPkgPM::SetupSlavePtyMagic()
  1055. {
  1056. if(d->master == -1 || d->slave == NULL)
  1057. return;
  1058. if (close(d->master) == -1)
  1059. _error->FatalE("close", "Closing master %d in child failed!", d->master);
  1060. d->master = -1;
  1061. if (setsid() == -1)
  1062. _error->FatalE("setsid", "Starting a new session for child failed!");
  1063. int const slaveFd = open(d->slave, O_RDWR | O_NOCTTY);
  1064. if (slaveFd == -1)
  1065. _error->FatalE("open", _("Can not write log (%s)"), _("Is /dev/pts mounted?"));
  1066. else if (ioctl(slaveFd, TIOCSCTTY, 0) < 0)
  1067. _error->FatalE("ioctl", "Setting TIOCSCTTY for slave fd %d failed!", slaveFd);
  1068. else
  1069. {
  1070. unsigned short i = 0;
  1071. if (d->direct_stdin == true)
  1072. ++i;
  1073. for (; i < 3; ++i)
  1074. if (dup2(slaveFd, i) == -1)
  1075. _error->FatalE("dup2", "Dupping %d to %d in child failed!", slaveFd, i);
  1076. if (d->tt_is_valid == true && tcsetattr(STDIN_FILENO, TCSANOW, &d->tt) < 0)
  1077. _error->FatalE("tcsetattr", "Setting in Setup via TCSANOW for slave fd %d failed!", slaveFd);
  1078. }
  1079. if (slaveFd != -1)
  1080. close(slaveFd);
  1081. }
  1082. void pkgDPkgPM::StopPtyMagic()
  1083. {
  1084. if (d->slave != NULL)
  1085. free(d->slave);
  1086. d->slave = NULL;
  1087. if (d->protect_slave_from_dying != -1)
  1088. {
  1089. close(d->protect_slave_from_dying);
  1090. d->protect_slave_from_dying = -1;
  1091. }
  1092. if(d->master >= 0)
  1093. {
  1094. if (d->tt_is_valid == true && tcsetattr(STDIN_FILENO, TCSAFLUSH, &d->tt) == -1)
  1095. _error->FatalE("tcsetattr", "Setting in Stop via TCSAFLUSH for stdin failed!");
  1096. close(d->master);
  1097. d->master = -1;
  1098. }
  1099. }
  1100. // DPkgPM::Go - Run the sequence /*{{{*/
  1101. // ---------------------------------------------------------------------
  1102. /* This globs the operations and calls dpkg
  1103. *
  1104. * If it is called with a progress object apt will report the install
  1105. * progress to this object. It maps the dpkg states a package goes
  1106. * through to human readable (and i10n-able)
  1107. * names and calculates a percentage for each step.
  1108. */
  1109. bool pkgDPkgPM::Go(APT::Progress::PackageManager *progress)
  1110. {
  1111. pkgPackageManager::SigINTStop = false;
  1112. d->progress = progress;
  1113. // Generate the base argument list for dpkg
  1114. std::vector<std::string> const sArgs = debSystem::GetDpkgBaseCommand();
  1115. std::vector<const char *> Args(sArgs.size(), NULL);
  1116. std::transform(sArgs.begin(), sArgs.end(), Args.begin(),
  1117. [](std::string const &s) { return s.c_str(); });
  1118. unsigned long long const StartSize = std::accumulate(sArgs.begin(), sArgs.end(), 0llu,
  1119. [](unsigned long long const i, std::string const &s) { return i + s.length(); });
  1120. size_t const BaseArgs = Args.size();
  1121. fd_set rfds;
  1122. struct timespec tv;
  1123. // FIXME: do we really need this limit when we have MaxArgBytes?
  1124. unsigned int const MaxArgs = _config->FindI("Dpkg::MaxArgs",32*1024);
  1125. // try to figure out the max environment size
  1126. int OSArgMax = sysconf(_SC_ARG_MAX);
  1127. if(OSArgMax < 0)
  1128. OSArgMax = 32*1024;
  1129. OSArgMax -= EnvironmentSize() - 2*1024;
  1130. unsigned int const MaxArgBytes = _config->FindI("Dpkg::MaxArgBytes", OSArgMax);
  1131. bool const NoTriggers = _config->FindB("DPkg::NoTriggers", false);
  1132. if (RunScripts("DPkg::Pre-Invoke") == false)
  1133. return false;
  1134. if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
  1135. return false;
  1136. // support subpressing of triggers processing for special
  1137. // cases like d-i that runs the triggers handling manually
  1138. bool const TriggersPending = _config->FindB("DPkg::TriggersPending", false);
  1139. if (_config->FindB("DPkg::ConfigurePending", true) == true)
  1140. List.push_back(Item(Item::ConfigurePending, PkgIterator()));
  1141. // for the progress
  1142. BuildPackagesProgressMap();
  1143. d->stdin_is_dev_null = false;
  1144. // create log
  1145. OpenLog();
  1146. bool dpkgMultiArch = debSystem::SupportsMultiArch();
  1147. // start pty magic before the loop
  1148. StartPtyMagic();
  1149. // Tell the progress that its starting and fork dpkg
  1150. d->progress->Start(d->master);
  1151. // this loop is runs once per dpkg operation
  1152. vector<Item>::const_iterator I = List.begin();
  1153. while (I != List.end())
  1154. {
  1155. // Do all actions with the same Op in one run
  1156. vector<Item>::const_iterator J = I;
  1157. if (TriggersPending == true)
  1158. for (; J != List.end(); ++J)
  1159. {
  1160. if (J->Op == I->Op)
  1161. continue;
  1162. if (J->Op != Item::TriggersPending)
  1163. break;
  1164. vector<Item>::const_iterator T = J + 1;
  1165. if (T != List.end() && T->Op == I->Op)
  1166. continue;
  1167. break;
  1168. }
  1169. else
  1170. for (; J != List.end() && J->Op == I->Op; ++J)
  1171. /* nothing */;
  1172. // keep track of allocated strings for multiarch package names
  1173. std::vector<char *> Packages;
  1174. // start with the baseset of arguments
  1175. unsigned long Size = StartSize;
  1176. Args.erase(Args.begin() + BaseArgs, Args.end());
  1177. // Now check if we are within the MaxArgs limit
  1178. //
  1179. // this code below is problematic, because it may happen that
  1180. // the argument list is split in a way that A depends on B
  1181. // and they are in the same "--configure A B" run
  1182. // - with the split they may now be configured in different
  1183. // runs, using Immediate-Configure-All can help prevent this.
  1184. if (J - I > (signed)MaxArgs)
  1185. {
  1186. J = I + MaxArgs;
  1187. unsigned long const size = MaxArgs + 10;
  1188. Args.reserve(size);
  1189. Packages.reserve(size);
  1190. }
  1191. else
  1192. {
  1193. unsigned long const size = (J - I) + 10;
  1194. Args.reserve(size);
  1195. Packages.reserve(size);
  1196. }
  1197. int fd[2];
  1198. if (pipe(fd) != 0)
  1199. return _error->Errno("pipe","Failed to create IPC pipe to dpkg");
  1200. #define ADDARG(X) Args.push_back(X); Size += strlen(X)
  1201. #define ADDARGC(X) Args.push_back(X); Size += sizeof(X) - 1
  1202. ADDARGC("--status-fd");
  1203. char status_fd_buf[20];
  1204. snprintf(status_fd_buf,sizeof(status_fd_buf),"%i", fd[1]);
  1205. ADDARG(status_fd_buf);
  1206. unsigned long const Op = I->Op;
  1207. switch (I->Op)
  1208. {
  1209. case Item::Remove:
  1210. ADDARGC("--force-depends");
  1211. ADDARGC("--force-remove-essential");
  1212. ADDARGC("--remove");
  1213. break;
  1214. case Item::Purge:
  1215. ADDARGC("--force-depends");
  1216. ADDARGC("--force-remove-essential");
  1217. ADDARGC("--purge");
  1218. break;
  1219. case Item::Configure:
  1220. ADDARGC("--configure");
  1221. break;
  1222. case Item::ConfigurePending:
  1223. ADDARGC("--configure");
  1224. ADDARGC("--pending");
  1225. break;
  1226. case Item::TriggersPending:
  1227. ADDARGC("--triggers-only");
  1228. ADDARGC("--pending");
  1229. break;
  1230. case Item::Install:
  1231. ADDARGC("--unpack");
  1232. ADDARGC("--auto-deconfigure");
  1233. break;
  1234. }
  1235. if (NoTriggers == true && I->Op != Item::TriggersPending &&
  1236. I->Op != Item::ConfigurePending)
  1237. {
  1238. ADDARGC("--no-triggers");
  1239. }
  1240. #undef ADDARGC
  1241. // Write in the file or package names
  1242. if (I->Op == Item::Install)
  1243. {
  1244. for (;I != J && Size < MaxArgBytes; ++I)
  1245. {
  1246. if (I->File[0] != '/')
  1247. return _error->Error("Internal Error, Pathname to install is not absolute '%s'",I->File.c_str());
  1248. Args.push_back(I->File.c_str());
  1249. Size += I->File.length();
  1250. }
  1251. }
  1252. else
  1253. {
  1254. string const nativeArch = _config->Find("APT::Architecture");
  1255. unsigned long const oldSize = I->Op == Item::Configure ? Size : 0;
  1256. for (;I != J && Size < MaxArgBytes; ++I)
  1257. {
  1258. if((*I).Pkg.end() == true)
  1259. continue;
  1260. if (I->Op == Item::Configure && disappearedPkgs.find(I->Pkg.FullName(true)) != disappearedPkgs.end())
  1261. continue;
  1262. // We keep this here to allow "smooth" transitions from e.g. multiarch dpkg/ubuntu to dpkg/debian
  1263. if (dpkgMultiArch == false && (I->Pkg.Arch() == nativeArch ||
  1264. strcmp(I->Pkg.Arch(), "all") == 0 ||
  1265. strcmp(I->Pkg.Arch(), "none") == 0))
  1266. {
  1267. char const * const name = I->Pkg.Name();
  1268. ADDARG(name);
  1269. }
  1270. else
  1271. {
  1272. pkgCache::VerIterator PkgVer;
  1273. std::string name = I->Pkg.Name();
  1274. if (Op == Item::Remove || Op == Item::Purge)
  1275. {
  1276. PkgVer = I->Pkg.CurrentVer();
  1277. if(PkgVer.end() == true)
  1278. PkgVer = FindNowVersion(I->Pkg);
  1279. }
  1280. else
  1281. PkgVer = Cache[I->Pkg].InstVerIter(Cache);
  1282. if (strcmp(I->Pkg.Arch(), "none") == 0)
  1283. ; // never arch-qualify a package without an arch
  1284. else if (PkgVer.end() == false)
  1285. name.append(":").append(PkgVer.Arch());
  1286. else
  1287. _error->Warning("Can not find PkgVer for '%s'", name.c_str());
  1288. char * const fullname = strdup(name.c_str());
  1289. Packages.push_back(fullname);
  1290. ADDARG(fullname);
  1291. }
  1292. }
  1293. // skip configure action if all sheduled packages disappeared
  1294. if (oldSize == Size)
  1295. continue;
  1296. }
  1297. #undef ADDARG
  1298. J = I;
  1299. if (_config->FindB("Debug::pkgDPkgPM",false) == true)
  1300. {
  1301. for (std::vector<const char *>::const_iterator a = Args.begin();
  1302. a != Args.end(); ++a)
  1303. clog << *a << ' ';
  1304. clog << endl;
  1305. for (std::vector<char *>::const_iterator p = Packages.begin();
  1306. p != Packages.end(); ++p)
  1307. free(*p);
  1308. Packages.clear();
  1309. continue;
  1310. }
  1311. Args.push_back(NULL);
  1312. cout << flush;
  1313. clog << flush;
  1314. cerr << flush;
  1315. /* Mask off sig int/quit. We do this because dpkg also does when
  1316. it forks scripts. What happens is that when you hit ctrl-c it sends
  1317. it to all processes in the group. Since dpkg ignores the signal
  1318. it doesn't die but we do! So we must also ignore it */
  1319. sighandler_t old_SIGQUIT = signal(SIGQUIT,SIG_IGN);
  1320. sighandler_t old_SIGINT = signal(SIGINT,SigINT);
  1321. // Check here for any SIGINT
  1322. if (pkgPackageManager::SigINTStop && (Op == Item::Remove || Op == Item::Purge || Op == Item::Install))
  1323. break;
  1324. // ignore SIGHUP as well (debian #463030)
  1325. sighandler_t old_SIGHUP = signal(SIGHUP,SIG_IGN);
  1326. // now run dpkg
  1327. d->progress->StartDpkg();
  1328. std::set<int> KeepFDs;
  1329. KeepFDs.insert(fd[1]);
  1330. MergeKeepFdsFromConfiguration(KeepFDs);
  1331. pid_t Child = ExecFork(KeepFDs);
  1332. if (Child == 0)
  1333. {
  1334. // This is the child
  1335. SetupSlavePtyMagic();
  1336. close(fd[0]); // close the read end of the pipe
  1337. debSystem::DpkgChrootDirectory();
  1338. if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
  1339. _exit(100);
  1340. if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
  1341. {
  1342. int Flags;
  1343. int dummy = 0;
  1344. if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
  1345. _exit(100);
  1346. // Discard everything in stdin before forking dpkg
  1347. if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
  1348. _exit(100);
  1349. while (read(STDIN_FILENO,&dummy,1) == 1);
  1350. if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
  1351. _exit(100);
  1352. }
  1353. execvp(Args[0], (char**) &Args[0]);
  1354. cerr << "Could not exec dpkg!" << endl;
  1355. _exit(100);
  1356. }
  1357. // apply ionice
  1358. if (_config->FindB("DPkg::UseIoNice", false) == true)
  1359. ionice(Child);
  1360. // Wait for dpkg
  1361. int Status = 0;
  1362. // we read from dpkg here
  1363. int const _dpkgin = fd[0];
  1364. close(fd[1]); // close the write end of the pipe
  1365. // setups fds
  1366. sigemptyset(&d->sigmask);
  1367. sigprocmask(SIG_BLOCK,&d->sigmask,&d->original_sigmask);
  1368. /* free vectors (and therefore memory) as we don't need the included data anymore */
  1369. for (std::vector<char *>::const_iterator p = Packages.begin();
  1370. p != Packages.end(); ++p)
  1371. free(*p);
  1372. Packages.clear();
  1373. // the result of the waitpid call
  1374. int res;
  1375. int select_ret;
  1376. while ((res=waitpid(Child,&Status, WNOHANG)) != Child) {
  1377. if(res < 0) {
  1378. // FIXME: move this to a function or something, looks ugly here
  1379. // error handling, waitpid returned -1
  1380. if (errno == EINTR)
  1381. continue;
  1382. RunScripts("DPkg::Post-Invoke");
  1383. // Restore sig int/quit
  1384. signal(SIGQUIT,old_SIGQUIT);
  1385. signal(SIGINT,old_SIGINT);
  1386. signal(SIGHUP,old_SIGHUP);
  1387. return _error->Errno("waitpid","Couldn't wait for subprocess");
  1388. }
  1389. // wait for input or output here
  1390. FD_ZERO(&rfds);
  1391. if (d->master >= 0 && d->direct_stdin == false && d->stdin_is_dev_null == false)
  1392. FD_SET(STDIN_FILENO, &rfds);
  1393. FD_SET(_dpkgin, &rfds);
  1394. if(d->master >= 0)
  1395. FD_SET(d->master, &rfds);
  1396. tv.tv_sec = 0;
  1397. tv.tv_nsec = d->progress->GetPulseInterval();
  1398. select_ret = pselect(max(d->master, _dpkgin)+1, &rfds, NULL, NULL,
  1399. &tv, &d->original_sigmask);
  1400. if (select_ret < 0 && (errno == EINVAL || errno == ENOSYS))
  1401. select_ret = racy_pselect(max(d->master, _dpkgin)+1, &rfds, NULL,
  1402. NULL, &tv, &d->original_sigmask);
  1403. d->progress->Pulse();
  1404. if (select_ret == 0)
  1405. continue;
  1406. else if (select_ret < 0 && errno == EINTR)
  1407. continue;
  1408. else if (select_ret < 0)
  1409. {
  1410. perror("select() returned error");
  1411. continue;
  1412. }
  1413. if(d->master >= 0 && FD_ISSET(d->master, &rfds))
  1414. DoTerminalPty(d->master);
  1415. if(d->master >= 0 && FD_ISSET(0, &rfds))
  1416. DoStdin(d->master);
  1417. if(FD_ISSET(_dpkgin, &rfds))
  1418. DoDpkgStatusFd(_dpkgin);
  1419. }
  1420. close(_dpkgin);
  1421. // Restore sig int/quit
  1422. signal(SIGQUIT,old_SIGQUIT);
  1423. signal(SIGINT,old_SIGINT);
  1424. signal(SIGHUP,old_SIGHUP);
  1425. // Check for an error code.
  1426. if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
  1427. {
  1428. // if it was set to "keep-dpkg-runing" then we won't return
  1429. // here but keep the loop going and just report it as a error
  1430. // for later
  1431. bool const stopOnError = _config->FindB("Dpkg::StopOnError",true);
  1432. if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
  1433. strprintf(d->dpkg_error, "Sub-process %s received a segmentation fault.",Args[0]);
  1434. else if (WIFEXITED(Status) != 0)
  1435. strprintf(d->dpkg_error, "Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
  1436. else
  1437. strprintf(d->dpkg_error, "Sub-process %s exited unexpectedly",Args[0]);
  1438. _error->Error("%s", d->dpkg_error.c_str());
  1439. if(stopOnError)
  1440. break;
  1441. }
  1442. }
  1443. // dpkg is done at this point
  1444. d->progress->Stop();
  1445. StopPtyMagic();
  1446. CloseLog();
  1447. if (pkgPackageManager::SigINTStop)
  1448. _error->Warning(_("Operation was interrupted before it could finish"));
  1449. if (RunScripts("DPkg::Post-Invoke") == false)
  1450. return false;
  1451. if (_config->FindB("Debug::pkgDPkgPM",false) == false)
  1452. {
  1453. std::string const oldpkgcache = _config->FindFile("Dir::cache::pkgcache");
  1454. if (oldpkgcache.empty() == false && RealFileExists(oldpkgcache) == true &&
  1455. RemoveFile("pkgDPkgPM::Go", oldpkgcache))
  1456. {
  1457. std::string const srcpkgcache = _config->FindFile("Dir::cache::srcpkgcache");
  1458. if (srcpkgcache.empty() == false && RealFileExists(srcpkgcache) == true)
  1459. {
  1460. _error->PushToStack();
  1461. pkgCacheFile CacheFile;
  1462. CacheFile.BuildCaches(NULL, true);
  1463. _error->RevertToStack();
  1464. }
  1465. }
  1466. }
  1467. Cache.writeStateFile(NULL);
  1468. return d->dpkg_error.empty();
  1469. }
  1470. void SigINT(int /*sig*/) {
  1471. pkgPackageManager::SigINTStop = true;
  1472. }
  1473. /*}}}*/
  1474. // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
  1475. // ---------------------------------------------------------------------
  1476. /* */
  1477. void pkgDPkgPM::Reset()
  1478. {
  1479. List.erase(List.begin(),List.end());
  1480. }
  1481. /*}}}*/
  1482. // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
  1483. // ---------------------------------------------------------------------
  1484. /* */
  1485. void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
  1486. {
  1487. // If apport doesn't exist or isn't installed do nothing
  1488. // This e.g. prevents messages in 'universes' without apport
  1489. pkgCache::PkgIterator apportPkg = Cache.FindPkg("apport");
  1490. if (apportPkg.end() == true || apportPkg->CurrentVer == 0)
  1491. return;
  1492. string pkgname, reportfile, pkgver, arch;
  1493. string::size_type pos;
  1494. FILE *report;
  1495. if (_config->FindB("Dpkg::ApportFailureReport", true) == false)
  1496. {
  1497. std::clog << "configured to not write apport reports" << std::endl;
  1498. return;
  1499. }
  1500. // only report the first errors
  1501. if(pkgFailures > _config->FindI("APT::Apport::MaxReports", 3))
  1502. {
  1503. std::clog << _("No apport report written because MaxReports is reached already") << std::endl;
  1504. return;
  1505. }
  1506. // check if its not a follow up error
  1507. const char *needle = dgettext("dpkg", "dependency problems - leaving unconfigured");
  1508. if(strstr(errormsg, needle) != NULL) {
  1509. std::clog << _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl;
  1510. return;
  1511. }
  1512. // do not report disk-full failures
  1513. if(strstr(errormsg, strerror(ENOSPC)) != NULL) {
  1514. std::clog << _("No apport report written because the error message indicates a disk full error") << std::endl;
  1515. return;
  1516. }
  1517. // do not report out-of-memory failures
  1518. if(strstr(errormsg, strerror(ENOMEM)) != NULL ||
  1519. strstr(errormsg, "failed to allocate memory") != NULL) {
  1520. std::clog << _("No apport report written because the error message indicates a out of memory error") << std::endl;
  1521. return;
  1522. }
  1523. // do not report bugs regarding inaccessible local files
  1524. if(strstr(errormsg, strerror(ENOENT)) != NULL ||
  1525. strstr(errormsg, "cannot access archive") != NULL) {
  1526. std::clog << _("No apport report written because the error message indicates an issue on the local system") << std::endl;
  1527. return;
  1528. }
  1529. // do not report errors encountered when decompressing packages
  1530. if(strstr(errormsg, "--fsys-tarfile returned error exit status 2") != NULL) {
  1531. std::clog << _("No apport report written because the error message indicates an issue on the local system") << std::endl;
  1532. return;
  1533. }
  1534. // do not report dpkg I/O errors, this is a format string, so we compare
  1535. // the prefix and the suffix of the error with the dpkg error message
  1536. vector<string> io_errors;
  1537. io_errors.push_back(string("failed to read"));
  1538. io_errors.push_back(string("failed to write"));
  1539. io_errors.push_back(string("failed to seek"));
  1540. io_errors.push_back(string("unexpected end of file or stream"));
  1541. for (vector<string>::iterator I = io_errors.begin(); I != io_errors.end(); ++I)
  1542. {
  1543. vector<string> list = VectorizeString(dgettext("dpkg", (*I).c_str()), '%');
  1544. if (list.size() > 1) {
  1545. // we need to split %s, VectorizeString only allows char so we need
  1546. // to kill the "s" manually
  1547. if (list[1].size() > 1) {
  1548. list[1].erase(0, 1);
  1549. if(strstr(errormsg, list[0].c_str()) &&
  1550. strstr(errormsg, list[1].c_str())) {
  1551. std::clog << _("No apport report written because the error message indicates a dpkg I/O error") << std::endl;
  1552. return;
  1553. }
  1554. }
  1555. }
  1556. }
  1557. // get the pkgname and reportfile
  1558. pkgname = flNotDir(pkgpath);
  1559. pos = pkgname.find('_');
  1560. if(pos != string::npos)
  1561. pkgname = pkgname.substr(0, pos);
  1562. // find the package version and source package name
  1563. pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
  1564. if (Pkg.end() == true)
  1565. return;
  1566. pkgCache::VerIterator Ver = Cache.GetCandidateVersion(Pkg);
  1567. if (Ver.end() == true)
  1568. return;
  1569. pkgver = Ver.VerStr() == NULL ? "unknown" : Ver.VerStr();
  1570. // if the file exists already, we check:
  1571. // - if it was reported already (touched by apport).
  1572. // If not, we do nothing, otherwise
  1573. // we overwrite it. This is the same behaviour as apport
  1574. // - if we have a report with the same pkgversion already
  1575. // then we skip it
  1576. reportfile = flCombine("/var/crash",pkgname+".0.crash");
  1577. if(FileExists(reportfile))
  1578. {
  1579. struct stat buf;
  1580. char strbuf[255];
  1581. // check atime/mtime
  1582. stat(reportfile.c_str(), &buf);
  1583. if(buf.st_mtime > buf.st_atime)
  1584. return;
  1585. // check if the existing report is the same version
  1586. report = fopen(reportfile.c_str(),"r");
  1587. while(fgets(strbuf, sizeof(strbuf), report) != NULL)
  1588. {
  1589. if(strstr(strbuf,"Package:") == strbuf)
  1590. {
  1591. char pkgname[255], version[255];
  1592. if(sscanf(strbuf, "Package: %254s %254s", pkgname, version) == 2)
  1593. if(strcmp(pkgver.c_str(), version) == 0)
  1594. {
  1595. fclose(report);
  1596. return;
  1597. }
  1598. }
  1599. }
  1600. fclose(report);
  1601. }
  1602. // now write the report
  1603. arch = _config->Find("APT::Architecture");
  1604. report = fopen(reportfile.c_str(),"w");
  1605. if(report == NULL)
  1606. return;
  1607. if(_config->FindB("DPkgPM::InitialReportOnly",false) == true)
  1608. chmod(reportfile.c_str(), 0);
  1609. else
  1610. chmod(reportfile.c_str(), 0600);
  1611. fprintf(report, "ProblemType: Package\n");
  1612. fprintf(report, "Architecture: %s\n", arch.c_str());
  1613. time_t now = time(NULL);
  1614. char ctime_buf[26]; // need at least 26 bytes according to ctime(3)
  1615. fprintf(report, "Date: %s" , ctime_r(&now, ctime_buf));
  1616. fprintf(report, "Package: %s %s\n", pkgname.c_str(), pkgver.c_str());
  1617. fprintf(report, "SourcePackage: %s\n", Ver.SourcePkgName());
  1618. fprintf(report, "ErrorMessage:\n %s\n", errormsg);
  1619. // ensure that the log is flushed
  1620. if(d->term_out)
  1621. fflush(d->term_out);
  1622. // attach terminal log it if we have it
  1623. string logfile_name = _config->FindFile("Dir::Log::Terminal");
  1624. if (!logfile_name.empty())
  1625. {
  1626. FILE *log = NULL;
  1627. fprintf(report, "DpkgTerminalLog:\n");
  1628. log = fopen(logfile_name.c_str(),"r");
  1629. if(log != NULL)
  1630. {
  1631. char buf[1024];
  1632. while( fgets(buf, sizeof(buf), log) != NULL)
  1633. fprintf(report, " %s", buf);
  1634. fprintf(report, " \n");
  1635. fclose(log);
  1636. }
  1637. }
  1638. // attach history log it if we have it
  1639. string histfile_name = _config->FindFile("Dir::Log::History");
  1640. if (!histfile_name.empty())
  1641. {
  1642. fprintf(report, "DpkgHistoryLog:\n");
  1643. FILE* log = fopen(histfile_name.c_str(),"r");
  1644. if(log != NULL)
  1645. {
  1646. char buf[1024];
  1647. while( fgets(buf, sizeof(buf), log) != NULL)
  1648. fprintf(report, " %s", buf);
  1649. fclose(log);
  1650. }
  1651. }
  1652. // log the ordering, see dpkgpm.h and the "Ops" enum there
  1653. const char *ops_str[] = {
  1654. "Install",
  1655. "Configure",
  1656. "Remove",
  1657. "Purge",
  1658. "ConfigurePending",
  1659. "TriggersPending",
  1660. };
  1661. fprintf(report, "AptOrdering:\n");
  1662. for (vector<Item>::iterator I = List.begin(); I != List.end(); ++I)
  1663. if ((*I).Pkg != NULL)
  1664. fprintf(report, " %s: %s\n", (*I).Pkg.Name(), ops_str[(*I).Op]);
  1665. else
  1666. fprintf(report, " %s: %s\n", "NULL", ops_str[(*I).Op]);
  1667. // attach dmesg log (to learn about segfaults)
  1668. if (FileExists("/bin/dmesg"))
  1669. {
  1670. fprintf(report, "Dmesg:\n");
  1671. FILE *log = popen("/bin/dmesg","r");
  1672. if(log != NULL)
  1673. {
  1674. char buf[1024];
  1675. while( fgets(buf, sizeof(buf), log) != NULL)
  1676. fprintf(report, " %s", buf);
  1677. pclose(log);
  1678. }
  1679. }
  1680. // attach df -l log (to learn about filesystem status)
  1681. if (FileExists("/bin/df"))
  1682. {
  1683. fprintf(report, "Df:\n");
  1684. FILE *log = popen("/bin/df -l","r");
  1685. if(log != NULL)
  1686. {
  1687. char buf[1024];
  1688. while( fgets(buf, sizeof(buf), log) != NULL)
  1689. fprintf(report, " %s", buf);
  1690. pclose(log);
  1691. }
  1692. }
  1693. fclose(report);
  1694. }
  1695. /*}}}*/