apt-pkg/deb/dpkgpm.cc: fix off-by-one in SetupTerminalScrollArea reset
[ntk/apt.git] / apt-pkg / deb / dpkgpm.cc
index 51e896a..b4d812d 100644 (file)
@@ -37,6 +37,7 @@
 #include <map>
 #include <pwd.h>
 #include <grp.h>
+#include <iomanip>
 
 #include <termios.h>
 #include <unistd.h>
@@ -51,8 +52,17 @@ using namespace std;
 class pkgDPkgPMPrivate 
 {
 public:
-   pkgDPkgPMPrivate() : dpkgbuf_pos(0), term_out(NULL), history_out(NULL)
+   pkgDPkgPMPrivate() : stdin_is_dev_null(false), dpkgbuf_pos(0),
+                       term_out(NULL), history_out(NULL), 
+                        last_reported_progress(0.0), nr_terminal_rows(0),
+                        fancy_progress_output(false)
    {
+      dpkgbuf[0] = '\0';
+      if(_config->FindB("Dpkg::Progress-Fancy", false) == true)
+      {
+         fancy_progress_output = true;
+         _config->Set("DpkgPM::Progress", true);
+      }
    }
    bool stdin_is_dev_null;
    // the buffer we use for the dpkg status-fd reading
@@ -61,6 +71,10 @@ public:
    FILE *term_out;
    FILE *history_out;
    string dpkg_error;
+
+   float last_reported_progress;
+   int nr_terminal_rows;
+   bool fancy_progress_output;
 };
 
 namespace
@@ -132,6 +146,35 @@ static void dpkgChrootDirectory()
    std::cerr << "Chrooting into " << chrootDir << std::endl;
    if (chroot(chrootDir.c_str()) != 0)
       _exit(100);
+   if (chdir("/") != 0)
+      _exit(100);
+}
+                                                                       /*}}}*/
+
+
+// FindNowVersion - Helper to find a Version in "now" state    /*{{{*/
+// ---------------------------------------------------------------------
+/* This is helpful when a package is no longer installed but has residual 
+ * config files
+ */
+static 
+pkgCache::VerIterator FindNowVersion(const pkgCache::PkgIterator &Pkg)
+{
+   pkgCache::VerIterator Ver;
+   for (Ver = Pkg.VersionList(); Ver.end() == false; ++Ver)
+   {
+      pkgCache::VerFileIterator Vf = Ver.FileList();
+      pkgCache::PkgFileIterator F = Vf.File();
+      for (F = Vf.File(); F.end() == false; ++F)
+      {
+         if (F && F.Archive())
+         {
+            if (strcmp(F.Archive(), "now")) 
+               return Ver;
+         }
+      }
+   }
+   return Ver;
 }
                                                                        /*}}}*/
 
@@ -158,7 +201,7 @@ pkgDPkgPM::~pkgDPkgPM()
 bool pkgDPkgPM::Install(PkgIterator Pkg,string File)
 {
    if (File.empty() == true || Pkg.end() == true)
-      return _error->Error("Internal Error, No file name for %s",Pkg.Name());
+      return _error->Error("Internal Error, No file name for %s",Pkg.FullName().c_str());
 
    // If the filename string begins with DPkg::Chroot-Directory, return the
    // substr that is within the chroot so dpkg can access it.
@@ -209,15 +252,23 @@ bool pkgDPkgPM::Remove(PkgIterator Pkg,bool Purge)
    return true;
 }
                                                                        /*}}}*/
