]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/dird.c
Do not update state file after a bacula-xxx -t
[bacula/bacula] / bacula / src / dird / dird.c
1 /*
2    Bacula(R) - The Network Backup Solution
3
4    Copyright (C) 2000-2015 Kern Sibbald
5    Copyright (C) 2000-2014 Free Software Foundation Europe e.V.
6
7    The original author of Bacula is Kern Sibbald, with contributions
8    from many others, a complete list can be found in the file AUTHORS.
9
10    You may use this file and others of this release according to the
11    license defined in the LICENSE file, which includes the Affero General
12    Public License, v3.0 ("AGPLv3") and some additional permissions and
13    terms pursuant to its AGPLv3 Section 7.
14
15    This notice must be preserved when any source code is 
16    conveyed and/or propagated.
17
18    Bacula(R) is a registered trademark of Kern Sibbald.
19 */
20 /*
21  *
22  *   Bacula Director daemon -- this is the main program
23  *
24  *     Kern Sibbald, March MM
25  *
26  */
27
28 #include "bacula.h"
29 #include "dird.h"
30 #ifndef HAVE_REGEX_H
31 #include "lib/bregex.h"
32 #else
33 #include <regex.h>
34 #endif
35 #ifdef HAVE_DIRENT_H
36 #include <dirent.h>
37 #define NAMELEN(dirent) (strlen((dirent)->d_name))
38 #endif
39 #ifndef HAVE_READDIR_R
40 int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result);
41 #endif
42
43 /* Forward referenced subroutines */
44 void terminate_dird(int sig);
45 static bool check_resources();
46 static void cleanup_old_files();
47
48 /* Exported subroutines */
49 extern "C" void reload_config(int sig);
50 extern void invalidate_schedules();
51 extern bool parse_dir_config(CONFIG *config, const char *configfile, int exit_code);
52
53 /* Imported subroutines */
54 JCR *wait_for_next_job(char *runjob);
55 void term_scheduler();
56 void term_ua_server();
57 void start_UA_server(dlist *addrs);
58 void init_job_server(int max_workers);
59 void term_job_server();
60 void store_jobtype(LEX *lc, RES_ITEM *item, int index, int pass);
61 void store_level(LEX *lc, RES_ITEM *item, int index, int pass);
62 void store_replace(LEX *lc, RES_ITEM *item, int index, int pass);
63 void store_migtype(LEX *lc, RES_ITEM *item, int index, int pass);
64 void init_device_resources();
65
66
67 static char *runjob = NULL;
68 static bool background = true;
69 static void init_reload(void);
70 static CONFIG *config;
71 static bool test_config = false;
72
73 /* Globals Exported */
74 DIRRES *director;                     /* Director resource */
75 int FDConnectTimeout;
76 int SDConnectTimeout;
77 char *configfile = NULL;
78 void *start_heap;
79 utime_t last_reload_time = 0;
80
81 /* Globals Imported */
82 extern RES_ITEM job_items[];
83 #if defined(_MSC_VER)
84 extern "C" { // work around visual compiler mangling variables
85    extern URES res_all;
86 }
87 #else
88 extern URES res_all;
89 #endif
90
91 typedef enum {
92    CHECK_CONNECTION,  /* Check catalog connection */
93    UPDATE_CATALOG,    /* Ensure that catalog is ok with conf */
94    UPDATE_AND_FIX     /* Ensure that catalog is ok, and fix old jobs */
95 } cat_op;
96 static bool check_catalog(cat_op mode);
97
98 #define CONFIG_FILE "bacula-dir.conf" /* default configuration file */
99
100 static bool dir_sql_query(JCR *jcr, const char *cmd) 
101
102    if (jcr && jcr->db && jcr->db->is_connected()) {
103       return db_sql_query(jcr->db, cmd, NULL, NULL);
104    } 
105    return false; 
106
107
108 static bool dir_sql_escape(JCR *jcr, BDB *mdb, char *snew, char *sold, int len) 
109
110    if (jcr && jcr->db && jcr->db->is_connected()) { 
111       db_escape_string(jcr, mdb, snew, sold, len);
112       return true;
113    } 
114    return false; 
115
116
117 static void usage()
118 {
119    fprintf(stderr, _(
120       PROG_COPYRIGHT
121       "\nVersion: %s (%s)\n\n"
122       "Usage: bacula-dir [-f -s] [-c config_file] [-d debug_level] [config_file]\n"
123       "     -c <file>        set configuration file to file\n"
124       "     -d <nn>[,<tags>] set debug level to <nn>, debug tags to <tags>\n"
125       "     -dt              print timestamp in debug output\n"
126       "     -T               set trace on\n"
127       "     -f               run in foreground (for debugging)\n"
128       "     -g               groupid\n"
129       "     -m               print kaboom output (for debugging)\n"
130       "     -r <job>         run <job> now\n"
131       "     -s               no signals\n"
132       "     -t               test - read configuration and exit\n"
133       "     -u               userid\n"
134       "     -v               verbose user messages\n"
135       "     -?               print this message.\n"
136       "\n"), 2000, VERSION, BDATE);
137
138    exit(1);
139 }
140
141 /*
142  * !!! WARNING !!! Use this function only when bacula is stopped.
143  * ie, after a fatal signal and before exiting the program
144  * Print information about a JCR
145  */
146 static void dir_debug_print(JCR *jcr, FILE *fp)
147 {
148    fprintf(fp, "\twstore=%p rstore=%p wjcr=%p client=%p reschedule_count=%d SD_msg_chan_started=%d\n",
149            jcr->wstore, jcr->rstore, jcr->wjcr, jcr->client, jcr->reschedule_count, (int)jcr->SD_msg_chan_started);
150 }
151
152 /*********************************************************************
153  *
154  *         Main Bacula Director Server program
155  *
156  */
157 #if defined(HAVE_WIN32)
158 /* For Win32 main() is in src/win32 code ... */
159 #define main BaculaMain
160 #endif
161
162 int main (int argc, char *argv[])
163 {
164    int ch;
165    JCR *jcr;
166    bool no_signals = false;
167    char *uid = NULL;
168    char *gid = NULL;
169
170    start_heap = sbrk(0);
171    setlocale(LC_ALL, "");
172    bindtextdomain("bacula", LOCALEDIR);
173    textdomain("bacula");
174
175    init_stack_dump();
176    my_name_is(argc, argv, "bacula-dir");
177    init_msg(NULL, NULL);              /* initialize message handler */
178    init_reload();
179    daemon_start_time = time(NULL);
180
181    console_command = run_console_command;
182
183    while ((ch = getopt(argc, argv, "c:d:fg:mr:stu:v?T")) != -1) {
184       switch (ch) {
185       case 'c':                    /* specify config file */
186          if (configfile != NULL) {
187             free(configfile);
188          }
189          configfile = bstrdup(optarg);
190          break;
191
192       case 'd':                    /* set debug level */
193          if (*optarg == 't') {
194             dbg_timestamp = true;
195          } else {
196             char *p;
197             /* We probably find a tag list -d 10,sql,bvfs */
198             if ((p = strchr(optarg, ',')) != NULL) {
199                *p = 0;
200             }
201             debug_level = atoi(optarg);
202             if (debug_level <= 0) {
203                debug_level = 1;
204             }
205             if (p) {
206                debug_parse_tags(p+1, &debug_level_tags);
207             }
208          }
209          Dmsg1(10, "Debug level = %lld\n", debug_level);
210          break;
211
212       case 'T':
213          set_trace(true);
214          break;
215
216       case 'f':                    /* run in foreground */
217          background = false;
218          break;
219
220       case 'g':                    /* set group id */
221          gid = optarg;
222          break;
223
224       case 'm':                    /* print kaboom output */
225          prt_kaboom = true;
226          break;
227
228       case 'r':                    /* run job */
229          if (runjob != NULL) {
230             free(runjob);
231          }
232          if (optarg) {
233             runjob = bstrdup(optarg);
234          }
235          break;
236
237       case 's':                    /* turn off signals */
238          no_signals = true;
239          break;
240
241       case 't':                    /* test config */
242          test_config = true;
243          break;
244
245       case 'u':                    /* set uid */
246          uid = optarg;
247          break;
248
249       case 'v':                    /* verbose */
250          verbose++;
251          break;
252
253       case '?':
254       default:
255          usage();
256
257       }
258    }
259    argc -= optind;
260    argv += optind;
261
262    if (!no_signals) {
263       init_signals(terminate_dird);
264    }
265
266    if (argc) {
267       if (configfile != NULL) {
268          free(configfile);
269       }
270       configfile = bstrdup(*argv);
271       argc--;
272       argv++;
273    }
274    if (argc) {
275       usage();
276    }
277
278    if (!test_config) {                /* we don't need to do this block in test mode */
279       if (background) {
280          daemon_start();
281          init_stack_dump();              /* grab new pid */
282       }
283    }
284
285    if (configfile == NULL) {
286       configfile = bstrdup(CONFIG_FILE);
287    }
288
289    config = new_config_parser();
290
291    parse_dir_config(config, configfile, M_ERROR_TERM);
292
293    if (init_crypto() != 0) {
294       Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Cryptography library initialization failed.\n"));
295    }
296
297    if (!check_resources()) {
298       Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
299    }
300
301    if (!test_config) {
302       /* Create pid must come after we are a daemon -- so we have our final pid */
303       create_pid_file(director->pid_directory, "bacula-dir",
304                       get_first_port_host_order(director->DIRaddrs));
305       read_state_file(director->working_directory, "bacula-dir",
306                       get_first_port_host_order(director->DIRaddrs));
307    }
308
309    set_jcr_in_tsd(INVALID_JCR);
310    set_thread_concurrency(director->MaxConcurrentJobs * 2 +
311                           4 /* UA */ + 5 /* sched+watchdog+jobsvr+misc */);
312    lmgr_init_thread(); /* initialize the lockmanager stack */
313
314    load_dir_plugins(director->plugin_directory);
315
316    drop(uid, gid, false);                    /* reduce privileges if requested */
317
318    /* If we are in testing mode, we don't try to fix the catalog */
319    cat_op mode=(test_config)?CHECK_CONNECTION:UPDATE_AND_FIX;
320
321    if (!check_catalog(mode)) {
322       Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
323    }
324
325    if (test_config) {
326       terminate_dird(0);
327    }
328
329    my_name_is(0, NULL, director->name());    /* set user defined name */
330
331    cleanup_old_files();
332
333    /* Plug database interface for library routines */
334    p_sql_query = (sql_query_call)dir_sql_query;
335    p_sql_escape = (sql_escape_call)dir_sql_escape;
336
337    FDConnectTimeout = (int)director->FDConnectTimeout;
338    SDConnectTimeout = (int)director->SDConnectTimeout;
339
340 #if !defined(HAVE_WIN32)
341    signal(SIGHUP, reload_config);
342 #endif
343
344    init_console_msg(working_directory);
345
346    Dmsg0(200, "Start UA server\n");
347    start_UA_server(director->DIRaddrs);
348
349    start_watchdog();                  /* start network watchdog thread */
350
351    init_jcr_subsystem();              /* start JCR watchdogs etc. */
352
353    init_job_server(director->MaxConcurrentJobs);
354
355    dbg_jcr_add_hook(dir_debug_print); /* used to director variables */
356    dbg_jcr_add_hook(bdb_debug_print);     /* used to debug B_DB connexion after fatal signal */
357
358 //   init_device_resources();
359
360    Dmsg0(200, "wait for next job\n");
361    /* Main loop -- call scheduler to get next job to run */
362    while ( (jcr = wait_for_next_job(runjob)) ) {
363       run_job(jcr);                   /* run job */
364       free_jcr(jcr);                  /* release jcr */
365       set_jcr_in_tsd(INVALID_JCR);
366       if (runjob) {                   /* command line, run a single job? */
367          break;                       /* yes, terminate */
368       }
369    }
370
371    terminate_dird(0);
372
373    return 0;
374 }
375
376 struct RELOAD_TABLE {
377    int job_count;
378    RES **res_table;
379 };
380
381 static const int max_reloads = 50;
382 static RELOAD_TABLE reload_table[max_reloads];
383
384 static void init_reload(void)
385 {
386    for (int i=0; i < max_reloads; i++) {
387       reload_table[i].job_count = 0;
388       reload_table[i].res_table = NULL;
389    }
390 }
391
392 /*
393  * This subroutine frees a saved resource table.
394  *  It was saved when a new table was created with "reload"
395  */
396 static void free_saved_resources(int table)
397 {
398    int num = r_last - r_first + 1;
399    RES **res_tab = reload_table[table].res_table;
400    if (!res_tab) {
401       Dmsg1(100, "res_tab for table %d already released.\n", table);
402       return;
403    }
404    Dmsg1(100, "Freeing resources for table %d\n", table);
405    for (int j=0; j<num; j++) {
406       free_resource(res_tab[j], r_first + j);
407    }
408    free(res_tab);
409    reload_table[table].job_count = 0;
410    reload_table[table].res_table = NULL;
411 }
412
413 /*
414  * Called here at the end of every job that was
415  * hooked decrementing the active job_count. When
416  * it goes to zero, no one is using the associated
417  * resource table, so free it.
418  */
419 static void reload_job_end_cb(JCR *jcr, void *ctx)
420 {
421    int reload_id = (int)((intptr_t)ctx);
422    Dmsg3(100, "reload job_end JobId=%d table=%d cnt=%d\n", jcr->JobId,
423       reload_id, reload_table[reload_id].job_count);
424    lock_jobs();
425    LockRes();
426    if (--reload_table[reload_id].job_count <= 0) {
427       free_saved_resources(reload_id);
428    }
429    UnlockRes();
430    unlock_jobs();
431 }
432
433 static int find_free_reload_table_entry()
434 {
435    int table = -1;
436    for (int i=0; i < max_reloads; i++) {
437       if (reload_table[i].res_table == NULL) {
438          table = i;
439          break;
440       }
441    }
442    return table;
443 }
444
445 /*
446  * If we get here, we have received a SIGHUP, which means to
447  *    reread our configuration file.
448  *
449  * The algorithm used is as follows: we count how many jobs are
450  *   running and mark the running jobs to make a callback on
451  *   exiting. The old config is saved with the reload table
452  *   id in a reload table. The new config file is read. Now, as
453  *   each job exits, it calls back to the reload_job_end_cb(), which
454  *   decrements the count of open jobs for the given reload table.
455  *   When the count goes to zero, we release those resources.
456  *   This allows us to have pointers into the resource table (from
457  *   jobs), and once they exit and all the pointers are released, we
458  *   release the old table. Note, if no new jobs are running since the
459  *   last reload, then the old resources will be immediately release.
460  *   A console is considered a job because it may have pointers to
461  *   resources, but a SYSTEM job is not since it *should* not have any
462  *   permanent pointers to jobs.
463  */
464 extern "C"
465 void reload_config(int sig)
466 {
467    static bool already_here = false;
468 #if !defined(HAVE_WIN32)
469    sigset_t set;
470 #endif
471    JCR *jcr;
472    int njobs = 0;                     /* number of running jobs */
473    int table, rtable;
474    bool ok;
475
476    if (already_here) {
477       abort();                        /* Oops, recursion -> die */
478    }
479    already_here = true;
480
481 #if !defined(HAVE_WIN32)
482    sigemptyset(&set);
483    sigaddset(&set, SIGHUP);
484    sigprocmask(SIG_BLOCK, &set, NULL);
485 #endif
486
487    lock_jobs();
488    LockRes();
489
490    table = find_free_reload_table_entry();
491    if (table < 0) {
492       Jmsg(NULL, M_ERROR, 0, _("Too many open reload requests. Request ignored.\n"));
493       goto bail_out;
494    }
495
496    Dmsg1(100, "Reload_config njobs=%d\n", njobs);
497    reload_table[table].res_table = config->save_resources();
498    Dmsg1(100, "Saved old config in table %d\n", table);
499
500    ok = parse_dir_config(config, configfile, M_ERROR);
501
502    Dmsg0(100, "Reloaded config file\n");
503    if (!ok || !check_resources() || !check_catalog(UPDATE_CATALOG)) {
504       rtable = find_free_reload_table_entry();    /* save new, bad table */
505       if (rtable < 0) {
506          Jmsg(NULL, M_ERROR, 0, _("Please correct configuration file: %s\n"), configfile);
507          Jmsg(NULL, M_ERROR_TERM, 0, _("Out of reload table entries. Giving up.\n"));
508       } else {
509          Jmsg(NULL, M_ERROR, 0, _("Please correct configuration file: %s\n"), configfile);
510          Jmsg(NULL, M_ERROR, 0, _("Resetting previous configuration.\n"));
511       }
512       reload_table[rtable].res_table = config->save_resources();
513       /* Now restore old resource values */
514       int num = r_last - r_first + 1;
515       RES **res_tab = reload_table[table].res_table;
516       for (int i=0; i<num; i++) {
517          res_head[i] = res_tab[i];
518       }
519       table = rtable;                 /* release new, bad, saved table below */
520    } else {
521       invalidate_schedules();
522       /*
523        * Hook all active jobs so that they release this table
524        */
525       foreach_jcr(jcr) {
526          if (jcr->getJobType() != JT_SYSTEM) {
527             reload_table[table].job_count++;
528             job_end_push(jcr, reload_job_end_cb, (void *)((long int)table));
529             njobs++;
530          }
531       }
532       endeach_jcr(jcr);
533    }
534
535    /* Reset globals */
536    set_working_directory(director->working_directory);
537    FDConnectTimeout = director->FDConnectTimeout;
538    SDConnectTimeout = director->SDConnectTimeout;
539    Dmsg0(10, "Director's configuration file reread.\n");
540
541    /* Now release saved resources, if no jobs using the resources */
542    if (njobs == 0) {
543       free_saved_resources(table);
544    }
545
546 bail_out:
547    UnlockRes();
548    unlock_jobs();
549 #if !defined(HAVE_WIN32)
550    sigprocmask(SIG_UNBLOCK, &set, NULL);
551    signal(SIGHUP, reload_config);
552 #endif
553    already_here = false;
554 }
555
556 /* Cleanup and then exit */
557 void terminate_dird(int sig)
558 {
559    static bool already_here = false;
560
561    if (already_here) {                /* avoid recursive temination problems */
562       bmicrosleep(2, 0);              /* yield */
563       exit(1);
564    }
565    already_here = true;
566    debug_level = 0;                   /* turn off debug */
567    stop_watchdog();
568    generate_daemon_event(NULL, "Exit");
569    unload_plugins();
570    if (!test_config) {
571       write_state_file(director->working_directory, "bacula-dir", get_first_port_host_order(director->DIRaddrs));
572       delete_pid_file(director->pid_directory, "bacula-dir", get_first_port_host_order(director->DIRaddrs));
573    }
574    term_scheduler();
575    term_job_server();
576    if (runjob) {
577       free(runjob);
578    }
579    if (configfile != NULL) {
580       free(configfile);
581    }
582    if (chk_dbglvl(5)) {
583       print_memory_pool_stats();
584    }
585    if (config) {
586       config->free_resources();
587       free(config);
588       config = NULL;
589    }
590    term_ua_server();
591    term_msg();                        /* terminate message handler */
592    cleanup_crypto();
593    close_memory_pool();               /* release free memory in pool */
594    lmgr_cleanup_main();
595    sm_dump(false);
596    exit(sig);
597 }
598
599 /*
600  * Make a quick check to see that we have all the
601  * resources needed.
602  *
603  *  **** FIXME **** this routine could be a lot more
604  *   intelligent and comprehensive.
605  */
606 static bool check_resources()
607 {
608    bool OK = true;
609    JOB *job;
610    bool need_tls;
611
612    LockRes();
613
614    job = (JOB *)GetNextRes(R_JOB, NULL);
615    director = (DIRRES *)GetNextRes(R_DIRECTOR, NULL);
616    if (!director) {
617       Jmsg(NULL, M_FATAL, 0, _("No Director resource defined in %s\n"
618 "Without that I don't know who I am :-(\n"), configfile);
619       OK = false;
620    } else {
621       set_working_directory(director->working_directory);
622       if (!director->messages) {       /* If message resource not specified */
623          director->messages = (MSGS *)GetNextRes(R_MSGS, NULL);
624          if (!director->messages) {
625             Jmsg(NULL, M_FATAL, 0, _("No Messages resource defined in %s\n"), configfile);
626             OK = false;
627          }
628       }
629       if (GetNextRes(R_DIRECTOR, (RES *)director) != NULL) {
630          Jmsg(NULL, M_FATAL, 0, _("Only one Director resource permitted in %s\n"),
631             configfile);
632          OK = false;
633       }
634       /* tls_require implies tls_enable */
635       if (director->tls_require) {
636          if (have_tls) {
637             director->tls_enable = true;
638          } else {
639             Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
640             OK = false;
641          }
642       }
643
644       need_tls = director->tls_enable || director->tls_authenticate;
645
646       if (!director->tls_certfile && need_tls) {
647          Jmsg(NULL, M_FATAL, 0, _("\"TLS Certificate\" file not defined for Director \"%s\" in %s.\n"),
648             director->name(), configfile);
649          OK = false;
650       }
651
652       if (!director->tls_keyfile && need_tls) {
653          Jmsg(NULL, M_FATAL, 0, _("\"TLS Key\" file not defined for Director \"%s\" in %s.\n"),
654             director->name(), configfile);
655          OK = false;
656       }
657
658       if ((!director->tls_ca_certfile && !director->tls_ca_certdir) &&
659            need_tls && director->tls_verify_peer) {
660          Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\" or \"TLS CA"
661               " Certificate Dir\" are defined for Director \"%s\" in %s."
662               " At least one CA certificate store is required"
663               " when using \"TLS Verify Peer\".\n"),
664               director->name(), configfile);
665          OK = false;
666       }
667
668       /* If everything is well, attempt to initialize our per-resource TLS context */
669       if (OK && (need_tls || director->tls_require)) {
670          /* Initialize TLS context:
671           * Args: CA certfile, CA certdir, Certfile, Keyfile,
672           * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
673          director->tls_ctx = new_tls_context(director->tls_ca_certfile,
674             director->tls_ca_certdir, director->tls_certfile,
675             director->tls_keyfile, NULL, NULL, director->tls_dhfile,
676             director->tls_verify_peer);
677
678          if (!director->tls_ctx) {
679             Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for Director \"%s\" in %s.\n"),
680                  director->name(), configfile);
681             OK = false;
682          }
683       }
684    }
685
686    if (!job) {
687       Jmsg(NULL, M_FATAL, 0, _("No Job records defined in %s\n"), configfile);
688       OK = false;
689    }
690    foreach_res(job, R_JOB) {
691       int i;
692
693       if (job->jobdefs) {
694          /* Handle Storage alists specifically */
695          JOB *jobdefs = job->jobdefs;
696          if (jobdefs->storage && !job->storage) {
697             STORE *st;
698             job->storage = New(alist(10, not_owned_by_alist));
699             foreach_alist(st, jobdefs->storage) {
700                job->storage->append(st);
701             }
702          }
703          /* Handle RunScripts alists specifically */
704          if (jobdefs->RunScripts) {
705             RUNSCRIPT *rs, *elt;
706
707             if (!job->RunScripts) {
708                job->RunScripts = New(alist(10, not_owned_by_alist));
709             }
710
711             foreach_alist(rs, jobdefs->RunScripts) {
712                elt = copy_runscript(rs);
713                job->RunScripts->append(elt); /* we have to free it */
714             }
715          }
716
717          /* Transfer default items from JobDefs Resource */
718          for (i=0; job_items[i].name; i++) {
719             char **def_svalue, **svalue;  /* string value */
720             uint32_t *def_ivalue, *ivalue;     /* integer value */
721             bool *def_bvalue, *bvalue;    /* bool value */
722             int64_t *def_lvalue, *lvalue; /* 64 bit values */
723             uint32_t offset;
724
725             Dmsg4(1400, "Job \"%s\", field \"%s\" bit=%d def=%d\n",
726                 job->name(), job_items[i].name,
727                 bit_is_set(i, job->hdr.item_present),
728                 bit_is_set(i, job->jobdefs->hdr.item_present));
729
730             if (!bit_is_set(i, job->hdr.item_present) &&
731                  bit_is_set(i, job->jobdefs->hdr.item_present)) {
732                Dmsg2(400, "Job \"%s\", field \"%s\": getting default.\n",
733                  job->name(), job_items[i].name);
734                offset = (char *)(job_items[i].value) - (char *)&res_all;
735                /*
736                 * Handle strings and directory strings
737                 */
738                if (job_items[i].handler == store_str ||
739                    job_items[i].handler == store_dir) {
740                   def_svalue = (char **)((char *)(job->jobdefs) + offset);
741                   Dmsg5(400, "Job \"%s\", field \"%s\" def_svalue=%s item %d offset=%u\n",
742                        job->name(), job_items[i].name, *def_svalue, i, offset);
743                   svalue = (char **)((char *)job + offset);
744                   if (*svalue) {
745                      Pmsg1(000, _("Hey something is wrong. p=0x%lu\n"), *svalue);
746                   }
747                   *svalue = bstrdup(*def_svalue);
748                   set_bit(i, job->hdr.item_present);
749                /*
750                 * Handle resources
751                 */
752                } else if (job_items[i].handler == store_res) {
753                   def_svalue = (char **)((char *)(job->jobdefs) + offset);
754                   Dmsg4(400, "Job \"%s\", field \"%s\" item %d offset=%u\n",
755                        job->name(), job_items[i].name, i, offset);
756                   svalue = (char **)((char *)job + offset);
757                   if (*svalue) {
758                      Pmsg1(000, _("Hey something is wrong. p=0x%lu\n"), *svalue);
759                   }
760                   *svalue = *def_svalue;
761                   set_bit(i, job->hdr.item_present);
762                /*
763                 * Handle alist resources
764                 */
765                } else if (job_items[i].handler == store_alist_res) {
766                   if (bit_is_set(i, job->jobdefs->hdr.item_present)) {
767                      set_bit(i, job->hdr.item_present);
768                   }
769                /*
770                 * Handle integer fields
771                 *    Note, our store_bit does not handle bitmaped fields
772                 */
773                } else if (job_items[i].handler == store_bit     ||
774                           job_items[i].handler == store_pint32  ||
775                           job_items[i].handler == store_jobtype ||
776                           job_items[i].handler == store_level   ||
777                           job_items[i].handler == store_int32   ||
778                           job_items[i].handler == store_size32  ||
779                           job_items[i].handler == store_migtype ||
780                           job_items[i].handler == store_replace) {
781                   def_ivalue = (uint32_t *)((char *)(job->jobdefs) + offset);
782                   Dmsg5(400, "Job \"%s\", field \"%s\" def_ivalue=%d item %d offset=%u\n",
783                        job->name(), job_items[i].name, *def_ivalue, i, offset);
784                   ivalue = (uint32_t *)((char *)job + offset);
785                   *ivalue = *def_ivalue;
786                   set_bit(i, job->hdr.item_present);
787                /*
788                 * Handle 64 bit integer fields
789                 */
790                } else if (job_items[i].handler == store_time   ||
791                           job_items[i].handler == store_size64 ||
792                           job_items[i].handler == store_speed  ||
793                           job_items[i].handler == store_int64) {
794                   def_lvalue = (int64_t *)((char *)(job->jobdefs) + offset);
795                   Dmsg5(400, "Job \"%s\", field \"%s\" def_lvalue=%" lld " item %d offset=%u\n",
796                        job->name(), job_items[i].name, *def_lvalue, i, offset);
797                   lvalue = (int64_t *)((char *)job + offset);
798                   *lvalue = *def_lvalue;
799                   set_bit(i, job->hdr.item_present);
800                /*
801                 * Handle bool fields
802                 */
803                } else if (job_items[i].handler == store_bool) {
804                   def_bvalue = (bool *)((char *)(job->jobdefs) + offset);
805                   Dmsg5(400, "Job \"%s\", field \"%s\" def_bvalue=%d item %d offset=%u\n",
806                        job->name(), job_items[i].name, *def_bvalue, i, offset);
807                   bvalue = (bool *)((char *)job + offset);
808                   *bvalue = *def_bvalue;
809                   set_bit(i, job->hdr.item_present);
810                }
811             }
812          }
813       }
814       /*
815        * Ensure that all required items are present
816        */
817       for (i=0; job_items[i].name; i++) {
818          if (job_items[i].flags & ITEM_REQUIRED) {
819                if (!bit_is_set(i, job->hdr.item_present)) {
820                   Jmsg(NULL, M_ERROR_TERM, 0, _("\"%s\" directive in Job \"%s\" resource is required, but not found.\n"),
821                     job_items[i].name, job->name());
822                   OK = false;
823                 }
824          }
825          /* If this triggers, take a look at lib/parse_conf.h */
826          if (i >= MAX_RES_ITEMS) {
827             Emsg0(M_ERROR_TERM, 0, _("Too many items in Job resource\n"));
828          }
829       }
830       if (!job->storage && !job->pool->storage) {
831          Jmsg(NULL, M_FATAL, 0, _("No storage specified in Job \"%s\" nor in Pool.\n"),
832             job->name());
833          OK = false;
834       }
835    } /* End loop over Job res */
836
837
838    /* Loop over Consoles */
839    CONRES *cons;
840    foreach_res(cons, R_CONSOLE) {
841       /* tls_require implies tls_enable */
842       if (cons->tls_require) {
843          if (have_tls) {
844             cons->tls_enable = true;
845          } else {
846             Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
847             OK = false;
848             continue;
849          }
850       }
851
852       need_tls = cons->tls_enable || cons->tls_authenticate;
853
854       if (!cons->tls_certfile && need_tls) {
855          Jmsg(NULL, M_FATAL, 0, _("\"TLS Certificate\" file not defined for Console \"%s\" in %s.\n"),
856             cons->name(), configfile);
857          OK = false;
858       }
859
860       if (!cons->tls_keyfile && need_tls) {
861          Jmsg(NULL, M_FATAL, 0, _("\"TLS Key\" file not defined for Console \"%s\" in %s.\n"),
862             cons->name(), configfile);
863          OK = false;
864       }
865
866       if ((!cons->tls_ca_certfile && !cons->tls_ca_certdir)
867             && need_tls && cons->tls_verify_peer) {
868          Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\" or \"TLS CA"
869             " Certificate Dir\" are defined for Console \"%s\" in %s."
870             " At least one CA certificate store is required"
871             " when using \"TLS Verify Peer\".\n"),
872             cons->name(), configfile);
873          OK = false;
874       }
875       /* If everything is well, attempt to initialize our per-resource TLS context */
876       if (OK && (need_tls || cons->tls_require)) {
877          /* Initialize TLS context:
878           * Args: CA certfile, CA certdir, Certfile, Keyfile,
879           * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
880          cons->tls_ctx = new_tls_context(cons->tls_ca_certfile,
881             cons->tls_ca_certdir, cons->tls_certfile,
882             cons->tls_keyfile, NULL, NULL, cons->tls_dhfile, cons->tls_verify_peer);
883
884          if (!cons->tls_ctx) {
885             Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for File daemon \"%s\" in %s.\n"),
886                cons->name(), configfile);
887             OK = false;
888          }
889       }
890
891    }
892
893    /* Loop over Clients */
894    CLIENT *client;
895    foreach_res(client, R_CLIENT) {
896       /* tls_require implies tls_enable */
897       if (client->tls_require) {
898          if (have_tls) {
899             client->tls_enable = true;
900          } else {
901             Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
902             OK = false;
903             continue;
904          }
905       }
906       need_tls = client->tls_enable || client->tls_authenticate;
907       if ((!client->tls_ca_certfile && !client->tls_ca_certdir) && need_tls) {
908          Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\""
909             " or \"TLS CA Certificate Dir\" are defined for File daemon \"%s\" in %s.\n"),
910             client->name(), configfile);
911          OK = false;
912       }
913
914       /* If everything is well, attempt to initialize our per-resource TLS context */
915       if (OK && (need_tls || client->tls_require)) {
916          /* Initialize TLS context:
917           * Args: CA certfile, CA certdir, Certfile, Keyfile,
918           * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
919          client->tls_ctx = new_tls_context(client->tls_ca_certfile,
920             client->tls_ca_certdir, client->tls_certfile,
921             client->tls_keyfile, NULL, NULL, NULL,
922             true);
923
924          if (!client->tls_ctx) {
925             Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for File daemon \"%s\" in %s.\n"),
926                client->name(), configfile);
927             OK = false;
928          }
929       }
930    }
931
932    UnlockRes();
933    if (OK) {
934       close_msg(NULL);                /* close temp message handler */
935       init_msg(NULL, director->messages); /* open daemon message handler */
936       last_reload_time = time(NULL);
937    }
938    return OK;
939 }
940
941 /*
942  * In this routine,
943  *  - we can check the connection (mode=CHECK_CONNECTION)
944  *  - we can synchronize the catalog with the configuration (mode=UPDATE_CATALOG)
945  *  - we can synchronize, and fix old job records (mode=UPDATE_AND_FIX)
946  */
947 static bool check_catalog(cat_op mode)
948 {
949    bool OK = true;
950    bool need_tls;
951
952    /* Loop over databases */
953    CAT *catalog;
954    foreach_res(catalog, R_CATALOG) {
955       BDB *db;
956       /*
957        * Make sure we can open catalog, otherwise print a warning
958        * message because the server is probably not running.
959        */
960       db = db_init_database(NULL, catalog->db_driver, catalog->db_name, 
961               catalog->db_user,
962               catalog->db_password, catalog->db_address,
963               catalog->db_port, catalog->db_socket,
964               catalog->mult_db_connections,
965               catalog->disable_batch_insert);
966       if (!db || !db_open_database(NULL, db)) {
967          Pmsg2(000, _("Could not open Catalog \"%s\", database \"%s\".\n"),
968               catalog->name(), catalog->db_name);
969          Jmsg(NULL, M_FATAL, 0, _("Could not open Catalog \"%s\", database \"%s\".\n"),
970               catalog->name(), catalog->db_name);
971          if (db) {
972             Jmsg(NULL, M_FATAL, 0, _("%s"), db_strerror(db));
973             Pmsg1(000, "%s", db_strerror(db));
974             db_close_database(NULL, db);
975          }
976          OK = false;
977          continue;
978       }
979
980       /* Display a message if the db max_connections is too low */
981       if (!db_check_max_connections(NULL, db, director->MaxConcurrentJobs)) {
982          Pmsg1(000, "Warning, settings problem for Catalog=%s\n", catalog->name());
983          Pmsg1(000, "%s", db_strerror(db));
984       }
985
986       /* we are in testing mode, so don't touch anything in the catalog */
987       if (mode == CHECK_CONNECTION) {
988          if (db) db_close_database(NULL, db);
989          continue;
990       }
991
992       /* Loop over all pools, defining/updating them in each database */
993       POOL *pool;
994       foreach_res(pool, R_POOL) {
995          /*
996           * If the Pool has a catalog resource create the pool only
997           *   in that catalog.
998           */
999          if (!pool->catalog || pool->catalog == catalog) {
1000             create_pool(NULL, db, pool, POOL_OP_UPDATE);  /* update request */
1001          }
1002       }
1003
1004       /* Once they are created, we can loop over them again, updating
1005        * references (RecyclePool)
1006        */
1007       foreach_res(pool, R_POOL) {
1008          /*
1009           * If the Pool has a catalog resource update the pool only
1010           *   in that catalog.
1011           */
1012          if (!pool->catalog || pool->catalog == catalog) {
1013             update_pool_references(NULL, db, pool);
1014          }
1015       }
1016
1017       /* Ensure basic client record is in DB */
1018       CLIENT *client;
1019       foreach_res(client, R_CLIENT) {
1020          CLIENT_DBR cr;
1021          /* Create clients only if they use the current catalog */
1022          if (client->catalog != catalog) {
1023             Dmsg3(500, "Skip client=%s with cat=%s not catalog=%s\n",
1024                   client->name(), client->catalog->name(), catalog->name());
1025             continue;
1026          }
1027          Dmsg2(500, "create cat=%s for client=%s\n",
1028                client->catalog->name(), client->name());
1029          memset(&cr, 0, sizeof(cr));
1030          bstrncpy(cr.Name, client->name(), sizeof(cr.Name));
1031
1032          db_create_client_record(NULL, db, &cr);
1033       }
1034
1035       /* Ensure basic storage record is in DB */
1036       STORE *store;
1037       foreach_res(store, R_STORAGE) {
1038          STORAGE_DBR sr;
1039          MEDIATYPE_DBR mtr;
1040          memset(&sr, 0, sizeof(sr));
1041          memset(&mtr, 0, sizeof(mtr));
1042          if (store->media_type) {
1043             bstrncpy(mtr.MediaType, store->media_type, sizeof(mtr.MediaType));
1044             mtr.ReadOnly = 0;
1045             db_create_mediatype_record(NULL, db, &mtr);
1046          } else {
1047             mtr.MediaTypeId = 0;
1048          }
1049          bstrncpy(sr.Name, store->name(), sizeof(sr.Name));
1050          sr.AutoChanger = store->autochanger;
1051          if (!db_create_storage_record(NULL, db, &sr)) {
1052             Jmsg(NULL, M_FATAL, 0, _("Could not create storage record for %s\n"),
1053                  store->name());
1054             OK = false;
1055          }
1056          store->StorageId = sr.StorageId;   /* set storage Id */
1057          if (!sr.created) {                 /* if not created, update it */
1058             sr.AutoChanger = store->autochanger;
1059             if (!db_update_storage_record(NULL, db, &sr)) {
1060                Jmsg(NULL, M_FATAL, 0, _("Could not update storage record for %s\n"),
1061                     store->name());
1062                OK = false;
1063             }
1064          }
1065
1066          /* tls_require implies tls_enable */
1067          if (store->tls_require) {
1068             if (have_tls) {
1069                store->tls_enable = true;
1070             } else {
1071                Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
1072                OK = false;
1073             }
1074          }
1075
1076          need_tls = store->tls_enable || store->tls_authenticate;
1077
1078          if ((!store->tls_ca_certfile && !store->tls_ca_certdir) && need_tls) {
1079             Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\""
1080                  " or \"TLS CA Certificate Dir\" are defined for Storage \"%s\" in %s.\n"),
1081                  store->name(), configfile);
1082             OK = false;
1083          }
1084
1085          /* If everything is well, attempt to initialize our per-resource TLS context */
1086          if (OK && (need_tls || store->tls_require)) {
1087            /* Initialize TLS context:
1088             * Args: CA certfile, CA certdir, Certfile, Keyfile,
1089             * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
1090             store->tls_ctx = new_tls_context(store->tls_ca_certfile,
1091                store->tls_ca_certdir, store->tls_certfile,
1092                store->tls_keyfile, NULL, NULL, NULL, true);
1093
1094             if (!store->tls_ctx) {
1095                Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for Storage \"%s\" in %s.\n"),
1096                     store->name(), configfile);
1097                OK = false;
1098             }
1099          }
1100       }
1101
1102       /* Loop over all counters, defining them in each database */
1103       /* Set default value in all counters */
1104       COUNTER *counter;
1105       foreach_res(counter, R_COUNTER) {
1106          /* Write to catalog? */
1107          if (!counter->created && counter->Catalog == catalog) {
1108             COUNTER_DBR cr;
1109             bstrncpy(cr.Counter, counter->name(), sizeof(cr.Counter));
1110             cr.MinValue = counter->MinValue;
1111             cr.MaxValue = counter->MaxValue;
1112             cr.CurrentValue = counter->MinValue;
1113             if (counter->WrapCounter) {
1114                bstrncpy(cr.WrapCounter, counter->WrapCounter->name(), sizeof(cr.WrapCounter));
1115             } else {
1116                cr.WrapCounter[0] = 0;  /* empty string */
1117             }
1118             if (db_create_counter_record(NULL, db, &cr)) {
1119                counter->CurrentValue = cr.CurrentValue;
1120                counter->created = true;
1121                Dmsg2(100, "Create counter %s val=%d\n", counter->name(), counter->CurrentValue);
1122             }
1123          }
1124          if (!counter->created) {
1125             counter->CurrentValue = counter->MinValue;  /* default value */
1126          }
1127       }
1128       /* cleanup old job records */
1129       if (mode == UPDATE_AND_FIX) {
1130          db_sql_query(db, cleanup_created_job, NULL, NULL);
1131          db_sql_query(db, cleanup_running_job, NULL, NULL);
1132       }
1133
1134       /* Set SQL engine name in global for debugging */
1135       set_db_engine_name(db_get_engine_name(db));
1136       if (db) db_close_database(NULL, db);
1137    }
1138    return OK;
1139 }
1140
1141 static void cleanup_old_files()
1142 {
1143    DIR* dp;
1144    struct dirent *entry, *result;
1145    int rc, name_max;
1146    int my_name_len = strlen(my_name);
1147    int len = strlen(director->working_directory);
1148    POOLMEM *cleanup = get_pool_memory(PM_MESSAGE);
1149    POOLMEM *basename = get_pool_memory(PM_MESSAGE);
1150    regex_t preg1;
1151    char prbuf[500];
1152    const int nmatch = 30;
1153    regmatch_t pmatch[nmatch];
1154    berrno be;
1155
1156    /* Exclude spaces and look for .mail, .tmp or .restore.xx.bsr files */
1157    const char *pat1 = "^[^ ]+\\.(restore\\.[^ ]+\\.bsr|mail|tmp)$";
1158
1159    /* Setup working directory prefix */
1160    pm_strcpy(basename, director->working_directory);
1161    if (len > 0 && !IsPathSeparator(director->working_directory[len-1])) {
1162       pm_strcat(basename, "/");
1163    }
1164
1165    /* Compile regex expressions */
1166    rc = regcomp(&preg1, pat1, REG_EXTENDED);
1167    if (rc != 0) {
1168       regerror(rc, &preg1, prbuf, sizeof(prbuf));
1169       Pmsg2(000,  _("Could not compile regex pattern \"%s\" ERR=%s\n"),
1170            pat1, prbuf);
1171       goto get_out2;
1172    }
1173
1174    name_max = pathconf(".", _PC_NAME_MAX);
1175    if (name_max < 1024) {
1176       name_max = 1024;
1177    }
1178
1179    if (!(dp = opendir(director->working_directory))) {
1180       berrno be;
1181       Pmsg2(000, "Failed to open working dir %s for cleanup: ERR=%s\n",
1182             director->working_directory, be.bstrerror());
1183       goto get_out1;
1184       return;
1185    }
1186
1187    entry = (struct dirent *)malloc(sizeof(struct dirent) + name_max + 1000);
1188    while (1) {
1189       if ((readdir_r(dp, entry, &result) != 0) || (result == NULL)) {
1190          break;
1191       }
1192       /* Exclude any name with ., .., not my_name or containing a space */
1193       if (strcmp(result->d_name, ".") == 0 || strcmp(result->d_name, "..") == 0 ||
1194           strncmp(result->d_name, my_name, my_name_len) != 0) {
1195          Dmsg1(500, "Skipped: %s\n", result->d_name);
1196          continue;
1197       }
1198
1199       /* Unlink files that match regexes */
1200       if (regexec(&preg1, result->d_name, nmatch, pmatch,  0) == 0) {
1201          pm_strcpy(cleanup, basename);
1202          pm_strcat(cleanup, result->d_name);
1203          Dmsg1(100, "Unlink: %s\n", cleanup);
1204          unlink(cleanup);
1205       }
1206    }
1207
1208    free(entry);
1209    closedir(dp);
1210 /* Be careful to free up the correct resources */
1211 get_out1:
1212    regfree(&preg1);
1213 get_out2:
1214    free_pool_memory(cleanup);
1215    free_pool_memory(basename);
1216 }