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