]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/dird.c
Backport from BEE
[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 (configfile == NULL) {
260       configfile = bstrdup(CONFIG_FILE);
261    }
262
263    config = new_config_parser();
264    parse_dir_config(config, configfile, M_ERROR_TERM);
265
266    if (init_crypto() != 0) {
267       Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Cryptography library initialization failed.\n"));
268    }
269
270    if (!check_resources()) {
271       Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
272    }
273
274    if (!test_config) {                /* we don't need to do this block in test mode */
275       if (background) {
276          daemon_start();
277          init_stack_dump();              /* grab new pid */
278       }
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));
284    }
285
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 */
290
291    load_dir_plugins(director->plugin_directory);
292
293    drop(uid, gid, false);                    /* reduce privileges if requested */
294
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;
297
298    if (!check_catalog(mode)) {
299       Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
300    }
301
302    if (test_config) {
303       terminate_dird(0);
304    }
305
306    my_name_is(0, NULL, director->name());    /* set user defined name */
307
308    cleanup_old_files();
309
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;
313
314    FDConnectTimeout = (int)director->FDConnectTimeout;
315    SDConnectTimeout = (int)director->SDConnectTimeout;
316
317 #if !defined(HAVE_WIN32)
318    signal(SIGHUP, reload_config);
319 #endif
320
321    init_console_msg(working_directory);
322
323    Dmsg0(200, "Start UA server\n");
324    start_UA_server(director->DIRaddrs);
325
326    start_watchdog();                  /* start network watchdog thread */
327
328    init_jcr_subsystem();              /* start JCR watchdogs etc. */
329
330    init_job_server(director->MaxConcurrentJobs);
331
332    dbg_jcr_add_hook(db_debug_print); /* used to debug B_DB connexion after fatal signal */
333
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 */
342       }
343    }
344
345    terminate_dird(0);
346
347    return 0;
348 }
349
350 /* Cleanup and then exit */
351 void terminate_dird(int sig)
352 {
353    static bool already_here = false;
354
355    if (already_here) {                /* avoid recursive temination problems */
356       bmicrosleep(2, 0);              /* yield */
357       exit(1);
358    }
359    already_here = true;
360    debug_level = 0;                   /* turn off debug */
361    stop_watchdog();
362    generate_daemon_event(NULL, "Exit");
363    unload_plugins();
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));
366    term_scheduler();
367    term_job_server();
368    if (runjob) {
369       free(runjob);
370    }
371    if (configfile != NULL) {
372       free(configfile);
373    }
374    if (debug_level > 5) {
375       print_memory_pool_stats();
376    }
377    if (config) {
378       config->free_resources();
379       free(config);
380       config = NULL;
381    }
382    term_ua_server();
383    term_msg();                        /* terminate message handler */
384    cleanup_crypto();
385    close_memory_pool();               /* release free memory in pool */
386    lmgr_cleanup_main();
387    sm_dump(false);
388    exit(sig);
389 }
390
391 struct RELOAD_TABLE {
392    int job_count;
393    RES **res_table;
394 };
395
396 static const int max_reloads = 32;
397 static RELOAD_TABLE reload_table[max_reloads];
398
399 static void init_reload(void)
400 {
401    for (int i=0; i < max_reloads; i++) {
402       reload_table[i].job_count = 0;
403       reload_table[i].res_table = NULL;
404    }
405 }
406
407 static void free_saved_resources(int table)
408 {
409    int num = r_last - r_first + 1;
410    RES **res_tab = reload_table[table].res_table;
411    if (!res_tab) {
412       Dmsg1(100, "res_tab for table %d already released.\n", table);
413       return;
414    }
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);
418    }
419    free(res_tab);
420    reload_table[table].job_count = 0;
421    reload_table[table].res_table = NULL;
422 }
423
424 /*
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.
429  */
430 static void reload_job_end_cb(JCR *jcr, void *ctx)
431 {
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);
435    lock_jobs();
436    LockRes();
437    if (--reload_table[reload_id].job_count <= 0) {
438       free_saved_resources(reload_id);
439    }
440    UnlockRes();
441    unlock_jobs();
442 }
443
444 static int find_free_reload_table_entry()
445 {
446    int table = -1;
447    for (int i=0; i < max_reloads; i++) {
448       if (reload_table[i].res_table == NULL) {
449          table = i;
450          break;
451       }
452    }
453    return table;
454 }
455
456 /*
457  * If we get here, we have received a SIGHUP, which means to
458  *    reread our configuration file.
459  *
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.
474  */
475 extern "C"
476 void reload_config(int sig)
477 {
478    static bool already_here = false;
479 #if !defined(HAVE_WIN32)
480    sigset_t set;
481 #endif
482    JCR *jcr;
483    int njobs = 0;                     /* number of running jobs */
484    int table, rtable;
485    bool ok;
486
487    if (already_here) {
488       abort();                        /* Oops, recursion -> die */
489    }
490    already_here = true;
491
492 #if !defined(HAVE_WIN32)
493    sigemptyset(&set);
494    sigaddset(&set, SIGHUP);
495    sigprocmask(SIG_BLOCK, &set, NULL);
496 #endif
497
498    lock_jobs();
499    LockRes();
500
501    table = find_free_reload_table_entry();
502    if (table < 0) {
503       Jmsg(NULL, M_ERROR, 0, _("Too many open reload requests. Request ignored.\n"));
504       goto bail_out;
505    }
506
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);
510
511    ok = parse_dir_config(config, configfile, M_ERROR);
512
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 */
516       if (rtable < 0) {
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"));
519       } else {
520          Jmsg(NULL, M_ERROR, 0, _("Please correct configuration file: %s\n"), configfile);
521          Jmsg(NULL, M_ERROR, 0, _("Resetting previous configuration.\n"));
522       }
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];
529       }
530       table = rtable;                 /* release new, bad, saved table below */
531    } else {
532       invalidate_schedules();
533       /*
534        * Hook all active jobs so that they release this table
535        */
536       foreach_jcr(jcr) {
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));
540             njobs++;
541          }
542       }
543       endeach_jcr(jcr);
544    }
545
546    /* Reset globals */
547    set_working_directory(director->working_directory);
548    FDConnectTimeout = director->FDConnectTimeout;
549    SDConnectTimeout = director->SDConnectTimeout;
550    Dmsg0(10, "Director's configuration file reread.\n");
551
552    /* Now release saved resources, if no jobs using the resources */
553    if (njobs == 0) {
554       free_saved_resources(table);
555    }
556
557 bail_out:
558    UnlockRes();
559    unlock_jobs();
560 #if !defined(HAVE_WIN32)
561    sigprocmask(SIG_UNBLOCK, &set, NULL);
562    signal(SIGHUP, reload_config);
563 #endif
564    already_here = false;
565 }
566
567 /*
568  * Make a quick check to see that we have all the
569  * resources needed.
570  *
571  *  **** FIXME **** this routine could be a lot more
572  *   intelligent and comprehensive.
573  */
574 static bool check_resources()
575 {
576    bool OK = true;
577    JOB *job;
578    bool need_tls;
579
580    LockRes();
581
582    job = (JOB *)GetNextRes(R_JOB, NULL);
583    director = (DIRRES *)GetNextRes(R_DIRECTOR, NULL);
584    if (!director) {
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);
587       OK = false;
588    } else {
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);
594             OK = false;
595          }
596       }
597       if (GetNextRes(R_DIRECTOR, (RES *)director) != NULL) {
598          Jmsg(NULL, M_FATAL, 0, _("Only one Director resource permitted in %s\n"),
599             configfile);
600          OK = false;
601       }
602       /* tls_require implies tls_enable */
603       if (director->tls_require) {
604          if (have_tls) {
605             director->tls_enable = true;
606          } else {
607             Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
608             OK = false;
609          }
610       }
611
612       need_tls = director->tls_enable || director->tls_authenticate;
613
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);
617          OK = false;
618       }
619
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);
623          OK = false;
624       }
625
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);
633          OK = false;
634       }
635
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);
645
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);
649             OK = false;
650          }
651       }
652    }
653
654    if (!job) {
655       Jmsg(NULL, M_FATAL, 0, _("No Job records defined in %s\n"), configfile);
656       OK = false;
657    }
658    foreach_res(job, R_JOB) {
659       int i;
660
661       if (job->jobdefs) {
662          /* Handle Storage alists specifically */
663          JOB *jobdefs = job->jobdefs;
664          if (jobdefs->storage && !job->storage) {
665             STORE *st;
666             job->storage = New(alist(10, not_owned_by_alist));
667             foreach_alist(st, jobdefs->storage) {
668                job->storage->append(st);
669             }
670          }
671          /* Handle RunScripts alists specifically */
672          if (jobdefs->RunScripts) {
673             RUNSCRIPT *rs, *elt;
674
675             if (!job->RunScripts) {
676                job->RunScripts = New(alist(10, not_owned_by_alist));
677             }
678
679             foreach_alist(rs, jobdefs->RunScripts) {
680                elt = copy_runscript(rs);
681                job->RunScripts->append(elt); /* we have to free it */
682             }
683          }
684
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 */
691             uint32_t offset;
692
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));
697
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;
703                /*
704                 * Handle strings and directory strings
705                 */
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);
712                   if (*svalue) {
713                      Pmsg1(000, _("Hey something is wrong. p=0x%lu\n"), *svalue);
714                   }
715                   *svalue = bstrdup(*def_svalue);
716                   set_bit(i, job->hdr.item_present);
717                /*
718                 * Handle resources
719                 */
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);
725                   if (*svalue) {
726                      Pmsg1(000, _("Hey something is wrong. p=0x%lu\n"), *svalue);
727                   }
728                   *svalue = *def_svalue;
729                   set_bit(i, job->hdr.item_present);
730                /*
731                 * Handle alist resources
732                 */
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);
736                   }
737                /*
738                 * Handle integer fields
739                 *    Note, our store_bit does not handle bitmaped fields
740                 */
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);
755                /*
756                 * Handle 64 bit integer fields
757                 */
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);
767                /*
768                 * Handle bool fields
769                 */
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);
777                }
778             }
779          }
780       }
781       /*
782        * Ensure that all required items are present
783        */
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());
789                   OK = false;
790                 }
791          }
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"));
795          }
796       }
797       if (!job->storage && !job->pool->storage) {
798          Jmsg(NULL, M_FATAL, 0, _("No storage specified in Job \"%s\" nor in Pool.\n"),
799             job->name());
800          OK = false;
801       }
802    } /* End loop over Job res */
803
804
805    /* Loop over Consoles */
806    CONRES *cons;
807    foreach_res(cons, R_CONSOLE) {
808       /* tls_require implies tls_enable */
809       if (cons->tls_require) {
810          if (have_tls) {
811             cons->tls_enable = true;
812          } else {
813             Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
814             OK = false;
815             continue;
816          }
817       }
818
819       need_tls = cons->tls_enable || cons->tls_authenticate;
820
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);
824          OK = false;
825       }
826
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);
830          OK = false;
831       }
832
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);
840          OK = false;
841       }
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);
850
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);
854             OK = false;
855          }
856       }
857
858    }
859
860    /* Loop over Clients */
861    CLIENT *client;
862    foreach_res(client, R_CLIENT) {
863       /* tls_require implies tls_enable */
864       if (client->tls_require) {
865          if (have_tls) {
866             client->tls_enable = true;
867          } else {
868             Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
869             OK = false;
870             continue;
871          }
872       }
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);
878          OK = false;
879       }
880
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,
889             true);
890
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);
894             OK = false;
895          }
896       }
897    }
898
899    /* Loop over Storages */
900    STORE *store;
901    foreach_res(store, R_STORAGE) {
902       /* tls_require implies tls_enable */
903       if (store->tls_require) {
904          if (have_tls) {
905             store->tls_enable = true;
906          } else {
907             Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
908             OK = false;
909             continue;
910          }
911       }
912
913       need_tls = store->tls_enable || store->tls_authenticate;
914
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);
919          OK = false;
920       }
921
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);
930
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);
934             OK = false;
935          }
936       }
937    }
938
939    UnlockRes();
940    if (OK) {
941       close_msg(NULL);                /* close temp message handler */
942       init_msg(NULL, director->messages); /* open daemon message handler */
943    }
944    return OK;
945 }
946
947 /*
948  * In this routine,
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)
952  */
953 static bool check_catalog(cat_op mode)
954 {
955    bool OK = true;
956
957    /* Loop over databases */
958    CAT *catalog;
959    foreach_res(catalog, R_CATALOG) {
960       B_DB *db;
961       /*
962        * Make sure we can open catalog, otherwise print a warning
963        * message because the server is probably not running.
964        */
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);
975          if (db) {
976             Jmsg(NULL, M_FATAL, 0, _("%s"), db_strerror(db));
977             Pmsg1(000, "%s", db_strerror(db));
978             db_close_database(NULL, db);
979          }
980          OK = false;
981          continue;
982       }
983
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));
988       }
989
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);
993          continue;
994       }
995
996       /* Loop over all pools, defining/updating them in each database */
997       POOL *pool;
998       foreach_res(pool, R_POOL) {
999          /*
1000           * If the Pool has a catalog resource create the pool only
1001           *   in that catalog.
1002           */
1003          if (!pool->catalog || pool->catalog == catalog) {
1004             create_pool(NULL, db, pool, POOL_OP_UPDATE);  /* update request */
1005          }
1006       }
1007
1008       /* Once they are created, we can loop over them again, updating
1009        * references (RecyclePool)
1010        */
1011       foreach_res(pool, R_POOL) {
1012          /*
1013           * If the Pool has a catalog resource update the pool only
1014           *   in that catalog.
1015           */
1016          if (!pool->catalog || pool->catalog == catalog) {
1017             update_pool_references(NULL, db, pool);
1018          }
1019       }
1020
1021       /* Ensure basic client record is in DB */
1022       CLIENT *client;
1023       foreach_res(client, R_CLIENT) {
1024          CLIENT_DBR cr;
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());
1029             continue;
1030          }
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);
1036       }
1037
1038       /* Ensure basic storage record is in DB */
1039       STORE *store;
1040       foreach_res(store, R_STORAGE) {
1041          STORAGE_DBR sr;
1042          MEDIATYPE_DBR mtr;
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));
1047             mtr.ReadOnly = 0;
1048             db_create_mediatype_record(NULL, db, &mtr);
1049          } else {
1050             mtr.MediaTypeId = 0;
1051          }
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"),
1056                  store->name());
1057             OK = false;
1058          }
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"),
1064                     store->name());
1065                OK = false;
1066             }
1067          }
1068       }
1069
1070       /* Loop over all counters, defining them in each database */
1071       /* Set default value in all counters */
1072       COUNTER *counter;
1073       foreach_res(counter, R_COUNTER) {
1074          /* Write to catalog? */
1075          if (!counter->created && counter->Catalog == catalog) {
1076             COUNTER_DBR cr;
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));
1083             } else {
1084                cr.WrapCounter[0] = 0;  /* empty string */
1085             }
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);
1090             }
1091          }
1092          if (!counter->created) {
1093             counter->CurrentValue = counter->MinValue;  /* default value */
1094          }
1095       }
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);
1100       }
1101
1102       /* Set type in global for debugging */
1103       set_db_type(db_get_type(db));
1104
1105       db_close_database(NULL, db);
1106    }
1107    return OK;
1108 }
1109
1110 static void cleanup_old_files()
1111 {
1112    DIR* dp;
1113    struct dirent *entry, *result;
1114    int rc, name_max;
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);
1119    regex_t preg1;
1120    char prbuf[500];
1121    const int nmatch = 30;
1122    regmatch_t pmatch[nmatch];
1123    berrno be;
1124
1125    /* Exclude spaces and look for .mail or .restore.xx.bsr files */
1126    const char *pat1 = "^[^ ]+\\.(restore\\.[^ ]+\\.bsr|mail)$";
1127
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, "/");
1132    }
1133
1134    /* Compile regex expressions */
1135    rc = regcomp(&preg1, pat1, REG_EXTENDED);
1136    if (rc != 0) {
1137       regerror(rc, &preg1, prbuf, sizeof(prbuf));
1138       Pmsg2(000,  _("Could not compile regex pattern \"%s\" ERR=%s\n"),
1139            pat1, prbuf);
1140       goto get_out2;
1141    }
1142
1143    name_max = pathconf(".", _PC_NAME_MAX);
1144    if (name_max < 1024) {
1145       name_max = 1024;
1146    }
1147
1148    if (!(dp = opendir(director->working_directory))) {
1149       berrno be;
1150       Pmsg2(000, "Failed to open working dir %s for cleanup: ERR=%s\n",
1151             director->working_directory, be.bstrerror());
1152       goto get_out1;
1153       return;
1154    }
1155
1156    entry = (struct dirent *)malloc(sizeof(struct dirent) + name_max + 1000);
1157    while (1) {
1158       if ((readdir_r(dp, entry, &result) != 0) || (result == NULL)) {
1159          break;
1160       }
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);
1165          continue;
1166       }
1167
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);
1173          unlink(cleanup);
1174       }
1175    }
1176
1177    free(entry);
1178    closedir(dp);
1179 /* Be careful to free up the correct resources */
1180 get_out1:
1181    regfree(&preg1);
1182 get_out2:
1183    free_pool_memory(cleanup);
1184    free_pool_memory(basename);
1185 }