fix progress report for upgrade and reinstall
[ntk/apt.git] / apt-pkg / deb / dpkgpm.cc
index b4bfd14..5411d9e 100644 (file)
 // Includes                                                            /*{{{*/
 #include <config.h>
 
-#include <apt-pkg/dpkgpm.h>
-#include <apt-pkg/error.h>
+#include <apt-pkg/cachefile.h>
 #include <apt-pkg/configuration.h>
 #include <apt-pkg/depcache.h>
-#include <apt-pkg/pkgrecords.h>
-#include <apt-pkg/strutl.h>
+#include <apt-pkg/dpkgpm.h>
+#include <apt-pkg/error.h>
 #include <apt-pkg/fileutl.h>
-#include <apt-pkg/cachefile.h>
-#include <apt-pkg/packagemanager.h>
 #include <apt-pkg/install-progress.h>
+#include <apt-pkg/packagemanager.h>
+#include <apt-pkg/pkgrecords.h>
+#include <apt-pkg/strutl.h>
+#include <apt-pkg/cacheiterators.h>
+#include <apt-pkg/macros.h>
+#include <apt-pkg/pkgcache.h>
 
-#include <unistd.h>
-#include <stdlib.h>
+#include <errno.h>
 #include <fcntl.h>
+#include <grp.h>
+#include <pty.h>
+#include <pwd.h>
+#include <signal.h>
+#include <stddef.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/ioctl.h>
 #include <sys/select.h>
 #include <sys/stat.h>
-#include <sys/types.h>
+#include <sys/time.h>
 #include <sys/wait.h>
-#include <signal.h>
-#include <errno.h>
-#include <string.h>
-#include <stdio.h>
-#include <string.h>
-#include <algorithm>
-#include <sstream>
-#include <map>
-#include <pwd.h>
-#include <grp.h>
-#include <iomanip>
-
 #include <termios.h>
+#include <time.h>
 #include <unistd.h>
-#include <sys/ioctl.h>
-#include <pty.h>
+#include <algorithm>
+#include <cstring>
+#include <iostream>
+#include <map>
+#include <set>
+#include <string>
+#include <utility>
+#include <vector>
 
 #include <apti18n.h>
                                                                        /*}}}*/
@@ -394,10 +399,14 @@ bool pkgDPkgPM::SendPkgsInfo(FILE * const F, unsigned int const &Version)
    that are due to be installed. */
 bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf)
 {
+   bool result = true;
+
    Configuration::Item const *Opts = _config->Tree(Cnf);
    if (Opts == 0 || Opts->Child == 0)
       return true;
    Opts = Opts->Child;
+
+   sighandler_t old_sigpipe = signal(SIGPIPE, SIG_IGN);
    
    unsigned int Count = 1;
    for (; Opts != 0; Opts = Opts->Next, Count++)
@@ -405,6 +414,10 @@ bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf)
       if (Opts->Value.empty() == true)
          continue;
 
+      if(_config->FindB("Debug::RunScripts", false) == true)
+         std::clog << "Running external script with list of all .deb file: '"
+                   << Opts->Value << "'" << std::endl;
+
       // Determine the protocol version
       string OptSec = Opts->Value;
       string::size_type Pos;
@@ -419,8 +432,10 @@ bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf)
       std::set<int> KeepFDs;
       MergeKeepFdsFromConfiguration(KeepFDs);
       int Pipes[2];
-      if (pipe(Pipes) != 0)
-        return _error->Errno("pipe","Failed to create IPC pipe to subprocess");
+      if (pipe(Pipes) != 0) {
+         result = _error->Errno("pipe","Failed to create IPC pipe to subprocess");
+         break;
+      }
       if (InfoFD != (unsigned)Pipes[0])
         SetCloseExec(Pipes[0],true);
       else
@@ -454,8 +469,10 @@ bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf)
       }
       close(Pipes[0]);
       FILE *F = fdopen(Pipes[1],"w");
-      if (F == 0)
-        return _error->Errno("fdopen","Faild to open new FD");
+      if (F == 0) {
+         result = _error->Errno("fdopen","Faild to open new FD");
+         break;
+      }
       
       // Feed it the filenames.
       if (Version <= 1)
@@ -483,11 +500,14 @@ bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf)
       fclose(F);
       
       // Clean up the sub process
-      if (ExecWait(Process,Opts->Value.c_str()) == false)
-        return _error->Error("Failure running script %s",Opts->Value.c_str());
+      if (ExecWait(Process,Opts->Value.c_str()) == false) {
+        result = _error->Error("Failure running script %s",Opts->Value.c_str());
+         break;
+      }
    }
