dpkgpm.cc 54 KB

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