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 (!test_config) { /* we don't need to do this block in test mode */
262 init_stack_dump(); /* grab new pid */
266 if (configfile == NULL) {
267 configfile = bstrdup(CONFIG_FILE);
270 config = new_config_parser();
271 parse_dir_config(config, configfile, M_ERROR_TERM);
273 if (init_crypto() != 0) {
274 Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Cryptography library initialization failed.\n"));
277 if (!check_resources()) {
278 Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
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));
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 */
294 load_dir_plugins(director->plugin_directory);
296 drop(uid, gid, false); /* reduce privileges if requested */
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;
301 if (!check_catalog(mode)) {
302 Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
309 my_name_is(0, NULL, director->name()); /* set user defined name */
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;
317 FDConnectTimeout = (int)director->FDConnectTimeout;
318 SDConnectTimeout = (int)director->SDConnectTimeout;
320 #if !defined(HAVE_WIN32)
321 signal(SIGHUP, reload_config);
324 init_console_msg(working_directory);
326 Dmsg0(200, "Start UA server\n");
327 start_UA_server(director->DIRaddrs);
329 start_watchdog(); /* start network watchdog thread */
331 init_jcr_subsystem(); /* start JCR watchdogs etc. */
333 init_job_server(director->MaxConcurrentJobs);
335 dbg_jcr_add_hook(db_debug_print); /* used to debug B_DB connexion after fatal signal */
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 */
353 /* Cleanup and then exit */
354 void terminate_dird(int sig)
356 static bool already_here = false;
358 if (already_here) { /* avoid recursive temination problems */
359 bmicrosleep(2, 0); /* yield */
363 debug_level = 0; /* turn off debug */
365 generate_daemon_event(NULL, "Exit");
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));
374 if (configfile != NULL) {
377 if (debug_level > 5) {
378 print_memory_pool_stats();
381 config->free_resources();
386 term_msg(); /* terminate message handler */
388 close_memory_pool(); /* release free memory in pool */
394 struct RELOAD_TABLE {
399 static const int max_reloads = 32;
400 static RELOAD_TABLE reload_table[max_reloads];
402 static void init_reload(void)
404 for (int i=0; i < max_reloads; i++) {
405 reload_table[i].job_count = 0;
406 reload_table[i].res_table = NULL;
410 static void free_saved_resources(int table)
412 int num = r_last - r_first + 1;
413 RES **res_tab = reload_table[table].res_table;
415 Dmsg1(100, "res_tab for table %d already released.\n", table);
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);
423 reload_table[table].job_count = 0;
424 reload_table[table].res_table = NULL;
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.
433 static void reload_job_end_cb(JCR *jcr, void *ctx)
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);
440 if (--reload_table[reload_id].job_count <= 0) {
441 free_saved_resources(reload_id);
447 static int find_free_reload_table_entry()
450 for (int i=0; i < max_reloads; i++) {
451 if (reload_table[i].res_table == NULL) {
460 * If we get here, we have received a SIGHUP, which means to
461 * reread our configuration file.
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.
479 void reload_config(int sig)
481 static bool already_here = false;
482 #if !defined(HAVE_WIN32)
486 int njobs = 0; /* number of running jobs */
491 abort(); /* Oops, recursion -> die */
495 #if !defined(HAVE_WIN32)
497 sigaddset(&set, SIGHUP);
498 sigprocmask(SIG_BLOCK, &set, NULL);
504 table = find_free_reload_table_entry();
506 Jmsg(NULL, M_ERROR, 0, _("Too many open reload requests. Request ignored.\n"));
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);
514 ok = parse_dir_config(config, configfile, M_ERROR);
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 */
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"));
523 Jmsg(NULL, M_ERROR, 0, _("Please correct configuration file: %s\n"), configfile);
524 Jmsg(NULL, M_ERROR, 0, _("Resetting previous configuration.\n"));
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];
533 table = rtable; /* release new, bad, saved table below */
535 invalidate_schedules();
537 * Hook all active jobs so that they release this table
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));
550 set_working_directory(director->working_directory);
551 FDConnectTimeout = director->FDConnectTimeout;
552 SDConnectTimeout = director->SDConnectTimeout;
553 Dmsg0(10, "Director's configuration file reread.\n");
555 /* Now release saved resources, if no jobs using the resources */
557 free_saved_resources(table);
563 #if !defined(HAVE_WIN32)
564 sigprocmask(SIG_UNBLOCK, &set, NULL);
565 signal(SIGHUP, reload_config);
567 already_here = false;
571 * Make a quick check to see that we have all the
574 * **** FIXME **** this routine could be a lot more
575 * intelligent and comprehensive.
577 static bool check_resources()
585 job = (JOB *)GetNextRes(R_JOB, NULL);
586 director = (DIRRES *)GetNextRes(R_DIRECTOR, NULL);
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);
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);
600 if (GetNextRes(R_DIRECTOR, (RES *)director) != NULL) {
601 Jmsg(NULL, M_FATAL, 0, _("Only one Director resource permitted in %s\n"),
605 /* tls_require implies tls_enable */
606 if (director->tls_require) {
608 director->tls_enable = true;
610 Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
615 need_tls = director->tls_enable || director->tls_authenticate;
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);
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);
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);
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);
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);
658 Jmsg(NULL, M_FATAL, 0, _("No Job records defined in %s\n"), configfile);
661 foreach_res(job, R_JOB) {
665 /* Handle Storage alists specifically */
666 JOB *jobdefs = job->jobdefs;
667 if (jobdefs->storage && !job->storage) {
669 job->storage = New(alist(10, not_owned_by_alist));
670 foreach_alist(st, jobdefs->storage) {
671 job->storage->append(st);
674 /* Handle RunScripts alists specifically */
675 if (jobdefs->RunScripts) {
678 if (!job->RunScripts) {
679 job->RunScripts = New(alist(10, not_owned_by_alist));
682 foreach_alist(rs, jobdefs->RunScripts) {
683 elt = copy_runscript(rs);
684 job->RunScripts->append(elt); /* we have to free it */
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 */
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));
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;
707 * Handle strings and directory strings
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);
716 Pmsg1(000, _("Hey something is wrong. p=0x%lu\n"), *svalue);
718 *svalue = bstrdup(*def_svalue);
719 set_bit(i, job->hdr.item_present);
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);
729 Pmsg1(000, _("Hey something is wrong. p=0x%lu\n"), *svalue);
731 *svalue = *def_svalue;
732 set_bit(i, job->hdr.item_present);
734 * Handle alist resources
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);
741 * Handle integer fields
742 * Note, our store_bit does not handle bitmaped fields
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);
759 * Handle 64 bit integer fields
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);
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);
785 * Ensure that all required items are present
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());
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"));
800 if (!job->storage && !job->pool->storage) {
801 Jmsg(NULL, M_FATAL, 0, _("No storage specified in Job \"%s\" nor in Pool.\n"),
805 } /* End loop over Job res */
808 /* Loop over Consoles */
810 foreach_res(cons, R_CONSOLE) {
811 /* tls_require implies tls_enable */
812 if (cons->tls_require) {
814 cons->tls_enable = true;
816 Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
822 need_tls = cons->tls_enable || cons->tls_authenticate;
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);
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);
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);
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);
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);
863 /* Loop over Clients */
865 foreach_res(client, R_CLIENT) {
866 /* tls_require implies tls_enable */
867 if (client->tls_require) {
869 client->tls_enable = true;
871 Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
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);
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,
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);
902 /* Loop over Storages */
904 foreach_res(store, R_STORAGE) {
905 /* tls_require implies tls_enable */
906 if (store->tls_require) {
908 store->tls_enable = true;
910 Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
916 need_tls = store->tls_enable || store->tls_authenticate;
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);
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);
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);
944 close_msg(NULL); /* close temp message handler */
945 init_msg(NULL, director->messages); /* open daemon message handler */
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)
956 static bool check_catalog(cat_op mode)
960 /* Loop over databases */
962 foreach_res(catalog, R_CATALOG) {
965 * Make sure we can open catalog, otherwise print a warning
966 * message because the server is probably not running.
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);
979 Jmsg(NULL, M_FATAL, 0, _("%s"), db_strerror(db));
980 Pmsg1(000, "%s", db_strerror(db));
981 db_close_database(NULL, db);
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));
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);
999 /* Loop over all pools, defining/updating them in each database */
1001 foreach_res(pool, R_POOL) {
1003 * If the Pool has a catalog resource create the pool only
1006 if (!pool->catalog || pool->catalog == catalog) {
1007 create_pool(NULL, db, pool, POOL_OP_UPDATE); /* update request */
1011 /* Once they are created, we can loop over them again, updating
1012 * references (RecyclePool)
1014 foreach_res(pool, R_POOL) {
1016 * If the Pool has a catalog resource update the pool only
1019 if (!pool->catalog || pool->catalog == catalog) {
1020 update_pool_references(NULL, db, pool);
1024 /* Ensure basic client record is in DB */
1026 foreach_res(client, R_CLIENT) {
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());
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);
1041 /* Ensure basic storage record is in DB */
1043 foreach_res(store, R_STORAGE) {
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));
1051 db_create_mediatype_record(NULL, db, &mtr);
1053 mtr.MediaTypeId = 0;
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"),
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"),
1073 /* Loop over all counters, defining them in each database */
1074 /* Set default value in all counters */
1076 foreach_res(counter, R_COUNTER) {
1077 /* Write to catalog? */
1078 if (!counter->created && counter->Catalog == catalog) {
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));
1087 cr.WrapCounter[0] = 0; /* empty string */
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);
1095 if (!counter->created) {
1096 counter->CurrentValue = counter->MinValue; /* default value */
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);
1105 /* Set type in global for debugging */
1106 set_db_type(db_get_type(db));
1108 db_close_database(NULL, db);
1113 static void cleanup_old_files()
1116 struct dirent *entry, *result;
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);
1124 const int nmatch = 30;
1125 regmatch_t pmatch[nmatch];
1128 /* Exclude spaces and look for .mail or .restore.xx.bsr files */
1129 const char *pat1 = "^[^ ]+\\.(restore\\.[^ ]+\\.bsr|mail)$";
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, "/");
1137 /* Compile regex expressions */
1138 rc = regcomp(&preg1, pat1, REG_EXTENDED);
1140 regerror(rc, &preg1, prbuf, sizeof(prbuf));
1141 Pmsg2(000, _("Could not compile regex pattern \"%s\" ERR=%s\n"),
1146 name_max = pathconf(".", _PC_NAME_MAX);
1147 if (name_max < 1024) {
1151 if (!(dp = opendir(director->working_directory))) {
1153 Pmsg2(000, "Failed to open working dir %s for cleanup: ERR=%s\n",
1154 director->working_directory, be.bstrerror());
1159 entry = (struct dirent *)malloc(sizeof(struct dirent) + name_max + 1000);
1161 if ((readdir_r(dp, entry, &result) != 0) || (result == NULL)) {
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);
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);
1182 /* Be careful to free up the correct resources */
1186 free_pool_memory(cleanup);
1187 free_pool_memory(basename);