+   signal(SIGPIPE, old_sigpipe);
 
-   return true;
+   return result;
 }
                                                                        /*}}}*/
 // DPkgPM::DoStdin - Read stdin and pass to slave pty                  /*{{{*/
@@ -544,8 +564,8 @@ void pkgDPkgPM::ProcessDpkgStatusLine(char *line)
       'status:   <pkg>: <pkg  qstate>'
       'status:   <pkg>:<arch>: <pkg  qstate>'
       
-      'processing: {install,configure,remove,purge,disappear,trigproc}: pkg'
-      'processing: {install,configure,remove,purge,disappear,trigproc}: trigger'
+      'processing: {install,upgrade,configure,remove,purge,disappear,trigproc}: pkg'
+      'processing: {install,upgrade,configure,remove,purge,disappear,trigproc}: trigger'
    */
 
    // we need to split on ": " (note the appended space) as the ':' is
@@ -567,15 +587,17 @@ void pkgDPkgPM::ProcessDpkgStatusLine(char *line)
    std::string prefix = APT::String::Strip(list[0]);
    std::string pkgname;
    std::string action;
-   ostringstream status;
 
    // "processing" has the form "processing: action: pkg or trigger"
-   // with action = ["install", "configure", "remove", "purge", "disappear",
-   //                "trigproc"]
+   // with action = ["install", "upgrade", "configure", "remove", "purge",
+   //                "disappear", "trigproc"]
    if (prefix == "processing")
    {
       pkgname = APT::String::Strip(list[2]);
       action = APT::String::Strip(list[1]);
+      // we don't care for the difference (as dpkg doesn't really either)
+      if (action == "upgrade")
+        action = "install";
    }
    // "status" has the form: "status: pkg: state"
    // with state in ["half-installed", "unpacked", "half-configured", 
@@ -596,21 +618,21 @@ void pkgDPkgPM::ProcessDpkgStatusLine(char *line)
       errors look like this:
       '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 
       and conffile-prompt like this
