dpkgpm.cc 58 KB

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