-// DPkgPM::SendV2Pkgs - Send version 2 package info                    /*{{{*/
+// DPkgPM::SendPkgInfo - Send info for install-pkgs hook               /*{{{*/
 // ---------------------------------------------------------------------
 /* This is part of the helper script communication interface, it sends
    very complete information down to the other end of the pipe.*/
 bool pkgDPkgPM::SendV2Pkgs(FILE *F)
 {
-   fprintf(F,"VERSION 2\n");
-   
-   /* Write out all of the configuration directives by walking the 
+   return SendPkgsInfo(F, 2);
+}
+bool pkgDPkgPM::SendPkgsInfo(FILE * const F, unsigned int const &Version)
+{
+   // This version of APT supports only v3, so don't sent higher versions
+   if (Version <= 3)
+      fprintf(F,"VERSION %u\n", Version);
+   else
+      fprintf(F,"VERSION 3\n");
+
+   /* Write out all of the configuration directives by walking the
       configuration tree */
    const Configuration::Item *Top = _config->Tree(0);
    for (; Top != 0;)
@@ -251,30 +302,51 @@ bool pkgDPkgPM::SendV2Pkgs(FILE *F)
       pkgDepCache::StateCache &S = Cache[I->Pkg];
       
       fprintf(F,"%s ",I->Pkg.Name());
-      // Current version
-      if (I->Pkg->CurrentVer == 0)
-        fprintf(F,"- ");
+
+      // Current version which we are going to replace
+      pkgCache::VerIterator CurVer = I->Pkg.CurrentVer();
+      if (CurVer.end() == true && (I->Op == Item::Remove || I->Op == Item::Purge))
+        CurVer = FindNowVersion(I->Pkg);
+
+      if (CurVer.end() == true)
+      {
+        if (Version <= 2)
+           fprintf(F, "- ");
+        else
+           fprintf(F, "- - none ");
+      }
       else
-        fprintf(F,"%s ",I->Pkg.CurrentVer().VerStr());
-      
-      // Show the compare operator
-      // Target version
+      {
+        fprintf(F, "%s ", CurVer.VerStr());
+        if (Version >= 3)
+           fprintf(F, "%s %s ", CurVer.Arch(), CurVer.MultiArchType());
+      }
+
+      // Show the compare operator between current and install version
       if (S.InstallVer != 0)
       {
+        pkgCache::VerIterator const InstVer = S.InstVerIter(Cache);
         int Comp = 2;
-        if (I->Pkg->CurrentVer != 0)
-           Comp = S.InstVerIter(Cache).CompareVer(I->Pkg.CurrentVer());
+        if (CurVer.end() == false)
+           Comp = InstVer.CompareVer(CurVer);
         if (Comp < 0)
            fprintf(F,"> ");
-        if (Comp == 0)
+        else if (Comp == 0)
            fprintf(F,"= ");
-        if (Comp > 0)
+        else if (Comp > 0)
            fprintf(F,"< ");
-        fprintf(F,"%s ",S.InstVerIter(Cache).VerStr());
+        fprintf(F, "%s ", InstVer.VerStr());
+        if (Version >= 3)
+           fprintf(F, "%s %s ", InstVer.Arch(), InstVer.MultiArchType());
       }
       else
-        fprintf(F,"> - ");
-      
+      {
+        if (Version <= 2)
+           fprintf(F, "> - ");
+        else
+           fprintf(F, "> - - none ");
+      }
+
       // Show the filename/operation
       if (I->Op == Item::Install)
       {
@@ -284,9 +356,9 @@ bool pkgDPkgPM::SendV2Pkgs(FILE *F)
         else
            fprintf(F,"%s\n",I->File.c_str());
       }      
-      if (I->Op == Item::Configure)
+      else if (I->Op == Item::Configure)
         fprintf(F,"**CONFIGURE**\n");
-      if (I->Op == Item::Remove ||
+      else if (I->Op == Item::Remove ||
          I->Op == Item::Purge)
         fprintf(F,"**REMOVE**\n");
       
@@ -322,24 +394,32 @@ bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf)
       OptSec = "DPkg::Tools::Options::" + string(Opts->Value.c_str(),Pos);
       
       unsigned int Version = _config->FindI(OptSec+"::Version",1);
+      unsigned int InfoFD = _config->FindI(OptSec + "::InfoFD", STDIN_FILENO);
       
       // Create the pipes
       int Pipes[2];
       if (pipe(Pipes) != 0)
         return _error->Errno("pipe","Failed to create IPC pipe to subprocess");
-      SetCloseExec(Pipes[0],true);
+      if (InfoFD != (unsigned)Pipes[0])
+        SetCloseExec(Pipes[0],true);
+      else
+        _config->Set("APT::Keep-Fds::", Pipes[0]);
       SetCloseExec(Pipes[1],true);
-      
+
       // Purified Fork for running the script
-      pid_t Process = ExecFork();      
+      pid_t Process = ExecFork();
       if (Process == 0)
       {
         // Setup the FDs
-        dup2(Pipes[0],STDIN_FILENO);
+        dup2(Pipes[0], InfoFD);
         SetCloseExec(STDOUT_FILENO,false);
-        SetCloseExec(STDIN_FILENO,false);      
+        SetCloseExec(STDIN_FILENO,false);
         SetCloseExec(STDERR_FILENO,false);
 
+        string hookfd;
+        strprintf(hookfd, "%d", InfoFD);
+        setenv("APT_HOOK_INFO_FD", hookfd.c_str(), 1);
+
         dpkgChrootDirectory();
         const char *Args[4];
         Args[0] = "/bin/sh";
@@ -349,6 +429,8 @@ bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf)
         execv(Args[0],(char **)Args);
         _exit(100);
       }
