Improve comment of snapshot_currently_being_removed.
[dss.git] / dss.c
diff --git a/dss.c b/dss.c
index 3612d4f..c2aef36 100644 (file)
--- a/dss.c
+++ b/dss.c
+/* SPDX-License-Identifier: GPL-2.0 */
 #include <string.h>
 #include <stdlib.h>
+#include <stdio.h>
 #include <stdarg.h>
 #include <assert.h>
 #include <errno.h>
 #include <sys/types.h>
 #include <signal.h>
 #include <ctype.h>
+#include <stdbool.h>
 #include <sys/stat.h>
 #include <unistd.h>
 #include <inttypes.h>
+#include <sys/time.h>
 #include <time.h>
 #include <sys/wait.h>
 #include <fnmatch.h>
 #include <limits.h>
-
+#include <fcntl.h>
+#include <lopsub.h>
+#include <sys/mman.h>
 
 #include "gcc-compat.h"
-#include "cmdline.h"
 #include "log.h"
-#include "string.h"
-#include "error.h"
-#include "fd.h"
+#include "str.h"
+#include "err.h"
+#include "file.h"
 #include "exec.h"
 #include "daemon.h"
-#include "signal.h"
-
+#include "sig.h"
+#include "df.h"
+#include "tv.h"
+#include "snap.h"
+#include "ipc.h"
+#include "dss.lsg.h"
+
+#define CMD_PTR(_cname) lls_cmd(LSG_DSS_CMD_ ## _cname, dss_suite)
+#define OPT_RESULT(_cname, _oname) (lls_opt_result(\
+       LSG_DSS_ ## _cname ## _OPT_ ## _oname, (CMD_PTR(_cname) == CMD_PTR(DSS))? lpr : sublpr))
+#define OPT_GIVEN(_cname, _oname) (lls_opt_given(OPT_RESULT(_cname, _oname)))
+#define OPT_STRING_VAL(_cname, _oname) (lls_string_val(0, \
+       OPT_RESULT(_cname, _oname)))
+#define OPT_UINT32_VAL(_cname, _oname) (lls_uint32_val(0, \
+               OPT_RESULT(_cname, _oname)))
+
+struct dss_user_data {int (*handler)(void);};
+#define EXPORT_CMD_HANDLER(_cmd) const struct dss_user_data \
+       lsg_dss_com_ ## _cmd ## _user_data = { \
+               .handler = com_ ## _cmd \
+       };
 
-struct gengetopt_args_info conf;
-char *dss_error_txt = NULL;
+/*
+ * Command line and active options. We need to keep a copy of the parsed
+ * command line options for the SIGHUP case where we merge the command line
+ * options and the new config file options.
+ */
+static struct lls_parse_result *cmdline_lpr, *lpr;
+
+/** Parsed subcommand options. */
+static struct lls_parse_result *cmdline_sublpr, *sublpr;
+/* The executing subcommand (NULL at startup). */
+static const struct lls_command *subcmd;
+/** Wether daemon_init() was called. */
+static bool daemonized;
+/** Non-NULL if we log to a file. */
 static FILE *logfile;
-int signal_pipe;
+/** The read end of the signal pipe */
+static int signal_pipe;
+/** Process id of current pre-create-hook/rsync/post-create-hook process. */
+static pid_t create_pid;
+/** Whether the pre-create-hook/rsync/post-create-hook is currently stopped. */
+static int create_process_stopped;
+/** How many times in a row the rsync command failed. */
+static int num_consecutive_rsync_errors;
+/** Process id of current pre-remove/rm/post-remove process. */
+static pid_t remove_pid;
+/** When the next snapshot is due. */
+static int64_t next_snapshot_time;
+/** When to try to remove something. */
+static struct timeval next_removal_check;
+/** Creation time of the snapshot currently being created. */
+static int64_t current_snapshot_creation_time;
+/* Set by the pre-rm hook, cleared by handle_remove_exit(). */
+struct snapshot *snapshot_currently_being_removed;
+/** Needed by the post-create hook. */
+static char *path_to_last_complete_snapshot;
+static char *name_of_reference_snapshot;
+/** \sa \ref snap.h for details. */
+enum hook_status snapshot_creation_status;
+/** \sa \ref snap.h for details. */
+enum hook_status snapshot_removal_status;
+
 
 DEFINE_DSS_ERRLIST;
+static const char *hook_status_description[] = {HOOK_STATUS_ARRAY};
+
+/* may be called with ds == NULL. */
+static int disk_space_low(struct disk_space *ds)
+{
+       struct disk_space ds_struct;
+       uint32_t val;
 
+       if (!ds) {
+               int ret = get_disk_space(".", &ds_struct);
+               if (ret < 0)
+                       return ret;
+               ds = &ds_struct;
+       }
+       val = OPT_UINT32_VAL(DSS, MIN_FREE_MB);
+       if (val != 0)
+               if (ds->free_mb < val)
+                       return 1;
+       val = OPT_UINT32_VAL(DSS, MIN_FREE_PERCENT);
+       if (val != 0)
+               if (ds->percent_free < val)
+                       return 1;
+       val = OPT_UINT32_VAL(DSS, MIN_FREE_PERCENT_INODES);
+       if (val != 0)
+               if (ds->percent_free_inodes < val)
+                       return 1;
+       return 0;
+}
 
-/* a litte cpp magic helps to DRY */
-#define COMMANDS \
-       COMMAND(ls) \
-       COMMAND(create) \
-       COMMAND(prune) \
-       COMMAND(run)
-#define COMMAND(x) int com_ ##x(void);
-COMMANDS
-#undef COMMAND
-#define COMMAND(x) if (conf.x ##_given) return com_ ##x();
-int call_command_handler(void)
+static void dump_dss_config(const char *msg)
 {
-       COMMANDS
-       DSS_EMERG_LOG("BUG: did not find command handler\n");
-       exit(EXIT_FAILURE);
+       const char dash[] = "-----------------------------";
+       char *lopsub_dump;
+       int ret;
+       FILE *log = logfile? logfile : stderr;
+       struct disk_space ds;
+       int64_t now = get_current_time();
+
+       if (OPT_UINT32_VAL(DSS, LOGLEVEL) > INFO)
+               return;
+
+       fprintf(log, "%s <%s config> %s\n", dash, msg, dash);
+       fprintf(log, "\n*** disk space ***\n\n");
+       ret = get_disk_space(".", &ds);
+       if (ret >= 0) {
+               DSS_INFO_LOG(("disk space low: %s\n", disk_space_low(&ds)?
+                       "yes" : "no"));
+               log_disk_space(&ds);
+       } else
+               DSS_ERROR_LOG(("can not get free disk space: %s\n",
+                       dss_strerror(-ret)));
+
+       /* we continue on errors from get_disk_space */
+
+       fprintf(log, "\n*** non-default options ***\n\n");
+       lopsub_dump = lls_dump_parse_result(lpr, CMD_PTR(DSS), true);
+       fprintf(log, "%s", lopsub_dump);
+       free(lopsub_dump);
+       fprintf(log, "\n*** non-default options for \"run\" ***\n\n");
+       lopsub_dump = lls_dump_parse_result(lpr, CMD_PTR(RUN), true);
+       fprintf(log, "%s", lopsub_dump);
+       free(lopsub_dump);
+       fprintf(log, "\n*** internal state ***\n\n");
+       fprintf(log,
+               "pid: %d\n"
+               "logfile: %s\n"
+               "snapshot_currently_being_removed: %s\n"
+               "path_to_last_complete_snapshot: %s\n"
+               "reference_snapshot: %s\n"
+               "snapshot_creation_status: %s\n"
+               "snapshot_removal_status: %s\n"
+               "num_consecutive_rsync_errors: %d\n"
+               ,
+               (int) getpid(),
+               logfile? OPT_STRING_VAL(RUN, LOGFILE) : "stderr",
+               snapshot_currently_being_removed?
+                       snapshot_currently_being_removed->name : "(none)",
+               path_to_last_complete_snapshot?
+                       path_to_last_complete_snapshot : "(none)",
+               name_of_reference_snapshot?
+                       name_of_reference_snapshot : "(none)",
+               hook_status_description[snapshot_creation_status],
+               hook_status_description[snapshot_removal_status],
+               num_consecutive_rsync_errors
+       );
+       if (create_pid != 0)
+               fprintf(log,
+                       "create_pid: %" PRId32 "\n"
+                       "create process is %sstopped\n"
+                       ,
+                       create_pid,
+                       create_process_stopped? "" : "not "
+               );
+       if (remove_pid != 0)
+               fprintf(log, "remove_pid: %" PRId32 "\n", remove_pid);
+       if (next_snapshot_time != 0)
+               fprintf(log, "next snapshot due in %" PRId64 " seconds\n",
+                       next_snapshot_time - now);
+       if (current_snapshot_creation_time != 0)
+               fprintf(log, "current_snapshot_creation_time: %"
+                       PRId64 " (%" PRId64 " seconds ago)\n",
+                       current_snapshot_creation_time,
+                       now - current_snapshot_creation_time
+               );
+       if (next_removal_check.tv_sec != 0) {
+               fprintf(log, "next removal check: %llu (%llu seconds ago)\n",
+                       (long long unsigned)next_removal_check.tv_sec,
+                       now - (long long unsigned)next_removal_check.tv_sec
+               );
+
+       }
+       fprintf(log, "%s </%s config> %s\n", dash, msg, dash);
 }
-#undef COMMAND
-#undef COMMANDS
 
-/*
- * complete, not being deleted: 1204565370-1204565371.Sun_Mar_02_2008_14_33-Sun_Mar_02_2008_14_43
- * complete, being deleted: 1204565370-1204565371.being_deleted
- * incomplete, not being deleted: 1204565370-incomplete
- * incomplete, being deleted: 1204565370-incomplete.being_deleted
- */
-enum snapshot_status_flags {
-       SS_COMPLETE = 1,
-       SS_BEING_DELETED = 2,
-};
+static int loglevel = -1;
+static const char *location_file = NULL;
+static int         location_line = -1;
+static const char *location_func = NULL;
 
-struct snapshot {
-       char *name;
-       int64_t creation_time;
-       int64_t completion_time;
-       enum snapshot_status_flags flags;
-       unsigned interval;
-};
+void dss_log_set_params(int ll, const char *file, int line, const char *func)
+{
+       loglevel = ll;
+       location_file = file;
+       location_line = line;
+       location_func = func;
+}
 
