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