]> git.tuebingen.mpg.de Git - dss.git/blob - dss.c
dss.c: Fix initialization of argv[].
[dss.git] / dss.c
1 /*
2  * Copyright (C) 2008-2011 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 pre-remove/rm/post-remove process. */
48 static pid_t remove_pid;
49 /** When the next snapshot is due. */
50 static int64_t next_snapshot_time;
51 /** When to try to remove something. */
52 static struct timeval next_removal_check;
53 /** Creation time of the snapshot currently being created. */
54 static int64_t current_snapshot_creation_time;
55 /** The snapshot currently being removed. */
56 struct snapshot *snapshot_currently_being_removed;
57 /** Needed by the post-create hook. */
58 static char *path_to_last_complete_snapshot;
59 static char *name_of_reference_snapshot;
60 /** \sa \ref snap.h for details. */
61 enum hook_status snapshot_creation_status;
62 /** \sa \ref snap.h for details. */
63 enum hook_status snapshot_removal_status;
64
65
66 DEFINE_DSS_ERRLIST;
67 static const char *hook_status_description[] = {HOOK_STATUS_ARRAY};
68
69 /* may be called with ds == NULL. */
70 static int disk_space_low(struct disk_space *ds)
71 {
72         struct disk_space ds_struct;
73
74         if (!ds) {
75                 int ret = get_disk_space(".", &ds_struct);
76                 if (ret < 0)
77                         return ret;
78                 ds = &ds_struct;
79         }
80         if (conf.min_free_mb_arg)
81                 if (ds->free_mb < conf.min_free_mb_arg)
82                         return 1;
83         if (conf.min_free_percent_arg)
84                 if (ds->percent_free < conf.min_free_percent_arg)
85                         return 1;
86         if (conf.min_free_percent_inodes_arg)
87                 if (ds->percent_free_inodes < conf.min_free_percent_inodes_arg)
88                         return 1;
89         return 0;
90 }
91
92 static void dump_dss_config(const char *msg)
93 {
94         const char dash[] = "-----------------------------";
95         int ret;
96         FILE *log = logfile? logfile : stderr;
97         struct disk_space ds;
98         int64_t now = get_current_time();
99
100         if (conf.loglevel_arg > INFO)
101                 return;
102
103         fprintf(log, "%s <%s config> %s\n", dash, msg, dash);
104         fprintf(log, "\n*** disk space ***\n\n");
105         ret = get_disk_space(".", &ds);
106         if (ret >= 0) {
107                 DSS_INFO_LOG("disk space low: %s\n", disk_space_low(&ds)?
108                         "yes" : "no");
109                 log_disk_space(&ds);
110         } else
111                 DSS_ERROR_LOG("can not get free disk space: %s\n",
112                         dss_strerror(-ret));
113
114         /* we continue on errors from get_disk_space */
115
116         fprintf(log, "\n*** command line and config file options ***\n\n");
117         cmdline_parser_dump(log, &conf);
118         fprintf(log, "\n*** internal state ***\n\n");
119         fprintf(log,
120                 "pid: %d\n"
121                 "logile: %s\n"
122                 "snapshot_currently_being_removed: %s\n"
123                 "path_to_last_complete_snapshot: %s\n"
124                 "reference_snapshot: %s\n"
125                 "snapshot_creation_status: %s\n"
126                 "snapshot_removal_status: %s\n"
127                 ,
128                 (int) getpid(),
129                 logfile? conf.logfile_arg : "stderr",
130                 snapshot_currently_being_removed?
131                         snapshot_currently_being_removed->name : "(none)",
132                 path_to_last_complete_snapshot?
133                         path_to_last_complete_snapshot : "(none)",
134                 name_of_reference_snapshot?
135                         name_of_reference_snapshot : "(none)",
136                 hook_status_description[snapshot_creation_status],
137                 hook_status_description[snapshot_removal_status]
138         );
139         if (create_pid != 0)
140                 fprintf(log,
141                         "create_pid: %" PRId32 "\n"
142                         "create process is %sstopped\n"
143                         ,
144                         create_pid,
145                         create_process_stopped? "" : "not "
146                 );
147         if (remove_pid != 0)
148                 fprintf(log, "remove_pid: %" PRId32 "\n", remove_pid);
149         if (next_snapshot_time != 0)
150                 fprintf(log, "next snapshot due in %" PRId64 " seconds\n",
151                         next_snapshot_time - now);
152         if (current_snapshot_creation_time != 0)
153                 fprintf(log, "current_snapshot_creation_time: %"
154                         PRId64 " (%" PRId64 " seconds ago)\n",
155                         current_snapshot_creation_time,
156                         now - current_snapshot_creation_time
157                 );
158         if (next_removal_check.tv_sec != 0) {
159                 fprintf(log, "next removal check: %llu (%llu seconds ago)\n",
160                         (long long unsigned)next_removal_check.tv_sec,
161                         now - (long long unsigned)next_removal_check.tv_sec
162                 );
163
164         }
165         fprintf(log, "%s </%s config> %s\n", dash, msg, dash);
166 }
167
168 /* a litte cpp magic helps to DRY */
169 #define COMMANDS \
170         COMMAND(ls) \
171         COMMAND(create) \
172         COMMAND(prune) \
173         COMMAND(run)
174 #define COMMAND(x) static int com_ ##x(void);
175 COMMANDS
176 #undef COMMAND
177 #define COMMAND(x) if (conf.x ##_given) return com_ ##x();
178 static int call_command_handler(void)
179 {
180         COMMANDS
181         DSS_EMERG_LOG("BUG: did not find command handler\n");
182         return -E_BUG;
183 }
184 #undef COMMAND
185 #undef COMMANDS
186
187 /**
188  * The log function of dss.
189  *
190  * \param ll Loglevel.
191  * \param fml Usual format string.
192  *
193  * All DSS_XXX_LOG() macros use this function.
194  */
195 __printf_2_3 void dss_log(int ll, const char* fmt,...)
196 {
197         va_list argp;
198         FILE *outfd;
199         struct tm *tm;
200         time_t t1;
201         char str[255] = "";
202
203         if (ll < conf.loglevel_arg)
204                 return;
205         outfd = logfile? logfile : stderr;
206         time(&t1);
207         tm = localtime(&t1);
208         strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
209         fprintf(outfd, "%s ", str);
210         if (conf.loglevel_arg <= INFO)
211                 fprintf(outfd, "%i: ", ll);
212         va_start(argp, fmt);
213         vfprintf(outfd, fmt, argp);
214         va_end(argp);
215 }
216
217 /**
218  * Print a message either to stdout or to the log file.
219  */
220 static __printf_1_2 void dss_msg(const char* fmt,...)
221 {
222         FILE *outfd = conf.daemon_given? logfile : stdout;
223         va_list argp;
224         va_start(argp, fmt);
225         vfprintf(outfd, fmt, argp);
226         va_end(argp);
227 }
228
229 static void dss_get_snapshot_list(struct snapshot_list *sl)
230 {
231         get_snapshot_list(sl, conf.unit_interval_arg, conf.num_intervals_arg);
232 }
233
234 static int64_t compute_next_snapshot_time(void)
235 {
236         int64_t x = 0, now = get_current_time(), unit_interval
237                 = 24 * 3600 * conf.unit_interval_arg, ret;
238         unsigned wanted = desired_number_of_snapshots(0, conf.num_intervals_arg),
239                 num_complete_snapshots = 0;
240         int i;
241         struct snapshot *s = NULL;
242         struct snapshot_list sl;
243
244         dss_get_snapshot_list(&sl);
245         FOR_EACH_SNAPSHOT(s, i, &sl) {
246                 if (!(s->flags & SS_COMPLETE))
247                         continue;
248                 num_complete_snapshots++;
249                 x += s->completion_time - s->creation_time;
250         }
251         assert(x >= 0);
252
253         ret = now;
254         if (num_complete_snapshots == 0)
255                 goto out;
256         x /= num_complete_snapshots; /* avg time to create one snapshot */
257         if (unit_interval < x * wanted) /* oops, no sleep at all */
258                 goto out;
259         ret = s->completion_time + unit_interval / wanted - x;
260 out:
261         free_snapshot_list(&sl);
262         return ret;
263 }
264
265 static inline void invalidate_next_snapshot_time(void)
266 {
267         next_snapshot_time = 0;
268 }
269
270 static inline int next_snapshot_time_is_valid(void)
271 {
272         return next_snapshot_time != 0;
273 }
274
275 static int next_snapshot_is_due(void)
276 {
277         int64_t now = get_current_time();
278
279         if (!next_snapshot_time_is_valid())
280                 next_snapshot_time = compute_next_snapshot_time();
281         if (next_snapshot_time <= now) {
282                 DSS_DEBUG_LOG("next snapshot: now\n");
283                 return 1;
284         }
285         DSS_DEBUG_LOG("next snapshot due in %" PRId64 " seconds\n",
286                 next_snapshot_time - now);
287         return 0;
288 }
289
290 static void pre_create_hook(void)
291 {
292         assert(snapshot_creation_status == HS_READY);
293         /* make sure that the next snapshot time will be recomputed */
294         invalidate_next_snapshot_time();
295         DSS_DEBUG_LOG("executing %s\n", conf.pre_create_hook_arg);
296         dss_exec_cmdline_pid(&create_pid, conf.pre_create_hook_arg);
297         snapshot_creation_status = HS_PRE_RUNNING;
298 }
299
300 static void pre_remove_hook(struct snapshot *s, const char *why)
301 {
302         char *cmd;
303
304         if (!s)
305                 return;
306         DSS_DEBUG_LOG("%s snapshot %s\n", why, s->name);
307         assert(snapshot_removal_status == HS_READY);
308         assert(remove_pid == 0);
309         assert(!snapshot_currently_being_removed);
310
311         snapshot_currently_being_removed = dss_malloc(sizeof(struct snapshot));
312         *snapshot_currently_being_removed = *s;
313         snapshot_currently_being_removed->name = dss_strdup(s->name);
314
315         cmd = make_message("%s %s/%s", conf.pre_remove_hook_arg,
316                 conf.dest_dir_arg, s->name);
317         DSS_DEBUG_LOG("executing %s\n", cmd);
318         dss_exec_cmdline_pid(&remove_pid, cmd);
319         free(cmd);
320         snapshot_removal_status = HS_PRE_RUNNING;
321 }
322
323 static int exec_rm(void)
324 {
325         struct snapshot *s = snapshot_currently_being_removed;
326         char *new_name = being_deleted_name(s);
327         char *argv[4];
328         int ret;
329
330         argv[0] = "rm";
331         argv[1] = "-rf";
332         argv[2] = new_name;
333         argv[3] = NULL;
334
335         assert(snapshot_removal_status == HS_PRE_SUCCESS);
336         assert(remove_pid == 0);
337
338         DSS_NOTICE_LOG("removing %s (interval = %i)\n", s->name, s->interval);
339         ret = dss_rename(s->name, new_name);
340         if (ret < 0)
341                 goto out;
342         dss_exec(&remove_pid, argv[0], argv);
343         snapshot_removal_status = HS_RUNNING;
344 out:
345         free(new_name);
346         return ret;
347 }
348
349 static int snapshot_is_being_created(struct snapshot *s)
350 {
351         return s->creation_time == current_snapshot_creation_time;
352 }
353
354 static struct snapshot *find_orphaned_snapshot(struct snapshot_list *sl)
355 {
356         struct snapshot *s;
357         int i;
358
359         DSS_DEBUG_LOG("looking for orphaned snapshots\n");
360         FOR_EACH_SNAPSHOT(s, i, sl) {
361                 if (snapshot_is_being_created(s))
362                         continue;
363                 /*
364                  * We know that no rm is currently running, so if s is marked
365                  * as being deleted, a previously started rm must have failed.
366                  */
367                 if (s->flags & SS_BEING_DELETED)
368                         return s;
369
370                 if (s->flags & SS_COMPLETE) /* good snapshot */
371                         continue;
372                 /*
373                  * This snapshot is incomplete and it is not the snapshot
374                  * currently being created. However, we must not remove it if
375                  * rsync is about to be restarted. As only the newest snapshot
376                  * can be restarted, this snapshot is orphaned if it is not the
377                  * newest snapshot or if we are not about to restart rsync.
378                  */
379                 if (get_newest_snapshot(sl) != s)
380                         return s;
381                 if (snapshot_creation_status != HS_NEEDS_RESTART)
382                         return s;
383         }
384         /* no orphaned snapshots */
385         return NULL;
386 }
387
388 static int is_reference_snapshot(struct snapshot *s)
389 {
390         if (!name_of_reference_snapshot)
391                 return 0;
392         return strcmp(s->name, name_of_reference_snapshot)? 0 : 1;
393 }
394
395 /*
396  * return: 0: no redundant snapshots, 1: rm process started, negative: error
397  */
398 static struct snapshot *find_redundant_snapshot(struct snapshot_list *sl)
399 {
400         int i, interval;
401         struct snapshot *s;
402         unsigned missing = 0;
403
404         DSS_DEBUG_LOG("looking for intervals containing too many snapshots\n");
405         for (interval = conf.num_intervals_arg - 1; interval >= 0; interval--) {
406                 unsigned keep = desired_number_of_snapshots(interval, conf.num_intervals_arg);
407                 unsigned num = sl->interval_count[interval];
408                 struct snapshot *victim = NULL, *prev = NULL;
409                 int64_t score = LONG_MAX;
410
411                 if (keep >= num)
412                         missing += keep - num;
413 //              DSS_DEBUG_LOG("interval %i: keep: %u, have: %u, missing: %u\n",
414 //                      interval, keep, num, missing);
415                 if (keep + missing >= num)
416                         continue;
417                 /* redundant snapshot in this interval, pick snapshot with lowest score */
418                 FOR_EACH_SNAPSHOT(s, i, sl) {
419                         int64_t this_score;
420
421                         if (snapshot_is_being_created(s))
422                                 continue;
423                         if (is_reference_snapshot(s))
424                                 continue;
425                         //DSS_DEBUG_LOG("checking %s\n", s->name);
426                         if (s->interval > interval) {
427                                 prev = s;
428                                 continue;
429                         }
430                         if (s->interval < interval)
431                                 break;
432                         if (!victim) {
433                                 victim = s;
434                                 prev = s;
435                                 continue;
436                         }
437                         assert(prev);
438                         /* check if s is a better victim */
439                         this_score = s->creation_time - prev->creation_time;
440                         assert(this_score >= 0);
441                         //DSS_DEBUG_LOG("%s: score %lli\n", s->name, (long long)score);
442                         if (this_score < score) {
443                                 score = this_score;
444                                 victim = s;
445                         }
446                         prev = s;
447                 }
448                 assert(victim);
449                 return victim;
450         }
451         return NULL;
452 }
453
454 static struct snapshot *find_outdated_snapshot(struct snapshot_list *sl)
455 {
456         int i;
457         struct snapshot *s;
458
459         DSS_DEBUG_LOG("looking for snapshots belonging to intervals >= %d\n",
460                 conf.num_intervals_arg);
461         FOR_EACH_SNAPSHOT(s, i, sl) {
462                 if (snapshot_is_being_created(s))
463                         continue;
464                 if (is_reference_snapshot(s))
465                         continue;
466                 if (s->interval < conf.num_intervals_arg)
467                         continue;
468                 return s;
469         }
470         return NULL;
471 }
472
473 struct snapshot *find_oldest_removable_snapshot(struct snapshot_list *sl)
474 {
475         int i;
476         struct snapshot *s;
477         FOR_EACH_SNAPSHOT(s, i, sl) {
478                 if (snapshot_is_being_created(s))
479                         continue;
480                 if (is_reference_snapshot(s))
481                         continue;
482                 DSS_INFO_LOG("oldest removable snapshot: %s\n", s->name);
483                 return s;
484         }
485         return NULL;
486 }
487
488 static int rename_incomplete_snapshot(int64_t start)
489 {
490         char *old_name;
491         int ret;
492
493         free(path_to_last_complete_snapshot);
494         ret = complete_name(start, get_current_time(),
495                 &path_to_last_complete_snapshot);
496         if (ret < 0)
497                 return ret;
498         old_name = incomplete_name(start);
499         ret = dss_rename(old_name, path_to_last_complete_snapshot);
500         if (ret >= 0)
501                 DSS_NOTICE_LOG("%s -> %s\n", old_name,
502                         path_to_last_complete_snapshot);
503         free(old_name);
504         return ret;
505 }
506
507 static int try_to_free_disk_space(void)
508 {
509         int ret;
510         struct snapshot_list sl;
511         struct snapshot *victim;
512         struct timeval now;
513         const char *why;
514         int low_disk_space;
515
516         ret = disk_space_low(NULL);
517         if (ret < 0)
518                 return ret;
519         low_disk_space = ret;
520         gettimeofday(&now, NULL);
521         if (tv_diff(&next_removal_check, &now, NULL) > 0)
522                 return 0;
523         if (!low_disk_space) {
524                 if (conf.keep_redundant_given)
525                         return 0;
526                 if (snapshot_creation_status != HS_READY)
527                         return 0;
528                 if (next_snapshot_is_due())
529                         return 0;
530         }
531         dss_get_snapshot_list(&sl);
532         ret = 0;
533         if (!low_disk_space && sl.num_snapshots <= 1)
534                 goto out;
535         why = "outdated";
536         victim = find_outdated_snapshot(&sl);
537         if (victim)
538                 goto remove;
539         why = "redundant";
540         victim = find_redundant_snapshot(&sl);
541         if (victim)
542                 goto remove;
543         /* try harder only if disk space is low */
544         if (!low_disk_space)
545                 goto out;
546         why = "orphaned";
547         victim = find_orphaned_snapshot(&sl);
548         if (victim)
549                 goto remove;
550         DSS_WARNING_LOG("disk space low and nothing obvious to remove\n");
551         victim = find_oldest_removable_snapshot(&sl);
552         if (victim)
553                 goto remove;
554         DSS_CRIT_LOG("uhuhu: disk space low and nothing to remove\n");
555         ret = -ERRNO_TO_DSS_ERROR(ENOSPC);
556         goto out;
557 remove:
558         pre_remove_hook(victim, why);
559 out:
560         free_snapshot_list(&sl);
561         return ret;
562 }
563
564 static void post_create_hook(void)
565 {
566         char *cmd = make_message("%s %s/%s", conf.post_create_hook_arg,
567                 conf.dest_dir_arg, path_to_last_complete_snapshot);
568         DSS_NOTICE_LOG("executing %s\n", cmd);
569         dss_exec_cmdline_pid(&create_pid, cmd);
570         free(cmd);
571         snapshot_creation_status = HS_POST_RUNNING;
572 }
573
574 static void post_remove_hook(void)
575 {
576         char *cmd;
577         struct snapshot *s = snapshot_currently_being_removed;
578
579         assert(s);
580
581         cmd = make_message("%s %s/%s", conf.post_remove_hook_arg,
582                 conf.dest_dir_arg, s->name);
583         DSS_NOTICE_LOG("executing %s\n", cmd);
584         dss_exec_cmdline_pid(&remove_pid, cmd);
585         free(cmd);
586         snapshot_removal_status = HS_POST_RUNNING;
587 }
588
589 static void dss_kill(pid_t pid, int sig, const char *msg)
590 {
591         const char *signame, *process_name;
592
593         if (pid == 0)
594                 return;
595         switch (sig) {
596         case SIGTERM: signame = "TERM"; break;
597         case SIGSTOP: signame = "STOP"; break;
598         case SIGCONT: signame = "CONT"; break;
599         default: signame = "????";
600         }
601
602         if (pid == create_pid)
603                 process_name = "create";
604         else if (pid == remove_pid)
605                 process_name = "remove";
606         else process_name = "??????";
607
608         if (msg)
609                 DSS_INFO_LOG("%s\n", msg);
610         DSS_DEBUG_LOG("sending signal %d (%s) to pid %d (%s process)\n",
611                 sig, signame, (int)pid, process_name);
612         if (kill(pid, sig) >= 0)
613                 return;
614         DSS_INFO_LOG("failed to send signal %d (%s) to pid %d (%s process)\n",
615                 sig, signame, (int)pid, process_name);
616 }
617
618 static void stop_create_process(void)
619 {
620         if (create_process_stopped)
621                 return;
622         dss_kill(create_pid, SIGSTOP, "suspending create process");
623         create_process_stopped = 1;
624 }
625
626 static void restart_create_process(void)
627 {
628         if (!create_process_stopped)
629                 return;
630         dss_kill(create_pid, SIGCONT, "resuming create process");
631         create_process_stopped = 0;
632 }
633
634 /**
635  * Print a log message about the exit status of a child.
636  */
637 static void log_termination_msg(pid_t pid, int status)
638 {
639         if (WIFEXITED(status))
640                 DSS_INFO_LOG("child %i exited. Exit status: %i\n", (int)pid,
641                         WEXITSTATUS(status));
642         else if (WIFSIGNALED(status))
643                 DSS_NOTICE_LOG("child %i was killed by signal %i\n", (int)pid,
644                         WTERMSIG(status));
645         else
646                 DSS_WARNING_LOG("child %i terminated abormally\n", (int)pid);
647 }
648
649 static int wait_for_process(pid_t pid, int *status)
650 {
651         int ret;
652
653         DSS_DEBUG_LOG("Waiting for process %d to terminate\n", (int)pid);
654         for (;;) {
655                 fd_set rfds;
656
657                 FD_ZERO(&rfds);
658                 FD_SET(signal_pipe, &rfds);
659                 ret = dss_select(signal_pipe + 1, &rfds, NULL, NULL);
660                 if (ret < 0)
661                         break;
662                 ret = next_signal();
663                 if (!ret)
664                         continue;
665                 if (ret == SIGCHLD) {
666                         ret = waitpid(pid, status, 0);
667                         if (ret >= 0)
668                                 break;
669                         if (errno != EINTR) { /* error */
670                                 ret = -ERRNO_TO_DSS_ERROR(errno);
671                                 break;
672                         }
673                 }
674                 /* SIGINT or SIGTERM */
675                 dss_kill(pid, SIGTERM, "killing child process");
676         }
677         if (ret < 0)
678                 DSS_ERROR_LOG("failed to wait for process %d\n", (int)pid);
679         else
680                 log_termination_msg(pid, *status);
681         return ret;
682 }
683
684 static void handle_pre_remove_exit(int status)
685 {
686         if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
687                 snapshot_removal_status = HS_READY;
688                 gettimeofday(&next_removal_check, NULL);
689                 next_removal_check.tv_sec += 60;
690                 return;
691         }
692         snapshot_removal_status = HS_PRE_SUCCESS;
693 }
694
695 static int handle_rm_exit(int status)
696 {
697         if (!WIFEXITED(status)) {
698                 snapshot_removal_status = HS_READY;
699                 return -E_INVOLUNTARY_EXIT;
700         }
701         if (WEXITSTATUS(status)) {
702                 snapshot_removal_status = HS_READY;
703                 return -E_BAD_EXIT_CODE;
704         }
705         snapshot_removal_status = HS_SUCCESS;
706         return 1;
707 }
708
709 static void handle_post_remove_exit(void)
710 {
711         snapshot_removal_status = HS_READY;
712 }
713
714 static int handle_remove_exit(int status)
715 {
716         int ret;
717         struct snapshot *s = snapshot_currently_being_removed;
718
719         assert(s);
720         switch (snapshot_removal_status) {
721         case HS_PRE_RUNNING:
722                 handle_pre_remove_exit(status);
723                 ret = 1;
724                 break;
725         case HS_RUNNING:
726                 ret = handle_rm_exit(status);
727                 break;
728         case HS_POST_RUNNING:
729                 handle_post_remove_exit();
730                 ret = 1;
731                 break;
732         default:
733                 ret = -E_BUG;
734         }
735         if (snapshot_removal_status == HS_READY) {
736                 free(s->name);
737                 free(s);
738                 snapshot_currently_being_removed = NULL;
739         }
740         remove_pid = 0;
741         return ret;
742 }
743
744 static int wait_for_remove_process(void)
745 {
746         int status, ret;
747
748         assert(remove_pid);
749         assert(
750                 snapshot_removal_status == HS_PRE_RUNNING ||
751                 snapshot_removal_status == HS_RUNNING ||
752                 snapshot_removal_status == HS_POST_RUNNING
753         );
754         ret = wait_for_process(remove_pid, &status);
755         if (ret < 0)
756                 return ret;
757         return handle_remove_exit(status);
758 }
759
760 static int handle_rsync_exit(int status)
761 {
762         int es, ret;
763
764         if (!WIFEXITED(status)) {
765                 DSS_ERROR_LOG("rsync process %d died involuntary\n", (int)create_pid);
766                 ret = -E_INVOLUNTARY_EXIT;
767                 snapshot_creation_status = HS_READY;
768                 goto out;
769         }
770         es = WEXITSTATUS(status);
771         /*
772          * Restart rsync on non-fatal errors:
773          * 12: Error in rsync protocol data stream
774          * 13: Errors with program diagnostics
775          */
776         if (es == 12 || es == 13) {
777                 DSS_WARNING_LOG("rsync process %d returned %d -- restarting\n",
778                         (int)create_pid, es);
779                 snapshot_creation_status = HS_NEEDS_RESTART;
780                 next_snapshot_time = get_current_time() + 60;
781                 ret = 1;
782                 goto out;
783         }
784         if (es != 0 && es != 23 && es != 24) {
785                 DSS_ERROR_LOG("rsync process %d returned %d\n", (int)create_pid, es);
786                 ret = -E_BAD_EXIT_CODE;
787                 snapshot_creation_status = HS_READY;
788                 goto out;
789         }
790         ret = rename_incomplete_snapshot(current_snapshot_creation_time);
791         if (ret < 0)
792                 goto out;
793         snapshot_creation_status = HS_SUCCESS;
794         free(name_of_reference_snapshot);
795         name_of_reference_snapshot = NULL;
796 out:
797         create_process_stopped = 0;
798         return ret;
799 }
800
801 static int handle_pre_create_hook_exit(int status)
802 {
803         int es, ret;
804         static int warn_count;
805
806         if (!WIFEXITED(status)) {
807                 snapshot_creation_status = HS_READY;
808                 ret = -E_INVOLUNTARY_EXIT;
809                 goto out;
810         }
811         es = WEXITSTATUS(status);
812         if (es) {
813                 if (!warn_count--) {
814                         DSS_NOTICE_LOG("pre_create_hook %s returned %d\n",
815                                 conf.pre_create_hook_arg, es);
816                         DSS_NOTICE_LOG("deferring snapshot creation...\n");
817                         warn_count = 60; /* warn only once per hour */
818                 }
819                 next_snapshot_time = get_current_time() + 60;
820                 snapshot_creation_status = HS_READY;
821                 ret = 0;
822                 goto out;
823         }
824         warn_count = 0;
825         snapshot_creation_status = HS_PRE_SUCCESS;
826         ret = 1;
827 out:
828         return ret;
829 }
830
831 static int handle_sigchld(void)
832 {
833         pid_t pid;
834         int status, ret = reap_child(&pid, &status);
835
836         if (ret <= 0)
837                 return ret;
838
839         if (pid == create_pid) {
840                 switch (snapshot_creation_status) {
841                 case HS_PRE_RUNNING:
842                         ret = handle_pre_create_hook_exit(status);
843                         break;
844                 case HS_RUNNING:
845                         ret = handle_rsync_exit(status);
846                         break;
847                 case HS_POST_RUNNING:
848                         snapshot_creation_status = HS_READY;
849                         ret = 1;
850                         break;
851                 default:
852                         DSS_EMERG_LOG("BUG: create can't die in status %d\n",
853                                 snapshot_creation_status);
854                         return -E_BUG;
855                 }
856                 create_pid = 0;
857                 return ret;
858         }
859         if (pid == remove_pid) {
860                 ret = handle_remove_exit(status);
861                 if (ret < 0)
862                         return ret;
863                 return ret;
864         }
865         DSS_EMERG_LOG("BUG: unknown process %d died\n", (int)pid);
866         return -E_BUG;
867 }
868
869 static int check_config(void)
870 {
871         if (conf.unit_interval_arg <= 0) {
872                 DSS_ERROR_LOG("bad unit interval: %i\n", conf.unit_interval_arg);
873                 return -E_INVALID_NUMBER;
874         }
875         DSS_DEBUG_LOG("unit interval: %i day(s)\n", conf.unit_interval_arg);
876         if (conf.num_intervals_arg <= 0) {
877                 DSS_ERROR_LOG("bad number of intervals  %i\n", conf.num_intervals_arg);
878                 return -E_INVALID_NUMBER;
879         }
880         DSS_DEBUG_LOG("number of intervals: %i\n", conf.num_intervals_arg);
881         return 1;
882 }
883
884 /*
885  * Returns < 0 on errors, 0 if no config file is given and > 0 if the config
886  * file was read successfully.
887  */
888 static int parse_config_file(int override)
889 {
890         int ret, config_file_exists;
891         char *config_file;
892         struct stat statbuf;
893         char *old_logfile_arg = NULL;
894         int old_daemon_given = 0;
895
896         if (conf.config_file_given)
897                 config_file = dss_strdup(conf.config_file_arg);
898         else {
899                 char *home = get_homedir();
900                 config_file = make_message("%s/.dssrc", home);
901                 free(home);
902         }
903         if (override) { /* SIGHUP */
904                 if (conf.logfile_given)
905                         old_logfile_arg = dss_strdup(conf.logfile_arg);
906                 old_daemon_given = conf.daemon_given;
907         }
908
909         config_file_exists = !stat(config_file, &statbuf);
910         if (!config_file_exists && conf.config_file_given) {
911                 ret = -ERRNO_TO_DSS_ERROR(errno);
912                 DSS_ERROR_LOG("failed to stat config file %s\n", config_file);
913                 goto out;
914         }
915         if (config_file_exists) {
916                 struct cmdline_parser_params params = {
917                         .override = override,
918                         .initialize = 0,
919                         .check_required = 1,
920                         .check_ambiguity = 0,
921                         .print_errors = 1
922                 };
923                 if (override) { /* invalidate all rsync options */
924                         int i;
925
926                         for (i = 0; i < conf.rsync_option_given; i++) {
927                                 free(conf.rsync_option_arg[i]);
928                                 conf.rsync_option_arg[i] = NULL;
929                         }
930                         conf.rsync_option_given = 0;
931                 }
932                 cmdline_parser_config_file(config_file, &conf, &params);
933         }
934         ret = check_config();
935         if (ret < 0)
936                 goto out;
937         if (override) {
938                 /* don't change daemon mode on SIGHUP */
939                 conf.daemon_given = old_daemon_given;
940                 close_log(logfile);
941                 logfile = NULL;
942                 if (conf.logfile_given)
943                         free(old_logfile_arg);
944                 else if (conf.daemon_given) { /* re-use old logfile */
945                         conf.logfile_arg = old_logfile_arg;
946                         conf.logfile_given = 1;
947                 }
948         }
949         if (conf.logfile_given && conf.run_given && conf.daemon_given) {
950                 logfile = open_log(conf.logfile_arg);
951                 log_welcome(conf.loglevel_arg);
952         }
953         DSS_DEBUG_LOG("loglevel: %d\n", conf.loglevel_arg);
954         ret = config_file_exists;
955 out:
956         free(config_file);
957         if (ret < 0)
958                 DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
959         return ret;
960 }
961
962 static int change_to_dest_dir(void)
963 {
964         DSS_INFO_LOG("changing cwd to %s\n", conf.dest_dir_arg);
965         return dss_chdir(conf.dest_dir_arg);
966 }
967
968 static int handle_sighup(void)
969 {
970         int ret;
971
972         DSS_NOTICE_LOG("SIGHUP, re-reading config\n");
973         dump_dss_config("old");
974         ret = parse_config_file(1);
975         if (ret < 0)
976                 return ret;
977         dump_dss_config("reloaded");
978         invalidate_next_snapshot_time();
979         return change_to_dest_dir();
980 }
981
982 static int handle_signal(void)
983 {
984         int sig, ret = next_signal();
985
986         if (ret <= 0)
987                 goto out;
988         sig = ret;
989         switch (sig) {
990         case SIGINT:
991         case SIGTERM:
992                 restart_create_process();
993                 dss_kill(create_pid, SIGTERM, NULL);
994                 dss_kill(remove_pid, SIGTERM, NULL);
995                 ret = -E_SIGNAL;
996                 break;
997         case SIGHUP:
998                 ret = handle_sighup();
999                 break;
1000         case SIGCHLD:
1001                 ret = handle_sigchld();
1002                 break;
1003         }
1004 out:
1005         if (ret < 0)
1006                 DSS_ERROR_LOG("%s\n", dss_strerror(-ret));
1007         return ret;
1008 }
1009
1010 /*
1011  * We can not use rsync locally if the local user is different from the remote
1012  * user or if the src dir is not on the local host (or both).
1013  */
1014 static int use_rsync_locally(char *logname)
1015 {
1016         char *h = conf.remote_host_arg;
1017
1018         if (strcmp(h, "localhost") && strcmp(h, "127.0.0.1"))
1019                 return 0;
1020         if (conf.remote_user_given && strcmp(conf.remote_user_arg, logname))
1021                 return 0;
1022         return 1;
1023 }
1024
1025 static int rename_resume_snap(int64_t creation_time)
1026 {
1027         struct snapshot_list sl = {.num_snapshots = 0};
1028         struct snapshot *s = NULL;
1029         char *new_name = incomplete_name(creation_time);
1030         int ret;
1031         const char *why;
1032
1033         ret = 0;
1034         if (conf.no_resume_given)
1035                 goto out;
1036         dss_get_snapshot_list(&sl);
1037         /*
1038          * Snapshot recycling: We first look at the newest snapshot. If this
1039          * snapshot happens to be incomplete, the last rsync process was
1040          * aborted and we reuse this one. Otherwise we look at snapshots which
1041          * could be removed (outdated and redundant snapshots) as candidates
1042          * for recycling. If no outdated/redundant snapshot exists, we check if
1043          * there is an orphaned snapshot, which likely is useless anyway.
1044          *
1045          * Only if no existing snapshot is suitable for recycling, we bite the
1046          * bullet and create a new one.
1047          */
1048         s = get_newest_snapshot(&sl);
1049         if (!s) /* no snapshots at all */
1050                 goto out;
1051         /* re-use last snapshot if it is incomplete */
1052         why = "aborted";
1053         if ((s->flags & SS_COMPLETE) == 0)
1054                 goto out;
1055         why = "outdated";
1056         s = find_outdated_snapshot(&sl);
1057         if (s)
1058                 goto out;
1059         why = "redundant";
1060         s = find_redundant_snapshot(&sl);
1061         if (s)
1062                 goto out;
1063         why = "orphaned";
1064         s = find_orphaned_snapshot(&sl);
1065 out:
1066         if (s) {
1067                 DSS_INFO_LOG("reusing %s snapshot %s\n", why, s->name);
1068                 ret = dss_rename(s->name, new_name);
1069         }
1070         if (ret >= 0)
1071                 DSS_NOTICE_LOG("creating new snapshot %s\n", new_name);
1072         free(new_name);
1073         free_snapshot_list(&sl);
1074         return ret;
1075 }
1076
1077 static void create_rsync_argv(char ***argv, int64_t *num)
1078 {
1079         char *logname;
1080         int i = 0, j;
1081         struct snapshot_list sl;
1082
1083         dss_get_snapshot_list(&sl);
1084         assert(!name_of_reference_snapshot);
1085         name_of_reference_snapshot = name_of_newest_complete_snapshot(&sl);
1086         free_snapshot_list(&sl);
1087
1088         *argv = dss_malloc((15 + conf.rsync_option_given) * sizeof(char *));
1089         (*argv)[i++] = dss_strdup("rsync");
1090         (*argv)[i++] = dss_strdup("-aq");
1091         (*argv)[i++] = dss_strdup("--delete");
1092         for (j = 0; j < conf.rsync_option_given; j++)
1093                 (*argv)[i++] = dss_strdup(conf.rsync_option_arg[j]);
1094         if (name_of_reference_snapshot) {
1095                 DSS_INFO_LOG("using %s as reference\n", name_of_reference_snapshot);
1096                 (*argv)[i++] = make_message("--link-dest=../%s",
1097                         name_of_reference_snapshot);
1098         } else
1099                 DSS_INFO_LOG("no suitable reference snapshot found\n");
1100         logname = dss_logname();
1101         if (use_rsync_locally(logname))
1102                 (*argv)[i++] = dss_strdup(conf.source_dir_arg);
1103         else
1104                 (*argv)[i++] = make_message("%s@%s:%s/", conf.remote_user_given?
1105                         conf.remote_user_arg : logname,
1106                         conf.remote_host_arg, conf.source_dir_arg);
1107         free(logname);
1108         *num = get_current_time();
1109         (*argv)[i++] = incomplete_name(*num);
1110         (*argv)[i++] = NULL;
1111         for (j = 0; j < i; j++)
1112                 DSS_DEBUG_LOG("argv[%d] = %s\n", j, (*argv)[j]);
1113 }
1114
1115 static void free_rsync_argv(char **argv)
1116 {
1117         int i;
1118
1119         if (!argv)
1120                 return;
1121         for (i = 0; argv[i]; i++)
1122                 free(argv[i]);
1123         free(argv);
1124 }
1125
1126 static int create_snapshot(char **argv)
1127 {
1128         int ret;
1129
1130         ret = rename_resume_snap(current_snapshot_creation_time);
1131         if (ret < 0)
1132                 return ret;
1133         dss_exec(&create_pid, argv[0], argv);
1134         snapshot_creation_status = HS_RUNNING;
1135         return ret;
1136 }
1137
1138 static int select_loop(void)
1139 {
1140         int ret;
1141         /* check every 60 seconds for free disk space */
1142         struct timeval tv;
1143         char **rsync_argv = NULL;
1144
1145         for (;;) {
1146                 fd_set rfds;
1147                 struct timeval *tvp;
1148
1149                 if (remove_pid)
1150                         tvp = NULL; /* sleep until rm hook/process dies */
1151                 else { /* sleep one minute */
1152                         tv.tv_sec = 60;
1153                         tv.tv_usec = 0;
1154                         tvp = &tv;
1155                 }
1156                 FD_ZERO(&rfds);
1157                 FD_SET(signal_pipe, &rfds);
1158                 ret = dss_select(signal_pipe + 1, &rfds, NULL, tvp);
1159                 if (ret < 0)
1160                         goto out;
1161                 if (FD_ISSET(signal_pipe, &rfds)) {
1162                         ret = handle_signal();
1163                         if (ret < 0)
1164                                 goto out;
1165                 }
1166                 if (remove_pid)
1167                         continue;
1168                 if (snapshot_removal_status == HS_PRE_SUCCESS) {
1169                         ret = exec_rm();
1170                         if (ret < 0)
1171                                 goto out;
1172                         continue;
1173                 }
1174                 if (snapshot_removal_status == HS_SUCCESS) {
1175                         post_remove_hook();
1176                         continue;
1177                 }
1178                 ret = try_to_free_disk_space();
1179                 if (ret < 0)
1180                         goto out;
1181                 if (snapshot_removal_status != HS_READY) {
1182                         stop_create_process();
1183                         continue;
1184                 }
1185                 restart_create_process();
1186                 switch (snapshot_creation_status) {
1187                 case HS_READY:
1188                         if (!next_snapshot_is_due())
1189                                 continue;
1190                         pre_create_hook();
1191                         continue;
1192                 case HS_PRE_RUNNING:
1193                 case HS_RUNNING:
1194                 case HS_POST_RUNNING:
1195                         continue;
1196                 case HS_PRE_SUCCESS:
1197                         if (!name_of_reference_snapshot) {
1198                                 free_rsync_argv(rsync_argv);
1199                                 create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
1200                         }
1201                         ret = create_snapshot(rsync_argv);
1202                         if (ret < 0)
1203                                 goto out;
1204                         continue;
1205                 case HS_NEEDS_RESTART:
1206                         if (!next_snapshot_is_due())
1207                                 continue;
1208                         ret = create_snapshot(rsync_argv);
1209                         if (ret < 0)
1210                                 goto out;
1211                         continue;
1212                 case HS_SUCCESS:
1213                         post_create_hook();
1214                         continue;
1215                 }
1216         }
1217 out:
1218         return ret;
1219 }
1220
1221 static void exit_hook(int exit_code)
1222 {
1223         char *argv[3];
1224         pid_t pid;
1225
1226         argv[0] = conf.exit_hook_arg;
1227         argv[1] = dss_strerror(-exit_code);
1228         argv[2] = NULL;
1229
1230         DSS_NOTICE_LOG("executing %s %s\n", argv[0], argv[1]);
1231         dss_exec(&pid, conf.exit_hook_arg, argv);
1232 }
1233
1234 static int com_run(void)
1235 {
1236         int ret;
1237
1238         if (conf.dry_run_given) {
1239                 DSS_ERROR_LOG("dry_run not supported by this command\n");
1240                 return -E_SYNTAX;
1241         }
1242         ret = install_sighandler(SIGHUP);
1243         if (ret < 0)
1244                 return ret;
1245         ret = select_loop();
1246         if (ret >= 0) /* impossible */
1247                 ret = -E_BUG;
1248         exit_hook(ret);
1249         return ret;
1250 }
1251
1252 static int com_prune(void)
1253 {
1254         int ret;
1255         struct snapshot_list sl;
1256         struct snapshot *victim;
1257         struct disk_space ds;
1258         const char *why;
1259
1260         ret = get_disk_space(".", &ds);
1261         if (ret < 0)
1262                 return ret;
1263         log_disk_space(&ds);
1264         dss_get_snapshot_list(&sl);
1265         why = "outdated";
1266         victim = find_outdated_snapshot(&sl);
1267         if (victim)
1268                 goto rm;
1269         why = "redundant";
1270         victim = find_redundant_snapshot(&sl);
1271         if (victim)
1272                 goto rm;
1273         ret = 0;
1274         goto out;
1275 rm:
1276         if (conf.dry_run_given) {
1277                 dss_msg("%s snapshot %s (interval = %i)\n",
1278                         why, victim->name, victim->interval);
1279                 ret = 0;
1280                 goto out;
1281         }
1282         pre_remove_hook(victim, why);
1283         if (snapshot_removal_status == HS_PRE_RUNNING) {
1284                 ret = wait_for_remove_process();
1285                 if (ret < 0)
1286                         goto out;
1287                 if (snapshot_removal_status != HS_PRE_SUCCESS)
1288                         goto out;
1289         }
1290         ret = exec_rm();
1291         if (ret < 0)
1292                 goto out;
1293         ret = wait_for_remove_process();
1294         if (ret < 0)
1295                 goto out;
1296         if (snapshot_removal_status != HS_SUCCESS)
1297                 goto out;
1298         post_remove_hook();
1299         if (snapshot_removal_status != HS_POST_RUNNING)
1300                 goto out;
1301         ret = wait_for_remove_process();
1302         if (ret < 0)
1303                 goto out;
1304         ret = 1;
1305 out:
1306         free_snapshot_list(&sl);
1307         return ret;
1308 }
1309
1310 static int com_create(void)
1311 {
1312         int ret, status;
1313         char **rsync_argv;
1314
1315         if (conf.dry_run_given) {
1316                 int i;
1317                 char *msg = NULL;
1318                 create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
1319                 for (i = 0; rsync_argv[i]; i++) {
1320                         char *tmp = msg;
1321                         msg = make_message("%s%s%s", tmp? tmp : "",
1322                                 tmp? " " : "", rsync_argv[i]);
1323                         free(tmp);
1324                 }
1325                 free_rsync_argv(rsync_argv);
1326                 dss_msg("%s\n", msg);
1327                 free(msg);
1328                 return 1;
1329         }
1330         pre_create_hook();
1331         if (create_pid) {
1332                 ret = wait_for_process(create_pid, &status);
1333                 if (ret < 0)
1334                         return ret;
1335                 ret = handle_pre_create_hook_exit(status);
1336                 if (ret <= 0) /* error, or pre-create failed */
1337                         return ret;
1338         }
1339         create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
1340         ret = create_snapshot(rsync_argv);
1341         if (ret < 0)
1342                 goto out;
1343         ret = wait_for_process(create_pid, &status);
1344         if (ret < 0)
1345                 goto out;
1346         ret = handle_rsync_exit(status);
1347         if (ret < 0)
1348                 goto out;
1349         post_create_hook();
1350         if (create_pid)
1351                 ret = wait_for_process(create_pid, &status);
1352 out:
1353         free_rsync_argv(rsync_argv);
1354         return ret;
1355 }
1356
1357 static int com_ls(void)
1358 {
1359         int i;
1360         struct snapshot_list sl;
1361         struct snapshot *s;
1362
1363         dss_get_snapshot_list(&sl);
1364         FOR_EACH_SNAPSHOT(s, i, &sl) {
1365                 int64_t d = 0;
1366                 if (s->flags & SS_COMPLETE)
1367                         d = (s->completion_time - s->creation_time) / 60;
1368                 dss_msg("%u\t%s\t%3" PRId64 ":%02" PRId64 "\n", s->interval, s->name, d/60, d%60);
1369         };
1370         free_snapshot_list(&sl);
1371         return 1;
1372 }
1373
1374 static int setup_signal_handling(void)
1375 {
1376         int ret;
1377
1378         DSS_INFO_LOG("setting up signal handlers\n");
1379         signal_pipe = signal_init(); /* always successful */
1380         ret = install_sighandler(SIGINT);
1381         if (ret < 0)
1382                 return ret;
1383         ret = install_sighandler(SIGTERM);
1384         if (ret < 0)
1385                 return ret;
1386         return install_sighandler(SIGCHLD);
1387 }
1388
1389 /**
1390  * The main function of dss.
1391  *
1392  * \param argc Usual argument count.
1393  * \param argv Usual argument vector.
1394  */
1395 int main(int argc, char **argv)
1396 {
1397         int ret;
1398         struct cmdline_parser_params params = {
1399                 .override = 0,
1400                 .initialize = 1,
1401                 .check_required = 0,
1402                 .check_ambiguity = 0,
1403                 .print_errors = 1
1404         };
1405
1406         cmdline_parser_ext(argc, argv, &conf, &params); /* aborts on errors */
1407         ret = parse_config_file(0);
1408         if (ret < 0)
1409                 goto out;
1410         if (ret == 0) { /* no config file given */
1411                 /*
1412                  * Parse the command line options again, but this time check
1413                  * that all required options are given.
1414                  */
1415                 params = (struct cmdline_parser_params) {
1416                         .override = 1,
1417                         .initialize = 1,
1418                         .check_required = 1,
1419                         .check_ambiguity = 1,
1420                         .print_errors = 1
1421                 };
1422                 cmdline_parser_ext(argc, argv, &conf, &params); /* aborts on errors */
1423         }
1424         if (conf.daemon_given)
1425                 daemon_init();
1426         ret = change_to_dest_dir();
1427         if (ret < 0)
1428                 goto out;
1429         dump_dss_config("startup");
1430         ret = setup_signal_handling();
1431         if (ret < 0)
1432                 goto out;
1433         ret = call_command_handler();
1434 out:
1435         if (ret < 0)
1436                 DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
1437         exit(ret >= 0? EXIT_SUCCESS : EXIT_FAILURE);
1438 }