From 3709ec73eac27cc67c8b96d41c46437c24d91c01 Mon Sep 17 00:00:00 2001 From: Michael Friedrich Date: Thu, 30 Oct 2014 19:52:22 +0100 Subject: [PATCH] Add Utility::SetFileOwnership() on Linux refs #7476 --- lib/base/utility.cpp | 53 ++++++++++++++++++++++++++++++++++++++++++++ lib/base/utility.hpp | 1 + 2 files changed, 54 insertions(+) diff --git a/lib/base/utility.cpp b/lib/base/utility.cpp index 58c902606..a834df587 100644 --- a/lib/base/utility.cpp +++ b/lib/base/utility.cpp @@ -43,6 +43,13 @@ # include #endif /* HAVE_CXXABI_H */ +#ifndef _WIN32 +# include +# include +# include +#endif /* _WIN32 */ + + using namespace icinga; boost::thread_specific_ptr Utility::m_ThreadName; @@ -650,6 +657,52 @@ void Utility::CopyFile(const String& source, const String& target) ofs << ifs.rdbuf(); } +/* + * Set file permissions + */ +bool Utility::SetFileOwnership(const String& file, const String& user, const String& group) +{ +#ifndef _WIN32 + errno = 0; + struct passwd *pw = getpwnam(user.CStr()); + + if (!pw) { + if (errno == 0) { + Log(LogCritical, "cli") + << "Invalid user specified: " << user; + return false; + } else { + Log(LogCritical, "cli") + << "getpwnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; + return false; + } + } + + errno = 0; + struct group *gr = getgrnam(group.CStr()); + + if (!gr) { + if (errno == 0) { + Log(LogCritical, "cli") + << "Invalid group specified: " << group; + return false; + } else { + Log(LogCritical, "cli") + << "getgrnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; + return false; + } + } + + if (chown(file.CStr(), pw->pw_uid, gr->gr_gid) < 0) { + Log(LogCritical, "cli") + << "chown() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; + return false; + } +#endif /* _WIN32 */ + + return true; +} + #ifndef _WIN32 void Utility::SetNonBlocking(int fd) { diff --git a/lib/base/utility.hpp b/lib/base/utility.hpp index 361dbb035..126b41bdb 100644 --- a/lib/base/utility.hpp +++ b/lib/base/utility.hpp @@ -91,6 +91,7 @@ public: static bool GlobRecursive(const String& path, const String& pattern, const boost::function& callback, int type = GlobFile | GlobDirectory); static bool MkDir(const String& path, int flags); static bool MkDirP(const String& path, int flags); + static bool SetFileOwnership(const String& file, const String& user, const String& group); static void QueueAsyncCallback(const boost::function& callback, SchedulerPolicy policy = DefaultScheduler);