-      'status: conffile-prompt: conffile : 'current-conffile' 'new-conffile' useredited distedited
+      'status:/etc/compiz.conf/compiz.conf :  conffile-prompt: 'current-conffile' 'new-conffile' useredited distedited
    */
    if (prefix == "status")
    {
       if(action == "error")
       {
-         d->progress->Error(list[1], PackagesDone, PackagesTotal,
+         d->progress->Error(pkgname, PackagesDone, PackagesTotal,
                             list[3]);
          pkgFailures++;
-         WriteApportReport(list[1].c_str(), list[3].c_str());
+         WriteApportReport(pkgname.c_str(), list[3].c_str());
          return;
       }
-      else if(action == "conffile")
+      else if(action == "conffile-prompt")
       {
-         d->progress->ConffilePrompt(list[1], PackagesDone, PackagesTotal,
+         d->progress->ConffilePrompt(pkgname, PackagesDone, PackagesTotal,
                                      list[3]);
          return;
       }
@@ -619,27 +641,26 @@ void pkgDPkgPM::ProcessDpkgStatusLine(char *line)
    // at this point we know that we should have a valid pkgname, so build all 
    // the info from it
 
-   // dpkg does not send always send "pkgname:arch" so we add it here 
-   // if needed
+   // dpkg does not always send "pkgname:arch" so we add it here if needed
    if (pkgname.find(":") == std::string::npos)
    {
-      // find the package in the group that is in a touched by dpkg
-      // if there are multiple dpkg will send us a full pkgname:arch
+      // find the package in the group that is touched by dpkg
+      // if there are multiple pkgs dpkg would send us a full pkgname:arch
       pkgCache::GrpIterator Grp = Cache.FindGrp(pkgname);
-      if (Grp.end() == false) 
+      if (Grp.end() == false)
       {
-          pkgCache::PkgIterator P = Grp.PackageList();
-          for (; P.end() != true; P = Grp.NextPkg(P))
-          {
-              if(Cache[P].Mode != pkgDepCache::ModeKeep)
-              {
-                  pkgname = P.FullName();
-                  break;
-              }
-          }
+        pkgCache::PkgIterator P = Grp.PackageList();
+        for (; P.end() != true; P = Grp.NextPkg(P))
+        {
+           if(Cache[P].Keep() == false || Cache[P].ReInstall() == true)
+           {
+              pkgname = P.FullName();
+              break;
+           }
+        }
       }
    }
-   
+
    const char* const pkg = pkgname.c_str();
    std::string short_pkgname = StringSplit(pkgname, ":")[0];
    std::string arch = "";
@@ -678,28 +699,29 @@ void pkgDPkgPM::ProcessDpkgStatusLine(char *line)
    if (prefix == "status")
    {
       vector<struct DpkgState> const &states = PackageOps[pkg];
-      const char *next_action = NULL;
       if(PackageOpsDone[pkg] < states.size())
-         next_action = states[PackageOpsDone[pkg]].state;
-      // check if the package moved to the next dpkg state
-      if(next_action && (action == next_action))
       {
-         // only read the translation if there is actually a next
-         // action
-         const char *translation = _(states[PackageOpsDone[pkg]].str);
-         std::string msg;
-
-         // we moved from one dpkg state to a new one, report that
-         PackageOpsDone[pkg]++;
-         PackagesDone++;
-
-         strprintf(msg, translation, i18n_pkgname.c_str());
-         d->progress->StatusChanged(pkgname, PackagesDone, PackagesTotal, msg);
-         
+         char const * const next_action = states[PackageOpsDone[pkg]].state;
+        if (next_action && Debug == true)
+           std::clog << "(parsed from dpkg) pkg: " << short_pkgname
+              << " action: " << action << " (expected: '" << next_action << "' "
+              << PackageOpsDone[pkg] << " of " << states.size() << ")" << endl;
+
+        // check if the package moved to the next dpkg state
+        if(next_action && (action == next_action))
+        {
+           // only read the translation if there is actually a next action
+           char const * const translation = _(states[PackageOpsDone[pkg]].str);
+
+           // we moved from one dpkg state to a new one, report that
+           ++PackageOpsDone[pkg];
+           ++PackagesDone;
+
+           std::string msg;
+           strprintf(msg, translation, i18n_pkgname.c_str());
+           d->progress->StatusChanged(pkgname, PackagesDone, PackagesTotal, msg);
+        }
       }
-      if (Debug == true) 
-         std::clog << "(parsed from dpkg) pkg: " << short_pkgname
-                   << " action: " << action << endl;
    }
 }
                                                                        /*}}}*/
@@ -1027,16 +1049,25 @@ bool pkgDPkgPM::Go(int StatusFd)
 
 void pkgDPkgPM::StartPtyMagic()
 {
+   if (_config->FindB("Dpkg::Use-Pty", true) == false)
+   {
+      d->master = d->slave = -1;
+      return;
+   }
+
    // setup the pty and stuff
-   struct      winsize win;
+   struct winsize win;
 
-   // if tcgetattr does not return zero there was a error
-   // and we do not do any pty magic
+   // if tcgetattr for both stdin/stdout returns 0 (no error)
+   // we do the pty magic
    _error->PushToStack();
-   if (tcgetattr(STDOUT_FILENO, &d->tt) == 0)
+   if (tcgetattr(STDIN_FILENO, &d->tt) == 0 &&
+       tcgetattr(STDOUT_FILENO, &d->tt) == 0)
    {
-       ioctl(1, TIOCGWINSZ, (char *)&win);
-       if (openpty(&d->master, &d->slave, NULL, &d->tt, &win) < 0)
+       if (ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&win) < 0)
+       {
+           _error->Errno("ioctl", _("ioctl(TIOCGWINSZ) failed"));
+       } else if (openpty(&d->master, &d->slave, NULL, &d->tt, &win) < 0)
        {
            _error->Errno("openpty", _("Can not write log (%s)"), _("Is /dev/pts mounted?"));
            d->master = d->slave = -1;
@@ -1182,7 +1213,7 @@ bool pkgDPkgPM::GoNoABIBreak(APT::Progress::PackageManager *progress)
    StartPtyMagic();
 
    // Tell the progress that its starting and fork dpkg 
-   d->progress->Start();
+   d->progress->Start(d->master);
 
    // this loop is runs once per dpkg operation
    vector<Item>::const_iterator I = List.begin();
@@ -1389,12 +1420,17 @@ bool pkgDPkgPM::GoNoABIBreak(APT::Progress::PackageManager *progress)
         if(d->slave >= 0 && d->master >= 0) 
         {
            setsid();
-           ioctl(d->slave, TIOCSCTTY, 0);
-           close(d->master);
-           dup2(d->slave, 0);
-           dup2(d->slave, 1);
-           dup2(d->slave, 2);
-           close(d->slave);
+           int res = ioctl(d->slave, TIOCSCTTY, 0);
+            if (res < 0) {
+               std::cerr << "ioctl(TIOCSCTTY) failed for fd: " 
+                         << d->slave << std::endl;
+            } else {
+               close(d->master);
+               dup2(d->slave, 0);
+               dup2(d->slave, 1);
+               dup2(d->slave, 2);
+               close(d->slave);
+            }
         }
         close(fd[0]); // close the read end of the pipe
 
@@ -1405,7 +1441,8 @@ bool pkgDPkgPM::GoNoABIBreak(APT::Progress::PackageManager *progress)
 
         if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
         {
-           int Flags,dummy;
+           int Flags;
+            int dummy = 0;
            if ((Flags = fcntl(STDIN_FILENO,F_GETFL,dummy)) < 0)
               _exit(100);
            
@@ -1513,28 +1550,18 @@ bool pkgDPkgPM::GoNoABIBreak(APT::Progress::PackageManager *progress)
         // here but keep the loop going and just report it as a error
         // for later
         bool const stopOnError = _config->FindB("Dpkg::StopOnError",true);
-        
-        if(stopOnError)
-           RunScripts("DPkg::Post-Invoke");
 
-        if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV) 
+        if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
            strprintf(d->dpkg_error, "Sub-process %s received a segmentation fault.",Args[0]);
         else if (WIFEXITED(Status) != 0)
            strprintf(d->dpkg_error, "Sub-process %s returned an error code (%u)",Args[0],WEXITSTATUS(Status));
-        else 
+        else
            strprintf(d->dpkg_error, "Sub-process %s exited unexpectedly",Args[0]);
+        _error->Error("%s", d->dpkg_error.c_str());
 
-        if(d->dpkg_error.size() > 0)
-           _error->Error("%s", d->dpkg_error.c_str());
-
-        if(stopOnError) 
-        {
-           CloseLog();
-            StopPtyMagic();
-            d->progress->Stop();
-           return false;
-        }
-      }      
+        if(stopOnError)
+           break;
+      }
    }
    // dpkg is done at this point
    d->progress->Stop();
@@ -1565,10 +1592,10 @@ bool pkgDPkgPM::GoNoABIBreak(APT::Progress::PackageManager *progress)
    }
 
    Cache.writeStateFile(NULL);
