2a0fb9edce9cb6af9ee9eecc880f9148bb2546bc
[dss.git] / dss.c
1 /*
2  * Copyright (C) 2008 Andre Noll <maan@systemlinux.org>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6 #include <string.h>
7 #include <stdlib.h>
8 #include <stdarg.h>
9 #include <assert.h>
10 #include <errno.h>
11 #include <sys/types.h>
12 #include <signal.h>
13 #include <ctype.h>
14 #include <sys/stat.h>
15 #include <unistd.h>
16 #include <inttypes.h>
17 #include <sys/time.h>
18 #include <time.h>
19 #include <sys/wait.h>
20 #include <fnmatch.h>
21 #include <limits.h>
22
23
24 #include "gcc-compat.h"
25 #include "cmdline.h"
26 #include "log.h"
27 #include "string.h"
28 #include "error.h"
29 #include "fd.h"
30 #include "exec.h"
31 #include "daemon.h"
32 #include "signal.h"
33 #include "df.h"
34 #include "time.h"
35 #include "snap.h"
36
37 /** Command line and config file options. */
38 static struct gengetopt_args_info conf;
39 /** Non-NULL if we log to a file. */
40 static FILE *logfile;
41 /** The read end of the signal pipe */
42 static int signal_pipe;
43 /** Process id of current pre-create-hook/rsync/post-create-hook process. */
44 static pid_t create_pid;
45 /** Whether the pre-create-hook/rsync/post-create-hook is currently stopped. */
46 static int create_process_stopped;
47 /** Process id of current rm process. */
48 static pid_t rm_pid;
49 /** When the next snapshot is due. */
50 static struct timeval next_snapshot_time;
51 /** Creation time of the snapshot currently being created. */
52 static int64_t current_snapshot_creation_time;
53 /** Needed by the post-create hook. */
54 static char *path_to_last_complete_snapshot;
55 /** \sa \ref snap.h for details. */
56 static unsigned snapshot_creation_status;
57 /** \sa \ref snap.h for details. */
58 static unsigned snapshot_removal_status;
59
60
61 DEFINE_DSS_ERRLIST;
62
63
64 /* a litte cpp magic helps to DRY */
65 #define COMMANDS \
66         COMMAND(ls) \
67         COMMAND(create) \
68         COMMAND(prune) \
69         COMMAND(run)
70 #define COMMAND(x) static int com_ ##x(void);
71 COMMANDS
72 #undef COMMAND
73 #define COMMAND(x) if (conf.x ##_given) return com_ ##x();
74 static int call_command_handler(void)
75 {
76         COMMANDS
77         DSS_EMERG_LOG("BUG: did not find command handler\n");
78         return -E_BUG;
79 }
80 #undef COMMAND
81 #undef COMMANDS
82
83 /**
84  * The log function of dss.
85  *
86  * \param ll Loglevel.
87  * \param fml Usual format string.
88  *
89  * All DSS_XXX_LOG() macros use this function.
90  */
91 __printf_2_3 void dss_log(int ll, const char* fmt,...)
92 {
93         va_list argp;
94         FILE *outfd;
95         struct tm *tm;
96         time_t t1;
97         char str[255] = "";
98
99         if (ll < conf.loglevel_arg)
100                 return;
101         outfd = logfile? logfile : stderr;
102         time(&t1);
103         tm = localtime(&t1);
104         strftime(str, sizeof(str), "%b %d %H:%M:%S", tm);
105         fprintf(outfd, "%s ", str);
106         if (conf.loglevel_arg <= INFO)
107                 fprintf(outfd, "%i: ", ll);
108         va_start(argp, fmt);
109         vfprintf(outfd, fmt, argp);
110         va_end(argp);
111 }
112
113 /**
114  * Print a message either to stdout or to the log file.
115  */
116 static __printf_1_2 void dss_msg(const char* fmt,...)
117 {
118         FILE *outfd = conf.daemon_given? logfile : stdout;
119         va_list argp;
120         va_start(argp, fmt);
121         vfprintf(outfd, fmt, argp);
122         va_end(argp);
123 }
124
125 static int disk_space_low(void)
126 {
127         struct disk_space ds;
128         int ret = get_disk_space(".", &ds);
129
130         if (ret < 0)
131                 return ret;
132         if (conf.min_free_mb_arg)
133                 if (ds.free_mb < conf.min_free_mb_arg)
134                         return 1;
135         if (conf.min_free_percent_arg)
136                 if (ds.percent_free < conf.min_free_percent_arg)
137                         return 1;
138         if (conf.min_free_percent_inodes_arg)
139                 if (ds.percent_free_inodes < conf.min_free_percent_inodes_arg)
140                         return 1;
141         return 0;
142 }
143
144 static void dss_get_snapshot_list(struct snapshot_list *sl)
145 {
146         get_snapshot_list(sl, conf.unit_interval_arg, conf.num_intervals_arg);
147 }
148
149 static void compute_next_snapshot_time(void)
150 {
151         struct timeval now, unit_interval = {.tv_sec = 24 * 3600 * conf.unit_interval_arg},
152                 tmp, diff;
153         int64_t x = 0;
154         unsigned wanted = desired_number_of_snapshots(0, conf.num_intervals_arg),
155                 num_complete_snapshots = 0;
156         int i, ret;
157         struct snapshot *s = NULL;
158         struct snapshot_list sl;
159
160         assert(snapshot_creation_status == SCS_READY);
161         current_snapshot_creation_time = 0;
162         dss_get_snapshot_list(&sl);
163         FOR_EACH_SNAPSHOT(s, i, &sl) {
164                 if (!(s->flags & SS_COMPLETE))
165                         continue;
166                 num_complete_snapshots++;
167                 x += s->completion_time - s->creation_time;
168         }
169         assert(x >= 0);
170         if (num_complete_snapshots)
171                 x /= num_complete_snapshots; /* avg time to create one snapshot */
172         x *= wanted; /* time to create all snapshots in interval 0 */
173         tmp.tv_sec = x;
174         tmp.tv_usec = 0;
175         ret = tv_diff(&unit_interval, &tmp, &diff); /* total sleep time per unit interval */
176         if (ret < 0 || !s) /* unit_interval < tmp or no snapshot */
177                 goto min_sleep;
178         tv_divide(wanted, &diff, &tmp); /* sleep time betweeen two snapshots */
179         diff.tv_sec = s->completion_time; /* completion time of the the latest snaphot */
180         diff.tv_usec = 0;
181         tv_add(&diff, &tmp, &next_snapshot_time);
182         gettimeofday(&now, NULL);
183         if (tv_diff(&now, &next_snapshot_time, NULL) < 0)
184                 goto out;
185 min_sleep:
186         next_snapshot_time = now;
187         next_snapshot_time.tv_sec += 60;
188 out:
189         free_snapshot_list(&sl);
190 }
191
192
193 static int remove_snapshot(struct snapshot *s, char *why)
194 {
195         int fds[3] = {0, 0, 0};
196         assert(!rm_pid);
197         char *new_name = being_deleted_name(s);
198         int ret = dss_rename(s->name, new_name);
199         char *argv[] = {"rm", "-rf", new_name, NULL};
200
201         if (ret < 0)
202                 goto out;
203         DSS_NOTICE_LOG("removing %s snapshot %s (interval = %i)\n",
204                 why, s->name, s->interval);
205         ret = dss_exec(&rm_pid, argv[0], argv, fds);
206 out:
207         free(new_name);
208         return ret;
209 }
210
211 static int snapshot_is_being_created(struct snapshot *s)
212 {
213         return s->creation_time == current_snapshot_creation_time;
214 }
215
216 /*
217  * return: 0: no redundant snapshots, 1: rm process started, negative: error
218  */
219 static int remove_redundant_snapshot(struct snapshot_list *sl)
220 {
221         int ret, i, interval;
222         struct snapshot *s;
223         unsigned missing = 0;
224
225         DSS_DEBUG_LOG("looking for intervals containing too many snapshots\n");
226         for (interval = conf.num_intervals_arg - 1; interval >= 0; interval--) {
227                 unsigned keep = desired_number_of_snapshots(interval, conf.num_intervals_arg);
228                 unsigned num = sl->interval_count[interval];
229                 struct snapshot *victim = NULL, *prev = NULL;
230                 int64_t score = LONG_MAX;
231
232                 if (keep >= num)
233                         missing += keep - num;
234 //              DSS_DEBUG_LOG("interval %i: keep: %u, have: %u, missing: %u\n",
235 //                      interval, keep, num, missing);
236                 if (keep + missing >= num)
237                         continue;
238                 /* redundant snapshot in this interval, pick snapshot with lowest score */
239                 FOR_EACH_SNAPSHOT(s, i, sl) {
240                         int64_t this_score;
241
242                         if (snapshot_is_being_created(s))
243                                 continue;
244                         //DSS_DEBUG_LOG("checking %s\n", s->name);
245                         if (s->interval > interval) {
246                                 prev = s;
247                                 continue;
248                         }
249                         if (s->interval < interval)
250                                 break;
251                         if (!victim) {
252                                 victim = s;
253                                 prev = s;
254                                 continue;
255                         }
256                         assert(prev);
257                         /* check if s is a better victim */
258                         this_score = s->creation_time - prev->creation_time;
259                         assert(this_score >= 0);
260                         //DSS_DEBUG_LOG("%s: score %lli\n", s->name, (long long)score);
261                         if (this_score < score) {
262                                 score = this_score;
263                                 victim = s;
264                         }
265                         prev = s;
266                 }
267                 assert(victim);
268                 if (conf.dry_run_given) {
269                         dss_msg("%s would be removed (interval = %i)\n",
270                                 victim->name, victim->interval);
271                         continue;
272                 }
273                 ret = remove_snapshot(victim, "redundant");
274                 return ret < 0? ret : 1;
275         }
276         return 0;
277 }
278
279 static int remove_outdated_snapshot(struct snapshot_list *sl)
280 {
281         int i, ret;
282         struct snapshot *s;
283
284         DSS_DEBUG_LOG("looking for snapshots belonging to intervals greater than %d\n",
285                 conf.num_intervals_arg);
286         FOR_EACH_SNAPSHOT(s, i, sl) {
287                 if (snapshot_is_being_created(s))
288                         continue;
289                 if (s->interval <= conf.num_intervals_arg)
290                         continue;
291                 if (conf.dry_run_given) {
292                         dss_msg("%s would be removed (interval = %i)\n",
293                                 s->name, s->interval);
294                         continue;
295                 }
296                 ret = remove_snapshot(s, "outdated");
297                 if (ret < 0)
298                         return ret;
299                 return 1;
300         }
301         return 0;
302 }
303
304 static int remove_oldest_snapshot(struct snapshot_list *sl)
305 {
306         struct snapshot *s = get_oldest_snapshot(sl);
307
308         if (!s) /* no snapshot found */
309                 return 0;
310         DSS_INFO_LOG("oldest snapshot: %s\n", s->name);
311         if (snapshot_is_being_created(s))
312                 return 0;
313         return remove_snapshot(s, "oldest");
314 }
315
316 static int rename_incomplete_snapshot(int64_t start)
317 {
318         char *old_name;
319         int ret;
320
321         free(path_to_last_complete_snapshot);
322         ret = complete_name(start, get_current_time(),
323                 &path_to_last_complete_snapshot);
324         if (ret < 0)
325                 return ret;
326         old_name = incomplete_name(start);
327         ret = dss_rename(old_name, path_to_last_complete_snapshot);
328         if (ret >= 0)
329                 DSS_NOTICE_LOG("%s -> %s\n", old_name,
330                         path_to_last_complete_snapshot);
331         free(old_name);
332         return ret;
333 }
334
335 static int try_to_free_disk_space(int low_disk_space)
336 {
337         int ret;
338         struct snapshot_list sl;
339
340         if (!low_disk_space && conf.keep_redundant_given)
341                 return 0;
342         dss_get_snapshot_list(&sl);
343         ret = remove_outdated_snapshot(&sl);
344         if (ret) /* error, or we are removing something */
345                 goto out;
346         /* no outdated snapshot */
347         ret = remove_redundant_snapshot(&sl);
348         if (ret)
349                 goto out;
350         ret = 0;
351         if (!low_disk_space)
352                 goto out;
353         DSS_WARNING_LOG("disk space low and nothing obvious to remove\n");
354         ret = remove_oldest_snapshot(&sl);
355         if (ret)
356                 goto out;
357         DSS_CRIT_LOG("uhuhu: not enough disk space for a single snapshot\n");
358         ret = -ERRNO_TO_DSS_ERROR(ENOSPC);
359 out:
360         free_snapshot_list(&sl);
361         return ret;
362 }
363
364 static int pre_create_hook(void)
365 {
366         int ret, fds[3] = {0, 0, 0};
367
368         if (!conf.pre_create_hook_given) {
369                 snapshot_creation_status = SCS_PRE_HOOK_SUCCESS;
370                 return 0;
371         }
372         DSS_DEBUG_LOG("executing %s\n", conf.pre_create_hook_arg);
373         ret = dss_exec_cmdline_pid(&create_pid,
374                 conf.pre_create_hook_arg, fds);
375         if (ret < 0)
376                 return ret;
377         snapshot_creation_status = SCS_PRE_HOOK_RUNNING;
378         return ret;
379 }
380
381 static int post_create_hook(void)
382 {
383         int ret, fds[3] = {0, 0, 0};
384         char *cmd;
385
386         if (!conf.post_create_hook_given) {
387                 snapshot_creation_status = SCS_READY;
388                 compute_next_snapshot_time();
389                 return 0;
390         }
391         cmd = make_message("%s %s/%s", conf.post_create_hook_arg,
392                 conf.dest_dir_arg, path_to_last_complete_snapshot);
393         DSS_NOTICE_LOG("executing %s\n", cmd);
394         ret = dss_exec_cmdline_pid(&create_pid, cmd, fds);
395         free(cmd);
396         if (ret < 0)
397                 return ret;
398         snapshot_creation_status = SCS_POST_HOOK_RUNNING;
399         return ret;
400 }
401
402 static void kill_process(pid_t pid)
403 {
404         if (!pid)
405                 return;
406         DSS_WARNING_LOG("sending SIGTERM to pid %d\n", (int)pid);
407         kill(pid, SIGTERM);
408 }
409
410 static void stop_create_process(void)
411 {
412         if (!create_pid || create_process_stopped)
413                 return;
414         kill(SIGSTOP, create_pid);
415         create_process_stopped = 1;
416 }
417
418 static void restart_create_process(void)
419 {
420         if (!create_pid || !create_process_stopped)
421                 return;
422         kill (SIGCONT, create_pid);
423         create_process_stopped = 0;
424 }
425
426 /**
427  * Print a log message about the exit status of a child.
428  */
429 static void log_termination_msg(pid_t pid, int status)
430 {
431         if (WIFEXITED(status))
432                 DSS_INFO_LOG("child %i exited. Exit status: %i\n", (int)pid,
433                         WEXITSTATUS(status));
434         else if (WIFSIGNALED(status))
435                 DSS_NOTICE_LOG("child %i was killed by signal %i\n", (int)pid,
436                         WTERMSIG(status));
437         else
438                 DSS_WARNING_LOG("child %i terminated abormally\n", (int)pid);
439 }
440
441 static int wait_for_process(pid_t pid, int *status)
442 {
443         int ret;
444
445         DSS_DEBUG_LOG("Waiting for process %d to terminate\n", (int)pid);
446         for (;;) {
447                 fd_set rfds;
448
449                 FD_ZERO(&rfds);
450                 FD_SET(signal_pipe, &rfds);
451                 ret = dss_select(signal_pipe + 1, &rfds, NULL, NULL);
452                 if (ret < 0)
453                         break;
454                 ret = next_signal();
455                 if (!ret)
456                         continue;
457                 if (ret == SIGCHLD) {
458                         ret = waitpid(pid, status, 0);
459                         if (ret >= 0)
460                                 break;
461                         if (errno != EINTR) { /* error */
462                                 ret = -ERRNO_TO_DSS_ERROR(errno);
463                                 break;
464                         }
465                 }
466                 /* SIGINT or SIGTERM */
467                 DSS_WARNING_LOG("sending SIGTERM to pid %d\n", (int)pid);
468                 kill(pid, SIGTERM);
469         }
470         if (ret < 0)
471                 DSS_ERROR_LOG("failed to wait for process %d\n", (int)pid);
472         else
473                 log_termination_msg(pid, *status);
474         return ret;
475 }
476
477 static int handle_rm_exit(int status)
478 {
479         rm_pid = 0;
480         if (!WIFEXITED(status))
481                 return -E_INVOLUNTARY_EXIT;
482         if (WEXITSTATUS(status))
483                 return -E_BAD_EXIT_CODE;
484         return 1;
485 }
486
487 static int wait_for_rm_process(void)
488 {
489         int status, ret = wait_for_process(rm_pid, &status);
490
491         if (ret < 0)
492                 return ret;
493         return handle_rm_exit(status);
494 }
495
496 static int handle_rsync_exit(int status)
497 {
498         int es, ret;
499
500         if (!WIFEXITED(status)) {
501                 DSS_ERROR_LOG("rsync process %d died involuntary\n", (int)create_pid);
502                 ret = -E_INVOLUNTARY_EXIT;
503                 snapshot_creation_status = SCS_READY;
504                 compute_next_snapshot_time();
505                 goto out;
506         }
507         es = WEXITSTATUS(status);
508         if (es == 13) { /* Errors with program diagnostics */
509                 DSS_WARNING_LOG("rsync process %d returned %d -- restarting\n",
510                         (int)create_pid, es);
511                 snapshot_creation_status = SCS_RSYNC_NEEDS_RESTART;
512                 gettimeofday(&next_snapshot_time, NULL);
513                 next_snapshot_time.tv_sec += 60;
514                 ret = 1;
515                 goto out;
516         }
517         if (es != 0 && es != 23 && es != 24) {
518                 DSS_ERROR_LOG("rsync process %d returned %d\n", (int)create_pid, es);
519                 ret = -E_BAD_EXIT_CODE;
520                 snapshot_creation_status = SCS_READY;
521                 compute_next_snapshot_time();
522                 goto out;
523         }
524         ret = rename_incomplete_snapshot(current_snapshot_creation_time);
525         if (ret < 0)
526                 goto out;
527         snapshot_creation_status = SCS_RSYNC_SUCCESS;
528 out:
529         create_pid = 0;
530         create_process_stopped = 0;
531         return ret;
532 }
533
534 static int handle_pre_create_hook_exit(int status)
535 {
536         int es, ret;
537         static int warn_count;
538
539         if (!WIFEXITED(status)) {
540                 snapshot_creation_status = SCS_READY;
541                 compute_next_snapshot_time();
542                 ret = -E_INVOLUNTARY_EXIT;
543                 goto out;
544         }
545         es = WEXITSTATUS(status);
546         if (es) {
547                 if (!warn_count--) {
548                         DSS_NOTICE_LOG("pre_create_hook %s returned %d\n",
549                                 conf.pre_create_hook_arg, es);
550                         DSS_NOTICE_LOG("deferring snapshot creation...\n");
551                         warn_count = 60; /* warn only once per hour */
552                 }
553                 snapshot_creation_status = SCS_READY;
554                 compute_next_snapshot_time();
555                 ret = 0;
556                 goto out;
557         }
558         warn_count = 0;
559         snapshot_creation_status = SCS_PRE_HOOK_SUCCESS;
560         ret = 1;
561 out:
562         create_pid = 0;
563         return ret;
564 }
565
566 static int handle_sigchld(void)
567 {
568         pid_t pid;
569         int status, ret = reap_child(&pid, &status);
570
571         if (ret <= 0)
572                 return ret;
573
574         if (pid == create_pid) {
575                 switch (snapshot_creation_status) {
576                 case SCS_PRE_HOOK_RUNNING:
577                         return handle_pre_create_hook_exit(status);
578                 case SCS_RSYNC_RUNNING:
579                         return handle_rsync_exit(status);
580                 case SCS_POST_HOOK_RUNNING:
581                         snapshot_creation_status = SCS_READY;
582                         compute_next_snapshot_time();
583                         return 1;
584                 default:
585                         DSS_EMERG_LOG("BUG: create can't die in status %d\n",
586                                 snapshot_creation_status);
587                         return -E_BUG;
588                 }
589         }
590         if (pid == rm_pid)
591                 return handle_rm_exit(status);
592         DSS_EMERG_LOG("BUG: unknown process %d died\n", (int)pid);
593         return -E_BUG;
594 }
595
596 static int check_config(void)
597 {
598         if (conf.unit_interval_arg <= 0) {
599                 DSS_ERROR_LOG("bad unit interval: %i\n", conf.unit_interval_arg);
600                 return -E_INVALID_NUMBER;
601         }
602         DSS_DEBUG_LOG("unit interval: %i day(s)\n", conf.unit_interval_arg);
603         if (conf.num_intervals_arg <= 0) {
604                 DSS_ERROR_LOG("bad number of intervals  %i\n", conf.num_intervals_arg);
605                 return -E_INVALID_NUMBER;
606         }
607         DSS_DEBUG_LOG("number of intervals: %i\n", conf.num_intervals_arg);
608         return 1;
609 }
610
611 static int parse_config_file(int override)
612 {
613         int ret;
614         char *config_file;
615         struct stat statbuf;
616         char *old_logfile_arg = NULL;
617         int old_daemon_given = 0;
618
619         if (conf.config_file_given)
620                 config_file = dss_strdup(conf.config_file_arg);
621         else {
622                 char *home = get_homedir();
623                 config_file = make_message("%s/.dssrc", home);
624                 free(home);
625         }
626         if (override) { /* SIGHUP */
627                 if (conf.logfile_given)
628                         old_logfile_arg = dss_strdup(conf.logfile_arg);
629                 old_daemon_given = conf.daemon_given;
630         }
631
632         ret = stat(config_file, &statbuf);
633         if (ret && conf.config_file_given) {
634                 ret = -ERRNO_TO_DSS_ERROR(errno);
635                 DSS_ERROR_LOG("failed to stat config file %s\n", config_file);
636                 goto out;
637         }
638         if (!ret) {
639                 struct cmdline_parser_params params = {
640                         .override = override,
641                         .initialize = 0,
642                         .check_required = 1,
643                         .check_ambiguity = 0,
644                         .print_errors = 1
645                 };
646                 if (override) { /* invalidate all rsync options */
647                         int i;
648
649                         for (i = 0; i < conf.rsync_option_given; i++) {
650                                 free(conf.rsync_option_arg[i]);
651                                 conf.rsync_option_arg[i] = NULL;
652                         }
653                         conf.rsync_option_given = 0;
654                 }
655                 cmdline_parser_config_file(config_file, &conf, &params);
656         }
657         ret = check_config();
658         if (ret < 0)
659                 goto out;
660         if (override) {
661                 /* don't change daemon mode on SIGHUP */
662                 conf.daemon_given = old_daemon_given;
663                 close_log(logfile);
664                 logfile = NULL;
665                 if (conf.logfile_given)
666                         free(old_logfile_arg);
667                 else if (conf.daemon_given) { /* re-use old logfile */
668                         conf.logfile_arg = old_logfile_arg;
669                         conf.logfile_given = 1;
670                 }
671         }
672         if (conf.logfile_given) {
673                 logfile = open_log(conf.logfile_arg);
674                 log_welcome(conf.loglevel_arg);
675         }
676         DSS_DEBUG_LOG("loglevel: %d\n", conf.loglevel_arg);
677 //      cmdline_parser_dump(logfile? logfile : stdout, &conf);
678 out:
679         free(config_file);
680         if (ret < 0)
681                 DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
682         return ret;
683 }
684
685 static int change_to_dest_dir(void)
686 {
687         DSS_INFO_LOG("changing cwd to %s\n", conf.dest_dir_arg);
688         return dss_chdir(conf.dest_dir_arg);
689 }
690
691 static int handle_sighup(void)
692 {
693         int ret;
694
695         DSS_NOTICE_LOG("SIGHUP\n");
696         ret = parse_config_file(1);
697         if (ret < 0)
698                 return ret;
699         return change_to_dest_dir();
700 }
701
702 static int handle_signal(void)
703 {
704         int sig, ret = next_signal();
705
706         if (ret <= 0)
707                 goto out;
708         sig = ret;
709         switch (sig) {
710         case SIGINT:
711         case SIGTERM:
712                 restart_create_process();
713                 kill_process(create_pid);
714                 kill_process(rm_pid);
715                 ret = -E_SIGNAL;
716                 break;
717         case SIGHUP:
718                 ret = handle_sighup();
719                 break;
720         case SIGCHLD:
721                 ret = handle_sigchld();
722                 break;
723         }
724 out:
725         if (ret < 0)
726                 DSS_ERROR_LOG("%s\n", dss_strerror(-ret));
727         return ret;
728 }
729
730 /*
731  * We can not use rsync locally if the local user is different from the remote
732  * user or if the src dir is not on the local host (or both).
733  */
734 static int use_rsync_locally(char *logname)
735 {
736         char *h = conf.remote_host_arg;
737
738         if (strcmp(h, "localhost") && strcmp(h, "127.0.0.1"))
739                 return 0;
740         if (conf.remote_user_given && strcmp(conf.remote_user_arg, logname))
741                 return 0;
742         return 1;
743 }
744
745 static void create_rsync_argv(char ***argv, int64_t *num)
746 {
747         char *logname, *newest;
748         int i = 0, j;
749         struct snapshot_list sl;
750
751         dss_get_snapshot_list(&sl);
752         newest = name_of_newest_complete_snapshot(&sl);
753         free_snapshot_list(&sl);
754
755         *argv = dss_malloc((15 + conf.rsync_option_given) * sizeof(char *));
756         (*argv)[i++] = dss_strdup("rsync");
757         (*argv)[i++] = dss_strdup("-aq");
758         (*argv)[i++] = dss_strdup("--delete");
759         for (j = 0; j < conf.rsync_option_given; j++)
760                 (*argv)[i++] = dss_strdup(conf.rsync_option_arg[j]);
761         if (newest) {
762                 DSS_INFO_LOG("using %s as reference snapshot\n", newest);
763                 (*argv)[i++] = make_message("--link-dest=../%s", newest);
764                 free(newest);
765         } else
766                 DSS_INFO_LOG("no previous snapshot found\n");
767         logname = dss_logname();
768         if (use_rsync_locally(logname))
769                 (*argv)[i++] = dss_strdup(conf.source_dir_arg);
770         else
771                 (*argv)[i++] = make_message("%s@%s:%s/", conf.remote_user_given?
772                         conf.remote_user_arg : logname,
773                         conf.remote_host_arg, conf.source_dir_arg);
774         free(logname);
775         *num = get_current_time();
776         (*argv)[i++] = incomplete_name(*num);
777         (*argv)[i++] = NULL;
778         for (j = 0; j < i; j++)
779                 DSS_DEBUG_LOG("argv[%d] = %s\n", j, (*argv)[j]);
780 }
781
782 static void free_rsync_argv(char **argv)
783 {
784         int i;
785
786         if (!argv)
787                 return;
788         for (i = 0; argv[i]; i++)
789                 free(argv[i]);
790         free(argv);
791 }
792
793 static int create_snapshot(char **argv)
794 {
795         int ret, fds[3] = {0, 0, 0};
796         char *name;
797
798         name = incomplete_name(current_snapshot_creation_time);
799         DSS_NOTICE_LOG("creating new snapshot %s\n", name);
800         free(name);
801         ret = dss_exec(&create_pid, argv[0], argv, fds);
802         if (ret < 0)
803                 return ret;
804         snapshot_creation_status = SCS_RSYNC_RUNNING;
805         return ret;
806 }
807
808 static int select_loop(void)
809 {
810         int ret;
811         /* check every 60 seconds for free disk space */
812         struct timeval tv;
813         char **rsync_argv = NULL;
814
815         for (;;) {
816                 fd_set rfds;
817                 int low_disk_space;
818                 struct timeval now, *tvp;
819
820                 if (rm_pid)
821                         tvp = NULL; /* sleep until rm process dies */
822                 else { /* sleep one minute */
823                         tv.tv_sec = 60;
824                         tv.tv_usec = 0;
825                         tvp = &tv;
826                 }
827                 FD_ZERO(&rfds);
828                 FD_SET(signal_pipe, &rfds);
829                 DSS_DEBUG_LOG("tvp: %p, tv_sec : %lu\n", tvp, (long unsigned) tv.tv_sec);
830                 ret = dss_select(signal_pipe + 1, &rfds, NULL, tvp);
831                 if (ret < 0)
832                         goto out;
833                 if (FD_ISSET(signal_pipe, &rfds)) {
834                         ret = handle_signal();
835                         if (ret < 0)
836                                 goto out;
837                 }
838                 if (rm_pid)
839                         continue;
840                 ret = disk_space_low();
841                 if (ret < 0)
842                         goto out;
843                 low_disk_space = ret;
844                 ret = try_to_free_disk_space(low_disk_space);
845                 if (ret < 0)
846                         goto out;
847                 if (rm_pid) {
848                         stop_create_process();
849                         continue;
850                 }
851                 restart_create_process();
852                 gettimeofday(&now, NULL);
853                 if (tv_diff(&next_snapshot_time, &now, NULL) > 0)
854                         continue;
855                 switch (snapshot_creation_status) {
856                 case SCS_READY:
857                         ret = pre_create_hook();
858                         if (ret < 0)
859                                 goto out;
860                         continue;
861                 case SCS_PRE_HOOK_RUNNING:
862                         continue;
863                 case SCS_RSYNC_NEEDS_RESTART:
864                         ret = create_snapshot(rsync_argv);
865                         if (ret < 0)
866                                 goto out;
867                         continue;
868                 case SCS_PRE_HOOK_SUCCESS:
869                         free_rsync_argv(rsync_argv);
870                         create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
871                         ret = create_snapshot(rsync_argv);
872                         if (ret < 0)
873                                 goto out;
874                         continue;
875                 case SCS_RSYNC_RUNNING:
876                         continue;
877                 case SCS_RSYNC_SUCCESS:
878                         ret = post_create_hook();
879                         if (ret < 0)
880                                 goto out;
881                         continue;
882                 case SCS_POST_HOOK_RUNNING:
883                         continue;
884                 }
885         }
886 out:
887         return ret;
888 }
889
890 static void exit_hook(int exit_code)
891 {
892         int fds[3] = {0, 0, 0};
893         char *argv[] = {conf.exit_hook_arg, dss_strerror(-exit_code), NULL};
894         pid_t pid;
895
896         if (!conf.exit_hook_given)
897                 return;
898         DSS_NOTICE_LOG("executing %s %s\n", argv[0], argv[1]);
899         dss_exec(&pid, conf.exit_hook_arg, argv, fds);
900 }
901
902 static int com_run(void)
903 {
904         int ret;
905
906         if (conf.dry_run_given) {
907                 DSS_ERROR_LOG("dry_run not supported by this command\n");
908                 return -E_SYNTAX;
909         }
910         ret = install_sighandler(SIGHUP);
911         if (ret < 0)
912                 return ret;
913         compute_next_snapshot_time();
914         ret = select_loop();
915         if (ret >= 0) /* impossible */
916                 ret = -E_BUG;
917         exit_hook(ret);
918         return ret;
919 }
920
921 static int com_prune(void)
922 {
923         int ret;
924         struct snapshot_list sl;
925         struct disk_space ds;
926
927         ret = get_disk_space(".", &ds);
928         if (ret < 0)
929                 return ret;
930         log_disk_space(&ds);
931         for (;;) {
932                 dss_get_snapshot_list(&sl);
933                 ret = remove_outdated_snapshot(&sl);
934                 free_snapshot_list(&sl);
935                 if (ret < 0)
936                         return ret;
937                 if (!ret)
938                         break;
939                 ret = wait_for_rm_process();
940                 if (ret < 0)
941                         goto out;
942         }
943         for (;;) {
944                 dss_get_snapshot_list(&sl);
945                 ret = remove_redundant_snapshot(&sl);
946                 free_snapshot_list(&sl);
947                 if (ret < 0)
948                         return ret;
949                 if (!ret)
950                         break;
951                 ret = wait_for_rm_process();
952                 if (ret < 0)
953                         goto out;
954         }
955         return 1;
956 out:
957         return ret;
958 }
959
960 static int com_create(void)
961 {
962         int ret, status;
963         char **rsync_argv;
964
965         if (conf.dry_run_given) {
966                 int i;
967                 char *msg = NULL;
968                 create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
969                 for (i = 0; rsync_argv[i]; i++) {
970                         char *tmp = msg;
971                         msg = make_message("%s%s%s", tmp? tmp : "",
972                                 tmp? " " : "", rsync_argv[i]);
973                         free(tmp);
974                 }
975                 free_rsync_argv(rsync_argv);
976                 dss_msg("%s\n", msg);
977                 free(msg);
978                 return 1;
979         }
980         ret = pre_create_hook();
981         if (ret < 0)
982                 return ret;
983         if (create_pid) {
984                 ret = wait_for_process(create_pid, &status);
985                 if (ret < 0)
986                         return ret;
987                 ret = handle_pre_create_hook_exit(status);
988                 if (ret < 0)
989                         return ret;
990         }
991         create_rsync_argv(&rsync_argv, &current_snapshot_creation_time);
992         ret = create_snapshot(rsync_argv);
993         if (ret < 0)
994                 goto out;
995         ret = wait_for_process(create_pid, &status);
996         if (ret < 0)
997                 goto out;
998         ret = handle_rsync_exit(status);
999         if (ret < 0)
1000                 goto out;
1001         post_create_hook();
1002         if (create_pid)
1003                 ret = wait_for_process(create_pid, &status);
1004 out:
1005         free_rsync_argv(rsync_argv);
1006         return ret;
1007 }
1008
1009 static int com_ls(void)
1010 {
1011         int i;
1012         struct snapshot_list sl;
1013         struct snapshot *s;
1014
1015         dss_get_snapshot_list(&sl);
1016         FOR_EACH_SNAPSHOT(s, i, &sl) {
1017                 int64_t d = 0;
1018                 if (s->flags & SS_COMPLETE)
1019                         d = (s->completion_time - s->creation_time) / 60;
1020                 dss_msg("%u\t%s\t%3" PRId64 ":%02" PRId64 "\n", s->interval, s->name, d/60, d%60);
1021         };
1022         free_snapshot_list(&sl);
1023         return 1;
1024 }
1025
1026 static int setup_signal_handling(void)
1027 {
1028         int ret;
1029
1030         DSS_INFO_LOG("setting up signal handlers\n");
1031         signal_pipe = signal_init(); /* always successful */
1032         ret = install_sighandler(SIGINT);
1033         if (ret < 0)
1034                 return ret;
1035         ret = install_sighandler(SIGTERM);
1036         if (ret < 0)
1037                 return ret;
1038         return install_sighandler(SIGCHLD);
1039 }
1040
1041 /**
1042  * The main function of dss.
1043  *
1044  * \param argc Usual argument count.
1045  * \param argv Usual argument vector.
1046  */
1047 int main(int argc, char **argv)
1048 {
1049         int ret;
1050         struct cmdline_parser_params params = {
1051                 .override = 0,
1052                 .initialize = 1,
1053                 .check_required = 0,
1054                 .check_ambiguity = 0,
1055                 .print_errors = 1
1056         };
1057
1058         cmdline_parser_ext(argc, argv, &conf, &params); /* aborts on errors */
1059         ret = parse_config_file(0);
1060         if (ret < 0)
1061                 goto out;
1062         if (conf.daemon_given)
1063                 daemon_init();
1064         ret = change_to_dest_dir();
1065         if (ret < 0)
1066                 goto out;
1067         ret = setup_signal_handling();
1068         if (ret < 0)
1069                 goto out;
1070         ret = call_command_handler();
1071 out:
1072         if (ret < 0)
1073                 DSS_EMERG_LOG("%s\n", dss_strerror(-ret));
1074         exit(ret >= 0? EXIT_SUCCESS : EXIT_FAILURE);
1075 }