+      if (InfoFD == (unsigned)Pipes[0])
+        _config->Clear("APT::Keep-Fds", Pipes[0]);
       close(Pipes[0]);
       FILE *F = fdopen(Pipes[1],"w");
       if (F == 0)
@@ -375,7 +457,7 @@ bool pkgDPkgPM::RunScriptsWithPkgs(const char *Cnf)
         }
       }
       else
-        SendV2Pkgs(F);
+        SendPkgsInfo(F, Version);
 
       fclose(F);
       
@@ -396,7 +478,7 @@ void pkgDPkgPM::DoStdin(int master)
    unsigned char input_buf[256] = {0,}; 
    ssize_t len = read(0, input_buf, sizeof(input_buf));
    if (len)
-      write(master, input_buf, len);
+      FileFd::Write(master, input_buf, len);
    else
       d->stdin_is_dev_null = true;
 }
@@ -422,7 +504,7 @@ void pkgDPkgPM::DoTerminalPty(int master)
    }  
    if(len <= 0) 
       return;
-   write(1, term_buf, len);
+   FileFd::Write(1, term_buf, len);
    if(d->term_out)
       fwrite(term_buf, len, sizeof(char), d->term_out);
 }
@@ -442,7 +524,8 @@ void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd, char *line)
 
 
    /* dpkg sends strings like this:
-      'status:   <pkg>:  <pkg  qstate>'
+      'status:   <pkg>: <pkg  qstate>'
+      'status:   <pkg>:<arch>: <pkg  qstate>'
       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
@@ -457,29 +540,36 @@ void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd, char *line)
       'processing: trigproc: trigger'
            
    */
-   char* list[6];
-   //        dpkg sends multiline error messages sometimes (see
-   //        #374195 for a example. we should support this by
-   //        either patching dpkg to not send multiline over the
-   //        statusfd or by rewriting the code here to deal with
-   //        it. for now we just ignore it and not crash
-   TokSplitString(':', line, list, sizeof(list)/sizeof(list[0]));
-   if( list[0] == NULL || list[1] == NULL || list[2] == NULL) 
+   // we need to split on ": " (note the appended space) as the ':' is
+   // part of the pkgname:arch information that dpkg sends
+   // 
+   // A dpkg error message may contain additional ":" (like
+   //  "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
+   // so we need to ensure to not split too much
+   std::vector<std::string> list = StringSplit(line, ": ", 3);
+   if(list.size() != 3)
    {
       if (Debug == true)
         std::clog << "ignoring line: not enough ':'" << std::endl;
       return;
    }
