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