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