-   const char* const pkg = list[1];
-   const char* action = _strstrip(list[2]);
+   // dpkg does not send always send "pkgname:arch" so we add it here if needed
+   std::string pkgname = list[1];
+   if (pkgname.find(":") == std::string::npos)
+   {
+      string const nativeArch = _config->Find("APT::Architecture");
+      pkgname = pkgname + ":" + nativeArch;
+   }
+   const char* const pkg = pkgname.c_str();
+   const char* action = list[2].c_str();
 
    // 'processing' from dpkg looks like
    // 'processing: action: pkg'
-   if(strncmp(list[0], "processing", strlen("processing")) == 0)
+   if(strncmp(list[0].c_str(), "processing", strlen("processing")) == 0)
    {
       char s[200];
-      const char* const pkg_or_trigger = _strstrip(list[2]);
-      action = _strstrip( list[1]);
+      const char* const pkg_or_trigger = list[2].c_str();
+      action =  list[1].c_str();
       const std::pair<const char *, const char *> * const iter =
        std::find_if(PackageProcessingOpsBegin,
                     PackageProcessingOpsEnd,
@@ -497,7 +587,7 @@ void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd, char *line)
             << ":" << s
             << endl;
       if(OutStatusFd > 0)
-        write(OutStatusFd, status.str().c_str(), status.str().size());
+        FileFd::Write(OutStatusFd, status.str().c_str(), status.str().size());
       if (Debug == true)
         std::clog << "send: '" << status.str() << "'" << endl;
 
@@ -508,24 +598,16 @@ void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd, char *line)
 
    if(strncmp(action,"error",strlen("error")) == 0)
    {
-      // urgs, sometime has ":" in its error string so that we
-      // end up with the error message split between list[3]
-      // and list[4], e.g. the message: 
-      // "failed in buffer_write(fd) (10, ret=-1): backend dpkg-deb ..."
-      // concat them again
-      if( list[4] != NULL )
-        list[3][strlen(list[3])] = ':';
-
       status << "pmerror:" << list[1]
             << ":"  << (PackagesDone/float(PackagesTotal)*100.0) 
             << ":" << list[3]
             << endl;
       if(OutStatusFd > 0)
-        write(OutStatusFd, status.str().c_str(), status.str().size());
+        FileFd::Write(OutStatusFd, status.str().c_str(), status.str().size());
       if (Debug == true)
         std::clog << "send: '" << status.str() << "'" << endl;
       pkgFailures++;
-      WriteApportReport(list[1], list[3]);
+      WriteApportReport(list[1].c_str(), list[3].c_str());
       return;
    }
    else if(strncmp(action,"conffile",strlen("conffile")) == 0)
@@ -535,7 +617,7 @@ void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd, char *line)
             << ":" << list[3]
             << endl;
       if(OutStatusFd > 0)
-        write(OutStatusFd, status.str().c_str(), status.str().size());
+        FileFd::Write(OutStatusFd, status.str().c_str(), status.str().size());
       if (Debug == true)
         std::clog << "send: '" << status.str() << "'" << endl;
       return;
@@ -562,8 +644,11 @@ void pkgDPkgPM::ProcessDpkgStatusLine(int OutStatusFd, char *line)
             << ":"  << (PackagesDone/float(PackagesTotal)*100.0) 
             << ":" << s
             << endl;
+      if(_config->FindB("DPkgPM::Progress", false) == true)
+         SendTerminalProgress(PackagesDone/float(PackagesTotal)*100.0);
+
       if(OutStatusFd > 0)
-        write(OutStatusFd, status.str().c_str(), status.str().size());
+        FileFd::Write(OutStatusFd, status.str().c_str(), status.str().size());
       if (Debug == true)
         std::clog << "send: '" << status.str() << "'" << endl;
    }
@@ -691,13 +776,15 @@ bool pkgDPkgPM::OpenLog()
         return _error->WarningE("OpenLog", _("Could not open file '%s'"), logfile_name.c_str());
       setvbuf(d->term_out, NULL, _IONBF, 0);
       SetCloseExec(fileno(d->term_out), true);
