]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/dird.c
ebl Fix bug on RunBefore
[bacula/bacula] / bacula / src / dird / dird.c
1 /*
2  *
3  *   Bacula Director daemon -- this is the main program
4  *
5  *     Kern Sibbald, March MM
6  *
7  *   Version $Id$
8  */
9 /*
10    Copyright (C) 2000-2006 Kern Sibbald
11
12    This program is free software; you can redistribute it and/or
13    modify it under the terms of the GNU General Public License
14    version 2 as amended with additional clauses defined in the
15    file LICENSE in the main source directory.
16
17    This program is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
20    the file LICENSE for additional details.
21
22  */
23
24 #include "bacula.h"
25 #include "dird.h"
26
27 /* Forward referenced subroutines */
28 void terminate_dird(int sig);
29 static int check_resources();
30 static void dir_sql_query(JCR *jcr, const char *cmd);
31   
32 /* Exported subroutines */
33 extern "C" void reload_config(int sig);
34 extern void invalidate_schedules();
35
36
37 /* Imported subroutines */
38 JCR *wait_for_next_job(char *runjob);
39 void term_scheduler();
40 void term_ua_server();
41 void start_UA_server(dlist *addrs);
42 void init_job_server(int max_workers);
43 void term_job_server();
44 void store_jobtype(LEX *lc, RES_ITEM *item, int index, int pass);
45 void store_level(LEX *lc, RES_ITEM *item, int index, int pass);
46 void store_replace(LEX *lc, RES_ITEM *item, int index, int pass);
47 void init_device_resources();
48
49 static char *runjob = NULL;
50 static int background = 1;
51 static void init_reload(void);
52
53 /* Globals Exported */
54 DIRRES *director;                     /* Director resource */
55 int FDConnectTimeout;
56 int SDConnectTimeout;
57 char *configfile = NULL;
58
59 /* Globals Imported */
60 extern int r_first, r_last;           /* first and last resources */
61 extern RES_TABLE resources[];
62 extern RES **res_head;
63 extern RES_ITEM job_items[];
64
65 #if defined(_MSC_VER)
66 extern "C" { // work around visual compiler mangling variables
67     extern URES res_all;
68 }
69 #else
70 extern URES res_all;
71 #endif
72
73 #define CONFIG_FILE "./bacula-dir.conf" /* default configuration file */
74
75 static void usage()
76 {
77    fprintf(stderr, _(
78 "Copyright (C) 2000-%s Kern Sibbald.\n"
79 "\nVersion: %s (%s)\n\n"
80 "Usage: dird [-f -s] [-c config_file] [-d debug_level] [config_file]\n"
81 "       -c <file>   set configuration file to file\n"
82 "       -dnn        set debug level to nn\n"
83 "       -f          run in foreground (for debugging)\n"
84 "       -g          groupid\n"
85 "       -r <job>    run <job> now\n"
86 "       -s          no signals\n"
87 "       -t          test - read configuration and exit\n"
88 "       -u          userid\n"
89 "       -v          verbose user messages\n"
90 "       -?          print this message.\n"
91 "\n"), BYEAR, VERSION, BDATE);
92
93    exit(1);
94 }
95
96
97 /*********************************************************************
98  *
99  *         Main Bacula Server program
100  *
101  */
102 #if defined(HAVE_WIN32)
103 #define main BaculaMain
104 #endif
105
106 int main (int argc, char *argv[])
107 {
108    int ch;
109    JCR *jcr;
110    int no_signals = FALSE;
111    int test_config = FALSE;
112    char *uid = NULL;
113    char *gid = NULL;
114
115    setlocale(LC_ALL, "");
116    bindtextdomain("bacula", LOCALEDIR);
117    textdomain("bacula");
118
119    init_stack_dump();
120    my_name_is(argc, argv, "bacula-dir");
121    init_msg(NULL, NULL);              /* initialize message handler */
122    init_reload();
123    daemon_start_time = time(NULL);
124
125    while ((ch = getopt(argc, argv, "c:d:fg:r:stu:v?")) != -1) {
126       switch (ch) {
127       case 'c':                    /* specify config file */
128          if (configfile != NULL) {
129             free(configfile);
130          }
131          configfile = bstrdup(optarg);
132          break;
133
134       case 'd':                    /* set debug level */
135          debug_level = atoi(optarg);
136          if (debug_level <= 0) {
137             debug_level = 1;
138          }
139          Dmsg1(0, "Debug level = %d\n", debug_level);
140          break;
141
142       case 'f':                    /* run in foreground */
143          background = FALSE;
144          break;
145
146       case 'g':                    /* set group id */
147          gid = optarg;
148          break;
149
150       case 'r':                    /* run job */
151          if (runjob != NULL) {
152             free(runjob);
153          }
154          if (optarg) {
155             runjob = bstrdup(optarg);
156          }
157          break;
158
159       case 's':                    /* turn off signals */
160          no_signals = TRUE;
161          break;
162
163       case 't':                    /* test config */
164          test_config = TRUE;
165          break;
166
167       case 'u':                    /* set uid */
168          uid = optarg;
169          break;
170
171       case 'v':                    /* verbose */
172          verbose++;
173          break;
174
175       case '?':
176       default:
177          usage();
178
179       }
180    }
181    argc -= optind;
182    argv += optind;
183
184    if (!no_signals) {
185       init_signals(terminate_dird);
186    }
187
188    if (argc) {
189       if (configfile != NULL) {
190          free(configfile);
191       }
192       configfile = bstrdup(*argv);
193       argc--;
194       argv++;
195    }
196    if (argc) {
197       usage();
198    }
199
200    if (configfile == NULL) {
201       configfile = bstrdup(CONFIG_FILE);
202    }
203
204    parse_config(configfile);
205
206    if (init_crypto() != 0) {
207       Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Cryptography library initialization failed.\n"));
208    }
209
210    if (!check_resources()) {
211       Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
212    }
213
214    if (test_config) {
215       terminate_dird(0);
216    }
217
218    my_name_is(0, NULL, director->hdr.name);    /* set user defined name */
219
220    /* Plug database interface for library routines */
221    p_sql_query = (sql_query)dir_sql_query;                                   
222
223    FDConnectTimeout = (int)director->FDConnectTimeout;
224    SDConnectTimeout = (int)director->SDConnectTimeout;
225
226    if (background) {
227       daemon_start();
228       init_stack_dump();              /* grab new pid */
229    }
230
231    /* Create pid must come after we are a daemon -- so we have our final pid */
232    create_pid_file(director->pid_directory, "bacula-dir", get_first_port_host_order(director->DIRaddrs));
233    read_state_file(director->working_directory, "bacula-dir", get_first_port_host_order(director->DIRaddrs));
234
235    drop(uid, gid);                    /* reduce priveleges if requested */
236
237 #if !defined(HAVE_WIN32)
238    signal(SIGHUP, reload_config);
239 #endif
240
241    init_console_msg(working_directory);
242
243    init_python_interpreter(director->hdr.name, director->scripts_directory, 
244        "DirStartUp");
245
246    set_thread_concurrency(director->MaxConcurrentJobs * 2 +
247       4 /* UA */ + 4 /* sched+watchdog+jobsvr+misc */);
248
249    Dmsg0(200, "Start UA server\n");
250    start_UA_server(director->DIRaddrs);
251
252    start_watchdog();                  /* start network watchdog thread */
253
254    init_jcr_subsystem();              /* start JCR watchdogs etc. */
255
256    init_job_server(director->MaxConcurrentJobs);
257
258    Dmsg0(200, "wait for next job\n");
259    /* Main loop -- call scheduler to get next job to run */
260    while ( (jcr = wait_for_next_job(runjob)) ) {
261       run_job(jcr);                   /* run job */
262       free_jcr(jcr);                  /* release jcr */
263       if (runjob) {                   /* command line, run a single job? */
264          break;                       /* yes, terminate */
265       }
266    }
267
268    terminate_dird(0);
269
270    return 0;
271 }
272
273 static void dir_sql_query(JCR *jcr, const char *cmd)
274 {
275    if (!jcr || !jcr->db) {
276       return;
277    }
278    db_sql_query(jcr->db, cmd, NULL, NULL);
279 }
280
281 /* Cleanup and then exit */
282 void terminate_dird(int sig)
283 {
284    static bool already_here = false;
285
286    if (already_here) {                /* avoid recursive temination problems */
287       exit(1);
288    }
289    already_here = true;
290    generate_daemon_event(NULL, "Exit");
291    write_state_file(director->working_directory, "bacula-dir", get_first_port_host_order(director->DIRaddrs));
292    delete_pid_file(director->pid_directory, "bacula-dir", get_first_port_host_order(director->DIRaddrs));
293 // signal(SIGCHLD, SIG_IGN);          /* don't worry about children now */
294    term_scheduler();
295    term_job_server();
296    if (runjob) {
297       free(runjob);
298    }
299    if (configfile != NULL) {
300       free(configfile);
301    }
302    if (debug_level > 5) {
303       print_memory_pool_stats();
304    }
305    free_config_resources();
306    term_ua_server();
307    term_msg();                        /* terminate message handler */
308    stop_watchdog();
309    cleanup_crypto();
310    close_memory_pool();               /* release free memory in pool */
311    sm_dump(false);
312    exit(sig);
313 }
314
315 struct RELOAD_TABLE {
316    int job_count;
317    RES **res_table;
318 };
319
320 static const int max_reloads = 32;
321 static RELOAD_TABLE reload_table[max_reloads];
322
323 static void init_reload(void)
324 {
325    for (int i=0; i < max_reloads; i++) {
326       reload_table[i].job_count = 0;
327       reload_table[i].res_table = NULL;
328    }
329 }
330
331 static void free_saved_resources(int table)
332 {
333    int num = r_last - r_first + 1;
334    RES **res_tab = reload_table[table].res_table;
335    if (!res_tab) {
336       Dmsg1(100, "res_tab for table %d already released.\n", table);
337       return;
338    }
339    Dmsg1(100, "Freeing resources for table %d\n", table);
340    for (int j=0; j<num; j++) {
341       free_resource(res_tab[j], r_first + j);
342    }
343    free(res_tab);
344    reload_table[table].job_count = 0;
345    reload_table[table].res_table = NULL;
346 }
347
348 /*
349  * Called here at the end of every job that was
350  * hooked decrementing the active job_count. When
351  * it goes to zero, no one is using the associated
352  * resource table, so free it.
353  */
354 static void reload_job_end_cb(JCR *jcr, void *ctx)
355 {
356    int reload_id = (int)((long int)ctx);
357    Dmsg3(100, "reload job_end JobId=%d table=%d cnt=%d\n", jcr->JobId,
358       reload_id, reload_table[reload_id].job_count);
359    lock_jobs();
360    LockRes();
361    if (--reload_table[reload_id].job_count <= 0) {
362       free_saved_resources(reload_id);
363    }
364    UnlockRes();
365    unlock_jobs();
366 }
367
368 static int find_free_reload_table_entry()
369 {
370    int table = -1;
371    for (int i=0; i < max_reloads; i++) {
372       if (reload_table[i].res_table == NULL) {
373          table = i;
374          break;
375       }
376    }
377    return table;
378 }
379
380 /*
381  * If we get here, we have received a SIGHUP, which means to
382  *    reread our configuration file.
383  *
384  * The algorithm used is as follows: we count how many jobs are
385  *   running and mark the running jobs to make a callback on
386  *   exiting. The old config is saved with the reload table
387  *   id in a reload table. The new config file is read. Now, as
388  *   each job exits, it calls back to the reload_job_end_cb(), which
389  *   decrements the count of open jobs for the given reload table.
390  *   When the count goes to zero, we release those resources.
391  *   This allows us to have pointers into the resource table (from
392  *   jobs), and once they exit and all the pointers are released, we
393  *   release the old table. Note, if no new jobs are running since the
394  *   last reload, then the old resources will be immediately release.
395  *   A console is considered a job because it may have pointers to
396  *   resources, but a SYSTEM job is not since it *should* not have any
397  *   permanent pointers to jobs.
398  */
399 extern "C"
400 void reload_config(int sig)
401 {
402    static bool already_here = false;
403 #if !defined(HAVE_WIN32)
404    sigset_t set;
405 #endif
406    JCR *jcr;
407    int njobs = 0;                     /* number of running jobs */
408    int table, rtable;
409    bool ok;       
410
411    if (already_here) {
412       abort();                        /* Oops, recursion -> die */
413    }
414    already_here = true;
415
416 #if !defined(HAVE_WIN32)
417    sigemptyset(&set);
418    sigaddset(&set, SIGHUP);
419    sigprocmask(SIG_BLOCK, &set, NULL);
420 #endif
421
422    lock_jobs();
423    LockRes();
424
425    table = find_free_reload_table_entry();
426    if (table < 0) {
427       Jmsg(NULL, M_ERROR, 0, _("Too many open reload requests. Request ignored.\n"));
428       goto bail_out;
429    }
430
431    Dmsg1(100, "Reload_config njobs=%d\n", njobs);
432    reload_table[table].res_table = save_config_resources();
433    Dmsg1(100, "Saved old config in table %d\n", table);
434
435    ok = parse_config(configfile, 0, M_ERROR);  /* no exit on error */
436
437    Dmsg0(100, "Reloaded config file\n");
438    if (!ok || !check_resources()) {
439       rtable = find_free_reload_table_entry();    /* save new, bad table */
440       if (rtable < 0) {
441          Jmsg(NULL, M_ERROR, 0, _("Please correct configuration file: %s\n"), configfile);
442          Jmsg(NULL, M_ERROR_TERM, 0, _("Out of reload table entries. Giving up.\n"));
443       } else {
444          Jmsg(NULL, M_ERROR, 0, _("Please correct configuration file: %s\n"), configfile);
445          Jmsg(NULL, M_ERROR, 0, _("Resetting previous configuration.\n"));
446       }
447       reload_table[rtable].res_table = save_config_resources();
448       /* Now restore old resoure values */
449       int num = r_last - r_first + 1;
450       RES **res_tab = reload_table[table].res_table;
451       for (int i=0; i<num; i++) {
452          res_head[i] = res_tab[i];
453       }
454       table = rtable;                 /* release new, bad, saved table below */
455    } else {
456       invalidate_schedules();
457       /*
458        * Hook all active jobs so that they release this table
459        */
460       foreach_jcr(jcr) {
461          if (jcr->JobType != JT_SYSTEM) {
462             reload_table[table].job_count++;
463             job_end_push(jcr, reload_job_end_cb, (void *)((long int)table));
464             njobs++;
465          }
466       }
467       endeach_jcr(jcr);
468    }
469
470    /* Reset globals */
471    set_working_directory(director->working_directory);
472    FDConnectTimeout = director->FDConnectTimeout;
473    SDConnectTimeout = director->SDConnectTimeout;
474    Dmsg0(0, "Director's configuration file reread.\n");
475
476    /* Now release saved resources, if no jobs using the resources */
477    if (njobs == 0) {
478       free_saved_resources(table);
479    }
480
481 bail_out:
482    UnlockRes();
483    unlock_jobs();
484 #if !defined(HAVE_WIN32)
485    sigprocmask(SIG_UNBLOCK, &set, NULL);
486    signal(SIGHUP, reload_config);
487 #endif
488    already_here = false;
489 }
490
491 /*
492  * Make a quick check to see that we have all the
493  * resources needed.
494  *
495  *  **** FIXME **** this routine could be a lot more
496  *   intelligent and comprehensive.
497  */
498 static int check_resources()
499 {
500    bool OK = true;
501    JOB *job;
502
503    LockRes();
504
505    job = (JOB *)GetNextRes(R_JOB, NULL);
506    director = (DIRRES *)GetNextRes(R_DIRECTOR, NULL);
507    if (!director) {
508       Jmsg(NULL, M_FATAL, 0, _("No Director resource defined in %s\n"
509 "Without that I don't know who I am :-(\n"), configfile);
510       OK = false;
511    } else {
512       set_working_directory(director->working_directory);
513       if (!director->messages) {       /* If message resource not specified */
514          director->messages = (MSGS *)GetNextRes(R_MSGS, NULL);
515          if (!director->messages) {
516             Jmsg(NULL, M_FATAL, 0, _("No Messages resource defined in %s\n"), configfile);
517             OK = false;
518          }
519       }
520       if (GetNextRes(R_DIRECTOR, (RES *)director) != NULL) {
521          Jmsg(NULL, M_FATAL, 0, _("Only one Director resource permitted in %s\n"),
522             configfile);
523          OK = false;
524       }
525       /* tls_require implies tls_enable */
526       if (director->tls_require) {
527          if (have_tls) {
528             director->tls_enable = true;
529          } else {
530             Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
531             OK = false;
532          }
533       }
534
535       if (!director->tls_certfile && director->tls_enable) {
536          Jmsg(NULL, M_FATAL, 0, _("\"TLS Certificate\" file not defined for Director \"%s\" in %s.\n"),
537             director->hdr.name, configfile);
538          OK = false;
539       }
540
541       if (!director->tls_keyfile && director->tls_enable) {
542          Jmsg(NULL, M_FATAL, 0, _("\"TLS Key\" file not defined for Director \"%s\" in %s.\n"),
543             director->hdr.name, configfile);
544          OK = false;
545       }
546
547       if ((!director->tls_ca_certfile && !director->tls_ca_certdir) && director->tls_enable && director->tls_verify_peer) {
548          Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\" or \"TLS CA"
549               " Certificate Dir\" are defined for Director \"%s\" in %s."
550               " At least one CA certificate store is required"
551               " when using \"TLS Verify Peer\".\n"),
552               director->hdr.name, configfile);
553          OK = false;
554       }
555
556       /* If everything is well, attempt to initialize our per-resource TLS context */
557       if (OK && (director->tls_enable || director->tls_require)) {
558          /* Initialize TLS context:
559           * Args: CA certfile, CA certdir, Certfile, Keyfile,
560           * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
561          director->tls_ctx = new_tls_context(director->tls_ca_certfile,
562             director->tls_ca_certdir, director->tls_certfile,
563             director->tls_keyfile, NULL, NULL, director->tls_dhfile,
564             director->tls_verify_peer);
565          
566          if (!director->tls_ctx) {
567             Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for Director \"%s\" in %s.\n"),
568                  director->hdr.name, configfile);
569             OK = false;
570          }
571       }
572    }
573
574    if (!job) {
575       Jmsg(NULL, M_FATAL, 0, _("No Job records defined in %s\n"), configfile);
576       OK = false;
577    }
578    foreach_res(job, R_JOB) {
579       int i;
580
581       if (job->jobdefs) {
582          /* Handle Storage alists specifically */
583          JOB *jobdefs = job->jobdefs;
584          if (jobdefs->storage && !job->storage) {
585             STORE *st;
586             job->storage = New(alist(10, not_owned_by_alist));
587             foreach_alist(st, jobdefs->storage) {
588                job->storage->append(st);
589             }
590          }
591          /* Handle RunScripts alists specifically */
592          if (jobdefs->RunScripts) {
593             RUNSCRIPT *rs, *elt;
594             
595             if (!job->RunScripts) {
596                job->RunScripts = New(alist(10, not_owned_by_alist));
597             }
598            
599             foreach_alist(rs, jobdefs->RunScripts) {
600                elt = copy_runscript(rs);
601                job->RunScripts->append(elt); /* we have to free it */
602             }
603          }
604
605          /* Transfer default items from JobDefs Resource */
606          for (i=0; job_items[i].name; i++) {
607             char **def_svalue, **svalue;  /* string value */
608             int *def_ivalue, *ivalue;     /* integer value */
609             bool *def_bvalue, *bvalue;    /* bool value */
610             int64_t *def_lvalue, *lvalue; /* 64 bit values */
611             uint32_t offset;
612
613             Dmsg4(1400, "Job \"%s\", field \"%s\" bit=%d def=%d\n",
614                 job->hdr.name, job_items[i].name,
615                 bit_is_set(i, job->hdr.item_present),
616                 bit_is_set(i, job->jobdefs->hdr.item_present));
617
618             if (!bit_is_set(i, job->hdr.item_present) &&
619                  bit_is_set(i, job->jobdefs->hdr.item_present)) {
620                Dmsg2(400, "Job \"%s\", field \"%s\": getting default.\n",
621                  job->hdr.name, job_items[i].name);
622                offset = (char *)(job_items[i].value) - (char *)&res_all;
623                /*
624                 * Handle strings and directory strings
625                 */
626                if (job_items[i].handler == store_str ||
627                    job_items[i].handler == store_dir) {
628                   def_svalue = (char **)((char *)(job->jobdefs) + offset);
629                   Dmsg5(400, "Job \"%s\", field \"%s\" def_svalue=%s item %d offset=%u\n",
630                        job->hdr.name, job_items[i].name, *def_svalue, i, offset);
631                   svalue = (char **)((char *)job + offset);
632                   if (*svalue) {
633                      Pmsg1(000, _("Hey something is wrong. p=0x%lu\n"), *svalue);
634                   }
635                   *svalue = bstrdup(*def_svalue);
636                   set_bit(i, job->hdr.item_present);
637                /*
638                 * Handle resources
639                 */
640                } else if (job_items[i].handler == store_res) {
641                   def_svalue = (char **)((char *)(job->jobdefs) + offset);
642                   Dmsg4(400, "Job \"%s\", field \"%s\" item %d offset=%u\n",
643                        job->hdr.name, job_items[i].name, i, offset);
644                   svalue = (char **)((char *)job + offset);
645                   if (*svalue) {
646                      Pmsg1(000, _("Hey something is wrong. p=0x%lu\n"), *svalue);
647                   }
648                   *svalue = *def_svalue;
649                   set_bit(i, job->hdr.item_present);
650                /*
651                 * Handle alist resources
652                 */
653                } else if (job_items[i].handler == store_alist_res) {
654                   if (bit_is_set(i, job->jobdefs->hdr.item_present)) {
655                      set_bit(i, job->hdr.item_present);
656                   }
657                /*
658                 * Handle integer fields
659                 *    Note, our store_bit does not handle bitmaped fields
660                 */
661                } else if (job_items[i].handler == store_bit     ||
662                           job_items[i].handler == store_pint    ||
663                           job_items[i].handler == store_jobtype ||
664                           job_items[i].handler == store_level   ||
665                           job_items[i].handler == store_pint    ||
666                           job_items[i].handler == store_replace) {
667                   def_ivalue = (int *)((char *)(job->jobdefs) + offset);
668                   Dmsg5(400, "Job \"%s\", field \"%s\" def_ivalue=%d item %d offset=%u\n",
669                        job->hdr.name, job_items[i].name, *def_ivalue, i, offset);
670                   ivalue = (int *)((char *)job + offset);
671                   *ivalue = *def_ivalue;
672                   set_bit(i, job->hdr.item_present);
673                /*
674                 * Handle 64 bit integer fields
675                 */
676                } else if (job_items[i].handler == store_time   ||
677                           job_items[i].handler == store_size   ||
678                           job_items[i].handler == store_int64) {
679                   def_lvalue = (int64_t *)((char *)(job->jobdefs) + offset);
680                   Dmsg5(400, "Job \"%s\", field \"%s\" def_lvalue=%" lld " item %d offset=%u\n",
681                        job->hdr.name, job_items[i].name, *def_lvalue, i, offset);
682                   lvalue = (int64_t *)((char *)job + offset);
683                   *lvalue = *def_lvalue;
684                   set_bit(i, job->hdr.item_present);
685                /*
686                 * Handle bool fields
687                 */
688                } else if (job_items[i].handler == store_bool) {
689                   def_bvalue = (bool *)((char *)(job->jobdefs) + offset);
690                   Dmsg5(400, "Job \"%s\", field \"%s\" def_bvalue=%d item %d offset=%u\n",
691                        job->hdr.name, job_items[i].name, *def_bvalue, i, offset);
692                   bvalue = (bool *)((char *)job + offset);
693                   *bvalue = *def_bvalue;
694                   set_bit(i, job->hdr.item_present);
695                }
696             }
697          }
698       }
699       /*
700        * Ensure that all required items are present
701        */
702       for (i=0; job_items[i].name; i++) {
703          if (job_items[i].flags & ITEM_REQUIRED) {
704                if (!bit_is_set(i, job->hdr.item_present)) {
705                   Jmsg(NULL, M_FATAL, 0, _("\"%s\" directive in Job \"%s\" resource is required, but not found.\n"),
706                     job_items[i].name, job->hdr.name);
707                   OK = false;
708                 }
709          }
710          /* If this triggers, take a look at lib/parse_conf.h */
711          if (i >= MAX_RES_ITEMS) {
712             Emsg0(M_ERROR_TERM, 0, _("Too many items in Job resource\n"));
713          }
714       }
715    } /* End loop over Job res */
716
717    /* Loop over databases */
718    CAT *catalog;
719    foreach_res(catalog, R_CATALOG) {
720       B_DB *db;
721       /*
722        * Make sure we can open catalog, otherwise print a warning
723        * message because the server is probably not running.
724        */
725       db = db_init_database(NULL, catalog->db_name, catalog->db_user,
726                          catalog->db_password, catalog->db_address,
727                          catalog->db_port, catalog->db_socket,
728                          catalog->mult_db_connections);
729       if (!db || !db_open_database(NULL, db)) {
730          Jmsg(NULL, M_FATAL, 0, _("Could not open Catalog \"%s\", database \"%s\".\n"),
731               catalog->hdr.name, catalog->db_name);
732          if (db) {
733             Jmsg(NULL, M_FATAL, 0, _("%s"), db_strerror(db));
734          }
735          OK = false;
736          continue;
737       }
738
739       /* Loop over all pools, defining/updating them in each database */
740       POOL *pool;
741       foreach_res(pool, R_POOL) {
742          create_pool(NULL, db, pool, POOL_OP_UPDATE);  /* update request */
743       }
744
745       STORE *store;
746       foreach_res(store, R_STORAGE) {
747          STORAGE_DBR sr;
748          MEDIATYPE_DBR mr;
749          if (store->media_type) {
750             bstrncpy(mr.MediaType, store->media_type, sizeof(mr.MediaType));
751             mr.ReadOnly = 0;
752             db_create_mediatype_record(NULL, db, &mr);
753          } else {
754             mr.MediaTypeId = 0;
755          }
756          bstrncpy(sr.Name, store->name(), sizeof(sr.Name));
757          sr.AutoChanger = store->autochanger;
758          db_create_storage_record(NULL, db, &sr);
759          store->StorageId = sr.StorageId;   /* set storage Id */
760          if (!sr.created) {                 /* if not created, update it */
761             db_update_storage_record(NULL, db, &sr);
762          }
763
764          /* tls_require implies tls_enable */
765          if (store->tls_require) {
766             if (have_tls) {
767                store->tls_enable = true;
768             } else {
769                Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
770                OK = false;
771             }
772          } 
773
774          if ((!store->tls_ca_certfile && !store->tls_ca_certdir) && store->tls_enable) {
775             Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\""
776                  " or \"TLS CA Certificate Dir\" are defined for Storage \"%s\" in %s.\n"),
777                  store->hdr.name, configfile);
778             OK = false;
779          }
780
781          /* If everything is well, attempt to initialize our per-resource TLS context */
782          if (OK && (store->tls_enable || store->tls_require)) {
783            /* Initialize TLS context:
784             * Args: CA certfile, CA certdir, Certfile, Keyfile,
785             * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
786             store->tls_ctx = new_tls_context(store->tls_ca_certfile,
787                store->tls_ca_certdir, store->tls_certfile,
788                store->tls_keyfile, NULL, NULL, NULL, true);
789          
790             if (!store->tls_ctx) {
791                Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for Storage \"%s\" in %s.\n"),
792                     store->hdr.name, configfile);
793                OK = false;
794             }
795          }
796       }
797
798       /* Loop over all counters, defining them in each database */
799       /* Set default value in all counters */
800       COUNTER *counter;
801       foreach_res(counter, R_COUNTER) {
802          /* Write to catalog? */
803          if (!counter->created && counter->Catalog == catalog) {
804             COUNTER_DBR cr;
805             bstrncpy(cr.Counter, counter->hdr.name, sizeof(cr.Counter));
806             cr.MinValue = counter->MinValue;
807             cr.MaxValue = counter->MaxValue;
808             cr.CurrentValue = counter->MinValue;
809             if (counter->WrapCounter) {
810                bstrncpy(cr.WrapCounter, counter->WrapCounter->hdr.name, sizeof(cr.WrapCounter));
811             } else {
812                cr.WrapCounter[0] = 0;  /* empty string */
813             }
814             if (db_create_counter_record(NULL, db, &cr)) {
815                counter->CurrentValue = cr.CurrentValue;
816                counter->created = true;
817                Dmsg2(100, "Create counter %s val=%d\n", counter->hdr.name, counter->CurrentValue);
818             }
819          }
820          if (!counter->created) {
821             counter->CurrentValue = counter->MinValue;  /* default value */
822          }
823       }
824       db_close_database(NULL, db);
825    }
826
827    /* Loop over Consoles */
828    CONRES *cons;
829    foreach_res(cons, R_CONSOLE) {
830       /* tls_require implies tls_enable */
831       if (cons->tls_require) {
832          if (have_tls) {
833             cons->tls_enable = true;
834          } else {
835             Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
836             OK = false;
837             continue;
838          }
839       }
840
841       if (!cons->tls_certfile && cons->tls_enable) {
842          Jmsg(NULL, M_FATAL, 0, _("\"TLS Certificate\" file not defined for Console \"%s\" in %s.\n"),
843             cons->hdr.name, configfile);
844          OK = false;
845       }
846
847       if (!cons->tls_keyfile && cons->tls_enable) {
848          Jmsg(NULL, M_FATAL, 0, _("\"TLS Key\" file not defined for Console \"%s\" in %s.\n"),
849             cons->hdr.name, configfile);
850          OK = false;
851       }
852
853       if ((!cons->tls_ca_certfile && !cons->tls_ca_certdir) && cons->tls_enable && cons->tls_verify_peer) {
854          Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\" or \"TLS CA"
855             " Certificate Dir\" are defined for Console \"%s\" in %s."
856             " At least one CA certificate store is required"
857             " when using \"TLS Verify Peer\".\n"),
858             cons->hdr.name, configfile);
859          OK = false;
860       }
861       /* If everything is well, attempt to initialize our per-resource TLS context */
862       if (OK && (cons->tls_enable || cons->tls_require)) {
863          /* Initialize TLS context:
864           * Args: CA certfile, CA certdir, Certfile, Keyfile,
865           * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
866          cons->tls_ctx = new_tls_context(cons->tls_ca_certfile,
867             cons->tls_ca_certdir, cons->tls_certfile,
868             cons->tls_keyfile, NULL, NULL, cons->tls_dhfile, cons->tls_verify_peer);
869          
870          if (!cons->tls_ctx) {
871             Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for File daemon \"%s\" in %s.\n"),
872                cons->hdr.name, configfile);
873             OK = false;
874          }
875       }
876
877    }
878
879    /* Loop over Clients */
880    CLIENT *client;
881    foreach_res(client, R_CLIENT) {
882       /* tls_require implies tls_enable */
883       if (client->tls_require) {
884          if (have_tls) {
885             client->tls_enable = true;
886          } else {
887             Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
888             OK = false;
889             continue;
890          }
891       }
892
893       if ((!client->tls_ca_certfile && !client->tls_ca_certdir) && client->tls_enable) {
894          Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\""
895             " or \"TLS CA Certificate Dir\" are defined for File daemon \"%s\" in %s.\n"),
896             client->hdr.name, configfile);
897          OK = false;
898       }
899
900       /* If everything is well, attempt to initialize our per-resource TLS context */
901       if (OK && (client->tls_enable || client->tls_require)) {
902          /* Initialize TLS context:
903           * Args: CA certfile, CA certdir, Certfile, Keyfile,
904           * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
905          client->tls_ctx = new_tls_context(client->tls_ca_certfile,
906             client->tls_ca_certdir, client->tls_certfile,
907             client->tls_keyfile, NULL, NULL, NULL,
908             true);
909          
910          if (!client->tls_ctx) {
911             Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for File daemon \"%s\" in %s.\n"),
912                client->hdr.name, configfile);
913             OK = false;
914          }
915       }
916    }
917
918    UnlockRes();
919    if (OK) {
920       close_msg(NULL);                /* close temp message handler */
921       init_msg(NULL, director->messages); /* open daemon message handler */
922    }
923    return OK;
924 }