]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/dird.c
aa1ec186a8c3225b4346e565fc214e86c5771c4b
[bacula/bacula] / bacula / src / dird / dird.c
1 /*
2    Bacula(R) - The Network Backup Solution
3
4    Copyright (C) 2000-2015 Kern Sibbald
5    Copyright (C) 2000-2014 Free Software Foundation Europe e.V.
6
7    The original author of Bacula is Kern Sibbald, with contributions
8    from many others, a complete list can be found in the file AUTHORS.
9
10    You may use this file and others of this release according to the
11    license defined in the LICENSE file, which includes the Affero General
12    Public License, v3.0 ("AGPLv3") and some additional permissions and
13    terms pursuant to its AGPLv3 Section 7.
14
15    This notice must be preserved when any source code is 
16    conveyed and/or propagated.
17
18    Bacula(R) is a registered trademark of Kern Sibbald.
19 */
20 /*
21  *
22  *   Bacula Director daemon -- this is the main program
23  *
24  *     Kern Sibbald, March MM
25  *
26  */
27
28 #include "bacula.h"
29 #include "dird.h"
30 #ifndef HAVE_REGEX_H
31 #include "lib/bregex.h"
32 #else
33 #include <regex.h>
34 #endif
35 #ifdef HAVE_DIRENT_H
36 #include <dirent.h>
37 #define NAMELEN(dirent) (strlen((dirent)->d_name))
38 #endif
39 #ifndef HAVE_READDIR_R
40 int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result);
41 #endif
42
43 /* Forward referenced subroutines */
44 void terminate_dird(int sig);
45 static bool check_resources();
46 static void cleanup_old_files();
47
48 /* Exported subroutines */
49 extern "C" void reload_config(int sig);
50 extern void invalidate_schedules();
51 extern bool parse_dir_config(CONFIG *config, const char *configfile, int exit_code);
52
53 /* Imported subroutines */
54 JCR *wait_for_next_job(char *runjob);
55 void term_scheduler();
56 void term_ua_server();
57 void start_UA_server(dlist *addrs);
58 void init_job_server(int max_workers);
59 void term_job_server();
60 void store_jobtype(LEX *lc, RES_ITEM *item, int index, int pass);
61 void store_level(LEX *lc, RES_ITEM *item, int index, int pass);
62 void store_replace(LEX *lc, RES_ITEM *item, int index, int pass);
63 void store_migtype(LEX *lc, RES_ITEM *item, int index, int pass);
64 void init_device_resources();
65
66
67 static char *runjob = NULL;
68 static bool background = true;
69 static void init_reload(void);
70 static CONFIG *config;
71
72 /* Globals Exported */
73 DIRRES *director;                     /* Director resource */
74 int FDConnectTimeout;
75 int SDConnectTimeout;
76 char *configfile = NULL;
77 void *start_heap;
78 utime_t last_reload_time = 0;
79
80 /* Globals Imported */
81 extern RES_ITEM job_items[];
82 #if defined(_MSC_VER)
83 extern "C" { // work around visual compiler mangling variables
84    extern URES res_all;
85 }
86 #else
87 extern URES res_all;
88 #endif
89
90 typedef enum {
91    CHECK_CONNECTION,  /* Check catalog connection */
92    UPDATE_CATALOG,    /* Ensure that catalog is ok with conf */
93    UPDATE_AND_FIX     /* Ensure that catalog is ok, and fix old jobs */
94 } cat_op;
95 static bool check_catalog(cat_op mode);
96
97 #define CONFIG_FILE "bacula-dir.conf" /* default configuration file */
98
99 static bool dir_sql_query(JCR *jcr, const char *cmd) 
100
101    if (jcr && jcr->db && jcr->db->is_connected()) {
102       return db_sql_query(jcr->db, cmd, NULL, NULL);
103    } 
104    return false; 
105
106
107 static bool dir_sql_escape(JCR *jcr, BDB *mdb, char *snew, char *sold, int len) 
108
109    if (jcr && jcr->db && jcr->db->is_connected()) { 
110       db_escape_string(jcr, mdb, snew, sold, len);
111       return true;
112    } 
113    return false; 
114
115
116 static void usage()
117 {
118    fprintf(stderr, _(
119       PROG_COPYRIGHT
120       "\nVersion: %s (%s)\n\n"
121       "Usage: bacula-dir [-f -s] [-c config_file] [-d debug_level] [config_file]\n"
122       "     -c <file>        set configuration file to file\n"
123       "     -d <nn>[,<tags>] set debug level to <nn>, debug tags to <tags>\n"
124       "     -dt              print timestamp in debug output\n"
125       "     -T               set trace on\n"
126       "     -f               run in foreground (for debugging)\n"
127       "     -g               groupid\n"
128       "     -m               print kaboom output (for debugging)\n"
129       "     -r <job>         run <job> now\n"
130       "     -s               no signals\n"
131       "     -t               test - read configuration and exit\n"
132       "     -u               userid\n"
133       "     -v               verbose user messages\n"
134       "     -?               print this message.\n"
135       "\n"), 2000, VERSION, BDATE);
136
137    exit(1);
138 }
139
140 /*
141  * !!! WARNING !!! Use this function only when bacula is stopped.
142  * ie, after a fatal signal and before exiting the program
143  * Print information about a JCR
144  */
145 static void dir_debug_print(JCR *jcr, FILE *fp)
146 {
147    fprintf(fp, "\twstore=%p rstore=%p wjcr=%p client=%p reschedule_count=%d SD_msg_chan_started=%d\n",
148            jcr->wstore, jcr->rstore, jcr->wjcr, jcr->client, jcr->reschedule_count, (int)jcr->SD_msg_chan_started);
149 }
150
151 /*********************************************************************
152  *
153  *         Main Bacula Director Server program
154  *
155  */
156 #if defined(HAVE_WIN32)
157 /* For Win32 main() is in src/win32 code ... */
158 #define main BaculaMain
159 #endif
160
161 int main (int argc, char *argv[])
162 {
163    int ch;
164    JCR *jcr;
165    bool no_signals = false;
166    bool test_config = false;
167    char *uid = NULL;
168    char *gid = NULL;
169
170    start_heap = sbrk(0);
171    setlocale(LC_ALL, "");
172    bindtextdomain("bacula", LOCALEDIR);
173    textdomain("bacula");
174
175    init_stack_dump();
176    my_name_is(argc, argv, "bacula-dir");
177    init_msg(NULL, NULL);              /* initialize message handler */
178    init_reload();
179    daemon_start_time = time(NULL);
180
181    console_command = run_console_command;
182
183    while ((ch = getopt(argc, argv, "c:d:fg:mr:stu:v?T")) != -1) {
184       switch (ch) {
185       case 'c':                    /* specify config file */
186          if (configfile != NULL) {
187             free(configfile);
188          }
189          configfile = bstrdup(optarg);
190          break;
191
192       case 'd':                    /* set debug level */
193          if (*optarg == 't') {
194             dbg_timestamp = true;
195          } else {
196             char *p;
197             /* We probably find a tag list -d 10,sql,bvfs */
198             if ((p = strchr(optarg, ',')) != NULL) {
199                *p = 0;
200             }
201             debug_level = atoi(optarg);
202             if (debug_level <= 0) {
203                debug_level = 1;
204             }
205             if (p) {
206                debug_parse_tags(p+1, &debug_level_tags);
207             }
208          }
209          Dmsg1(10, "Debug level = %lld\n", debug_level);
210          break;
211
212       case 'T':
213          set_trace(true);
214          break;
215
216       case 'f':                    /* run in foreground */
217          background = false;
218          break;
219
220       case 'g':                    /* set group id */
221          gid = optarg;
222          break;
223
224       case 'm':                    /* print kaboom output */
225          prt_kaboom = true;
226          break;
227
228       case 'r':                    /* run job */
229          if (runjob != NULL) {
230             free(runjob);
231          }
232          if (optarg) {
233             runjob = bstrdup(optarg);
234          }
235          break;
236
237       case 's':                    /* turn off signals */
238          no_signals = true;
239          break;
240
241       case 't':                    /* test config */
242          test_config = true;
243          break;
244
245       case 'u':                    /* set uid */
246          uid = optarg;
247          break;
248
249       case 'v':                    /* verbose */
250          verbose++;
251          break;
252
253       case '?':
254       default:
255          usage();
256
257       }
258    }
259    argc -= optind;
260    argv += optind;
261
262    if (!no_signals) {
263       init_signals(terminate_dird);
264    }
265
266    if (argc) {
267       if (configfile != NULL) {
268          free(configfile);
269       }
270       configfile = bstrdup(*argv);
271       argc--;
272       argv++;
273    }
274    if (argc) {
275       usage();
276    }
277
278    if (!test_config) {                /* we don't need to do this block in test mode */
279       if (background) {
280          daemon_start();
281          init_stack_dump();              /* grab new pid */
282       }
283    }
284
285    if (configfile == NULL) {
286       configfile = bstrdup(CONFIG_FILE);
287    }
288
289    config = new_config_parser();
290
291    parse_dir_config(config, configfile, M_ERROR_TERM);
292
293    if (init_crypto() != 0) {
294       Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Cryptography library initialization failed.\n"));
295    }
296
297    if (!check_resources()) {
298       Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
299    }
300
301    if (!test_config) {
302       /* Create pid must come after we are a daemon -- so we have our final pid */
303       create_pid_file(director->pid_directory, "bacula-dir",
304                       get_first_port_host_order(director->DIRaddrs));
305       read_state_file(director->working_directory, "bacula-dir",
306                       get_first_port_host_order(director->DIRaddrs));
307    }
308
309    set_jcr_in_tsd(INVALID_JCR);
310    set_thread_concurrency(director->MaxConcurrentJobs * 2 +
311                           4 /* UA */ + 5 /* sched+watchdog+jobsvr+misc */);
312    lmgr_init_thread(); /* initialize the lockmanager stack */
313
314    load_dir_plugins(director->plugin_directory);
315
316    drop(uid, gid, false);                    /* reduce privileges if requested */
317
318    /* If we are in testing mode, we don't try to fix the catalog */
319    cat_op mode=(test_config)?CHECK_CONNECTION:UPDATE_AND_FIX;
320
321    if (!check_catalog(mode)) {
322       Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
323    }
324
325    if (test_config) {
326       terminate_dird(0);
327    }
328
329    my_name_is(0, NULL, director->name());    /* set user defined name */
330
331    cleanup_old_files();
332
333    /* Plug database interface for library routines */
334    p_sql_query = (sql_query_call)dir_sql_query;
335    p_sql_escape = (sql_escape_call)dir_sql_escape;
336
337    FDConnectTimeout = (int)director->FDConnectTimeout;
338    SDConnectTimeout = (int)director->SDConnectTimeout;
339
340 #if !defined(HAVE_WIN32)
341    signal(SIGHUP, reload_config);
342 #endif
343
344    init_console_msg(working_directory);
345
346    Dmsg0(200, "Start UA server\n");
347    start_UA_server(director->DIRaddrs);
348
349    start_watchdog();                  /* start network watchdog thread */
350
351    init_jcr_subsystem();              /* start JCR watchdogs etc. */
352
353    init_job_server(director->MaxConcurrentJobs);
354
355    dbg_jcr_add_hook(dir_debug_print); /* used to director variables */
356    dbg_jcr_add_hook(bdb_debug_print);     /* used to debug B_DB connexion after fatal signal */
357
358 //   init_device_resources();
359
360    Dmsg0(200, "wait for next job\n");
361    /* Main loop -- call scheduler to get next job to run */
362    while ( (jcr = wait_for_next_job(runjob)) ) {
363       run_job(jcr);                   /* run job */
364       free_jcr(jcr);                  /* release jcr */
365       set_jcr_in_tsd(INVALID_JCR);
366       if (runjob) {                   /* command line, run a single job? */
367          break;                       /* yes, terminate */
368       }
369    }
370
371    terminate_dird(0);
372
373    return 0;
374 }
375
376 struct RELOAD_TABLE {
377    int job_count;
378    RES **res_table;
379 };
380
381 static const int max_reloads = 50;
382 static RELOAD_TABLE reload_table[max_reloads];
383
384 static void init_reload(void)
385 {
386    for (int i=0; i < max_reloads; i++) {
387       reload_table[i].job_count = 0;
388       reload_table[i].res_table = NULL;
389    }
390 }
391
392 /*
393  * This subroutine frees a saved resource table.
394  *  It was saved when a new table was created with "reload"
395  */
396 static void free_saved_resources(int table)
397 {
398    int num = r_last - r_first + 1;
399    RES **res_tab = reload_table[table].res_table;
400    if (!res_tab) {
401       Dmsg1(100, "res_tab for table %d already released.\n", table);
402       return;
403    }
404    Dmsg1(100, "Freeing resources for table %d\n", table);
405    for (int j=0; j<num; j++) {
406       free_resource(res_tab[j], r_first + j);
407    }
408    free(res_tab);
409    reload_table[table].job_count = 0;
410    reload_table[table].res_table = NULL;
411 }
412
413 /*
414  * Called here at the end of every job that was
415  * hooked decrementing the active job_count. When
416  * it goes to zero, no one is using the associated
417  * resource table, so free it.
418  */
419 static void reload_job_end_cb(JCR *jcr, void *ctx)
420 {
421    int reload_id = (int)((intptr_t)ctx);
422    Dmsg3(100, "reload job_end JobId=%d table=%d cnt=%d\n", jcr->JobId,
423       reload_id, reload_table[reload_id].job_count);
424    lock_jobs();
425    LockRes();
426    if (--reload_table[reload_id].job_count <= 0) {
427       free_saved_resources(reload_id);
428    }
429    UnlockRes();
430    unlock_jobs();
431 }
432
433 static int find_free_reload_table_entry()
434 {
435    int table = -1;
436    for (int i=0; i < max_reloads; i++) {
437       if (reload_table[i].res_table == NULL) {
438          table = i;
439          break;
440       }
441    }
442    return table;
443 }
444
445 /*
446  * If we get here, we have received a SIGHUP, which means to
447  *    reread our configuration file.
448  *
449  * The algorithm used is as follows: we count how many jobs are
450  *   running and mark the running jobs to make a callback on
451  *   exiting. The old config is saved with the reload table
452  *   id in a reload table. The new config file is read. Now, as
453  *   each job exits, it calls back to the reload_job_end_cb(), which
454  *   decrements the count of open jobs for the given reload table.
455  *   When the count goes to zero, we release those resources.
456  *   This allows us to have pointers into the resource table (from
457  *   jobs), and once they exit and all the pointers are released, we
458  *   release the old table. Note, if no new jobs are running since the
459  *   last reload, then the old resources will be immediately release.
460  *   A console is considered a job because it may have pointers to
461  *   resources, but a SYSTEM job is not since it *should* not have any
462  *   permanent pointers to jobs.
463  */
464 extern "C"
465 void reload_config(int sig)
466 {
467    static bool already_here = false;
468 #if !defined(HAVE_WIN32)
469    sigset_t set;
470 #endif
471    JCR *jcr;
472    int njobs = 0;                     /* number of running jobs */
473    int table, rtable;
474    bool ok;
475
476    if (already_here) {
477       abort();                        /* Oops, recursion -> die */
478    }
479    already_here = true;
480
481 #if !defined(HAVE_WIN32)
482    sigemptyset(&set);
483    sigaddset(&set, SIGHUP);
484    sigprocmask(SIG_BLOCK, &set, NULL);
485 #endif
486
487    lock_jobs();
488    LockRes();
489
490    table = find_free_reload_table_entry();
491    if (table < 0) {
492       Jmsg(NULL, M_ERROR, 0, _("Too many open reload requests. Request ignored.\n"));
493       goto bail_out;
494    }
495
496    Dmsg1(100, "Reload_config njobs=%d\n", njobs);
497    reload_table[table].res_table = config->save_resources();
498    Dmsg1(100, "Saved old config in table %d\n", table);
499
500    ok = parse_dir_config(config, configfile, M_ERROR);
501
502    Dmsg0(100, "Reloaded config file\n");
503    if (!ok || !check_resources() || !check_catalog(UPDATE_CATALOG)) {
504       rtable = find_free_reload_table_entry();    /* save new, bad table */
505       if (rtable < 0) {
506          Jmsg(NULL, M_ERROR, 0, _("Please correct configuration file: %s\n"), configfile);
507          Jmsg(NULL, M_ERROR_TERM, 0, _("Out of reload table entries. Giving up.\n"));
508       } else {
509          Jmsg(NULL, M_ERROR, 0, _("Please correct configuration file: %s\n"), configfile);
510          Jmsg(NULL, M_ERROR, 0, _("Resetting previous configuration.\n"));
511       }
512       reload_table[rtable].res_table = config->save_resources();
513       /* Now restore old resource values */
514       int num = r_last - r_first + 1;
515       RES **res_tab = reload_table[table].res_table;
516       for (int i=0; i<num; i++) {
517          res_head[i] = res_tab[i];
518       }
519       table = rtable;                 /* release new, bad, saved table below */
520    } else {
521       invalidate_schedules();
522       /*
523        * Hook all active jobs so that they release this table
524        */
525       foreach_jcr(jcr) {
526          if (jcr->getJobType() != JT_SYSTEM) {
527             reload_table[table].job_count++;
528             job_end_push(jcr, reload_job_end_cb, (void *)((long int)table));
529             njobs++;
530          }
531       }
532       endeach_jcr(jcr);
533    }
534
535    /* Reset globals */
536    set_working_directory(director->working_directory);
537    FDConnectTimeout = director->FDConnectTimeout;
538    SDConnectTimeout = director->SDConnectTimeout;
539    Dmsg0(10, "Director's configuration file reread.\n");
540
541    /* Now release saved resources, if no jobs using the resources */
542    if (njobs == 0) {
543       free_saved_resources(table);
544    }
545
546 bail_out:
547    UnlockRes();
548    unlock_jobs();
549 #if !defined(HAVE_WIN32)
550    sigprocmask(SIG_UNBLOCK, &set, NULL);
551    signal(SIGHUP, reload_config);
552 #endif
553    already_here = false;
554 }
555
556 /* Cleanup and then exit */
557 void terminate_dird(int sig)
558 {
559    static bool already_here = false;
560
561    if (already_here) {                /* avoid recursive temination problems */
562       bmicrosleep(2, 0);              /* yield */
563       exit(1);
564    }
565    already_here = true;
566    debug_level = 0;                   /* turn off debug */
567    stop_watchdog();
568    generate_daemon_event(NULL, "Exit");
569    unload_plugins();
570    write_state_file(director->working_directory, "bacula-dir", get_first_port_host_order(director->DIRaddrs));
571    delete_pid_file(director->pid_directory, "bacula-dir", get_first_port_host_order(director->DIRaddrs));
572    term_scheduler();
573    term_job_server();
574    if (runjob) {
575       free(runjob);
576    }
577    if (configfile != NULL) {
578       free(configfile);
579    }
580    if (chk_dbglvl(5)) {
581       print_memory_pool_stats();
582    }
583    if (config) {
584       config->free_resources();
585       free(config);
586       config = NULL;
587    }
588    term_ua_server();
589    term_msg();                        /* terminate message handler */
590    cleanup_crypto();
591    close_memory_pool();               /* release free memory in pool */
592    lmgr_cleanup_main();
593    sm_dump(false);
594    exit(sig);
595 }
596
597 /*
598  * Make a quick check to see that we have all the
599  * resources needed.
600  *
601  *  **** FIXME **** this routine could be a lot more
602  *   intelligent and comprehensive.
603  */
604 static bool check_resources()
605 {
606    bool OK = true;
607    JOB *job;
608    bool need_tls;
609
610    LockRes();
611
612    job = (JOB *)GetNextRes(R_JOB, NULL);
613    director = (DIRRES *)GetNextRes(R_DIRECTOR, NULL);
614    if (!director) {
615       Jmsg(NULL, M_FATAL, 0, _("No Director resource defined in %s\n"
616 "Without that I don't know who I am :-(\n"), configfile);
617       OK = false;
618    } else {
619       set_working_directory(director->working_directory);
620       if (!director->messages) {       /* If message resource not specified */
621          director->messages = (MSGS *)GetNextRes(R_MSGS, NULL);
622          if (!director->messages) {
623             Jmsg(NULL, M_FATAL, 0, _("No Messages resource defined in %s\n"), configfile);
624             OK = false;
625          }
626       }
627       if (GetNextRes(R_DIRECTOR, (RES *)director) != NULL) {
628          Jmsg(NULL, M_FATAL, 0, _("Only one Director resource permitted in %s\n"),
629             configfile);
630          OK = false;
631       }
632       /* tls_require implies tls_enable */
633       if (director->tls_require) {
634          if (have_tls) {
635             director->tls_enable = true;
636          } else {
637             Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
638             OK = false;
639          }
640       }
641
642       need_tls = director->tls_enable || director->tls_authenticate;
643
644       if (!director->tls_certfile && need_tls) {
645          Jmsg(NULL, M_FATAL, 0, _("\"TLS Certificate\" file not defined for Director \"%s\" in %s.\n"),
646             director->name(), configfile);
647          OK = false;
648       }
649
650       if (!director->tls_keyfile && need_tls) {
651          Jmsg(NULL, M_FATAL, 0, _("\"TLS Key\" file not defined for Director \"%s\" in %s.\n"),
652             director->name(), configfile);
653          OK = false;
654       }
655
656       if ((!director->tls_ca_certfile && !director->tls_ca_certdir) &&
657            need_tls && director->tls_verify_peer) {
658          Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\" or \"TLS CA"
659               " Certificate Dir\" are defined for Director \"%s\" in %s."
660               " At least one CA certificate store is required"
661               " when using \"TLS Verify Peer\".\n"),
662               director->name(), configfile);
663          OK = false;
664       }
665
666       /* If everything is well, attempt to initialize our per-resource TLS context */
667       if (OK && (need_tls || director->tls_require)) {
668          /* Initialize TLS context:
669           * Args: CA certfile, CA certdir, Certfile, Keyfile,
670           * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
671          director->tls_ctx = new_tls_context(director->tls_ca_certfile,
672             director->tls_ca_certdir, director->tls_certfile,
673             director->tls_keyfile, NULL, NULL, director->tls_dhfile,
674             director->tls_verify_peer);
675
676          if (!director->tls_ctx) {
677             Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for Director \"%s\" in %s.\n"),
678                  director->name(), configfile);
679             OK = false;
680          }
681       }
682    }
683
684    if (!job) {
685       Jmsg(NULL, M_FATAL, 0, _("No Job records defined in %s\n"), configfile);
686       OK = false;
687    }
688    foreach_res(job, R_JOB) {
689       int i;
690
691       if (job->jobdefs) {
692          /* Handle Storage alists specifically */
693          JOB *jobdefs = job->jobdefs;
694          if (jobdefs->storage && !job->storage) {
695             STORE *st;
696             job->storage = New(alist(10, not_owned_by_alist));
697             foreach_alist(st, jobdefs->storage) {
698                job->storage->append(st);
699             }
700          }
701          /* Handle RunScripts alists specifically */
702          if (jobdefs->RunScripts) {
703             RUNSCRIPT *rs, *elt;
704
705             if (!job->RunScripts) {
706                job->RunScripts = New(alist(10, not_owned_by_alist));
707             }
708
709             foreach_alist(rs, jobdefs->RunScripts) {
710                elt = copy_runscript(rs);
711                job->RunScripts->append(elt); /* we have to free it */
712             }
713          }
714
715          /* Transfer default items from JobDefs Resource */
716          for (i=0; job_items[i].name; i++) {
717             char **def_svalue, **svalue;  /* string value */
718             uint32_t *def_ivalue, *ivalue;     /* integer value */
719             bool *def_bvalue, *bvalue;    /* bool value */
720             int64_t *def_lvalue, *lvalue; /* 64 bit values */
721             uint32_t offset;
722
723             Dmsg4(1400, "Job \"%s\", field \"%s\" bit=%d def=%d\n",
724                 job->name(), job_items[i].name,
725                 bit_is_set(i, job->hdr.item_present),
726                 bit_is_set(i, job->jobdefs->hdr.item_present));
727
728             if (!bit_is_set(i, job->hdr.item_present) &&
729                  bit_is_set(i, job->jobdefs->hdr.item_present)) {
730                Dmsg2(400, "Job \"%s\", field \"%s\": getting default.\n",
731                  job->name(), job_items[i].name);
732                offset = (char *)(job_items[i].value) - (char *)&res_all;
733                /*
734                 * Handle strings and directory strings
735                 */
736                if (job_items[i].handler == store_str ||
737                    job_items[i].handler == store_dir) {
738                   def_svalue = (char **)((char *)(job->jobdefs) + offset);
739                   Dmsg5(400, "Job \"%s\", field \"%s\" def_svalue=%s item %d offset=%u\n",
740                        job->name(), job_items[i].name, *def_svalue, i, offset);
741                   svalue = (char **)((char *)job + offset);
742                   if (*svalue) {
743                      Pmsg1(000, _("Hey something is wrong. p=0x%lu\n"), *svalue);
744                   }
745                   *svalue = bstrdup(*def_svalue);
746                   set_bit(i, job->hdr.item_present);
747                /*
748                 * Handle resources
749                 */
750                } else if (job_items[i].handler == store_res) {
751                   def_svalue = (char **)((char *)(job->jobdefs) + offset);
752                   Dmsg4(400, "Job \"%s\", field \"%s\" item %d offset=%u\n",
753                        job->name(), job_items[i].name, i, offset);
754                   svalue = (char **)((char *)job + offset);
755                   if (*svalue) {
756                      Pmsg1(000, _("Hey something is wrong. p=0x%lu\n"), *svalue);
757                   }
758                   *svalue = *def_svalue;
759                   set_bit(i, job->hdr.item_present);
760                /*
761                 * Handle alist resources
762                 */
763                } else if (job_items[i].handler == store_alist_res) {
764                   if (bit_is_set(i, job->jobdefs->hdr.item_present)) {
765                      set_bit(i, job->hdr.item_present);
766                   }
767                /*
768                 * Handle integer fields
769                 *    Note, our store_bit does not handle bitmaped fields
770                 */
771                } else if (job_items[i].handler == store_bit     ||
772                           job_items[i].handler == store_pint32  ||
773                           job_items[i].handler == store_jobtype ||
774                           job_items[i].handler == store_level   ||
775                           job_items[i].handler == store_int32   ||
776                           job_items[i].handler == store_size32  ||
777                           job_items[i].handler == store_migtype ||
778                           job_items[i].handler == store_replace) {
779                   def_ivalue = (uint32_t *)((char *)(job->jobdefs) + offset);
780                   Dmsg5(400, "Job \"%s\", field \"%s\" def_ivalue=%d item %d offset=%u\n",
781                        job->name(), job_items[i].name, *def_ivalue, i, offset);
782                   ivalue = (uint32_t *)((char *)job + offset);
783                   *ivalue = *def_ivalue;
784                   set_bit(i, job->hdr.item_present);
785                /*
786                 * Handle 64 bit integer fields
787                 */
788                } else if (job_items[i].handler == store_time   ||
789                           job_items[i].handler == store_size64 ||
790                           job_items[i].handler == store_speed  ||
791                           job_items[i].handler == store_int64) {
792                   def_lvalue = (int64_t *)((char *)(job->jobdefs) + offset);
793                   Dmsg5(400, "Job \"%s\", field \"%s\" def_lvalue=%" lld " item %d offset=%u\n",
794                        job->name(), job_items[i].name, *def_lvalue, i, offset);
795                   lvalue = (int64_t *)((char *)job + offset);
796                   *lvalue = *def_lvalue;
797                   set_bit(i, job->hdr.item_present);
798                /*
799                 * Handle bool fields
800                 */
801                } else if (job_items[i].handler == store_bool) {
802                   def_bvalue = (bool *)((char *)(job->jobdefs) + offset);
803                   Dmsg5(400, "Job \"%s\", field \"%s\" def_bvalue=%d item %d offset=%u\n",
804                        job->name(), job_items[i].name, *def_bvalue, i, offset);
805                   bvalue = (bool *)((char *)job + offset);
806                   *bvalue = *def_bvalue;
807                   set_bit(i, job->hdr.item_present);
808                }
809             }
810          }
811       }
812       /*
813        * Ensure that all required items are present
814        */
815       for (i=0; job_items[i].name; i++) {
816          if (job_items[i].flags & ITEM_REQUIRED) {
817                if (!bit_is_set(i, job->hdr.item_present)) {
818                   Jmsg(NULL, M_ERROR_TERM, 0, _("\"%s\" directive in Job \"%s\" resource is required, but not found.\n"),
819                     job_items[i].name, job->name());
820                   OK = false;
821                 }
822          }
823          /* If this triggers, take a look at lib/parse_conf.h */
824          if (i >= MAX_RES_ITEMS) {
825             Emsg0(M_ERROR_TERM, 0, _("Too many items in Job resource\n"));
826          }
827       }
828       if (!job->storage && !job->pool->storage) {
829          Jmsg(NULL, M_FATAL, 0, _("No storage specified in Job \"%s\" nor in Pool.\n"),
830             job->name());
831          OK = false;
832       }
833    } /* End loop over Job res */
834
835
836    /* Loop over Consoles */
837    CONRES *cons;
838    foreach_res(cons, R_CONSOLE) {
839       /* tls_require implies tls_enable */
840       if (cons->tls_require) {
841          if (have_tls) {
842             cons->tls_enable = true;
843          } else {
844             Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
845             OK = false;
846             continue;
847          }
848       }
849
850       need_tls = cons->tls_enable || cons->tls_authenticate;
851
852       if (!cons->tls_certfile && need_tls) {
853          Jmsg(NULL, M_FATAL, 0, _("\"TLS Certificate\" file not defined for Console \"%s\" in %s.\n"),
854             cons->name(), configfile);
855          OK = false;
856       }
857
858       if (!cons->tls_keyfile && need_tls) {
859          Jmsg(NULL, M_FATAL, 0, _("\"TLS Key\" file not defined for Console \"%s\" in %s.\n"),
860             cons->name(), configfile);
861          OK = false;
862       }
863
864       if ((!cons->tls_ca_certfile && !cons->tls_ca_certdir)
865             && need_tls && cons->tls_verify_peer) {
866          Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\" or \"TLS CA"
867             " Certificate Dir\" are defined for Console \"%s\" in %s."
868             " At least one CA certificate store is required"
869             " when using \"TLS Verify Peer\".\n"),
870             cons->name(), configfile);
871          OK = false;
872       }
873       /* If everything is well, attempt to initialize our per-resource TLS context */
874       if (OK && (need_tls || cons->tls_require)) {
875          /* Initialize TLS context:
876           * Args: CA certfile, CA certdir, Certfile, Keyfile,
877           * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
878          cons->tls_ctx = new_tls_context(cons->tls_ca_certfile,
879             cons->tls_ca_certdir, cons->tls_certfile,
880             cons->tls_keyfile, NULL, NULL, cons->tls_dhfile, cons->tls_verify_peer);
881
882          if (!cons->tls_ctx) {
883             Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for File daemon \"%s\" in %s.\n"),
884                cons->name(), configfile);
885             OK = false;
886          }
887       }
888
889    }
890
891    /* Loop over Clients */
892    CLIENT *client;
893    foreach_res(client, R_CLIENT) {
894       /* tls_require implies tls_enable */
895       if (client->tls_require) {
896          if (have_tls) {
897             client->tls_enable = true;
898          } else {
899             Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
900             OK = false;
901             continue;
902          }
903       }
904       need_tls = client->tls_enable || client->tls_authenticate;
905       if ((!client->tls_ca_certfile && !client->tls_ca_certdir) && need_tls) {
906          Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\""
907             " or \"TLS CA Certificate Dir\" are defined for File daemon \"%s\" in %s.\n"),
908             client->name(), configfile);
909          OK = false;
910       }
911
912       /* If everything is well, attempt to initialize our per-resource TLS context */
913       if (OK && (need_tls || client->tls_require)) {
914          /* Initialize TLS context:
915           * Args: CA certfile, CA certdir, Certfile, Keyfile,
916           * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
917          client->tls_ctx = new_tls_context(client->tls_ca_certfile,
918             client->tls_ca_certdir, client->tls_certfile,
919             client->tls_keyfile, NULL, NULL, NULL,
920             true);
921
922          if (!client->tls_ctx) {
923             Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for File daemon \"%s\" in %s.\n"),
924                client->name(), configfile);
925             OK = false;
926          }
927       }
928    }
929
930    UnlockRes();
931    if (OK) {
932       close_msg(NULL);                /* close temp message handler */
933       init_msg(NULL, director->messages); /* open daemon message handler */
934       last_reload_time = time(NULL);
935    }
936    return OK;
937 }
938
939 /*
940  * In this routine,
941  *  - we can check the connection (mode=CHECK_CONNECTION)
942  *  - we can synchronize the catalog with the configuration (mode=UPDATE_CATALOG)
943  *  - we can synchronize, and fix old job records (mode=UPDATE_AND_FIX)
944  */
945 static bool check_catalog(cat_op mode)
946 {
947    bool OK = true;
948    bool need_tls;
949
950    /* Loop over databases */
951    CAT *catalog;
952    foreach_res(catalog, R_CATALOG) {
953       BDB *db;
954       /*
955        * Make sure we can open catalog, otherwise print a warning
956        * message because the server is probably not running.
957        */
958       db = db_init_database(NULL, catalog->db_driver, catalog->db_name, 
959               catalog->db_user,
960               catalog->db_password, catalog->db_address,
961               catalog->db_port, catalog->db_socket,
962               catalog->mult_db_connections,
963               catalog->disable_batch_insert);
964       if (!db || !db_open_database(NULL, db)) {
965          Pmsg2(000, _("Could not open Catalog \"%s\", database \"%s\".\n"),
966               catalog->name(), catalog->db_name);
967          Jmsg(NULL, M_FATAL, 0, _("Could not open Catalog \"%s\", database \"%s\".\n"),
968               catalog->name(), catalog->db_name);
969          if (db) {
970             Jmsg(NULL, M_FATAL, 0, _("%s"), db_strerror(db));
971             Pmsg1(000, "%s", db_strerror(db));
972             db_close_database(NULL, db);
973          }
974          OK = false;
975          continue;
976       }
977
978       /* Display a message if the db max_connections is too low */
979       if (!db_check_max_connections(NULL, db, director->MaxConcurrentJobs)) {
980          Pmsg1(000, "Warning, settings problem for Catalog=%s\n", catalog->name());
981          Pmsg1(000, "%s", db_strerror(db));
982       }
983
984       /* we are in testing mode, so don't touch anything in the catalog */
985       if (mode == CHECK_CONNECTION) {
986          if (db) db_close_database(NULL, db);
987          continue;
988       }
989
990       /* Loop over all pools, defining/updating them in each database */
991       POOL *pool;
992       foreach_res(pool, R_POOL) {
993          /*
994           * If the Pool has a catalog resource create the pool only
995           *   in that catalog.
996           */
997          if (!pool->catalog || pool->catalog == catalog) {
998             create_pool(NULL, db, pool, POOL_OP_UPDATE);  /* update request */
999          }
1000       }
1001
1002       /* Once they are created, we can loop over them again, updating
1003        * references (RecyclePool)
1004        */
1005       foreach_res(pool, R_POOL) {
1006          /*
1007           * If the Pool has a catalog resource update the pool only
1008           *   in that catalog.
1009           */
1010          if (!pool->catalog || pool->catalog == catalog) {
1011             update_pool_references(NULL, db, pool);
1012          }
1013       }
1014
1015       /* Ensure basic client record is in DB */
1016       CLIENT *client;
1017       foreach_res(client, R_CLIENT) {
1018          CLIENT_DBR cr;
1019          /* Create clients only if they use the current catalog */
1020          if (client->catalog != catalog) {
1021             Dmsg3(500, "Skip client=%s with cat=%s not catalog=%s\n",
1022                   client->name(), client->catalog->name(), catalog->name());
1023             continue;
1024          }
1025          Dmsg2(500, "create cat=%s for client=%s\n",
1026                client->catalog->name(), client->name());
1027          memset(&cr, 0, sizeof(cr));
1028          bstrncpy(cr.Name, client->name(), sizeof(cr.Name));
1029
1030          db_create_client_record(NULL, db, &cr);
1031       }
1032
1033       /* Ensure basic storage record is in DB */
1034       STORE *store;
1035       foreach_res(store, R_STORAGE) {
1036          STORAGE_DBR sr;
1037          MEDIATYPE_DBR mtr;
1038          memset(&sr, 0, sizeof(sr));
1039          memset(&mtr, 0, sizeof(mtr));
1040          if (store->media_type) {
1041             bstrncpy(mtr.MediaType, store->media_type, sizeof(mtr.MediaType));
1042             mtr.ReadOnly = 0;
1043             db_create_mediatype_record(NULL, db, &mtr);
1044          } else {
1045             mtr.MediaTypeId = 0;
1046          }
1047          bstrncpy(sr.Name, store->name(), sizeof(sr.Name));
1048          sr.AutoChanger = store->autochanger;
1049          if (!db_create_storage_record(NULL, db, &sr)) {
1050             Jmsg(NULL, M_FATAL, 0, _("Could not create storage record for %s\n"),
1051                  store->name());
1052             OK = false;
1053          }
1054          store->StorageId = sr.StorageId;   /* set storage Id */
1055          if (!sr.created) {                 /* if not created, update it */
1056             sr.AutoChanger = store->autochanger;
1057             if (!db_update_storage_record(NULL, db, &sr)) {
1058                Jmsg(NULL, M_FATAL, 0, _("Could not update storage record for %s\n"),
1059                     store->name());
1060                OK = false;
1061             }
1062          }
1063
1064          /* tls_require implies tls_enable */
1065          if (store->tls_require) {
1066             if (have_tls) {
1067                store->tls_enable = true;
1068             } else {
1069                Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
1070                OK = false;
1071             }
1072          }
1073
1074          need_tls = store->tls_enable || store->tls_authenticate;
1075
1076          if ((!store->tls_ca_certfile && !store->tls_ca_certdir) && need_tls) {
1077             Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\""
1078                  " or \"TLS CA Certificate Dir\" are defined for Storage \"%s\" in %s.\n"),
1079                  store->name(), configfile);
1080             OK = false;
1081          }
1082
1083          /* If everything is well, attempt to initialize our per-resource TLS context */
1084          if (OK && (need_tls || store->tls_require)) {
1085            /* Initialize TLS context:
1086             * Args: CA certfile, CA certdir, Certfile, Keyfile,
1087             * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
1088             store->tls_ctx = new_tls_context(store->tls_ca_certfile,
1089                store->tls_ca_certdir, store->tls_certfile,
1090                store->tls_keyfile, NULL, NULL, NULL, true);
1091
1092             if (!store->tls_ctx) {
1093                Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for Storage \"%s\" in %s.\n"),
1094                     store->name(), configfile);
1095                OK = false;
1096             }
1097          }
1098       }
1099
1100       /* Loop over all counters, defining them in each database */
1101       /* Set default value in all counters */
1102       COUNTER *counter;
1103       foreach_res(counter, R_COUNTER) {
1104          /* Write to catalog? */
1105          if (!counter->created && counter->Catalog == catalog) {
1106             COUNTER_DBR cr;
1107             bstrncpy(cr.Counter, counter->name(), sizeof(cr.Counter));
1108             cr.MinValue = counter->MinValue;
1109             cr.MaxValue = counter->MaxValue;
1110             cr.CurrentValue = counter->MinValue;
1111             if (counter->WrapCounter) {
1112                bstrncpy(cr.WrapCounter, counter->WrapCounter->name(), sizeof(cr.WrapCounter));
1113             } else {
1114                cr.WrapCounter[0] = 0;  /* empty string */
1115             }
1116             if (db_create_counter_record(NULL, db, &cr)) {
1117                counter->CurrentValue = cr.CurrentValue;
1118                counter->created = true;
1119                Dmsg2(100, "Create counter %s val=%d\n", counter->name(), counter->CurrentValue);
1120             }
1121          }
1122          if (!counter->created) {
1123             counter->CurrentValue = counter->MinValue;  /* default value */
1124          }
1125       }
1126       /* cleanup old job records */
1127       if (mode == UPDATE_AND_FIX) {
1128          db_sql_query(db, cleanup_created_job, NULL, NULL);
1129          db_sql_query(db, cleanup_running_job, NULL, NULL);
1130       }
1131
1132       /* Set SQL engine name in global for debugging */
1133       set_db_engine_name(db_get_engine_name(db));
1134       if (db) db_close_database(NULL, db);
1135    }
1136    return OK;
1137 }
1138
1139 static void cleanup_old_files()
1140 {
1141    DIR* dp;
1142    struct dirent *entry, *result;
1143    int rc, name_max;
1144    int my_name_len = strlen(my_name);
1145    int len = strlen(director->working_directory);
1146    POOLMEM *cleanup = get_pool_memory(PM_MESSAGE);
1147    POOLMEM *basename = get_pool_memory(PM_MESSAGE);
1148    regex_t preg1;
1149    char prbuf[500];
1150    const int nmatch = 30;
1151    regmatch_t pmatch[nmatch];
1152    berrno be;
1153
1154    /* Exclude spaces and look for .mail, .tmp or .restore.xx.bsr files */
1155    const char *pat1 = "^[^ ]+\\.(restore\\.[^ ]+\\.bsr|mail|tmp)$";
1156
1157    /* Setup working directory prefix */
1158    pm_strcpy(basename, director->working_directory);
1159    if (len > 0 && !IsPathSeparator(director->working_directory[len-1])) {
1160       pm_strcat(basename, "/");
1161    }
1162
1163    /* Compile regex expressions */
1164    rc = regcomp(&preg1, pat1, REG_EXTENDED);
1165    if (rc != 0) {
1166       regerror(rc, &preg1, prbuf, sizeof(prbuf));
1167       Pmsg2(000,  _("Could not compile regex pattern \"%s\" ERR=%s\n"),
1168            pat1, prbuf);
1169       goto get_out2;
1170    }
1171
1172    name_max = pathconf(".", _PC_NAME_MAX);
1173    if (name_max < 1024) {
1174       name_max = 1024;
1175    }
1176
1177    if (!(dp = opendir(director->working_directory))) {
1178       berrno be;
1179       Pmsg2(000, "Failed to open working dir %s for cleanup: ERR=%s\n",
1180             director->working_directory, be.bstrerror());
1181       goto get_out1;
1182       return;
1183    }
1184
1185    entry = (struct dirent *)malloc(sizeof(struct dirent) + name_max + 1000);
1186    while (1) {
1187       if ((readdir_r(dp, entry, &result) != 0) || (result == NULL)) {
1188          break;
1189       }
1190       /* Exclude any name with ., .., not my_name or containing a space */
1191       if (strcmp(result->d_name, ".") == 0 || strcmp(result->d_name, "..") == 0 ||
1192           strncmp(result->d_name, my_name, my_name_len) != 0) {
1193          Dmsg1(500, "Skipped: %s\n", result->d_name);
1194          continue;
1195       }
1196
1197       /* Unlink files that match regexes */
1198       if (regexec(&preg1, result->d_name, nmatch, pmatch,  0) == 0) {
1199          pm_strcpy(cleanup, basename);
1200          pm_strcat(cleanup, result->d_name);
1201          Dmsg1(100, "Unlink: %s\n", cleanup);
1202          unlink(cleanup);
1203       }
1204    }
1205
1206    free(entry);
1207    closedir(dp);
1208 /* Be careful to free up the correct resources */
1209 get_out1:
1210    regfree(&preg1);
1211 get_out2:
1212    free_pool_memory(cleanup);
1213    free_pool_memory(basename);
1214 }