-      struct passwd *pw;
-      struct group *gr;
-      pw = getpwnam("root");
-      gr = getgrnam("adm");
-      if (pw != NULL && gr != NULL)
-         chown(logfile_name.c_str(), pw->pw_uid, gr->gr_gid);
-      chmod(logfile_name.c_str(), 0644);
+      if (getuid() == 0) // if we aren't root, we can't chown a file, so don't try it
+      {
+        struct passwd *pw = getpwnam("root");
+        struct group *gr = getgrnam("adm");
+        if (pw != NULL && gr != NULL && chown(logfile_name.c_str(), pw->pw_uid, gr->gr_gid) != 0)
+           _error->WarningE("OpenLog", "chown to root:adm of file %s failed", logfile_name.c_str());
+      }
+      if (chmod(logfile_name.c_str(), 0640) != 0)
+        _error->WarningE("OpenLog", "chmod 0640 of file %s failed", logfile_name.c_str());
       fprintf(d->term_out, "\nLog started: %s\n", timestr);
    }
 
@@ -709,6 +796,7 @@ bool pkgDPkgPM::OpenLog()
       d->history_out = fopen(history_name.c_str(),"a");
       if (d->history_out == NULL)
         return _error->WarningE("OpenLog", _("Could not open file '%s'"), history_name.c_str());
+      SetCloseExec(fileno(d->history_out), true);
       chmod(history_name.c_str(), 0644);
       fprintf(d->history_out, "\nStart-Date: %s\n", timestr);
       string remove, purge, install, reinstall, upgrade, downgrade;
@@ -801,6 +889,51 @@ bool pkgDPkgPM::CloseLog()
    return true;
 }
                                                                        /*}}}*/
+// DPkgPM::SendTerminalProgress                                        /*{{{*/
+// ---------------------------------------------------------------------
+/* Send progress info to the terminal
+ */
+void pkgDPkgPM::SendTerminalProgress(float percentage)
+{
+   int reporting_steps = _config->FindI("DpkgPM::Reporting-Steps", 1);
+
+   if(percentage < (d->last_reported_progress + reporting_steps))
+      return;
+
+   std::string progress_str;
+   strprintf(progress_str, "Progress: [%3i%%]", (int)percentage);
+   if (d->fancy_progress_output)
+   {
+         int row = d->nr_terminal_rows;
+
+         static string save_cursor = "\033[s";
+         static string restore_cursor = "\033[u";
+
+         static string set_bg_color = "\033[42m"; // green
+         static string set_fg_color = "\033[30m"; // black
+
+         static string restore_bg =  "\033[49m";
+         static string restore_fg = "\033[39m";
+
+         std::cout << save_cursor
+            // move cursor position to last row
+                   << "\033[" << row << ";0f" 
+                   << set_bg_color
+                   << set_fg_color
+                   << progress_str
+                   << restore_cursor
+                   << restore_bg
+                   << restore_fg;
+   }
+   else
+   {
+         std::cout << progress_str << "\r\n";
+   }
+   std::flush(std::cout);
+                   
+   d->last_reported_progress = percentage;
+}
+                                                                       /*}}}*/
 /*{{{*/
 // This implements a racy version of pselect for those architectures
 // that don't have a working implementation.
@@ -822,6 +955,29 @@ static int racy_pselect(int nfds, fd_set *readfds, fd_set *writefds,
    return retval;
 }
 /*}}}*/
