dpkgpm.cc 59 KB

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