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