]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/dird.c
ebl add sql_escape to catalog messages
[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    p_sql_escape = (sql_escape)db_escape_string;
223
224    FDConnectTimeout = (int)director->FDConnectTimeout;
225    SDConnectTimeout = (int)director->SDConnectTimeout;
226
227    if (background) {
228       daemon_start();
229       init_stack_dump();              /* grab new pid */
230    }
231
232    /* Create pid must come after we are a daemon -- so we have our final pid */
233    create_pid_file(director->pid_directory, "bacula-dir", get_first_port_host_order(director->DIRaddrs));
234    read_state_file(director->working_directory, "bacula-dir", get_first_port_host_order(director->DIRaddrs));
235
236    drop(uid, gid);                    /* reduce priveleges if requested */
237
238 #if !defined(HAVE_WIN32)
239    signal(SIGHUP, reload_config);
240 #endif
241
242    init_console_msg(working_directory);
243
244    init_python_interpreter(director->hdr.name, director->scripts_directory, 
245        "DirStartUp");
246
247    set_thread_concurrency(director->MaxConcurrentJobs * 2 +
248       4 /* UA */ + 4 /* sched+watchdog+jobsvr+misc */);
249
250    Dmsg0(200, "Start UA server\n");
251    start_UA_server(director->DIRaddrs);
252
253    start_watchdog();                  /* start network watchdog thread */
254
255    init_jcr_subsystem();              /* start JCR watchdogs etc. */
256
257    init_job_server(director->MaxConcurrentJobs);
258
259    Dmsg0(200, "wait for next job\n");
260    /* Main loop -- call scheduler to get next job to run */
261    while ( (jcr = wait_for_next_job(runjob)) ) {
262       run_job(jcr);                   /* run job */
263       free_jcr(jcr);                  /* release jcr */
264       if (runjob) {                   /* command line, run a single job? */
265          break;                       /* yes, terminate */
266       }
267    }
268
269    terminate_dird(0);
270
271    return 0;
272 }
273
274 static void dir_sql_query(JCR *jcr, const char *cmd)
275 {
276    if (!jcr || !jcr->db) {
277       return;
278    }
279    db_sql_query(jcr->db, cmd, NULL, NULL);
280 }
281
282 /* Cleanup and then exit */
283 void terminate_dird(int sig)
284 {
285    static bool already_here = false;
286
287    if (already_here) {                /* avoid recursive temination problems */
288       exit(1);
289    }
290    already_here = true;
291    generate_daemon_event(NULL, "Exit");
292    write_state_file(director->working_directory, "bacula-dir", get_first_port_host_order(director->DIRaddrs));
293    delete_pid_file(director->pid_directory, "bacula-dir", get_first_port_host_order(director->DIRaddrs));
294 // signal(SIGCHLD, SIG_IGN);          /* don't worry about children now */
295    term_scheduler();
296    term_job_server();
297    if (runjob) {
298       free(runjob);
299    }
300    if (configfile != NULL) {
301       free(configfile);
302    }
303    if (debug_level > 5) {
304       print_memory_pool_stats();
305    }
306    free_config_resources();
307    term_ua_server();
308    term_msg();                        /* terminate message handler */
309    stop_watchdog();
310    cleanup_crypto();
311    close_memory_pool();               /* release free memory in pool */
312    sm_dump(false);
313    exit(sig);
314 }
315
316 struct RELOAD_TABLE {
317    int job_count;
318    RES **res_table;
319 };
320
321 static const int max_reloads = 32;
322 static RELOAD_TABLE reload_table[max_reloads];
323
324 static void init_reload(void)
325 {
326    for (int i=0; i < max_reloads; i++) {
327       reload_table[i].job_count = 0;
328       reload_table[i].res_table = NULL;
329    }
330 }
331
332 static void free_saved_resources(int table)
333 {
334    int num = r_last - r_first + 1;
335    RES **res_tab = reload_table[table].res_table;
336    if (!res_tab) {
337       Dmsg1(100, "res_tab for table %d already released.\n", table);
338       return;
339    }
340    Dmsg1(100, "Freeing resources for table %d\n", table);
341    for (int j=0; j<num; j++) {
342       free_resource(res_tab[j], r_first + j);
343    }
344    free(res_tab);
345    reload_table[table].job_count = 0;
346    reload_table[table].res_table = NULL;
347 }
348
349 /*
350  * Called here at the end of every job that was
351  * hooked decrementing the active job_count. When
352  * it goes to zero, no one is using the associated
353  * resource table, so free it.
354  */
355 static void reload_job_end_cb(JCR *jcr, void *ctx)
356 {
357    int reload_id = (int)((long int)ctx);
358    Dmsg3(100, "reload job_end JobId=%d table=%d cnt=%d\n", jcr->JobId,
359       reload_id, reload_table[reload_id].job_count);
360    lock_jobs();
361    LockRes();
362    if (--reload_table[reload_id].job_count <= 0) {
363       free_saved_resources(reload_id);
364    }
365    UnlockRes();
366    unlock_jobs();
367 }
368
369 static int find_free_reload_table_entry()
370 {
371    int table = -1;
372    for (int i=0; i < max_reloads; i++) {
373       if (reload_table[i].res_table == NULL) {
374          table = i;
375          break;
376       }
377    }
378    return table;
379 }
380
381 /*
382  * If we get here, we have received a SIGHUP, which means to
383  *    reread our configuration file.
384  *
385  * The algorithm used is as follows: we count how many jobs are
386  *   running and mark the running jobs to make a callback on
387  *   exiting. The old config is saved with the reload table
388  *   id in a reload table. The new config file is read. Now, as
389  *   each job exits, it calls back to the reload_job_end_cb(), which
390  *   decrements the count of open jobs for the given reload table.
391  *   When the count goes to zero, we release those resources.
392  *   This allows us to have pointers into the resource table (from
393  *   jobs), and once they exit and all the pointers are released, we
394  *   release the old table. Note, if no new jobs are running since the
395  *   last reload, then the old resources will be immediately release.
396  *   A console is considered a job because it may have pointers to
397  *   resources, but a SYSTEM job is not since it *should* not have any
398  *   permanent pointers to jobs.
399  */
400 extern "C"
401 void reload_config(int sig)
402 {
403    static bool already_here = false;
404 #if !defined(HAVE_WIN32)
405    sigset_t set;
406 #endif
407    JCR *jcr;
408    int njobs = 0;                     /* number of running jobs */
409    int table, rtable;
410    bool ok;       
411
412    if (already_here) {
413       abort();                        /* Oops, recursion -> die */
414    }
415    already_here = true;
416
417 #if !defined(HAVE_WIN32)
418    sigemptyset(&set);
419    sigaddset(&set, SIGHUP);
420    sigprocmask(SIG_BLOCK, &set, NULL);
421 #endif
422
423    lock_jobs();
424    LockRes();
425
426    table = find_free_reload_table_entry();
427    if (table < 0) {
428       Jmsg(NULL, M_ERROR, 0, _("Too many open reload requests. Request ignored.\n"));
429       goto bail_out;
430    }
431
432    Dmsg1(100, "Reload_config njobs=%d\n", njobs);
433    reload_table[table].res_table = save_config_resources();
434    Dmsg1(100, "Saved old config in table %d\n", table);
435
436    ok = parse_config(configfile, 0, M_ERROR);  /* no exit on error */
437
438    Dmsg0(100, "Reloaded config file\n");
439    if (!ok || !check_resources()) {
440       rtable = find_free_reload_table_entry();    /* save new, bad table */
441       if (rtable < 0) {
442          Jmsg(NULL, M_ERROR, 0, _("Please correct configuration file: %s\n"), configfile);
443          Jmsg(NULL, M_ERROR_TERM, 0, _("Out of reload table entries. Giving up.\n"));
444       } else {
445          Jmsg(NULL, M_ERROR, 0, _("Please correct configuration file: %s\n"), configfile);
446          Jmsg(NULL, M_ERROR, 0, _("Resetting previous configuration.\n"));
447       }
448       reload_table[rtable].res_table = save_config_resources();
449       /* Now restore old resoure values */
450       int num = r_last - r_first + 1;
451       RES **res_tab = reload_table[table].res_table;
452       for (int i=0; i<num; i++) {
453          res_head[i] = res_tab[i];
454       }
455       table = rtable;                 /* release new, bad, saved table below */
456    } else {
457       invalidate_schedules();
458       /*
459        * Hook all active jobs so that they release this table
460        */
461       foreach_jcr(jcr) {
462          if (jcr->JobType != JT_SYSTEM) {
463             reload_table[table].job_count++;
464             job_end_push(jcr, reload_job_end_cb, (void *)((long int)table));
465             njobs++;
466          }
467       }
468       endeach_jcr(jcr);
469    }
470
471    /* Reset globals */
472    set_working_directory(director->working_directory);
473    FDConnectTimeout = director->FDConnectTimeout;
474    SDConnectTimeout = director->SDConnectTimeout;
475    Dmsg0(0, "Director's configuration file reread.\n");
476
477    /* Now release saved resources, if no jobs using the resources */
478    if (njobs == 0) {
479       free_saved_resources(table);
480    }
481
482 bail_out:
483    UnlockRes();
484    unlock_jobs();
485 #if !defined(HAVE_WIN32)
486    sigprocmask(SIG_UNBLOCK, &set, NULL);
487    signal(SIGHUP, reload_config);
488 #endif
489    already_here = false;
490 }
491
492 /*
493  * Make a quick check to see that we have all the
494  * resources needed.
495  *
496  *  **** FIXME **** this routine could be a lot more
497  *   intelligent and comprehensive.
498  */
499 static int check_resources()
500 {
501    bool OK = true;
502    JOB *job;
503
504    LockRes();
505
506    job = (JOB *)GetNextRes(R_JOB, NULL);
507    director = (DIRRES *)GetNextRes(R_DIRECTOR, NULL);
508    if (!director) {
509       Jmsg(NULL, M_FATAL, 0, _("No Director resource defined in %s\n"
510 "Without that I don't know who I am :-(\n"), configfile);
511       OK = false;
512    } else {
513       set_working_directory(director->working_directory);
514       if (!director->messages) {       /* If message resource not specified */
515          director->messages = (MSGS *)GetNextRes(R_MSGS, NULL);
516          if (!director->messages) {
517             Jmsg(NULL, M_FATAL, 0, _("No Messages resource defined in %s\n"), configfile);
518             OK = false;
519          }
520       }
521       if (GetNextRes(R_DIRECTOR, (RES *)director) != NULL) {
522          Jmsg(NULL, M_FATAL, 0, _("Only one Director resource permitted in %s\n"),
523             configfile);
524          OK = false;
525       }
526       /* tls_require implies tls_enable */
527       if (director->tls_require) {
528          if (have_tls) {
529             director->tls_enable = true;
530          } else {
531             Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
532             OK = false;
533          }
534       }
535
536       if (!director->tls_certfile && director->tls_enable) {
537          Jmsg(NULL, M_FATAL, 0, _("\"TLS Certificate\" file not defined for Director \"%s\" in %s.\n"),
538             director->hdr.name, configfile);
539          OK = false;
540       }
541
542       if (!director->tls_keyfile && director->tls_enable) {
543          Jmsg(NULL, M_FATAL, 0, _("\"TLS Key\" file not defined for Director \"%s\" in %s.\n"),
544             director->hdr.name, configfile);
545          OK = false;
546       }
547
548       if ((!director->tls_ca_certfile && !director->tls_ca_certdir) && director->tls_enable && director->tls_verify_peer) {
549          Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\" or \"TLS CA"
550               " Certificate Dir\" are defined for Director \"%s\" in %s."
551               " At least one CA certificate store is required"
552               " when using \"TLS Verify Peer\".\n"),
553               director->hdr.name, configfile);
554          OK = false;
555       }
556
557       /* If everything is well, attempt to initialize our per-resource TLS context */
558       if (OK && (director->tls_enable || director->tls_require)) {
559          /* Initialize TLS context:
560           * Args: CA certfile, CA certdir, Certfile, Keyfile,
561           * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
562          director->tls_ctx = new_tls_context(director->tls_ca_certfile,
563             director->tls_ca_certdir, director->tls_certfile,
564             director->tls_keyfile, NULL, NULL, director->tls_dhfile,
565             director->tls_verify_peer);
566          
567          if (!director->tls_ctx) {
568             Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for Director \"%s\" in %s.\n"),
569                  director->hdr.name, configfile);
570             OK = false;
571          }
572       }
573    }
574
575    if (!job) {
576       Jmsg(NULL, M_FATAL, 0, _("No Job records defined in %s\n"), configfile);
577       OK = false;
578    }
579    foreach_res(job, R_JOB) {
580       int i;
581
582       if (job->jobdefs) {
583          /* Handle Storage alists specifically */
584          JOB *jobdefs = job->jobdefs;
585          if (jobdefs->storage && !job->storage) {
586             STORE *st;
587             job->storage = New(alist(10, not_owned_by_alist));
588             foreach_alist(st, jobdefs->storage) {
589                job->storage->append(st);
590             }
591          }
592          /* Handle RunScripts alists specifically */
593          if (jobdefs->RunScripts) {
594             RUNSCRIPT *rs, *elt;
595             
596             if (!job->RunScripts) {
597                job->RunScripts = New(alist(10, not_owned_by_alist));
598             }
599            
600             foreach_alist(rs, jobdefs->RunScripts) {
601                elt = copy_runscript(rs);
602                job->RunScripts->append(elt); /* we have to free it */
603             }
604          }
605
606          /* Transfer default items from JobDefs Resource */
607          for (i=0; job_items[i].name; i++) {
608             char **def_svalue, **svalue;  /* string value */
609             int *def_ivalue, *ivalue;     /* integer value */
610             bool *def_bvalue, *bvalue;    /* bool value */
611             int64_t *def_lvalue, *lvalue; /* 64 bit values */
612             uint32_t offset;
613
614             Dmsg4(1400, "Job \"%s\", field \"%s\" bit=%d def=%d\n",
615                 job->hdr.name, job_items[i].name,
616                 bit_is_set(i, job->hdr.item_present),
617                 bit_is_set(i, job->jobdefs->hdr.item_present));
618
619             if (!bit_is_set(i, job->hdr.item_present) &&
620                  bit_is_set(i, job->jobdefs->hdr.item_present)) {
621                Dmsg2(400, "Job \"%s\", field \"%s\": getting default.\n",
622                  job->hdr.name, job_items[i].name);
623                offset = (char *)(job_items[i].value) - (char *)&res_all;
624                /*
625                 * Handle strings and directory strings
626                 */
627                if (job_items[i].handler == store_str ||
628                    job_items[i].handler == store_dir) {
629                   def_svalue = (char **)((char *)(job->jobdefs) + offset);
630                   Dmsg5(400, "Job \"%s\", field \"%s\" def_svalue=%s item %d offset=%u\n",
631                        job->hdr.name, job_items[i].name, *def_svalue, i, offset);
632                   svalue = (char **)((char *)job + offset);
633                   if (*svalue) {
634                      Pmsg1(000, _("Hey something is wrong. p=0x%lu\n"), *svalue);
635                   }
636                   *svalue = bstrdup(*def_svalue);
637                   set_bit(i, job->hdr.item_present);
638                /*
639                 * Handle resources
640                 */
641                } else if (job_items[i].handler == store_res) {
642                   def_svalue = (char **)((char *)(job->jobdefs) + offset);
643                   Dmsg4(400, "Job \"%s\", field \"%s\" item %d offset=%u\n",
644                        job->hdr.name, job_items[i].name, i, offset);
645                   svalue = (char **)((char *)job + offset);
646                   if (*svalue) {
647                      Pmsg1(000, _("Hey something is wrong. p=0x%lu\n"), *svalue);
648                   }
649                   *svalue = *def_svalue;
650                   set_bit(i, job->hdr.item_present);
651                /*
652                 * Handle alist resources
653                 */
654                } else if (job_items[i].handler == store_alist_res) {
655                   if (bit_is_set(i, job->jobdefs->hdr.item_present)) {
656                      set_bit(i, job->hdr.item_present);
657                   }
658                /*
659                 * Handle integer fields
660                 *    Note, our store_bit does not handle bitmaped fields
661                 */
662                } else if (job_items[i].handler == store_bit     ||
663                           job_items[i].handler == store_pint    ||
664                           job_items[i].handler == store_jobtype ||
665                           job_items[i].handler == store_level   ||
666                           job_items[i].handler == store_pint    ||
667                           job_items[i].handler == store_replace) {
668                   def_ivalue = (int *)((char *)(job->jobdefs) + offset);
669                   Dmsg5(400, "Job \"%s\", field \"%s\" def_ivalue=%d item %d offset=%u\n",
670                        job->hdr.name, job_items[i].name, *def_ivalue, i, offset);
671                   ivalue = (int *)((char *)job + offset);
672                   *ivalue = *def_ivalue;
673                   set_bit(i, job->hdr.item_present);
674                /*
675                 * Handle 64 bit integer fields
676                 */
677                } else if (job_items[i].handler == store_time   ||
678                           job_items[i].handler == store_size   ||
679                           job_items[i].handler == store_int64) {
680                   def_lvalue = (int64_t *)((char *)(job->jobdefs) + offset);
681                   Dmsg5(400, "Job \"%s\", field \"%s\" def_lvalue=%" lld " item %d offset=%u\n",
682                        job->hdr.name, job_items[i].name, *def_lvalue, i, offset);
683                   lvalue = (int64_t *)((char *)job + offset);
684                   *lvalue = *def_lvalue;
685                   set_bit(i, job->hdr.item_present);
686                /*
687                 * Handle bool fields
688                 */
689                } else if (job_items[i].handler == store_bool) {
690                   def_bvalue = (bool *)((char *)(job->jobdefs) + offset);
691                   Dmsg5(400, "Job \"%s\", field \"%s\" def_bvalue=%d item %d offset=%u\n",
692                        job->hdr.name, job_items[i].name, *def_bvalue, i, offset);
693                   bvalue = (bool *)((char *)job + offset);
694                   *bvalue = *def_bvalue;
695                   set_bit(i, job->hdr.item_present);
696                }
697             }
698          }
699       }
700       /*
701        * Ensure that all required items are present
702        */
703       for (i=0; job_items[i].name; i++) {
704          if (job_items[i].flags & ITEM_REQUIRED) {
705                if (!bit_is_set(i, job->hdr.item_present)) {
706                   Jmsg(NULL, M_FATAL, 0, _("\"%s\" directive in Job \"%s\" resource is required, but not found.\n"),
707                     job_items[i].name, job->hdr.name);
708                   OK = false;
709                 }
710          }
711          /* If this triggers, take a look at lib/parse_conf.h */
712          if (i >= MAX_RES_ITEMS) {
713             Emsg0(M_ERROR_TERM, 0, _("Too many items in Job resource\n"));
714          }
715       }
716    } /* End loop over Job res */
717
718    /* Loop over databases */
719    CAT *catalog;
720    foreach_res(catalog, R_CATALOG) {
721       B_DB *db;
722       /*
723        * Make sure we can open catalog, otherwise print a warning
724        * message because the server is probably not running.
725        */
726       db = db_init_database(NULL, catalog->db_name, catalog->db_user,
727                          catalog->db_password, catalog->db_address,
728                          catalog->db_port, catalog->db_socket,
729                          catalog->mult_db_connections);
730       if (!db || !db_open_database(NULL, db)) {
731          Jmsg(NULL, M_FATAL, 0, _("Could not open Catalog \"%s\", database \"%s\".\n"),
732               catalog->hdr.name, catalog->db_name);
733          if (db) {
734             Jmsg(NULL, M_FATAL, 0, _("%s"), db_strerror(db));
735          }
736          OK = false;
737          continue;
738       }
739
740       /* Loop over all pools, defining/updating them in each database */
741       POOL *pool;
742       foreach_res(pool, R_POOL) {
743          create_pool(NULL, db, pool, POOL_OP_UPDATE);  /* update request */
744       }
745
746       STORE *store;
747       foreach_res(store, R_STORAGE) {
748          STORAGE_DBR sr;
749          MEDIATYPE_DBR mr;
750          if (store->media_type) {
751             bstrncpy(mr.MediaType, store->media_type, sizeof(mr.MediaType));
752             mr.ReadOnly = 0;
753             db_create_mediatype_record(NULL, db, &mr);
754          } else {
755             mr.MediaTypeId = 0;
756          }
757          bstrncpy(sr.Name, store->name(), sizeof(sr.Name));
758          sr.AutoChanger = store->autochanger;
759          db_create_storage_record(NULL, db, &sr);
760          store->StorageId = sr.StorageId;   /* set storage Id */
761          if (!sr.created) {                 /* if not created, update it */
762             db_update_storage_record(NULL, db, &sr);
763          }
764
765          /* tls_require implies tls_enable */
766          if (store->tls_require) {
767             if (have_tls) {
768                store->tls_enable = true;
769             } else {
770                Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
771                OK = false;
772             }
773          } 
774
775          if ((!store->tls_ca_certfile && !store->tls_ca_certdir) && store->tls_enable) {
776             Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\""
777                  " or \"TLS CA Certificate Dir\" are defined for Storage \"%s\" in %s.\n"),
778                  store->hdr.name, configfile);
779             OK = false;
780          }
781
782          /* If everything is well, attempt to initialize our per-resource TLS context */
783          if (OK && (store->tls_enable || store->tls_require)) {
784            /* Initialize TLS context:
785             * Args: CA certfile, CA certdir, Certfile, Keyfile,
786             * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
787             store->tls_ctx = new_tls_context(store->tls_ca_certfile,
788                store->tls_ca_certdir, store->tls_certfile,
789                store->tls_keyfile, NULL, NULL, NULL, true);
790          
791             if (!store->tls_ctx) {
792                Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for Storage \"%s\" in %s.\n"),
793                     store->hdr.name, configfile);
794                OK = false;
795             }
796          }
797       }
798
799       /* Loop over all counters, defining them in each database */
800       /* Set default value in all counters */
801       COUNTER *counter;
802       foreach_res(counter, R_COUNTER) {
803          /* Write to catalog? */
804          if (!counter->created && counter->Catalog == catalog) {
805             COUNTER_DBR cr;
806             bstrncpy(cr.Counter, counter->hdr.name, sizeof(cr.Counter));
807             cr.MinValue = counter->MinValue;
808             cr.MaxValue = counter->MaxValue;
809             cr.CurrentValue = counter->MinValue;
810             if (counter->WrapCounter) {
811                bstrncpy(cr.WrapCounter, counter->WrapCounter->hdr.name, sizeof(cr.WrapCounter));
812             } else {
813                cr.WrapCounter[0] = 0;  /* empty string */
814             }
815             if (db_create_counter_record(NULL, db, &cr)) {
816                counter->CurrentValue = cr.CurrentValue;
817                counter->created = true;
818                Dmsg2(100, "Create counter %s val=%d\n", counter->hdr.name, counter->CurrentValue);
819             }
820          }
821          if (!counter->created) {
822             counter->CurrentValue = counter->MinValue;  /* default value */
823          }
824       }
825       db_close_database(NULL, db);
826    }
827
828    /* Loop over Consoles */
829    CONRES *cons;
830    foreach_res(cons, R_CONSOLE) {
831       /* tls_require implies tls_enable */
832       if (cons->tls_require) {
833          if (have_tls) {
834             cons->tls_enable = true;
835          } else {
836             Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
837             OK = false;
838             continue;
839          }
840       }
841
842       if (!cons->tls_certfile && cons->tls_enable) {
843          Jmsg(NULL, M_FATAL, 0, _("\"TLS Certificate\" file not defined for Console \"%s\" in %s.\n"),
844             cons->hdr.name, configfile);
845          OK = false;
846       }
847
848       if (!cons->tls_keyfile && cons->tls_enable) {
849          Jmsg(NULL, M_FATAL, 0, _("\"TLS Key\" file not defined for Console \"%s\" in %s.\n"),
850             cons->hdr.name, configfile);
851          OK = false;
852       }
853
854       if ((!cons->tls_ca_certfile && !cons->tls_ca_certdir) && cons->tls_enable && cons->tls_verify_peer) {
855          Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\" or \"TLS CA"
856             " Certificate Dir\" are defined for Console \"%s\" in %s."
857             " At least one CA certificate store is required"
858             " when using \"TLS Verify Peer\".\n"),
859             cons->hdr.name, configfile);
860          OK = false;
861       }
862       /* If everything is well, attempt to initialize our per-resource TLS context */
863       if (OK && (cons->tls_enable || cons->tls_require)) {
864          /* Initialize TLS context:
865           * Args: CA certfile, CA certdir, Certfile, Keyfile,
866           * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
867          cons->tls_ctx = new_tls_context(cons->tls_ca_certfile,
868             cons->tls_ca_certdir, cons->tls_certfile,
869             cons->tls_keyfile, NULL, NULL, cons->tls_dhfile, cons->tls_verify_peer);
870          
871          if (!cons->tls_ctx) {
872             Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for File daemon \"%s\" in %s.\n"),
873                cons->hdr.name, configfile);
874             OK = false;
875          }
876       }
877
878    }
879
880    /* Loop over Clients */
881    CLIENT *client;
882    foreach_res(client, R_CLIENT) {
883       /* tls_require implies tls_enable */
884       if (client->tls_require) {
885          if (have_tls) {
886             client->tls_enable = true;
887          } else {
888             Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
889             OK = false;
890             continue;
891          }
892       }
893
894       if ((!client->tls_ca_certfile && !client->tls_ca_certdir) && client->tls_enable) {
895          Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\""
896             " or \"TLS CA Certificate Dir\" are defined for File daemon \"%s\" in %s.\n"),
897             client->hdr.name, configfile);
898          OK = false;
899       }
900
901       /* If everything is well, attempt to initialize our per-resource TLS context */
902       if (OK && (client->tls_enable || client->tls_require)) {
903          /* Initialize TLS context:
904           * Args: CA certfile, CA certdir, Certfile, Keyfile,
905           * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
906          client->tls_ctx = new_tls_context(client->tls_ca_certfile,
907             client->tls_ca_certdir, client->tls_certfile,
908             client->tls_keyfile, NULL, NULL, NULL,
909             true);
910          
911          if (!client->tls_ctx) {
912             Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for File daemon \"%s\" in %s.\n"),
913                client->hdr.name, configfile);
914             OK = false;
915          }
916       }
917    }
918
919    UnlockRes();
920    if (OK) {
921       close_msg(NULL);                /* close temp message handler */
922       init_msg(NULL, director->messages); /* open daemon message handler */
923    }
924    return OK;
925 }