]> git.tuebingen.mpg.de Git - dss.git/blob - dss.c
Remove stale comment.
[dss.git] / dss.c
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #include <string.h>
3 #include <stdlib.h>
4 #include <stdio.h>
5 #include <stdarg.h>
6 #include <assert.h>
7 #include <errno.h>
8 #include <sys/types.h>
9 #include <signal.h>
10 #include <ctype.h>
11 #include <stdbool.h>
12 #include <sys/stat.h>
13 #include <unistd.h>
14 #include <inttypes.h>
15 #include <sys/time.h>
16 #include <time.h>
17 #include <sys/wait.h>
18 #include <fnmatch.h>
19 #include <limits.h>
20 #include <fcntl.h>
21 #include <lopsub.h>
22 #include <sys/mman.h>
23
24 #include "gcc-compat.h"
25 #include "log.h"
26 #include "str.h"
27 #include "err.h"
28 #include "file.h"
29 #include "exec.h"
30 #include "daemon.h"
31 #include "sig.h"
32 #include "df.h"
33 #include "tv.h"
34 #include "snap.h"
35 #include "ipc.h"
36 #include "dss.lsg.h"
37
38 #define CMD_PTR(_cname) lls_cmd(LSG_DSS_CMD_ ## _cname, dss_suite)
39 #define OPT_RESULT(_cname, _oname) (lls_opt_result(\
40         LSG_DSS_ ## _cname ## _OPT_ ## _oname, (CMD_PTR(_cname) == CMD_PTR(DSS))? lpr : sublpr))
41 #define OPT_GIVEN(_cname, _oname) (lls_opt_given(OPT_RESULT(_cname, _oname)))
42 #define OPT_STRING_VAL(_cname, _oname) (lls_string_val(0, \
43         OPT_RESULT(_cname, _oname)))
44 #define OPT_UINT32_VAL(_cname, _oname) (lls_uint32_val(0, \
45                 OPT_RESULT(_cname, _oname)))
46
47 struct dss_user_data {int (*handler)(void);};
48 #define EXPORT_CMD_HANDLER(_cmd) const struct dss_user_data \
49         lsg_dss_com_ ## _cmd ## _user_data = { \
50                 .handler = com_ ## _cmd \
51         };
52
53 /*
54  * Command line and active options. We need to keep a copy of the parsed
55  * command line options for the SIGHUP case where we merge the command line
56  * options and the new config file options.
57  */
58 static struct lls_parse_result *cmdline_lpr, *lpr;
59
60 /** Parsed subcommand options. */
61 static struct lls_parse_result *cmdline_sublpr, *sublpr;
62 /* The executing subcommand (NULL at startup). */
63 static const struct lls_command *subcmd;
64 /** Wether daemon_init() was called. */
65 static bool daemonized;
66 /** Non-NULL if we log to a file. */
67 static FILE *logfile;
68 /** The read end of the signal pipe */
69 static int signal_pipe;
70 /** Process id of current pre-create-hook/rsync/post-create-hook process. */
71 static pid_t create_pid;
72 /** Whether the pre-create-hook/rsync/post-create-hook is currently stopped. */
73 static int create_process_stopped;
74 /** How many times in a row the rsync command failed. */
75 static int num_consecutive_rsync_errors;
76 /** Process id of current pre-remove/rm/post-remove process. */
77 static pid_t remove_pid;
78 /** When the next snapshot is due. */
79 static int64_t next_snapshot_time;
80 /** When to try to remove something. */
81 static struct timeval next_removal_check;
82 /** Creation time of the snapshot currently being created. */
83 static int64_t current_snapshot_creation_time;
84 /* Set by the pre-rm hook, cleared by handle_remove_exit(). */
85 struct snapshot *snapshot_currently_being_removed;
86 /** Needed by the post-create hook. */
87 static char *path_to_last_complete_snapshot;
88 static char *name_of_reference_snapshot;
89 /** \sa \ref snap.h for details. */
90 enum hook_status snapshot_creation_status;
91 /** \sa \ref snap.h for details. */
92 enum hook_status snapshot_removal_status;
93
94
95 DEFINE_DSS_ERRLIST;
96 static const char *hook_status_description[] = {HOOK_STATUS_ARRAY};
97
98 /* may be called with ds == NULL. */
99 static int disk_space_low(struct disk_space *ds)
100 {
101         struct disk_space ds_struct;
102         uint32_t val;
103
104         if (!ds) {
105                 int ret = get_disk_space(".", &ds_struct);
106                 if (ret < 0)
107                         return ret;
108                 ds = &ds_struct;
109         }
110         val = OPT_UINT32_VAL(DSS, MIN_FREE_MB);
111         if (val != 0)
112                 if (ds->free_mb < val)
113                         return 1;
114         val = OPT_UINT32_VAL(DSS, MIN_FREE_PERCENT);
115         if (val != 0)
116                 if (ds->percent_free < val)
117                         return 1;
118         val = OPT_UINT32_VAL(DSS, MIN_FREE_PERCENT_INODES);
119         if (val != 0)
120                 if (ds->percent_free_inodes < val)
121                         return 1;
122         return 0;
123 }
124
125 static void dump_dss_config(const char *msg)
126 {
127         const char dash[] = "-----------------------------";
128         char *lopsub_dump;
129         int ret;
130         FILE *log = logfile? logfile : stderr;
131         struct disk_space ds;
132         int64_t now = get_current_time();
133
134         if (OPT_UINT32_VAL(DSS, LOGLEVEL) > INFO)
135                 return;
136
137         fprintf(log, "%s <%s config> %s\n", dash, msg, dash);
138         fprintf(log, "\n*** disk space ***\n\n");
139         ret = get_disk_space(".", &ds);
140         if (ret >= 0) {
141                 DSS_INFO_LOG(("disk space low: %s\n", disk_space_low(&ds)?
142                         "yes" : "no"));
143                 log_disk_space(&ds);
144         } else
145                 DSS_ERROR_LOG(("can not get free disk space: %s\n",
146                         dss_strerror(-ret)));
147
148         /* we continue on errors from get_disk_space */
149
150         fprintf(log, "\n*** non-default options ***\n\n");
151         lopsub_dump = lls_dump_parse_result(lpr, CMD_PTR(DSS), true);
152         fprintf(log, "%s", lopsub_dump);
153         free(lopsub_dump);
154         fprintf(log, "\n*** non-default options for \"run\" ***\n\n");
155         lopsub_dump = lls_dump_parse_result(lpr, CMD_PTR(RUN), true);
156         fprintf(log, "%s", lopsub_dump);
157         free(lopsub_dump);
158         fprintf(log, "\n*** internal state ***\n\n");
159         fprintf(log,
160                 "pid: %d\n"
161                 "logfile: %s\n"
162                 "snapshot_currently_being_removed: %s\n"
163                 "path_to_last_complete_snapshot: %s\n"
164                 "reference_snapshot: %s\n"
165                 "snapshot_creation_status: %s\n"
166                 "snapshot_removal_status: %s\n"
167                 "num_consecutive_rsync_errors: %d\n"
168                 ,
169                 (int) getpid(),
170                 logfile? OPT_STRING_VAL(RUN, LOGFILE) : "stderr",
171                 snapshot_currently_being_removed?
172                         snapshot_currently_being_removed->name : "(none)",
173                 path_to_last_complete_snapshot?
174                         path_to_last_complete_snapshot : "(none)",
175                 name_of_reference_snapshot?
176                         name_of_reference_snapshot : "(none)",
177                 hook_status_description[snapshot_creation_status],
178                 hook_status_description[snapshot_removal_status],
179                 num_consecutive_rsync_errors
180         );
181         if (create_pid != 0)
182                 fprintf(log,
183                         "create_pid: %" PRId32 "\n"
184                         "create process is %sstopped\n"
185                         ,
186                         create_pid,
187                         create_process_stopped? "" : "not "
188                 );
189         if (remove_pid != 0)
190                 fprintf(log, "remove_pid: %" PRId32 "\n", remove_pid);
191         if (next_snapshot_time != 0)
192                 fprintf(log, "next snapshot due in %" PRId64 " seconds\n",
193                         next_snapshot_time - now);
194         if (current_snapshot_creation_time != 0)
195                 fprintf(log, "current_snapshot_creation_time: %"
196                         PRId64 " (%" PRId64 " seconds ago)\n",
197                         current_snapshot_creation_time,
198                         now - current_snapshot_creation_time
199                 );
200         if (next_removal_check.tv_sec != 0) {
201                 fprintf(log, "next removal check: %llu (%llu seconds ago)\n",
202                         (long long unsigned)next_removal_check.tv_sec,
203                         now - (long long unsigned)next_removal_check.tv_sec
204                 );
205
206         }
207         fprintf(log, "%s </%s config> %s\n", dash, msg, dash);
208 }
209
210 static int loglevel = -1;
211 static const char *location_file = NULL;
212 static int         location_line = -1;
213 static const char *location_func = NULL;
214
215 void dss_log_set_params(int ll, const char *file, int line, const char *func)
216 {
217         loglevel = ll;
218         location_file = file;
219         location_line = line;
220         location_func = func;
221 }
222
223 /**
224  * The log function of dss.
225  *
226  * \param ll Loglevel.
227  * \param fml Usual format string.
228  *
229  * All DSS_XXX_LOG() macros use this function.
230  */
231 __printf_1_2 void dss_log(const char* fmt,...)
232 {
233         va_list argp;
234         FILE *outfd;
235         struct tm *tm;
236         time_t t1;
237         char str[255] = "";
238         int lpr_ll = lpr? OPT_UINT32_VAL(DSS, LOGLEVEL) : WARNING;
239
240         if (loglevel < lpr_ll)
241                 return;
242         outfd = logfile? logfile : stderr;
243         if (subcmd == CMD_PTR(RUN)) {
244                 time(&t1);
245                 tm = localtime(&t1);
246                 strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
247                 fprintf(outfd, "%s ", str);
248                 if (lpr_ll <= INFO)
249                         fprintf(outfd, "%i: ", loglevel);
250         }
251         if (subcmd == CMD_PTR(RUN))
252 #ifdef DSS_NO_FUNC_NAMES
253                 fprintf(outfd, "%s:%d: ", location_file, location_line);
254 #else
255                 fprintf(outfd, "%s: ", location_func);
256 #endif
257         va_start(argp, fmt);
258         vfprintf(outfd, fmt, argp);
259         va_end(argp);
260 }
261
262 /**
263  * Print a message either to stdout or to the log file.
264  */
265 static __printf_1_2 void dss_msg(const char* fmt,...)
266 {
267         FILE *outfd = logfile? logfile : stdout;
268         va_list argp;
269         va_start(argp, fmt);
270         vfprintf(outfd, fmt, argp);
271         va_end(argp);
272 }
273
274 static char *get_config_file_name(void)
275 {
276         char *home, *config_file;
277
278         if (OPT_GIVEN(DSS, CONFIG_FILE))
279                 return dss_strdup(OPT_STRING_VAL(DSS, CONFIG_FILE));
280         home = get_homedir();
281         config_file = make_message("%s/.dssrc", home);
282         free(home);
283         return config_file;
284 }
285
286 static int send_signal(int sig, bool wait)
287 {
288         pid_t pid;
289         char *config_file = get_config_file_name();
290         int ret = get_dss_pid(config_file, &pid);
291         unsigned ms = 32;
292         struct timespec ts;
293
294         free(config_file);
295         if (ret < 0)
296                 return ret;
297         if (OPT_GIVEN(DSS, DRY_RUN)) {
298                 dss_msg("%d\n", (int)pid);
299                 return 0;
300         }
301         DSS_NOTICE_LOG(("sending signal %d to pid %d\n", sig, (int)pid));
302         ret = kill(pid, sig);
303         if (ret < 0)
304                 return -ERRNO_TO_DSS_ERROR(errno);
305         if (!wait)
306                 return 1;
307         while (ms < 5000) {
308                 ts.tv_sec = ms / 1000;
309                 ts.tv_nsec = (ms % 1000) * 1000 * 1000;
310                 ret = nanosleep(&ts, NULL);
311                 if (ret < 0)
312                         return -ERRNO_TO_DSS_ERROR(errno);
313                 ret = kill(pid, 0);
314                 if (ret < 0) {
315                         if (errno != ESRCH)
316                                 return -ERRNO_TO_DSS_ERROR(errno);
317                         return 1;
318                 }
319                 ms *= 2;
320         }
321         return -E_KILL_TIMEOUT;
322 }
323
324 struct signal_info {
325         const char * const name;
326         int num;
327 };
328
329 /*
330  * The table below was taken 2016 from proc/sig.c of procps-3.2.8. Copyright
331  * 1998-2003 by Albert Cahalan, GPLv2.
332  */
333 static const struct signal_info signal_table[] = {
334         {"ABRT",   SIGABRT},  /* IOT */
335         {"ALRM",   SIGALRM},
336         {"BUS",    SIGBUS},
337         {"CHLD",   SIGCHLD},  /* CLD */
338         {"CONT",   SIGCONT},
339         {"FPE",    SIGFPE},
340         {"HUP",    SIGHUP},
341         {"ILL",    SIGILL},
342         {"INT",    SIGINT},
343         {"KILL",   SIGKILL},
344         {"PIPE",   SIGPIPE},
345 #ifdef SIGPOLL
346         {"POLL",   SIGPOLL},  /* IO */
347 #endif
348         {"PROF",   SIGPROF},
349 #ifdef SIGPWR
350         {"PWR",    SIGPWR},
351 #endif
352         {"QUIT",   SIGQUIT},
353         {"SEGV",   SIGSEGV},
354 #ifdef SIGSTKFLT
355         {"STKFLT", SIGSTKFLT},
356 #endif
357         {"STOP",   SIGSTOP},
358         {"SYS",    SIGSYS},   /* UNUSED */
359         {"TERM",   SIGTERM},
360         {"TRAP",   SIGTRAP},
361         {"TSTP",   SIGTSTP},
362         {"TTIN",   SIGTTIN},
363         {"TTOU",   SIGTTOU},
364         {"URG",    SIGURG},
365         {"USR1",   SIGUSR1},
366         {"USR2",   SIGUSR2},
367         {"VTALRM", SIGVTALRM},
368         {"WINCH",  SIGWINCH},
369         {"XCPU",   SIGXCPU},
370         {"XFSZ",   SIGXFSZ}
371 };
372
373 #define SIGNAL_TABLE_SIZE (sizeof(signal_table) / sizeof(signal_table[0]))
374 #ifndef SIGRTMAX
375 #define SIGRTMAX 64
376 #endif
377
378 static int com_kill(void)
379 {
380         bool w_given = OPT_GIVEN(KILL, WAIT);
381         const char *arg = OPT_STRING_VAL(KILL, SIGNAL);
382         int ret, i;
383
384         if (*arg >= '0' && *arg <= '9') {
385                 int64_t val;
386                 ret = dss_atoi64(arg, &val);
387                 if (ret < 0)
388                         return ret;
389                 if (val < 0 || val > SIGRTMAX)
390                         return -ERRNO_TO_DSS_ERROR(EINVAL);
391                 return send_signal(val, w_given);
392         }
393         if (strncasecmp(arg, "sig", 3) == 0)
394                 arg += 3;
395         if (strcasecmp(arg, "CLD") == 0)
396                 return send_signal(SIGCHLD, w_given);
397         if (strcasecmp(arg, "IOT") == 0)
398                 return send_signal(SIGABRT, w_given);
399         for (i = 0; i < SIGNAL_TABLE_SIZE; i++)
400                 if (strcasecmp(arg, signal_table[i].name) == 0)
401                         return send_signal(signal_table[i].num, w_given);
402         DSS_ERROR_LOG(("invalid sigspec: %s\n", arg));
403         return -ERRNO_TO_DSS_ERROR(EINVAL);
404 }
405 EXPORT_CMD_HANDLER(kill);
406
407 static void dss_get_snapshot_list(struct snapshot_list *sl)
408 {
409         get_snapshot_list(sl, OPT_UINT32_VAL(DSS, UNIT_INTERVAL),
410                 OPT_UINT32_VAL(DSS, NUM_INTERVALS));
411 }
412
413 static int64_t compute_next_snapshot_time(void)
414 {
415         int64_t x = 0, now = get_current_time(), unit_interval
416                 = 24 * 3600 * OPT_UINT32_VAL(DSS, UNIT_INTERVAL), ret,
417                 last_completion_time;
418         unsigned wanted = desired_number_of_snapshots(0,
419                 OPT_UINT32_VAL(DSS, NUM_INTERVALS)),
420                 num_complete = 0;
421         int i;
422         struct snapshot *s = NULL;
423         struct snapshot_list sl;
424
425         dss_get_snapshot_list(&sl);
426         FOR_EACH_SNAPSHOT(s, i, &sl) {
427                 if (!(s->flags & SS_COMPLETE))
428                         continue;
429                 num_complete++;
430                 x += s->completion_time - s->creation_time;
431                 last_completion_time = s->completion_time;
432         }
433         assert(x >= 0);
434
435         ret = now;
436         if (num_complete == 0)
437                 goto out;
438         x /= num_complete; /* avg time to create one snapshot */
439         if (unit_interval < x * wanted) /* oops, no sleep at all */
440                 goto out;
441         ret = last_completion_time + unit_interval / wanted - x;
442 out:
443         free_snapshot_list(&sl);
444         return ret;
445 }
446
447 static inline void invalidate_next_snapshot_time(void)
448 {
449         next_snapshot_time = 0;
450 }
451
452 static inline int next_snapshot_time_is_valid(void)
453 {
454         return next_snapshot_time != 0;
455 }
456
457 static int next_snapshot_is_due(void)
458 {
459         int64_t now = get_current_time();
460
461         if (!next_snapshot_time_is_valid())
462                 next_snapshot_time = compute_next_snapshot_time();
463         if (next_snapshot_time <= now) {
464                 DSS_DEBUG_LOG(("next snapshot: now\n"));
465                 return 1;
466         }
467         DSS_DEBUG_LOG(("next snapshot due in %" PRId64 " seconds\n",
468                 next_snapshot_time - now));
469         return 0;
470 }
471
472 static void pre_create_hook(void)
473 {
474         assert(snapshot_creation_status == HS_READY);
475         /* make sure that the next snapshot time will be recomputed */
476         invalidate_next_snapshot_time();
477         DSS_DEBUG_LOG(("executing %s\n", OPT_STRING_VAL(DSS, PRE_CREATE_HOOK)));
478         dss_exec_cmdline_pid(&create_pid, OPT_STRING_VAL(DSS, PRE_CREATE_HOOK));
479         snapshot_creation_status = HS_PRE_RUNNING;
480 }
481
482 static void pre_remove_hook(struct snapshot *s, const char *why)
483 {
484         char *cmd;
485
486         if (!s)
487                 return;
488         DSS_DEBUG_LOG(("%s snapshot %s\n", why, s->name));
489         assert(snapshot_removal_status == HS_READY);
490         assert(remove_pid == 0);
491         assert(!snapshot_currently_being_removed);
492
493         snapshot_currently_being_removed = dss_malloc(sizeof(struct snapshot));
494         *snapshot_currently_being_removed = *s;
495         snapshot_currently_being_removed->name = dss_strdup(s->name);
496
497         cmd = make_message("%s %s/%s", OPT_STRING_VAL(DSS, PRE_REMOVE_HOOK),
498                 OPT_STRING_VAL(DSS, DEST_DIR), s->name);
499         DSS_DEBUG_LOG(("executing %s\n", cmd));
500         dss_exec_cmdline_pid(&remove_pid, cmd);
501         free(cmd);
502         snapshot_removal_status = HS_PRE_RUNNING;
503 }
504
505 static int exec_rm(void)
506 {
507         struct snapshot *s = snapshot_currently_being_removed;
508         char *new_name = being_deleted_name(s);
509         char *argv[4];
510         int ret;
511
512         argv[0] = "rm";
513         argv[1] = "-rf";
514         argv[2] = new_name;
515         argv[3] = NULL;
516
517         assert(snapshot_removal_status == HS_PRE_SUCCESS);
518         assert(remove_pid == 0);
519
520         DSS_NOTICE_LOG(("removing %s (interval = %i)\n", s->name, s->interval));
521         ret = dss_rename(s->name, new_name);
522         if (ret < 0)
523                 goto out;
524         dss_exec(&remove_pid, argv[0], argv);
525         snapshot_removal_status = HS_RUNNING;
526 out:
527         free(new_name);
528         return ret;
529 }
530
531 static int snapshot_is_being_created(struct snapshot *s)
532 {
533         return s->creation_time == current_snapshot_creation_time;
534 }
535
536 static struct snapshot *find_orphaned_snapshot(struct snapshot_list *sl)
537 {
538         struct snapshot *s;
539         int i;
540
541         DSS_DEBUG_LOG(("looking for old incomplete snapshots\n"));
542         FOR_EACH_SNAPSHOT(s, i, sl) {
543                 if (snapshot_is_being_created(s))
544                         continue;
545                 /*
546                  * We know that no rm is currently running, so if s is marked
547                  * as being deleted, a previously started rm must have failed.
548                  */
549                 if (s->flags & SS_BEING_DELETED)
550                         return s;
551
552                 if (s->flags & SS_COMPLETE) /* good snapshot */
553                         continue;
554                 /*
555                  * This snapshot is incomplete and it is not the snapshot
556                  * currently being created. However, we must not remove it if
557                  * rsync is about to be restarted. As only the newest snapshot
558                  * can be restarted, this snapshot is orphaned if it is not the
559                  * newest snapshot or if we are not about to restart rsync.
560                  */
561                 if (get_newest_snapshot(sl) != s)
562                         return s;
563                 if (snapshot_creation_status != HS_NEEDS_RESTART)
564                         return s;
565         }
566         /* no orphaned snapshots */
567         return NULL;
568 }
569
570 static int is_reference_snapshot(struct snapshot *s)
571 {
572         if (!name_of_reference_snapshot)
573                 return 0;
574         return strcmp(s->name, name_of_reference_snapshot)? 0 : 1;
575 }
576
577 static struct snapshot *find_redundant_snapshot(struct snapshot_list *sl)
578 {
579         int i, interval;
580         struct snapshot *s;
581         unsigned missing = 0;
582         uint32_t N = OPT_UINT32_VAL(DSS, NUM_INTERVALS);
583
584         DSS_DEBUG_LOG(("looking for intervals containing too many snapshots\n"));
585         for (interval = N - 1; interval >= 0; interval--) {
586                 unsigned keep = desired_number_of_snapshots(interval, N);
587                 unsigned num = sl->interval_count[interval];
588                 struct snapshot *victim = NULL, *prev = NULL;
589                 int64_t score = LONG_MAX;
590
591                 if (keep >= num)
592                         missing += keep - num;
593                 if (keep + missing >= num)
594                         continue;
595                 /* redundant snapshot in this interval, pick snapshot with lowest score */
596                 FOR_EACH_SNAPSHOT(s, i, sl) {
597                         int64_t this_score;
598
599                         if (snapshot_is_being_created(s))
600                                 continue;
601                         if (is_reference_snapshot(s))
602                                 continue;
603                         if (s->interval > interval) {
604                                 prev = s;
605                                 continue;
606                         }
607                         if (s->interval < interval)
608                                 break;
609                         if (!victim) {
610                                 victim = s;
611                                 prev = s;
612                                 continue;
613                         }
614                         assert(prev);
615                         /* check if s is a better victim */
616                         this_score = s->creation_time - prev->creation_time;
617                         assert(this_score >= 0);
618                         if (this_score < score) {
619                                 score = this_score;
620                                 victim = s;
621                         }
622                         prev = s;
623                 }
624                 assert(victim);
625                 return victim;
626         }
627         return NULL;
628 }
629
630 static struct snapshot *find_outdated_snapshot(struct snapshot_list *sl)
631 {
632         int i;
633         struct snapshot *s;
634
635         DSS_DEBUG_LOG(("looking for snapshots belonging to intervals >= %d\n",
636                 OPT_UINT32_VAL(DSS, NUM_INTERVALS)));
637         FOR_EACH_SNAPSHOT(s, i, sl) {
638                 if (snapshot_is_being_created(s))
639                         continue;
640                 if (is_reference_snapshot(s))
641                         continue;
642                 if (s->interval < OPT_UINT32_VAL(DSS, NUM_INTERVALS))
643                         continue;
644                 return s;
645         }
646         return NULL;
647 }
648
649 static struct snapshot *find_oldest_removable_snapshot(struct snapshot_list *sl)
650 {
651         int i, num_complete;
652         struct snapshot *s, *ref = NULL;
653
654         num_complete = num_complete_snapshots(sl);
655         if (num_complete <= OPT_UINT32_VAL(DSS, MIN_COMPLETE))
656                 return NULL;
657         FOR_EACH_SNAPSHOT(s, i, sl) {
658                 if (snapshot_is_being_created(s))
659                         continue;
660                 if (is_reference_snapshot(s)) { /* avoid this one */
661                         ref = s;
662                         continue;
663                 }
664                 DSS_INFO_LOG(("oldest removable snapshot: %s\n", s->name));
665                 return s;
666         }
667         assert(ref);
668         DSS_WARNING_LOG(("removing reference snapshot %s\n", ref->name));
669         return ref;
670 }
671
672 static int rename_incomplete_snapshot(int64_t start)
673 {
674         char *old_name;
675         int ret;
676         int64_t now;
677
678         /*
679          * We don't want the dss_rename() below to fail with EEXIST because the
680          * last complete snapshot was created (and completed) in the same
681          * second as this one.
682          */
683         while ((now = get_current_time()) == start)
684                 sleep(1);
685         free(path_to_last_complete_snapshot);
686         ret = complete_name(start, now, &path_to_last_complete_snapshot);
687         if (ret < 0)
688                 return ret;
689         old_name = incomplete_name(start);
690         ret = dss_rename(old_name, path_to_last_complete_snapshot);
691         if (ret >= 0)
692                 DSS_NOTICE_LOG(("%s -> %s\n", old_name,
693                         path_to_last_complete_snapshot));
694         free(old_name);
695         return ret;
696 }
697
698 static int try_to_free_disk_space(void)
699 {
700         int ret;
701         struct snapshot_list sl;
702         struct snapshot *victim;
703         struct timeval now;
704         const char *why;
705         int low_disk_space;
706
707         ret = disk_space_low(NULL);
708         if (ret < 0)
709                 return ret;
710         low_disk_space = ret;
711         gettimeofday(&now, NULL);
712         if (tv_diff(&next_removal_check, &now, NULL) > 0)
713                 return 0;
714         if (!low_disk_space) {
715                 if (OPT_GIVEN(DSS, KEEP_REDUNDANT))
716                         return 0;
717                 if (snapshot_creation_status != HS_READY)
718                         return 0;
719                 if (next_snapshot_is_due())
720                         return 0;
721         }
722         /*
723          * Idle and --keep_redundant not given, or low disk space. Look at
724          * existing snapshots.
725          */
726         dss_get_snapshot_list(&sl);
727         ret = 0;
728         /*
729          * Don't remove anything if there is free space and we have fewer
730          * snapshots than configured, plus one. This way there is always one
731          * snapshot that can be recycled.
732          */
733         if (!low_disk_space && sl.num_snapshots <=
734                         1 << OPT_UINT32_VAL(DSS, NUM_INTERVALS))
735                 goto out;
736         why = "outdated";
737         victim = find_outdated_snapshot(&sl);
738         if (victim)
739                 goto remove;
740         why = "redundant";
741         victim = find_redundant_snapshot(&sl);
742         if (victim)
743                 goto remove;
744         why = "orphaned";
745         victim = find_orphaned_snapshot(&sl);
746         if (victim)
747                 goto remove;
748         /* try harder only if disk space is low */
749         if (!low_disk_space)
750                 goto out;
751         DSS_WARNING_LOG(("disk space low and nothing obvious to remove\n"));
752         why = "oldest";
753         victim = find_oldest_removable_snapshot(&sl);
754         if (victim)
755                 goto remove;
756         DSS_CRIT_LOG(("uhuhu: disk space low and nothing to remove\n"));
757         ret = -ERRNO_TO_DSS_ERROR(ENOSPC);
758         goto out;
759 remove:
760         pre_remove_hook(victim, why);
761 out:
762         free_snapshot_list(&sl);
763         return ret;
764 }
765
766 static void post_create_hook(void)
767 {
768         char *cmd = make_message("%s %s/%s",
769                 OPT_STRING_VAL(DSS, POST_CREATE_HOOK),
770                 OPT_STRING_VAL(DSS, DEST_DIR), path_to_last_complete_snapshot);
771         DSS_NOTICE_LOG(("executing %s\n", cmd));
772         dss_exec_cmdline_pid(&create_pid, cmd);
773         free(cmd);
774         snapshot_creation_status = HS_POST_RUNNING;
775 }
776
777 static void post_remove_hook(void)
778 {
779         char *cmd;
780         struct snapshot *s = snapshot_currently_being_removed;
781
782         assert(s);
783
784         cmd = make_message("%s %s/%s", OPT_STRING_VAL(DSS, POST_REMOVE_HOOK),
785                 OPT_STRING_VAL(DSS, DEST_DIR), s->name);
786         DSS_NOTICE_LOG(("executing %s\n", cmd));
787         dss_exec_cmdline_pid(&remove_pid, cmd);
788         free(cmd);
789         snapshot_removal_status = HS_POST_RUNNING;
790 }
791
792 static void dss_kill(pid_t pid, int sig, const char *msg)
793 {
794         const char *signame, *process_name;
795
796         if (pid == 0)
797                 return;
798         switch (sig) {
799         case SIGTERM: signame = "TERM"; break;
800         case SIGSTOP: signame = "STOP"; break;
801         case SIGCONT: signame = "CONT"; break;
802         default: signame = "????";
803         }
804
805         if (pid == create_pid)
806                 process_name = "create";
807         else if (pid == remove_pid)
808                 process_name = "remove";
809         else process_name = "??????";
810
811         if (msg)
812                 DSS_INFO_LOG(("%s\n", msg));
813         DSS_DEBUG_LOG(("sending signal %d (%s) to pid %d (%s process)\n",
814                 sig, signame, (int)pid, process_name));
815         if (kill(pid, sig) >= 0)
816                 return;
817         DSS_INFO_LOG(("failed to send signal %d (%s) to pid %d (%s process)\n",
818                 sig, signame, (int)pid, process_name));
819 }
820
821 static void stop_create_process(void)
822 {
823         if (create_process_stopped)
824                 return;
825         dss_kill(create_pid, SIGSTOP, "suspending create process");
826         create_process_stopped = 1;
827 }
828
829 static void restart_create_process(void)
830 {
831         if (!create_process_stopped)
832                 return;
833         dss_kill(create_pid, SIGCONT, "resuming create process");
834         create_process_stopped = 0;
835 }
836
837 /**
838  * Print a log message about the exit status of a child.
839  */
840 static void log_termination_msg(pid_t pid, int status)
841 {
842         if (WIFEXITED(status))
843                 DSS_INFO_LOG(("child %i exited. Exit status: %i\n", (int)pid,
844                         WEXITSTATUS(status)));
845         else if (WIFSIGNALED(status))
846                 DSS_NOTICE_LOG(("child %i was killed by signal %i\n", (int)pid,
847                         WTERMSIG(status)));
848         else
849                 DSS_WARNING_LOG(("child %i terminated abormally\n", (int)pid));
850 }
851
852 static int wait_for_process(pid_t pid, int *status)
853 {
854         int ret;
855
856         DSS_DEBUG_LOG(("Waiting for process %d to terminate\n", (int)pid));
857         for (;;) {
858                 fd_set rfds;
859
860                 FD_ZERO(&rfds);
861                 FD_SET(signal_pipe, &rfds);
862                 ret = dss_select(signal_pipe + 1, &rfds, NULL, NULL);
863                 if (ret < 0)
864                         break;
865                 ret = next_signal();
866                 if (!ret)
867                         continue;
868                 if (ret == SIGCHLD) {
869                         ret = waitpid(pid, status, 0);
870                         if (ret >= 0)
871                                 break;
872                         if (errno != EINTR) { /* error */
873                                 ret = -ERRNO_TO_DSS_ERROR(errno);
874                                 break;
875                         }
876                 }
877                 /* SIGINT or SIGTERM */
878                 dss_kill(pid, SIGTERM, "killing child process");
879         }
880         if (ret < 0)
881                 DSS_ERROR_LOG(("failed to wait for process %d\n", (int)pid));
882         else
883                 log_termination_msg(pid, *status);
884         return ret;
885 }
886
887 static void handle_pre_remove_exit(int status)
888 {
889         if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
890                 snapshot_removal_status = HS_READY;
891                 gettimeofday(&next_removal_check, NULL);
892                 next_removal_check.tv_sec += 60;
893                 return;
894         }
895         snapshot_removal_status = HS_PRE_SUCCESS;
896 }
897
898 static int handle_rm_exit(int status)
899 {
900         if (!WIFEXITED(status)) {
901                 snapshot_removal_status = HS_READY;
902                 return -E_INVOLUNTARY_EXIT;
903         }
904         if (WEXITSTATUS(status)) {
905                 snapshot_removal_status = HS_READY;
906                 return -E_BAD_EXIT_CODE;
907         }
908         snapshot_removal_status = HS_SUCCESS;
909         return 1;
910 }
911
912 static void handle_post_remove_exit(void)
913 {
914         snapshot_removal_status = HS_READY;
915 }
916
917 static int handle_remove_exit(int status)
918 {
919         int ret;
920         struct snapshot *s = snapshot_currently_being_removed;
921
922         assert(s);
923         switch (snapshot_removal_status) {
924         case HS_PRE_RUNNING:
925                 handle_pre_remove_exit(status);
926                 ret = 1;
927                 break;
928         case HS_RUNNING:
929                 ret = handle_rm_exit(status);
930                 break;
931         case HS_POST_RUNNING:
932                 handle_post_remove_exit();
933                 ret = 1;
934                 break;
935         default:
936                 ret = -E_BUG;
937         }
938         if (snapshot_removal_status == HS_READY) {
939                 free(s->name);
940                 free(s);
941                 snapshot_currently_being_removed = NULL;
942         }
943         remove_pid = 0;
944         return ret;
945 }
946
947 static int wait_for_remove_process(void)
948 {
949         int status, ret;
950
951         assert(remove_pid);
952         assert(
953                 snapshot_removal_status == HS_PRE_RUNNING ||
954                 snapshot_removal_status == HS_RUNNING ||
955                 snapshot_removal_status == HS_POST_RUNNING
956         );
957         ret = wait_for_process(remove_pid, &status);
958         if (ret < 0)
959                 return ret;
960         return handle_remove_exit(status);
961 }
962
963 static int handle_rsync_exit(int status)
964 {
965         int es, ret;
966
967         if (!WIFEXITED(status)) {
968                 DSS_ERROR_LOG(("rsync process %d died involuntary\n", (int)create_pid));
969                 ret = -E_INVOLUNTARY_EXIT;
970                 snapshot_creation_status = HS_READY;
971                 goto out;
972         }
973         es = WEXITSTATUS(status);
974         /*
975          * Restart rsync on non-fatal errors:
976          * 24: Partial transfer due to vanished source files
977          */
978         if (es != 0 && es != 24) {
979                 DSS_WARNING_LOG(("rsync exit code %d, error count %d\n",
980                         es, ++num_consecutive_rsync_errors));
981                 if (!logfile) { /* called by com_run() */
982                         ret = -E_BAD_EXIT_CODE;
983                         goto out;
984                 }
985                 if (num_consecutive_rsync_errors >
986                                 OPT_UINT32_VAL(RUN, MAX_RSYNC_ERRORS)) {
987                         ret = -E_TOO_MANY_RSYNC_ERRORS;
988                         snapshot_creation_status = HS_READY;
989                         goto out;
990                 }
991                 DSS_WARNING_LOG(("restarting rsync process\n"));
992                 snapshot_creation_status = HS_NEEDS_RESTART;
993                 next_snapshot_time = get_current_time() + 60;
994                 ret = 1;
995                 goto out;
996         }
997         num_consecutive_rsync_errors = 0;
998         ret = rename_incomplete_snapshot(current_snapshot_creation_time);
999         if (ret < 0)
1000                 goto out;
1001         snapshot_creation_status = HS_SUCCESS;
1002         free(name_of_reference_snapshot);
1003         name_of_reference_snapshot = NULL;
1004 out:
1005         create_process_stopped = 0;
1006         return ret;
1007 }
1008
1009 static int handle_pre_create_hook_exit(int status)
1010 {
1011         int es, ret;
1012         static int warn_count;
1013
1014         if (!WIFEXITED(status)) {
1015                 snapshot_creation_status = HS_READY;
1016                 ret = -E_INVOLUNTARY_EXIT;
1017                 goto out;
1018         }
1019         es = WEXITSTATUS(status);
1020         if (es) {
1021                 if (!warn_count--) {
1022                         DSS_NOTICE_LOG(("pre_create_hook %s returned %d\n",
1023                                 OPT_STRING_VAL(DSS, PRE_CREATE_HOOK), es));
1024                         DSS_NOTICE_LOG(("deferring snapshot creation...\n"));
1025                         warn_count = 60; /* warn only once per hour */
1026                 }
1027                 next_snapshot_time = get_current_time() + 60;
1028                 snapshot_creation_status = HS_READY;
1029                 ret = 0;
1030                 goto out;
1031         }
1032         warn_count = 0;
1033         snapshot_creation_status = HS_PRE_SUCCESS;
1034         ret = 1;
1035 out:
1036         return ret;
1037 }
1038
1039 static int handle_sigchld(void)
1040 {
1041         pid_t pid;
1042         int status, ret = reap_child(&pid, &status);
1043
1044         if (ret <= 0)
1045                 return ret;
1046
1047         if (pid == create_pid) {
1048                 switch (snapshot_creation_status) {
1049                 case HS_PRE_RUNNING:
1050                         ret = handle_pre_create_hook_exit(status);
1051                         break;
1052                 case HS_RUNNING:
1053                         ret = handle_rsync_exit(status);
1054                         break;
1055                 case HS_POST_RUNNING:
1056                         snapshot_creation_status = HS_READY;
1057                         ret = 1;
1058                         break;
1059                 default:
1060                         DSS_EMERG_LOG(("BUG: create can't die in status %d\n",
1061                                 snapshot_creation_status));
1062                         return -E_BUG;
1063                 }
1064                 create_pid = 0;
1065                 return ret;
1066         }
1067         if (pid == remove_pid) {
1068                 ret = handle_remove_exit(status);
1069                 if (ret < 0)
1070                         return ret;
1071                 return ret;
1072         }
1073         DSS_EMERG_LOG(("BUG: unknown process %d died\n", (int)pid));
1074         return -E_BUG;
1075 }
1076
1077 /* also checks if . is a mountpoint, if --mountpoint was given */
1078 static int change_to_dest_dir(void)
1079 {
1080         int ret;
1081         const char *dd = OPT_STRING_VAL(DSS, DEST_DIR);
1082         struct stat dot, dotdot;
1083
1084         DSS_INFO_LOG(("changing cwd to %s\n", dd));
1085         if (chdir(dd) < 0) {
1086                 ret = -ERRNO_TO_DSS_ERROR(errno);
1087                 DSS_ERROR_LOG(("could not change cwd to %s\n", dd));
1088                 return ret;
1089         }
1090         if (!OPT_GIVEN(DSS, MOUNTPOINT))
1091                 return 0;
1092         if (stat(".", &dot) < 0) {
1093                 ret = -ERRNO_TO_DSS_ERROR(errno);
1094                 DSS_ERROR_LOG(("could not stat .\n"));
1095                 return ret;
1096         }
1097         if (stat("..", &dotdot) < 0) {
1098                 ret = -ERRNO_TO_DSS_ERROR(errno);
1099                 DSS_ERROR_LOG(("could not stat ..\n"));
1100                 return ret;
1101         }
1102         if (dot.st_dev == dotdot.st_dev && dot.st_ino != dotdot.st_ino) {
1103                 DSS_ERROR_LOG(("mountpoint check failed for %s\n", dd));
1104                 return -E_MOUNTPOINT;
1105         }
1106         return 1;
1107 }
1108
1109 static int check_config(void)
1110 {
1111         int ret;
1112         uint32_t unit_interval = OPT_UINT32_VAL(DSS, UNIT_INTERVAL);
1113         uint32_t num_intervals = OPT_UINT32_VAL(DSS, NUM_INTERVALS);
1114
1115         if (unit_interval == 0) {
1116                 DSS_ERROR_LOG(("bad unit interval: %i\n", unit_interval));
1117                 return -E_INVALID_NUMBER;
1118         }
1119         DSS_DEBUG_LOG(("unit interval: %i day(s)\n", unit_interval));
1120
1121         if (num_intervals == 0 || num_intervals > 30) {
1122                 DSS_ERROR_LOG(("bad number of intervals: %i\n", num_intervals));
1123                 return -E_INVALID_NUMBER;
1124         }
1125         if (subcmd == CMD_PTR(RUN) || subcmd == CMD_PTR(CREATE))
1126                 if (!OPT_GIVEN(DSS, SOURCE_DIR)) {
1127                         DSS_ERROR_LOG(("--source-dir required\n"));
1128                         return -E_SYNTAX;
1129                 }
1130         if (subcmd == CMD_PTR(RUN) || subcmd == CMD_PTR(CREATE)
1131                         || subcmd == CMD_PTR(LS) || subcmd == CMD_PTR(PRUNE)) {
1132                 if (!OPT_GIVEN(DSS, DEST_DIR)) {
1133                         DSS_ERROR_LOG(("--dest-dir required\n"));
1134                         return -E_SYNTAX;
1135                 }
1136                 ret = change_to_dest_dir();
1137                 if (ret < 0)
1138                         return ret;
1139         }
1140         DSS_DEBUG_LOG(("number of intervals: %i\n", num_intervals));
1141         return 1;
1142 }
1143
1144 static int lopsub_error(int lopsub_ret, char **errctx)
1145 {
1146         const char *msg = lls_strerror(-lopsub_ret);
1147         if (*errctx)
1148                 DSS_ERROR_LOG(("%s: %s\n", *errctx, msg));
1149         else
1150                 DSS_ERROR_LOG(("%s\n", msg));
1151         free(*errctx);
1152         *errctx = NULL;
1153         return -E_LOPSUB;
1154 }
1155
1156 static int parse_config_file(bool sighup, const struct lls_command *cmd)
1157 {
1158         int ret, fd = -1;
1159         char *config_file = get_config_file_name();
1160         struct stat statbuf;
1161         void *map;
1162         size_t sz;
1163         int cf_argc;
1164         char **cf_argv, *errctx = NULL;
1165         struct lls_parse_result *cf_lpr, *merged_lpr, *clpr;
1166         const char *subcmd_name;
1167
1168         ret = open(config_file, O_RDONLY);
1169         if (ret < 0) {
1170                 if (errno != ENOENT || OPT_GIVEN(DSS, CONFIG_FILE)) {
1171                         ret = -ERRNO_TO_DSS_ERROR(errno);
1172                         DSS_ERROR_LOG(("config file %s can not be opened\n",
1173                                 config_file));
1174                         goto out;
1175                 }
1176                 /* no config file -- nothing to do */
1177                 ret = 0;
1178                 goto success;
1179         }
1180         fd = ret;
1181         ret = fstat(fd, &statbuf);
1182         if (ret < 0) {
1183                 ret = -ERRNO_TO_DSS_ERROR(errno);
1184                 DSS_ERROR_LOG(("failed to stat config file %s\n", config_file));
1185                 goto close_fd;
1186         }
1187         sz = statbuf.st_size;
1188         if (sz == 0) { /* config file is empty -- nothing to do */
1189                 ret = 0;
1190                 goto success;
1191         }
1192         map = mmap(NULL, sz, PROT_READ, MAP_PRIVATE, fd, 0);
1193         if (map == MAP_FAILED) {
1194                 ret = -ERRNO_TO_DSS_ERROR(errno);
1195                 DSS_ERROR_LOG(("failed to mmap config file %s\n",
1196                         config_file));
1197                 goto close_fd;
1198         }
1199         if (cmd == CMD_PTR(DSS))
1200                 subcmd_name = NULL;
1201         else
1202                 subcmd_name = lls_command_name(cmd);
1203         ret = lls_convert_config(map, sz, subcmd_name, &cf_argv, &errctx);
1204         munmap(map, sz);
1205         if (ret < 0) {
1206                 DSS_ERROR_LOG(("failed to convert config file %s\n",
1207                         config_file));
1208                 ret = lopsub_error(ret, &errctx);
1209                 goto close_fd;
1210         }
1211         cf_argc = ret;
1212         ret = lls_parse(cf_argc, cf_argv, cmd, &cf_lpr, &errctx);
1213         lls_free_argv(cf_argv);
1214         if (ret < 0) {
1215                 ret = lopsub_error(ret, &errctx);
1216                 goto close_fd;
1217         }
1218         clpr = cmd == CMD_PTR(DSS)? cmdline_lpr : cmdline_sublpr;
1219         if (sighup) /* config file overrides command line */
1220                 ret = lls_merge(cf_lpr, clpr, cmd, &merged_lpr, &errctx);
1221         else /* command line options overrride config file options */
1222                 ret = lls_merge(clpr, cf_lpr, cmd, &merged_lpr, &errctx);
1223         lls_free_parse_result(cf_lpr, cmd);
1224         if (ret < 0) {
1225                 ret = lopsub_error(ret, &errctx);
1226                 goto close_fd;
1227         }
1228         ret = 1;
1229 success:
1230         assert(ret >= 0);
1231         DSS_DEBUG_LOG(("loglevel: %d\n", OPT_UINT32_VAL(DSS, LOGLEVEL)));
1232         if (cmd != CMD_PTR(DSS)) {
1233                 if (ret > 0) {
1234                         if (sublpr != cmdline_sublpr)
1235                                 lls_free_parse_result(sublpr, cmd);
1236                         sublpr = merged_lpr;
1237                 } else
1238                         sublpr = cmdline_sublpr;
1239         } else {
1240                 if (ret > 0) {
1241                         if (lpr != cmdline_lpr)
1242                                 lls_free_parse_result(lpr, cmd);
1243                         lpr = merged_lpr;
1244                 } else
1245                         lpr = cmdline_lpr;
1246         }
1247 close_fd:
1248         if (fd >= 0)
1249                 close(fd);
1250 out:
1251         free(config_file);
1252         if (ret < 0)
1253                 DSS_EMERG_LOG(("%s\n", dss_strerror(-ret)));
1254         return ret;
1255 }
1256
1257 static int handle_sighup(void)
1258 {
1259         int ret;
1260
1261         DSS_NOTICE_LOG(("SIGHUP, re-reading config\n"));
1262         dump_dss_config("old");
1263         ret = parse_config_file(true /* SIGHUP */, CMD_PTR(DSS));
1264         if (ret < 0)
1265                 return ret;
1266         ret = parse_config_file(true /* SIGHUP */, CMD_PTR(RUN));
1267         if (ret < 0)
1268                 return ret;
1269         ret = check_config();
1270         if (ret < 0)
1271                 return ret;
1272         close_log(logfile);
1273         logfile = NULL;
1274         if (OPT_GIVEN(RUN, DAEMON) || daemonized) {
1275                 logfile = open_log(OPT_STRING_VAL(RUN, LOGFILE));
1276                 log_welcome(OPT_UINT32_VAL(DSS, LOGLEVEL));
1277                 daemonized = true;
1278         }
1279         dump_dss_config("reloaded");
1280         invalidate_next_snapshot_time();
1281         return 1;
1282 }
1283
1284 static void kill_children(void)
1285 {
1286         restart_create_process();
1287         dss_kill(create_pid, SIGTERM, NULL);
1288         dss_kill(remove_pid, SIGTERM, NULL);
1289 }
1290
1291 static int handle_signal(void)
1292 {
1293         int sig, ret = next_signal();
1294
1295         if (ret <= 0)
1296                 goto out;
1297         sig = ret;
1298         switch (sig) {
1299         case SIGINT:
1300         case SIGTERM:
1301                 return -E_SIGNAL;
1302         case SIGHUP:
1303                 ret = handle_sighup();
1304                 break;
1305         case SIGCHLD:
1306                 ret = handle_sigchld();
1307                 break;
1308         }
1309 out:
1310         if (ret < 0)
1311                 DSS_ERROR_LOG(("%s\n", dss_strerror(-ret)));
1312         return ret;
1313 }
1314
1315 /*
1316  * We can not use rsync locally if the local user is different from the remote
1317  * user or if the src dir is not on the local host (or both).
1318  */
1319 static int use_rsync_locally(char *logname)
1320 {
1321         const char *h = OPT_STRING_VAL(DSS, REMOTE_HOST);
1322
1323         if (strcmp(h, "localhost") && strcmp(h, "127.0.0.1"))
1324                 return 0;
1325         if (OPT_GIVEN(DSS, REMOTE_USER) &&
1326                         strcmp(OPT_STRING_VAL(DSS, REMOTE_USER), logname))
1327                 return 0;
1328         return 1;
1329 }
1330
1331 static int rename_resume_snap(int64_t creation_time)
1332 {
1333         struct snapshot_list sl;
1334         struct snapshot *s = NULL;
1335         char *new_name = incomplete_name(creation_time);
1336         int ret;
1337         const char *why;
1338
1339         sl.num_snapshots = 0;
1340
1341         ret = 0;
1342         dss_get_snapshot_list(&sl);
1343         /*
1344          * Snapshot recycling: We first look at the newest snapshot. If this
1345          * snapshot happens to be incomplete, the last rsync process was
1346          * aborted and we reuse this one. Otherwise we look at snapshots which
1347          * could be removed (outdated and redundant snapshots) as candidates
1348          * for recycling. If no outdated/redundant snapshot exists, we check if
1349          * there is an orphaned snapshot, which likely is useless anyway.
1350          *
1351          * Only if no existing snapshot is suitable for recycling, we bite the
1352          * bullet and create a new one.
1353          */
1354         s = get_newest_snapshot(&sl);
1355         if (!s) /* no snapshots at all */
1356                 goto out;
1357         /* re-use last snapshot if it is incomplete */
1358         why = "aborted";
1359         if ((s->flags & SS_COMPLETE) == 0)
1360                 goto out;
1361         why = "outdated";
1362         s = find_outdated_snapshot(&sl);
1363         if (s)
1364                 goto out;
1365         why = "redundant";
1366         s = find_redundant_snapshot(&sl);
1367         if (s)
1368                 goto out;
1369         why = "orphaned";
1370         s = find_orphaned_snapshot(&sl);
1371 out:
1372         if (s) {
1373                 DSS_NOTICE_LOG(("recycling %s snapshot %s\n", why, s->name));
1374                 ret = dss_rename(s->name, new_name);
1375         }
1376         if (ret >= 0)
1377                 DSS_NOTICE_LOG(("creating %s\n", new_name));
1378         free(new_name);
1379         free_snapshot_list(&sl);
1380         return ret;
1381 }
1382
1383 static void create_rsync_argv(char ***argv, int64_t *num)
1384 {
1385         char *logname;
1386         int i = 0, j, N = OPT_GIVEN(DSS, RSYNC_OPTION);
1387         struct snapshot_list sl;
1388         static bool seeded;
1389
1390         dss_get_snapshot_list(&sl);
1391         assert(!name_of_reference_snapshot);
1392         name_of_reference_snapshot = name_of_newest_complete_snapshot(&sl);
1393         free_snapshot_list(&sl);
1394
1395         *argv = dss_malloc((15 + N) * sizeof(char *));
1396         (*argv)[i++] = dss_strdup("rsync");
1397         (*argv)[i++] = dss_strdup("-a");
1398         (*argv)[i++] = dss_strdup("--delete");
1399         if (!seeded) {
1400                 srandom((unsigned)time(NULL)); /* no need to be fancy here */
1401                 seeded = true;
1402         }
1403         if (1000 * (random() / (RAND_MAX + 1.0)) < OPT_UINT32_VAL(DSS, CHECKSUM)) {
1404                 DSS_NOTICE_LOG(("adding --checksum to rsync options\n"));
1405                 (*argv)[i++] = dss_strdup("--checksum");
1406         }
1407         for (j = 0; j < N; j++)
1408                 (*argv)[i++] = dss_strdup(lls_string_val(j,
1409                         OPT_RESULT(DSS, RSYNC_OPTION)));
1410         if (name_of_reference_snapshot) {
1411                 DSS_INFO_LOG(("using %s as reference\n", name_of_reference_snapshot));
1412                 (*argv)[i++] = make_message("--link-dest=../%s",
1413                         name_of_reference_snapshot);
1414         } else
1415                 DSS_INFO_LOG(("no suitable reference snapshot found\n"));
1416         logname = dss_logname();
1417         if (use_rsync_locally(logname))
1418                 (*argv)[i++] = dss_strdup(OPT_STRING_VAL(DSS, SOURCE_DIR));
1419         else
1420                 (*argv)[i++] = make_message("%s@%s:%s/",
1421                         OPT_GIVEN(DSS, REMOTE_USER)?
1422                                 OPT_STRING_VAL(DSS, REMOTE_USER) : logname,
1423                         OPT_STRING_VAL(DSS, REMOTE_HOST),
1424                         OPT_STRING_VAL(DSS, SOURCE_DIR));
1425         free(logname);
1426         *num = get_current_time();
1427         (*argv)[i++] = incomplete_name(*num);
1428         (*argv)[i++] = NULL;
1429         for (j = 0; j < i; j++)
1430                 DSS_DEBUG_LOG(("argv[%d] = %s\n", j, (*argv)[j]));
1431 }
1432
1433 static void free_rsync_argv(char **argv)
1434 {
1435         int i;
1436
1437         if (!argv)
1438                 return;
1439         for (i = 0; argv[i]; i++)
1440                 free(argv[i]);
1441         free(argv);
1442 }
1443
1444 static int create_snapshot(char **argv)
1445 {
1446         int ret;
1447
1448         assert(argv);
1449         ret = rename_resume_snap(current_snapshot_creation_time);
1450         if (ret < 0)
1451                 return ret;
1452         dss_exec(&create_pid, argv[0], argv);
1453         snapshot_creation_status = HS_RUNNING;
1454         return ret;
1455 }
1456
1457 static int select_loop(void)
1458 {
1459         int ret;
1460         /* check every 60 seconds for free disk space */
1461         struct timeval tv;
1462         char **rsync_argv = NULL;
1463
1464         for (;;) {
1465                 fd_set rfds;
1466                 struct timeval *tvp;
1467
1468                 if (remove_pid)
1469                         tvp = NULL; /* sleep until rm hook/process dies */
1470                 else { /* sleep one minute */
1471                         tv.tv_sec = 60;
1472                         tv.tv_usec = 0;
1473                         tvp = &tv;
1474                 }
1475                 FD_ZERO(&rfds);
1476                 FD_SET(signal_pipe, &rfds);
1477                 ret = dss_select(signal_pipe + 1, &rfds, NULL, tvp);
1478                 if (ret < 0)
1479                         goto out;
1480                 if (FD_ISSET(signal_pipe, &rfds)) {
1481                         ret = handle_signal();
1482                         if (ret < 0)
1483                                 goto out;
1484                 }
1485                 if (remove_pid)
1486                         continue;
1487                 if (snapshot_removal_status == HS_PRE_SUCCESS) {
1488                         ret = exec_rm();
1489                         if (ret < 0)
1490                                 goto out;
1491                         continue;
1492                 }
1493                 if (snapshot_removal_status == HS_SUCCESS) {
1494                         post_remove_hook();
1495                         continue;
1496                 }
1497                 ret = try_to_free_disk_space();
1498                 if (ret < 0)
1499                         goto out;
1500                 if (snapshot_removal_status != HS_READY) {
1501                         stop_create_process();
1502                         continue;
1503                 }
1504                 restart_create_process();
1505                 switch (snapshot_creation_status) {
1506                 case HS_READY:
1507                         if (!next_snapshot_is_due())
1508                                 continue;
1509                         pre_create_hook();
1510                         continue;
1511                 case HS_PRE_RUNNING:
1512                 case HS_RUNNING:
1513                 case HS_POST_RUNNING:
1514                         continue;
1515                 case HS_PRE_SUCCESS:
1516                         if (!name_of_reference_snapshot) {
1517                                 free_rsync_argv(rsync_argv);
1518                                 create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
1519                         }
1520                         ret = create_snapshot(rsync_argv);
1521                         if (ret < 0)
1522                                 goto out;
1523                         continue;
1524                 case HS_NEEDS_RESTART:
1525                         if (!next_snapshot_is_due())
1526                                 continue;
1527                         ret = create_snapshot(rsync_argv);
1528                         if (ret < 0)
1529                                 goto out;
1530                         continue;
1531                 case HS_SUCCESS:
1532                         post_create_hook();
1533                         continue;
1534                 }
1535         }
1536 out:
1537         return ret;
1538 }
1539
1540 static void exit_hook(int exit_code)
1541 {
1542         pid_t pid;
1543         char **argv, *tmp = dss_strdup(OPT_STRING_VAL(DSS, EXIT_HOOK));
1544         unsigned n = split_args(tmp, &argv, " \t");
1545
1546         n++;
1547         argv = dss_realloc(argv, (n + 1) * sizeof(char *));
1548         argv[n - 1] = dss_strdup(dss_strerror(-exit_code));
1549         argv[n] = NULL;
1550         dss_exec(&pid, argv[0], argv);
1551         free(argv[n - 1]);
1552         free(argv);
1553         free(tmp);
1554 }
1555
1556 static void lock_dss_or_die(void)
1557 {
1558         char *config_file = get_config_file_name();
1559         int ret = lock_dss(config_file);
1560
1561         free(config_file);
1562         if (ret < 0) {
1563                 DSS_EMERG_LOG(("failed to lock: %s\n", dss_strerror(-ret)));
1564                 exit(EXIT_FAILURE);
1565         }
1566 }
1567
1568 static int com_run(void)
1569 {
1570         int ret, fd = -1;
1571         char *config_file;
1572         pid_t pid;
1573
1574         if (OPT_GIVEN(DSS, DRY_RUN)) {
1575                 DSS_ERROR_LOG(("dry run not supported by this command\n"));
1576                 return -E_SYNTAX;
1577         }
1578         config_file = get_config_file_name();
1579         ret = get_dss_pid(config_file, &pid);
1580         free(config_file);
1581         if (ret >= 0) {
1582                 DSS_ERROR_LOG(("pid %d\n", (int)pid));
1583                 return -E_ALREADY_RUNNING;
1584         }
1585         if (OPT_GIVEN(RUN, DAEMON)) {
1586                 fd = daemon_init();
1587                 daemonized = true;
1588                 logfile = open_log(OPT_STRING_VAL(RUN, LOGFILE));
1589         }
1590         lock_dss_or_die();
1591         dump_dss_config("startup");
1592         ret = install_sighandler(SIGHUP);
1593         if (ret < 0)
1594                 return ret;
1595         if (fd >= 0) {
1596                 ret = write(fd, "\0", 1);
1597                 if (ret != 1) {
1598                         DSS_ERROR_LOG(("write to daemon pipe returned %d\n",
1599                                 ret));
1600                         if (ret < 0)
1601                                 return -ERRNO_TO_DSS_ERROR(errno);
1602                         return -E_BUG;
1603                 }
1604         }
1605         ret = select_loop();
1606         if (ret >= 0) /* impossible */
1607                 ret = -E_BUG;
1608         kill_children();
1609         exit_hook(ret);
1610         while (wait(NULL) >= 0 || errno != ECHILD)
1611                 ; /* still have children to wait for */
1612         return ret;
1613 }
1614 EXPORT_CMD_HANDLER(run);
1615
1616 static int com_prune(void)
1617 {
1618         int ret;
1619         struct snapshot_list sl;
1620         struct snapshot *victim;
1621         struct disk_space ds;
1622         const char *why;
1623
1624         lock_dss_or_die();
1625         ret = get_disk_space(".", &ds);
1626         if (ret < 0)
1627                 return ret;
1628         log_disk_space(&ds);
1629         dss_get_snapshot_list(&sl);
1630         why = "outdated";
1631         victim = find_outdated_snapshot(&sl);
1632         if (victim)
1633                 goto rm;
1634         why = "redundant";
1635         victim = find_redundant_snapshot(&sl);
1636         if (victim)
1637                 goto rm;
1638         ret = 0;
1639         goto out;
1640 rm:
1641         if (OPT_GIVEN(DSS, DRY_RUN)) {
1642                 dss_msg("%s snapshot %s (interval = %i)\n",
1643                         why, victim->name, victim->interval);
1644                 ret = 0;
1645                 goto out;
1646         }
1647         pre_remove_hook(victim, why);
1648         if (snapshot_removal_status == HS_PRE_RUNNING) {
1649                 ret = wait_for_remove_process();
1650                 if (ret < 0)
1651                         goto out;
1652                 if (snapshot_removal_status != HS_PRE_SUCCESS)
1653                         goto out;
1654         }
1655         ret = exec_rm();
1656         if (ret < 0)
1657                 goto out;
1658         ret = wait_for_remove_process();
1659         if (ret < 0)
1660                 goto out;
1661         if (snapshot_removal_status != HS_SUCCESS)
1662                 goto out;
1663         post_remove_hook();
1664         if (snapshot_removal_status != HS_POST_RUNNING)
1665                 goto out;
1666         ret = wait_for_remove_process();
1667         if (ret < 0)
1668                 goto out;
1669         ret = 1;
1670 out:
1671         free_snapshot_list(&sl);
1672         return ret;
1673 }
1674 EXPORT_CMD_HANDLER(prune);
1675
1676 static int com_create(void)
1677 {
1678         int ret, status;
1679         char **rsync_argv;
1680
1681         lock_dss_or_die();
1682         if (OPT_GIVEN(DSS, DRY_RUN)) {
1683                 int i;
1684                 char *msg = NULL;
1685                 create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
1686                 for (i = 0; rsync_argv[i]; i++) {
1687                         char *tmp = msg;
1688                         msg = make_message("%s%s%s", tmp? tmp : "",
1689                                 tmp? " " : "", rsync_argv[i]);
1690                         free(tmp);
1691                 }
1692                 free_rsync_argv(rsync_argv);
1693                 dss_msg("%s\n", msg);
1694                 free(msg);
1695                 return 1;
1696         }
1697         pre_create_hook();
1698         if (create_pid) {
1699                 ret = wait_for_process(create_pid, &status);
1700                 if (ret < 0)
1701                         return ret;
1702                 ret = handle_pre_create_hook_exit(status);
1703                 if (ret <= 0) /* error, or pre-create failed */
1704                         return ret;
1705         }
1706         create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
1707         ret = create_snapshot(rsync_argv);
1708         if (ret < 0)
1709                 goto out;
1710         ret = wait_for_process(create_pid, &status);
1711         if (ret < 0)
1712                 goto out;
1713         ret = handle_rsync_exit(status);
1714         if (ret < 0)
1715                 goto out;
1716         post_create_hook();
1717         if (create_pid)
1718                 ret = wait_for_process(create_pid, &status);
1719 out:
1720         free_rsync_argv(rsync_argv);
1721         return ret;
1722 }
1723 EXPORT_CMD_HANDLER(create);
1724
1725 static int com_ls(void)
1726 {
1727         int i;
1728         struct snapshot_list sl;
1729         struct snapshot *s;
1730         int64_t now = get_current_time();
1731
1732         dss_get_snapshot_list(&sl);
1733         FOR_EACH_SNAPSHOT(s, i, &sl) {
1734                 int64_t d;
1735                 if (s->flags & SS_COMPLETE)
1736                         d = (s->completion_time - s->creation_time) / 60;
1737                 else
1738                         d = (now - s->creation_time) / 60;
1739                 dss_msg("%u\t%s\t%3" PRId64 ":%02" PRId64 "\n", s->interval,
1740                         s->name, d / 60, d % 60);
1741         }
1742         free_snapshot_list(&sl);
1743         return 1;
1744 }
1745 EXPORT_CMD_HANDLER(ls);
1746
1747 static int com_configtest(void)
1748 {
1749         printf("Syntax Ok\n");
1750         return 0;
1751 }
1752 EXPORT_CMD_HANDLER(configtest);
1753
1754 static int setup_signal_handling(void)
1755 {
1756         int ret;
1757
1758         DSS_INFO_LOG(("setting up signal handlers\n"));
1759         signal_pipe = signal_init(); /* always successful */
1760         ret = install_sighandler(SIGINT);
1761         if (ret < 0)
1762                 return ret;
1763         ret = install_sighandler(SIGTERM);
1764         if (ret < 0)
1765                 return ret;
1766         return install_sighandler(SIGCHLD);
1767 }
1768
1769 static void handle_version_and_help(void)
1770 {
1771         char *txt;
1772
1773         if (OPT_GIVEN(DSS, DETAILED_HELP))
1774                 txt = lls_long_help(CMD_PTR(DSS));
1775         else if (OPT_GIVEN(DSS, HELP))
1776                 txt = lls_short_help(CMD_PTR(DSS));
1777         else if (OPT_GIVEN(DSS, VERSION))
1778                 txt = make_message("%s\n", VERSION_STRING);
1779         else
1780                 return;
1781         printf("%s", txt);
1782         free(txt);
1783         exit(EXIT_SUCCESS);
1784 }
1785
1786 static void show_subcommand_summary(void)
1787 {
1788         const struct lls_command *cmd;
1789         int i;
1790
1791         printf("Available subcommands:\n");
1792         for (i = 1; (cmd = lls_cmd(i, dss_suite)); i++) {
1793                 const char *name = lls_command_name(cmd);
1794                 const char *purpose = lls_purpose(cmd);
1795                 printf("%-11s%s\n", name, purpose);
1796         }
1797         exit(EXIT_SUCCESS);
1798 }
1799
1800 int main(int argc, char **argv)
1801 {
1802         int ret;
1803         char *errctx = NULL;
1804         unsigned num_inputs;
1805         const struct dss_user_data *ud;
1806
1807         ret = lls_parse(argc, argv, CMD_PTR(DSS), &cmdline_lpr, &errctx);
1808         if (ret < 0) {
1809                 ret = lopsub_error(ret, &errctx);
1810                 goto out;
1811         }
1812         lpr = cmdline_lpr;
1813         ret = parse_config_file(false /* no SIGHUP */, CMD_PTR(DSS));
1814         if (ret < 0)
1815                 goto out;
1816         handle_version_and_help();
1817         num_inputs = lls_num_inputs(lpr);
1818         if (num_inputs == 0)
1819                 show_subcommand_summary();
1820         ret = lls_lookup_subcmd(argv[argc - num_inputs], dss_suite, &errctx);
1821         if (ret < 0) {
1822                 ret = lopsub_error(ret, &errctx);
1823                 goto out;
1824         }
1825         subcmd = lls_cmd(ret, dss_suite);
1826         ret = lls_parse(num_inputs, argv + argc - num_inputs, subcmd,
1827                 &cmdline_sublpr, &errctx);
1828         if (ret < 0) {
1829                 ret = lopsub_error(ret, &errctx);
1830                 goto out;
1831         }
1832         sublpr = cmdline_sublpr;
1833         ret = parse_config_file(false /* no SIGHUP */, subcmd);
1834         if (ret < 0)
1835                 goto out;
1836         ret = check_config();
1837         if (ret < 0)
1838                 goto out;
1839         ret = setup_signal_handling();
1840         if (ret < 0)
1841                 goto out;
1842         ud = lls_user_data(subcmd);
1843         ret = ud->handler();
1844         signal_shutdown();
1845 out:
1846         if (ret < 0) {
1847                 if (errctx)
1848                         DSS_ERROR_LOG(("%s\n", errctx));
1849                 DSS_EMERG_LOG(("%s\n", dss_strerror(-ret)));
1850         }
1851         free(errctx);
1852         lls_free_parse_result(lpr, CMD_PTR(DSS));
1853         if (lpr != cmdline_lpr)
1854                 lls_free_parse_result(cmdline_lpr, CMD_PTR(DSS));
1855         lls_free_parse_result(sublpr, subcmd);
1856         if (sublpr != cmdline_sublpr)
1857                 lls_free_parse_result(cmdline_sublpr, subcmd);
1858         exit(ret >= 0? EXIT_SUCCESS : EXIT_FAILURE);
1859 }