Merge commit 'fml/master'
[dss.git] / dss.c
1 #include <string.h>
2 #include <stdlib.h>
3 #include <stdarg.h>
4 #include <assert.h>
5 #include <errno.h>
6 #include <sys/types.h>
7 #include <signal.h>
8 #include <ctype.h>
9 #include <sys/stat.h>
10 #include <unistd.h>
11 #include <inttypes.h>
12 #include <sys/time.h>
13 #include <time.h>
14 #include <sys/wait.h>
15 #include <fnmatch.h>
16 #include <limits.h>
17
18
19 #include "gcc-compat.h"
20 #include "cmdline.h"
21 #include "log.h"
22 #include "string.h"
23 #include "error.h"
24 #include "fd.h"
25 #include "exec.h"
26 #include "daemon.h"
27 #include "signal.h"
28 #include "df.h"
29 #include "time.h"
30 #include "snap.h"
31
32 /** Command line and config file options. */
33 static struct gengetopt_args_info conf;
34 /** Non-NULL if we log to a file. */
35 static FILE *logfile;
36 /** The read end of the signal pipe */
37 static int signal_pipe;
38 /** Process id of current rsync process. */
39 static pid_t rsync_pid;
40 /** Whether the rsync process is currently stopped */
41 static int rsync_stopped;
42 /** Process id of current rm process. */
43 static pid_t rm_pid;
44 /** When the next snapshot is due. */
45 static struct timeval next_snapshot_time;
46 /** The pid of the pre-create hook. */
47 static pid_t pre_create_hook_pid;
48 /** The pid of the post-create hook. */
49 static pid_t post_create_hook_pid;
50 /** Creation time of the snapshot currently being created. */
51 static int64_t current_snapshot_creation_time;
52 /** Needed by the post-create hook. */
53 static char *path_to_last_complete_snapshot;
54 /** \sa \ref snap.h for details. */
55 static unsigned snapshot_creation_status;
56
57
58 DEFINE_DSS_ERRLIST;
59
60
61 /* a litte cpp magic helps to DRY */
62 #define COMMANDS \
63         COMMAND(ls) \
64         COMMAND(create) \
65         COMMAND(prune) \
66         COMMAND(run)
67 #define COMMAND(x) static int com_ ##x(void);
68 COMMANDS
69 #undef COMMAND
70 #define COMMAND(x) if (conf.x ##_given) return com_ ##x();
71 static int call_command_handler(void)
72 {
73         COMMANDS
74         DSS_EMERG_LOG("BUG: did not find command handler\n");
75         exit(EXIT_FAILURE);
76 }
77 #undef COMMAND
78 #undef COMMANDS
79
80 /**
81  * The log function of dss.
82  *
83  * \param ll Loglevel.
84  * \param fml Usual format string.
85  *
86  * All DSS_XXX_LOG() macros use this function.
87  */
88 __printf_2_3 void dss_log(int ll, const char* fmt,...)
89 {
90         va_list argp;
91         FILE *outfd;
92         struct tm *tm;
93         time_t t1;
94         char str[255] = "";
95
96         if (ll < conf.loglevel_arg)
97                 return;
98         outfd = logfile? logfile : stderr;
99         time(&t1);
100         tm = localtime(&t1);
101         strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
102         fprintf(outfd, "%s ", str);
103         if (conf.loglevel_arg <= INFO)
104                 fprintf(outfd, "%i: ", ll);
105         va_start(argp, fmt);
106         vfprintf(outfd, fmt, argp);
107         va_end(argp);
108 }
109
110 /**
111  * Print a message either to stdout or to the log file.
112  */
113 static __printf_1_2 void dss_msg(const char* fmt,...)
114 {
115         FILE *outfd = conf.daemon_given? logfile : stdout;
116         va_list argp;
117         va_start(argp, fmt);
118         vfprintf(outfd, fmt, argp);
119         va_end(argp);
120 }
121
122 /* TODO: Also consider number of inodes. */
123 static int disk_space_low(void)
124 {
125         struct disk_space ds;
126         int ret = get_disk_space(".", &ds);
127
128         if (ret < 0)
129                 return ret;
130         if (conf.min_free_mb_arg)
131                 if (ds.free_mb < conf.min_free_mb_arg)
132                         return 1;
133         if (conf.min_free_percent_arg)
134                 if (ds.percent_free < conf.min_free_percent_arg)
135                         return 1;
136         if (conf.min_free_percent_inodes_arg)
137                 if (ds.percent_free_inodes < conf.min_free_percent_inodes_arg)
138                         return 1;
139         return 0;
140 }
141
142 static void dss_get_snapshot_list(struct snapshot_list *sl)
143 {
144         get_snapshot_list(sl, conf.unit_interval_arg, conf.num_intervals_arg);
145 }
146
147 static void compute_next_snapshot_time(void)
148 {
149         struct timeval now, unit_interval = {.tv_sec = 24 * 3600 * conf.unit_interval_arg},
150                 tmp, diff;
151         int64_t x = 0;
152         unsigned wanted = desired_number_of_snapshots(0, conf.num_intervals_arg),
153                 num_complete_snapshots = 0;
154         int i, ret;
155         struct snapshot *s = NULL;
156         struct snapshot_list sl;
157
158         assert(snapshot_creation_status == SCS_READY);
159         current_snapshot_creation_time = 0;
160         dss_get_snapshot_list(&sl);
161         FOR_EACH_SNAPSHOT(s, i, &sl) {
162                 if (!(s->flags & SS_COMPLETE))
163                         continue;
164                 num_complete_snapshots++;
165                 x += s->completion_time - s->creation_time;
166         }
167         assert(x >= 0);
168         if (num_complete_snapshots)
169                 x /= num_complete_snapshots; /* avg time to create one snapshot */
170         x *= wanted; /* time to create all snapshots in interval 0 */
171         tmp.tv_sec = x;
172         tmp.tv_usec = 0;
173         ret = tv_diff(&unit_interval, &tmp, &diff); /* total sleep time per unit interval */
174         gettimeofday(&now, NULL);
175         if (ret < 0 || !s)
176                 goto min_sleep;
177         tv_divide(wanted, &diff, &tmp); /* sleep time betweeen two snapshots */
178         diff.tv_sec = s->completion_time;
179         diff.tv_usec = 0;
180         tv_add(&diff, &tmp, &next_snapshot_time);
181         if (tv_diff(&now, &next_snapshot_time, NULL) < 0)
182                 goto out;
183 min_sleep:
184         next_snapshot_time = now;
185         next_snapshot_time.tv_sec += 60;
186 out:
187         free_snapshot_list(&sl);
188 }
189
190
191 static int remove_snapshot(struct snapshot *s)
192 {
193         int fds[3] = {0, 0, 0};
194         assert(!rm_pid);
195         char *new_name = being_deleted_name(s);
196         int ret = dss_rename(s->name, new_name);
197         char *argv[] = {"rm", "-rf", new_name, NULL};
198
199         if (ret < 0)
200                 goto out;
201         DSS_NOTICE_LOG("removing %s (interval = %i)\n", s->name, s->interval);
202         ret = dss_exec(&rm_pid, argv[0], argv, fds);
203 out:
204         free(new_name);
205         return ret;
206 }
207
208 /*
209  * return: 0: no redundant snapshots, 1: rm process started, negative: error
210  */
211 static int remove_redundant_snapshot(struct snapshot_list *sl)
212 {
213         int ret, i, interval;
214         struct snapshot *s;
215         unsigned missing = 0;
216
217         DSS_INFO_LOG("looking for intervals containing too many snapshots\n");
218         for (interval = conf.num_intervals_arg - 1; interval >= 0; interval--) {
219                 unsigned keep = desired_number_of_snapshots(interval, conf.num_intervals_arg);
220                 unsigned num = sl->interval_count[interval];
221                 struct snapshot *victim = NULL, *prev = NULL;
222                 int64_t score = LONG_MAX;
223
224                 if (keep >= num)
225                         missing += keep - num;
226 //              DSS_DEBUG_LOG("interval %i: keep: %u, have: %u, missing: %u\n",
227 //                      interval, keep, num, missing);
228                 if (keep + missing >= num)
229                         continue;
230                 /* redundant snapshot in this interval, pick snapshot with lowest score */
231                 FOR_EACH_SNAPSHOT(s, i, sl) {
232                         int64_t this_score;
233
234                         //DSS_DEBUG_LOG("checking %s\n", s->name);
235                         if (s->interval > interval) {
236                                 prev = s;
237                                 continue;
238                         }
239                         if (s->interval < interval)
240                                 break;
241                         if (!victim) {
242                                 victim = s;
243                                 prev = s;
244                                 continue;
245                         }
246                         assert(prev);
247                         /* check if s is a better victim */
248                         this_score = s->creation_time - prev->creation_time;
249                         assert(this_score >= 0);
250                         //DSS_DEBUG_LOG("%s: score %lli\n", s->name, (long long)score);
251                         if (this_score < score) {
252                                 score = this_score;
253                                 victim = s;
254                         }
255                         prev = s;
256                 }
257                 assert(victim);
258                 if (conf.dry_run_given) {
259                         dss_msg("%s would be removed (interval = %i)\n",
260                                 victim->name, victim->interval);
261                         continue;
262                 }
263                 ret = remove_snapshot(victim);
264                 return ret < 0? ret : 1;
265         }
266         return 0;
267 }
268
269 static int remove_outdated_snapshot(struct snapshot_list *sl)
270 {
271         int i, ret;
272         struct snapshot *s;
273
274         DSS_INFO_LOG("looking for snapshots belonging to intervals greater than %d\n",
275                 conf.num_intervals_arg);
276         FOR_EACH_SNAPSHOT(s, i, sl) {
277                 if (s->interval <= conf.num_intervals_arg)
278                         continue;
279                 if (conf.dry_run_given) {
280                         dss_msg("%s would be removed (interval = %i)\n",
281                                 s->name, s->interval);
282                         continue;
283                 }
284                 ret = remove_snapshot(s);
285                 if (ret < 0)
286                         return ret;
287                 return 1;
288         }
289         return 0;
290 }
291
292 static int remove_oldest_snapshot(struct snapshot_list *sl)
293 {
294         struct snapshot *s = get_oldest_snapshot(sl);
295
296         if (!s) /* no snapshot found */
297                 return 0;
298         DSS_INFO_LOG("oldest snapshot: %s\n", s->name);
299         if (s->creation_time == current_snapshot_creation_time)
300                 return 0; /* do not remove the snapshot currently being created */
301         return remove_snapshot(s);
302 }
303
304 static int rename_incomplete_snapshot(int64_t start)
305 {
306         char *old_name;
307         int ret;
308
309         free(path_to_last_complete_snapshot);
310         ret = complete_name(start, get_current_time(),
311                 &path_to_last_complete_snapshot);
312         if (ret < 0)
313                 return ret;
314         old_name = incomplete_name(start);
315         ret = dss_rename(old_name, path_to_last_complete_snapshot);
316         if (ret >= 0)
317                 DSS_NOTICE_LOG("%s -> %s\n", old_name,
318                         path_to_last_complete_snapshot);
319         free(old_name);
320         return ret;
321 }
322
323 static int try_to_free_disk_space(int low_disk_space)
324 {
325         int ret;
326         struct snapshot_list sl;
327
328         dss_get_snapshot_list(&sl);
329         ret = remove_outdated_snapshot(&sl);
330         if (ret) /* error, or we are removing something */
331                 goto out;
332         /* no outdated snapshot */
333         ret = remove_redundant_snapshot(&sl);
334         if (ret)
335                 goto out;
336         ret = 0;
337         if (!low_disk_space)
338                 goto out;
339         DSS_WARNING_LOG("disk space low and nothing obvious to remove\n");
340         ret = remove_oldest_snapshot(&sl);
341         if (ret)
342                 goto out;
343         DSS_CRIT_LOG("uhuhu: not enough disk space for a single snapshot\n");
344         ret= -ENOSPC;
345 out:
346         free_snapshot_list(&sl);
347         return ret;
348 }
349
350 static int pre_create_hook(void)
351 {
352         int ret, fds[3] = {0, 0, 0};
353
354         if (!conf.pre_create_hook_given) {
355                 snapshot_creation_status = SCS_PRE_HOOK_SUCCESS;
356                 return 0;
357         }
358         DSS_NOTICE_LOG("executing %s\n", conf.pre_create_hook_arg);
359         ret = dss_exec_cmdline_pid(&pre_create_hook_pid,
360                 conf.pre_create_hook_arg, fds);
361         if (ret < 0)
362                 return ret;
363         snapshot_creation_status = SCS_PRE_HOOK_RUNNING;
364         return ret;
365 }
366
367 static int post_create_hook(void)
368 {
369         int ret, fds[3] = {0, 0, 0};
370         char *cmd;
371
372         if (!conf.post_create_hook_given) {
373                 snapshot_creation_status = SCS_READY;
374                 compute_next_snapshot_time();
375                 return 0;
376         }
377         cmd = make_message("%s %s", conf.post_create_hook_arg,
378                 path_to_last_complete_snapshot);
379         DSS_NOTICE_LOG("executing %s\n", cmd);
380         ret = dss_exec_cmdline_pid(&post_create_hook_pid, cmd, fds);
381         free(cmd);
382         if (ret < 0)
383                 return ret;
384         snapshot_creation_status = SCS_POST_HOOK_RUNNING;
385         return ret;
386 }
387
388 static void kill_process(pid_t pid)
389 {
390         if (!pid)
391                 return;
392         DSS_WARNING_LOG("sending SIGTERM to pid %d\n", (int)pid);
393         kill(pid, SIGTERM);
394 }
395
396 static void stop_rsync_process(void)
397 {
398         if (!rsync_pid || rsync_stopped)
399                 return;
400         kill(SIGSTOP, rsync_pid);
401         rsync_stopped = 1;
402 }
403
404 static void restart_rsync_process(void)
405 {
406         if (!rsync_pid || !rsync_stopped)
407                 return;
408         kill (SIGCONT, rsync_pid);
409         rsync_stopped = 0;
410 }
411
412
413 /**
414  * Print a log message about the exit status of a child.
415  */
416 static void log_termination_msg(pid_t pid, int status)
417 {
418         if (WIFEXITED(status))
419                 DSS_INFO_LOG("child %i exited. Exit status: %i\n", (int)pid,
420                         WEXITSTATUS(status));
421         else if (WIFSIGNALED(status))
422                 DSS_NOTICE_LOG("child %i was killed by signal %i\n", (int)pid,
423                         WTERMSIG(status));
424         else
425                 DSS_WARNING_LOG("child %i terminated abormally\n", (int)pid);
426 }
427
428 static int wait_for_process(pid_t pid, int *status)
429 {
430         int ret;
431
432         DSS_DEBUG_LOG("Waiting for process %d to terminate\n", (int)pid);
433         for (;;) {
434                 fd_set rfds;
435
436                 FD_ZERO(&rfds);
437                 FD_SET(signal_pipe, &rfds);
438                 ret = dss_select(signal_pipe + 1, &rfds, NULL, NULL);
439                 if (ret < 0)
440                         break;
441                 ret = next_signal();
442                 if (!ret)
443                         continue;
444                 if (ret == SIGCHLD) {
445                         ret = waitpid(pid, status, 0);
446                         if (ret >= 0)
447                                 break;
448                         if (errno != EINTR) { /* error */
449                                 ret = -ERRNO_TO_DSS_ERROR(errno);
450                                 break;
451                         }
452                 }
453                 /* SIGINT or SIGTERM */
454                 DSS_WARNING_LOG("sending SIGTERM to pid %d\n", (int)pid);
455                 kill(pid, SIGTERM);
456         }
457         if (ret < 0)
458                 DSS_ERROR_LOG("failed to wait for process %d\n", (int)pid);
459         else
460                 log_termination_msg(pid, *status);
461         return ret;
462 }
463
464 static int handle_rm_exit(int status)
465 {
466         rm_pid = 0;
467         if (!WIFEXITED(status))
468                 return -E_INVOLUNTARY_EXIT;
469         if (WEXITSTATUS(status))
470                 return -E_BAD_EXIT_CODE;
471         return 1;
472 }
473
474 static int wait_for_rm_process(void)
475 {
476         int status, ret = wait_for_process(rm_pid, &status);
477
478         if (ret < 0)
479                 return ret;
480         return handle_rm_exit(status);
481 }
482
483 static int handle_rsync_exit(int status)
484 {
485         int es, ret;
486
487         if (!WIFEXITED(status)) {
488                 DSS_ERROR_LOG("rsync process %d died involuntary\n", (int)rsync_pid);
489                 ret = -E_INVOLUNTARY_EXIT;
490                 snapshot_creation_status = SCS_READY;
491                 compute_next_snapshot_time();
492                 goto out;
493         }
494         es = WEXITSTATUS(status);
495         if (es != 0 && es != 23 && es != 24) {
496                 DSS_ERROR_LOG("rsync process %d returned %d\n", (int)rsync_pid, es);
497                 ret = -E_BAD_EXIT_CODE;
498                 snapshot_creation_status = SCS_READY;
499                 compute_next_snapshot_time();
500                 goto out;
501         }
502         ret = rename_incomplete_snapshot(current_snapshot_creation_time);
503         if (ret < 0)
504                 goto out;
505         snapshot_creation_status = SCS_RSYNC_SUCCESS;
506 out:
507         rsync_pid = 0;
508         rsync_stopped = 0;
509         return ret;
510 }
511
512 static int handle_pre_create_hook_exit(int status)
513 {
514         int es, ret;
515
516         if (!WIFEXITED(status)) {
517                 snapshot_creation_status = SCS_READY;
518                 compute_next_snapshot_time();
519                 ret = -E_INVOLUNTARY_EXIT;
520                 goto out;
521         }
522         es = WEXITSTATUS(status);
523         if (es) {
524                 snapshot_creation_status = SCS_READY;
525                 compute_next_snapshot_time();
526                 ret = -E_BAD_EXIT_CODE;
527                 goto out;
528         }
529         snapshot_creation_status = SCS_PRE_HOOK_SUCCESS;
530         ret = 1;
531 out:
532         pre_create_hook_pid = 0;
533         return ret;
534 }
535
536 static int handle_sigchld(void)
537 {
538         pid_t pid;
539         int status, ret = reap_child(&pid, &status);
540
541         if (ret <= 0)
542                 return ret;
543         if (pid == rsync_pid)
544                 return handle_rsync_exit(status);
545         if (pid == rm_pid)
546                 return handle_rm_exit(status);
547         if (pid == pre_create_hook_pid)
548                 return handle_pre_create_hook_exit(status);
549         if (pid == post_create_hook_pid) {
550                 snapshot_creation_status = SCS_READY;
551                 compute_next_snapshot_time();
552                 return 1;
553         }
554         DSS_EMERG_LOG("BUG: unknown process %d died\n", (int)pid);
555         exit(EXIT_FAILURE);
556 }
557
558 static int check_config(void)
559 {
560         if (conf.unit_interval_arg <= 0) {
561                 DSS_ERROR_LOG("bad unit interval: %i\n", conf.unit_interval_arg);
562                 return -E_INVALID_NUMBER;
563         }
564         DSS_DEBUG_LOG("unit interval: %i day(s)\n", conf.unit_interval_arg);
565         if (conf.num_intervals_arg <= 0) {
566                 DSS_ERROR_LOG("bad number of intervals  %i\n", conf.num_intervals_arg);
567                 return -E_INVALID_NUMBER;
568         }
569         DSS_DEBUG_LOG("number of intervals: %i\n", conf.num_intervals_arg);
570         return 1;
571 }
572
573 /* exits on errors */
574 static void parse_config_file(int override)
575 {
576         int ret;
577         char *config_file;
578         struct stat statbuf;
579         char *old_logfile_arg = NULL;
580         int old_daemon_given = 0;
581
582         if (conf.config_file_given)
583                 config_file = dss_strdup(conf.config_file_arg);
584         else {
585                 char *home = get_homedir();
586                 config_file = make_message("%s/.dssrc", home);
587                 free(home);
588         }
589         if (override) { /* SIGHUP */
590                 if (conf.logfile_given)
591                         old_logfile_arg = dss_strdup(conf.logfile_arg);
592                 old_daemon_given = conf.daemon_given;
593         }
594
595         ret = stat(config_file, &statbuf);
596         if (ret && conf.config_file_given) {
597                 ret = -ERRNO_TO_DSS_ERROR(errno);
598                 DSS_ERROR_LOG("failed to stat config file %s\n", config_file);
599                 goto out;
600         }
601         if (!ret) {
602                 struct cmdline_parser_params params = {
603                         .override = override,
604                         .initialize = 0,
605                         .check_required = 1,
606                         .check_ambiguity = 0,
607                         .print_errors = 1
608                 };
609                 cmdline_parser_config_file(config_file, &conf, &params);
610         }
611         ret = check_config();
612         if (ret < 0)
613                 goto out;
614         if (override) {
615                 /* don't change daemon mode on SIGHUP */
616                 conf.daemon_given = old_daemon_given;
617                 close_log(logfile);
618                 logfile = NULL;
619                 if (conf.logfile_given)
620                         free(old_logfile_arg);
621                 else if (conf.daemon_given) { /* re-use old logfile */
622                         conf.logfile_arg = old_logfile_arg;
623                         conf.logfile_given = 1;
624                 }
625         }
626         if (conf.logfile_given) {
627                 logfile = open_log(conf.logfile_arg);
628                 log_welcome(conf.loglevel_arg);
629         }
630         DSS_EMERG_LOG("loglevel: %d\n", conf.loglevel_arg);
631 //      cmdline_parser_dump(logfile? logfile : stdout, &conf);
632 out:
633         free(config_file);
634         if (ret >= 0)
635                 return;
636         DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
637         exit(EXIT_FAILURE);
638 }
639
640 static void change_to_dest_dir(void)
641 {
642         int ret;
643
644         DSS_INFO_LOG("changing cwd to %s\n", conf.dest_dir_arg);
645         ret = dss_chdir(conf.dest_dir_arg);
646         if (ret >= 0)
647                 return;
648         DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
649         exit(EXIT_FAILURE);
650 }
651
652 static void handle_sighup(void)
653 {
654         DSS_NOTICE_LOG("SIGHUP\n");
655         parse_config_file(1);
656         change_to_dest_dir();
657 }
658
659 static void handle_signal(void)
660 {
661         int sig, ret = next_signal();
662
663         if (ret <= 0)
664                 goto out;
665         sig = ret;
666         switch (sig) {
667         case SIGINT:
668         case SIGTERM:
669                 restart_rsync_process();
670                 kill_process(rsync_pid);
671                 kill_process(rm_pid);
672                 exit(EXIT_FAILURE);
673         case SIGHUP:
674                 handle_sighup();
675                 ret = 1;
676                 break;
677         case SIGCHLD:
678                 ret = handle_sigchld();
679                 break;
680         }
681 out:
682         if (ret < 0)
683                 DSS_ERROR_LOG("%s\n", dss_strerror(-ret));
684 }
685
686 static void create_rsync_argv(char ***argv, int64_t *num)
687 {
688         char *logname, *newest;
689         int i = 0, j;
690         struct snapshot_list sl;
691
692         dss_get_snapshot_list(&sl);
693         newest = name_of_newest_complete_snapshot(&sl);
694         free_snapshot_list(&sl);
695
696         *argv = dss_malloc((15 + conf.rsync_option_given) * sizeof(char *));
697         (*argv)[i++] = dss_strdup("rsync");
698         (*argv)[i++] = dss_strdup("-aq");
699         (*argv)[i++] = dss_strdup("--delete");
700         for (j = 0; j < conf.rsync_option_given; j++)
701                 (*argv)[i++] = dss_strdup(conf.rsync_option_arg[j]);
702         if (newest) {
703                 DSS_INFO_LOG("using %s as reference snapshot\n", newest);
704                 (*argv)[i++] = make_message("--link-dest=../%s", newest);
705                 free(newest);
706         } else
707                 DSS_INFO_LOG("no previous snapshot found\n");
708         logname = dss_logname();
709         if (conf.remote_user_given && !strcmp(conf.remote_user_arg, logname))
710                 (*argv)[i++] = dss_strdup(conf.source_dir_arg);
711         else
712                 (*argv)[i++] = make_message("%s@%s:%s/", conf.remote_user_given?
713                         conf.remote_user_arg : logname,
714                         conf.remote_host_arg, conf.source_dir_arg);
715         free(logname);
716         *num = get_current_time();
717         (*argv)[i++] = incomplete_name(*num);
718         (*argv)[i++] = NULL;
719         for (j = 0; j < i; j++)
720                 DSS_DEBUG_LOG("argv[%d] = %s\n", j, (*argv)[j]);
721 }
722
723 static void free_rsync_argv(char **argv)
724 {
725         int i;
726         for (i = 0; argv[i]; i++)
727                 free(argv[i]);
728         free(argv);
729 }
730
731 static int create_snapshot(char **argv)
732 {
733         int ret, fds[3] = {0, 0, 0};
734         char *name;
735
736         name = incomplete_name(current_snapshot_creation_time);
737         DSS_NOTICE_LOG("creating new snapshot %s\n", name);
738         free(name);
739         ret = dss_exec(&rsync_pid, argv[0], argv, fds);
740         if (ret < 0)
741                 return ret;
742         snapshot_creation_status = SCS_RSYNC_RUNNING;
743         return ret;
744 }
745
746 static int select_loop(void)
747 {
748         int ret;
749         /* check every 60 seconds for free disk space */
750         struct timeval tv = {.tv_sec = 60, .tv_usec = 0};
751
752         for (;;) {
753                 fd_set rfds;
754                 int low_disk_space;
755                 char **rsync_argv;
756                 struct timeval now, *tvp = &tv;
757
758                 if (rm_pid)
759                         tvp = NULL; /* sleep until rm process dies */
760                 FD_ZERO(&rfds);
761                 FD_SET(signal_pipe, &rfds);
762                 DSS_DEBUG_LOG("tvp: %p, tv_sec: %lu\n", tvp, (long unsigned) tv.tv_sec);
763                 ret = dss_select(signal_pipe + 1, &rfds, NULL, tvp);
764                 if (ret < 0)
765                         return ret;
766                 if (FD_ISSET(signal_pipe, &rfds))
767                         handle_signal();
768                 if (rm_pid)
769                         continue;
770                 ret = disk_space_low();
771                 if (ret < 0)
772                         break;
773                 low_disk_space = ret;
774                 ret = try_to_free_disk_space(low_disk_space);
775                 if (ret < 0)
776                         break;
777                 if (rm_pid) {
778                         stop_rsync_process();
779                         continue;
780                 }
781                 restart_rsync_process();
782                 gettimeofday(&now, NULL);
783                 if (tv_diff(&next_snapshot_time, &now, NULL) > 0)
784                         continue;
785                 switch (snapshot_creation_status) {
786                 case SCS_READY:
787                         ret = pre_create_hook();
788                         if (ret < 0)
789                                 goto out;
790                         continue;
791                 case SCS_PRE_HOOK_RUNNING:
792                         continue;
793                 case SCS_PRE_HOOK_SUCCESS:
794                         create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
795                         ret = create_snapshot(rsync_argv);
796                         free_rsync_argv(rsync_argv);
797                         if (ret < 0)
798                                 goto out;
799                         continue;
800                 case SCS_RSYNC_RUNNING:
801                         continue;
802                 case SCS_RSYNC_SUCCESS:
803                         ret = post_create_hook();
804                         if (ret < 0)
805                                 goto out;
806                         continue;
807                 case SCS_POST_HOOK_RUNNING:
808                         continue;
809                 }
810         }
811 out:
812         return ret;
813 }
814
815 static int com_run(void)
816 {
817         int ret;
818
819         if (conf.dry_run_given) {
820                 DSS_ERROR_LOG("dry_run not supported by this command\n");
821                 return -E_SYNTAX;
822         }
823         ret = install_sighandler(SIGHUP);
824         if (ret < 0)
825                 return ret;
826         compute_next_snapshot_time();
827         return select_loop();
828 }
829
830 static int com_prune(void)
831 {
832         int ret;
833         struct snapshot_list sl;
834         struct disk_space ds;
835
836         ret = get_disk_space(".", &ds);
837         if (ret < 0)
838                 return ret;
839         log_disk_space(&ds);
840         for (;;) {
841                 dss_get_snapshot_list(&sl);
842                 ret = remove_outdated_snapshot(&sl);
843                 free_snapshot_list(&sl);
844                 if (ret < 0)
845                         return ret;
846                 if (!ret)
847                         break;
848                 ret = wait_for_rm_process();
849                 if (ret < 0)
850                         goto out;
851         }
852         for (;;) {
853                 dss_get_snapshot_list(&sl);
854                 ret = remove_redundant_snapshot(&sl);
855                 free_snapshot_list(&sl);
856                 if (ret < 0)
857                         return ret;
858                 if (!ret)
859                         break;
860                 ret = wait_for_rm_process();
861                 if (ret < 0)
862                         goto out;
863         }
864         return 1;
865 out:
866         return ret;
867 }
868
869 static int com_create(void)
870 {
871         int ret, status;
872         char **rsync_argv;
873
874         if (conf.dry_run_given) {
875                 int i;
876                 char *msg = NULL;
877                 create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
878                 for (i = 0; rsync_argv[i]; i++) {
879                         char *tmp = msg;
880                         msg = make_message("%s%s%s", tmp? tmp : "",
881                                 tmp? " " : "", rsync_argv[i]);
882                         free(tmp);
883                 }
884                 free_rsync_argv(rsync_argv);
885                 dss_msg("%s\n", msg);
886                 free(msg);
887                 return 1;
888         }
889         ret = pre_create_hook();
890         if (ret < 0)
891                 return ret;
892         if (pre_create_hook_pid) {
893                 ret = wait_for_process(pre_create_hook_pid, &status);
894                 if (ret < 0)
895                         return ret;
896                 ret = handle_pre_create_hook_exit(status);
897                 if (ret < 0)
898                         return ret;
899         }
900         create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
901         ret = create_snapshot(rsync_argv);
902         if (ret < 0)
903                 goto out;
904         ret = wait_for_process(rsync_pid, &status);
905         if (ret < 0)
906                 goto out;
907         ret = handle_rsync_exit(status);
908         if (ret < 0)
909                 goto out;
910         post_create_hook();
911         if (post_create_hook_pid)
912                 ret = wait_for_process(post_create_hook_pid, &status);
913 out:
914         free_rsync_argv(rsync_argv);
915         return ret;
916 }
917
918 static int com_ls(void)
919 {
920         int i;
921         struct snapshot_list sl;
922         struct snapshot *s;
923
924         dss_get_snapshot_list(&sl);
925         FOR_EACH_SNAPSHOT(s, i, &sl)
926                 dss_msg("%u\t%s\n", s->interval, s->name);
927         free_snapshot_list(&sl);
928         return 1;
929 }
930
931 static void setup_signal_handling(void)
932 {
933         int ret;
934
935         DSS_INFO_LOG("setting up signal handlers\n");
936         signal_pipe = signal_init(); /* always successful */
937         ret = install_sighandler(SIGINT);
938         if (ret < 0)
939                 goto err;
940         ret = install_sighandler(SIGTERM);
941         if (ret < 0)
942                 goto err;
943         ret = install_sighandler(SIGCHLD);
944         if (ret < 0)
945                 goto err;
946         return;
947 err:
948         DSS_EMERG_LOG("could not install signal handlers\n");
949         exit(EXIT_FAILURE);
950 }
951
952 /**
953  * The main function of dss.
954  *
955  * \param argc Usual argument count.
956  * \param argv Usual argument vector.
957  */
958 int main(int argc, char **argv)
959 {
960         int ret;
961         struct cmdline_parser_params params = {
962                 .override = 0,
963                 .initialize = 1,
964                 .check_required = 0,
965                 .check_ambiguity = 0,
966                 .print_errors = 1
967         };
968
969         cmdline_parser_ext(argc, argv, &conf, &params); /* aborts on errors */
970         parse_config_file(0);
971
972         if (conf.daemon_given)
973                 daemon_init();
974         change_to_dest_dir();
975         setup_signal_handling();
976         ret = call_command_handler();
977         if (ret < 0)
978                 DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
979         exit(ret >= 0? EXIT_SUCCESS : EXIT_FAILURE);
980 }