/*
* UCW Library -- Daemonization
*
- * (c) 2012 Martin Mares <mj@ucw.cz>
+ * (c) 2012--2014 Martin Mares <mj@ucw.cz>
*
* This software may be freely distributed and used according to the terms
* of the GNU Lesser General Public License.
#include <sys/stat.h>
#include <sys/file.h>
-static void
+void
daemon_resolve_ugid(struct daemon_params *dp)
{
// Resolve user name
}
}
+void daemon_switch_ugid(struct daemon_params *dp)
+{
+ if (dp->want_setgid && setresgid(dp->run_as_gid, dp->run_as_gid, dp->run_as_gid) < 0)
+ die("Cannot set GID to %d: %m", (int) dp->run_as_gid);
+ if (dp->want_setgid > 1 && initgroups(dp->run_as_user, dp->run_as_gid) < 0)
+ die("Cannot initialize groups: %m");
+ if (dp->want_setuid && setresuid(dp->run_as_uid, dp->run_as_uid, dp->run_as_uid) < 0)
+ die("Cannot set UID to %d: %m", (int) dp->run_as_uid);
+}
+
void
daemon_init(struct daemon_params *dp)
{
}
// Switch GID and UID
- if (dp->want_setgid && setresgid(dp->run_as_gid, dp->run_as_gid, dp->run_as_gid) < 0)
- die("Cannot set GID to %d: %m", (int) dp->run_as_gid);
- if (dp->want_setgid > 1 && initgroups(dp->run_as_user, dp->run_as_gid) < 0)
- die("Cannot initialize groups: %m");
- if (dp->want_setuid && setresuid(dp->run_as_uid, dp->run_as_uid, dp->run_as_uid) < 0)
- die("Cannot set UID to %d: %m", (int) dp->run_as_uid);
+ daemon_switch_ugid(dp);
// Create a new session and close stdio
setsid();
/*
* UCW Library -- Daemonization
*
- * (c) 2012 Martin Mares <mj@ucw.cz>
+ * (c) 2012--2014 Martin Mares <mj@ucw.cz>
*
* This software may be freely distributed and used according to the terms
* of the GNU Lesser General Public License.
**/
void daemon_exit(struct daemon_params *dp);
+/**
+ * Parse `run_as_user` and `run_as_group` and remember the results in internal fields.
+ * This is called automatically by daemon_init(), but also provided as a separate
+ * function in case you want to use daemon_switch_ugid(). Upon parse error, it calls die().
+ **/
+void daemon_resolve_ugid(struct daemon_params *dp);
+
+/**
+ * Switch user and group as specified by the `run_as_user` and `run_as_group`.
+ * This is performed automatically by daemon_run(), but sometimes you might want to
+ * switch the user and group separately. In this case, you have to call daemon_resolve_ugid()
+ * beforehand.
+ **/
+void daemon_switch_ugid(struct daemon_params *dp);
+
#define DAEMON_ERR_LEN 256
/** Parameters passed to @daemon_control() **/