From 8f0d6c1f5406ba4b1fd399a1fc6437c4dc6bda9e Mon Sep 17 00:00:00 2001 From: Olaf Rempel Date: Tue, 24 Feb 2009 14:55:09 +0100 Subject: [PATCH] daemon code --- torrent-stats.c | 46 +++++++++++++++++++++++++++++++++++++++++++++- torrent-stats.conf | 2 ++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/torrent-stats.c b/torrent-stats.c index aea9036..42767a0 100644 --- a/torrent-stats.c +++ b/torrent-stats.c @@ -21,6 +21,7 @@ #include #include +#include #include "configfile.h" #include "connection.h" @@ -32,9 +33,12 @@ #include "tcpsocket.h" #define DEFAULT_CONFIG "torrent-stats.conf" +#define DEFAULT_LOGFILE "torrent-stats.log" static struct option opts[] = { {"config", 1, 0, 'c'}, + {"user", 1, 0, 'u'}, + {"debug", 0, 0, 'd'}, {"help", 0, 0, 'h'}, {0, 0, 0, 0} }; @@ -62,20 +66,32 @@ static int listen_cb(const char *parameter, void *privdata) int main(int argc, char *argv[]) { char *config = DEFAULT_CONFIG; + char *user = NULL; + int debug = 0; int code, arg = 0; do { - code = getopt_long(argc, argv, "c:h", opts, &arg); + code = getopt_long(argc, argv, "c:u:dh", opts, &arg); switch (code) { case 'c': /* config */ config = optarg; break; + case 'u': /* user */ + user = optarg; + break; + + case 'd': /* debug */ + debug = 1; + break; + case 'h': /* help */ printf("Usage: torrent-stats [options]\n" "Options: \n" " --config -c configfile use this configfile\n" + " --debug -d do not fork and log to stderr\n" + " --user -u username change uid to username\n" " --help -h this help\n" "\n"); exit(0); @@ -90,9 +106,37 @@ int main(int argc, char *argv[]) } } while (code != -1); + /* userwechsel */ + if (user) { + struct passwd *pwl; + if (!(pwl = getpwnam(user))) { + log_print(LOG_ERROR, "unknown user: %s", user); + exit(-1); + } + + if (setgid(pwl->pw_gid) || setuid(pwl->pw_uid)) { + log_print(LOG_ERROR, "setgid/setuid"); + exit(-1); + } + } + + /* parse config file */ if (config_parse(config) < 0) exit(1); + /* check logfile */ + const char *logfile = config_get_string("global", "logfile", DEFAULT_LOGFILE); + if (!debug) { + /* start logging */ + if (log_init(logfile) < 0) + exit(-1); + + /* zum daemon mutieren */ + daemon(-1, 0); + } + + log_print(LOG_INFO, "torrent-stats started (user: %s, pid: %d)", getpwuid(getuid())->pw_name, getpid()); + config_get_strings("global", "listen", listen_cb, ctcs_accept_handler); config_get_strings("global", "listen-http", listen_cb, httpd_accept_handler); diff --git a/torrent-stats.conf b/torrent-stats.conf index b07a034..99ca6a1 100644 --- a/torrent-stats.conf +++ b/torrent-stats.conf @@ -4,3 +4,5 @@ listen-http 0.0.0.0:8080 status-interval 10 seed-timeout 300 + +logfile torrent-stats.log