From 11b126f9d229c85bfc7a6092527af46f7314f188 Mon Sep 17 00:00:00 2001
From: David Kalnischkies <kalnischkies@gmail.com>
Date: Sat, 13 Jul 2013 23:05:55 +0200
Subject: [PATCH] do not try to chown if not run as root
MIME-Version: 1.0
Content-Type: text/plain; charset=utf8
Content-Transfer-Encoding: 8bit

If this code is run as non-root we are in a special situation (e.g. in
our testcases) where it is obvious that we can't enforce user/group on
any file, so skip this code altogether instead of bugging users with
an error message – which we also switch to a warning as a failure to
open the file is "just" a warning, so the 'wrong' owner shouldn't be
that much of an issue.

The file is still handled with chmod, so all the security we can enforce
is still enforced of course, which also gets a warning if it fails.

Git-Dch: Ignore
---
 apt-pkg/deb/dpkgpm.cc | 17 +++++++++--------
 1 file changed, 9 insertions(+), 8 deletions(-)

diff --git a/apt-pkg/deb/dpkgpm.cc b/apt-pkg/deb/dpkgpm.cc
index 34ae4e593..5b2a8251e 100644
--- a/apt-pkg/deb/dpkgpm.cc
+++ b/apt-pkg/deb/dpkgpm.cc
@@ -751,14 +751,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)
-         if(chown(logfile_name.c_str(), pw->pw_uid, gr->gr_gid) != 0)
-            _error->Errno("OpenLog", "chown failed");
-      chmod(logfile_name.c_str(), 0640);
+      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);
    }
 
-- 
2.47.2