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