Kill unused dss_error_txt.
[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
31
32 struct gengetopt_args_info conf;
33 static FILE *logfile;
34 static int signal_pipe;
35
36 /** Process id of current rsync process. */
37 static pid_t rsync_pid;
38 /** Whether the rsync process is currently stopped */
39 static int rsync_stopped;
40 /** Process id of current rm process. */
41 static pid_t rm_pid;
42 /** When the next snapshot is due. */
43 struct timeval next_snapshot_time;
44 /** The pid of the pre-create hook. */
45 pid_t pre_create_hook_pid;
46 /** The pid of the post-create hook. */
47 pid_t post_create_hook_pid;
48
49 /* Creation time of the snapshot currently being created. */
50 int64_t current_snapshot_creation_time;
51
52 static char *path_to_last_complete_snapshot;
53
54 enum {
55         /** We are ready to take the next snapshot. */
56         SCS_READY,
57         /** The pre-creation hook has been started. */
58         SCS_PRE_HOOK_RUNNING,
59         /** The pre-creation hook exited successfully. */
60         SCS_PRE_HOOK_SUCCESS,
61         /** The rsync process is running. */
62         SCS_RSYNC_RUNNING,
63         /** The rsync process exited successfully. */
64         SCS_RSYNC_SUCCESS,
65         /** The post-create hook has been started- */
66         SCS_POST_HOOK_RUNNING,
67 };
68
69 static unsigned snapshot_creation_status;
70
71
72 DEFINE_DSS_ERRLIST;
73
74
75 /* a litte cpp magic helps to DRY */
76 #define COMMANDS \
77         COMMAND(ls) \
78         COMMAND(create) \
79         COMMAND(prune) \
80         COMMAND(run)
81 #define COMMAND(x) int com_ ##x(void);
82 COMMANDS
83 #undef COMMAND
84 #define COMMAND(x) if (conf.x ##_given) return com_ ##x();
85 int call_command_handler(void)
86 {
87         COMMANDS
88         DSS_EMERG_LOG("BUG: did not find command handler\n");
89         exit(EXIT_FAILURE);
90 }
91 #undef COMMAND
92 #undef COMMANDS
93
94 /*
95  * complete, not being deleted: 1204565370-1204565371.Sun_Mar_02_2008_14_33-Sun_Mar_02_2008_14_43
96  * complete, being deleted: 1204565370-1204565371.being_deleted
97  * incomplete, not being deleted: 1204565370-incomplete
98  * incomplete, being deleted: 1204565370-incomplete.being_deleted
99  */
100 enum snapshot_status_flags {
101         /** The rsync process terminated successfully. */
102         SS_COMPLETE = 1,
103         /** The rm process is running to remove this snapshot. */
104         SS_BEING_DELETED = 2,
105 };
106
107 struct snapshot {
108         char *name;
109         int64_t creation_time;
110         int64_t completion_time;
111         enum snapshot_status_flags flags;
112         unsigned interval;
113 };
114
115 __printf_2_3 void dss_log(int ll, const char* fmt,...)
116 {
117         va_list argp;
118         FILE *outfd;
119         struct tm *tm;
120         time_t t1;
121         char str[255] = "";
122
123         if (ll < conf.loglevel_arg)
124                 return;
125         outfd = logfile? logfile : stderr;
126         time(&t1);
127         tm = localtime(&t1);
128         strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
129         fprintf(outfd, "%s ", str);
130         if (conf.loglevel_arg <= INFO)
131                 fprintf(outfd, "%i: ", ll);
132         va_start(argp, fmt);
133         vfprintf(outfd, fmt, argp);
134         va_end(argp);
135 }
136
137 /**
138  * Print a message either to stdout or to the log file.
139  */
140 __printf_1_2 void dss_msg(const char* fmt,...)
141 {
142         FILE *outfd = conf.daemon_given? logfile : stdout;
143         va_list argp;
144         va_start(argp, fmt);
145         vfprintf(outfd, fmt, argp);
146         va_end(argp);
147 }
148
149 /**
150  * Return the desired number of snapshots of an interval.
151  */
152 unsigned num_snapshots(int interval)
153 {
154         unsigned n;
155
156         assert(interval >= 0);
157
158         if (interval >= conf.num_intervals_arg)
159                 return 0;
160         n = conf.num_intervals_arg - interval - 1;
161         return 1 << n;
162 }
163
164 /* return: Whether dirname is a snapshot directory (0: no, 1: yes) */
165 int is_snapshot(const char *dirname, int64_t now, struct snapshot *s)
166 {
167         int i, ret;
168         char *dash, *dot, *tmp;
169         int64_t num;
170
171         assert(dirname);
172         dash = strchr(dirname, '-');
173         if (!dash || !dash[1] || dash == dirname)
174                 return 0;
175         for (i = 0; dirname[i] != '-'; i++)
176                 if (!isdigit(dirname[i]))
177                         return 0;
178         tmp = dss_strdup(dirname);
179         tmp[i] = '\0';
180         ret = dss_atoi64(tmp, &num);
181         free(tmp);
182         if (ret < 0)
183                 return 0;
184         assert(num >= 0);
185         if (num > now)
186                 return 0;
187         s->creation_time = num;
188         //DSS_DEBUG_LOG("%s start time: %lli\n", dirname, (long long)s->creation_time);
189         s->interval = (long long) ((now - s->creation_time)
190                 / conf.unit_interval_arg / 24 / 3600);
191         if (!strcmp(dash + 1, "incomplete")) {
192                 s->completion_time = -1;
193                 s->flags = 0; /* neither complete, nor being deleted */
194                 goto success;
195         }
196         if (!strcmp(dash + 1, "incomplete.being_deleted")) {
197                 s->completion_time = -1;
198                 s->flags = SS_BEING_DELETED; /* mot cpmplete, being deleted */
199                 goto success;
200         }
201         tmp = dash + 1;
202         dot = strchr(tmp, '.');
203         if (!dot || !dot[1] || dot == tmp)
204                 return 0;
205         for (i = 0; tmp[i] != '.'; i++)
206                 if (!isdigit(tmp[i]))
207                         return 0;
208         tmp = dss_strdup(dash + 1);
209         tmp[i] = '\0';
210         ret = dss_atoi64(tmp, &num);
211         free(tmp);
212         if (ret < 0)
213                 return 0;
214         if (num > now)
215                 return 0;
216         s->completion_time = num;
217         s->flags = SS_COMPLETE;
218         if (!strcmp(dot + 1, "being_deleted"))
219                 s->flags |= SS_BEING_DELETED;
220 success:
221         s->name = dss_strdup(dirname);
222         return 1;
223 }
224
225 int64_t get_current_time(void)
226 {
227         time_t now;
228         time(&now);
229         DSS_DEBUG_LOG("now: %lli\n", (long long) now);
230         return (int64_t)now;
231 }
232
233 char *incomplete_name(int64_t start)
234 {
235         return make_message("%lli-incomplete", (long long)start);
236 }
237
238 char *being_deleted_name(struct snapshot *s)
239 {
240         if (s->flags & SS_COMPLETE)
241                 return make_message("%lli-%lli.being_deleted",
242                         (long long)s->creation_time,
243                         (long long)s->completion_time);
244         return make_message("%lli-incomplete.being_deleted",
245                 (long long)s->creation_time);
246 }
247
248 int complete_name(int64_t start, int64_t end, char **result)
249 {
250         struct tm start_tm, end_tm;
251         time_t *start_seconds = (time_t *) (uint64_t *)&start; /* STFU, gcc */
252         time_t *end_seconds = (time_t *) (uint64_t *)&end; /* STFU, gcc */
253         char start_str[200], end_str[200];
254
255         if (!localtime_r(start_seconds, &start_tm))
256                 return -E_LOCALTIME;
257         if (!localtime_r(end_seconds, &end_tm))
258                 return -E_LOCALTIME;
259         if (!strftime(start_str, sizeof(start_str), "%a_%b_%d_%Y_%H_%M_%S", &start_tm))
260                 return -E_STRFTIME;
261         if (!strftime(end_str, sizeof(end_str), "%a_%b_%d_%Y_%H_%M_%S", &end_tm))
262                 return -E_STRFTIME;
263         *result = make_message("%lli-%lli.%s-%s", (long long) start, (long long) end,
264                 start_str, end_str);
265         return 1;
266 }
267
268 struct snapshot_list {
269         int64_t now;
270         unsigned num_snapshots;
271         unsigned array_size;
272         struct snapshot **snapshots;
273         /**
274          * Array of size num_intervals + 1
275          *
276          * It contains the number of snapshots in each interval. interval_count[num_intervals]
277          * is the number of snapshots which belong to any interval greater than num_intervals.
278          */
279         unsigned *interval_count;
280 };
281
282 #define FOR_EACH_SNAPSHOT(s, i, sl) \
283         for ((i) = 0; (i) < (sl)->num_snapshots && ((s) = (sl)->snapshots[(i)]); (i)++)
284
285 #define FOR_EACH_SNAPSHOT_REVERSE(s, i, sl) \
286         for ((i) = (sl)->num_snapshots; (i) > 0 && ((s) = (sl)->snapshots[(i - 1)]); (i)--)
287
288 static inline struct snapshot *oldest_snapshot(struct snapshot_list *sl)
289 {
290         if (!sl->num_snapshots)
291                 return NULL;
292         return sl->snapshots[0];
293 }
294
295 #define NUM_COMPARE(x, y) ((int)((x) < (y)) - (int)((x) > (y)))
296
297 static int compare_snapshots(const void *a, const void *b)
298 {
299         struct snapshot *s1 = *(struct snapshot **)a;
300         struct snapshot *s2 = *(struct snapshot **)b;
301         return NUM_COMPARE(s2->creation_time, s1->creation_time);
302 }
303
304 /** Compute the minimum of \a a and \a b. */
305 #define DSS_MIN(a,b) ((a) < (b) ? (a) : (b))
306
307 int add_snapshot(const char *dirname, void *private)
308 {
309         struct snapshot_list *sl = private;
310         struct snapshot s;
311         int ret = is_snapshot(dirname, sl->now, &s);
312
313         if (!ret)
314                 return 1;
315         if (sl->num_snapshots >= sl->array_size) {
316                 sl->array_size = 2 * sl->array_size + 1;
317                 sl->snapshots = dss_realloc(sl->snapshots,
318                         sl->array_size * sizeof(struct snapshot *));
319         }
320         sl->snapshots[sl->num_snapshots] = dss_malloc(sizeof(struct snapshot));
321         *(sl->snapshots[sl->num_snapshots]) = s;
322         sl->interval_count[DSS_MIN(s.interval, conf.num_intervals_arg)]++;
323         sl->num_snapshots++;
324         return 1;
325 }
326
327 void get_snapshot_list(struct snapshot_list *sl)
328 {
329         sl->now = get_current_time();
330         sl->num_snapshots = 0;
331         sl->array_size = 0;
332         sl->snapshots = NULL;
333         sl->interval_count = dss_calloc((conf.num_intervals_arg + 1) * sizeof(unsigned));
334         for_each_subdir(add_snapshot, sl);
335         qsort(sl->snapshots, sl->num_snapshots, sizeof(struct snapshot *),
336                 compare_snapshots);
337 }
338
339 void free_snapshot_list(struct snapshot_list *sl)
340 {
341         int i;
342         struct snapshot *s;
343
344         FOR_EACH_SNAPSHOT(s, i, sl) {
345                 free(s->name);
346                 free(s);
347         }
348         free(sl->interval_count);
349         sl->interval_count = NULL;
350         free(sl->snapshots);
351         sl->snapshots = NULL;
352         sl->num_snapshots = 0;
353 }
354
355 void stop_rsync_process(void)
356 {
357         if (!rsync_pid || rsync_stopped)
358                 return;
359         kill(SIGSTOP, rsync_pid);
360         rsync_stopped = 1;
361 }
362
363 void restart_rsync_process(void)
364 {
365         if (!rsync_pid || !rsync_stopped)
366                 return;
367         kill (SIGCONT, rsync_pid);
368         rsync_stopped = 0;
369 }
370
371 /**
372  * Print a log message about the exit status of a child.
373  */
374 void log_termination_msg(pid_t pid, int status)
375 {
376         if (WIFEXITED(status))
377                 DSS_INFO_LOG("child %i exited. Exit status: %i\n", (int)pid,
378                         WEXITSTATUS(status));
379         else if (WIFSIGNALED(status))
380                 DSS_NOTICE_LOG("child %i was killed by signal %i\n", (int)pid,
381                         WTERMSIG(status));
382         else
383                 DSS_WARNING_LOG("child %i terminated abormally\n", (int)pid);
384 }
385
386 int wait_for_process(pid_t pid, int *status)
387 {
388         int ret;
389
390         DSS_DEBUG_LOG("Waiting for process %d to terminate\n", (int)pid);
391         for (;;) {
392                 fd_set rfds;
393
394                 FD_ZERO(&rfds);
395                 FD_SET(signal_pipe, &rfds);
396                 ret = dss_select(signal_pipe + 1, &rfds, NULL, NULL);
397                 if (ret < 0)
398                         break;
399                 ret = next_signal();
400                 if (!ret)
401                         continue;
402                 if (ret == SIGCHLD) {
403                         ret = waitpid(pid, status, 0);
404                         if (ret >= 0)
405                                 break;
406                         if (errno != EINTR) { /* error */
407                                 ret = -ERRNO_TO_DSS_ERROR(errno);
408                                 break;
409                         }
410                 }
411                 /* SIGINT or SIGTERM */
412                 DSS_WARNING_LOG("sending SIGTERM to pid %d\n", (int)pid);
413                 kill(pid, SIGTERM);
414         }
415         if (ret < 0)
416                 DSS_ERROR_LOG("failed to wait for process %d\n", (int)pid);
417         else
418                 log_termination_msg(pid, *status);
419         return ret;
420 }
421
422 int remove_snapshot(struct snapshot *s)
423 {
424         int fds[3] = {0, 0, 0};
425         assert(!rm_pid);
426         char *new_name = being_deleted_name(s);
427         int ret = dss_rename(s->name, new_name);
428         char *argv[] = {"rm", "-rf", new_name, NULL};
429
430         if (ret < 0)
431                 goto out;
432         DSS_NOTICE_LOG("removing %s (interval = %i)\n", s->name, s->interval);
433         stop_rsync_process();
434         ret = dss_exec(&rm_pid, argv[0], argv, fds);
435 out:
436         free(new_name);
437         return ret;
438 }
439
440 /*
441  * return: 0: no redundant snapshots, 1: rm process started, negative: error
442  */
443 int remove_redundant_snapshot(struct snapshot_list *sl)
444 {
445         int ret, i, interval;
446         struct snapshot *s;
447         unsigned missing = 0;
448
449         DSS_INFO_LOG("looking for intervals containing too many snapshots\n");
450         for (interval = conf.num_intervals_arg - 1; interval >= 0; interval--) {
451                 unsigned keep = num_snapshots(interval);
452                 unsigned num = sl->interval_count[interval];
453                 struct snapshot *victim = NULL, *prev = NULL;
454                 int64_t score = LONG_MAX;
455
456                 if (keep >= num)
457                         missing += keep - num;
458 //              DSS_DEBUG_LOG("interval %i: keep: %u, have: %u, missing: %u\n",
459 //                      interval, keep, num, missing);
460                 if (keep + missing >= num)
461                         continue;
462                 /* redundant snapshot in this interval, pick snapshot with lowest score */
463                 FOR_EACH_SNAPSHOT(s, i, sl) {
464                         int64_t this_score;
465
466                         //DSS_DEBUG_LOG("checking %s\n", s->name);
467                         if (s->interval > interval) {
468                                 prev = s;
469                                 continue;
470                         }
471                         if (s->interval < interval)
472                                 break;
473                         if (!victim) {
474                                 victim = s;
475                                 prev = s;
476                                 continue;
477                         }
478                         assert(prev);
479                         /* check if s is a better victim */
480                         this_score = s->creation_time - prev->creation_time;
481                         assert(this_score >= 0);
482                         //DSS_DEBUG_LOG("%s: score %lli\n", s->name, (long long)score);
483                         if (this_score < score) {
484                                 score = this_score;
485                                 victim = s;
486                         }
487                         prev = s;
488                 }
489                 assert(victim);
490                 if (conf.dry_run_given) {
491                         dss_msg("%s would be removed (interval = %i)\n",
492                                 victim->name, victim->interval);
493                         continue;
494                 }
495                 ret = remove_snapshot(victim);
496                 return ret < 0? ret : 1;
497         }
498         return 0;
499 }
500
501 int remove_outdated_snapshot(struct snapshot_list *sl)
502 {
503         int i, ret;
504         struct snapshot *s;
505
506         DSS_INFO_LOG("looking for snapshots belonging to intervals greater than %d\n",
507                 conf.num_intervals_arg);
508         FOR_EACH_SNAPSHOT(s, i, sl) {
509                 if (s->interval <= conf.num_intervals_arg)
510                         continue;
511                 if (conf.dry_run_given) {
512                         dss_msg("%s would be removed (interval = %i)\n",
513                                 s->name, s->interval);
514                         continue;
515                 }
516                 ret = remove_snapshot(s);
517                 if (ret < 0)
518                         return ret;
519                 return 1;
520         }
521         return 0;
522 }
523
524 int handle_rm_exit(int status)
525 {
526         rm_pid = 0;
527         if (!WIFEXITED(status))
528                 return -E_INVOLUNTARY_EXIT;
529         if (WEXITSTATUS(status))
530                 return -E_BAD_EXIT_CODE;
531         return 1;
532 }
533
534 int wait_for_rm_process(void)
535 {
536         int status, ret = wait_for_process(rm_pid, &status);
537
538         if (ret < 0)
539                 return ret;
540         return handle_rm_exit(status);
541 }
542
543 void kill_process(pid_t pid)
544 {
545         if (!pid)
546                 return;
547         DSS_WARNING_LOG("sending SIGTERM to pid %d\n", (int)pid);
548         kill(pid, SIGTERM);
549 }
550
551 int check_config(void)
552 {
553         if (conf.unit_interval_arg <= 0) {
554                 DSS_ERROR_LOG("bad unit interval: %i\n", conf.unit_interval_arg);
555                 return -E_INVALID_NUMBER;
556         }
557         DSS_DEBUG_LOG("unit interval: %i day(s)\n", conf.unit_interval_arg);
558         if (conf.num_intervals_arg <= 0) {
559                 DSS_ERROR_LOG("bad number of intervals  %i\n", conf.num_intervals_arg);
560                 return -E_INVALID_NUMBER;
561         }
562         DSS_DEBUG_LOG("number of intervals: %i\n", conf.num_intervals_arg);
563         return 1;
564 }
565
566 /* exits on errors */
567 void parse_config_file(int override)
568 {
569         int ret;
570         char *config_file;
571         struct stat statbuf;
572         char *old_logfile_arg = NULL;
573         int old_daemon_given = 0;
574
575         if (conf.config_file_given)
576                 config_file = dss_strdup(conf.config_file_arg);
577         else {
578                 char *home = get_homedir();
579                 config_file = make_message("%s/.dssrc", home);
580                 free(home);
581         }
582         if (override) { /* SIGHUP */
583                 if (conf.logfile_given)
584                         old_logfile_arg = dss_strdup(conf.logfile_arg);
585                 old_daemon_given = conf.daemon_given;
586         }
587
588         ret = stat(config_file, &statbuf);
589         if (ret && conf.config_file_given) {
590                 ret = -ERRNO_TO_DSS_ERROR(errno);
591                 DSS_ERROR_LOG("failed to stat config file %s\n", config_file);
592                 goto out;
593         }
594         if (!ret) {
595                 struct cmdline_parser_params params = {
596                         .override = override,
597                         .initialize = 0,
598                         .check_required = 1,
599                         .check_ambiguity = 0
600                 };
601                 cmdline_parser_config_file(config_file, &conf, &params);
602         }
603         ret = check_config();
604         if (ret < 0)
605                 goto out;
606         if (override) {
607                 /* don't change daemon mode on SIGHUP */
608                 conf.daemon_given = old_daemon_given;
609                 close_log(logfile);
610                 logfile = NULL;
611                 if (conf.logfile_given)
612                         free(old_logfile_arg);
613                 else if (conf.daemon_given) { /* re-use old logfile */
614                         conf.logfile_arg = old_logfile_arg;
615                         conf.logfile_given = 1;
616                 }
617         }
618         if (conf.logfile_given) {
619                 logfile = open_log(conf.logfile_arg);
620                 log_welcome(conf.loglevel_arg);
621         }
622         DSS_EMERG_LOG("loglevel: %d\n", conf.loglevel_arg);
623 //      cmdline_parser_dump(logfile? logfile : stdout, &conf);
624         ret = dss_chdir(conf.dest_dir_arg);
625 out:
626         free(config_file);
627         if (ret >= 0)
628                 return;
629         DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
630         exit(EXIT_FAILURE);
631 }
632
633 void handle_sighup(void)
634 {
635         DSS_NOTICE_LOG("SIGHUP\n");
636         parse_config_file(1);
637 }
638
639 int rename_incomplete_snapshot(int64_t start)
640 {
641         char *old_name;
642         int ret;
643
644         free(path_to_last_complete_snapshot);
645         ret = complete_name(start, get_current_time(),
646                 &path_to_last_complete_snapshot);
647         if (ret < 0)
648                 return ret;
649         old_name = incomplete_name(start);
650         ret = dss_rename(old_name, path_to_last_complete_snapshot);
651         if (ret >= 0)
652                 DSS_NOTICE_LOG("%s -> %s\n", old_name,
653                         path_to_last_complete_snapshot);
654         free(old_name);
655         return ret;
656 }
657
658 void compute_next_snapshot_time(void)
659 {
660         struct timeval now, unit_interval = {.tv_sec = 24 * 3600 * conf.unit_interval_arg},
661                 tmp, diff;
662         int64_t x = 0;
663         unsigned wanted = num_snapshots(0), num_complete_snapshots = 0;
664         int i, ret;
665         struct snapshot *s = NULL;
666         struct snapshot_list sl;
667
668         assert(snapshot_creation_status == SCS_READY);
669         current_snapshot_creation_time = 0;
670         get_snapshot_list(&sl);
671         FOR_EACH_SNAPSHOT(s, i, &sl) {
672                 if (!(s->flags & SS_COMPLETE))
673                         continue;
674                 num_complete_snapshots++;
675                 x += s->completion_time - s->creation_time;
676         }
677         assert(x >= 0);
678         if (num_complete_snapshots)
679                 x /= num_complete_snapshots; /* avg time to create one snapshot */
680         x *= wanted; /* time to create all snapshots in interval 0 */
681         tmp.tv_sec = x;
682         tmp.tv_usec = 0;
683         ret = tv_diff(&unit_interval, &tmp, &diff); /* total sleep time per unit interval */
684         gettimeofday(&now, NULL);
685         if (ret < 0 || !s)
686                 goto min_sleep;
687         tv_divide(wanted, &diff, &tmp); /* sleep time betweeen two snapshots */
688         diff.tv_sec = s->completion_time;
689         diff.tv_usec = 0;
690         tv_add(&diff, &tmp, &next_snapshot_time);
691         if (tv_diff(&now, &next_snapshot_time, NULL) < 0)
692                 goto out;
693 min_sleep:
694         next_snapshot_time = now;
695         next_snapshot_time.tv_sec += 60;
696 out:
697         free_snapshot_list(&sl);
698 }
699
700 int handle_rsync_exit(int status)
701 {
702         int es, ret;
703
704         if (!WIFEXITED(status)) {
705                 DSS_ERROR_LOG("rsync process %d died involuntary\n", (int)rsync_pid);
706                 ret = -E_INVOLUNTARY_EXIT;
707                 snapshot_creation_status = SCS_READY;
708                 compute_next_snapshot_time();
709                 goto out;
710         }
711         es = WEXITSTATUS(status);
712         if (es != 0 && es != 23 && es != 24) {
713                 DSS_ERROR_LOG("rsync process %d returned %d\n", (int)rsync_pid, es);
714                 ret = -E_BAD_EXIT_CODE;
715                 snapshot_creation_status = SCS_READY;
716                 compute_next_snapshot_time();
717                 goto out;
718         }
719         ret = rename_incomplete_snapshot(current_snapshot_creation_time);
720         if (ret < 0)
721                 goto out;
722         snapshot_creation_status = SCS_RSYNC_SUCCESS;
723 out:
724         rsync_pid = 0;
725         rsync_stopped = 0;
726         return ret;
727 }
728
729 __malloc char *name_of_newest_complete_snapshot(void)
730 {
731         struct snapshot_list sl;
732         struct snapshot *s;
733         int i;
734         char *name = NULL;
735
736         get_snapshot_list(&sl);
737
738         FOR_EACH_SNAPSHOT_REVERSE(s, i, &sl) {
739                 if (s->flags != SS_COMPLETE) /* incomplete or being deleted */
740                         continue;
741                 name = dss_strdup(s->name);
742                 break;
743         }
744         free_snapshot_list(&sl);
745         return name;
746 }
747
748 void create_rsync_argv(char ***argv, int64_t *num)
749 {
750         char *logname, *newest = name_of_newest_complete_snapshot();
751         int i = 0, j;
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         if (conf.exclude_patterns_given) {
766                 (*argv)[i++] = dss_strdup("--exclude-from");
767                 (*argv)[i++] = dss_strdup(conf.exclude_patterns_arg);
768
769         }
770         logname = dss_logname();
771         if (conf.remote_user_given && !strcmp(conf.remote_user_arg, logname))
772                 (*argv)[i++] = dss_strdup(conf.source_dir_arg);
773         else
774                 (*argv)[i++] = make_message("%s@%s:%s/", conf.remote_user_given?
775                         conf.remote_user_arg : logname,
776                         conf.remote_host_arg, conf.source_dir_arg);
777         free(logname);
778         *num = get_current_time();
779         (*argv)[i++] = incomplete_name(*num);
780         (*argv)[i++] = NULL;
781         for (j = 0; j < i; j++)
782                 DSS_DEBUG_LOG("argv[%d] = %s\n", j, (*argv)[j]);
783 }
784
785 void free_rsync_argv(char **argv)
786 {
787         int i;
788         for (i = 0; argv[i]; i++)
789                 free(argv[i]);
790         free(argv);
791 }
792
793 int pre_create_hook(void)
794 {
795         int ret, fds[3] = {0, 0, 0};
796
797         if (!conf.pre_create_hook_given) {
798                 snapshot_creation_status = SCS_PRE_HOOK_SUCCESS;
799                 return 0;
800         }
801         DSS_NOTICE_LOG("executing %s\n", conf.pre_create_hook_arg);
802         ret = dss_exec_cmdline_pid(&pre_create_hook_pid,
803                 conf.pre_create_hook_arg, fds);
804         if (ret < 0)
805                 return ret;
806         snapshot_creation_status = SCS_PRE_HOOK_RUNNING;
807         return ret;
808 }
809
810 int post_create_hook(void)
811 {
812         int ret, fds[3] = {0, 0, 0};
813         char *cmd;
814
815         if (!conf.post_create_hook_given) {
816                 snapshot_creation_status = SCS_READY;
817                 compute_next_snapshot_time();
818                 return 0;
819         }
820         cmd = make_message("%s %s", conf.post_create_hook_arg,
821                 path_to_last_complete_snapshot);
822         DSS_NOTICE_LOG("executing %s\n", cmd);
823         ret = dss_exec_cmdline_pid(&post_create_hook_pid, cmd, fds);
824         free(cmd);
825         if (ret < 0)
826                 return ret;
827         snapshot_creation_status = SCS_POST_HOOK_RUNNING;
828         return ret;
829 }
830
831 int create_snapshot(char **argv)
832 {
833         int ret, fds[3] = {0, 0, 0};
834         char *name;
835
836         name = incomplete_name(current_snapshot_creation_time);
837         DSS_NOTICE_LOG("creating new snapshot %s\n", name);
838         free(name);
839         ret = dss_exec(&rsync_pid, argv[0], argv, fds);
840         if (ret < 0)
841                 return ret;
842         snapshot_creation_status = SCS_RSYNC_RUNNING;
843         return ret;
844 }
845
846 int handle_pre_create_hook_exit(int status)
847 {
848         int es, ret;
849
850         if (!WIFEXITED(status)) {
851                 snapshot_creation_status = SCS_READY;
852                 compute_next_snapshot_time();
853                 ret = -E_INVOLUNTARY_EXIT;
854                 goto out;
855         }
856         es = WEXITSTATUS(status);
857         if (es) {
858                 snapshot_creation_status = SCS_READY;
859                 compute_next_snapshot_time();
860                 ret = -E_BAD_EXIT_CODE;
861                 goto out;
862         }
863         snapshot_creation_status = SCS_PRE_HOOK_SUCCESS;
864         ret = 1;
865 out:
866         pre_create_hook_pid = 0;
867         return ret;
868 }
869
870 int handle_sigchld()
871 {
872         pid_t pid;
873         int status, ret = reap_child(&pid, &status);
874
875         if (ret <= 0)
876                 return ret;
877         if (pid == rsync_pid)
878                 return handle_rsync_exit(status);
879         if (pid == rm_pid)
880                 return handle_rm_exit(status);
881         if (pid == pre_create_hook_pid)
882                 return handle_pre_create_hook_exit(status);
883         if (pid == post_create_hook_pid) {
884                 snapshot_creation_status = SCS_READY;
885                 compute_next_snapshot_time();
886                 return 1;
887         }
888         DSS_EMERG_LOG("BUG: unknown process %d died\n", (int)pid);
889         exit(EXIT_FAILURE);
890 }
891
892 void handle_signal(void)
893 {
894         int sig, ret = next_signal();
895
896         if (ret <= 0)
897                 goto out;
898         sig = ret;
899         switch (sig) {
900         case SIGINT:
901         case SIGTERM:
902                 restart_rsync_process();
903                 kill_process(rsync_pid);
904                 kill_process(rm_pid);
905                 exit(EXIT_FAILURE);
906         case SIGHUP:
907                 handle_sighup();
908                 ret = 1;
909                 break;
910         case SIGCHLD:
911                 ret = handle_sigchld();
912                 break;
913         }
914 out:
915         if (ret < 0)
916                 DSS_ERROR_LOG("%s\n", dss_strerror(-ret));
917 }
918
919 int remove_oldest_snapshot(struct snapshot_list *sl)
920 {
921         struct snapshot *s = oldest_snapshot(sl);
922
923         if (!s) /* no snapshot found */
924                 return 0;
925         DSS_INFO_LOG("oldest snapshot: %s\n", s->name);
926         if (s->creation_time == current_snapshot_creation_time)
927                 return 0; /* do not remove the snapshot currently being created */
928         return remove_snapshot(s);
929 }
930
931 /* TODO: Also consider number of inodes. */
932 int disk_space_low(void)
933 {
934         struct disk_space ds;
935         int ret = get_disk_space(".", &ds);
936
937         if (ret < 0)
938                 return ret;
939         if (conf.min_free_mb_arg)
940                 if (ds.free_mb < conf.min_free_mb_arg)
941                         return 1;
942         if (conf.min_free_percent_arg)
943                 if (ds.percent_free < conf.min_free_percent_arg)
944                         return 1;
945         return 0;
946 }
947
948 int try_to_free_disk_space(int low_disk_space)
949 {
950         int ret;
951         struct snapshot_list sl;
952
953         get_snapshot_list(&sl);
954         ret = remove_outdated_snapshot(&sl);
955         if (ret) /* error, or we are removing something */
956                 goto out;
957         /* no outdated snapshot */
958         ret = remove_redundant_snapshot(&sl);
959         if (ret)
960                 goto out;
961         ret = 0;
962         if (!low_disk_space)
963                 goto out;
964         DSS_WARNING_LOG("disk space low and nothing obvious to remove\n");
965         ret = remove_oldest_snapshot(&sl);
966         if (ret)
967                 goto out;
968         DSS_CRIT_LOG("uhuhu: not enough disk space for a single snapshot\n");
969         ret= -ENOSPC;
970 out:
971         free_snapshot_list(&sl);
972         return ret;
973 }
974
975 int select_loop(void)
976 {
977         int ret;
978         struct timeval tv = {.tv_sec = 0, .tv_usec = 0};
979
980         for (;;) {
981                 fd_set rfds;
982                 int low_disk_space;
983                 char **rsync_argv;
984                 struct timeval now, *tvp = &tv;
985
986                 if (rsync_pid)
987                         tv.tv_sec = 60; /* check every 60 seconds for free disk space */
988                 else if (rm_pid)
989                         tvp = NULL; /* sleep until rm process dies */
990                 FD_ZERO(&rfds);
991                 FD_SET(signal_pipe, &rfds);
992                 DSS_DEBUG_LOG("tvp: %p, tv_sec: %lu\n", tvp, (long unsigned) tv.tv_sec);
993                 ret = dss_select(signal_pipe + 1, &rfds, NULL, tvp);
994                 if (ret < 0)
995                         return ret;
996                 if (FD_ISSET(signal_pipe, &rfds))
997                         handle_signal();
998                 if (rm_pid)
999                         continue;
1000                 ret = disk_space_low();
1001                 if (ret < 0)
1002                         break;
1003                 low_disk_space = ret;
1004                 if (low_disk_space)
1005                         stop_rsync_process();
1006                 ret = try_to_free_disk_space(low_disk_space);
1007                 if (ret < 0)
1008                         break;
1009                 if (rm_pid)
1010                         continue;
1011                 restart_rsync_process();
1012                 gettimeofday(&now, NULL);
1013                 if (tv_diff(&next_snapshot_time, &now, &tv) > 0)
1014                         continue;
1015                 switch (snapshot_creation_status) {
1016                 case SCS_READY:
1017                         ret = pre_create_hook();
1018                         if (ret < 0)
1019                                 goto out;
1020                         continue;
1021                 case SCS_PRE_HOOK_RUNNING:
1022                         continue;
1023                 case SCS_PRE_HOOK_SUCCESS:
1024                         create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
1025                         ret = create_snapshot(rsync_argv);
1026                         free_rsync_argv(rsync_argv);
1027                         if (ret < 0)
1028                                 goto out;
1029                         continue;
1030                 case SCS_RSYNC_RUNNING:
1031                         continue;
1032                 case SCS_RSYNC_SUCCESS:
1033                         ret = post_create_hook();
1034                         if (ret < 0)
1035                                 goto out;
1036                         continue;
1037                 case SCS_POST_HOOK_RUNNING:
1038                         continue;
1039                 }
1040         }
1041 out:
1042         return ret;
1043 }
1044
1045 int com_run(void)
1046 {
1047         int ret;
1048
1049         if (conf.dry_run_given) {
1050                 DSS_ERROR_LOG("dry_run not supported by this command\n");
1051                 return -E_SYNTAX;
1052         }
1053         ret = install_sighandler(SIGHUP);
1054         if (ret < 0)
1055                 return ret;
1056         compute_next_snapshot_time();
1057         return select_loop();
1058 }
1059
1060 int com_prune(void)
1061 {
1062         int ret;
1063         struct snapshot_list sl;
1064         struct disk_space ds;
1065
1066         ret = get_disk_space(".", &ds);
1067         if (ret < 0)
1068                 return ret;
1069         log_disk_space(&ds);
1070         for (;;) {
1071                 get_snapshot_list(&sl);
1072                 ret = remove_outdated_snapshot(&sl);
1073                 free_snapshot_list(&sl);
1074                 if (ret < 0)
1075                         return ret;
1076                 if (!ret)
1077                         break;
1078                 ret = wait_for_rm_process();
1079                 if (ret < 0)
1080                         goto out;
1081         }
1082         for (;;) {
1083                 get_snapshot_list(&sl);
1084                 ret = remove_redundant_snapshot(&sl);
1085                 free_snapshot_list(&sl);
1086                 if (ret < 0)
1087                         return ret;
1088                 if (!ret)
1089                         break;
1090                 ret = wait_for_rm_process();
1091                 if (ret < 0)
1092                         goto out;
1093         }
1094         return 1;
1095 out:
1096         return ret;
1097 }
1098
1099 int com_create(void)
1100 {
1101         int ret, status;
1102         char **rsync_argv;
1103
1104         if (conf.dry_run_given) {
1105                 int i;
1106                 char *msg = NULL;
1107                 create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
1108                 for (i = 0; rsync_argv[i]; i++) {
1109                         char *tmp = msg;
1110                         msg = make_message("%s%s%s", tmp? tmp : "",
1111                                 tmp? " " : "", rsync_argv[i]);
1112                         free(tmp);
1113                 }
1114                 free_rsync_argv(rsync_argv);
1115                 dss_msg("%s\n", msg);
1116                 free(msg);
1117                 return 1;
1118         }
1119         ret = pre_create_hook();
1120         if (ret < 0)
1121                 return ret;
1122         if (pre_create_hook_pid) {
1123                 ret = wait_for_process(pre_create_hook_pid, &status);
1124                 if (ret < 0)
1125                         return ret;
1126                 ret = handle_pre_create_hook_exit(status);
1127                 if (ret < 0)
1128                         return ret;
1129         }
1130         create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
1131         ret = create_snapshot(rsync_argv);
1132         if (ret < 0)
1133                 goto out;
1134         ret = wait_for_process(rsync_pid, &status);
1135         if (ret < 0)
1136                 goto out;
1137         ret = handle_rsync_exit(status);
1138         if (ret < 0)
1139                 goto out;
1140         post_create_hook();
1141         if (post_create_hook_pid)
1142                 ret = wait_for_process(post_create_hook_pid, &status);
1143 out:
1144         free_rsync_argv(rsync_argv);
1145         return ret;
1146 }
1147
1148 int com_ls(void)
1149 {
1150         int i;
1151         struct snapshot_list sl;
1152         struct snapshot *s;
1153         get_snapshot_list(&sl);
1154         FOR_EACH_SNAPSHOT(s, i, &sl)
1155                 dss_msg("%u\t%s\n", s->interval, s->name);
1156         free_snapshot_list(&sl);
1157         return 1;
1158 }
1159
1160 static void setup_signal_handling(void)
1161 {
1162         int ret;
1163
1164         DSS_INFO_LOG("setting up signal handlers\n");
1165         signal_pipe = signal_init(); /* always successful */
1166         ret = install_sighandler(SIGINT);
1167         if (ret < 0)
1168                 goto err;
1169         ret = install_sighandler(SIGTERM);
1170         if (ret < 0)
1171                 goto err;
1172         ret = install_sighandler(SIGCHLD);
1173         if (ret < 0)
1174                 goto err;
1175         return;
1176 err:
1177         DSS_EMERG_LOG("could not install signal handlers\n");
1178         exit(EXIT_FAILURE);
1179 }
1180
1181 int main(int argc, char **argv)
1182 {
1183         int ret;
1184         struct cmdline_parser_params params = {
1185                 .override = 0,
1186                 .initialize = 1,
1187                 .check_required = 0,
1188                 .check_ambiguity = 0
1189         };
1190
1191         cmdline_parser_ext(argc, argv, &conf, &params); /* aborts on errors */
1192         parse_config_file(0);
1193
1194         if (conf.daemon_given)
1195                 daemon_init();
1196         setup_signal_handling();
1197         ret = call_command_handler();
1198         if (ret < 0)
1199                 DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
1200         exit(ret >= 0? EXIT_SUCCESS : EXIT_FAILURE);
1201 }