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