dpkgpm.cc 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: dpkgpm.cc,v 1.28 2004/01/27 02:25:01 mdz Exp $
  4. /* ######################################################################
  5. DPKG Package Manager - Provide an interface to dpkg
  6. ##################################################################### */
  7. /*}}}*/
  8. // Includes /*{{{*/
  9. #include <config.h>
  10. #include <apt-pkg/cachefile.h>
  11. #include <apt-pkg/configuration.h>
  12. #include <apt-pkg/depcache.h>
  13. #include <apt-pkg/dpkgpm.h>
  14. #include <apt-pkg/error.h>
  15. #include <apt-pkg/fileutl.h>
  16. #include <apt-pkg/install-progress.h>
  17. #include <apt-pkg/packagemanager.h>
  18. #include <apt-pkg/pkgrecords.h>
  19. #include <apt-pkg/strutl.h>
  20. #include <apt-pkg/cacheiterators.h>
  21. #include <apt-pkg/macros.h>
  22. #include <apt-pkg/pkgcache.h>
  23. #include <errno.h>
  24. #include <fcntl.h>
  25. #include <grp.h>
  26. #include <pty.h>
  27. #include <pwd.h>
  28. #include <signal.h>
  29. #include <stddef.h>
  30. #include <stdio.h>
  31. #include <stdlib.h>
  32. #include <sys/ioctl.h>
  33. #include <sys/select.h>
  34. #include <sys/stat.h>
  35. #include <sys/time.h>
  36. #include <sys/wait.h>
  37. #include <termios.h>
  38. #include <time.h>
  39. #include <unistd.h>
  40. #include <algorithm>
  41. #include <cstring>
  42. #include <iostream>
  43. #include <map>
  44. #include <set>
  45. #include <string>
  46. #include <utility>
  47. #include <vector>
  48. #include <apti18n.h>
  49. /*}}}*/
  50. using namespace std;
  51. APT_PURE static unsigned int
  52. EnvironmentSize()
  53. {
  54. unsigned int size = 0;
  55. char **envp = environ;
  56. while (*envp != NULL)
  57. size += strlen (*envp++) + 1;
  58. return size;
  59. }
  60. class pkgDPkgPMPrivate
  61. {
  62. public:
  63. pkgDPkgPMPrivate() : stdin_is_dev_null(false), dpkgbuf_pos(0),
  64. term_out(NULL), history_out(NULL),
  65. progress(NULL), tt_is_valid(false), master(-1),
  66. slave(NULL), protect_slave_from_dying(-1)
  67. {
  68. dpkgbuf[0] = '\0';
  69. }
  70. ~pkgDPkgPMPrivate()
  71. {
  72. }
  73. bool stdin_is_dev_null;
  74. // the buffer we use for the dpkg status-fd reading
  75. char dpkgbuf[1024];
  76. int dpkgbuf_pos;
  77. FILE *term_out;
  78. FILE *history_out;
  79. string dpkg_error;
  80. APT::Progress::PackageManager *progress;
  81. // pty stuff
  82. struct termios tt;
  83. bool tt_is_valid;
  84. int master;
  85. char * slave;
  86. int protect_slave_from_dying;
  87. // signals
  88. sigset_t sigmask;
  89. sigset_t original_sigmask;
  90. };
  91. namespace
  92. {
  93. // Maps the dpkg "processing" info to human readable names. Entry 0
  94. // of each array is the key, entry 1 is the value.
  95. const std::pair<const char *, const char *> PackageProcessingOps[] = {
  96. std::make_pair("install", N_("Installing %s")),
  97. std::make_pair("configure", N_("Configuring %s")),
  98. std::make_pair("remove", N_("Removing %s")),
  99. std::make_pair("purge", N_("Completely removing %s")),
  100. std::make_pair("disappear", N_("Noting disappearance of %s")),
  101. std::make_pair("trigproc", N_("Running post-installation trigger %s"))
  102. };
  103. const std::pair<const char *, const char *> * const PackageProcessingOpsBegin = PackageProcessingOps;
  104. const std::pair<const char *, const char *> * const PackageProcessingOpsEnd = PackageProcessingOps + sizeof(PackageProcessingOps) / sizeof(PackageProcessingOps[0]);
  105. // Predicate to test whether an entry in the PackageProcessingOps
  106. // array matches a string.
  107. class MatchProcessingOp
  108. {
  109. const char *target;
  110. public:
  111. MatchProcessingOp(const char *the_target)
  112. : target(the_target)
  113. {
  114. }
  115. bool operator()(const std::pair<const char *, const char *> &pair) const
  116. {
  117. return strcmp(pair.first, target) == 0;
  118. }
  119. };
  120. }
  121. /* helper function to ionice the given PID
  122. there is no C header for ionice yet - just the syscall interface
  123. so we use the binary from util-linux
  124. */
  125. static bool
  126. ionice(int PID)
  127. {
  128. if (!FileExists("/usr/bin/ionice"))
  129. return false;
  130. pid_t Process = ExecFork();
  131. if (Process == 0)
  132. {
  133. char buf[32];
  134. snprintf(buf, sizeof(buf), "-p%d", PID);
  135. const char *Args[4];
  136. Args[0] = "/usr/bin/ionice";
  137. Args[1] = "-c3";
  138. Args[2] = buf;
  139. Args[3] = 0;
  140. execv(Args[0], (char **)Args);
  141. }
  142. return ExecWait(Process, "ionice");
  143. }
  144. static std::string getDpkgExecutable()
  145. {
  146. string Tmp = _config->Find("Dir::Bin::dpkg","dpkg");
  147. string const dpkgChrootDir = _config->FindDir("DPkg::Chroot-Directory", "/");
  148. size_t dpkgChrootLen = dpkgChrootDir.length();
  149. if (dpkgChrootDir != "/" && Tmp.find(dpkgChrootDir) == 0)
  150. {
  151. if (dpkgChrootDir[dpkgChrootLen - 1] == '/')
  152. --dpkgChrootLen;
  153. Tmp = Tmp.substr(dpkgChrootLen);
  154. }
  155. return Tmp;
  156. }
  157. // dpkgChrootDirectory - chrooting for dpkg if needed /*{{{*/
  158. static void dpkgChrootDirectory()
  159. {
  160. std::string const chrootDir = _config->FindDir("DPkg::Chroot-Directory");
  161. if (chrootDir == "/")
  162. return;
  163. std::cerr << "Chrooting into " << chrootDir << std::endl;
  164. if (chroot(chrootDir.c_str()) != 0)
  165. _exit(100);
  166. if (chdir("/") != 0)
  167. _exit(100);
  168. }
  169. /*}}}*/
  170. // FindNowVersion - Helper to find a Version in "now" state /*{{{*/
  171. // ---------------------------------------------------------------------
  172. /* This is helpful when a package is no longer installed but has residual
  173. * config files
  174. */
  175. static
  176. pkgCache::VerIterator FindNowVersion(const pkgCache::PkgIterator &Pkg)
  177. {
  178. pkgCache::VerIterator Ver;
  179. for (Ver = Pkg.VersionList(); Ver.end() == false; ++Ver)
  180. for (pkgCache::VerFileIterator Vf = Ver.FileList(); Vf.end() == false; ++Vf)
  181. for (pkgCache::PkgFileIterator F = Vf.File(); F.end() == false; ++F)
  182. if (F->Archive != 0 && strcmp(F.Archive(), "now") == 0)
  183. return Ver;
  184. return Ver;
  185. }
  186. /*}}}*/
  187. // DPkgPM::pkgDPkgPM - Constructor /*{{{*/
  188. // ---------------------------------------------------------------------
  189. /* */
  190. pkgDPkgPM::pkgDPkgPM(pkgDepCache *Cache)
  191. : pkgPackageManager(Cache), pkgFailures(0), PackagesDone(0), PackagesTotal(0)
  192. {
  193. d = new pkgDPkgPMPrivate();
  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. 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. // ---------------------------------------------------------------------
  705. /*
  706. */
  707. void pkgDPkgPM::DoDpkgStatusFd(int statusfd)
  708. {
  709. char *p, *q;
  710. int len;
  711. len=read(statusfd, &d->dpkgbuf[d->dpkgbuf_pos], sizeof(d->dpkgbuf)-d->dpkgbuf_pos);
  712. d->dpkgbuf_pos += len;
  713. if(len <= 0)
  714. return;
  715. // process line by line if we have a buffer
  716. p = q = d->dpkgbuf;
  717. while((q=(char*)memchr(p, '\n', d->dpkgbuf+d->dpkgbuf_pos-p)) != NULL)
  718. {
  719. *q = 0;
  720. ProcessDpkgStatusLine(p);
  721. p=q+1; // continue with next line
  722. }
  723. // now move the unprocessed bits (after the final \n that is now a 0x0)
  724. // to the start and update d->dpkgbuf_pos
  725. p = (char*)memrchr(d->dpkgbuf, 0, d->dpkgbuf_pos);
  726. if(p == NULL)
  727. return;
  728. // we are interessted in the first char *after* 0x0
  729. p++;
  730. // move the unprocessed tail to the start and update pos
  731. memmove(d->dpkgbuf, p, p-d->dpkgbuf);
  732. d->dpkgbuf_pos = d->dpkgbuf+d->dpkgbuf_pos-p;
  733. }
  734. /*}}}*/
  735. // DPkgPM::WriteHistoryTag /*{{{*/
  736. void pkgDPkgPM::WriteHistoryTag(string const &tag, string value)
  737. {
  738. size_t const length = value.length();
  739. if (length == 0)
  740. return;
  741. // poor mans rstrip(", ")
  742. if (value[length-2] == ',' && value[length-1] == ' ')
  743. value.erase(length - 2, 2);
  744. fprintf(d->history_out, "%s: %s\n", tag.c_str(), value.c_str());
  745. } /*}}}*/
  746. // DPkgPM::OpenLog /*{{{*/
  747. bool pkgDPkgPM::OpenLog()
  748. {
  749. string const logdir = _config->FindDir("Dir::Log");
  750. if(CreateAPTDirectoryIfNeeded(logdir, logdir) == false)
  751. // FIXME: use a better string after freeze
  752. return _error->Error(_("Directory '%s' missing"), logdir.c_str());
  753. // get current time
  754. char timestr[200];
  755. time_t const t = time(NULL);
  756. struct tm const * const tmp = localtime(&t);
  757. strftime(timestr, sizeof(timestr), "%F %T", tmp);
  758. // open terminal log
  759. string const logfile_name = flCombine(logdir,
  760. _config->Find("Dir::Log::Terminal"));
  761. if (!logfile_name.empty())
  762. {
  763. d->term_out = fopen(logfile_name.c_str(),"a");
  764. if (d->term_out == NULL)
  765. return _error->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name.c_str());
  766. setvbuf(d->term_out, NULL, _IONBF, 0);
  767. SetCloseExec(fileno(d->term_out), true);
  768. if (getuid() == 0) // if we aren't root, we can't chown a file, so don't try it
  769. {
  770. struct passwd *pw = getpwnam("root");
  771. struct group *gr = getgrnam("adm");
  772. if (pw != NULL && gr != NULL && chown(logfile_name.c_str(), pw->pw_uid, gr->gr_gid) != 0)
  773. _error->WarningE("OpenLog", "chown to root:adm of file %s failed", logfile_name.c_str());
  774. }
  775. if (chmod(logfile_name.c_str(), 0640) != 0)
  776. _error->WarningE("OpenLog", "chmod 0640 of file %s failed", logfile_name.c_str());
  777. fprintf(d->term_out, "\nLog started: %s\n", timestr);
  778. }
  779. // write your history
  780. string const history_name = flCombine(logdir,
  781. _config->Find("Dir::Log::History"));
  782. if (!history_name.empty())
  783. {
  784. d->history_out = fopen(history_name.c_str(),"a");
  785. if (d->history_out == NULL)
  786. return _error->WarningE("OpenLog", _("Could not open file '%s'"), history_name.c_str());
  787. SetCloseExec(fileno(d->history_out), true);
  788. chmod(history_name.c_str(), 0644);
  789. fprintf(d->history_out, "\nStart-Date: %s\n", timestr);
  790. string remove, purge, install, reinstall, upgrade, downgrade;
  791. for (pkgCache::PkgIterator I = Cache.PkgBegin(); I.end() == false; ++I)
  792. {
  793. enum { CANDIDATE, CANDIDATE_AUTO, CURRENT_CANDIDATE, CURRENT } infostring;
  794. string *line = NULL;
  795. #define HISTORYINFO(X, Y) { line = &X; infostring = Y; }
  796. if (Cache[I].NewInstall() == true)
  797. HISTORYINFO(install, CANDIDATE_AUTO)
  798. else if (Cache[I].ReInstall() == true)
  799. HISTORYINFO(reinstall, CANDIDATE)
  800. else if (Cache[I].Upgrade() == true)
  801. HISTORYINFO(upgrade, CURRENT_CANDIDATE)
  802. else if (Cache[I].Downgrade() == true)
  803. HISTORYINFO(downgrade, CURRENT_CANDIDATE)
  804. else if (Cache[I].Delete() == true)
  805. HISTORYINFO((Cache[I].Purge() ? purge : remove), CURRENT)
  806. else
  807. continue;
  808. #undef HISTORYINFO
  809. line->append(I.FullName(false)).append(" (");
  810. switch (infostring) {
  811. case CANDIDATE: line->append(Cache[I].CandVersion); break;
  812. case CANDIDATE_AUTO:
  813. line->append(Cache[I].CandVersion);
  814. if ((Cache[I].Flags & pkgCache::Flag::Auto) == pkgCache::Flag::Auto)
  815. line->append(", automatic");
  816. break;
  817. case CURRENT_CANDIDATE: line->append(Cache[I].CurVersion).append(", ").append(Cache[I].CandVersion); break;
  818. case CURRENT: line->append(Cache[I].CurVersion); break;
  819. }
  820. line->append("), ");
  821. }
  822. if (_config->Exists("Commandline::AsString") == true)
  823. WriteHistoryTag("Commandline", _config->Find("Commandline::AsString"));
  824. WriteHistoryTag("Install", install);
  825. WriteHistoryTag("Reinstall", reinstall);
  826. WriteHistoryTag("Upgrade", upgrade);
  827. WriteHistoryTag("Downgrade",downgrade);
  828. WriteHistoryTag("Remove",remove);
  829. WriteHistoryTag("Purge",purge);
  830. fflush(d->history_out);
  831. }
  832. return true;
  833. }
  834. /*}}}*/
  835. // DPkg::CloseLog /*{{{*/
  836. bool pkgDPkgPM::CloseLog()
  837. {
  838. char timestr[200];
  839. time_t t = time(NULL);
  840. struct tm *tmp = localtime(&t);
  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. _error->PushToStack();
  973. d->master = posix_openpt(O_RDWR | O_NOCTTY);
  974. if (d->master == -1)
  975. _error->Errno("posix_openpt", _("Can not write log (%s)"), _("Is /dev/pts mounted?"));
  976. else if (unlockpt(d->master) == -1)
  977. _error->Errno("unlockpt", "Unlocking the slave of master fd %d failed!", d->master);
  978. else
  979. {
  980. char const * const slave_name = ptsname(d->master);
  981. if (slave_name == NULL)
  982. _error->Errno("ptsname", "Getting name for slave of master fd %d failed!", d->master);
  983. else
  984. {
  985. d->slave = strdup(slave_name);
  986. if (d->slave == NULL)
  987. _error->Errno("strdup", "Copying name %s for slave of master fd %d failed!", slave_name, d->master);
  988. else if (grantpt(d->master) == -1)
  989. _error->Errno("grantpt", "Granting access to slave %s based on master fd %d failed!", slave_name, d->master);
  990. else if (tcgetattr(STDIN_FILENO, &d->tt) == 0)
  991. {
  992. d->tt_is_valid = true;
  993. struct termios raw_tt;
  994. // copy window size of stdout if its a 'good' terminal
  995. if (tcgetattr(STDOUT_FILENO, &raw_tt) == 0)
  996. {
  997. struct winsize win;
  998. if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) < 0)
  999. _error->Errno("ioctl", "Getting TIOCGWINSZ from stdout failed!");
  1000. if (ioctl(d->master, TIOCSWINSZ, &win) < 0)
  1001. _error->Errno("ioctl", "Setting TIOCSWINSZ for master fd %d failed!", d->master);
  1002. }
  1003. if (tcsetattr(d->master, TCSANOW, &d->tt) == -1)
  1004. _error->Errno("tcsetattr", "Setting in Start via TCSANOW for master fd %d failed!", d->master);
  1005. raw_tt = d->tt;
  1006. cfmakeraw(&raw_tt);
  1007. raw_tt.c_lflag &= ~ECHO;
  1008. raw_tt.c_lflag |= ISIG;
  1009. // block SIGTTOU during tcsetattr to prevent a hang if
  1010. // the process is a member of the background process group
  1011. // http://www.opengroup.org/onlinepubs/000095399/functions/tcsetattr.html
  1012. sigemptyset(&d->sigmask);
  1013. sigaddset(&d->sigmask, SIGTTOU);
  1014. sigprocmask(SIG_BLOCK,&d->sigmask, &d->original_sigmask);
  1015. if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw_tt) == -1)
  1016. _error->Errno("tcsetattr", "Setting in Start via TCSAFLUSH for stdin failed!");
  1017. sigprocmask(SIG_SETMASK, &d->original_sigmask, NULL);
  1018. }
  1019. if (d->slave != NULL)
  1020. {
  1021. /* on linux, closing (and later reopening) all references to the slave
  1022. makes the slave a death end, so we open it here to have one open all
  1023. the time. We could use this fd in SetupSlavePtyMagic() for linux, but
  1024. on kfreebsd we get an incorrect ("step like") output then while it has
  1025. no problem with closing all references… so to avoid platform specific
  1026. code here we combine both and be happy once more */
  1027. d->protect_slave_from_dying = open(d->slave, O_RDWR | O_CLOEXEC);
  1028. }
  1029. }
  1030. }
  1031. if (_error->PendingError() == true)
  1032. {
  1033. if (d->master != -1)
  1034. {
  1035. close(d->master);
  1036. d->master = -1;
  1037. }
  1038. if (d->slave != NULL)
  1039. {
  1040. free(d->slave);
  1041. d->slave = NULL;
  1042. }
  1043. _error->DumpErrors(std::cerr);
  1044. }
  1045. _error->RevertToStack();
  1046. }
  1047. void pkgDPkgPM::SetupSlavePtyMagic()
  1048. {
  1049. if(d->master == -1 || d->slave == NULL)
  1050. return;
  1051. if (close(d->master) == -1)
  1052. _error->FatalE("close", "Closing master %d in child failed!", d->master);
  1053. d->master = -1;
  1054. if (setsid() == -1)
  1055. _error->FatalE("setsid", "Starting a new session for child failed!");
  1056. int const slaveFd = open(d->slave, O_RDWR);
  1057. if (slaveFd == -1)
  1058. _error->FatalE("open", _("Can not write log (%s)"), _("Is /dev/pts mounted?"));
  1059. else if (ioctl(slaveFd, TIOCSCTTY, 0) < 0)
  1060. _error->FatalE("ioctl", "Setting TIOCSCTTY for slave fd %d failed!", slaveFd);
  1061. else
  1062. {
  1063. for (unsigned short i = 0; i < 3; ++i)
  1064. if (dup2(slaveFd, i) == -1)
  1065. _error->FatalE("dup2", "Dupping %d to %d in child failed!", slaveFd, i);
  1066. if (d->tt_is_valid == true && tcsetattr(STDIN_FILENO, TCSANOW, &d->tt) < 0)
  1067. _error->FatalE("tcsetattr", "Setting in Setup via TCSANOW for slave fd %d failed!", slaveFd);
  1068. }
  1069. if (slaveFd != -1)
  1070. close(slaveFd);
  1071. }
  1072. void pkgDPkgPM::StopPtyMagic()
  1073. {
  1074. if (d->slave != NULL)
  1075. free(d->slave);
  1076. d->slave = NULL;
  1077. if (d->protect_slave_from_dying != -1)
  1078. {
  1079. close(d->protect_slave_from_dying);
  1080. d->protect_slave_from_dying = -1;
  1081. }
  1082. if(d->master >= 0)
  1083. {
  1084. if (d->tt_is_valid == true && tcsetattr(STDIN_FILENO, TCSAFLUSH, &d->tt) == -1)
  1085. _error->FatalE("tcsetattr", "Setting in Stop via TCSAFLUSH for stdin failed!");
  1086. close(d->master);
  1087. d->master = -1;
  1088. }
  1089. }
  1090. // DPkgPM::Go - Run the sequence /*{{{*/
  1091. // ---------------------------------------------------------------------
  1092. /* This globs the operations and calls dpkg
  1093. *
  1094. * If it is called with a progress object apt will report the install
  1095. * progress to this object. It maps the dpkg states a package goes
  1096. * through to human readable (and i10n-able)
  1097. * names and calculates a percentage for each step.
  1098. */
  1099. bool pkgDPkgPM::Go(APT::Progress::PackageManager *progress)
  1100. {
  1101. pkgPackageManager::SigINTStop = false;
  1102. d->progress = progress;
  1103. // Generate the base argument list for dpkg
  1104. unsigned long StartSize = 0;
  1105. std::vector<const char *> Args;
  1106. std::string DpkgExecutable = getDpkgExecutable();
  1107. Args.push_back(DpkgExecutable.c_str());
  1108. StartSize += DpkgExecutable.length();
  1109. // Stick in any custom dpkg options
  1110. Configuration::Item const *Opts = _config->Tree("DPkg::Options");
  1111. if (Opts != 0)
  1112. {
  1113. Opts = Opts->Child;
  1114. for (; Opts != 0; Opts = Opts->Next)
  1115. {
  1116. if (Opts->Value.empty() == true)
  1117. continue;
  1118. Args.push_back(Opts->Value.c_str());
  1119. StartSize += Opts->Value.length();
  1120. }
  1121. }
  1122. size_t const BaseArgs = Args.size();
  1123. // we need to detect if we can qualify packages with the architecture or not
  1124. Args.push_back("--assert-multi-arch");
  1125. Args.push_back(NULL);
  1126. pid_t dpkgAssertMultiArch = ExecFork();
  1127. if (dpkgAssertMultiArch == 0)
  1128. {
  1129. dpkgChrootDirectory();
  1130. // redirect everything to the ultimate sink as we only need the exit-status
  1131. int const nullfd = open("/dev/null", O_RDONLY);
  1132. dup2(nullfd, STDIN_FILENO);
  1133. dup2(nullfd, STDOUT_FILENO);
  1134. dup2(nullfd, STDERR_FILENO);
  1135. execvp(Args[0], (char**) &Args[0]);
  1136. _error->WarningE("dpkgGo", "Can't detect if dpkg supports multi-arch!");
  1137. _exit(2);
  1138. }
  1139. fd_set rfds;
  1140. struct timespec tv;
  1141. // FIXME: do we really need this limit when we have MaxArgBytes?
  1142. unsigned int const MaxArgs = _config->FindI("Dpkg::MaxArgs",32*1024);
  1143. // try to figure out the max environment size
  1144. int OSArgMax = sysconf(_SC_ARG_MAX);
  1145. if(OSArgMax < 0)
  1146. OSArgMax = 32*1024;
  1147. OSArgMax -= EnvironmentSize() - 2*1024;
  1148. unsigned int const MaxArgBytes = _config->FindI("Dpkg::MaxArgBytes", OSArgMax);
  1149. bool const NoTriggers = _config->FindB("DPkg::NoTriggers", false);
  1150. if (RunScripts("DPkg::Pre-Invoke") == false)
  1151. return false;
  1152. if (RunScriptsWithPkgs("DPkg::Pre-Install-Pkgs") == false)
  1153. return false;
  1154. // support subpressing of triggers processing for special
  1155. // cases like d-i that runs the triggers handling manually
  1156. bool const TriggersPending = _config->FindB("DPkg::TriggersPending", false);
  1157. if (_config->FindB("DPkg::ConfigurePending", true) == true)
  1158. List.push_back(Item(Item::ConfigurePending, PkgIterator()));
  1159. // for the progress
  1160. BuildPackagesProgressMap();
  1161. d->stdin_is_dev_null = false;
  1162. // create log
  1163. OpenLog();
  1164. bool dpkgMultiArch = false;
  1165. if (dpkgAssertMultiArch > 0)
  1166. {
  1167. int Status = 0;
  1168. while (waitpid(dpkgAssertMultiArch, &Status, 0) != dpkgAssertMultiArch)
  1169. {
  1170. if (errno == EINTR)
  1171. continue;
  1172. _error->WarningE("dpkgGo", _("Waited for %s but it wasn't there"), "dpkg --assert-multi-arch");
  1173. break;
  1174. }
  1175. if (WIFEXITED(Status) == true && WEXITSTATUS(Status) == 0)
  1176. dpkgMultiArch = true;
  1177. }
  1178. // start pty magic before the loop
  1179. StartPtyMagic();
  1180. // Tell the progress that its starting and fork dpkg
  1181. d->progress->Start(d->master);
  1182. // this loop is runs once per dpkg operation
  1183. vector<Item>::const_iterator I = List.begin();
  1184. while (I != List.end())
  1185. {
  1186. // Do all actions with the same Op in one run
  1187. vector<Item>::const_iterator J = I;
  1188. if (TriggersPending == true)
  1189. for (; J != List.end(); ++J)
  1190. {
  1191. if (J->Op == I->Op)
  1192. continue;
  1193. if (J->Op != Item::TriggersPending)
  1194. break;
  1195. vector<Item>::const_iterator T = J + 1;
  1196. if (T != List.end() && T->Op == I->Op)
  1197. continue;
  1198. break;
  1199. }
  1200. else
  1201. for (; J != List.end() && J->Op == I->Op; ++J)
  1202. /* nothing */;
  1203. // keep track of allocated strings for multiarch package names
  1204. std::vector<char *> Packages;
  1205. // start with the baseset of arguments
  1206. unsigned long Size = StartSize;
  1207. Args.erase(Args.begin() + BaseArgs, Args.end());
  1208. // Now check if we are within the MaxArgs limit
  1209. //
  1210. // this code below is problematic, because it may happen that
  1211. // the argument list is split in a way that A depends on B
  1212. // and they are in the same "--configure A B" run
  1213. // - with the split they may now be configured in different
  1214. // runs, using Immediate-Configure-All can help prevent this.
  1215. if (J - I > (signed)MaxArgs)
  1216. {
  1217. J = I + MaxArgs;
  1218. unsigned long const size = MaxArgs + 10;
  1219. Args.reserve(size);
  1220. Packages.reserve(size);
  1221. }
  1222. else
  1223. {
  1224. unsigned long const size = (J - I) + 10;
  1225. Args.reserve(size);
  1226. Packages.reserve(size);
  1227. }
  1228. int fd[2];
  1229. if (pipe(fd) != 0)
  1230. return _error->Errno("pipe","Failed to create IPC pipe to dpkg");
  1231. #define ADDARG(X) Args.push_back(X); Size += strlen(X)
  1232. #define ADDARGC(X) Args.push_back(X); Size += sizeof(X) - 1
  1233. ADDARGC("--status-fd");
  1234. char status_fd_buf[20];
  1235. snprintf(status_fd_buf,sizeof(status_fd_buf),"%i", fd[1]);
  1236. ADDARG(status_fd_buf);
  1237. unsigned long const Op = I->Op;
  1238. switch (I->Op)
  1239. {
  1240. case Item::Remove:
  1241. ADDARGC("--force-depends");
  1242. ADDARGC("--force-remove-essential");
  1243. ADDARGC("--remove");
  1244. break;
  1245. case Item::Purge:
  1246. ADDARGC("--force-depends");
  1247. ADDARGC("--force-remove-essential");
  1248. ADDARGC("--purge");
  1249. break;
  1250. case Item::Configure:
  1251. ADDARGC("--configure");
  1252. break;
  1253. case Item::ConfigurePending:
  1254. ADDARGC("--configure");
  1255. ADDARGC("--pending");
  1256. break;
  1257. case Item::TriggersPending:
  1258. ADDARGC("--triggers-only");
  1259. ADDARGC("--pending");
  1260. break;
  1261. case Item::Install:
  1262. ADDARGC("--unpack");
  1263. ADDARGC("--auto-deconfigure");
  1264. break;
  1265. }
  1266. if (NoTriggers == true && I->Op != Item::TriggersPending &&
  1267. I->Op != Item::ConfigurePending)
  1268. {
  1269. ADDARGC("--no-triggers");
  1270. }
  1271. #undef ADDARGC
  1272. // Write in the file or package names
  1273. if (I->Op == Item::Install)
  1274. {
  1275. for (;I != J && Size < MaxArgBytes; ++I)
  1276. {
  1277. if (I->File[0] != '/')
  1278. return _error->Error("Internal Error, Pathname to install is not absolute '%s'",I->File.c_str());
  1279. Args.push_back(I->File.c_str());
  1280. Size += I->File.length();
  1281. }
  1282. }
  1283. else
  1284. {
  1285. string const nativeArch = _config->Find("APT::Architecture");
  1286. unsigned long const oldSize = I->Op == Item::Configure ? Size : 0;
  1287. for (;I != J && Size < MaxArgBytes; ++I)
  1288. {
  1289. if((*I).Pkg.end() == true)
  1290. continue;
  1291. if (I->Op == Item::Configure && disappearedPkgs.find(I->Pkg.FullName(true)) != disappearedPkgs.end())
  1292. continue;
  1293. // We keep this here to allow "smooth" transitions from e.g. multiarch dpkg/ubuntu to dpkg/debian
  1294. if (dpkgMultiArch == false && (I->Pkg.Arch() == nativeArch ||
  1295. strcmp(I->Pkg.Arch(), "all") == 0 ||
  1296. strcmp(I->Pkg.Arch(), "none") == 0))
  1297. {
  1298. char const * const name = I->Pkg.Name();
  1299. ADDARG(name);
  1300. }
  1301. else
  1302. {
  1303. pkgCache::VerIterator PkgVer;
  1304. std::string name = I->Pkg.Name();
  1305. if (Op == Item::Remove || Op == Item::Purge)
  1306. {
  1307. PkgVer = I->Pkg.CurrentVer();
  1308. if(PkgVer.end() == true)
  1309. PkgVer = FindNowVersion(I->Pkg);
  1310. }
  1311. else
  1312. PkgVer = Cache[I->Pkg].InstVerIter(Cache);
  1313. if (strcmp(I->Pkg.Arch(), "none") == 0)
  1314. ; // never arch-qualify a package without an arch
  1315. else if (PkgVer.end() == false)
  1316. name.append(":").append(PkgVer.Arch());
  1317. else
  1318. _error->Warning("Can not find PkgVer for '%s'", name.c_str());
  1319. char * const fullname = strdup(name.c_str());
  1320. Packages.push_back(fullname);
  1321. ADDARG(fullname);
  1322. }
  1323. }
  1324. // skip configure action if all sheduled packages disappeared
  1325. if (oldSize == Size)
  1326. continue;
  1327. }
  1328. #undef ADDARG
  1329. J = I;
  1330. if (_config->FindB("Debug::pkgDPkgPM",false) == true)
  1331. {
  1332. for (std::vector<const char *>::const_iterator a = Args.begin();
  1333. a != Args.end(); ++a)
  1334. clog << *a << ' ';
  1335. clog << endl;
  1336. continue;
  1337. }
  1338. Args.push_back(NULL);
  1339. cout << flush;
  1340. clog << flush;
  1341. cerr << flush;
  1342. /* Mask off sig int/quit. We do this because dpkg also does when
  1343. it forks scripts. What happens is that when you hit ctrl-c it sends
  1344. it to all processes in the group. Since dpkg ignores the signal
  1345. it doesn't die but we do! So we must also ignore it */
  1346. sighandler_t old_SIGQUIT = signal(SIGQUIT,SIG_IGN);
  1347. sighandler_t old_SIGINT = signal(SIGINT,SigINT);
  1348. // Check here for any SIGINT
  1349. if (pkgPackageManager::SigINTStop && (Op == Item::Remove || Op == Item::Purge || Op == Item::Install))
  1350. break;
  1351. // ignore SIGHUP as well (debian #463030)
  1352. sighandler_t old_SIGHUP = signal(SIGHUP,SIG_IGN);
  1353. // now run dpkg
  1354. d->progress->StartDpkg();
  1355. std::set<int> KeepFDs;
  1356. KeepFDs.insert(fd[1]);
  1357. MergeKeepFdsFromConfiguration(KeepFDs);
  1358. pid_t Child = ExecFork(KeepFDs);
  1359. if (Child == 0)
  1360. {
  1361. // This is the child
  1362. SetupSlavePtyMagic();
  1363. close(fd[0]); // close the read end of the pipe
  1364. dpkgChrootDirectory();
  1365. if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
  1366. _exit(100);
  1367. if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
  1368. {
  1369. int Flags;
  1370. int dummy = 0;
  1371. if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
  1372. _exit(100);
  1373. // Discard everything in stdin before forking dpkg
  1374. if (fcntl(STDIN_FILENO,F_SETFL,Flags | O_NONBLOCK) < 0)
  1375. _exit(100);
  1376. while (read(STDIN_FILENO,&dummy,1) == 1);
  1377. if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
  1378. _exit(100);
  1379. }
  1380. /* No Job Control Stop Env is a magic dpkg var that prevents it
  1381. from using sigstop */
  1382. putenv((char *)"DPKG_NO_TSTP=yes");
  1383. execvp(Args[0], (char**) &Args[0]);
  1384. cerr << "Could not exec dpkg!" << endl;
  1385. _exit(100);
  1386. }
  1387. // apply ionice
  1388. if (_config->FindB("DPkg::UseIoNice", false) == true)
  1389. ionice(Child);
  1390. // Wait for dpkg
  1391. int Status = 0;
  1392. // we read from dpkg here
  1393. int const _dpkgin = fd[0];
  1394. close(fd[1]); // close the write end of the pipe
  1395. // setups fds
  1396. sigemptyset(&d->sigmask);
  1397. sigprocmask(SIG_BLOCK,&d->sigmask,&d->original_sigmask);
  1398. /* free vectors (and therefore memory) as we don't need the included data anymore */
  1399. for (std::vector<char *>::const_iterator p = Packages.begin();
  1400. p != Packages.end(); ++p)
  1401. free(*p);
  1402. Packages.clear();
  1403. // the result of the waitpid call
  1404. int res;
  1405. int select_ret;
  1406. while ((res=waitpid(Child,&Status, WNOHANG)) != Child) {
  1407. if(res < 0) {
  1408. // FIXME: move this to a function or something, looks ugly here
  1409. // error handling, waitpid returned -1
  1410. if (errno == EINTR)
  1411. continue;
  1412. RunScripts("DPkg::Post-Invoke");
  1413. // Restore sig int/quit
  1414. signal(SIGQUIT,old_SIGQUIT);
  1415. signal(SIGINT,old_SIGINT);
  1416. signal(SIGHUP,old_SIGHUP);
  1417. return _error->Errno("waitpid","Couldn't wait for subprocess");
  1418. }
  1419. // wait for input or output here
  1420. FD_ZERO(&rfds);
  1421. if (d->master >= 0 && !d->stdin_is_dev_null)
  1422. FD_SET(0, &rfds);
  1423. FD_SET(_dpkgin, &rfds);
  1424. if(d->master >= 0)
  1425. FD_SET(d->master, &rfds);
  1426. tv.tv_sec = 0;
  1427. tv.tv_nsec = d->progress->GetPulseInterval();
  1428. select_ret = pselect(max(d->master, _dpkgin)+1, &rfds, NULL, NULL,
  1429. &tv, &d->original_sigmask);
  1430. if (select_ret < 0 && (errno == EINVAL || errno == ENOSYS))
  1431. select_ret = racy_pselect(max(d->master, _dpkgin)+1, &rfds, NULL,
  1432. NULL, &tv, &d->original_sigmask);
  1433. d->progress->Pulse();
  1434. if (select_ret == 0)
  1435. continue;
  1436. else if (select_ret < 0 && errno == EINTR)
  1437. continue;
  1438. else if (select_ret < 0)
  1439. {
  1440. perror("select() returned error");
  1441. continue;
  1442. }
  1443. if(d->master >= 0 && FD_ISSET(d->master, &rfds))
  1444. DoTerminalPty(d->master);
  1445. if(d->master >= 0 && FD_ISSET(0, &rfds))
  1446. DoStdin(d->master);
  1447. if(FD_ISSET(_dpkgin, &rfds))
  1448. DoDpkgStatusFd(_dpkgin);
  1449. }
  1450. close(_dpkgin);
  1451. // Restore sig int/quit
  1452. signal(SIGQUIT,old_SIGQUIT);
  1453. signal(SIGINT,old_SIGINT);
  1454. signal(SIGHUP,old_SIGHUP);
  1455. // Check for an error code.
  1456. if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
  1457. {
  1458. // if it was set to "keep-dpkg-runing" then we won't return
  1459. // here but keep the loop going and just report it as a error
  1460. // for later
  1461. bool const stopOnError = _config->FindB("Dpkg::StopOnError",true);
  1462. if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
  1463. strprintf(d->dpkg_error, "Sub-process %s received a segmentation fault.",Args[0]);
  1464. else if (WIFEXITED(Status) != 0)
  1465. strprintf(d->dpkg_error, "Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
  1466. else
  1467. strprintf(d->dpkg_error, "Sub-process %s exited unexpectedly",Args[0]);
  1468. _error->Error("%s", d->dpkg_error.c_str());
  1469. if(stopOnError)
  1470. break;
  1471. }
  1472. }
  1473. // dpkg is done at this point
  1474. d->progress->Stop();
  1475. StopPtyMagic();
  1476. CloseLog();
  1477. if (pkgPackageManager::SigINTStop)
  1478. _error->Warning(_("Operation was interrupted before it could finish"));
  1479. if (RunScripts("DPkg::Post-Invoke") == false)
  1480. return false;
  1481. if (_config->FindB("Debug::pkgDPkgPM",false) == false)
  1482. {
  1483. std::string const oldpkgcache = _config->FindFile("Dir::cache::pkgcache");
  1484. if (oldpkgcache.empty() == false && RealFileExists(oldpkgcache) == true &&
  1485. unlink(oldpkgcache.c_str()) == 0)
  1486. {
  1487. std::string const srcpkgcache = _config->FindFile("Dir::cache::srcpkgcache");
  1488. if (srcpkgcache.empty() == false && RealFileExists(srcpkgcache) == true)
  1489. {
  1490. _error->PushToStack();
  1491. pkgCacheFile CacheFile;
  1492. CacheFile.BuildCaches(NULL, true);
  1493. _error->RevertToStack();
  1494. }
  1495. }
  1496. }
  1497. Cache.writeStateFile(NULL);
  1498. return d->dpkg_error.empty();
  1499. }
  1500. void SigINT(int /*sig*/) {
  1501. pkgPackageManager::SigINTStop = true;
  1502. }
  1503. /*}}}*/
  1504. // pkgDpkgPM::Reset - Dump the contents of the command list /*{{{*/
  1505. // ---------------------------------------------------------------------
  1506. /* */
  1507. void pkgDPkgPM::Reset()
  1508. {
  1509. List.erase(List.begin(),List.end());
  1510. }
  1511. /*}}}*/
  1512. // pkgDpkgPM::WriteApportReport - write out error report pkg failure /*{{{*/
  1513. // ---------------------------------------------------------------------
  1514. /* */
  1515. void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
  1516. {
  1517. // If apport doesn't exist or isn't installed do nothing
  1518. // This e.g. prevents messages in 'universes' without apport
  1519. pkgCache::PkgIterator apportPkg = Cache.FindPkg("apport");
  1520. if (apportPkg.end() == true || apportPkg->CurrentVer == 0)
  1521. return;
  1522. string pkgname, reportfile, pkgver, arch;
  1523. string::size_type pos;
  1524. FILE *report;
  1525. if (_config->FindB("Dpkg::ApportFailureReport", true) == false)
  1526. {
  1527. std::clog << "configured to not write apport reports" << std::endl;
  1528. return;
  1529. }
  1530. // only report the first errors
  1531. if(pkgFailures > _config->FindI("APT::Apport::MaxReports", 3))
  1532. {
  1533. std::clog << _("No apport report written because MaxReports is reached already") << std::endl;
  1534. return;
  1535. }
  1536. // check if its not a follow up error
  1537. const char *needle = dgettext("dpkg", "dependency problems - leaving unconfigured");
  1538. if(strstr(errormsg, needle) != NULL) {
  1539. std::clog << _("No apport report written because the error message indicates its a followup error from a previous failure.") << std::endl;
  1540. return;
  1541. }
  1542. // do not report disk-full failures
  1543. if(strstr(errormsg, strerror(ENOSPC)) != NULL) {
  1544. std::clog << _("No apport report written because the error message indicates a disk full error") << std::endl;
  1545. return;
  1546. }
  1547. // do not report out-of-memory failures
  1548. if(strstr(errormsg, strerror(ENOMEM)) != NULL ||
  1549. strstr(errormsg, "failed to allocate memory") != NULL) {
  1550. std::clog << _("No apport report written because the error message indicates a out of memory error") << std::endl;
  1551. return;
  1552. }
  1553. // do not report bugs regarding inaccessible local files
  1554. if(strstr(errormsg, strerror(ENOENT)) != NULL ||
  1555. strstr(errormsg, "cannot access archive") != NULL) {
  1556. std::clog << _("No apport report written because the error message indicates an issue on the local system") << std::endl;
  1557. return;
  1558. }
  1559. // do not report errors encountered when decompressing packages
  1560. if(strstr(errormsg, "--fsys-tarfile returned error exit status 2") != NULL) {
  1561. std::clog << _("No apport report written because the error message indicates an issue on the local system") << std::endl;
  1562. return;
  1563. }
  1564. // do not report dpkg I/O errors, this is a format string, so we compare
  1565. // the prefix and the suffix of the error with the dpkg error message
  1566. vector<string> io_errors;
  1567. io_errors.push_back(string("failed to read"));
  1568. io_errors.push_back(string("failed to write"));
  1569. io_errors.push_back(string("failed to seek"));
  1570. io_errors.push_back(string("unexpected end of file or stream"));
  1571. for (vector<string>::iterator I = io_errors.begin(); I != io_errors.end(); ++I)
  1572. {
  1573. vector<string> list = VectorizeString(dgettext("dpkg", (*I).c_str()), '%');
  1574. if (list.size() > 1) {
  1575. // we need to split %s, VectorizeString only allows char so we need
  1576. // to kill the "s" manually
  1577. if (list[1].size() > 1) {
  1578. list[1].erase(0, 1);
  1579. if(strstr(errormsg, list[0].c_str()) &&
  1580. strstr(errormsg, list[1].c_str())) {
  1581. std::clog << _("No apport report written because the error message indicates a dpkg I/O error") << std::endl;
  1582. return;
  1583. }
  1584. }
  1585. }
  1586. }
  1587. // get the pkgname and reportfile
  1588. pkgname = flNotDir(pkgpath);
  1589. pos = pkgname.find('_');
  1590. if(pos != string::npos)
  1591. pkgname = pkgname.substr(0, pos);
  1592. // find the package versin and source package name
  1593. pkgCache::PkgIterator Pkg = Cache.FindPkg(pkgname);
  1594. if (Pkg.end() == true)
  1595. return;
  1596. pkgCache::VerIterator Ver = Cache.GetCandidateVer(Pkg);
  1597. if (Ver.end() == true)
  1598. return;
  1599. pkgver = Ver.VerStr() == NULL ? "unknown" : Ver.VerStr();
  1600. // if the file exists already, we check:
  1601. // - if it was reported already (touched by apport).
  1602. // If not, we do nothing, otherwise
  1603. // we overwrite it. This is the same behaviour as apport
  1604. // - if we have a report with the same pkgversion already
  1605. // then we skip it
  1606. reportfile = flCombine("/var/crash",pkgname+".0.crash");
  1607. if(FileExists(reportfile))
  1608. {
  1609. struct stat buf;
  1610. char strbuf[255];
  1611. // check atime/mtime
  1612. stat(reportfile.c_str(), &buf);
  1613. if(buf.st_mtime > buf.st_atime)
  1614. return;
  1615. // check if the existing report is the same version
  1616. report = fopen(reportfile.c_str(),"r");
  1617. while(fgets(strbuf, sizeof(strbuf), report) != NULL)
  1618. {
  1619. if(strstr(strbuf,"Package:") == strbuf)
  1620. {
  1621. char pkgname[255], version[255];
  1622. if(sscanf(strbuf, "Package: %254s %254s", pkgname, version) == 2)
  1623. if(strcmp(pkgver.c_str(), version) == 0)
  1624. {
  1625. fclose(report);
  1626. return;
  1627. }
  1628. }
  1629. }
  1630. fclose(report);
  1631. }
  1632. // now write the report
  1633. arch = _config->Find("APT::Architecture");
  1634. report = fopen(reportfile.c_str(),"w");
  1635. if(report == NULL)
  1636. return;
  1637. if(_config->FindB("DPkgPM::InitialReportOnly",false) == true)
  1638. chmod(reportfile.c_str(), 0);
  1639. else
  1640. chmod(reportfile.c_str(), 0600);
  1641. fprintf(report, "ProblemType: Package\n");
  1642. fprintf(report, "Architecture: %s\n", arch.c_str());
  1643. time_t now = time(NULL);
  1644. fprintf(report, "Date: %s" , ctime(&now));
  1645. fprintf(report, "Package: %s %s\n", pkgname.c_str(), pkgver.c_str());
  1646. #if APT_PKG_ABI >= 413
  1647. fprintf(report, "SourcePackage: %s\n", Ver.SourcePkgName());
  1648. #else
  1649. pkgRecords Recs(Cache);
  1650. pkgRecords::Parser &Parse = Recs.Lookup(Ver.FileList());
  1651. std::string srcpkgname = Parse.SourcePkg();
  1652. if(srcpkgname.empty())
  1653. srcpkgname = pkgname;
  1654. fprintf(report, "SourcePackage: %s\n", srcpkgname.c_str());
  1655. #endif
  1656. fprintf(report, "ErrorMessage:\n %s\n", errormsg);
  1657. // ensure that the log is flushed
  1658. if(d->term_out)
  1659. fflush(d->term_out);
  1660. // attach terminal log it if we have it
  1661. string logfile_name = _config->FindFile("Dir::Log::Terminal");
  1662. if (!logfile_name.empty())
  1663. {
  1664. FILE *log = NULL;
  1665. fprintf(report, "DpkgTerminalLog:\n");
  1666. log = fopen(logfile_name.c_str(),"r");
  1667. if(log != NULL)
  1668. {
  1669. char buf[1024];
  1670. while( fgets(buf, sizeof(buf), log) != NULL)
  1671. fprintf(report, " %s", buf);
  1672. fprintf(report, " \n");
  1673. fclose(log);
  1674. }
  1675. }
  1676. // attach history log it if we have it
  1677. string histfile_name = _config->FindFile("Dir::Log::History");
  1678. if (!histfile_name.empty())
  1679. {
  1680. fprintf(report, "DpkgHistoryLog:\n");
  1681. FILE* log = fopen(histfile_name.c_str(),"r");
  1682. if(log != NULL)
  1683. {
  1684. char buf[1024];
  1685. while( fgets(buf, sizeof(buf), log) != NULL)
  1686. fprintf(report, " %s", buf);
  1687. fclose(log);
  1688. }
  1689. }
  1690. // log the ordering
  1691. const char *ops_str[] = {"Install", "Configure","Remove","Purge"};
  1692. fprintf(report, "AptOrdering:\n");
  1693. for (vector<Item>::iterator I = List.begin(); I != List.end(); ++I)
  1694. if ((*I).Pkg != NULL)
  1695. fprintf(report, " %s: %s\n", (*I).Pkg.Name(), ops_str[(*I).Op]);
  1696. else
  1697. fprintf(report, " %s: %s\n", "NULL", ops_str[(*I).Op]);
  1698. // attach dmesg log (to learn about segfaults)
  1699. if (FileExists("/bin/dmesg"))
  1700. {
  1701. fprintf(report, "Dmesg:\n");
  1702. FILE *log = popen("/bin/dmesg","r");
  1703. if(log != NULL)
  1704. {
  1705. char buf[1024];
  1706. while( fgets(buf, sizeof(buf), log) != NULL)
  1707. fprintf(report, " %s", buf);
  1708. pclose(log);
  1709. }
  1710. }
  1711. // attach df -l log (to learn about filesystem status)
  1712. if (FileExists("/bin/df"))
  1713. {
  1714. fprintf(report, "Df:\n");
  1715. FILE *log = popen("/bin/df -l","r");
  1716. if(log != NULL)
  1717. {
  1718. char buf[1024];
  1719. while( fgets(buf, sizeof(buf), log) != NULL)
  1720. fprintf(report, " %s", buf);
  1721. pclose(log);
  1722. }
  1723. }
  1724. fclose(report);
  1725. }
  1726. /*}}}*/