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