/*
* 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 <pwd.h>
#include <grp.h>
#include <errno.h>
+#include <sys/types.h>
+#include <sys/stat.h>
#include <sys/file.h>
-static void
+void
daemon_resolve_ugid(struct daemon_params *dp)
{
// Resolve user name
{
if (u[0] == '#')
{
- uns id;
- const char *err = str_to_uns(&id, u, NULL, 10 | STN_WHOLE);
+ uint id;
+ const char *err = str_to_uint(&id, u, NULL, 10 | STN_WHOLE);
if (err)
die("Cannot parse user `%s': %s", u, err);
dp->run_as_uid = id;
{
if (g[0] == '#')
{
- uns id;
- const char *err = str_to_uns(&id, g, NULL, 10 | STN_WHOLE);
+ uint id;
+ const char *err = str_to_uint(&id, g, NULL, 10 | STN_WHOLE);
if (err)
die("Cannot parse group `%s': %s", g, err);
dp->run_as_gid = id;
}
}
+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)
{
daemon_resolve_ugid(dp);
+ if (dp->flags & DAEMON_FLAG_SIMULATE)
+ return;
+
if (dp->pid_file)
{
// Check that PID file path is absolute
void
daemon_run(struct daemon_params *dp, void (*body)(struct daemon_params *dp))
{
+ if (dp->flags & DAEMON_FLAG_SIMULATE)
+ {
+ body(dp);
+ return;
+ }
+
// 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();
void
daemon_exit(struct daemon_params *dp)
{
+ if (dp->flags & DAEMON_FLAG_SIMULATE)
+ return;
+
if (dp->pid_file)
{
if (unlink(dp->pid_file) < 0)