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