+
+void pkgDPkgPM::SetupTerminalScrollArea(int nr_rows)
+{
+     if(!d->fancy_progress_output)
+        return;
+
+     // scroll down a bit to avoid visual glitch when the screen
+     // area shrinks by one row
+     std::cout << "\n";
+         
+     // save cursor
+     std::cout << "\033[s";
+         
+     // set scroll region (this will place the cursor in the top left)
+     std::cout << "\033[1;" << nr_rows - 1 << "r";
+            
+     // restore cursor but ensure its inside the scrolling area
+     std::cout << "\033[u";
+     static const char *move_cursor_up = "\033[1A";
+     std::cout << move_cursor_up;
+     std::flush(std::cout);
+}
+
 // DPkgPM::Go - Run the sequence                                       /*{{{*/
 // ---------------------------------------------------------------------
 /* This globs the operations and calls dpkg 
@@ -833,6 +989,8 @@ static int racy_pselect(int nfds, fd_set *readfds, fd_set *writefds,
 */
 bool pkgDPkgPM::Go(int OutStatusFd)
 {
+   pkgPackageManager::SigINTStop = false;
+
    // Generate the base argument list for dpkg
    std::vector<const char *> Args;
    unsigned long StartSize = 0;
@@ -878,7 +1036,7 @@ bool pkgDPkgPM::Go(int OutStatusFd)
       dup2(nullfd, STDIN_FILENO);
       dup2(nullfd, STDOUT_FILENO);
       dup2(nullfd, STDERR_FILENO);
-      execv(Args[0], (char**) &Args[0]);
+      execvp(Args[0], (char**) &Args[0]);
       _error->WarningE("dpkgGo", "Can't detect if dpkg supports multi-arch!");
       _exit(2);
    }
@@ -945,7 +1103,7 @@ bool pkgDPkgPM::Go(int OutStatusFd)
       if((*I).Pkg.end() == true)
         continue;
 
-      string const name = (*I).Pkg.Name();
+      string const name = (*I).Pkg.FullName();
       PackageOpsDone[name] = 0;
       for(int i=0; (DpkgStatesOpMap[(*I).Op][i]).state != NULL; ++i)
       {
@@ -1024,7 +1182,8 @@ bool pkgDPkgPM::Go(int OutStatusFd)
       }
 
       int fd[2];
-      pipe(fd);
+      if (pipe(fd) != 0)
+        return _error->Errno("pipe","Failed to create IPC pipe to dpkg");
 
 #define ADDARG(X) Args.push_back(X); Size += strlen(X)
 #define ADDARGC(X) Args.push_back(X); Size += sizeof(X) - 1
@@ -1098,7 +1257,9 @@ bool pkgDPkgPM::Go(int OutStatusFd)
            if (I->Op == Item::Configure && disappearedPkgs.find(I->Pkg.Name()) != disappearedPkgs.end())
               continue;
            // We keep this here to allow "smooth" transitions from e.g. multiarch dpkg/ubuntu to dpkg/debian
