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