dpkgpm.cc 58 KB

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