summaryrefslogtreecommitdiff
path: root/src/daemon.cc
diff options
context:
space:
mode:
Diffstat (limited to 'src/daemon.cc')
-rw-r--r--src/daemon.cc44
1 files changed, 39 insertions, 5 deletions
diff --git a/src/daemon.cc b/src/daemon.cc
index 678a8c9..6e46bd5 100644
--- a/src/daemon.cc
+++ b/src/daemon.cc
@@ -31,17 +31,47 @@
#include <signal.h>
#include <stdio.h>
+// For getgrent and getgrent
+#include <sys/types.h>
+#include <grp.h>
+#include <pwd.h>
+
+// For strcmp
+#include <string.h>
+
Daemon::Daemon()
{}
Daemon::~Daemon()
{}
-int Daemon::run(uid_t uid, gid_t gid)
+int Daemon::run(const char *user, const char* group)
{
int f;
int fd;
+ // Fetch user id
+ int uid = -1;
+ struct passwd *p = getpwent();
+ while(p) {
+ if(strcmp(p->pw_name, user) == 0) uid = p->pw_uid;
+ p = getpwent();
+ }
+ if(uid == -1) {
+ fprintf(stderr, "Could not find user \"%s\" in /etc/passwd file.\n", user);
+ }
+
+ // Fetch group id
+ int gid = -1;
+ struct group *g = getgrent();
+ while(g) {
+ if(strcmp(g->gr_name, group) == 0) gid = g->gr_gid;
+ g = getgrent();
+ }
+ if(gid == -1) {
+ fprintf(stderr, "Could not find group \"%s\" in /etc/group file.\n", group);
+ }
+
chdir("/");
umask(0);
@@ -52,14 +82,18 @@ int Daemon::run(uid_t uid, gid_t gid)
return 1;
case 0: // Forked child
+ // Switch to given group
if(setgid(gid) != 0) {
- fprintf(stderr, "Failed to change to gid %d, quitting.\n", gid);
- return 1;
+ fprintf(stderr, "Failed to change to group \"%s\" (gid: %d), quitting.\n", group, gid);
+ perror("");
+ fprintf(stderr, "Runnning daemon as current group\n");
}
+ // Switch to given user
if(setuid(uid) != 0) {
- fprintf(stderr, "Failed to change to uid %d, quitting.\n", uid);
- return 1;
+ fprintf(stderr, "Failed to change to user \"%s\" (uid: %d), quitting.\n", user, uid);
+ perror("");
+ fprintf(stderr, "Runnning daemon as current user\n");
}
// Redirect stdin, stdout and stderr to /dev/null