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