2 Bacula® - The Network Backup Solution
4 Copyright (C) 2000-2014 Free Software Foundation Europe e.V.
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.
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.
14 Bacula® is a registered trademark of Kern Sibbald.
18 * Bacula Director daemon -- this is the main program
20 * Written by Kern Sibbald, March MM
27 #include "lib/bregex.h"
33 #define NAMELEN(dirent) (strlen((dirent)->d_name))
35 #ifndef HAVE_READDIR_R
36 int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result);
39 /* Forward referenced subroutines */
40 void terminate_dird(int sig);
41 static bool check_resources();
42 static void cleanup_old_files();
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);
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();
62 static char *runjob = NULL;
63 static bool background = true;
64 static void init_reload(void);
65 static CONFIG *config;
67 /* Globals Exported */
68 DIRRES *director; /* Director resource */
71 char *configfile = NULL;
74 /* Globals Imported */
75 extern RES_ITEM job_items[];
77 extern "C" { // work around visual compiler mangling variables
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 */
89 static bool check_catalog(cat_op mode);
91 #define CONFIG_FILE "bacula-dir.conf" /* default configuration file */
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
101 static bool dir_sql_query(JCR *jcr, const char *cmd)
103 if (!jcr || !jcr->db || !jcr->db->is_connected()) {
107 return db_sql_query(jcr->db, cmd);
110 static bool dir_sql_escape(JCR *jcr, B_DB *mdb, char *snew, char *old, int len)
112 if (!jcr || !jcr->db || !jcr->db->is_connected()) {
116 db_escape_string(jcr, mdb, snew, old, len);
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"
131 " -m print kaboom output (for debugging)\n"
132 " -r <job> run <job> now\n"
134 " -t test - read configuration and exit\n"
136 " -v verbose user messages\n"
137 " -? print this message.\n"
138 "\n"), 2000, VERSION, BDATE);
144 /*********************************************************************
146 * Main Bacula Director Server program
149 #if defined(HAVE_WIN32)
150 /* For Win32 main() is in src/win32 code ... */
151 #define main BaculaMain
154 int main (int argc, char *argv[])
158 bool no_signals = false;
159 bool test_config = false;
163 start_heap = sbrk(0);
164 setlocale(LC_ALL, "");
165 bindtextdomain("bacula", LOCALEDIR);
166 textdomain("bacula");
169 my_name_is(argc, argv, "bacula-dir");
170 init_msg(NULL, NULL); /* initialize message handler */
172 daemon_start_time = time(NULL);
174 console_command = run_console_command;
176 while ((ch = getopt(argc, argv, "c:d:fg:mr:stu:v?")) != -1) {
178 case 'c': /* specify config file */
179 if (configfile != NULL) {
182 configfile = bstrdup(optarg);
185 case 'd': /* set debug level */
186 if (*optarg == 't') {
187 dbg_timestamp = true;
189 debug_level = atoi(optarg);
190 if (debug_level <= 0) {
194 Dmsg1(10, "Debug level = %d\n", debug_level);
197 case 'f': /* run in foreground */
201 case 'g': /* set group id */
205 case 'm': /* print kaboom output */
209 case 'r': /* run job */
210 if (runjob != NULL) {
214 runjob = bstrdup(optarg);
218 case 's': /* turn off signals */
222 case 't': /* test config */
226 case 'u': /* set uid */
230 case 'v': /* verbose */
244 init_signals(terminate_dird);
248 if (configfile != NULL) {
251 configfile = bstrdup(*argv);
259 if (configfile == NULL) {
260 configfile = bstrdup(CONFIG_FILE);
263 config = new_config_parser();
264 parse_dir_config(config, configfile, M_ERROR_TERM);
266 if (init_crypto() != 0) {
267 Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Cryptography library initialization failed.\n"));
270 if (!check_resources()) {
271 Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
274 if (!test_config) { /* we don't need to do this block in test mode */
277 init_stack_dump(); /* grab new pid */
279 /* Create pid must come after we are a daemon -- so we have our final pid */
280 create_pid_file(director->pid_directory, "bacula-dir",
281 get_first_port_host_order(director->DIRaddrs));
282 read_state_file(director->working_directory, "bacula-dir",
283 get_first_port_host_order(director->DIRaddrs));
286 set_jcr_in_tsd(INVALID_JCR);
287 set_thread_concurrency(director->MaxConcurrentJobs * 2 +
288 4 /* UA */ + 5 /* sched+watchdog+jobsvr+misc */);
289 lmgr_init_thread(); /* initialize the lockmanager stack */
291 load_dir_plugins(director->plugin_directory);
293 drop(uid, gid, false); /* reduce privileges if requested */
295 /* If we are in testing mode, we don't try to fix the catalog */
296 cat_op mode=(test_config)?CHECK_CONNECTION:UPDATE_AND_FIX;
298 if (!check_catalog(mode)) {
299 Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
306 my_name_is(0, NULL, director->name()); /* set user defined name */
310 /* Plug database interface for library routines */
311 p_sql_query = (sql_query_func)dir_sql_query;
312 p_sql_escape = (sql_escape_func)dir_sql_escape;
314 FDConnectTimeout = (int)director->FDConnectTimeout;
315 SDConnectTimeout = (int)director->SDConnectTimeout;
317 #if !defined(HAVE_WIN32)
318 signal(SIGHUP, reload_config);
321 init_console_msg(working_directory);
323 Dmsg0(200, "Start UA server\n");
324 start_UA_server(director->DIRaddrs);
326 start_watchdog(); /* start network watchdog thread */
328 init_jcr_subsystem(); /* start JCR watchdogs etc. */
330 init_job_server(director->MaxConcurrentJobs);
332 dbg_jcr_add_hook(db_debug_print); /* used to debug B_DB connexion after fatal signal */
334 Dmsg0(200, "wait for next job\n");
335 /* Main loop -- call scheduler to get next job to run */
336 while ( (jcr = wait_for_next_job(runjob)) ) {
337 run_job(jcr); /* run job */
338 free_jcr(jcr); /* release jcr */
339 set_jcr_in_tsd(INVALID_JCR);
340 if (runjob) { /* command line, run a single job? */
341 break; /* yes, terminate */
350 /* Cleanup and then exit */
351 void terminate_dird(int sig)
353 static bool already_here = false;
355 if (already_here) { /* avoid recursive temination problems */
356 bmicrosleep(2, 0); /* yield */
360 debug_level = 0; /* turn off debug */
362 generate_daemon_event(NULL, "Exit");
364 write_state_file(director->working_directory, "bacula-dir", get_first_port_host_order(director->DIRaddrs));
365 delete_pid_file(director->pid_directory, "bacula-dir", get_first_port_host_order(director->DIRaddrs));
371 if (configfile != NULL) {
374 if (debug_level > 5) {
375 print_memory_pool_stats();
378 config->free_resources();
383 term_msg(); /* terminate message handler */
385 close_memory_pool(); /* release free memory in pool */
391 struct RELOAD_TABLE {
396 static const int max_reloads = 32;
397 static RELOAD_TABLE reload_table[max_reloads];
399 static void init_reload(void)
401 for (int i=0; i < max_reloads; i++) {
402 reload_table[i].job_count = 0;
403 reload_table[i].res_table = NULL;
407 static void free_saved_resources(int table)
409 int num = r_last - r_first + 1;
410 RES **res_tab = reload_table[table].res_table;
412 Dmsg1(100, "res_tab for table %d already released.\n", table);
415 Dmsg1(100, "Freeing resources for table %d\n", table);
416 for (int j=0; j<num; j++) {
417 free_resource(res_tab[j], r_first + j);
420 reload_table[table].job_count = 0;
421 reload_table[table].res_table = NULL;
425 * Called here at the end of every job that was
426 * hooked decrementing the active job_count. When
427 * it goes to zero, no one is using the associated
428 * resource table, so free it.
430 static void reload_job_end_cb(JCR *jcr, void *ctx)
432 int reload_id = (int)((intptr_t)ctx);
433 Dmsg3(100, "reload job_end JobId=%d table=%d cnt=%d\n", jcr->JobId,
434 reload_id, reload_table[reload_id].job_count);
437 if (--reload_table[reload_id].job_count <= 0) {
438 free_saved_resources(reload_id);
444 static int find_free_reload_table_entry()
447 for (int i=0; i < max_reloads; i++) {
448 if (reload_table[i].res_table == NULL) {
457 * If we get here, we have received a SIGHUP, which means to
458 * reread our configuration file.
460 * The algorithm used is as follows: we count how many jobs are
461 * running and mark the running jobs to make a callback on
462 * exiting. The old config is saved with the reload table
463 * id in a reload table. The new config file is read. Now, as
464 * each job exits, it calls back to the reload_job_end_cb(), which
465 * decrements the count of open jobs for the given reload table.
466 * When the count goes to zero, we release those resources.
467 * This allows us to have pointers into the resource table (from
468 * jobs), and once they exit and all the pointers are released, we
469 * release the old table. Note, if no new jobs are running since the
470 * last reload, then the old resources will be immediately release.
471 * A console is considered a job because it may have pointers to
472 * resources, but a SYSTEM job is not since it *should* not have any
473 * permanent pointers to jobs.
476 void reload_config(int sig)
478 static bool already_here = false;
479 #if !defined(HAVE_WIN32)
483 int njobs = 0; /* number of running jobs */
488 abort(); /* Oops, recursion -> die */
492 #if !defined(HAVE_WIN32)
494 sigaddset(&set, SIGHUP);
495 sigprocmask(SIG_BLOCK, &set, NULL);
501 table = find_free_reload_table_entry();
503 Jmsg(NULL, M_ERROR, 0, _("Too many open reload requests. Request ignored.\n"));
507 Dmsg1(100, "Reload_config njobs=%d\n", njobs);
508 reload_table[table].res_table = config->save_resources();
509 Dmsg1(100, "Saved old config in table %d\n", table);
511 ok = parse_dir_config(config, configfile, M_ERROR);
513 Dmsg0(100, "Reloaded config file\n");
514 if (!ok || !check_resources() || !check_catalog(UPDATE_CATALOG)) {
515 rtable = find_free_reload_table_entry(); /* save new, bad table */
517 Jmsg(NULL, M_ERROR, 0, _("Please correct configuration file: %s\n"), configfile);
518 Jmsg(NULL, M_ERROR_TERM, 0, _("Out of reload table entries. Giving up.\n"));
520 Jmsg(NULL, M_ERROR, 0, _("Please correct configuration file: %s\n"), configfile);
521 Jmsg(NULL, M_ERROR, 0, _("Resetting previous configuration.\n"));
523 reload_table[rtable].res_table = config->save_resources();
524 /* Now restore old resource values */
525 int num = r_last - r_first + 1;
526 RES **res_tab = reload_table[table].res_table;
527 for (int i=0; i<num; i++) {
528 res_head[i] = res_tab[i];
530 table = rtable; /* release new, bad, saved table below */
532 invalidate_schedules();
534 * Hook all active jobs so that they release this table
537 if (jcr->getJobType() != JT_SYSTEM) {
538 reload_table[table].job_count++;
539 job_end_push(jcr, reload_job_end_cb, (void *)((long int)table));
547 set_working_directory(director->working_directory);
548 FDConnectTimeout = director->FDConnectTimeout;
549 SDConnectTimeout = director->SDConnectTimeout;
550 Dmsg0(10, "Director's configuration file reread.\n");
552 /* Now release saved resources, if no jobs using the resources */
554 free_saved_resources(table);
560 #if !defined(HAVE_WIN32)
561 sigprocmask(SIG_UNBLOCK, &set, NULL);
562 signal(SIGHUP, reload_config);
564 already_here = false;
568 * Make a quick check to see that we have all the
571 * **** FIXME **** this routine could be a lot more
572 * intelligent and comprehensive.
574 static bool check_resources()
582 job = (JOB *)GetNextRes(R_JOB, NULL);
583 director = (DIRRES *)GetNextRes(R_DIRECTOR, NULL);
585 Jmsg(NULL, M_FATAL, 0, _("No Director resource defined in %s\n"
586 "Without that I don't know who I am :-(\n"), configfile);
589 set_working_directory(director->working_directory);
590 if (!director->messages) { /* If message resource not specified */
591 director->messages = (MSGS *)GetNextRes(R_MSGS, NULL);
592 if (!director->messages) {
593 Jmsg(NULL, M_FATAL, 0, _("No Messages resource defined in %s\n"), configfile);
597 if (GetNextRes(R_DIRECTOR, (RES *)director) != NULL) {
598 Jmsg(NULL, M_FATAL, 0, _("Only one Director resource permitted in %s\n"),
602 /* tls_require implies tls_enable */
603 if (director->tls_require) {
605 director->tls_enable = true;
607 Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
612 need_tls = director->tls_enable || director->tls_authenticate;
614 if (!director->tls_certfile && need_tls) {
615 Jmsg(NULL, M_FATAL, 0, _("\"TLS Certificate\" file not defined for Director \"%s\" in %s.\n"),
616 director->name(), configfile);
620 if (!director->tls_keyfile && need_tls) {
621 Jmsg(NULL, M_FATAL, 0, _("\"TLS Key\" file not defined for Director \"%s\" in %s.\n"),
622 director->name(), configfile);
626 if ((!director->tls_ca_certfile && !director->tls_ca_certdir) &&
627 need_tls && director->tls_verify_peer) {
628 Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\" or \"TLS CA"
629 " Certificate Dir\" are defined for Director \"%s\" in %s."
630 " At least one CA certificate store is required"
631 " when using \"TLS Verify Peer\".\n"),
632 director->name(), configfile);
636 /* If everything is well, attempt to initialize our per-resource TLS context */
637 if (OK && (need_tls || director->tls_require)) {
638 /* Initialize TLS context:
639 * Args: CA certfile, CA certdir, Certfile, Keyfile,
640 * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
641 director->tls_ctx = new_tls_context(director->tls_ca_certfile,
642 director->tls_ca_certdir, director->tls_certfile,
643 director->tls_keyfile, NULL, NULL, director->tls_dhfile,
644 director->tls_verify_peer);
646 if (!director->tls_ctx) {
647 Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for Director \"%s\" in %s.\n"),
648 director->name(), configfile);
655 Jmsg(NULL, M_FATAL, 0, _("No Job records defined in %s\n"), configfile);
658 foreach_res(job, R_JOB) {
662 /* Handle Storage alists specifically */
663 JOB *jobdefs = job->jobdefs;
664 if (jobdefs->storage && !job->storage) {
666 job->storage = New(alist(10, not_owned_by_alist));
667 foreach_alist(st, jobdefs->storage) {
668 job->storage->append(st);
671 /* Handle RunScripts alists specifically */
672 if (jobdefs->RunScripts) {
675 if (!job->RunScripts) {
676 job->RunScripts = New(alist(10, not_owned_by_alist));
679 foreach_alist(rs, jobdefs->RunScripts) {
680 elt = copy_runscript(rs);
681 job->RunScripts->append(elt); /* we have to free it */
685 /* Transfer default items from JobDefs Resource */
686 for (i=0; job_items[i].name; i++) {
687 char **def_svalue, **svalue; /* string value */
688 uint32_t *def_ivalue, *ivalue; /* integer value */
689 bool *def_bvalue, *bvalue; /* bool value */
690 int64_t *def_lvalue, *lvalue; /* 64 bit values */
693 Dmsg4(1400, "Job \"%s\", field \"%s\" bit=%d def=%d\n",
694 job->name(), job_items[i].name,
695 bit_is_set(i, job->hdr.item_present),
696 bit_is_set(i, job->jobdefs->hdr.item_present));
698 if (!bit_is_set(i, job->hdr.item_present) &&
699 bit_is_set(i, job->jobdefs->hdr.item_present)) {
700 Dmsg2(400, "Job \"%s\", field \"%s\": getting default.\n",
701 job->name(), job_items[i].name);
702 offset = (char *)(job_items[i].value) - (char *)&res_all;
704 * Handle strings and directory strings
706 if (job_items[i].handler == store_str ||
707 job_items[i].handler == store_dir) {
708 def_svalue = (char **)((char *)(job->jobdefs) + offset);
709 Dmsg5(400, "Job \"%s\", field \"%s\" def_svalue=%s item %d offset=%u\n",
710 job->name(), job_items[i].name, *def_svalue, i, offset);
711 svalue = (char **)((char *)job + offset);
713 Pmsg1(000, _("Hey something is wrong. p=0x%lu\n"), *svalue);
715 *svalue = bstrdup(*def_svalue);
716 set_bit(i, job->hdr.item_present);
720 } else if (job_items[i].handler == store_res) {
721 def_svalue = (char **)((char *)(job->jobdefs) + offset);
722 Dmsg4(400, "Job \"%s\", field \"%s\" item %d offset=%u\n",
723 job->name(), job_items[i].name, i, offset);
724 svalue = (char **)((char *)job + offset);
726 Pmsg1(000, _("Hey something is wrong. p=0x%lu\n"), *svalue);
728 *svalue = *def_svalue;
729 set_bit(i, job->hdr.item_present);
731 * Handle alist resources
733 } else if (job_items[i].handler == store_alist_res) {
734 if (bit_is_set(i, job->jobdefs->hdr.item_present)) {
735 set_bit(i, job->hdr.item_present);
738 * Handle integer fields
739 * Note, our store_bit does not handle bitmaped fields
741 } else if (job_items[i].handler == store_bit ||
742 job_items[i].handler == store_pint32 ||
743 job_items[i].handler == store_jobtype ||
744 job_items[i].handler == store_level ||
745 job_items[i].handler == store_int32 ||
746 job_items[i].handler == store_size32 ||
747 job_items[i].handler == store_migtype ||
748 job_items[i].handler == store_replace) {
749 def_ivalue = (uint32_t *)((char *)(job->jobdefs) + offset);
750 Dmsg5(400, "Job \"%s\", field \"%s\" def_ivalue=%d item %d offset=%u\n",
751 job->name(), job_items[i].name, *def_ivalue, i, offset);
752 ivalue = (uint32_t *)((char *)job + offset);
753 *ivalue = *def_ivalue;
754 set_bit(i, job->hdr.item_present);
756 * Handle 64 bit integer fields
758 } else if (job_items[i].handler == store_time ||
759 job_items[i].handler == store_size64 ||
760 job_items[i].handler == store_int64) {
761 def_lvalue = (int64_t *)((char *)(job->jobdefs) + offset);
762 Dmsg5(400, "Job \"%s\", field \"%s\" def_lvalue=%" lld " item %d offset=%u\n",
763 job->name(), job_items[i].name, *def_lvalue, i, offset);
764 lvalue = (int64_t *)((char *)job + offset);
765 *lvalue = *def_lvalue;
766 set_bit(i, job->hdr.item_present);
770 } else if (job_items[i].handler == store_bool) {
771 def_bvalue = (bool *)((char *)(job->jobdefs) + offset);
772 Dmsg5(400, "Job \"%s\", field \"%s\" def_bvalue=%d item %d offset=%u\n",
773 job->name(), job_items[i].name, *def_bvalue, i, offset);
774 bvalue = (bool *)((char *)job + offset);
775 *bvalue = *def_bvalue;
776 set_bit(i, job->hdr.item_present);
782 * Ensure that all required items are present
784 for (i=0; job_items[i].name; i++) {
785 if (job_items[i].flags & ITEM_REQUIRED) {
786 if (!bit_is_set(i, job->hdr.item_present)) {
787 Jmsg(NULL, M_ERROR_TERM, 0, _("\"%s\" directive in Job \"%s\" resource is required, but not found.\n"),
788 job_items[i].name, job->name());
792 /* If this triggers, take a look at lib/parse_conf.h */
793 if (i >= MAX_RES_ITEMS) {
794 Emsg0(M_ERROR_TERM, 0, _("Too many items in Job resource\n"));
797 if (!job->storage && !job->pool->storage) {
798 Jmsg(NULL, M_FATAL, 0, _("No storage specified in Job \"%s\" nor in Pool.\n"),
802 } /* End loop over Job res */
805 /* Loop over Consoles */
807 foreach_res(cons, R_CONSOLE) {
808 /* tls_require implies tls_enable */
809 if (cons->tls_require) {
811 cons->tls_enable = true;
813 Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
819 need_tls = cons->tls_enable || cons->tls_authenticate;
821 if (!cons->tls_certfile && need_tls) {
822 Jmsg(NULL, M_FATAL, 0, _("\"TLS Certificate\" file not defined for Console \"%s\" in %s.\n"),
823 cons->name(), configfile);
827 if (!cons->tls_keyfile && need_tls) {
828 Jmsg(NULL, M_FATAL, 0, _("\"TLS Key\" file not defined for Console \"%s\" in %s.\n"),
829 cons->name(), configfile);
833 if ((!cons->tls_ca_certfile && !cons->tls_ca_certdir)
834 && need_tls && cons->tls_verify_peer) {
835 Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\" or \"TLS CA"
836 " Certificate Dir\" are defined for Console \"%s\" in %s."
837 " At least one CA certificate store is required"
838 " when using \"TLS Verify Peer\".\n"),
839 cons->name(), configfile);
842 /* If everything is well, attempt to initialize our per-resource TLS context */
843 if (OK && (need_tls || cons->tls_require)) {
844 /* Initialize TLS context:
845 * Args: CA certfile, CA certdir, Certfile, Keyfile,
846 * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
847 cons->tls_ctx = new_tls_context(cons->tls_ca_certfile,
848 cons->tls_ca_certdir, cons->tls_certfile,
849 cons->tls_keyfile, NULL, NULL, cons->tls_dhfile, cons->tls_verify_peer);
851 if (!cons->tls_ctx) {
852 Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for File daemon \"%s\" in %s.\n"),
853 cons->name(), configfile);
860 /* Loop over Clients */
862 foreach_res(client, R_CLIENT) {
863 /* tls_require implies tls_enable */
864 if (client->tls_require) {
866 client->tls_enable = true;
868 Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
873 need_tls = client->tls_enable || client->tls_authenticate;
874 if ((!client->tls_ca_certfile && !client->tls_ca_certdir) && need_tls) {
875 Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\""
876 " or \"TLS CA Certificate Dir\" are defined for File daemon \"%s\" in %s.\n"),
877 client->name(), configfile);
881 /* If everything is well, attempt to initialize our per-resource TLS context */
882 if (OK && (need_tls || client->tls_require)) {
883 /* Initialize TLS context:
884 * Args: CA certfile, CA certdir, Certfile, Keyfile,
885 * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
886 client->tls_ctx = new_tls_context(client->tls_ca_certfile,
887 client->tls_ca_certdir, client->tls_certfile,
888 client->tls_keyfile, NULL, NULL, NULL,
891 if (!client->tls_ctx) {
892 Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for File daemon \"%s\" in %s.\n"),
893 client->name(), configfile);
899 /* Loop over Storages */
901 foreach_res(store, R_STORAGE) {
902 /* tls_require implies tls_enable */
903 if (store->tls_require) {
905 store->tls_enable = true;
907 Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
913 need_tls = store->tls_enable || store->tls_authenticate;
915 if ((!store->tls_ca_certfile && !store->tls_ca_certdir) && need_tls) {
916 Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\""
917 " or \"TLS CA Certificate Dir\" are defined for Storage \"%s\" in %s.\n"),
918 store->name(), configfile);
922 /* If everything is well, attempt to initialize our per-resource TLS context */
923 if (OK && (need_tls || store->tls_require)) {
924 /* Initialize TLS context:
925 * Args: CA certfile, CA certdir, Certfile, Keyfile,
926 * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
927 store->tls_ctx = new_tls_context(store->tls_ca_certfile,
928 store->tls_ca_certdir, store->tls_certfile,
929 store->tls_keyfile, NULL, NULL, NULL, true);
931 if (!store->tls_ctx) {
932 Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for Storage \"%s\" in %s.\n"),
933 store->name(), configfile);
941 close_msg(NULL); /* close temp message handler */
942 init_msg(NULL, director->messages); /* open daemon message handler */
949 * - we can check the connection (mode=CHECK_CONNECTION)
950 * - we can synchronize the catalog with the configuration (mode=UPDATE_CATALOG)
951 * - we can synchronize, and fix old job records (mode=UPDATE_AND_FIX)
953 static bool check_catalog(cat_op mode)
957 /* Loop over databases */
959 foreach_res(catalog, R_CATALOG) {
962 * Make sure we can open catalog, otherwise print a warning
963 * message because the server is probably not running.
965 db = db_init_database(NULL, catalog->db_driver, catalog->db_name, catalog->db_user,
966 catalog->db_password, catalog->db_address,
967 catalog->db_port, catalog->db_socket,
968 catalog->mult_db_connections,
969 catalog->disable_batch_insert);
970 if (!db || !db_open_database(NULL, db)) {
971 Pmsg2(000, _("Could not open Catalog \"%s\", database \"%s\".\n"),
972 catalog->name(), catalog->db_name);
973 Jmsg(NULL, M_FATAL, 0, _("Could not open Catalog \"%s\", database \"%s\".\n"),
974 catalog->name(), catalog->db_name);
976 Jmsg(NULL, M_FATAL, 0, _("%s"), db_strerror(db));
977 Pmsg1(000, "%s", db_strerror(db));
978 db_close_database(NULL, db);
984 /* Display a message if the db max_connections is too low */
985 if (!db_check_max_connections(NULL, db, director->MaxConcurrentJobs)) {
986 Pmsg1(000, "Warning, settings problem for Catalog=%s\n", catalog->name());
987 Pmsg1(000, "%s", db_strerror(db));
990 /* we are in testing mode, so don't touch anything in the catalog */
991 if (mode == CHECK_CONNECTION) {
992 db_close_database(NULL, db);
996 /* Loop over all pools, defining/updating them in each database */
998 foreach_res(pool, R_POOL) {
1000 * If the Pool has a catalog resource create the pool only
1003 if (!pool->catalog || pool->catalog == catalog) {
1004 create_pool(NULL, db, pool, POOL_OP_UPDATE); /* update request */
1008 /* Once they are created, we can loop over them again, updating
1009 * references (RecyclePool)
1011 foreach_res(pool, R_POOL) {
1013 * If the Pool has a catalog resource update the pool only
1016 if (!pool->catalog || pool->catalog == catalog) {
1017 update_pool_references(NULL, db, pool);
1021 /* Ensure basic client record is in DB */
1023 foreach_res(client, R_CLIENT) {
1025 /* Create clients only if they use the current catalog */
1026 if (client->catalog != catalog) {
1027 Dmsg3(500, "Skip client=%s with cat=%s not catalog=%s\n",
1028 client->name(), client->catalog->name(), catalog->name());
1031 Dmsg2(500, "create cat=%s for client=%s\n",
1032 client->catalog->name(), client->name());
1033 memset(&cr, 0, sizeof(cr));
1034 bstrncpy(cr.Name, client->name(), sizeof(cr.Name));
1035 db_create_client_record(NULL, db, &cr);
1038 /* Ensure basic storage record is in DB */
1040 foreach_res(store, R_STORAGE) {
1043 memset(&sr, 0, sizeof(sr));
1044 memset(&mtr, 0, sizeof(mtr));
1045 if (store->media_type) {
1046 bstrncpy(mtr.MediaType, store->media_type, sizeof(mtr.MediaType));
1048 db_create_mediatype_record(NULL, db, &mtr);
1050 mtr.MediaTypeId = 0;
1052 bstrncpy(sr.Name, store->name(), sizeof(sr.Name));
1053 sr.AutoChanger = store->autochanger;
1054 if (!db_create_storage_record(NULL, db, &sr)) {
1055 Jmsg(NULL, M_FATAL, 0, _("Could not create storage record for %s\n"),
1059 store->StorageId = sr.StorageId; /* set storage Id */
1060 if (!sr.created) { /* if not created, update it */
1061 sr.AutoChanger = store->autochanger;
1062 if (!db_update_storage_record(NULL, db, &sr)) {
1063 Jmsg(NULL, M_FATAL, 0, _("Could not update storage record for %s\n"),
1070 /* Loop over all counters, defining them in each database */
1071 /* Set default value in all counters */
1073 foreach_res(counter, R_COUNTER) {
1074 /* Write to catalog? */
1075 if (!counter->created && counter->Catalog == catalog) {
1077 bstrncpy(cr.Counter, counter->name(), sizeof(cr.Counter));
1078 cr.MinValue = counter->MinValue;
1079 cr.MaxValue = counter->MaxValue;
1080 cr.CurrentValue = counter->MinValue;
1081 if (counter->WrapCounter) {
1082 bstrncpy(cr.WrapCounter, counter->WrapCounter->name(), sizeof(cr.WrapCounter));
1084 cr.WrapCounter[0] = 0; /* empty string */
1086 if (db_create_counter_record(NULL, db, &cr)) {
1087 counter->CurrentValue = cr.CurrentValue;
1088 counter->created = true;
1089 Dmsg2(100, "Create counter %s val=%d\n", counter->name(), counter->CurrentValue);
1092 if (!counter->created) {
1093 counter->CurrentValue = counter->MinValue; /* default value */
1096 /* cleanup old job records */
1097 if (mode == UPDATE_AND_FIX) {
1098 db_sql_query(db, cleanup_created_job, NULL, NULL);
1099 db_sql_query(db, cleanup_running_job, NULL, NULL);
1102 /* Set type in global for debugging */
1103 set_db_type(db_get_type(db));
1105 db_close_database(NULL, db);
1110 static void cleanup_old_files()
1113 struct dirent *entry, *result;
1115 int my_name_len = strlen(my_name);
1116 int len = strlen(director->working_directory);
1117 POOLMEM *cleanup = get_pool_memory(PM_MESSAGE);
1118 POOLMEM *basename = get_pool_memory(PM_MESSAGE);
1121 const int nmatch = 30;
1122 regmatch_t pmatch[nmatch];
1125 /* Exclude spaces and look for .mail or .restore.xx.bsr files */
1126 const char *pat1 = "^[^ ]+\\.(restore\\.[^ ]+\\.bsr|mail)$";
1128 /* Setup working directory prefix */
1129 pm_strcpy(basename, director->working_directory);
1130 if (len > 0 && !IsPathSeparator(director->working_directory[len-1])) {
1131 pm_strcat(basename, "/");
1134 /* Compile regex expressions */
1135 rc = regcomp(&preg1, pat1, REG_EXTENDED);
1137 regerror(rc, &preg1, prbuf, sizeof(prbuf));
1138 Pmsg2(000, _("Could not compile regex pattern \"%s\" ERR=%s\n"),
1143 name_max = pathconf(".", _PC_NAME_MAX);
1144 if (name_max < 1024) {
1148 if (!(dp = opendir(director->working_directory))) {
1150 Pmsg2(000, "Failed to open working dir %s for cleanup: ERR=%s\n",
1151 director->working_directory, be.bstrerror());
1156 entry = (struct dirent *)malloc(sizeof(struct dirent) + name_max + 1000);
1158 if ((readdir_r(dp, entry, &result) != 0) || (result == NULL)) {
1161 /* Exclude any name with ., .., not my_name or containing a space */
1162 if (strcmp(result->d_name, ".") == 0 || strcmp(result->d_name, "..") == 0 ||
1163 strncmp(result->d_name, my_name, my_name_len) != 0) {
1164 Dmsg1(500, "Skipped: %s\n", result->d_name);
1168 /* Unlink files that match regexes */
1169 if (regexec(&preg1, result->d_name, nmatch, pmatch, 0) == 0) {
1170 pm_strcpy(cleanup, basename);
1171 pm_strcat(cleanup, result->d_name);
1172 Dmsg1(100, "Unlink: %s\n", cleanup);
1179 /* Be careful to free up the correct resources */
1183 free_pool_memory(cleanup);
1184 free_pool_memory(basename);