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