Add Utility::SetFileOwnership() on Linux

refs #7476
This commit is contained in:
Michael Friedrich 2014-10-30 19:52:22 +01:00
parent 70d2486f43
commit 3709ec73ea
2 changed files with 54 additions and 0 deletions

View File

@ -43,6 +43,13 @@
# include <cxxabi.h>
#endif /* HAVE_CXXABI_H */
#ifndef _WIN32
# include <sys/types.h>
# include <pwd.h>
# include <grp.h>
#endif /* _WIN32 */
using namespace icinga;
boost::thread_specific_ptr<String> 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)
{

View File

@ -91,6 +91,7 @@ public:
static bool GlobRecursive(const String& path, const String& pattern, const boost::function<void (const String&)>& 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<void (void)>& callback, SchedulerPolicy policy = DefaultScheduler);