]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/dird/dird.c
Backport Enterprise code
[bacula/bacula] / bacula / src / dird / dird.c
1 /*
2    Bacula(R) - The Network Backup Solution
3
4    Copyright (C) 2000-2017 Kern Sibbald
5
6    The original author of Bacula is Kern Sibbald, with contributions
7    from many others, a complete list can be found in the file AUTHORS.
8
9    You may use this file and others of this release according to the
10    license defined in the LICENSE file, which includes the Affero General
11    Public License, v3.0 ("AGPLv3") and some additional permissions and
12    terms pursuant to its AGPLv3 Section 7.
13
14    This notice must be preserved when any source code is
15    conveyed and/or propagated.
16
17    Bacula(R) is a registered trademark of Kern Sibbald.
18 */
19 /*
20  *   Bacula Director daemon -- this is the main program
21  *
22  *     Kern Sibbald, March MM
23  */
24
25 #include "bacula.h"
26 #include "dird.h"
27 #ifndef HAVE_REGEX_H
28 #include "lib/bregex.h"
29 #else
30 #include <regex.h>
31 #endif
32 #ifdef HAVE_DIRENT_H
33 #include <dirent.h>
34 #define NAMELEN(dirent) (strlen((dirent)->d_name))
35 #endif
36 #ifndef HAVE_READDIR_R
37 int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result);
38 #endif
39
40 /* Forward referenced subroutines */
41 void terminate_dird(int sig);
42 static bool check_resources();
43 static void cleanup_old_files();
44 static void resize_reload(int nb);
45
46 /* Exported subroutines */
47 extern "C" void reload_config(int sig);
48 extern void invalidate_schedules();
49 extern bool parse_dir_config(CONFIG *config, const char *configfile, int exit_code);
50
51 /* Imported subroutines */
52 JCR *wait_for_next_job(char *runjob);
53 void term_scheduler();
54 void term_ua_server();
55 void start_UA_server(dlist *addrs);
56 void init_job_server(int max_workers);
57 void term_job_server();
58 void store_jobtype(LEX *lc, RES_ITEM *item, int index, int pass);
59 void store_level(LEX *lc, RES_ITEM *item, int index, int pass);
60 void store_replace(LEX *lc, RES_ITEM *item, int index, int pass);
61 void store_migtype(LEX *lc, RES_ITEM *item, int index, int pass);
62 void init_device_resources();
63
64
65 static char *runjob = NULL;
66 static bool foreground = false;
67 static void init_reload(void);
68 static CONFIG *config;
69 static bool test_config = false;
70
71 /* Globals Exported */
72 DIRRES *director;                     /* Director resource */
73 int FDConnectTimeout;
74 int SDConnectTimeout;
75 char *configfile = NULL;
76 void *start_heap;
77 utime_t last_reload_time = 0;
78
79
80 /* Globals Imported */
81 extern dlist client_globals;
82 extern dlist store_globals;
83 extern dlist job_globals;
84 extern dlist sched_globals;
85 extern RES_ITEM job_items[];
86 #if defined(_MSC_VER)
87 extern "C" { // work around visual compiler mangling variables
88    extern URES res_all;
89 }
90 #else
91 extern URES res_all;
92 #endif
93
94 typedef enum {
95    CHECK_CONNECTION,  /* Check catalog connection */
96    UPDATE_CATALOG,    /* Ensure that catalog is ok with conf */
97    UPDATE_AND_FIX     /* Ensure that catalog is ok, and fix old jobs */
98 } cat_op;
99 static bool check_catalog(cat_op mode);
100
101 #define CONFIG_FILE "bacula-dir.conf" /* default configuration file */
102
103 static bool dir_sql_query(JCR *jcr, const char *cmd) 
104
105    if (jcr && jcr->db && jcr->db->is_connected()) {
106       return db_sql_query(jcr->db, cmd, NULL, NULL);
107    } 
108    return false; 
109
110
111 static bool dir_sql_escape(JCR *jcr, BDB *mdb, char *snew, char *sold, int len) 
112
113    if (jcr && jcr->db && jcr->db->is_connected()) { 
114       db_escape_string(jcr, mdb, snew, sold, len);
115       return true;
116    } 
117    return false; 
118
119
120 static void usage()
121 {
122    fprintf(stderr, _(
123       PROG_COPYRIGHT
124       "\n%sVersion: %s (%s)\n\n"
125       "Usage: bacula-dir [-f -s] [-c config_file] [-d debug_level] [config_file]\n"
126       "     -c <file>        set configuration file to file\n"
127       "     -d <nn>[,<tags>] set debug level to <nn>, debug tags to <tags>\n"
128       "     -dt              print timestamp in debug output\n"
129       "     -T               set trace on\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  * !!! WARNING !!! Use this function only when bacula is stopped.
146  * ie, after a fatal signal and before exiting the program
147  * Print information about a JCR
148  */
149 static void dir_debug_print(JCR *jcr, FILE *fp)
150 {
151    fprintf(fp, "\twstore=%p rstore=%p wjcr=%p client=%p reschedule_count=%d SD_msg_chan_started=%d\n",
152            jcr->wstore, jcr->rstore, jcr->wjcr, jcr->client, jcr->reschedule_count, (int)jcr->SD_msg_chan_started);
153 }
154
155 /*********************************************************************
156  *
157  *         Main Bacula Director Server program
158  *
159  */
160 #if defined(HAVE_WIN32)
161 /* For Win32 main() is in src/win32 code ... */
162 #define main BaculaMain
163 #endif
164
165 /* DELETE ME when bugs in MA1512, MA1632 MA1639 are fixed */
166 extern void (*MA1512_reload_job_end_cb)(JCR *,void *);
167 static void reload_job_end_cb(JCR *jcr, void *ctx);
168
169 int main (int argc, char *argv[])
170 {
171    int ch;
172    JCR *jcr;
173    bool no_signals = false;
174    char *uid = NULL;
175    char *gid = NULL;
176
177    /* DELETE ME when bugs in MA1512, MA1632 MA1639 are fixed */
178    MA1512_reload_job_end_cb = reload_job_end_cb;
179
180    start_heap = sbrk(0);
181    setlocale(LC_ALL, "");
182    bindtextdomain("bacula", LOCALEDIR);
183    textdomain("bacula");
184
185    init_stack_dump();
186    my_name_is(argc, argv, "bacula-dir");
187    init_msg(NULL, NULL);              /* initialize message handler */
188    init_reload();
189    daemon_start_time = time(NULL);
190    setup_daemon_message_queue();
191    console_command = run_console_command;
192
193    while ((ch = getopt(argc, argv, "c:d:fg:mr:stu:v?T")) != -1) {
194       switch (ch) {
195       case 'c':                    /* specify config file */
196          if (configfile != NULL) {
197             free(configfile);
198          }
199          configfile = bstrdup(optarg);
200          break;
201
202       case 'd':                    /* set debug level */
203          if (*optarg == 't') {
204             dbg_timestamp = true;
205          } else {
206             char *p;
207             /* We probably find a tag list -d 10,sql,bvfs */
208             if ((p = strchr(optarg, ',')) != NULL) {
209                *p = 0;
210             }
211             debug_level = atoi(optarg);
212             if (debug_level <= 0) {
213                debug_level = 1;
214             }
215             if (p) {
216                debug_parse_tags(p+1, &debug_level_tags);
217             }
218          }
219          Dmsg1(10, "Debug level = %lld\n", debug_level);
220          break;
221
222       case 'T':
223          set_trace(true);
224          break;
225
226       case 'f':                    /* run in foreground */
227          foreground = true;
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 (argc) {
273       if (configfile != NULL) {
274          free(configfile);
275       }
276       configfile = bstrdup(*argv);
277       argc--;
278       argv++;
279    }
280    if (argc) {
281       usage();
282    }
283
284    if (!foreground && !test_config) {
285       daemon_start();
286       init_stack_dump();              /* grab new pid */
287    }
288
289    if (!no_signals) {
290       init_signals(terminate_dird);
291    }
292
293    if (configfile == NULL) {
294       configfile = bstrdup(CONFIG_FILE);
295    }
296
297    config = New(CONFIG());
298    parse_dir_config(config, configfile, M_ERROR_TERM);
299
300    if (init_crypto() != 0) {
301       Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Cryptography library initialization failed.\n"));
302    }
303
304    if (!check_resources()) {
305       Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
306    }
307
308    if (!test_config) {
309       /* Create pid must come after we are a daemon -- so we have our final pid */
310       create_pid_file(director->pid_directory, "bacula-dir",
311                       get_first_port_host_order(director->DIRaddrs));
312       read_state_file(director->working_directory, "bacula-dir",
313                       get_first_port_host_order(director->DIRaddrs));
314    }
315
316    set_jcr_in_tsd(INVALID_JCR);
317    set_thread_concurrency(director->MaxConcurrentJobs * 2 +
318                           4 /* UA */ + 5 /* sched+watchdog+jobsvr+misc */);
319    lmgr_init_thread(); /* initialize the lockmanager stack */
320
321    load_dir_plugins(director->plugin_directory);
322
323    drop(uid, gid, false);                    /* reduce privileges if requested */
324
325    /* If we are in testing mode, we don't try to fix the catalog */
326    cat_op mode=(test_config)?CHECK_CONNECTION:UPDATE_AND_FIX;
327
328    if (!check_catalog(mode)) {
329       Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
330    }
331
332    if (test_config) {
333       terminate_dird(0);
334    }
335
336    my_name_is(0, NULL, director->name());    /* set user defined name */
337
338    cleanup_old_files();
339
340    /* Plug database interface for library routines */
341    p_sql_query = (sql_query_call)dir_sql_query;
342    p_sql_escape = (sql_escape_call)dir_sql_escape;
343
344    FDConnectTimeout = (int)director->FDConnectTimeout;
345    SDConnectTimeout = (int)director->SDConnectTimeout;
346
347    resize_reload(director->MaxReload);
348
349 #if !defined(HAVE_WIN32)
350    signal(SIGHUP, reload_config);
351 #endif
352
353    init_console_msg(working_directory);
354
355    Dmsg0(200, "Start UA server\n");
356    start_UA_server(director->DIRaddrs);
357
358    start_watchdog();                  /* start network watchdog thread */
359
360    init_jcr_subsystem();              /* start JCR watchdogs etc. */
361
362    init_job_server(director->MaxConcurrentJobs);
363
364    dbg_jcr_add_hook(dir_debug_print); /* used to director variables */
365    dbg_jcr_add_hook(bdb_debug_print);     /* used to debug B_DB connexion after fatal signal */
366
367 //   init_device_resources();
368
369    Dmsg0(200, "wait for next job\n");
370    /* Main loop -- call scheduler to get next job to run */
371    while ( (jcr = wait_for_next_job(runjob)) ) {
372       run_job(jcr);                   /* run job */
373       free_jcr(jcr);                  /* release jcr */
374       set_jcr_in_tsd(INVALID_JCR);
375       if (runjob) {                   /* command line, run a single job? */
376          break;                       /* yes, terminate */
377       }
378    }
379
380    terminate_dird(0);
381
382    return 0;
383 }
384
385 struct RELOAD_TABLE {
386    int job_count;
387    RES_HEAD **res_head;
388 };
389
390 static int max_reloads = 32;
391 static RELOAD_TABLE *reload_table=NULL;
392
393 static void resize_reload(int nb)
394 {
395    if (nb <= max_reloads) {
396       return;
397    }
398
399    reload_table = (RELOAD_TABLE*)realloc(reload_table, nb * sizeof(RELOAD_TABLE));
400    for (int i=max_reloads; i < nb ; i++) {
401       reload_table[i].job_count = 0;
402       reload_table[i].res_head = NULL;
403    }
404    max_reloads = nb;
405 }
406
407 static void init_reload(void)
408 {
409    reload_table = (RELOAD_TABLE*)malloc(max_reloads * sizeof(RELOAD_TABLE));
410    for (int i=0; i < max_reloads; i++) {
411       reload_table[i].job_count = 0;
412       reload_table[i].res_head = NULL;
413    }
414 }
415
416 /*
417  * This subroutine frees a saved resource table.
418  *  It was saved when a new table was created with "reload"
419  */
420 static void free_saved_resources(int table)
421 {
422    RES *next, *res;
423    int num = r_last - r_first + 1;
424    RES_HEAD **res_tab = reload_table[table].res_head;
425
426    if (res_tab == NULL) {
427       Dmsg1(100, "res_tab for table %d already released.\n", table);
428       return;
429    }
430    Dmsg1(100, "Freeing resources for table %d\n", table);
431    for (int j=0; j<num; j++) {
432       if (res_tab[j]) {
433          next = res_tab[j]->first;
434          for ( ; next; ) {
435             res = next;
436             next = res->res_next;
437             free_resource(res, r_first + j);
438          }
439          free(res_tab[j]->res_list);
440          free(res_tab[j]);
441          res_tab[j] = NULL;
442       }
443    }
444    free(res_tab);
445    reload_table[table].job_count = 0;
446    reload_table[table].res_head = NULL;
447 }
448
449 /*
450  * Called here at the end of every job that was
451  * hooked decrementing the active job_count. When
452  * it goes to zero, no one is using the associated
453  * resource table, so free it.
454  */
455 static void reload_job_end_cb(JCR *jcr, void *ctx)
456 {
457    int reload_id = (int)((intptr_t)ctx);
458    Dmsg3(100, "reload job_end JobId=%d table=%d cnt=%d\n", jcr->JobId,
459       reload_id, reload_table[reload_id].job_count);
460    lock_jobs();
461    LockRes();
462    if (--reload_table[reload_id].job_count <= 0) {
463       free_saved_resources(reload_id);
464    }
465    UnlockRes();
466    unlock_jobs();
467 }
468
469 static int find_free_reload_table_entry()
470 {
471    int table = -1;
472    for (int i=0; i < max_reloads; i++) {
473       if (reload_table[i].res_head == NULL) {
474          table = i;
475          break;
476       }
477    }
478    return table;
479 }
480
481 static pthread_mutex_t reload_mutex = PTHREAD_MUTEX_INITIALIZER;
482
483 /*
484  * If we get here, we have received a SIGHUP, which means to
485  *    reread our configuration file.
486  *
487  * The algorithm used is as follows: we count how many jobs are
488  *   running and mark the running jobs to make a callback on
489  *   exiting. The old config is saved with the reload table
490  *   id in a reload table. The new config file is read. Now, as
491  *   each job exits, it calls back to the reload_job_end_cb(), which
492  *   decrements the count of open jobs for the given reload table.
493  *   When the count goes to zero, we release those resources.
494  *   This allows us to have pointers into the resource table (from
495  *   jobs), and once they exit and all the pointers are released, we
496  *   release the old table. Note, if no new jobs are running since the
497  *   last reload, then the old resources will be immediately release.
498  *   A console is considered a job because it may have pointers to
499  *   resources, but a SYSTEM job is not since it *should* not have any
500  *   permanent pointers to jobs.
501  */
502 extern "C"
503 void reload_config(int sig)
504 {
505    static bool already_here = false;
506 #if !defined(HAVE_WIN32)
507    sigset_t set;
508 #endif
509    JCR *jcr;
510    int njobs = 0;                     /* number of running jobs */
511    int table, rtable;
512    bool ok=false;
513    int tries=0;
514
515    /* Wait to do the reload */
516    do {
517       P(reload_mutex);
518       if (already_here) {
519          V(reload_mutex);
520          if (tries++ > 10) {
521             Jmsg(NULL, M_INFO, 0, _("Already doing a reload request, "
522                                     "request ignored.\n"));
523             return;
524          }
525          Dmsg0(10, "Already doing a reload request, waiting a bit\n");
526          bmicrosleep(1, 0);
527       } else {
528          already_here = true;
529          V(reload_mutex);
530          ok = true;
531       }
532    } while (!ok);
533
534 #if !defined(HAVE_WIN32)
535    sigemptyset(&set);
536    sigaddset(&set, SIGHUP);
537    sigprocmask(SIG_BLOCK, &set, NULL);
538 #endif
539
540    lock_jobs();
541    LockRes();
542
543    table = find_free_reload_table_entry();
544    if (table < 0) {
545       Jmsg(NULL, M_ERROR, 0, _("Too many open reload requests. "
546                                "Request ignored.\n"));
547       goto bail_out;
548    }
549
550    Dmsg1(100, "Reload_config njobs=%d\n", njobs);
551    /* Save current res_head */
552    reload_table[table].res_head = res_head;
553    Dmsg1(100, "Saved old config in table %d\n", table);
554
555    /* Create a new res_head and parse into it */
556    ok = parse_dir_config(config, configfile, M_ERROR);
557
558    Dmsg0(100, "Reloaded config file\n");
559    if (!ok || !check_resources() || !check_catalog(UPDATE_CATALOG)) {
560       /*
561        * We got an error, save broken point, restore old one,
562        *  then release everything from broken pointer.
563        */
564       rtable = find_free_reload_table_entry();    /* save new, bad table */
565       if (rtable < 0) {
566          Jmsg(NULL, M_ERROR, 0, _("Please correct configuration file: %s\n"), configfile);
567          Jmsg(NULL, M_ERROR_TERM, 0, _("Out of reload table entries. Giving up.\n"));
568       } else {
569          Jmsg(NULL, M_ERROR, 0, _("Please correct configuration file: %s\n"), configfile);
570          Jmsg(NULL, M_ERROR, 0, _("Resetting previous configuration.\n"));
571       }
572       /* Save broken res_head pointer */
573       reload_table[rtable].res_head = res_head;
574
575       /* Now restore old resource pointer */
576       res_head = reload_table[table].res_head;
577       table = rtable;           /* release new, bad, saved table below */
578    } else {
579       invalidate_schedules();
580       /*
581        * Hook all active jobs so that they release this table
582        */
583       foreach_jcr(jcr) {
584          if (jcr->getJobType() != JT_SYSTEM) {
585             reload_table[table].job_count++;
586             job_end_push(jcr, reload_job_end_cb, (void *)((long int)table));
587             njobs++;
588          }
589       }
590       endeach_jcr(jcr);
591       /*
592        * Now walk through globals tables and plug them into the
593        * new resources.
594        */
595       CLIENT_GLOBALS *cg;
596       foreach_dlist(cg, &client_globals) {
597          CLIENT *client;
598          client = GetClientResWithName(cg->name);
599          if (!client) {
600             Jmsg(NULL, M_INFO, 0, _("Client=%s not found. Assuming it was removed!!!\n"), cg->name);
601          } else {
602             client->globals = cg;      /* Set globals pointer */
603          }
604       }
605       STORE_GLOBALS *sg;
606       foreach_dlist(sg, &store_globals) {
607          STORE *store;
608          store = GetStoreResWithName(sg->name);
609          if (!store) {
610             Jmsg(NULL, M_INFO, 0, _("Storage=%s not found. Assuming it was removed!!!\n"), sg->name);
611          } else {
612             store->globals = sg;       /* set globals pointer */
613             Dmsg2(200, "Reload found numConcurrent=%ld for Store %s\n",
614                sg->NumConcurrentJobs, sg->name);
615          }
616       }
617       JOB_GLOBALS *jg;
618       foreach_dlist(jg, &job_globals) {
619          JOB *job;
620          job = GetJobResWithName(jg->name);
621          if (!job) {
622             Jmsg(NULL, M_INFO, 0, _("Job=%s not found. Assuming it was removed!!!\n"), jg->name);
623          } else {
624             job->globals = jg;         /* Set globals pointer */
625          }
626       }
627       SCHED_GLOBALS *schg;
628       foreach_dlist(schg, &sched_globals) {
629          SCHED *sched;
630          sched = GetSchedResWithName(schg->name);
631          if (!sched) {
632             Jmsg(NULL, M_INFO, 0, _("Schedule=%s not found. Assuming it was removed!!!\n"), schg->name);
633          } else {
634             sched->globals = schg;     /* Set globals pointer */
635          }
636       }
637    }
638
639    /* Reset other globals */
640    set_working_directory(director->working_directory);
641    FDConnectTimeout = director->FDConnectTimeout;
642    SDConnectTimeout = director->SDConnectTimeout;
643    Dmsg0(10, "Director's configuration file reread.\n");
644
645    /* Now release saved resources, if no jobs using the resources */
646    if (njobs == 0) {
647       free_saved_resources(table);
648    }
649
650 bail_out:
651    UnlockRes();
652    unlock_jobs();
653 #if !defined(HAVE_WIN32)
654    sigprocmask(SIG_UNBLOCK, &set, NULL);
655    signal(SIGHUP, reload_config);
656 #endif
657    already_here = false;
658 }
659
660 /* Cleanup and then exit */
661 void terminate_dird(int sig)
662 {
663    static bool already_here = false;
664
665    if (already_here) {                /* avoid recursive temination problems */
666       bmicrosleep(2, 0);              /* yield */
667       exit(1);
668    }
669    already_here = true;
670    debug_level = 0;                   /* turn off debug */
671    stop_watchdog();
672    generate_daemon_event(NULL, "Exit");
673    unload_plugins();
674    if (!test_config) {
675       write_state_file(director->working_directory, "bacula-dir", get_first_port_host_order(director->DIRaddrs));
676       delete_pid_file(director->pid_directory, "bacula-dir", get_first_port_host_order(director->DIRaddrs));
677    }
678    term_scheduler();
679    term_job_server();
680    if (runjob) {
681       free(runjob);
682    }
683    if (configfile != NULL) {
684       free(configfile);
685    }
686    if (chk_dbglvl(5)) {
687       print_memory_pool_stats();
688    }
689    if (config) {
690       delete config;
691       config = NULL;
692    }
693    term_ua_server();
694    term_msg();                        /* terminate message handler */
695    cleanup_crypto();
696
697    free_daemon_message_queue();
698
699    if (reload_table) {
700       free(reload_table);
701    }
702    free(res_head);
703    res_head = NULL;
704    /*
705     * Now walk through resource globals tables and release them
706     */
707    CLIENT_GLOBALS *cg;
708    foreach_dlist(cg, &client_globals) {
709       free(cg->name);
710       if (cg->SetIPaddress) {
711          free(cg->SetIPaddress);
712       }
713       free(cg);
714    }
715    STORE_GLOBALS *sg;
716    foreach_dlist(sg, &store_globals) {
717       free(sg->name);
718       free(sg);
719    }
720    JOB_GLOBALS *jg;
721    foreach_dlist(jg, &job_globals) {
722       free(jg->name);
723       free(jg);
724    }
725    close_memory_pool();               /* release free memory in pool */
726    lmgr_cleanup_main();
727    sm_dump(false);
728    exit(sig);
729 }
730
731 /*
732  * Make a quick check to see that we have all the
733  * resources needed.
734  *
735  *  **** FIXME **** this routine could be a lot more
736  *   intelligent and comprehensive.
737  */
738 static bool check_resources()
739 {
740    bool OK = true;
741    JOB *job;
742    bool need_tls;
743
744    LockRes();
745
746    job = (JOB *)GetNextRes(R_JOB, NULL);
747    director = (DIRRES *)GetNextRes(R_DIRECTOR, NULL);
748    if (!director) {
749       Jmsg(NULL, M_FATAL, 0, _("No Director resource defined in %s\n"
750 "Without that I don't know who I am :-(\n"), configfile);
751       OK = false;
752    } else {
753       set_working_directory(director->working_directory);
754       if (!director->messages) {       /* If message resource not specified */
755          director->messages = (MSGS *)GetNextRes(R_MSGS, NULL);
756          if (!director->messages) {
757             Jmsg(NULL, M_FATAL, 0, _("No Messages resource defined in %s\n"), configfile);
758             OK = false;
759          }
760       }
761       if (GetNextRes(R_DIRECTOR, (RES *)director) != NULL) {
762          Jmsg(NULL, M_FATAL, 0, _("Only one Director resource permitted in %s\n"),
763             configfile);
764          OK = false;
765       }
766       /* tls_require implies tls_enable */
767       if (director->tls_require) {
768          if (have_tls) {
769             director->tls_enable = true;
770          } else {
771             Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
772             OK = false;
773          }
774       }
775
776       need_tls = director->tls_enable || director->tls_authenticate;
777
778       if (!director->tls_certfile && need_tls) {
779          Jmsg(NULL, M_FATAL, 0, _("\"TLS Certificate\" file not defined for Director \"%s\" in %s.\n"),
780             director->name(), configfile);
781          OK = false;
782       }
783
784       if (!director->tls_keyfile && need_tls) {
785          Jmsg(NULL, M_FATAL, 0, _("\"TLS Key\" file not defined for Director \"%s\" in %s.\n"),
786             director->name(), configfile);
787          OK = false;
788       }
789
790       if ((!director->tls_ca_certfile && !director->tls_ca_certdir) &&
791            need_tls && director->tls_verify_peer) {
792          Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\" or \"TLS CA"
793               " Certificate Dir\" are defined for Director \"%s\" in %s."
794               " At least one CA certificate store is required"
795               " when using \"TLS Verify Peer\".\n"),
796               director->name(), configfile);
797          OK = false;
798       }
799
800       /* If everything is well, attempt to initialize our per-resource TLS context */
801       if (OK && (need_tls || director->tls_require)) {
802          /* Initialize TLS context:
803           * Args: CA certfile, CA certdir, Certfile, Keyfile,
804           * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
805          director->tls_ctx = new_tls_context(director->tls_ca_certfile,
806             director->tls_ca_certdir, director->tls_certfile,
807             director->tls_keyfile, NULL, NULL, director->tls_dhfile,
808             director->tls_verify_peer);
809
810          if (!director->tls_ctx) {
811             Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for Director \"%s\" in %s.\n"),
812                  director->name(), configfile);
813             OK = false;
814          }
815       }
816    }
817
818    if (!job) {
819       Jmsg(NULL, M_FATAL, 0, _("No Job records defined in %s\n"), configfile);
820       OK = false;
821    }
822    foreach_res(job, R_JOB) {
823       int i;
824
825       if (job->jobdefs) {
826          JOB *jobdefs = job->jobdefs;
827          /* Handle RunScripts alists specifically */
828          if (jobdefs->RunScripts) {
829             RUNSCRIPT *rs, *elt;
830
831             if (!job->RunScripts) {
832                job->RunScripts = New(alist(10, not_owned_by_alist));
833             }
834
835             foreach_alist(rs, jobdefs->RunScripts) {
836                elt = copy_runscript(rs);
837                job->RunScripts->append(elt); /* we have to free it */
838             }
839          }
840
841          /* Transfer default items from JobDefs Resource */
842          for (i=0; job_items[i].name; i++) {
843             char **def_svalue, **svalue;  /* string value */
844             uint32_t *def_ivalue, *ivalue;     /* integer value */
845             bool *def_bvalue, *bvalue;    /* bool value */
846             int64_t *def_lvalue, *lvalue; /* 64 bit values */
847             alist **def_avalue, **avalue; /* alist values */
848             uint32_t offset;
849
850             Dmsg4(1400, "Job \"%s\", field \"%s\" bit=%d def=%d\n",
851                 job->name(), job_items[i].name,
852                 bit_is_set(i, job->hdr.item_present),
853                 bit_is_set(i, job->jobdefs->hdr.item_present));
854
855             if (!bit_is_set(i, job->hdr.item_present) &&
856                  bit_is_set(i, job->jobdefs->hdr.item_present)) {
857                Dmsg2(400, "Job \"%s\", field \"%s\": getting default.\n",
858                  job->name(), job_items[i].name);
859                offset = (char *)(job_items[i].value) - (char *)&res_all;
860                /*
861                 * Handle strings and directory strings
862                 */
863                if (job_items[i].handler == store_str ||
864                    job_items[i].handler == store_dir) {
865                   def_svalue = (char **)((char *)(job->jobdefs) + offset);
866                   Dmsg5(400, "Job \"%s\", field \"%s\" def_svalue=%s item %d offset=%u\n",
867                        job->name(), job_items[i].name, *def_svalue, i, offset);
868                   svalue = (char **)((char *)job + offset);
869                   if (*svalue) {
870                      Pmsg1(000, _("Hey something is wrong. p=0x%lu\n"), *svalue);
871                   }
872                   *svalue = bstrdup(*def_svalue);
873                   set_bit(i, job->hdr.item_present);
874                /*
875                 * Handle resources
876                 */
877                } else if (job_items[i].handler == store_res) {
878                   def_svalue = (char **)((char *)(job->jobdefs) + offset);
879                   Dmsg4(400, "Job \"%s\", field \"%s\" item %d offset=%u\n",
880                        job->name(), job_items[i].name, i, offset);
881                   svalue = (char **)((char *)job + offset);
882                   if (*svalue) {
883                      Pmsg1(000, _("Hey something is wrong. p=0x%lu\n"), *svalue);
884                   }
885                   *svalue = *def_svalue;
886                   set_bit(i, job->hdr.item_present);
887                /*
888                 * Handle alist resources
889                 */
890                } else if (job_items[i].handler == store_alist_res) {
891                   void *elt;
892
893                   def_avalue = (alist **)((char *)(job->jobdefs) + offset);
894                   avalue = (alist **)((char *)job + offset);
895
896                   *avalue = New(alist(10, not_owned_by_alist));
897
898                   foreach_alist(elt, (*def_avalue)) {
899                      (*avalue)->append(elt);
900                   }
901                   set_bit(i, job->hdr.item_present);
902                /*
903                 * Handle integer fields
904                 *    Note, our store_bit does not handle bitmaped fields
905                 */
906                } else if (job_items[i].handler == store_bit     ||
907                           job_items[i].handler == store_pint32  ||
908                           job_items[i].handler == store_jobtype ||
909                           job_items[i].handler == store_level   ||
910                           job_items[i].handler == store_int32   ||
911                           job_items[i].handler == store_size32  ||
912                           job_items[i].handler == store_migtype ||
913                           job_items[i].handler == store_replace) {
914                   def_ivalue = (uint32_t *)((char *)(job->jobdefs) + offset);
915                   Dmsg5(400, "Job \"%s\", field \"%s\" def_ivalue=%d item %d offset=%u\n",
916                        job->name(), job_items[i].name, *def_ivalue, i, offset);
917                   ivalue = (uint32_t *)((char *)job + offset);
918                   *ivalue = *def_ivalue;
919                   set_bit(i, job->hdr.item_present);
920                /*
921                 * Handle 64 bit integer fields
922                 */
923                } else if (job_items[i].handler == store_time   ||
924                           job_items[i].handler == store_size64 ||
925                           job_items[i].handler == store_speed  ||
926                           job_items[i].handler == store_int64) {
927                   def_lvalue = (int64_t *)((char *)(job->jobdefs) + offset);
928                   Dmsg5(400, "Job \"%s\", field \"%s\" def_lvalue=%" lld " item %d offset=%u\n",
929                        job->name(), job_items[i].name, *def_lvalue, i, offset);
930                   lvalue = (int64_t *)((char *)job + offset);
931                   *lvalue = *def_lvalue;
932                   set_bit(i, job->hdr.item_present);
933                /*
934                 * Handle bool fields
935                 */
936                } else if (job_items[i].handler == store_bool) {
937                   def_bvalue = (bool *)((char *)(job->jobdefs) + offset);
938                   Dmsg5(400, "Job \"%s\", field \"%s\" def_bvalue=%d item %d offset=%u\n",
939                        job->name(), job_items[i].name, *def_bvalue, i, offset);
940                   bvalue = (bool *)((char *)job + offset);
941                   *bvalue = *def_bvalue;
942                   set_bit(i, job->hdr.item_present);
943                }
944             }
945          }
946       }
947       /*
948        * Ensure that all required items are present
949        */
950       for (i=0; job_items[i].name; i++) {
951          if (job_items[i].flags & ITEM_REQUIRED) {
952                if (!bit_is_set(i, job->hdr.item_present)) {
953                   Jmsg(NULL, M_ERROR_TERM, 0, _("\"%s\" directive in Job \"%s\" resource is required, but not found.\n"),
954                     job_items[i].name, job->name());
955                   OK = false;
956                 }
957          }
958          /* If this triggers, take a look at lib/parse_conf.h */
959          if (i >= MAX_RES_ITEMS) {
960             Emsg0(M_ERROR_TERM, 0, _("Too many items in Job resource\n"));
961          }
962       }
963       if (!job->storage && !job->pool->storage) {
964          Jmsg(NULL, M_FATAL, 0, _("No storage specified in Job \"%s\" nor in Pool.\n"),
965             job->name());
966          OK = false;
967       }
968
969       /* Make sure the job doesn't use the Scratch Pool to start with */
970       const char *name;
971       if (!check_pool(job->JobType, job->JobLevel,
972                       job->pool, job->next_pool, &name)) { 
973          Jmsg(NULL, M_FATAL, 0,
974               _("%s \"Scratch\" not valid in Job \"%s\".\n"),
975               name, job->name());
976          OK = false;
977       }
978    } /* End loop over Job res */
979
980
981    /* Loop over Consoles */
982    CONRES *cons;
983    foreach_res(cons, R_CONSOLE) {
984       /* tls_require implies tls_enable */
985       if (cons->tls_require) {
986          if (have_tls) {
987             cons->tls_enable = true;
988          } else {
989             Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
990             OK = false;
991             continue;
992          }
993       }
994
995       need_tls = cons->tls_enable || cons->tls_authenticate;
996
997       if (!cons->tls_certfile && need_tls) {
998          Jmsg(NULL, M_FATAL, 0, _("\"TLS Certificate\" file not defined for Console \"%s\" in %s.\n"),
999             cons->name(), configfile);
1000          OK = false;
1001       }
1002
1003       if (!cons->tls_keyfile && need_tls) {
1004          Jmsg(NULL, M_FATAL, 0, _("\"TLS Key\" file not defined for Console \"%s\" in %s.\n"),
1005             cons->name(), configfile);
1006          OK = false;
1007       }
1008
1009       if ((!cons->tls_ca_certfile && !cons->tls_ca_certdir)
1010             && need_tls && cons->tls_verify_peer) {
1011          Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\" or \"TLS CA"
1012             " Certificate Dir\" are defined for Console \"%s\" in %s."
1013             " At least one CA certificate store is required"
1014             " when using \"TLS Verify Peer\".\n"),
1015             cons->name(), configfile);
1016          OK = false;
1017       }
1018       /* If everything is well, attempt to initialize our per-resource TLS context */
1019       if (OK && (need_tls || cons->tls_require)) {
1020          /* Initialize TLS context:
1021           * Args: CA certfile, CA certdir, Certfile, Keyfile,
1022           * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
1023          cons->tls_ctx = new_tls_context(cons->tls_ca_certfile,
1024             cons->tls_ca_certdir, cons->tls_certfile,
1025             cons->tls_keyfile, NULL, NULL, cons->tls_dhfile, cons->tls_verify_peer);
1026
1027          if (!cons->tls_ctx) {
1028             Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for File daemon \"%s\" in %s.\n"),
1029                cons->name(), configfile);
1030             OK = false;
1031          }
1032       }
1033
1034    }
1035
1036    /* Loop over Clients */
1037    CLIENT *client;
1038    foreach_res(client, R_CLIENT) {
1039       /* tls_require implies tls_enable */
1040       if (client->tls_require) {
1041          if (have_tls) {
1042             client->tls_enable = true;
1043          } else {
1044             Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
1045             OK = false;
1046             continue;
1047          }
1048       }
1049       need_tls = client->tls_enable || client->tls_authenticate;
1050       if ((!client->tls_ca_certfile && !client->tls_ca_certdir) && need_tls) {
1051          Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\""
1052             " or \"TLS CA Certificate Dir\" are defined for File daemon \"%s\" in %s.\n"),
1053             client->name(), configfile);
1054          OK = false;
1055       }
1056
1057       /* If everything is well, attempt to initialize our per-resource TLS context */
1058       if (OK && (need_tls || client->tls_require)) {
1059          /* Initialize TLS context:
1060           * Args: CA certfile, CA certdir, Certfile, Keyfile,
1061           * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
1062          client->tls_ctx = new_tls_context(client->tls_ca_certfile,
1063             client->tls_ca_certdir, client->tls_certfile,
1064             client->tls_keyfile, NULL, NULL, NULL,
1065             true);
1066
1067          if (!client->tls_ctx) {
1068             Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for File daemon \"%s\" in %s.\n"),
1069                client->name(), configfile);
1070             OK = false;
1071          }
1072       }
1073    }
1074
1075    /* Loop over all pools, check PoolType */
1076    POOL *pool;
1077    foreach_res(pool, R_POOL) {
1078       if (!pool->pool_type) {
1079          /* This case is checked by the parse engine, we should not */
1080          Jmsg(NULL, M_FATAL, 0, _("PoolType required in Pool resource \"%s\".\n"), pool->hdr.name);
1081          OK = false;
1082          continue;
1083       }
1084       if ((strcasecmp(pool->pool_type, NT_("backup"))  != 0) &&
1085           (strcasecmp(pool->pool_type, NT_("copy"))    != 0) &&
1086           (strcasecmp(pool->pool_type, NT_("cloned"))  != 0) &&
1087           (strcasecmp(pool->pool_type, NT_("archive")) != 0) &&
1088           (strcasecmp(pool->pool_type, NT_("migration")) != 0) &&
1089           (strcasecmp(pool->pool_type, NT_("scratch")) != 0))
1090       {
1091          Jmsg(NULL, M_FATAL, 0, _("Invalid PoolType \"%s\" in Pool resource \"%s\".\n"), pool->pool_type, pool->hdr.name);
1092          OK = false;
1093       }
1094
1095       if (pool->NextPool && strcmp(pool->NextPool->name(), "Scratch") == 0) {
1096          Jmsg(NULL, M_FATAL, 0,
1097               _("NextPool \"Scratch\" not valid in Pool \"%s\".\n"),
1098               pool->name());
1099          OK = false;
1100       }
1101    }
1102
1103    UnlockRes();
1104    if (OK) {
1105       close_msg(NULL);                /* close temp message handler */
1106       init_msg(NULL, director->messages); /* open daemon message handler */
1107       last_reload_time = time(NULL);
1108    }
1109    return OK;
1110 }
1111
1112 /*
1113  * In this routine,
1114  *  - we can check the connection (mode=CHECK_CONNECTION)
1115  *  - we can synchronize the catalog with the configuration (mode=UPDATE_CATALOG)
1116  *  - we can synchronize, and fix old job records (mode=UPDATE_AND_FIX)
1117  *  - we hook up the Autochange children with the parent, and
1118  *    we hook the shared autochangers together.
1119  */
1120 static bool check_catalog(cat_op mode)
1121 {
1122    bool OK = true;
1123    bool need_tls;
1124    STORE *store, *ac_child;
1125
1126    /* Loop over databases */
1127    CAT *catalog;
1128    foreach_res(catalog, R_CATALOG) {
1129       BDB *db;
1130       /*
1131        * Make sure we can open catalog, otherwise print a warning
1132        * message because the server is probably not running.
1133        */
1134       db = db_init_database(NULL, catalog->db_driver, catalog->db_name, 
1135               catalog->db_user,
1136               catalog->db_password, catalog->db_address,
1137               catalog->db_port, catalog->db_socket,
1138               catalog->db_ssl_mode, catalog->db_ssl_key,
1139               catalog->db_ssl_cert, catalog->db_ssl_ca,
1140               catalog->db_ssl_capath, catalog->db_ssl_cipher,
1141               catalog->mult_db_connections,
1142               catalog->disable_batch_insert);
1143       if (!db || !db_open_database(NULL, db)) {
1144          Pmsg2(000, _("Could not open Catalog \"%s\", database \"%s\".\n"),
1145               catalog->name(), catalog->db_name);
1146          Jmsg(NULL, M_FATAL, 0, _("Could not open Catalog \"%s\", database \"%s\".\n"),
1147               catalog->name(), catalog->db_name);
1148          if (db) {
1149             Jmsg(NULL, M_FATAL, 0, _("%s"), db_strerror(db));
1150             Pmsg1(000, "%s", db_strerror(db));
1151             db_close_database(NULL, db);
1152          }
1153          OK = false;
1154          continue;
1155       }
1156
1157       /* Display a message if the db max_connections is too low */
1158       if (!db_check_max_connections(NULL, db, director->MaxConcurrentJobs)) {
1159          Pmsg1(000, "Warning, settings problem for Catalog=%s\n", catalog->name());
1160          Pmsg1(000, "%s", db_strerror(db));
1161       }
1162
1163       /* we are in testing mode, so don't touch anything in the catalog */
1164       if (mode == CHECK_CONNECTION) {
1165          if (db) db_close_database(NULL, db);
1166          continue;
1167       }
1168
1169       /* Loop over all pools, defining/updating them in each database */
1170       POOL *pool;
1171       foreach_res(pool, R_POOL) {
1172          /*
1173           * If the Pool has a catalog resource create the pool only
1174           *   in that catalog.
1175           */
1176          if (!pool->catalog || pool->catalog == catalog) {
1177             create_pool(NULL, db, pool, POOL_OP_UPDATE);  /* update request */
1178          }
1179       }
1180
1181       /* Once they are created, we can loop over them again, updating
1182        * references (RecyclePool)
1183        */
1184       foreach_res(pool, R_POOL) {
1185          /*
1186           * If the Pool has a catalog resource update the pool only
1187           *   in that catalog.
1188           */
1189          if (!pool->catalog || pool->catalog == catalog) {
1190             update_pool_references(NULL, db, pool);
1191          }
1192       }
1193
1194       /* Ensure basic client record is in DB */
1195       CLIENT *client;
1196       foreach_res(client, R_CLIENT) {
1197          CLIENT_DBR cr;
1198          /* Create clients only if they use the current catalog */
1199          if (client->catalog != catalog) {
1200             Dmsg3(500, "Skip client=%s with cat=%s not catalog=%s\n",
1201                   client->name(), client->catalog->name(), catalog->name());
1202             continue;
1203          }
1204          Dmsg2(500, "create cat=%s for client=%s\n",
1205                client->catalog->name(), client->name());
1206          memset(&cr, 0, sizeof(cr));
1207          bstrncpy(cr.Name, client->name(), sizeof(cr.Name));
1208
1209          db_create_client_record(NULL, db, &cr);
1210       }
1211
1212       /* Ensure basic storage record is in DB */
1213       foreach_res(store, R_STORAGE) {
1214          STORAGE_DBR sr;
1215          MEDIATYPE_DBR mtr;
1216          memset(&sr, 0, sizeof(sr));
1217          memset(&mtr, 0, sizeof(mtr));
1218          if (store->media_type) {
1219             bstrncpy(mtr.MediaType, store->media_type, sizeof(mtr.MediaType));
1220             mtr.ReadOnly = 0;
1221             db_create_mediatype_record(NULL, db, &mtr);
1222          } else {
1223             mtr.MediaTypeId = 0;
1224          }
1225          bstrncpy(sr.Name, store->name(), sizeof(sr.Name));
1226          sr.AutoChanger = store->autochanger;
1227          if (!db_create_storage_record(NULL, db, &sr)) {
1228             Jmsg(NULL, M_FATAL, 0, _("Could not create storage record for %s\n"),
1229                  store->name());
1230             OK = false;
1231          }
1232          store->StorageId = sr.StorageId;   /* set storage Id */
1233          if (!sr.created) {                 /* if not created, update it */
1234             sr.AutoChanger = store->autochanger;
1235             if (!db_update_storage_record(NULL, db, &sr)) {
1236                Jmsg(NULL, M_FATAL, 0, _("Could not update storage record for %s\n"),
1237                     store->name());
1238                OK = false;
1239             }
1240          }
1241
1242          /* tls_require implies tls_enable */
1243          if (store->tls_require) {
1244             if (have_tls) {
1245                store->tls_enable = true;
1246             } else {
1247                Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
1248                OK = false;
1249             }
1250          }
1251
1252          need_tls = store->tls_enable || store->tls_authenticate;
1253
1254          if ((!store->tls_ca_certfile && !store->tls_ca_certdir) && need_tls) {
1255             Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\""
1256                  " or \"TLS CA Certificate Dir\" are defined for Storage \"%s\" in %s.\n"),
1257                  store->name(), configfile);
1258             OK = false;
1259          }
1260
1261          /* If everything is well, attempt to initialize our per-resource TLS context */
1262          if (OK && (need_tls || store->tls_require)) {
1263            /* Initialize TLS context:
1264             * Args: CA certfile, CA certdir, Certfile, Keyfile,
1265             * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
1266             store->tls_ctx = new_tls_context(store->tls_ca_certfile,
1267                store->tls_ca_certdir, store->tls_certfile,
1268                store->tls_keyfile, NULL, NULL, NULL, true);
1269
1270             if (!store->tls_ctx) {
1271                Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for Storage \"%s\" in %s.\n"),
1272                     store->name(), configfile);
1273                OK = false;
1274             }
1275          }
1276       }
1277
1278       /* Link up all the children for each changer */
1279       foreach_res(store, R_STORAGE) {
1280          char sid[50];
1281          if (store->changer == store) {  /* we are a real Autochanger */
1282             store->ac_group = get_pool_memory(PM_FNAME);
1283             store->ac_group[0] = 0;
1284             pm_strcat(store->ac_group, edit_int64(store->StorageId, sid));
1285             /* Now look for children who point to this storage */
1286             foreach_res(ac_child, R_STORAGE) {
1287                if (ac_child != store && ac_child->changer == store) {
1288                   /* Found a child -- add StorageId */
1289                   pm_strcat(store->ac_group, ",");
1290                   pm_strcat(store->ac_group, edit_int64(ac_child->StorageId, sid));
1291                }
1292             }
1293          }
1294       }
1295
1296       /* Link up all the shared storage devices */
1297       foreach_res(store, R_STORAGE) {
1298          if (store->ac_group) {  /* we are a real Autochanger */
1299             /* Now look for Shared Storage who point to this storage */
1300             foreach_res(ac_child, R_STORAGE) {
1301                if (ac_child->shared_storage == store && ac_child->ac_group &&
1302                    ac_child->shared_storage != ac_child) {
1303                   pm_strcat(store->ac_group, ",");
1304                   pm_strcat(store->ac_group, ac_child->ac_group);
1305                }
1306             }
1307          }
1308       }
1309
1310       /* Loop over all counters, defining them in each database */
1311       /* Set default value in all counters */
1312       COUNTER *counter;
1313       foreach_res(counter, R_COUNTER) {
1314          /* Write to catalog? */
1315          if (!counter->created && counter->Catalog == catalog) {
1316             COUNTER_DBR cr;
1317             bstrncpy(cr.Counter, counter->name(), sizeof(cr.Counter));
1318             cr.MinValue = counter->MinValue;
1319             cr.MaxValue = counter->MaxValue;
1320             cr.CurrentValue = counter->MinValue;
1321             if (counter->WrapCounter) {
1322                bstrncpy(cr.WrapCounter, counter->WrapCounter->name(), sizeof(cr.WrapCounter));
1323             } else {
1324                cr.WrapCounter[0] = 0;  /* empty string */
1325             }
1326             if (db_create_counter_record(NULL, db, &cr)) {
1327                counter->CurrentValue = cr.CurrentValue;
1328                counter->created = true;
1329                Dmsg2(100, "Create counter %s val=%d\n", counter->name(), counter->CurrentValue);
1330             }
1331          }
1332          if (!counter->created) {
1333             counter->CurrentValue = counter->MinValue;  /* default value */
1334          }
1335       }
1336       /* cleanup old job records */
1337       if (mode == UPDATE_AND_FIX) {
1338          db_sql_query(db, cleanup_created_job, NULL, NULL);
1339          db_sql_query(db, cleanup_running_job, NULL, NULL);
1340       }
1341
1342       /* Set SQL engine name in global for debugging */
1343       set_db_engine_name(db_get_engine_name(db));
1344       if (db) db_close_database(NULL, db);
1345    }
1346    return OK;
1347 }
1348
1349 static void cleanup_old_files()
1350 {
1351    DIR* dp;
1352    struct dirent *entry, *result;
1353    int rc, name_max;
1354    int my_name_len = strlen(my_name);
1355    int len = strlen(director->working_directory);
1356    POOLMEM *cleanup = get_pool_memory(PM_MESSAGE);
1357    POOLMEM *basename = get_pool_memory(PM_MESSAGE);
1358    regex_t preg1;
1359    char prbuf[500];
1360    const int nmatch = 30;
1361    regmatch_t pmatch[nmatch];
1362    berrno be;
1363
1364    /* Exclude spaces and look for .mail, .tmp or .restore.xx.bsr files */
1365    const char *pat1 = "^[^ ]+\\.(restore\\.[^ ]+\\.bsr|mail|tmp)$";
1366
1367    /* Setup working directory prefix */
1368    pm_strcpy(basename, director->working_directory);
1369    if (len > 0 && !IsPathSeparator(director->working_directory[len-1])) {
1370       pm_strcat(basename, "/");
1371    }
1372
1373    /* Compile regex expressions */
1374    rc = regcomp(&preg1, pat1, REG_EXTENDED);
1375    if (rc != 0) {
1376       regerror(rc, &preg1, prbuf, sizeof(prbuf));
1377       Pmsg2(000,  _("Could not compile regex pattern \"%s\" ERR=%s\n"),
1378            pat1, prbuf);
1379       goto get_out2;
1380    }
1381
1382    name_max = pathconf(".", _PC_NAME_MAX);
1383    if (name_max < 1024) {
1384       name_max = 1024;
1385    }
1386
1387    if (!(dp = opendir(director->working_directory))) {
1388       berrno be;
1389       Pmsg2(000, "Failed to open working dir %s for cleanup: ERR=%s\n",
1390             director->working_directory, be.bstrerror());
1391       goto get_out1;
1392       return;
1393    }
1394
1395    entry = (struct dirent *)malloc(sizeof(struct dirent) + name_max + 1000);
1396    while (1) {
1397       if ((readdir_r(dp, entry, &result) != 0) || (result == NULL)) {
1398          break;
1399       }
1400       /* Exclude any name with ., .., not my_name or containing a space */
1401       if (strcmp(result->d_name, ".") == 0 || strcmp(result->d_name, "..") == 0 ||
1402           strncmp(result->d_name, my_name, my_name_len) != 0) {
1403          Dmsg1(500, "Skipped: %s\n", result->d_name);
1404          continue;
1405       }
1406
1407       /* Unlink files that match regexes */
1408       if (regexec(&preg1, result->d_name, nmatch, pmatch,  0) == 0) {
1409          pm_strcpy(cleanup, basename);
1410          pm_strcat(cleanup, result->d_name);
1411          Dmsg1(100, "Unlink: %s\n", cleanup);
1412          unlink(cleanup);
1413       }
1414    }
1415
1416    free(entry);
1417    closedir(dp);
1418 /* Be careful to free up the correct resources */
1419 get_out1:
1420    regfree(&preg1);
1421 get_out2:
1422    free_pool_memory(cleanup);
1423    free_pool_memory(basename);
1424 }