-           if (dpkgMultiArch == false && (I->Pkg.Arch() == nativeArch || !strcmp(I->Pkg.Arch(), "all")))
+           if (dpkgMultiArch == false && (I->Pkg.Arch() == nativeArch ||
+                                          strcmp(I->Pkg.Arch(), "all") == 0 ||
+                                          strcmp(I->Pkg.Arch(), "none") == 0))
            {
               char const * const name = I->Pkg.Name();
               ADDARG(name);
@@ -1107,11 +1268,20 @@ bool pkgDPkgPM::Go(int OutStatusFd)
            {
               pkgCache::VerIterator PkgVer;
               std::string name = I->Pkg.Name();
-              if (Op == Item::Remove || Op == Item::Purge)
+              if (Op == Item::Remove || Op == Item::Purge) 
+               {
                  PkgVer = I->Pkg.CurrentVer();
+                  if(PkgVer.end() == true)
+                     PkgVer = FindNowVersion(I->Pkg);
+               }
               else
                  PkgVer = Cache[I->Pkg].InstVerIter(Cache);
-              name.append(":").append(PkgVer.Arch());
+              if (strcmp(I->Pkg.Arch(), "none") == 0)
+                 ; // never arch-qualify a package without an arch
+              else if (PkgVer.end() == false)
+                  name.append(":").append(PkgVer.Arch());
+               else
+                  _error->Warning("Can not find PkgVer for '%s'", name.c_str());
               char * const fullname = strdup(name.c_str());
               Packages.push_back(fullname);
               ADDARG(fullname);
@@ -1161,16 +1331,14 @@ bool pkgDPkgPM::Go(int OutStatusFd)
 
       // if tcgetattr does not return zero there was a error
       // and we do not do any pty magic
-      if (tcgetattr(0, &tt) == 0)
+      _error->PushToStack();
+      if (tcgetattr(STDOUT_FILENO, &tt) == 0)
       {
-        ioctl(0, TIOCGWINSZ, (char *)&win);
-        if (openpty(&master, &slave, NULL, &tt, &win) < 0) 
+        ioctl(1, TIOCGWINSZ, (char *)&win);
+         d->nr_terminal_rows = win.ws_row;
+        if (openpty(&master, &slave, NULL, &tt, &win) < 0)
         {
-           const char *s = _("Can not write log, openpty() "
-                             "failed (/dev/pts not mounted?)\n");
-           fprintf(stderr, "%s",s);
-            if(d->term_out)
-              fprintf(d->term_out, "%s",s);
+           _error->Errno("openpty", _("Can not write log (%s)"), _("Is /dev/pts mounted?"));
            master = slave = -1;
         }  else {
            struct termios rtt;
@@ -1188,6 +1356,15 @@ bool pkgDPkgPM::Go(int OutStatusFd)
            sigprocmask(SIG_SETMASK, &original_sigmask, 0);
         }
       }
+      // complain only if stdout is either a terminal (but still failed) or is an invalid
+      // descriptor otherwise we would complain about redirection to e.g. /dev/null as well.
+      else if (isatty(STDOUT_FILENO) == 1 || errno == EBADF)
+         _error->Errno("tcgetattr", _("Can not write log (%s)"), _("Is stdout a terminal?"));
+
+      if (_error->PendingError() == true)
+        _error->DumpErrors(std::cerr);
+      _error->RevertToStack();
+
        // Fork dpkg
       pid_t Child;
       _config->Set("APT::Keep-Fds::",fd[1]);
@@ -1198,13 +1375,14 @@ bool pkgDPkgPM::Go(int OutStatusFd)
                << (PackagesDone/float(PackagesTotal)*100.0) 
                << ":" << _("Running dpkg")
                << endl;
-        write(OutStatusFd, status.str().c_str(), status.str().size());
+        FileFd::Write(OutStatusFd, status.str().c_str(), status.str().size());
       }
+
       Child = ExecFork();
-            
       // This is the child
       if (Child == 0)
       {
+
         if(slave >= 0 && master >= 0) 
         {
            setsid();
@@ -1221,7 +1399,7 @@ bool pkgDPkgPM::Go(int OutStatusFd)
 
         if (chdir(_config->FindDir("DPkg::Run-Directory","/").c_str()) != 0)
            _exit(100);
-        
+
         if (_config->FindB("DPkg::FlushSTDIN",true) == true && isatty(STDIN_FILENO))
         {
            int Flags,dummy;
@@ -1237,6 +1415,7 @@ bool pkgDPkgPM::Go(int OutStatusFd)
            if (fcntl(STDIN_FILENO,F_SETFL,Flags & (~(long)O_NONBLOCK)) < 0)
               _exit(100);
         }
+         SetupTerminalScrollArea(d->nr_terminal_rows);
 
         /* No Job Control Stop Env is a magic dpkg var that prevents it
            from using sigstop */
@@ -1331,12 +1510,21 @@ bool pkgDPkgPM::Go(int OutStatusFd)
       
       signal(SIGHUP,old_SIGHUP);
 
+      // reset scroll area
+      SetupTerminalScrollArea(d->nr_terminal_rows + 1);
+      if(d->fancy_progress_output)
+      {
+         // override the progress line (sledgehammer)
+         static const char* clear_screen_below_cursor = "\033[J";
+         std::cout << clear_screen_below_cursor;
+      }
+
       if(master >= 0) 
       {
         tcsetattr(0, TCSAFLUSH, &tt);
         close(master);
       }
-       
+
       // Check for an error code.
       if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
       {
@@ -1366,7 +1554,11 @@ bool pkgDPkgPM::Go(int OutStatusFd)
       }      
    }
    CloseLog();
-   
+
+   // dpkg is done at this point
+   if(_config->FindB("DPkgPM::Progress", false) == true)
+      SendTerminalProgress(100);
+
    if (pkgPackageManager::SigINTStop)
        _error->Warning(_("Operation was interrupted before it could finish"));
 
@@ -1395,9 +1587,8 @@ bool pkgDPkgPM::Go(int OutStatusFd)
 }
 
 void SigINT(int sig) {
-   if (_config->FindB("APT::Immediate-Configure-All",false)) 
-      pkgPackageManager::SigINTStop = true;
-} 
+   pkgPackageManager::SigINTStop = true;
+}
                                                                        /*}}}*/
 // pkgDpkgPM::Reset - Dump the contents of the command list            /*{{{*/
 // ---------------------------------------------------------------------
