X-Git-Url: http://mj.ucw.cz/gitweb/?a=blobdiff_plain;ds=sidebyside;f=ucw%2Fdaemon.c;h=9b136d8ac2c171434d6d2d893dc4d824b73068f7;hb=0eb6d8317cdbdb28663ff779d31684b3c7a47274;hp=ec9a21877ea190019cef4101a94813ed4ddac221;hpb=6e229d7655b00065cfdb0e79059f6bb014530ee7;p=libucw.git diff --git a/ucw/daemon.c b/ucw/daemon.c index ec9a2187..9b136d8a 100644 --- a/ucw/daemon.c +++ b/ucw/daemon.c @@ -1,7 +1,7 @@ /* * UCW Library -- Daemonization * - * (c) 2012 Martin Mares + * (c) 2012--2014 Martin Mares * * This software may be freely distributed and used according to the terms * of the GNU Lesser General Public License. @@ -18,9 +18,11 @@ #include #include #include +#include +#include #include -static void +void daemon_resolve_ugid(struct daemon_params *dp) { // Resolve user name @@ -30,8 +32,8 @@ daemon_resolve_ugid(struct daemon_params *dp) { 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; @@ -54,8 +56,8 @@ daemon_resolve_ugid(struct daemon_params *dp) { 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; @@ -77,6 +79,16 @@ daemon_resolve_ugid(struct daemon_params *dp) } } +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) { @@ -125,12 +137,7 @@ daemon_run(struct daemon_params *dp, void (*body)(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();