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