@@ -1412,6 +1603,12 @@ void pkgDPkgPM::Reset()
 /* */
 void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg) 
 {
+   // If apport doesn't exist or isn't installed do nothing
+   // This e.g. prevents messages in 'universes' without apport
+   pkgCache::PkgIterator apportPkg = Cache.FindPkg("apport");
+   if (apportPkg.end() == true || apportPkg->CurrentVer == 0)
+      return;
+
    string pkgname, reportfile, srcpkgname, pkgver, arch;
    string::size_type pos;
    FILE *report;
@@ -1499,7 +1696,7 @@ void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
         if(strstr(strbuf,"Package:") == strbuf)
         {
            char pkgname[255], version[255];
-           if(sscanf(strbuf, "Package: %s %s", pkgname, version) == 2)
+           if(sscanf(strbuf, "Package: %254s %254s", pkgname, version) == 2)
               if(strcmp(pkgver.c_str(), version) == 0)
               {
                  fclose(report);
@@ -1536,12 +1733,12 @@ void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
    if (!logfile_name.empty())
    {
       FILE *log = NULL;
-      char buf[1024];
 
       fprintf(report, "DpkgTerminalLog:\n");
       log = fopen(logfile_name.c_str(),"r");
       if(log != NULL)
       {
+        char buf[1024];
         while( fgets(buf, sizeof(buf), log) != NULL)
            fprintf(report, " %s", buf);
         fclose(log);
@@ -1552,18 +1749,19 @@ void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
    const char *ops_str[] = {"Install", "Configure","Remove","Purge"};
    fprintf(report, "AptOrdering:\n");
    for (vector<Item>::iterator I = List.begin(); I != List.end(); ++I)
-      fprintf(report, " %s: %s\n", (*I).Pkg.Name(), ops_str[(*I).Op]);
+      if ((*I).Pkg != NULL)
+         fprintf(report, " %s: %s\n", (*I).Pkg.Name(), ops_str[(*I).Op]);
+      else
+         fprintf(report, " %s: %s\n", "NULL", ops_str[(*I).Op]);
 
    // attach dmesg log (to learn about segfaults)
    if (FileExists("/bin/dmesg"))
    {
-      FILE *log = NULL;
-      char buf[1024];
-
       fprintf(report, "Dmesg:\n");
-      log = popen("/bin/dmesg","r");
+      FILE *log = popen("/bin/dmesg","r");
       if(log != NULL)
       {
+        char buf[1024];
         while( fgets(buf, sizeof(buf), log) != NULL)
            fprintf(report, " %s", buf);
         pclose(log);
@@ -1573,13 +1771,12 @@ void pkgDPkgPM::WriteApportReport(const char *pkgpath, const char *errormsg)
    // attach df -l log (to learn about filesystem status)
    if (FileExists("/bin/df"))
    {
-      FILE *log = NULL;
-      char buf[1024];
 
       fprintf(report, "Df:\n");
-      log = popen("/bin/df -l","r");
+      FILE *log = popen("/bin/df -l","r");
       if(log != NULL)
       {
+        char buf[1024];
         while( fgets(buf, sizeof(buf), log) != NULL)
            fprintf(report, " %s", buf);
         pclose(log);