]> git.tuebingen.mpg.de Git - dss.git/blob - dss.c
0992ec6fd18651f85c2bab2c7d8d45603b3a786c
[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         DSS_DEBUG_LOG(("picking snapshot with earliest creation time\n"));
655         num_complete = num_complete_snapshots(sl);
656         if (num_complete <= OPT_UINT32_VAL(DSS, MIN_COMPLETE))
657                 return NULL;
658         FOR_EACH_SNAPSHOT(s, i, sl) {
659                 if (snapshot_is_being_created(s))
660                         continue;
661                 if (is_reference_snapshot(s)) { /* avoid this one */
662                         ref = s;
663                         continue;
664                 }
665                 return s;
666         }
667         assert(ref);
668         DSS_WARNING_LOG(("removing reference snapshot %s\n", ref->name));
669         return ref;
670 }
671
672 /* returns NULL <==> *reason is set to NULL */
673 static struct snapshot *find_removable_snapshot(struct snapshot_list *sl,
674                 bool try_hard, char **reason)
675 {
676         struct snapshot *victim;
677
678         /*
679          * Don't remove anything if there is free space and we have fewer
680          * snapshots than configured, plus one. This way there is always one
681          * snapshot that can be recycled.
682          */
683         if (!try_hard && sl->num_snapshots <=
684                         1 << OPT_UINT32_VAL(DSS, NUM_INTERVALS))
685                 goto nope;
686         victim = find_orphaned_snapshot(sl);
687         if (victim) {
688                 *reason = make_message("orphaned");
689                 return victim;
690         }
691         victim = find_outdated_snapshot(sl);
692         if (victim) {
693                 *reason = make_message("outdated");
694                 return victim;
695         }
696         if (!OPT_GIVEN(DSS, KEEP_REDUNDANT)) {
697                 victim = find_redundant_snapshot(sl);
698                 if (victim) {
699                         *reason = make_message("redundant");
700                         return victim;
701                 }
702         }
703         if (!try_hard)
704                 goto nope;
705         DSS_WARNING_LOG(("nothing obvious to remove\n"));
706         victim = find_oldest_removable_snapshot(sl);
707         if (victim) {
708                 *reason = make_message("oldest");
709                 return victim;
710         }
711 nope:
712         *reason = NULL;
713         return NULL;
714 }
715
716 static int rename_incomplete_snapshot(int64_t start)
717 {
718         char *old_name;
719         int ret;
720         int64_t now;
721
722         /*
723          * We don't want the dss_rename() below to fail with EEXIST because the
724          * last complete snapshot was created (and completed) in the same
725          * second as this one.
726          */
727         while ((now = get_current_time()) == start)
728                 sleep(1);
729         free(path_to_last_complete_snapshot);
730         ret = complete_name(start, now, &path_to_last_complete_snapshot);
731         if (ret < 0)
732                 return ret;
733         old_name = incomplete_name(start);
734         ret = dss_rename(old_name, path_to_last_complete_snapshot);
735         if (ret >= 0)
736                 DSS_NOTICE_LOG(("%s -> %s\n", old_name,
737                         path_to_last_complete_snapshot));
738         free(old_name);
739         return ret;
740 }
741
742 static int try_to_free_disk_space(void)
743 {
744         int ret;
745         struct snapshot_list sl;
746         struct snapshot *victim;
747         struct timeval now;
748         char *why;
749         int low_disk_space;
750
751         ret = disk_space_low(NULL);
752         if (ret < 0)
753                 return ret;
754         low_disk_space = ret;
755         gettimeofday(&now, NULL);
756         if (tv_diff(&next_removal_check, &now, NULL) > 0)
757                 return 0;
758         if (!low_disk_space) {
759                 if (snapshot_creation_status != HS_READY)
760                         return 0;
761                 if (next_snapshot_is_due())
762                         return 0;
763         }
764         /* Idle or low disk space, look at existing snapshots. */
765         dss_get_snapshot_list(&sl);
766         victim = find_removable_snapshot(&sl, low_disk_space, &why);
767         if (victim) {
768                 pre_remove_hook(victim, why);
769                 free(why);
770         }
771         free_snapshot_list(&sl);
772         if (victim)
773                 return 1;
774         if (!low_disk_space)
775                 return 0;
776         DSS_CRIT_LOG(("uhuhu: disk space low and nothing to remove\n"));
777         return -ERRNO_TO_DSS_ERROR(ENOSPC);
778 }
779
780 static void post_create_hook(void)
781 {
782         char *cmd = make_message("%s %s/%s",
783                 OPT_STRING_VAL(DSS, POST_CREATE_HOOK),
784                 OPT_STRING_VAL(DSS, DEST_DIR), path_to_last_complete_snapshot);
785         DSS_NOTICE_LOG(("executing %s\n", cmd));
786         dss_exec_cmdline_pid(&create_pid, cmd);
787         free(cmd);
788         snapshot_creation_status = HS_POST_RUNNING;
789 }
790
791 static void post_remove_hook(void)
792 {
793         char *cmd;
794         struct snapshot *s = snapshot_currently_being_removed;
795
796         assert(s);
797
798         cmd = make_message("%s %s/%s", OPT_STRING_VAL(DSS, POST_REMOVE_HOOK),
799                 OPT_STRING_VAL(DSS, DEST_DIR), s->name);
800         DSS_NOTICE_LOG(("executing %s\n", cmd));
801         dss_exec_cmdline_pid(&remove_pid, cmd);
802         free(cmd);
803         snapshot_removal_status = HS_POST_RUNNING;
804 }
805
806 static void dss_kill(pid_t pid, int sig, const char *msg)
807 {
808         const char *signame, *process_name;
809
810         if (pid == 0)
811                 return;
812         switch (sig) {
813         case SIGTERM: signame = "TERM"; break;
814         case SIGSTOP: signame = "STOP"; break;
815         case SIGCONT: signame = "CONT"; break;
816         default: signame = "????";
817         }
818
819         if (pid == create_pid)
820                 process_name = "create";
821         else if (pid == remove_pid)
822                 process_name = "remove";
823         else process_name = "??????";
824
825         if (msg)
826                 DSS_INFO_LOG(("%s\n", msg));
827         DSS_DEBUG_LOG(("sending signal %d (%s) to pid %d (%s process)\n",
828                 sig, signame, (int)pid, process_name));
829         if (kill(pid, sig) >= 0)
830                 return;
831         DSS_INFO_LOG(("failed to send signal %d (%s) to pid %d (%s process)\n",
832                 sig, signame, (int)pid, process_name));
833 }
834
835 static void stop_create_process(void)
836 {
837         if (create_process_stopped)
838                 return;
839         dss_kill(create_pid, SIGSTOP, "suspending create process");
840         create_process_stopped = 1;
841 }
842
843 static void restart_create_process(void)
844 {
845         if (!create_process_stopped)
846                 return;
847         dss_kill(create_pid, SIGCONT, "resuming create process");
848         create_process_stopped = 0;
849 }
850
851 /**
852  * Print a log message about the exit status of a child.
853  */
854 static void log_termination_msg(pid_t pid, int status)
855 {
856         if (WIFEXITED(status))
857                 DSS_INFO_LOG(("child %i exited. Exit status: %i\n", (int)pid,
858                         WEXITSTATUS(status)));
859         else if (WIFSIGNALED(status))
860                 DSS_NOTICE_LOG(("child %i was killed by signal %i\n", (int)pid,
861                         WTERMSIG(status)));
862         else
863                 DSS_WARNING_LOG(("child %i terminated abormally\n", (int)pid));
864 }
865
866 static int wait_for_process(pid_t pid, int *status)
867 {
868         int ret;
869
870         DSS_DEBUG_LOG(("Waiting for process %d to terminate\n", (int)pid));
871         for (;;) {
872                 fd_set rfds;
873
874                 FD_ZERO(&rfds);
875                 FD_SET(signal_pipe, &rfds);
876                 ret = dss_select(signal_pipe + 1, &rfds, NULL, NULL);
877                 if (ret < 0)
878                         break;
879                 ret = next_signal();
880                 if (!ret)
881                         continue;
882                 if (ret == SIGCHLD) {
883                         ret = waitpid(pid, status, 0);
884                         if (ret >= 0)
885                                 break;
886                         if (errno != EINTR) { /* error */
887                                 ret = -ERRNO_TO_DSS_ERROR(errno);
888                                 break;
889                         }
890                 }
891                 /* SIGINT or SIGTERM */
892                 dss_kill(pid, SIGTERM, "killing child process");
893         }
894         if (ret < 0)
895                 DSS_ERROR_LOG(("failed to wait for process %d\n", (int)pid));
896         else
897                 log_termination_msg(pid, *status);
898         return ret;
899 }
900
901 static void handle_pre_remove_exit(int status)
902 {
903         if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
904                 snapshot_removal_status = HS_READY;
905                 gettimeofday(&next_removal_check, NULL);
906                 next_removal_check.tv_sec += 60;
907                 return;
908         }
909         snapshot_removal_status = HS_PRE_SUCCESS;
910 }
911
912 static int handle_rm_exit(int status)
913 {
914         if (!WIFEXITED(status)) {
915                 snapshot_removal_status = HS_READY;
916                 return -E_INVOLUNTARY_EXIT;
917         }
918         if (WEXITSTATUS(status)) {
919                 snapshot_removal_status = HS_READY;
920                 return -E_BAD_EXIT_CODE;
921         }
922         snapshot_removal_status = HS_SUCCESS;
923         return 1;
924 }
925
926 static void handle_post_remove_exit(void)
927 {
928         snapshot_removal_status = HS_READY;
929 }
930
931 static int handle_remove_exit(int status)
932 {
933         int ret;
934         struct snapshot *s = snapshot_currently_being_removed;
935
936         assert(s);
937         switch (snapshot_removal_status) {
938         case HS_PRE_RUNNING:
939                 handle_pre_remove_exit(status);
940                 ret = 1;
941                 break;
942         case HS_RUNNING:
943                 ret = handle_rm_exit(status);
944                 break;
945         case HS_POST_RUNNING:
946                 handle_post_remove_exit();
947                 ret = 1;
948                 break;
949         default:
950                 ret = -E_BUG;
951         }
952         if (snapshot_removal_status == HS_READY) {
953                 free(s->name);
954                 free(s);
955                 snapshot_currently_being_removed = NULL;
956         }
957         remove_pid = 0;
958         return ret;
959 }
960
961 static int wait_for_remove_process(void)
962 {
963         int status, ret;
964
965         assert(remove_pid);
966         assert(
967                 snapshot_removal_status == HS_PRE_RUNNING ||
968                 snapshot_removal_status == HS_RUNNING ||
969                 snapshot_removal_status == HS_POST_RUNNING
970         );
971         ret = wait_for_process(remove_pid, &status);
972         if (ret < 0)
973                 return ret;
974         return handle_remove_exit(status);
975 }
976
977 static int handle_rsync_exit(int status)
978 {
979         int es, ret;
980
981         if (!WIFEXITED(status)) {
982                 DSS_ERROR_LOG(("rsync process %d died involuntary\n", (int)create_pid));
983                 ret = -E_INVOLUNTARY_EXIT;
984                 snapshot_creation_status = HS_READY;
985                 goto out;
986         }
987         es = WEXITSTATUS(status);
988         /*
989          * Restart rsync on non-fatal errors:
990          * 24: Partial transfer due to vanished source files
991          */
992         if (es != 0 && es != 24) {
993                 DSS_WARNING_LOG(("rsync exit code %d, error count %d\n",
994                         es, ++num_consecutive_rsync_errors));
995                 if (!logfile) { /* called by com_run() */
996                         ret = -E_BAD_EXIT_CODE;
997                         goto out;
998                 }
999                 if (num_consecutive_rsync_errors >
1000                                 OPT_UINT32_VAL(RUN, MAX_RSYNC_ERRORS)) {
1001                         ret = -E_TOO_MANY_RSYNC_ERRORS;
1002                         snapshot_creation_status = HS_READY;
1003                         goto out;
1004                 }
1005                 DSS_WARNING_LOG(("restarting rsync process\n"));
1006                 snapshot_creation_status = HS_NEEDS_RESTART;
1007                 next_snapshot_time = get_current_time() + 60;
1008                 ret = 1;
1009                 goto out;
1010         }
1011         num_consecutive_rsync_errors = 0;
1012         ret = rename_incomplete_snapshot(current_snapshot_creation_time);
1013         if (ret < 0)
1014                 goto out;
1015         snapshot_creation_status = HS_SUCCESS;
1016         free(name_of_reference_snapshot);
1017         name_of_reference_snapshot = NULL;
1018 out:
1019         create_process_stopped = 0;
1020         return ret;
1021 }
1022
1023 static int handle_pre_create_hook_exit(int status)
1024 {
1025         int es, ret;
1026         static int warn_count;
1027
1028         if (!WIFEXITED(status)) {
1029                 snapshot_creation_status = HS_READY;
1030                 ret = -E_INVOLUNTARY_EXIT;
1031                 goto out;
1032         }
1033         es = WEXITSTATUS(status);
1034         if (es) {
1035                 if (!warn_count--) {
1036                         DSS_NOTICE_LOG(("pre_create_hook %s returned %d\n",
1037                                 OPT_STRING_VAL(DSS, PRE_CREATE_HOOK), es));
1038                         DSS_NOTICE_LOG(("deferring snapshot creation...\n"));
1039                         warn_count = 60; /* warn only once per hour */
1040                 }
1041                 next_snapshot_time = get_current_time() + 60;
1042                 snapshot_creation_status = HS_READY;
1043                 ret = 0;
1044                 goto out;
1045         }
1046         warn_count = 0;
1047         snapshot_creation_status = HS_PRE_SUCCESS;
1048         ret = 1;
1049 out:
1050         return ret;
1051 }
1052
1053 static int handle_sigchld(void)
1054 {
1055         pid_t pid;
1056         int status, ret = reap_child(&pid, &status);
1057
1058         if (ret <= 0)
1059                 return ret;
1060
1061         if (pid == create_pid) {
1062                 switch (snapshot_creation_status) {
1063                 case HS_PRE_RUNNING:
1064                         ret = handle_pre_create_hook_exit(status);
1065                         break;
1066                 case HS_RUNNING:
1067                         ret = handle_rsync_exit(status);
1068                         break;
1069                 case HS_POST_RUNNING:
1070                         snapshot_creation_status = HS_READY;
1071                         ret = 1;
1072                         break;
1073                 default:
1074                         DSS_EMERG_LOG(("BUG: create can't die in status %d\n",
1075                                 snapshot_creation_status));
1076                         return -E_BUG;
1077                 }
1078                 create_pid = 0;
1079                 return ret;
1080         }
1081         if (pid == remove_pid) {
1082                 ret = handle_remove_exit(status);
1083                 if (ret < 0)
1084                         return ret;
1085                 return ret;
1086         }
1087         DSS_EMERG_LOG(("BUG: unknown process %d died\n", (int)pid));
1088         return -E_BUG;
1089 }
1090
1091 /* also checks if . is a mountpoint, if --mountpoint was given */
1092 static int change_to_dest_dir(void)
1093 {
1094         int ret;
1095         const char *dd = OPT_STRING_VAL(DSS, DEST_DIR);
1096         struct stat dot, dotdot;
1097
1098         DSS_INFO_LOG(("changing cwd to %s\n", dd));
1099         if (chdir(dd) < 0) {
1100                 ret = -ERRNO_TO_DSS_ERROR(errno);
1101                 DSS_ERROR_LOG(("could not change cwd to %s\n", dd));
1102                 return ret;
1103         }
1104         if (!OPT_GIVEN(DSS, MOUNTPOINT))
1105                 return 0;
1106         if (stat(".", &dot) < 0) {
1107                 ret = -ERRNO_TO_DSS_ERROR(errno);
1108                 DSS_ERROR_LOG(("could not stat .\n"));
1109                 return ret;
1110         }
1111         if (stat("..", &dotdot) < 0) {
1112                 ret = -ERRNO_TO_DSS_ERROR(errno);
1113                 DSS_ERROR_LOG(("could not stat ..\n"));
1114                 return ret;
1115         }
1116         if (dot.st_dev == dotdot.st_dev && dot.st_ino != dotdot.st_ino) {
1117                 DSS_ERROR_LOG(("mountpoint check failed for %s\n", dd));
1118                 return -E_MOUNTPOINT;
1119         }
1120         return 1;
1121 }
1122
1123 static int check_config(void)
1124 {
1125         uint32_t unit_interval = OPT_UINT32_VAL(DSS, UNIT_INTERVAL);
1126         uint32_t num_intervals = OPT_UINT32_VAL(DSS, NUM_INTERVALS);
1127
1128         if (unit_interval == 0) {
1129                 DSS_ERROR_LOG(("bad unit interval: %i\n", unit_interval));
1130                 return -E_INVALID_NUMBER;
1131         }
1132         DSS_DEBUG_LOG(("unit interval: %i day(s)\n", unit_interval));
1133
1134         if (num_intervals == 0 || num_intervals > 30) {
1135                 DSS_ERROR_LOG(("bad number of intervals: %i\n", num_intervals));
1136                 return -E_INVALID_NUMBER;
1137         }
1138         if (subcmd == CMD_PTR(RUN) || subcmd == CMD_PTR(CREATE))
1139                 if (!OPT_GIVEN(DSS, SOURCE_DIR)) {
1140                         DSS_ERROR_LOG(("--source-dir required\n"));
1141                         return -E_SYNTAX;
1142                 }
1143         if (subcmd == CMD_PTR(RUN) || subcmd == CMD_PTR(CREATE)
1144                         || subcmd == CMD_PTR(LS) || subcmd == CMD_PTR(PRUNE)) {
1145                 if (!OPT_GIVEN(DSS, DEST_DIR)) {
1146                         DSS_ERROR_LOG(("--dest-dir required\n"));
1147                         return -E_SYNTAX;
1148                 }
1149         }
1150         DSS_DEBUG_LOG(("number of intervals: %i\n", num_intervals));
1151         return 1;
1152 }
1153
1154 static int lopsub_error(int lopsub_ret, char **errctx)
1155 {
1156         const char *msg = lls_strerror(-lopsub_ret);
1157         if (*errctx)
1158                 DSS_ERROR_LOG(("%s: %s\n", *errctx, msg));
1159         else
1160                 DSS_ERROR_LOG(("%s\n", msg));
1161         free(*errctx);
1162         *errctx = NULL;
1163         return -E_LOPSUB;
1164 }
1165
1166 static int parse_config_file(bool sighup, const struct lls_command *cmd)
1167 {
1168         int ret, fd = -1;
1169         char *config_file = get_config_file_name();
1170         struct stat statbuf;
1171         void *map;
1172         size_t sz;
1173         int cf_argc;
1174         char **cf_argv, *errctx = NULL;
1175         struct lls_parse_result *cf_lpr, *merged_lpr, *clpr;
1176         const char *subcmd_name;
1177
1178         ret = open(config_file, O_RDONLY);
1179         if (ret < 0) {
1180                 if (errno != ENOENT || OPT_GIVEN(DSS, CONFIG_FILE)) {
1181                         ret = -ERRNO_TO_DSS_ERROR(errno);
1182                         DSS_ERROR_LOG(("config file %s can not be opened\n",
1183                                 config_file));
1184                         goto out;
1185                 }
1186                 /* no config file -- nothing to do */
1187                 ret = 0;
1188                 goto success;
1189         }
1190         fd = ret;
1191         ret = fstat(fd, &statbuf);
1192         if (ret < 0) {
1193                 ret = -ERRNO_TO_DSS_ERROR(errno);
1194                 DSS_ERROR_LOG(("failed to stat config file %s\n", config_file));
1195                 goto close_fd;
1196         }
1197         sz = statbuf.st_size;
1198         if (sz == 0) { /* config file is empty -- nothing to do */
1199                 ret = 0;
1200                 goto success;
1201         }
1202         map = mmap(NULL, sz, PROT_READ, MAP_PRIVATE, fd, 0);
1203         if (map == MAP_FAILED) {
1204                 ret = -ERRNO_TO_DSS_ERROR(errno);
1205                 DSS_ERROR_LOG(("failed to mmap config file %s\n",
1206                         config_file));
1207                 goto close_fd;
1208         }
1209         if (cmd == CMD_PTR(DSS))
1210                 subcmd_name = NULL;
1211         else
1212                 subcmd_name = lls_command_name(cmd);
1213         ret = lls_convert_config(map, sz, subcmd_name, &cf_argv, &errctx);
1214         munmap(map, sz);
1215         if (ret < 0) {
1216                 DSS_ERROR_LOG(("failed to convert config file %s\n",
1217                         config_file));
1218                 ret = lopsub_error(ret, &errctx);
1219                 goto close_fd;
1220         }
1221         cf_argc = ret;
1222         ret = lls_parse(cf_argc, cf_argv, cmd, &cf_lpr, &errctx);
1223         lls_free_argv(cf_argv);
1224         if (ret < 0) {
1225                 ret = lopsub_error(ret, &errctx);
1226                 goto close_fd;
1227         }
1228         clpr = cmd == CMD_PTR(DSS)? cmdline_lpr : cmdline_sublpr;
1229         if (sighup) /* config file overrides command line */
1230                 ret = lls_merge(cf_lpr, clpr, cmd, &merged_lpr, &errctx);
1231         else /* command line options overrride config file options */
1232                 ret = lls_merge(clpr, cf_lpr, cmd, &merged_lpr, &errctx);
1233         lls_free_parse_result(cf_lpr, cmd);
1234         if (ret < 0) {
1235                 ret = lopsub_error(ret, &errctx);
1236                 goto close_fd;
1237         }
1238         ret = 1;
1239 success:
1240         assert(ret >= 0);
1241         DSS_DEBUG_LOG(("loglevel: %d\n", OPT_UINT32_VAL(DSS, LOGLEVEL)));
1242         if (cmd != CMD_PTR(DSS)) {
1243                 if (ret > 0) {
1244                         if (sublpr != cmdline_sublpr)
1245                                 lls_free_parse_result(sublpr, cmd);
1246                         sublpr = merged_lpr;
1247                 } else
1248                         sublpr = cmdline_sublpr;
1249         } else {
1250                 if (ret > 0) {
1251                         if (lpr != cmdline_lpr)
1252                                 lls_free_parse_result(lpr, cmd);
1253                         lpr = merged_lpr;
1254                 } else
1255                         lpr = cmdline_lpr;
1256         }
1257 close_fd:
1258         if (fd >= 0)
1259                 close(fd);
1260 out:
1261         free(config_file);
1262         return ret;
1263 }
1264
1265 static int handle_sighup(void)
1266 {
1267         int ret;
1268
1269         DSS_NOTICE_LOG(("SIGHUP, re-reading config\n"));
1270         dump_dss_config("old");
1271         ret = parse_config_file(true /* SIGHUP */, CMD_PTR(DSS));
1272         if (ret < 0)
1273                 return ret;
1274         ret = parse_config_file(true /* SIGHUP */, CMD_PTR(RUN));
1275         if (ret < 0)
1276                 return ret;
1277         ret = check_config();
1278         if (ret < 0)
1279                 return ret;
1280         close_log(logfile);
1281         logfile = NULL;
1282         if (OPT_GIVEN(RUN, DAEMON) || daemonized) {
1283                 logfile = open_log(OPT_STRING_VAL(RUN, LOGFILE));
1284                 log_welcome(OPT_UINT32_VAL(DSS, LOGLEVEL));
1285                 daemonized = true;
1286         }
1287         dump_dss_config("reloaded");
1288         invalidate_next_snapshot_time();
1289         return 1;
1290 }
1291
1292 static void kill_children(void)
1293 {
1294         restart_create_process();
1295         dss_kill(create_pid, SIGTERM, NULL);
1296         dss_kill(remove_pid, SIGTERM, NULL);
1297 }
1298
1299 static int handle_signal(void)
1300 {
1301         int sig, ret = next_signal();
1302
1303         if (ret <= 0)
1304                 goto out;
1305         sig = ret;
1306         switch (sig) {
1307         case SIGINT:
1308         case SIGTERM:
1309                 return -E_SIGNAL;
1310         case SIGHUP:
1311                 ret = handle_sighup();
1312                 break;
1313         case SIGCHLD:
1314                 ret = handle_sigchld();
1315                 break;
1316         }
1317 out:
1318         if (ret < 0)
1319                 DSS_ERROR_LOG(("%s\n", dss_strerror(-ret)));
1320         return ret;
1321 }
1322
1323 /*
1324  * We can not use rsync locally if the local user is different from the remote
1325  * user or if the src dir is not on the local host (or both).
1326  */
1327 static int use_rsync_locally(char *logname)
1328 {
1329         const char *h = OPT_STRING_VAL(DSS, REMOTE_HOST);
1330
1331         if (strcmp(h, "localhost") && strcmp(h, "127.0.0.1"))
1332                 return 0;
1333         if (OPT_GIVEN(DSS, REMOTE_USER) &&
1334                         strcmp(OPT_STRING_VAL(DSS, REMOTE_USER), logname))
1335                 return 0;
1336         return 1;
1337 }
1338
1339 static int rename_resume_snap(int64_t creation_time)
1340 {
1341         struct snapshot_list sl;
1342         struct snapshot *s = NULL;
1343         char *new_name = incomplete_name(creation_time);
1344         int ret;
1345         const char *why;
1346
1347         sl.num_snapshots = 0;
1348
1349         ret = 0;
1350         dss_get_snapshot_list(&sl);
1351         /*
1352          * Snapshot recycling: We first look at the newest snapshot. If this
1353          * snapshot happens to be incomplete, the last rsync process was
1354          * aborted and we reuse this one. Otherwise we look at snapshots which
1355          * could be removed (outdated and redundant snapshots) as candidates
1356          * for recycling. If no outdated/redundant snapshot exists, we check if
1357          * there is an orphaned snapshot, which likely is useless anyway.
1358          *
1359          * Only if no existing snapshot is suitable for recycling, we bite the
1360          * bullet and create a new one.
1361          */
1362         s = get_newest_snapshot(&sl);
1363         if (!s) /* no snapshots at all */
1364                 goto out;
1365         /* re-use last snapshot if it is incomplete */
1366         why = "aborted";
1367         if ((s->flags & SS_COMPLETE) == 0)
1368                 goto out;
1369         why = "outdated";
1370         s = find_outdated_snapshot(&sl);
1371         if (s)
1372                 goto out;
1373         why = "redundant";
1374         s = find_redundant_snapshot(&sl);
1375         if (s)
1376                 goto out;
1377         why = "orphaned";
1378         s = find_orphaned_snapshot(&sl);
1379 out:
1380         if (s) {
1381                 DSS_NOTICE_LOG(("recycling %s snapshot %s\n", why, s->name));
1382                 ret = dss_rename(s->name, new_name);
1383         }
1384         if (ret >= 0)
1385                 DSS_NOTICE_LOG(("creating %s\n", new_name));
1386         free(new_name);
1387         free_snapshot_list(&sl);
1388         return ret;
1389 }
1390
1391 static void create_rsync_argv(char ***argv, int64_t *num)
1392 {
1393         char *logname;
1394         int i = 0, j, N;
1395         struct snapshot_list sl;
1396         static bool seeded;
1397
1398         dss_get_snapshot_list(&sl);
1399         assert(!name_of_reference_snapshot);
1400         name_of_reference_snapshot = name_of_newest_complete_snapshot(&sl);
1401         free_snapshot_list(&sl);
1402
1403         /*
1404          * We specify up to 6 arguments, one argument per given rsync option
1405          * and one argument per given source dir. We also need space for the
1406          * terminating NULL pointer.
1407          */
1408         N = OPT_GIVEN(DSS, RSYNC_OPTION) + OPT_GIVEN(DSS, SOURCE_DIR);
1409         *argv = dss_malloc((7 + N) * sizeof(char *));
1410         (*argv)[i++] = dss_strdup("rsync");
1411         (*argv)[i++] = dss_strdup("-a");
1412         (*argv)[i++] = dss_strdup("--delete");
1413         if (!seeded) {
1414                 srandom((unsigned)time(NULL)); /* no need to be fancy here */
1415                 seeded = true;
1416         }
1417         if (1000 * (random() / (RAND_MAX + 1.0)) < OPT_UINT32_VAL(DSS, CHECKSUM)) {
1418                 DSS_NOTICE_LOG(("adding --checksum to rsync options\n"));
1419                 (*argv)[i++] = dss_strdup("--checksum");
1420         }
1421         for (j = 0; j < OPT_GIVEN(DSS, RSYNC_OPTION); j++)
1422                 (*argv)[i++] = dss_strdup(lls_string_val(j,
1423                         OPT_RESULT(DSS, RSYNC_OPTION)));
1424         if (name_of_reference_snapshot) {
1425                 DSS_INFO_LOG(("using %s as reference\n", name_of_reference_snapshot));
1426                 (*argv)[i++] = make_message("--link-dest=../%s",
1427                         name_of_reference_snapshot);
1428         } else
1429                 DSS_INFO_LOG(("no suitable reference snapshot found\n"));
1430         logname = dss_logname();
1431         if (use_rsync_locally(logname)) {
1432                 for (j = 0; j < OPT_GIVEN(DSS, SOURCE_DIR); j++)
1433                         (*argv)[i++] = dss_strdup(lls_string_val(j,
1434                                 OPT_RESULT(DSS, SOURCE_DIR)));
1435         } else {
1436                 /*
1437                  * dss-1.0 and earlier did not support multiple source
1438                  * directories.  These versions appended a slash to the end of
1439                  * the source directory to make sure that only the contents of
1440                  * the single source directory, but not the directory itself,
1441                  * are copied to the destination. For multiple source
1442                  * directories, however, this is not a good idea because the
1443                  * source directories may well contain identical file names,
1444                  * which would then be copied to the same location on the
1445                  * destination, overwriting each other. Moreover, we want the
1446                  * directory on the destination match the source. To preserve
1447                  * the old behaviour, we thus have to special-case N=1.
1448                  */
1449                 for (j = 0; j < OPT_GIVEN(DSS, SOURCE_DIR); j++) {
1450                         (*argv)[i++] = make_message("%s@%s:%s%s",
1451                                 OPT_GIVEN(DSS, REMOTE_USER)?
1452                                         OPT_STRING_VAL(DSS, REMOTE_USER) : logname,
1453                                 OPT_STRING_VAL(DSS, REMOTE_HOST),
1454                                 lls_string_val(j, OPT_RESULT(DSS, SOURCE_DIR)),
1455                                 OPT_GIVEN(DSS, SOURCE_DIR) == 1? "/" : ""
1456                         );
1457                 }
1458         }
1459         free(logname);
1460         *num = get_current_time();
1461         (*argv)[i++] = incomplete_name(*num);
1462         (*argv)[i++] = NULL;
1463         for (j = 0; j < i; j++)
1464                 DSS_DEBUG_LOG(("argv[%d] = %s\n", j, (*argv)[j]));
1465 }
1466
1467 static void free_rsync_argv(char **argv)
1468 {
1469         int i;
1470
1471         if (!argv)
1472                 return;
1473         for (i = 0; argv[i]; i++)
1474                 free(argv[i]);
1475         free(argv);
1476 }
1477
1478 static int create_snapshot(char **argv)
1479 {
1480         int ret;
1481
1482         assert(argv);
1483         ret = rename_resume_snap(current_snapshot_creation_time);
1484         if (ret < 0)
1485                 return ret;
1486         dss_exec(&create_pid, argv[0], argv);
1487         snapshot_creation_status = HS_RUNNING;
1488         return ret;
1489 }
1490
1491 static int select_loop(void)
1492 {
1493         int ret;
1494         /* check every 60 seconds for free disk space */
1495         struct timeval tv;
1496         char **rsync_argv = NULL;
1497
1498         for (;;) {
1499                 fd_set rfds;
1500                 struct timeval *tvp;
1501
1502                 if (remove_pid)
1503                         tvp = NULL; /* sleep until rm hook/process dies */
1504                 else { /* sleep one minute */
1505                         tv.tv_sec = 60;
1506                         tv.tv_usec = 0;
1507                         tvp = &tv;
1508                 }
1509                 FD_ZERO(&rfds);
1510                 FD_SET(signal_pipe, &rfds);
1511                 ret = dss_select(signal_pipe + 1, &rfds, NULL, tvp);
1512                 if (ret < 0)
1513                         goto out;
1514                 if (FD_ISSET(signal_pipe, &rfds)) {
1515                         ret = handle_signal();
1516                         if (ret < 0)
1517                                 goto out;
1518                 }
1519                 if (remove_pid)
1520                         continue;
1521                 if (snapshot_removal_status == HS_PRE_SUCCESS) {
1522                         ret = exec_rm();
1523                         if (ret < 0)
1524                                 goto out;
1525                         continue;
1526                 }
1527                 if (snapshot_removal_status == HS_SUCCESS) {
1528                         post_remove_hook();
1529                         continue;
1530                 }
1531                 ret = try_to_free_disk_space();
1532                 if (ret < 0)
1533                         goto out;
1534                 if (snapshot_removal_status != HS_READY) {
1535                         stop_create_process();
1536                         continue;
1537                 }
1538                 restart_create_process();
1539                 switch (snapshot_creation_status) {
1540                 case HS_READY:
1541                         if (!next_snapshot_is_due())
1542                                 continue;
1543                         pre_create_hook();
1544                         continue;
1545                 case HS_PRE_RUNNING:
1546                 case HS_RUNNING:
1547                 case HS_POST_RUNNING:
1548                         continue;
1549                 case HS_PRE_SUCCESS:
1550                         if (!name_of_reference_snapshot) {
1551                                 free_rsync_argv(rsync_argv);
1552                                 create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
1553                         }
1554                         ret = create_snapshot(rsync_argv);
1555                         if (ret < 0)
1556                                 goto out;
1557                         continue;
1558                 case HS_NEEDS_RESTART:
1559                         if (!next_snapshot_is_due())
1560                                 continue;
1561                         ret = create_snapshot(rsync_argv);
1562                         if (ret < 0)
1563                                 goto out;
1564                         continue;
1565                 case HS_SUCCESS:
1566                         post_create_hook();
1567                         continue;
1568                 }
1569         }
1570 out:
1571         return ret;
1572 }
1573
1574 static void exit_hook(int exit_code)
1575 {
1576         pid_t pid;
1577         char **argv, *tmp = dss_strdup(OPT_STRING_VAL(DSS, EXIT_HOOK));
1578         unsigned n = split_args(tmp, &argv);
1579
1580         n++;
1581         argv = dss_realloc(argv, (n + 1) * sizeof(char *));
1582         argv[n - 1] = dss_strdup(dss_strerror(-exit_code));
1583         argv[n] = NULL;
1584         dss_exec(&pid, argv[0], argv);
1585         free(argv[n - 1]);
1586         free(argv);
1587         free(tmp);
1588 }
1589
1590 static void lock_dss_or_die(void)
1591 {
1592         char *config_file = get_config_file_name();
1593         int ret = lock_dss(config_file);
1594
1595         free(config_file);
1596         if (ret < 0) {
1597                 DSS_EMERG_LOG(("failed to lock: %s\n", dss_strerror(-ret)));
1598                 exit(EXIT_FAILURE);
1599         }
1600 }
1601
1602 static int com_run(void)
1603 {
1604         int ret, fd = -1;
1605         char *config_file;
1606         pid_t pid;
1607
1608         if (OPT_GIVEN(DSS, DRY_RUN)) {
1609                 DSS_ERROR_LOG(("dry run not supported by this command\n"));
1610                 return -E_SYNTAX;
1611         }
1612         config_file = get_config_file_name();
1613         ret = get_dss_pid(config_file, &pid);
1614         free(config_file);
1615         if (ret >= 0) {
1616                 DSS_ERROR_LOG(("pid %d\n", (int)pid));
1617                 return -E_ALREADY_RUNNING;
1618         }
1619         /*
1620          * Order is important here: Since daemon_init() forks, it would drop
1621          * the lock if it had been acquired already. Changing the cwd before
1622          * grabbing the lock causes stat(2) to fail in case a relative config
1623          * file path was given, which results in a different key ID for
1624          * locking. Therefore we must first daemonize, then lock, then change
1625          * the cwd.
1626          */
1627         if (OPT_GIVEN(RUN, DAEMON)) {
1628                 fd = daemon_init();
1629                 daemonized = true;
1630                 logfile = open_log(OPT_STRING_VAL(RUN, LOGFILE));
1631         }
1632         lock_dss_or_die();
1633         ret = change_to_dest_dir();
1634         if (ret < 0)
1635                 return ret;
1636         dump_dss_config("startup");
1637         ret = install_sighandler(SIGHUP);
1638         if (ret < 0)
1639                 return ret;
1640         if (fd >= 0) {
1641                 ret = write(fd, "\0", 1);
1642                 if (ret != 1) {
1643                         DSS_ERROR_LOG(("write to daemon pipe returned %d\n",
1644                                 ret));
1645                         if (ret < 0)
1646                                 return -ERRNO_TO_DSS_ERROR(errno);
1647                         return -E_BUG;
1648                 }
1649         }
1650         ret = select_loop();
1651         if (ret >= 0) /* impossible */
1652                 ret = -E_BUG;
1653         kill_children();
1654         exit_hook(ret);
1655         while (wait(NULL) >= 0 || errno != ECHILD)
1656                 ; /* still have children to wait for */
1657         return ret;
1658 }
1659 EXPORT_CMD_HANDLER(run);
1660
1661 static int com_prune(void)
1662 {
1663         int ret;
1664         struct snapshot_list sl;
1665         struct snapshot *victim;
1666         struct disk_space ds;
1667         char *why;
1668         bool try_hard;
1669
1670         lock_dss_or_die();
1671         ret = change_to_dest_dir();
1672         if (ret < 0)
1673                 return ret;
1674         switch (OPT_UINT32_VAL(PRUNE, DISK_SPACE)) {
1675         case FDS_LOW: try_hard = true; break;
1676         case FDS_HIGH: try_hard = false; break;
1677         default:
1678                 ret = get_disk_space(".", &ds);
1679                 if (ret < 0)
1680                         return ret;
1681                 log_disk_space(&ds);
1682                 try_hard = disk_space_low(&ds);
1683         }
1684         dss_get_snapshot_list(&sl);
1685         victim = find_removable_snapshot(&sl, try_hard, &why);
1686         if (!victim) {
1687                 dss_msg("nothing to prune\n");
1688                 ret = 0;
1689                 goto free_sl;
1690         }
1691         if (OPT_GIVEN(DSS, DRY_RUN)) {
1692                 dss_msg("picking %s snapshot %s (interval = %i)\n",
1693                         why, victim->name, victim->interval);
1694                 ret = 0;
1695                 goto free_why;
1696         }
1697         pre_remove_hook(victim, why);
1698         if (snapshot_removal_status == HS_PRE_RUNNING) {
1699                 ret = wait_for_remove_process();
1700                 if (ret < 0)
1701                         goto free_why;
1702                 ret = -E_HOOK_FAILED;
1703                 if (snapshot_removal_status != HS_PRE_SUCCESS)
1704                         goto free_why;
1705         }
1706         ret = exec_rm();
1707         if (ret < 0)
1708                 goto free_why;
1709         ret = wait_for_remove_process();
1710         if (ret < 0)
1711                 goto free_why;
1712         assert(snapshot_removal_status == HS_SUCCESS);
1713         post_remove_hook();
1714         assert(snapshot_removal_status == HS_POST_RUNNING);
1715         ret = wait_for_remove_process();
1716 free_why:
1717         free(why);
1718 free_sl:
1719         free_snapshot_list(&sl);
1720         return ret;
1721 }
1722 EXPORT_CMD_HANDLER(prune);
1723
1724 static int com_create(void)
1725 {
1726         int ret, status;
1727         char **rsync_argv;
1728
1729         lock_dss_or_die();
1730         ret = change_to_dest_dir();
1731         if (ret < 0)
1732                 return ret;
1733         if (OPT_GIVEN(DSS, DRY_RUN)) {
1734                 int i;
1735                 char *msg = NULL;
1736                 create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
1737                 for (i = 0; rsync_argv[i]; i++) {
1738                         char *tmp = msg;
1739                         msg = make_message("%s%s%s", tmp? tmp : "",
1740                                 tmp? " " : "", rsync_argv[i]);
1741                         free(tmp);
1742                 }
1743                 free_rsync_argv(rsync_argv);
1744                 dss_msg("%s\n", msg);
1745                 free(msg);
1746                 return 1;
1747         }
1748         pre_create_hook();
1749         if (create_pid) {
1750                 ret = wait_for_process(create_pid, &status);
1751                 if (ret < 0)
1752                         return ret;
1753                 ret = handle_pre_create_hook_exit(status);
1754                 if (ret <= 0) /* error, or pre-create failed */
1755                         return ret;
1756         }
1757         create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
1758         ret = create_snapshot(rsync_argv);
1759         if (ret < 0)
1760                 goto out;
1761         ret = wait_for_process(create_pid, &status);
1762         if (ret < 0)
1763                 goto out;
1764         ret = handle_rsync_exit(status);
1765         if (ret < 0)
1766                 goto out;
1767         post_create_hook();
1768         if (create_pid)
1769                 ret = wait_for_process(create_pid, &status);
1770 out:
1771         free_rsync_argv(rsync_argv);
1772         return ret;
1773 }
1774 EXPORT_CMD_HANDLER(create);
1775
1776 static int com_ls(void)
1777 {
1778         int i, ret;
1779         struct snapshot_list sl;
1780         struct snapshot *s;
1781         int64_t now = get_current_time();
1782
1783         ret = change_to_dest_dir();
1784         if (ret < 0)
1785                 return ret;
1786         dss_get_snapshot_list(&sl);
1787         FOR_EACH_SNAPSHOT(s, i, &sl) {
1788                 int64_t d;
1789                 if (s->flags & SS_COMPLETE)
1790                         d = (s->completion_time - s->creation_time) / 60;
1791                 else
1792                         d = (now - s->creation_time) / 60;
1793                 dss_msg("%u\t%s\t%3" PRId64 ":%02" PRId64 "\n", s->interval,
1794                         s->name, d / 60, d % 60);
1795         }
1796         free_snapshot_list(&sl);
1797         return 1;
1798 }
1799 EXPORT_CMD_HANDLER(ls);
1800
1801 static int com_configtest(void)
1802 {
1803         printf("Syntax Ok\n");
1804         return 0;
1805 }
1806 EXPORT_CMD_HANDLER(configtest);
1807
1808 static int setup_signal_handling(void)
1809 {
1810         int ret;
1811
1812         DSS_INFO_LOG(("setting up signal handlers\n"));
1813         signal_pipe = signal_init(); /* always successful */
1814         ret = install_sighandler(SIGINT);
1815         if (ret < 0)
1816                 return ret;
1817         ret = install_sighandler(SIGTERM);
1818         if (ret < 0)
1819                 return ret;
1820         return install_sighandler(SIGCHLD);
1821 }
1822
1823 static void handle_version_and_help(void)
1824 {
1825         char *txt;
1826
1827         if (OPT_GIVEN(DSS, DETAILED_HELP))
1828                 txt = lls_long_help(CMD_PTR(DSS));
1829         else if (OPT_GIVEN(DSS, HELP))
1830                 txt = lls_short_help(CMD_PTR(DSS));
1831         else if (OPT_GIVEN(DSS, VERSION))
1832                 txt = make_message("%s\n", VERSION_STRING);
1833         else
1834                 return;
1835         printf("%s", txt);
1836         free(txt);
1837         exit(EXIT_SUCCESS);
1838 }
1839
1840 static void show_subcommand_summary(void)
1841 {
1842         const struct lls_command *cmd;
1843         int i;
1844
1845         printf("Available subcommands:\n");
1846         for (i = 1; (cmd = lls_cmd(i, dss_suite)); i++) {
1847                 const char *name = lls_command_name(cmd);
1848                 const char *purpose = lls_purpose(cmd);
1849                 printf("%-11s%s\n", name, purpose);
1850         }
1851         exit(EXIT_SUCCESS);
1852 }
1853
1854 int main(int argc, char **argv)
1855 {
1856         int ret;
1857         char *errctx = NULL;
1858         unsigned num_inputs;
1859         const struct dss_user_data *ud;
1860
1861         ret = lls_parse(argc, argv, CMD_PTR(DSS), &cmdline_lpr, &errctx);
1862         if (ret < 0) {
1863                 ret = lopsub_error(ret, &errctx);
1864                 goto out;
1865         }
1866         lpr = cmdline_lpr;
1867         ret = parse_config_file(false /* no SIGHUP */, CMD_PTR(DSS));
1868         if (ret < 0)
1869                 goto out;
1870         handle_version_and_help();
1871         num_inputs = lls_num_inputs(lpr);
1872         if (num_inputs == 0)
1873                 show_subcommand_summary();
1874         ret = lls_lookup_subcmd(argv[argc - num_inputs], dss_suite, &errctx);
1875         if (ret < 0) {
1876                 ret = lopsub_error(ret, &errctx);
1877                 goto out;
1878         }
1879         subcmd = lls_cmd(ret, dss_suite);
1880         ret = lls_parse(num_inputs, argv + argc - num_inputs, subcmd,
1881                 &cmdline_sublpr, &errctx);
1882         if (ret < 0) {
1883                 ret = lopsub_error(ret, &errctx);
1884                 goto out;
1885         }
1886         sublpr = cmdline_sublpr;
1887         ret = parse_config_file(false /* no SIGHUP */, subcmd);
1888         if (ret < 0)
1889                 goto out;
1890         ret = check_config();
1891         if (ret < 0)
1892                 goto out;
1893         ret = setup_signal_handling();
1894         if (ret < 0)
1895                 goto out;
1896         ud = lls_user_data(subcmd);
1897         ret = ud->handler();
1898         signal_shutdown();
1899 out:
1900         if (ret < 0) {
1901                 if (errctx)
1902                         DSS_ERROR_LOG(("%s\n", errctx));
1903                 DSS_EMERG_LOG(("%s\n", dss_strerror(-ret)));
1904         }
1905         free(errctx);
1906         lls_free_parse_result(lpr, CMD_PTR(DSS));
1907         if (lpr != cmdline_lpr)
1908                 lls_free_parse_result(cmdline_lpr, CMD_PTR(DSS));
1909         lls_free_parse_result(sublpr, subcmd);
1910         if (sublpr != cmdline_sublpr)
1911                 lls_free_parse_result(cmdline_sublpr, subcmd);
1912         exit(ret >= 0? EXIT_SUCCESS : EXIT_FAILURE);
1913 }