-   return true;
+   return d->dpkg_error.empty();
 }
 
-void SigINT(int sig) {
+void SigINT(int /*sig*/) {
    pkgPackageManager::SigINTStop = true;
 }
                                                                        /*}}}*/
@@ -1595,7 +1622,7 @@ void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
    string::size_type pos;
    FILE *report;
 
-   if (_config->FindB("Dpkg::ApportFailureReport", false) == false)
+   if (_config->FindB("Dpkg::ApportFailureReport", true) == false)
    {
       std::clog << "configured to not write apport reports" << std::endl;
       return;
@@ -1644,11 +1671,12 @@ void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
    // do not report dpkg I/O errors, this is a format string, so we compare
    // the prefix and the suffix of the error with the dpkg error message
    vector<string> io_errors;
-   io_errors.push_back(string("failed to read on buffer copy for %s"));
-   io_errors.push_back(string("failed in write on buffer copy for %s"));
-   io_errors.push_back(string("short read on buffer copy for %s"));
+   io_errors.push_back(string("failed to read"));
+   io_errors.push_back(string("failed to write"));
+   io_errors.push_back(string("failed to seek"));
+   io_errors.push_back(string("unexpected end of file or stream"));
 
-   for (vector<string>::iterator I = io_errors.begin(); I != io_errors.end(); I++)
+   for (vector<string>::iterator I = io_errors.begin(); I != io_errors.end(); ++I)
    {
       vector<string> list = VectorizeString(dgettext("dpkg", (*I).c_str()), '%');
       if (list.size() > 1) {
@@ -1763,13 +1791,11 @@ void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
    string histfile_name = _config->FindFile("Dir::Log::History");
    if (!histfile_name.empty())
    {
-      FILE *log = NULL;
-      char buf[1024];
-
       fprintf(report, "DpkgHistoryLog:\n");
-      log = fopen(histfile_name.c_str(),"r");
+      FILE* log = fopen(histfile_name.c_str(),"r");
       if(log != NULL)
       {
+        char buf[1024];
         while( fgets(buf, sizeof(buf), log) != NULL)
            fprintf(report, " %s", buf);
         fclose(log);