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