-__printf_2_3 void dss_log(int ll, const char* fmt,...)
+/**
+ * The log function of dss.
+ *
+ * \param ll Loglevel.
+ * \param fml Usual format string.
+ *
+ * All DSS_XXX_LOG() macros use this function.
+ */
+__printf_1_2 void dss_log(const char* fmt,...)
 {
        va_list argp;
        FILE *outfd;
        struct tm *tm;
        time_t t1;
        char str[255] = "";
+       int lpr_ll = lpr? OPT_UINT32_VAL(DSS, LOGLEVEL) : WARNING;
 
-       if (ll < conf.loglevel_arg)
+       if (loglevel < lpr_ll)
                return;
        outfd = logfile? logfile : stderr;
-       time(&t1);
-       tm = localtime(&t1);
-       strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
-       fprintf(outfd, "%s ", str);
-       if (conf.loglevel_arg <= INFO)
-               fprintf(outfd, "%i: ", ll);
+       if (subcmd == CMD_PTR(RUN)) {
+               time(&t1);
+               tm = localtime(&t1);
+               strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
+               fprintf(outfd, "%s ", str);
+               if (lpr_ll <= INFO)
+                       fprintf(outfd, "%i: ", loglevel);
+       }
+       if (subcmd == CMD_PTR(RUN))
+#ifdef DSS_NO_FUNC_NAMES
+               fprintf(outfd, "%s:%d: ", location_file, location_line);
+#else
+               fprintf(outfd, "%s: ", location_func);
+#endif
        va_start(argp, fmt);
        vfprintf(outfd, fmt, argp);
        va_end(argp);
@@ -97,291 +262,347 @@ __printf_2_3 void dss_log(int ll, const char* fmt,...)
 /**
  * Print a message either to stdout or to the log file.
  */
-__printf_1_2 void dss_msg(const char* fmt,...)
+static __printf_1_2 void dss_msg(const char* fmt,...)
 {
-       FILE *outfd = conf.daemon_given? logfile : stdout;
+       FILE *outfd = logfile? logfile : stdout;
        va_list argp;
        va_start(argp, fmt);
        vfprintf(outfd, fmt, argp);
        va_end(argp);
 }
 
-int is_snapshot(const char *dirname, int64_t now, struct snapshot *s)
+static char *get_config_file_name(void)
 {
-       int i, ret;
-       char *dash, *dot, *tmp;
-       int64_t num;
+       char *home, *config_file;
+
+       if (OPT_GIVEN(DSS, CONFIG_FILE))
+               return dss_strdup(OPT_STRING_VAL(DSS, CONFIG_FILE));
+       home = get_homedir();
+       config_file = make_message("%s/.dssrc", home);
+       free(home);
+       return config_file;
+}
 
-       assert(dirname);
-       dash = strchr(dirname, '-');
-       if (!dash || !dash[1] || dash == dirname)
-               return 0;
-       for (i = 0; dirname[i] != '-'; i++)
-               if (!isdigit(dirname[i]))
-                       return 0;
-       tmp = dss_strdup(dirname);
-       tmp[i] = '\0';
-       ret = dss_atoi64(tmp, &num);
-       free(tmp);
-       if (ret < 0) {
-               free(dss_error_txt);
-               return 0;
-       }
-       assert(num >= 0);
-       if (num > now)
+static int send_signal(int sig, bool wait)
+{
+       pid_t pid;
+       char *config_file = get_config_file_name();
+       int ret = get_dss_pid(config_file, &pid);
+       unsigned ms = 32;
+       struct timespec ts;
+
+       free(config_file);
+       if (ret < 0)
+               return ret;
+       if (OPT_GIVEN(DSS, DRY_RUN)) {
+               dss_msg("%d\n", (int)pid);
                return 0;
-       s->creation_time = num;
-       //DSS_DEBUG_LOG("%s start time: %lli\n", dirname, (long long)s->creation_time);
-       s->interval = (long long) ((now - s->creation_time)
-               / conf.unit_interval_arg / 24 / 3600);
-       if (!strcmp(dash + 1, "incomplete")) {
-               s->completion_time = -1;
-               s->flags = 0; /* neither complete, nor being deleted */
-               goto success;
-       }
-       if (!strcmp(dash + 1, "incomplete.being_deleted")) {
-               s->completion_time = -1;
-               s->flags = SS_BEING_DELETED; /* mot cpmplete, being deleted */
-               goto success;
        }
-       tmp = dash + 1;
-       dot = strchr(tmp, '.');
-       if (!dot || !dot[1] || dot == tmp)
-               return 0;
-       for (i = 0; tmp[i] != '.'; i++)
-               if (!isdigit(tmp[i]))
-                       return 0;
-       tmp = dss_strdup(dash + 1);
-       tmp[i] = '\0';
-       ret = dss_atoi64(tmp, &num);
-       free(tmp);
-       if (ret < 0) {
-               free(dss_error_txt);
-               return 0;
+       DSS_NOTICE_LOG(("sending signal %d to pid %d\n", sig, (int)pid));
+       ret = kill(pid, sig);
+       if (ret < 0)
+               return -ERRNO_TO_DSS_ERROR(errno);
+       if (!wait)
+               return 1;
+       while (ms < 5000) {
+               ts.tv_sec = ms / 1000;
+               ts.tv_nsec = (ms % 1000) * 1000 * 1000;
+               ret = nanosleep(&ts, NULL);
+               if (ret < 0)
+                       return -ERRNO_TO_DSS_ERROR(errno);
+               ret = kill(pid, 0);
+               if (ret < 0) {
+                       if (errno != ESRCH)
+                               return -ERRNO_TO_DSS_ERROR(errno);
+                       return 1;
+               }
+               ms *= 2;
        }
-       if (num > now)
-               return 0;
-       s->completion_time = num;
-       s->flags = SS_COMPLETE;
-       if (strcmp(dot + 1, "being_deleted"))
-               s->flags |= SS_BEING_DELETED;
-success:
-       s->name = dss_strdup(dirname);
-       return 1;
+       return -E_KILL_TIMEOUT;
 }
 
-int64_t get_current_time(void)
-{
-       time_t now;
-       time(&now);
-       DSS_DEBUG_LOG("now: %lli\n", (long long) now);
-       return (int64_t)now;
-}
+struct signal_info {
+       const char * const name;
+       int num;
+};
 
-char *incomplete_name(int64_t start)
-{
-       return make_message("%lli-incomplete", (long long)start);
-}
+/*
+ * The table below was taken 2016 from proc/sig.c of procps-3.2.8. Copyright
+ * 1998-2003 by Albert Cahalan, GPLv2.
+ */
+static const struct signal_info signal_table[] = {
+       {"ABRT",   SIGABRT},  /* IOT */
+       {"ALRM",   SIGALRM},
+       {"BUS",    SIGBUS},
+       {"CHLD",   SIGCHLD},  /* CLD */
+       {"CONT",   SIGCONT},
+       {"FPE",    SIGFPE},
+       {"HUP",    SIGHUP},
+       {"ILL",    SIGILL},
+       {"INT",    SIGINT},
+       {"KILL",   SIGKILL},
+       {"PIPE",   SIGPIPE},
+#ifdef SIGPOLL
+       {"POLL",   SIGPOLL},  /* IO */
+#endif
+       {"PROF",   SIGPROF},
+#ifdef SIGPWR
+       {"PWR",    SIGPWR},
+#endif
+       {"QUIT",   SIGQUIT},
+       {"SEGV",   SIGSEGV},
+#ifdef SIGSTKFLT
+       {"STKFLT", SIGSTKFLT},
+#endif
+       {"STOP",   SIGSTOP},
+       {"SYS",    SIGSYS},   /* UNUSED */
+       {"TERM",   SIGTERM},
+       {"TRAP",   SIGTRAP},
+       {"TSTP",   SIGTSTP},
+       {"TTIN",   SIGTTIN},
+       {"TTOU",   SIGTTOU},
+       {"URG",    SIGURG},
+       {"USR1",   SIGUSR1},
+       {"USR2",   SIGUSR2},
+       {"VTALRM", SIGVTALRM},
+       {"WINCH",  SIGWINCH},
+       {"XCPU",   SIGXCPU},
+       {"XFSZ",   SIGXFSZ}
+};
 
-char *being_deleted_name(struct snapshot *s)
-{
-       if (s->flags & SS_COMPLETE)
-               return make_message("%lli-%lli.being_deleted",
-                       (long long)s->creation_time,
-                       (long long)s->completion_time);
-       return make_message("%lli-incomplete.being_deleted",
-               (long long)s->creation_time);
-}
+#define SIGNAL_TABLE_SIZE (sizeof(signal_table) / sizeof(signal_table[0]))
+#ifndef SIGRTMAX
+#define SIGRTMAX 64
+#endif
 
-int complete_name(int64_t start, int64_t end, char **result)
+static int com_kill(void)
 {
-       struct tm start_tm, end_tm;
-       time_t *start_seconds = (time_t *) (uint64_t *)&start; /* STFU, gcc */
-       time_t *end_seconds = (time_t *) (uint64_t *)&end; /* STFU, gcc */
-       char start_str[200], end_str[200];
+       bool w_given = OPT_GIVEN(KILL, WAIT);
+       const char *arg = OPT_STRING_VAL(KILL, SIGNAL);
+       int ret, i;
 
-       if (!localtime_r(start_seconds, &start_tm)) {
-               make_err_msg("%lli", (long long)start);
-               return -E_LOCALTIME;
-       }
-       if (!localtime_r(end_seconds, &end_tm)) {
-               make_err_msg("%lli", (long long)end);
-               return -E_LOCALTIME;
-       }
-       if (!strftime(start_str, sizeof(start_str), "%a_%b_%d_%Y_%H_%M_%S", &start_tm)) {
-               make_err_msg("%lli", (long long)start);
-               return -E_STRFTIME;
-       }
-       if (!strftime(end_str, sizeof(end_str), "%a_%b_%d_%Y_%H_%M_%S", &end_tm)) {
-               make_err_msg("%lli", (long long)end);
-               return -E_STRFTIME;
+       if (*arg >= '0' && *arg <= '9') {
+               int64_t val;
+               ret = dss_atoi64(arg, &val);
+               if (ret < 0)
+                       return ret;
+               if (val < 0 || val > SIGRTMAX)
+                       return -ERRNO_TO_DSS_ERROR(EINVAL);
+               return send_signal(val, w_given);
        }
-       *result = make_message("%lli-%lli.%s-%s", (long long) start, (long long) end,
-               start_str, end_str);
-       return 1;
+       if (strncasecmp(arg, "sig", 3) == 0)
+               arg += 3;
+       if (strcasecmp(arg, "CLD") == 0)
+               return send_signal(SIGCHLD, w_given);
+       if (strcasecmp(arg, "IOT") == 0)
+               return send_signal(SIGABRT, w_given);
+       for (i = 0; i < SIGNAL_TABLE_SIZE; i++)
+               if (strcasecmp(arg, signal_table[i].name) == 0)
+                       return send_signal(signal_table[i].num, w_given);
+       DSS_ERROR_LOG(("invalid sigspec: %s\n", arg));
+       return -ERRNO_TO_DSS_ERROR(EINVAL);
 }
+EXPORT_CMD_HANDLER(kill);
 
-struct snapshot_list {
-       int64_t now;
-       unsigned num_snapshots;
-       unsigned array_size;
-       struct snapshot **snapshots;
-       /**
-        * Array of size num_intervals + 1
-        *
-        * It contains the number of snapshots in each interval. interval_count[num_intervals]
-        * is the number of snapshots which belong to any interval greater than num_intervals.
-        */
-       unsigned *interval_count;
-};
-
-#define FOR_EACH_SNAPSHOT(s, i, sl) \
-       for ((i) = 0; (i) < (sl)->num_snapshots && ((s) = (sl)->snapshots[(i)]); (i)++)
-
+static void dss_get_snapshot_list(struct snapshot_list *sl)
+{
+       get_snapshot_list(sl, OPT_UINT32_VAL(DSS, UNIT_INTERVAL),
+               OPT_UINT32_VAL(DSS, NUM_INTERVALS));
+}
 
+static int64_t compute_next_snapshot_time(void)
+{
+       int64_t x = 0, now = get_current_time(), unit_interval
+               = 24 * 3600 * OPT_UINT32_VAL(DSS, UNIT_INTERVAL), ret,
+               last_completion_time;
+       unsigned wanted = desired_number_of_snapshots(0,
+               OPT_UINT32_VAL(DSS, NUM_INTERVALS)),
+               num_complete = 0;
+       int i;
+       struct snapshot *s = NULL;
+       struct snapshot_list sl;
 
-#define NUM_COMPARE(x, y) ((int)((x) < (y)) - (int)((x) > (y)))
+       dss_get_snapshot_list(&sl);
+       FOR_EACH_SNAPSHOT(s, i, &sl) {
+               if (!(s->flags & SS_COMPLETE))
+                       continue;
+               num_complete++;
+               x += s->completion_time - s->creation_time;
+               last_completion_time = s->completion_time;
+       }
+       assert(x >= 0);
 
-static int compare_snapshots(const void *a, const void *b)
-{
-       struct snapshot *s1 = *(struct snapshot **)a;
-       struct snapshot *s2 = *(struct snapshot **)b;
-       return NUM_COMPARE(s2->creation_time, s1->creation_time);
+       ret = now;
+       if (num_complete == 0)
+               goto out;
+       x /= num_complete; /* avg time to create one snapshot */
+       if (unit_interval < x * wanted) /* oops, no sleep at all */
+               goto out;
+       ret = last_completion_time + unit_interval / wanted - x;
+out:
+       free_snapshot_list(&sl);
+       return ret;
 }
 
-/** Compute the minimum of \a a and \a b. */
-#define DSS_MIN(a,b) ((a) < (b) ? (a) : (b))
-
-int add_snapshot(const char *dirname, void *private)
+static inline void invalidate_next_snapshot_time(void)
 {
-       struct snapshot_list *sl = private;
-       struct snapshot s;
-       int ret = is_snapshot(dirname, sl->now, &s);
-
-       if (!ret)
-               return 1;
-       if (sl->num_snapshots >= sl->array_size) {
-               sl->array_size = 2 * sl->array_size + 1;
-               sl->snapshots = dss_realloc(sl->snapshots,
-                       sl->array_size * sizeof(struct snapshot *));
-       }
-       sl->snapshots[sl->num_snapshots] = dss_malloc(sizeof(struct snapshot));
-       *(sl->snapshots[sl->num_snapshots]) = s;
-       sl->interval_count[DSS_MIN(s.interval, conf.num_intervals_arg)]++;
-       sl->num_snapshots++;
-       return 1;
+       next_snapshot_time = 0;
 }
 
-void get_snapshot_list(struct snapshot_list *sl)
+static inline int next_snapshot_time_is_valid(void)
 {
-       sl->now = get_current_time();
-       sl->num_snapshots = 0;
-       sl->array_size = 0;
-       sl->snapshots = NULL;
-       sl->interval_count = dss_calloc((conf.num_intervals_arg + 1) * sizeof(unsigned));
-       for_each_subdir(add_snapshot, sl);
-       qsort(sl->snapshots, sl->num_snapshots, sizeof(struct snapshot *),
-               compare_snapshots);
+       return next_snapshot_time != 0;
 }
 
-void free_snapshot_list(struct snapshot_list *sl)
+static int next_snapshot_is_due(void)
 {
-       int i;
-       struct snapshot *s;
+       int64_t now = get_current_time();
 
-       FOR_EACH_SNAPSHOT(s, i, sl) {
-               free(s->name);
-               free(s);
+       if (!next_snapshot_time_is_valid())
+               next_snapshot_time = compute_next_snapshot_time();
+       if (next_snapshot_time <= now) {
+               DSS_DEBUG_LOG(("next snapshot: now\n"));
+               return 1;
        }
-       free(sl->interval_count);
-       free(sl->snapshots);
+       DSS_DEBUG_LOG(("next snapshot due in %" PRId64 " seconds\n",
+               next_snapshot_time - now));
+       return 0;
 }
 
-/**
- * Print a log message about the exit status of a child.
- */
-void log_termination_msg(pid_t pid, int status)
+static void pre_create_hook(void)
 {
-       if (WIFEXITED(status))
-               DSS_INFO_LOG("child %i exited. Exit status: %i\n", (int)pid,
-                       WEXITSTATUS(status));
-       else if (WIFSIGNALED(status))
-               DSS_NOTICE_LOG("child %i was killed by signal %i\n", (int)pid,
-                       WTERMSIG(status));
-       else
-               DSS_WARNING_LOG("child %i terminated abormally\n", (int)pid);
+       assert(snapshot_creation_status == HS_READY);
+       /* make sure that the next snapshot time will be recomputed */
+       invalidate_next_snapshot_time();
+       DSS_DEBUG_LOG(("executing %s\n", OPT_STRING_VAL(DSS, PRE_CREATE_HOOK)));
+       dss_exec_cmdline_pid(&create_pid, OPT_STRING_VAL(DSS, PRE_CREATE_HOOK));
+       snapshot_creation_status = HS_PRE_RUNNING;
 }
 
-int wait_for_process(pid_t pid, int *status)
+static void pre_remove_hook(struct snapshot *s, const char *why)
 {
-       int ret;
+       char *cmd;
 
-       DSS_DEBUG_LOG("Waiting for process %d to terminate\n", (int)pid);
-       for (;;) {
-               pause();
-               ret = next_signal();
-               if  (ret < 0)
-                       break;
-               if (!ret)
-                       continue;
-               if (ret == SIGCHLD) {
-                       ret = waitpid(pid, status, 0);
-                       if (ret >= 0)
-                               break;
-                       if (errno != EINTR) /* error */
-                               break;
-               }
-               DSS_WARNING_LOG("sending SIGTERM to pid %d\n", (int)pid);
-               kill(pid, SIGTERM);
-       }
-       if (ret < 0) {
-               ret = -ERRNO_TO_DSS_ERROR(errno);
-               make_err_msg("failed to wait for process %d", (int)pid);
-       } else
-               log_termination_msg(pid, *status);
-       return ret;
+       if (!s)
+               return;
+       DSS_DEBUG_LOG(("%s snapshot %s\n", why, s->name));
+       assert(snapshot_removal_status == HS_READY);
+       assert(remove_pid == 0);
+       assert(!snapshot_currently_being_removed);
+
+       snapshot_currently_being_removed = dss_malloc(sizeof(struct snapshot));
+       *snapshot_currently_being_removed = *s;
+       snapshot_currently_being_removed->name = dss_strdup(s->name);
+
+       cmd = make_message("%s %s/%s", OPT_STRING_VAL(DSS, PRE_REMOVE_HOOK),
+               OPT_STRING_VAL(DSS, DEST_DIR), s->name);
+       DSS_DEBUG_LOG(("executing %s\n", cmd));
+       dss_exec_cmdline_pid(&remove_pid, cmd);
+       free(cmd);
+       snapshot_removal_status = HS_PRE_RUNNING;
 }
 
-int remove_snapshot(struct snapshot *s, pid_t *pid)
+static int exec_rm(void)
 {
-       int fds[3] = {0, 0, 0};
+       struct snapshot *s = snapshot_currently_being_removed;
        char *new_name = being_deleted_name(s);
-       int ret = dss_rename(s->name, new_name);
-       char *argv[] = {"rm", "-rf", new_name, NULL};
+       char *argv[4];
+       int ret;
+
+       argv[0] = "rm";
+       argv[1] = "-rf";
+       argv[2] = new_name;
+       argv[3] = NULL;
 
+       assert(snapshot_removal_status == HS_PRE_SUCCESS);
+       assert(remove_pid == 0);
+
+       DSS_NOTICE_LOG(("removing %s (interval = %i)\n", s->name, s->interval));
+       ret = dss_rename(s->name, new_name);
        if (ret < 0)
                goto out;
-       DSS_NOTICE_LOG("removing %s (interval = %i)\n", s->name, s->interval);
-       ret = dss_exec(pid, argv[0], argv, fds);
+       dss_exec(&remove_pid, argv[0], argv);
+       snapshot_removal_status = HS_RUNNING;
 out:
        free(new_name);
        return ret;
 }
 
-int remove_redundant_snapshot(struct snapshot_list *sl, pid_t *pid)
+static int snapshot_is_being_created(struct snapshot *s)
+{
+       return s->creation_time == current_snapshot_creation_time;
+}
+
+static struct snapshot *find_orphaned_snapshot(struct snapshot_list *sl)
+{
+       struct snapshot *s;
+       int i;
+
+       DSS_DEBUG_LOG(("looking for old incomplete snapshots\n"));
+       FOR_EACH_SNAPSHOT(s, i, sl) {
+               if (snapshot_is_being_created(s))
+                       continue;
+               /*
+                * We know that no rm is currently running, so if s is marked
+                * as being deleted, a previously started rm must have failed.
+                */
+               if (s->flags & SS_BEING_DELETED)
+                       return s;
+
+               if (s->flags & SS_COMPLETE) /* good snapshot */
+                       continue;
+               /*
+                * This snapshot is incomplete and it is not the snapshot
+                * currently being created. However, we must not remove it if
+                * rsync is about to be restarted. As only the newest snapshot
+                * can be restarted, this snapshot is orphaned if it is not the
+                * newest snapshot or if we are not about to restart rsync.
+                */
+               if (get_newest_snapshot(sl) != s)
+                       return s;
+               if (snapshot_creation_status != HS_NEEDS_RESTART)
+                       return s;
+       }
+       /* no orphaned snapshots */
+       return NULL;
+}
+
+static int is_reference_snapshot(struct snapshot *s)
 {
-       int ret, i, interval;
+       if (!name_of_reference_snapshot)
+               return 0;
+       return strcmp(s->name, name_of_reference_snapshot)? 0 : 1;
+}
+
+/*
+ * return: 0: no redundant snapshots, 1: rm process started, negative: error
+ */
+static struct snapshot *find_redundant_snapshot(struct snapshot_list *sl)
+{
+       int i, interval;
        struct snapshot *s;
        unsigned missing = 0;
+       uint32_t N = OPT_UINT32_VAL(DSS, NUM_INTERVALS);
 
-       DSS_INFO_LOG("looking for intervals containing too many snapshots\n");
-       for (interval = conf.num_intervals_arg - 1; interval >= 0; interval--) {
-               unsigned keep = 1<<(conf.num_intervals_arg - interval - 1);
+       DSS_DEBUG_LOG(("looking for intervals containing too many snapshots\n"));
+       for (interval = N - 1; interval >= 0; interval--) {
+               unsigned keep = desired_number_of_snapshots(interval, N);
                unsigned num = sl->interval_count[interval];
                struct snapshot *victim = NULL, *prev = NULL;
                int64_t score = LONG_MAX;
 
                if (keep >= num)
                        missing += keep - num;
-               DSS_DEBUG_LOG("interval %i: keep: %u, have: %u, missing: %u\n",
-                       interval, keep, num, missing);
                if (keep + missing >= num)
                        continue;
                /* redundant snapshot in this interval, pick snapshot with lowest score */
                FOR_EACH_SNAPSHOT(s, i, sl) {
                        int64_t this_score;
 
-                       DSS_DEBUG_LOG("checking %s\n", s->name);
+                       if (snapshot_is_being_created(s))
+                               continue;
+                       if (is_reference_snapshot(s))
+                               continue;
                        if (s->interval > interval) {
                                prev = s;
                                continue;
@@ -397,7 +618,6 @@ int remove_redundant_snapshot(struct snapshot_list *sl, pid_t *pid)
                        /* check if s is a better victim */
                        this_score = s->creation_time - prev->creation_time;
                        assert(this_score >= 0);
-                       DSS_DEBUG_LOG("%s: score %lli\n", s->name, (long long)score);
                        if (this_score < score) {
                                score = this_score;
                                victim = s;
@@ -405,379 +625,1238 @@ int remove_redundant_snapshot(struct snapshot_list *sl, pid_t *pid)
                        prev = s;
                }
                assert(victim);
-               if (conf.dry_run_given) {
-                       dss_msg("%s would be removed (interval = %i)\n",
-                               victim->name, victim->interval);
-                       continue;
-               }
-               ret = remove_snapshot(victim, pid);
-               return ret < 0? ret : 1;
+               return victim;
        }
-       return 0;
+       return NULL;
 }
 
-int remove_old_snapshot(struct snapshot_list *sl, pid_t *pid)
+static struct snapshot *find_outdated_snapshot(struct snapshot_list *sl)
 {
-       int i, ret;
+       int i;
        struct snapshot *s;
 
-       DSS_INFO_LOG("looking for snapshots belonging to intervals greater than %d\n",
-               conf.num_intervals_arg);
+       DSS_DEBUG_LOG(("looking for snapshots belonging to intervals >= %d\n",
+               OPT_UINT32_VAL(DSS, NUM_INTERVALS)));
        FOR_EACH_SNAPSHOT(s, i, sl) {
-               if (s->interval <= conf.num_intervals_arg)
+               if (snapshot_is_being_created(s))
                        continue;
-               if (conf.dry_run_given) {
-                       dss_msg("%s would be removed (interval = %i)\n",
-                               s->name, s->interval);
+               if (is_reference_snapshot(s))
                        continue;
-               }
-               ret = remove_snapshot(s, pid);
-               if (ret < 0)
-                       return ret;
-               return 1;
+               if (s->interval < OPT_UINT32_VAL(DSS, NUM_INTERVALS))
+                       continue;
+               return s;
        }
-       return 0;
+       return NULL;
 }
 
-int wait_for_rm_process(pid_t pid)
+static struct snapshot *find_oldest_removable_snapshot(struct snapshot_list *sl)
 {
-       int status, es, ret = wait_for_process(pid, &status);
-       if (ret < 0)
-               return ret;
-       if (!WIFEXITED(status)) {
-               ret = E_INVOLUNTARY_EXIT;
-               make_err_msg("rm process %d died involuntary", (int)pid);
-               return ret;
-       }
-       es = WEXITSTATUS(status);
-       if (es) {
-               ret = -E_BAD_EXIT_CODE;
-               make_err_msg("rm process %d returned %d", (int)pid, es);
-               return ret;
+       int i, num_complete;
+       struct snapshot *s, *ref = NULL;
+
+       num_complete = num_complete_snapshots(sl);
+       if (num_complete <= OPT_UINT32_VAL(DSS, MIN_COMPLETE))
+               return NULL;
+       FOR_EACH_SNAPSHOT(s, i, sl) {
+               if (snapshot_is_being_created(s))
+                       continue;
+               if (is_reference_snapshot(s)) { /* avoid this one */
+                       ref = s;
+                       continue;
+               }
+               DSS_INFO_LOG(("oldest removable snapshot: %s\n", s->name));
+               return s;
        }
-       return 1;
+       assert(ref);
+       DSS_WARNING_LOG(("removing reference snapshot %s\n", ref->name));
+       return ref;
 }
 
-int com_run(void)
+static int rename_incomplete_snapshot(int64_t start)
 {
+       char *old_name;
        int ret;
+       int64_t now;
 
-       if (conf.dry_run_given) {
-               make_err_msg("dry_run not supported by this command");
-               return -E_SYNTAX;
-       }
-       ret = install_sighandler(SIGHUP);
+       /*
+        * We don't want the dss_rename() below to fail with EEXIST because the
+        * last complete snapshot was created (and completed) in the same
+        * second as this one.
+        */
+       while ((now = get_current_time()) == start)
+               sleep(1);
+       free(path_to_last_complete_snapshot);
+       ret = complete_name(start, now, &path_to_last_complete_snapshot);
        if (ret < 0)
                return ret;
-       return 42;
+       old_name = incomplete_name(start);
+       ret = dss_rename(old_name, path_to_last_complete_snapshot);
+       if (ret >= 0)
+               DSS_NOTICE_LOG(("%s -> %s\n", old_name,
+                       path_to_last_complete_snapshot));
+       free(old_name);
+       return ret;
 }
 
-int com_prune(void)
+static int try_to_free_disk_space(void)
 {
        int ret;
        struct snapshot_list sl;
-       pid_t pid;
+       struct snapshot *victim;
+       struct timeval now;
+       const char *why;
+       int low_disk_space;
 
-       for (;;) {
-               get_snapshot_list(&sl);
-               ret = remove_old_snapshot(&sl, &pid);
-               free_snapshot_list(&sl);
-               if (ret < 0)
-                       return ret;
-               if (!ret)
-                       break;
-               ret = wait_for_rm_process(pid);
-               if (ret < 0)
-                       goto out;
-       }
-       for (;;) {
-               get_snapshot_list(&sl);
-               ret = remove_redundant_snapshot(&sl, &pid);
-               free_snapshot_list(&sl);
-               if (ret < 0)
-                       return ret;
-               if (!ret)
-                       break;
-               ret = wait_for_rm_process(pid);
-               if (ret < 0)
-                       goto out;
+       ret = disk_space_low(NULL);
+       if (ret < 0)
+               return ret;
+       low_disk_space = ret;
+       gettimeofday(&now, NULL);
+       if (tv_diff(&next_removal_check, &now, NULL) > 0)
+               return 0;
+       if (!low_disk_space) {
+               if (OPT_GIVEN(DSS, KEEP_REDUNDANT))
+                       return 0;
+               if (snapshot_creation_status != HS_READY)
+                       return 0;
+               if (next_snapshot_is_due())
+                       return 0;
        }
-       return 1;
+       /*
+        * Idle and --keep_redundant not given, or low disk space. Look at
+        * existing snapshots.
+        */
+       dss_get_snapshot_list(&sl);
+       ret = 0;
+       /*
+        * Don't remove anything if there is free space and we have fewer
+        * snapshots than configured, plus one. This way there is always one
+        * snapshot that can be recycled.
+        */
+       if (!low_disk_space && sl.num_snapshots <=
+                       1 << OPT_UINT32_VAL(DSS, NUM_INTERVALS))
+               goto out;
+       why = "outdated";
+       victim = find_outdated_snapshot(&sl);
+       if (victim)
+               goto remove;
+       why = "redundant";
+       victim = find_redundant_snapshot(&sl);
+       if (victim)
+               goto remove;
+       why = "orphaned";
+       victim = find_orphaned_snapshot(&sl);
+       if (victim)
+               goto remove;
+       /* try harder only if disk space is low */
+       if (!low_disk_space)
+               goto out;
+       DSS_WARNING_LOG(("disk space low and nothing obvious to remove\n"));
+       why = "oldest";
+       victim = find_oldest_removable_snapshot(&sl);
+       if (victim)
+               goto remove;
+       DSS_CRIT_LOG(("uhuhu: disk space low and nothing to remove\n"));
+       ret = -ERRNO_TO_DSS_ERROR(ENOSPC);
+       goto out;
+remove:
+       pre_remove_hook(victim, why);
 out:
+       free_snapshot_list(&sl);
        return ret;
 }
 
-struct newest_snapshot_data {
-       char * newest_name;
-       int64_t newest_creation_time;
-       int64_t now;
-};
-
-int get_newest_complete(const char *dirname, void *private)
+static void post_create_hook(void)
 {
-       struct newest_snapshot_data *nsd = private;
-       struct snapshot s;
-       int ret = is_snapshot(dirname, nsd->now, &s);
-
-       if (ret <= 0)
-               return 1;
-       if (s.creation_time < nsd->newest_creation_time)
-               return 1;
-       nsd->newest_creation_time = s.creation_time;
-       free(nsd->newest_name);
-       nsd->newest_name = s.name;
-       return 1;
+       char *cmd = make_message("%s %s/%s",
+               OPT_STRING_VAL(DSS, POST_CREATE_HOOK),
+               OPT_STRING_VAL(DSS, DEST_DIR), path_to_last_complete_snapshot);
+       DSS_NOTICE_LOG(("executing %s\n", cmd));
+       dss_exec_cmdline_pid(&create_pid, cmd);
+       free(cmd);
+       snapshot_creation_status = HS_POST_RUNNING;
 }
 
-__malloc char *name_of_newest_complete_snapshot(void)
+static void post_remove_hook(void)
 {
-       struct newest_snapshot_data nsd = {
-               .now = get_current_time(),
-               .newest_creation_time = -1
-       };
-       for_each_subdir(get_newest_complete, &nsd);
-       return nsd.newest_name;
+       char *cmd;
+       struct snapshot *s = snapshot_currently_being_removed;
+
+       assert(s);
+
+       cmd = make_message("%s %s/%s", OPT_STRING_VAL(DSS, POST_REMOVE_HOOK),
+               OPT_STRING_VAL(DSS, DEST_DIR), s->name);
+       DSS_NOTICE_LOG(("executing %s\n", cmd));
+       dss_exec_cmdline_pid(&remove_pid, cmd);
+       free(cmd);
+       snapshot_removal_status = HS_POST_RUNNING;
 }
 
-void create_rsync_argv(char ***argv, int64_t *num)
+static void dss_kill(pid_t pid, int sig, const char *msg)
 {
-       char *logname, *newest = name_of_newest_complete_snapshot();
-       int i = 0, j;
-
-       *argv = dss_malloc((15 + conf.rsync_option_given) * sizeof(char *));
-       (*argv)[i++] = dss_strdup("rsync");
-       (*argv)[i++] = dss_strdup("-aq");
-       (*argv)[i++] = dss_strdup("--delete");
-       for (j = 0; j < conf.rsync_option_given; j++)
-               (*argv)[i++] = dss_strdup(conf.rsync_option_arg[j]);
-       if (newest) {
-               DSS_INFO_LOG("using %s as reference snapshot\n", newest);
-               (*argv)[i++] = make_message("--link-dest=../%s", newest);
-               free(newest);
-       } else
-               DSS_INFO_LOG("no previous snapshot found");
-       if (conf.exclude_patterns_given) {
-               (*argv)[i++] = dss_strdup("--exclude-from");
-               (*argv)[i++] = dss_strdup(conf.exclude_patterns_arg);
+       const char *signame, *process_name;
 
+       if (pid == 0)
+               return;
+       switch (sig) {
+       case SIGTERM: signame = "TERM"; break;
+       case SIGSTOP: signame = "STOP"; break;
+       case SIGCONT: signame = "CONT"; break;
+       default: signame = "????";
        }
-       logname = dss_logname();
-       if (conf.remote_user_given && !strcmp(conf.remote_user_arg, logname))
-               (*argv)[i++] = dss_strdup(conf.source_dir_arg);
-       else
-               (*argv)[i++] = make_message("%s@%s:%s/", conf.remote_user_given?
-                       conf.remote_user_arg : logname,
-                       conf.remote_host_arg, conf.source_dir_arg);
-       free(logname);
-       *num = get_current_time();
-       (*argv)[i++] = incomplete_name(*num);
-       (*argv)[i++] = NULL;
-       for (j = 0; j < i; j++)
-               DSS_DEBUG_LOG("argv[%d] = %s\n", j, (*argv)[j]);
+
+       if (pid == create_pid)
+               process_name = "create";
+       else if (pid == remove_pid)
+               process_name = "remove";
+       else process_name = "??????";
+
+       if (msg)
+               DSS_INFO_LOG(("%s\n", msg));
+       DSS_DEBUG_LOG(("sending signal %d (%s) to pid %d (%s process)\n",
+               sig, signame, (int)pid, process_name));
+       if (kill(pid, sig) >= 0)
+               return;
+       DSS_INFO_LOG(("failed to send signal %d (%s) to pid %d (%s process)\n",
+               sig, signame, (int)pid, process_name));
 }
 
-void free_rsync_argv(char **argv)
+static void stop_create_process(void)
 {
-       int i;
-       for (i = 0; argv[i]; i++)
-               free(argv[i]);
-       free(argv);
+       if (create_process_stopped)
+               return;
+       dss_kill(create_pid, SIGSTOP, "suspending create process");
+       create_process_stopped = 1;
 }
 
-int create_snapshot(char **argv, pid_t *pid)
+static void restart_create_process(void)
 {
-       int fds[3] = {0, 0, 0};
+       if (!create_process_stopped)
+               return;
+       dss_kill(create_pid, SIGCONT, "resuming create process");
+       create_process_stopped = 0;
+}
 
-       return dss_exec(pid, argv[0], argv, fds);
+/**
+ * Print a log message about the exit status of a child.
+ */
+static void log_termination_msg(pid_t pid, int status)
+{
+       if (WIFEXITED(status))
+               DSS_INFO_LOG(("child %i exited. Exit status: %i\n", (int)pid,
+                       WEXITSTATUS(status)));
+       else if (WIFSIGNALED(status))
+               DSS_NOTICE_LOG(("child %i was killed by signal %i\n", (int)pid,
+                       WTERMSIG(status)));
+       else
+               DSS_WARNING_LOG(("child %i terminated abormally\n", (int)pid));
 }
 
-int rename_incomplete_snapshot(int64_t start)
+static int wait_for_process(pid_t pid, int *status)
 {
-       char *old_name, *new_name;
        int ret;
 
-       ret = complete_name(start, get_current_time(), &new_name);
-       if (ret < 0)
-               return ret;
-       old_name = incomplete_name(start);
-       ret = dss_rename(old_name, new_name);
-       if (ret >= 0)
-               DSS_NOTICE_LOG("%s -> %s\n", old_name, new_name);
-       free(old_name);
-       free(new_name);
+       DSS_DEBUG_LOG(("Waiting for process %d to terminate\n", (int)pid));
+       for (;;) {
+               fd_set rfds;
+
+               FD_ZERO(&rfds);
+               FD_SET(signal_pipe, &rfds);
+               ret = dss_select(signal_pipe + 1, &rfds, NULL, NULL);
+               if (ret < 0)
+                       break;
+               ret = next_signal();
+               if (!ret)
+                       continue;
+               if (ret == SIGCHLD) {
+                       ret = waitpid(pid, status, 0);
+                       if (ret >= 0)
+                               break;
+                       if (errno != EINTR) { /* error */
+                               ret = -ERRNO_TO_DSS_ERROR(errno);
+                               break;
+                       }
+               }
+               /* SIGINT or SIGTERM */
+               dss_kill(pid, SIGTERM, "killing child process");
+       }
+       if (ret < 0)
+               DSS_ERROR_LOG(("failed to wait for process %d\n", (int)pid));
+       else
+               log_termination_msg(pid, *status);
        return ret;
 }
 
-int com_create(void)
+static void handle_pre_remove_exit(int status)
 {
-       int ret, status, es;
-       char **rsync_argv;
-       int64_t snapshot_num;
-       pid_t pid;
+       if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
+               snapshot_removal_status = HS_READY;
+               gettimeofday(&next_removal_check, NULL);
+               next_removal_check.tv_sec += 60;
+               return;
+       }
+       snapshot_removal_status = HS_PRE_SUCCESS;
+}
 
-       create_rsync_argv(&rsync_argv, &snapshot_num);
-       if (conf.dry_run_given) {
-               int i;
-               char *msg = NULL;
-               for (i = 0; rsync_argv[i]; i++) {
-                       char *tmp = msg;
-                       msg = make_message("%s%s%s", tmp? tmp : "",
-                               tmp? " " : "", rsync_argv[i]);
-                       free(tmp);
-               }
-               dss_msg("%s\n", msg);
-               free(msg);
-               return 1;
+static int handle_rm_exit(int status)
+{
+       if (!WIFEXITED(status)) {
+               snapshot_removal_status = HS_READY;
+               return -E_INVOLUNTARY_EXIT;
+       }
+       if (WEXITSTATUS(status)) {
+               snapshot_removal_status = HS_READY;
+               return -E_BAD_EXIT_CODE;
+       }
+       snapshot_removal_status = HS_SUCCESS;
+       return 1;
+}
+
+static void handle_post_remove_exit(void)
+{
+       snapshot_removal_status = HS_READY;
+}
+
+static int handle_remove_exit(int status)
+{
+       int ret;
+       struct snapshot *s = snapshot_currently_being_removed;
+
+       assert(s);
+       switch (snapshot_removal_status) {
+       case HS_PRE_RUNNING:
+               handle_pre_remove_exit(status);
+               ret = 1;
+               break;
+       case HS_RUNNING:
+               ret = handle_rm_exit(status);
+               break;
+       case HS_POST_RUNNING:
+               handle_post_remove_exit();
+               ret = 1;
+               break;
+       default:
+               ret = -E_BUG;
+       }
+       if (snapshot_removal_status == HS_READY) {
+               free(s->name);
+               free(s);
+               snapshot_currently_being_removed = NULL;
        }
-       DSS_NOTICE_LOG("creating snapshot %lli\n", (long long)snapshot_num);
-       ret = create_snapshot(rsync_argv, &pid);
+       remove_pid = 0;
+       return ret;
+}
+
+static int wait_for_remove_process(void)
+{
+       int status, ret;
+
+       assert(remove_pid);
+       assert(
+               snapshot_removal_status == HS_PRE_RUNNING ||
+               snapshot_removal_status == HS_RUNNING ||
+               snapshot_removal_status == HS_POST_RUNNING
+       );
+       ret = wait_for_process(remove_pid, &status);
        if (ret < 0)
+               return ret;
+       return handle_remove_exit(status);
+}
+
+static int handle_rsync_exit(int status)
+{
+       int es, ret;
+
+       if (!WIFEXITED(status)) {
+               DSS_ERROR_LOG(("rsync process %d died involuntary\n", (int)create_pid));
+               ret = -E_INVOLUNTARY_EXIT;
+               snapshot_creation_status = HS_READY;
                goto out;
-       ret = wait_for_process(pid, &status);
+       }
+       es = WEXITSTATUS(status);
+       /*
+        * Restart rsync on non-fatal errors:
+        * 24: Partial transfer due to vanished source files
+        */
+       if (es != 0 && es != 24) {
+               DSS_WARNING_LOG(("rsync exit code %d, error count %d\n",
+                       es, ++num_consecutive_rsync_errors));
+               if (!logfile) { /* called by com_run() */
+                       ret = -E_BAD_EXIT_CODE;
+                       goto out;
+               }
+               if (num_consecutive_rsync_errors >
+                               OPT_UINT32_VAL(RUN, MAX_RSYNC_ERRORS)) {
+                       ret = -E_TOO_MANY_RSYNC_ERRORS;
+                       snapshot_creation_status = HS_READY;
+                       goto out;
+               }
+               DSS_WARNING_LOG(("restarting rsync process\n"));
+               snapshot_creation_status = HS_NEEDS_RESTART;
+               next_snapshot_time = get_current_time() + 60;
+               ret = 1;
+               goto out;
+       }
+       num_consecutive_rsync_errors = 0;
+       ret = rename_incomplete_snapshot(current_snapshot_creation_time);
        if (ret < 0)
                goto out;
+       snapshot_creation_status = HS_SUCCESS;
+       free(name_of_reference_snapshot);
+       name_of_reference_snapshot = NULL;
+out:
+       create_process_stopped = 0;
+       return ret;
+}
+
+static int handle_pre_create_hook_exit(int status)
+{
+       int es, ret;
+       static int warn_count;
+
        if (!WIFEXITED(status)) {
-               ret = E_INVOLUNTARY_EXIT;
-               make_err_msg("rsync process %d died involuntary", (int)pid);
+               snapshot_creation_status = HS_READY;
+               ret = -E_INVOLUNTARY_EXIT;
                goto out;
        }
        es = WEXITSTATUS(status);
-       if (es != 0 && es != 23 && es != 24) {
-               ret = -E_BAD_EXIT_CODE;
-               make_err_msg("rsync process %d returned %d", (int)pid, es);
+       if (es) {
+               if (!warn_count--) {
+                       DSS_NOTICE_LOG(("pre_create_hook %s returned %d\n",
+                               OPT_STRING_VAL(DSS, PRE_CREATE_HOOK), es));
+                       DSS_NOTICE_LOG(("deferring snapshot creation...\n"));
+                       warn_count = 60; /* warn only once per hour */
+               }
+               next_snapshot_time = get_current_time() + 60;
+               snapshot_creation_status = HS_READY;
+               ret = 0;
                goto out;
        }
-       ret = rename_incomplete_snapshot(snapshot_num);
+       warn_count = 0;
+       snapshot_creation_status = HS_PRE_SUCCESS;
+       ret = 1;
 out:
-       free_rsync_argv(rsync_argv);
        return ret;
 }
 
-int com_ls(void)
+static int handle_sigchld(void)
+{
+       pid_t pid;
+       int status, ret = reap_child(&pid, &status);
+
+       if (ret <= 0)
+               return ret;
+
+       if (pid == create_pid) {
+               switch (snapshot_creation_status) {
+               case HS_PRE_RUNNING:
+                       ret = handle_pre_create_hook_exit(status);
+                       break;
+               case HS_RUNNING:
+                       ret = handle_rsync_exit(status);
+                       break;
+               case HS_POST_RUNNING:
+                       snapshot_creation_status = HS_READY;
+                       ret = 1;
+                       break;
+               default:
+                       DSS_EMERG_LOG(("BUG: create can't die in status %d\n",
+                               snapshot_creation_status));
+                       return -E_BUG;
+               }
+               create_pid = 0;
+               return ret;
+       }
+       if (pid == remove_pid) {
+               ret = handle_remove_exit(status);
+               if (ret < 0)
+                       return ret;
+               return ret;
+       }
+       DSS_EMERG_LOG(("BUG: unknown process %d died\n", (int)pid));
+       return -E_BUG;
+}
+
+/* also checks if . is a mountpoint, if --mountpoint was given */
+static int change_to_dest_dir(void)
+{
+       int ret;
+       const char *dd = OPT_STRING_VAL(DSS, DEST_DIR);
+       struct stat dot, dotdot;
+
+       DSS_INFO_LOG(("changing cwd to %s\n", dd));
+       if (chdir(dd) < 0) {
+               ret = -ERRNO_TO_DSS_ERROR(errno);
+               DSS_ERROR_LOG(("could not change cwd to %s\n", dd));
+               return ret;
+       }
+       if (!OPT_GIVEN(DSS, MOUNTPOINT))
+               return 0;
+       if (stat(".", &dot) < 0) {
+               ret = -ERRNO_TO_DSS_ERROR(errno);
+               DSS_ERROR_LOG(("could not stat .\n"));
+               return ret;
+       }
+       if (stat("..", &dotdot) < 0) {
+               ret = -ERRNO_TO_DSS_ERROR(errno);
+               DSS_ERROR_LOG(("could not stat ..\n"));
+               return ret;
+       }
+       if (dot.st_dev == dotdot.st_dev && dot.st_ino != dotdot.st_ino) {
+               DSS_ERROR_LOG(("mountpoint check failed for %s\n", dd));
+               return -E_MOUNTPOINT;
+       }
+       return 1;
+}
+
+static int check_config(void)
+{
+       int ret;
+       uint32_t unit_interval = OPT_UINT32_VAL(DSS, UNIT_INTERVAL);
+       uint32_t num_intervals = OPT_UINT32_VAL(DSS, NUM_INTERVALS);
+
+       if (unit_interval == 0) {
+               DSS_ERROR_LOG(("bad unit interval: %i\n", unit_interval));
+               return -E_INVALID_NUMBER;
+       }
+       DSS_DEBUG_LOG(("unit interval: %i day(s)\n", unit_interval));
+
+       if (num_intervals == 0 || num_intervals > 30) {
+               DSS_ERROR_LOG(("bad number of intervals: %i\n", num_intervals));
+               return -E_INVALID_NUMBER;
+       }
+       if (subcmd == CMD_PTR(RUN) || subcmd == CMD_PTR(CREATE))
+               if (!OPT_GIVEN(DSS, SOURCE_DIR)) {
+                       DSS_ERROR_LOG(("--source-dir required\n"));
+                       return -E_SYNTAX;
+               }
+       if (subcmd == CMD_PTR(RUN) || subcmd == CMD_PTR(CREATE)
+                       || subcmd == CMD_PTR(LS) || subcmd == CMD_PTR(PRUNE)) {
+               if (!OPT_GIVEN(DSS, DEST_DIR)) {
+                       DSS_ERROR_LOG(("--dest-dir required\n"));
+                       return -E_SYNTAX;
+               }
+               ret = change_to_dest_dir();
+               if (ret < 0)
+                       return ret;
+       }
+       DSS_DEBUG_LOG(("number of intervals: %i\n", num_intervals));
+       return 1;
+}
+
+static int lopsub_error(int lopsub_ret, char **errctx)
+{
+       const char *msg = lls_strerror(-lopsub_ret);
+       if (*errctx)
+               DSS_ERROR_LOG(("%s: %s\n", *errctx, msg));
+       else
+               DSS_ERROR_LOG(("%s\n", msg));
+       free(*errctx);
+       *errctx = NULL;
+       return -E_LOPSUB;
+}
+
+static int parse_config_file(bool sighup, const struct lls_command *cmd)
+{
+       int ret, fd = -1;
+       char *config_file = get_config_file_name();
+       struct stat statbuf;
+       void *map;
+       size_t sz;
+       int cf_argc;
+       char **cf_argv, *errctx = NULL;
+       struct lls_parse_result *cf_lpr, *merged_lpr, *clpr;
+       const char *subcmd_name;
+
+       ret = open(config_file, O_RDONLY);
+       if (ret < 0) {
+               if (errno != ENOENT || OPT_GIVEN(DSS, CONFIG_FILE)) {
+                       ret = -ERRNO_TO_DSS_ERROR(errno);
+                       DSS_ERROR_LOG(("config file %s can not be opened\n",
+                               config_file));
+                       goto out;
+               }
+               /* no config file -- nothing to do */
+               ret = 0;
+               goto success;
+       }
+       fd = ret;
+       ret = fstat(fd, &statbuf);
+       if (ret < 0) {
+               ret = -ERRNO_TO_DSS_ERROR(errno);
+               DSS_ERROR_LOG(("failed to stat config file %s\n", config_file));
+               goto close_fd;
+       }
+       sz = statbuf.st_size;
+       if (sz == 0) { /* config file is empty -- nothing to do */
+               ret = 0;
+               goto success;
+       }
+       map = mmap(NULL, sz, PROT_READ, MAP_PRIVATE, fd, 0);
+       if (map == MAP_FAILED) {
+               ret = -ERRNO_TO_DSS_ERROR(errno);
+               DSS_ERROR_LOG(("failed to mmap config file %s\n",
+                       config_file));
+               goto close_fd;
+       }
+       if (cmd == CMD_PTR(DSS))
+               subcmd_name = NULL;
+       else
+               subcmd_name = lls_command_name(cmd);
+       ret = lls_convert_config(map, sz, subcmd_name, &cf_argv, &errctx);
+       munmap(map, sz);
+       if (ret < 0) {
+               DSS_ERROR_LOG(("failed to convert config file %s\n",
+                       config_file));
+               ret = lopsub_error(ret, &errctx);
+               goto close_fd;
+       }
+       cf_argc = ret;
+       ret = lls_parse(cf_argc, cf_argv, cmd, &cf_lpr, &errctx);
+       lls_free_argv(cf_argv);
+       if (ret < 0) {
+               ret = lopsub_error(ret, &errctx);
+               goto close_fd;
+       }
+       clpr = cmd == CMD_PTR(DSS)? cmdline_lpr : cmdline_sublpr;
+       if (sighup) /* config file overrides command line */
+               ret = lls_merge(cf_lpr, clpr, cmd, &merged_lpr, &errctx);
+       else /* command line options overrride config file options */
+               ret = lls_merge(clpr, cf_lpr, cmd, &merged_lpr, &errctx);
+       lls_free_parse_result(cf_lpr, cmd);
+       if (ret < 0) {
+               ret = lopsub_error(ret, &errctx);
+               goto close_fd;
+       }
+       ret = 1;
+success:
+       assert(ret >= 0);
+       DSS_DEBUG_LOG(("loglevel: %d\n", OPT_UINT32_VAL(DSS, LOGLEVEL)));
+       if (cmd != CMD_PTR(DSS)) {
+               if (ret > 0) {
+                       if (sublpr != cmdline_sublpr)
+                               lls_free_parse_result(sublpr, cmd);
+                       sublpr = merged_lpr;
+               } else
+                       sublpr = cmdline_sublpr;
+       } else {
+               if (ret > 0) {
+                       if (lpr != cmdline_lpr)
+                               lls_free_parse_result(lpr, cmd);
+                       lpr = merged_lpr;
+               } else
+                       lpr = cmdline_lpr;
+       }
+close_fd:
+       if (fd >= 0)
+               close(fd);
+out:
+       free(config_file);
+       if (ret < 0)
+               DSS_EMERG_LOG(("%s\n", dss_strerror(-ret)));
+       return ret;
+}
+
+static int handle_sighup(void)
+{
+       int ret;
+
+       DSS_NOTICE_LOG(("SIGHUP, re-reading config\n"));
+       dump_dss_config("old");
+       ret = parse_config_file(true /* SIGHUP */, CMD_PTR(DSS));
+       if (ret < 0)
+               return ret;
+       ret = parse_config_file(true /* SIGHUP */, CMD_PTR(RUN));
+       if (ret < 0)
+               return ret;
+       ret = check_config();
+       if (ret < 0)
+               return ret;
+       close_log(logfile);
+       logfile = NULL;
+       if (OPT_GIVEN(RUN, DAEMON) || daemonized) {
+               logfile = open_log(OPT_STRING_VAL(RUN, LOGFILE));
+               log_welcome(OPT_UINT32_VAL(DSS, LOGLEVEL));
+               daemonized = true;
+       }
+       dump_dss_config("reloaded");
+       invalidate_next_snapshot_time();
+       return 1;
+}
+
+static void kill_children(void)
+{
+       restart_create_process();
+       dss_kill(create_pid, SIGTERM, NULL);
+       dss_kill(remove_pid, SIGTERM, NULL);
+}
+
+static int handle_signal(void)
+{
+       int sig, ret = next_signal();
+
+       if (ret <= 0)
+               goto out;
+       sig = ret;
+       switch (sig) {
+       case SIGINT:
+       case SIGTERM:
+               return -E_SIGNAL;
+       case SIGHUP:
+               ret = handle_sighup();
+               break;
+       case SIGCHLD:
+               ret = handle_sigchld();
+               break;
+       }
+out:
+       if (ret < 0)
+               DSS_ERROR_LOG(("%s\n", dss_strerror(-ret)));
+       return ret;
+}
+
+/*
+ * We can not use rsync locally if the local user is different from the remote
+ * user or if the src dir is not on the local host (or both).
+ */
+static int use_rsync_locally(char *logname)
+{
+       const char *h = OPT_STRING_VAL(DSS, REMOTE_HOST);
+
+       if (strcmp(h, "localhost") && strcmp(h, "127.0.0.1"))
+               return 0;
+       if (OPT_GIVEN(DSS, REMOTE_USER) &&
+                       strcmp(OPT_STRING_VAL(DSS, REMOTE_USER), logname))
+               return 0;
+       return 1;
+}
+
+static int rename_resume_snap(int64_t creation_time)
 {
-       int i;
        struct snapshot_list sl;
-       struct snapshot *s;
-       get_snapshot_list(&sl);
-       FOR_EACH_SNAPSHOT(s, i, &sl)
-               dss_msg("%u\t%s\n", s->interval, s->name);
+       struct snapshot *s = NULL;
+       char *new_name = incomplete_name(creation_time);
+       int ret;
+       const char *why;
+
+       sl.num_snapshots = 0;
+
+       ret = 0;
+       dss_get_snapshot_list(&sl);
+       /*
+        * Snapshot recycling: We first look at the newest snapshot. If this
+        * snapshot happens to be incomplete, the last rsync process was
+        * aborted and we reuse this one. Otherwise we look at snapshots which
+        * could be removed (outdated and redundant snapshots) as candidates
+        * for recycling. If no outdated/redundant snapshot exists, we check if
+        * there is an orphaned snapshot, which likely is useless anyway.
+        *
+        * Only if no existing snapshot is suitable for recycling, we bite the
+        * bullet and create a new one.
+        */
+       s = get_newest_snapshot(&sl);
+       if (!s) /* no snapshots at all */
+               goto out;
+       /* re-use last snapshot if it is incomplete */
+       why = "aborted";
+       if ((s->flags & SS_COMPLETE) == 0)
+               goto out;
+       why = "outdated";
+       s = find_outdated_snapshot(&sl);
+       if (s)
+               goto out;
+       why = "redundant";
+       s = find_redundant_snapshot(&sl);
+       if (s)
+               goto out;
+       why = "orphaned";
+       s = find_orphaned_snapshot(&sl);
+out:
+       if (s) {
+               DSS_NOTICE_LOG(("recycling %s snapshot %s\n", why, s->name));
+               ret = dss_rename(s->name, new_name);
+       }
+       if (ret >= 0)
+               DSS_NOTICE_LOG(("creating %s\n", new_name));
+       free(new_name);
        free_snapshot_list(&sl);
-       return 1;
+       return ret;
 }
 
-/* TODO: Unlink pid file */
-__noreturn void clean_exit(int status)
+static void create_rsync_argv(char ***argv, int64_t *num)
 {
-       //kill(0, SIGTERM);
-       free(dss_error_txt);
-       exit(status);
+       char *logname;
+       int i = 0, j, N = OPT_GIVEN(DSS, RSYNC_OPTION);
+       struct snapshot_list sl;
+       static bool seeded;
+
+       dss_get_snapshot_list(&sl);
+       assert(!name_of_reference_snapshot);
+       name_of_reference_snapshot = name_of_newest_complete_snapshot(&sl);
+       free_snapshot_list(&sl);
+
+       *argv = dss_malloc((15 + N) * sizeof(char *));
+       (*argv)[i++] = dss_strdup("rsync");
+       (*argv)[i++] = dss_strdup("-a");
+       (*argv)[i++] = dss_strdup("--delete");
+       if (!seeded) {
+               srandom((unsigned)time(NULL)); /* no need to be fancy here */
+               seeded = true;
+       }
+       if (1000 * (random() / (RAND_MAX + 1.0)) < OPT_UINT32_VAL(DSS, CHECKSUM)) {
+               DSS_NOTICE_LOG(("adding --checksum to rsync options\n"));
+               (*argv)[i++] = dss_strdup("--checksum");
+       }
+       for (j = 0; j < N; j++)
+               (*argv)[i++] = dss_strdup(lls_string_val(j,
+                       OPT_RESULT(DSS, RSYNC_OPTION)));
+       if (name_of_reference_snapshot) {
+               DSS_INFO_LOG(("using %s as reference\n", name_of_reference_snapshot));
+               (*argv)[i++] = make_message("--link-dest=../%s",
+                       name_of_reference_snapshot);
+       } else
+               DSS_INFO_LOG(("no suitable reference snapshot found\n"));
+       logname = dss_logname();
+       if (use_rsync_locally(logname))
+               (*argv)[i++] = dss_strdup(OPT_STRING_VAL(DSS, SOURCE_DIR));
+       else
+               (*argv)[i++] = make_message("%s@%s:%s/",
+                       OPT_GIVEN(DSS, REMOTE_USER)?
+                               OPT_STRING_VAL(DSS, REMOTE_USER) : logname,
+                       OPT_STRING_VAL(DSS, REMOTE_HOST),
+                       OPT_STRING_VAL(DSS, SOURCE_DIR));
+       free(logname);
+       *num = get_current_time();
+       (*argv)[i++] = incomplete_name(*num);
+       (*argv)[i++] = NULL;
+       for (j = 0; j < i; j++)
+               DSS_DEBUG_LOG(("argv[%d] = %s\n", j, (*argv)[j]));
+}
+
+static void free_rsync_argv(char **argv)
+{
+       int i;
+
+       if (!argv)
+               return;
+       for (i = 0; argv[i]; i++)
+               free(argv[i]);
+       free(argv);
+}
+
+static int create_snapshot(char **argv)
+{
+       int ret;
+
+       assert(argv);
+       ret = rename_resume_snap(current_snapshot_creation_time);
+       if (ret < 0)
+               return ret;
+       dss_exec(&create_pid, argv[0], argv);
+       snapshot_creation_status = HS_RUNNING;
+       return ret;
 }
 
-int read_config_file(void)
+static int select_loop(void)
 {
        int ret;
+       /* check every 60 seconds for free disk space */
+       struct timeval tv;
+       char **rsync_argv = NULL;
+
+       for (;;) {
+               fd_set rfds;
+               struct timeval *tvp;
+
+               if (remove_pid)
+                       tvp = NULL; /* sleep until rm hook/process dies */
+               else { /* sleep one minute */
+                       tv.tv_sec = 60;
+                       tv.tv_usec = 0;
+                       tvp = &tv;
+               }
+               FD_ZERO(&rfds);
+               FD_SET(signal_pipe, &rfds);
+               ret = dss_select(signal_pipe + 1, &rfds, NULL, tvp);
+               if (ret < 0)
+                       goto out;
+               if (FD_ISSET(signal_pipe, &rfds)) {
+                       ret = handle_signal();
+                       if (ret < 0)
+                               goto out;
+               }
+               if (remove_pid)
+                       continue;
+               if (snapshot_removal_status == HS_PRE_SUCCESS) {
+                       ret = exec_rm();
+                       if (ret < 0)
+                               goto out;
+                       continue;
+               }
+               if (snapshot_removal_status == HS_SUCCESS) {
+                       post_remove_hook();
+                       continue;
+               }
+               ret = try_to_free_disk_space();
+               if (ret < 0)
+                       goto out;
+               if (snapshot_removal_status != HS_READY) {
+                       stop_create_process();
+                       continue;
+               }
+               restart_create_process();
+               switch (snapshot_creation_status) {
+               case HS_READY:
+                       if (!next_snapshot_is_due())
+                               continue;
+                       pre_create_hook();
+                       continue;
+               case HS_PRE_RUNNING:
+               case HS_RUNNING:
+               case HS_POST_RUNNING:
+                       continue;
+               case HS_PRE_SUCCESS:
+                       if (!name_of_reference_snapshot) {
+                               free_rsync_argv(rsync_argv);
+                               create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
+                       }
+                       ret = create_snapshot(rsync_argv);
+                       if (ret < 0)
+                               goto out;
+                       continue;
+               case HS_NEEDS_RESTART:
+                       if (!next_snapshot_is_due())
+                               continue;
+                       ret = create_snapshot(rsync_argv);
+                       if (ret < 0)
+                               goto out;
+                       continue;
+               case HS_SUCCESS:
+                       post_create_hook();
+                       continue;
+               }
+       }
+out:
+       return ret;
+}
+
+static void exit_hook(int exit_code)
+{
+       pid_t pid;
+       char **argv, *tmp = dss_strdup(OPT_STRING_VAL(DSS, EXIT_HOOK));
+       unsigned n = split_args(tmp, &argv, " \t");
+
+       n++;
+       argv = dss_realloc(argv, (n + 1) * sizeof(char *));
+       argv[n - 1] = dss_strdup(dss_strerror(-exit_code));
+       argv[n] = NULL;
+       dss_exec(&pid, argv[0], argv);
+       free(argv[n - 1]);
+       free(argv);
+       free(tmp);
+}
+
+static void lock_dss_or_die(void)
+{
+       char *config_file = get_config_file_name();
+       int ret = lock_dss(config_file);
+
+       free(config_file);
+       if (ret < 0) {
+               DSS_EMERG_LOG(("failed to lock: %s\n", dss_strerror(-ret)));
+               exit(EXIT_FAILURE);
+       }
+}
+
+static int com_run(void)
+{
+       int ret, fd = -1;
        char *config_file;
-       struct stat statbuf;
+       pid_t pid;
 
-       if (conf.config_file_given)
-               config_file = dss_strdup(conf.config_file_arg);
-       else {
-               char *home = get_homedir();
-               config_file = make_message("%s/.dssrc", home);
-               free(home);
+       if (OPT_GIVEN(DSS, DRY_RUN)) {
+               DSS_ERROR_LOG(("dry run not supported by this command\n"));
+               return -E_SYNTAX;
        }
-       ret = stat(config_file, &statbuf);
-       if (ret && conf.config_file_given) {
-               ret = -ERRNO_TO_DSS_ERROR(errno);
-               make_err_msg("failed to stat config file %s", config_file);
-               goto out;
+       config_file = get_config_file_name();
+       ret = get_dss_pid(config_file, &pid);
+       free(config_file);
+       if (ret >= 0) {
+               DSS_ERROR_LOG(("pid %d\n", (int)pid));
+               return -E_ALREADY_RUNNING;
        }
-       if (!ret) {
-               struct cmdline_parser_params params = {
-                       .override = 0,
-                       .initialize = 0,
-                       .check_required = 0,
-                       .check_ambiguity = 0
-               };
-               cmdline_parser_config_file(config_file, &conf, &params);
-       }
-       if (!conf.source_dir_given || !conf.dest_dir_given) {
-               ret = -E_SYNTAX;
-               make_err_msg("you need to specify both source_dir and dest_dir");
+       if (OPT_GIVEN(RUN, DAEMON)) {
+               fd = daemon_init();
+               daemonized = true;
+               logfile = open_log(OPT_STRING_VAL(RUN, LOGFILE));
+       }
+       lock_dss_or_die();
+       dump_dss_config("startup");
+       ret = install_sighandler(SIGHUP);
+       if (ret < 0)
+               return ret;
+       if (fd >= 0) {
+               ret = write(fd, "\0", 1);
+               if (ret != 1) {
+                       DSS_ERROR_LOG(("write to daemon pipe returned %d\n",
+                               ret));
+                       if (ret < 0)
+                               return -ERRNO_TO_DSS_ERROR(errno);
+                       return -E_BUG;
+               }
+       }
+       ret = select_loop();
+       if (ret >= 0) /* impossible */
+               ret = -E_BUG;
+       kill_children();
+       exit_hook(ret);
+       while (wait(NULL) >= 0 || errno != ECHILD)
+               ; /* still have children to wait for */
+       return ret;
+}
+EXPORT_CMD_HANDLER(run);
+
+static int com_prune(void)
+{
+       int ret;
+       struct snapshot_list sl;
+       struct snapshot *victim;
+       struct disk_space ds;
+       const char *why;
+
+       lock_dss_or_die();
+       ret = get_disk_space(".", &ds);
+       if (ret < 0)
+               return ret;
+       log_disk_space(&ds);
+       dss_get_snapshot_list(&sl);
+       why = "outdated";
+       victim = find_outdated_snapshot(&sl);
+       if (victim)
+               goto rm;
+       why = "redundant";
+       victim = find_redundant_snapshot(&sl);
+       if (victim)
+               goto rm;
+       ret = 0;
+       goto out;
+rm:
+       if (OPT_GIVEN(DSS, DRY_RUN)) {
+               dss_msg("%s snapshot %s (interval = %i)\n",
+                       why, victim->name, victim->interval);
+               ret = 0;
                goto out;
        }
+       pre_remove_hook(victim, why);
+       if (snapshot_removal_status == HS_PRE_RUNNING) {
+               ret = wait_for_remove_process();
+               if (ret < 0)
+                       goto out;
+               if (snapshot_removal_status != HS_PRE_SUCCESS)
+                       goto out;
+       }
+       ret = exec_rm();
+       if (ret < 0)
+               goto out;
+       ret = wait_for_remove_process();
+       if (ret < 0)
+               goto out;
+       if (snapshot_removal_status != HS_SUCCESS)
+               goto out;
+       post_remove_hook();
+       if (snapshot_removal_status != HS_POST_RUNNING)
+               goto out;
+       ret = wait_for_remove_process();
+       if (ret < 0)
+               goto out;
        ret = 1;
 out:
-       free(config_file);
+       free_snapshot_list(&sl);
        return ret;
 }
+EXPORT_CMD_HANDLER(prune);
 
-int check_config(void)
+static int com_create(void)
 {
-       if (conf.unit_interval_arg <= 0) {
-               make_err_msg("bad unit interval: %i", conf.unit_interval_arg);
-               return -E_INVALID_NUMBER;
+       int ret, status;
+       char **rsync_argv;
+
+       lock_dss_or_die();
+       if (OPT_GIVEN(DSS, DRY_RUN)) {
+               int i;
+               char *msg = NULL;
+               create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
+               for (i = 0; rsync_argv[i]; i++) {
+                       char *tmp = msg;
+                       msg = make_message("%s%s%s", tmp? tmp : "",
+                               tmp? " " : "", rsync_argv[i]);
+                       free(tmp);
+               }
+               free_rsync_argv(rsync_argv);
+               dss_msg("%s\n", msg);
+               free(msg);
+               return 1;
        }
-       DSS_DEBUG_LOG("unit interval: %i day(s)\n", conf.unit_interval_arg);
-       if (conf.num_intervals_arg <= 0) {
-               make_err_msg("bad number of intervals  %i", conf.num_intervals_arg);
-               return -E_INVALID_NUMBER;
+       pre_create_hook();
+       if (create_pid) {
+               ret = wait_for_process(create_pid, &status);
+               if (ret < 0)
+                       return ret;
+               ret = handle_pre_create_hook_exit(status);
+               if (ret <= 0) /* error, or pre-create failed */
+                       return ret;
        }
-       DSS_DEBUG_LOG("number of intervals: %i\n", conf.num_intervals_arg);
+       create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
+       ret = create_snapshot(rsync_argv);
+       if (ret < 0)
+               goto out;
+       ret = wait_for_process(create_pid, &status);
+       if (ret < 0)
+               goto out;
+       ret = handle_rsync_exit(status);
+       if (ret < 0)
+               goto out;
+       post_create_hook();
+       if (create_pid)
+               ret = wait_for_process(create_pid, &status);
+out:
+       free_rsync_argv(rsync_argv);
+       return ret;
+}
+EXPORT_CMD_HANDLER(create);
+
+static int com_ls(void)
+{
+       int i;
+       struct snapshot_list sl;
+       struct snapshot *s;
+       int64_t now = get_current_time();
+
+       dss_get_snapshot_list(&sl);
+       FOR_EACH_SNAPSHOT(s, i, &sl) {
+               int64_t d;
+               if (s->flags & SS_COMPLETE)
+                       d = (s->completion_time - s->creation_time) / 60;
+               else
+                       d = (now - s->creation_time) / 60;
+               dss_msg("%u\t%s\t%3" PRId64 ":%02" PRId64 "\n", s->interval,
+                       s->name, d / 60, d % 60);
+       }
+       free_snapshot_list(&sl);
        return 1;
 }
+EXPORT_CMD_HANDLER(ls);
 
-static void setup_signal_handling(void)
+static int com_configtest(void)
+{
+       printf("Syntax Ok\n");
+       return 0;
+}
+EXPORT_CMD_HANDLER(configtest);
+
+static int setup_signal_handling(void)
 {
        int ret;
 
-       DSS_NOTICE_LOG("setting up signal handlers\n");
+       DSS_INFO_LOG(("setting up signal handlers\n"));
        signal_pipe = signal_init(); /* always successful */
        ret = install_sighandler(SIGINT);
        if (ret < 0)
-               goto err;
+               return ret;
        ret = install_sighandler(SIGTERM);
        if (ret < 0)
-               goto err;
-       ret = install_sighandler(SIGCHLD);
-       if (ret < 0)
-               goto err;
-       return;
-err:
-       DSS_EMERG_LOG("could not install signal handlers\n");
-       exit(EXIT_FAILURE);
+               return ret;
+       return install_sighandler(SIGCHLD);
+}
+
+static void handle_version_and_help(void)
+{
+       char *txt;
+
+       if (OPT_GIVEN(DSS, DETAILED_HELP))
+               txt = lls_long_help(CMD_PTR(DSS));
+       else if (OPT_GIVEN(DSS, HELP))
+               txt = lls_short_help(CMD_PTR(DSS));
+       else if (OPT_GIVEN(DSS, VERSION))
+               txt = make_message("%s\n", VERSION_STRING);
+       else
+               return;
+       printf("%s", txt);
+       free(txt);
+       exit(EXIT_SUCCESS);
 }
 
+static void show_subcommand_summary(void)
+{
+       const struct lls_command *cmd;
+       int i;
+
+       printf("Available subcommands:\n");
+       for (i = 1; (cmd = lls_cmd(i, dss_suite)); i++) {
+               const char *name = lls_command_name(cmd);
+               const char *purpose = lls_purpose(cmd);
+               printf("%-11s%s\n", name, purpose);
+       }
+       exit(EXIT_SUCCESS);
+}
 
 int main(int argc, char **argv)
 {
        int ret;
+       char *errctx = NULL;
+       unsigned num_inputs;
+       const struct dss_user_data *ud;
 
-       cmdline_parser(argc, argv, &conf); /* aborts on errors */
-       if (conf.inputs_num) {
-               ret = -E_SYNTAX;
-               make_err_msg("additional non-options given");
+       ret = lls_parse(argc, argv, CMD_PTR(DSS), &cmdline_lpr, &errctx);
+       if (ret < 0) {
+               ret = lopsub_error(ret, &errctx);
                goto out;
        }
-       ret = read_config_file();
+       lpr = cmdline_lpr;
+       ret = parse_config_file(false /* no SIGHUP */, CMD_PTR(DSS));
+       if (ret < 0)
+               goto out;
+       handle_version_and_help();
+       num_inputs = lls_num_inputs(lpr);
+       if (num_inputs == 0)
+               show_subcommand_summary();
+       ret = lls_lookup_subcmd(argv[argc - num_inputs], dss_suite, &errctx);
+       if (ret < 0) {
+               ret = lopsub_error(ret, &errctx);
+               goto out;
+       }
+       subcmd = lls_cmd(ret, dss_suite);
+       ret = lls_parse(num_inputs, argv + argc - num_inputs, subcmd,
+               &cmdline_sublpr, &errctx);
+       if (ret < 0) {
+               ret = lopsub_error(ret, &errctx);
+               goto out;
+       }
+       sublpr = cmdline_sublpr;
+       ret = parse_config_file(false /* no SIGHUP */, subcmd);
        if (ret < 0)
                goto out;
        ret = check_config();
        if (ret < 0)
                goto out;
-       if (conf.logfile_given) {
-               logfile = open_log(conf.logfile_arg);
-               log_welcome(conf.loglevel_arg);
-       }
-       ret = dss_chdir(conf.dest_dir_arg);
+       ret = setup_signal_handling();
        if (ret < 0)
                goto out;
-       if (conf.daemon_given)
-               daemon_init();
-       setup_signal_handling();
-       ret = call_command_handler();
+       ud = lls_user_data(subcmd);
+       ret = ud->handler();
+       signal_shutdown();
 out:
-       if (ret < 0)
-               log_err_msg(EMERG, -ret);
-       clean_exit(ret >= 0? EXIT_SUCCESS : EXIT_FAILURE);
+       if (ret < 0) {
+               if (errctx)
+                       DSS_ERROR_LOG(("%s\n", errctx));
+               DSS_EMERG_LOG(("%s\n", dss_strerror(-ret)));
+       }
+       free(errctx);
+       lls_free_parse_result(lpr, CMD_PTR(DSS));
+       if (lpr != cmdline_lpr)
+               lls_free_parse_result(cmdline_lpr, CMD_PTR(DSS));
+       lls_free_parse_result(sublpr, subcmd);
+       if (sublpr != cmdline_sublpr)
+               lls_free_parse_result(cmdline_sublpr, subcmd);
+       exit(ret >= 0? EXIT_SUCCESS : EXIT_FAILURE);
 }