]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/filed/filed.c
Backport Enterprise code
[bacula/bacula] / bacula / src / filed / filed.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 File Daemon
21  *
22  *    Kern Sibbald, March MM
23  */
24
25 #include "bacula.h"
26 #include "filed.h"
27
28 /* Imported Functions */
29 extern void *handle_connection_request(void *dir_sock);
30 extern bool parse_fd_config(CONFIG *config, const char *configfile, int exit_code);
31
32 /* Forward referenced functions */
33 static bool check_resources();
34
35 /* Exported variables */
36 CLIENT *me;                           /* my resource */
37 bool no_signals = false;
38 void *start_heap;
39 extern struct s_cmds cmds[];
40
41 #ifndef CONFIG_FILE                   /* Might be overwritten */
42  #define CONFIG_FILE "bacula-fd.conf" /* default config file */
43  #define PROG_NAME   "bacula-fd"
44 #endif
45
46 char *configfile = NULL;
47 static bool test_config = false;
48 static bool foreground = false;
49 static workq_t dir_workq;             /* queue of work from Director */
50 static pthread_t server_tid;
51 static CONFIG *config;
52
53 static void usage()
54 {
55    fprintf(stderr, _(
56       PROG_COPYRIGHT
57       "\nVersion: %s (%s)\n\n"
58       "Usage: bacula-fd [-f -s] [-c config_file] [-d debug_level]\n"
59       "     -c <file>        use <file> as configuration file\n"
60       "     -d <n>[,<tags>]  set debug level to <nn>, debug tags to <tags>\n"
61       "     -dt              print a timestamp in debug output\n"
62       "     -f               run in foreground (for debugging)\n"
63       "     -g               groupid\n"
64       "     -k               keep readall capabilities\n"
65       "     -m               print kaboom output (for debugging)\n"
66       "     -s               no signals (for debugging)\n"
67       "     -t               test configuration file and exit\n"
68       "     -T               set trace on\n"
69       "     -u               userid\n"
70       "     -v               verbose user messages\n"
71       "     -?               print this message.\n"
72       "\n"), 2000, VERSION, BDATE);
73
74    exit(1);
75 }
76
77
78 /*********************************************************************
79  *
80  *  Main Bacula Unix Client Program
81  *
82  */
83
84 int main (int argc, char *argv[])
85 {
86    int ch;
87    bool keep_readall_caps = false;
88    char *uid = NULL;
89    char *gid = NULL;
90
91    start_heap = sbrk(0);
92    setlocale(LC_ALL, "");
93    bindtextdomain("bacula", LOCALEDIR);
94    textdomain("bacula");
95
96    init_stack_dump();
97    my_name_is(argc, argv, PROG_NAME);
98    init_msg(NULL, NULL);
99    daemon_start_time = time(NULL);
100    setup_daemon_message_queue();
101
102    while ((ch = getopt(argc, argv, "c:d:fg:kmstTu:v?D:")) != -1) {
103       switch (ch) {
104       case 'c':                    /* configuration file */
105          if (configfile != NULL) {
106             free(configfile);
107          }
108          configfile = bstrdup(optarg);
109          break;
110
111       case 'd':                    /* debug level */
112          if (*optarg == 't') {
113             dbg_timestamp = true;
114          } else {
115             char *p;
116             /* We probably find a tag list -d 10,sql,bvfs */
117             if ((p = strchr(optarg, ',')) != NULL) {
118                *p = 0;
119             }
120             debug_level = atoi(optarg);
121             if (debug_level <= 0) {
122                debug_level = 1;
123             }
124             if (p) {
125                debug_parse_tags(p+1, &debug_level_tags);
126             }
127          }
128          break;
129
130       case 'f':                    /* run in foreground */
131          foreground = true;
132          break;
133
134       case 'g':                    /* set group */
135          gid = optarg;
136          break;
137
138       case 'k':
139          keep_readall_caps = true;
140          break;
141
142       case 'm':                    /* print kaboom output */
143          prt_kaboom = true;
144          break;
145
146       case 's':
147          no_signals = true;
148          break;
149
150       case 't':
151          test_config = true;
152          break;
153
154       case 'T':
155          set_trace(true);
156          break;
157
158       case 'u':                    /* set userid */
159          uid = optarg;
160          break;
161
162       case 'v':                    /* verbose */
163          verbose++;
164          break;
165
166       case '?':
167       default:
168          usage();
169
170       }
171    }
172    argc -= optind;
173    argv += optind;
174
175    if (argc) {
176       if (configfile != NULL)
177          free(configfile);
178       configfile = bstrdup(*argv);
179       argc--;
180       argv++;
181    }
182    if (argc) {
183       usage();
184    }
185
186    if (!uid && keep_readall_caps) {
187       Emsg0(M_ERROR_TERM, 0, _("-k option has no meaning without -u option.\n"));
188    }
189
190    server_tid = pthread_self();
191
192    if (configfile == NULL) {
193       configfile = bstrdup(CONFIG_FILE);
194    }
195
196    if (!foreground && !test_config) {
197       daemon_start();
198       init_stack_dump();              /* set new pid */
199    }
200
201    if (!no_signals) {
202       init_signals(terminate_filed);
203    } else {
204       /* This reduces the number of signals facilitating debugging */
205       watchdog_sleep_time = 120;      /* long timeout for debugging */
206    }
207
208    config = New(CONFIG());
209    parse_fd_config(config, configfile, M_ERROR_TERM);
210
211    if (init_crypto() != 0) {
212       Emsg0(M_ERROR, 0, _("Cryptography library initialization failed.\n"));
213       terminate_filed(1);
214    }
215
216    if (!check_resources()) {
217       Emsg1(M_ERROR, 0, _("Please correct configuration file: %s\n"), configfile);
218       terminate_filed(1);
219    }
220
221    set_working_directory(me->working_directory);
222
223    if (test_config) {
224       terminate_filed(0);
225    }
226
227    set_thread_concurrency(me->MaxConcurrentJobs + 10);
228    lmgr_init_thread(); /* initialize the lockmanager stack */
229
230    /* Maximum 1 daemon at a time */
231    create_pid_file(me->pid_directory, PROG_NAME,
232                    get_first_port_host_order(me->FDaddrs));
233    read_state_file(me->working_directory, PROG_NAME,
234                    get_first_port_host_order(me->FDaddrs));
235
236    load_fd_plugins(me->plugin_directory);
237
238    drop(uid, gid, keep_readall_caps);
239
240 #ifdef BOMB
241    me += 1000000;
242 #endif
243
244    /* Setup default value for the the snapshot handler */
245    if (!me->snapshot_command) {
246       me->snapshot_command = snapshot_get_command();
247    }
248
249    if (!no_signals) {
250       start_watchdog();               /* start watchdog thread */
251       init_jcr_subsystem();           /* start JCR watchdogs etc. */
252    }
253    server_tid = pthread_self();
254
255    /* Become server, and handle requests */
256    IPADDR *p;
257    foreach_dlist(p, me->FDaddrs) {
258       Dmsg1(10, "filed: listening on port %d\n", p->get_port_host_order());
259    }
260    bnet_thread_server(me->FDaddrs, me->MaxConcurrentJobs, &dir_workq,
261       handle_connection_request);
262
263    terminate_filed(0);
264    exit(0);                           /* should never get here */
265 }
266
267 void terminate_filed(int sig)
268 {
269    static bool already_here = false;
270
271    if (already_here) {
272       bmicrosleep(2, 0);              /* yield */
273       exit(1);                        /* prevent loops */
274    }
275    already_here = true;
276    debug_level = 0;                   /* turn off debug */
277    stop_watchdog();
278
279    bnet_stop_thread_server(server_tid);
280    generate_daemon_event(NULL, "Exit");
281    unload_plugins();
282
283    free_daemon_message_queue();
284
285    if (!test_config) {
286       write_state_file(me->working_directory,
287                        "bacula-fd", get_first_port_host_order(me->FDaddrs));
288       delete_pid_file(me->pid_directory,
289                       "bacula-fd", get_first_port_host_order(me->FDaddrs));
290    }
291
292    if (configfile != NULL) {
293       free(configfile);
294    }
295
296    if (debug_level > 0) {
297       print_memory_pool_stats();
298    }
299
300    if (config) {
301       delete config;
302       config = NULL;
303    }
304    term_msg();
305    cleanup_crypto();
306    free(res_head);
307    res_head = NULL;
308    close_memory_pool();               /* release free memory in pool */
309    lmgr_cleanup_main();
310    sm_dump(false);                    /* dump orphaned buffers */
311    exit(sig);
312 }
313
314 /*
315 * Make a quick check to see that we have all the
316 * resources needed.
317 */
318 static bool check_resources()
319 {
320    int i;
321    bool found;
322    char *cmd;
323    bool OK = true;
324    DIRRES *director;
325    bool need_tls;
326
327    LockRes();
328
329    me = (CLIENT *)GetNextRes(R_CLIENT, NULL);
330    if (!me) {
331       Emsg1(M_FATAL, 0, _("No File daemon resource defined in %s\n"
332             "Without that I don't know who I am :-(\n"), configfile);
333       OK = false;
334    } else {
335       if (GetNextRes(R_CLIENT, (RES *) me) != NULL) {
336          Emsg1(M_FATAL, 0, _("Only one Client resource permitted in %s\n"),
337               configfile);
338          OK = false;
339       }
340       my_name_is(0, NULL, me->hdr.name);
341       if (!me->messages) {
342          me->messages = (MSGS *)GetNextRes(R_MSGS, NULL);
343          if (!me->messages) {
344              Emsg1(M_FATAL, 0, _("No Messages resource defined in %s\n"), configfile);
345              OK = false;
346          }
347       }
348
349       /* Construct disabled command array */
350       for (i=0; cmds[i].cmd; i++) { }  /* Count commands */
351       if (me->disable_cmds) {
352          me->disabled_cmds_array = (bool *)malloc(i);
353          memset(me->disabled_cmds_array, 0, i);
354          foreach_alist(cmd, me->disable_cmds) {
355             found = false;
356             for (i=0; cmds[i].cmd; i++) {
357                if (strncasecmp(cmds[i].cmd, cmd, strlen(cmd)) == 0) {
358                   me->disabled_cmds_array[i] = true;
359                   found = true;
360                   break;
361                }
362             }
363             if (!found) {
364                Jmsg(NULL, M_FATAL, 0, _("Disable Command \"%s\" not found.\n"),
365                   cmd);
366                OK = false;
367             }
368          }
369       }
370 #ifdef xxxDEBUG
371       for (i=0; cmds[i].cmd; i++) { }  /* Count commands */
372       while (i-- >= 0) {
373          if (me->disabled_cmds_array[i]) {
374             Dmsg1(050, "Command: %s disabled.\n", cmds[i].cmd);
375          }
376       }
377 #endif
378
379       /* tls_require implies tls_enable */
380       if (me->tls_require) {
381 #ifndef HAVE_TLS
382          Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
383          OK = false;
384 #else
385          me->tls_enable = true;
386 #endif
387       }
388       need_tls = me->tls_enable || me->tls_authenticate;
389
390       if ((!me->tls_ca_certfile && !me->tls_ca_certdir) && need_tls) {
391          Emsg1(M_FATAL, 0, _("Neither \"TLS CA Certificate\""
392             " or \"TLS CA Certificate Dir\" are defined for File daemon in %s.\n"),
393                             configfile);
394         OK = false;
395       }
396
397       /* If everything is well, attempt to initialize our per-resource TLS context */
398       if (OK && (need_tls || me->tls_require)) {
399          /* Initialize TLS context:
400           * Args: CA certfile, CA certdir, Certfile, Keyfile,
401           * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
402          me->tls_ctx = new_tls_context(me->tls_ca_certfile,
403             me->tls_ca_certdir, me->tls_certfile, me->tls_keyfile,
404             NULL, NULL, NULL, true);
405
406          if (!me->tls_ctx) {
407             Emsg2(M_FATAL, 0, _("Failed to initialize TLS context for File daemon \"%s\" in %s.\n"),
408                                 me->hdr.name, configfile);
409             OK = false;
410          }
411       }
412
413       if (me->pki_encrypt || me->pki_sign) {
414 #ifndef HAVE_CRYPTO
415          Jmsg(NULL, M_FATAL, 0, _("PKI encryption/signing enabled but not compiled into Bacula.\n"));
416          OK = false;
417 #endif
418       }
419
420       /* pki_encrypt implies pki_sign */
421       if (me->pki_encrypt) {
422          me->pki_sign = true;
423       }
424
425       if ((me->pki_encrypt || me->pki_sign) && !me->pki_keypair_file) {
426          Emsg2(M_FATAL, 0, _("\"PKI Key Pair\" must be defined for File"
427             " daemon \"%s\" in %s if either \"PKI Sign\" or"
428             " \"PKI Encrypt\" are enabled.\n"), me->hdr.name, configfile);
429          OK = false;
430       }
431
432       /* If everything is well, attempt to initialize our public/private keys */
433       if (OK && (me->pki_encrypt || me->pki_sign)) {
434          char *filepath;
435          /* Load our keypair */
436          me->pki_keypair = crypto_keypair_new();
437          if (!me->pki_keypair) {
438             Emsg0(M_FATAL, 0, _("Failed to allocate a new keypair object.\n"));
439             OK = false;
440          } else {
441             if (!crypto_keypair_load_cert(me->pki_keypair, me->pki_keypair_file)) {
442                Emsg2(M_FATAL, 0, _("Failed to load public certificate for File"
443                      " daemon \"%s\" in %s.\n"), me->hdr.name, configfile);
444                OK = false;
445             }
446
447             if (!crypto_keypair_load_key(me->pki_keypair, me->pki_keypair_file, NULL, NULL)) {
448                Emsg2(M_FATAL, 0, _("Failed to load private key for File"
449                      " daemon \"%s\" in %s.\n"), me->hdr.name, configfile);
450                OK = false;
451             }
452          }
453
454          /*
455           * Trusted Signers. We're always trusted.
456           */
457          me->pki_signers = New(alist(10, not_owned_by_alist));
458          if (me->pki_keypair) {
459             me->pki_signers->append(crypto_keypair_dup(me->pki_keypair));
460          }
461
462          /* If additional signing public keys have been specified, load them up */
463          if (me->pki_signing_key_files) {
464             foreach_alist(filepath, me->pki_signing_key_files) {
465                X509_KEYPAIR *keypair;
466
467                keypair = crypto_keypair_new();
468                if (!keypair) {
469                   Emsg0(M_FATAL, 0, _("Failed to allocate a new keypair object.\n"));
470                   OK = false;
471                } else {
472                   if (crypto_keypair_load_cert(keypair, filepath)) {
473                      me->pki_signers->append(keypair);
474
475                      /* Attempt to load a private key, if available */
476                      if (crypto_keypair_has_key(filepath)) {
477                         if (!crypto_keypair_load_key(keypair, filepath, NULL, NULL)) {
478                            Emsg3(M_FATAL, 0, _("Failed to load private key from file %s for File"
479                               " daemon \"%s\" in %s.\n"), filepath, me->hdr.name, configfile);
480                            OK = false;
481                         }
482                      }
483
484                   } else {
485                      Emsg3(M_FATAL, 0, _("Failed to load trusted signer certificate"
486                         " from file %s for File daemon \"%s\" in %s.\n"), filepath, me->hdr.name, configfile);
487                      OK = false;
488                   }
489                }
490             }
491          }
492
493          /*
494           * Crypto recipients. We're always included as a recipient.
495           * The symmetric session key will be encrypted for each of these readers.
496           */
497          me->pki_recipients = New(alist(10, not_owned_by_alist));
498          if (me->pki_keypair) {
499             me->pki_recipients->append(crypto_keypair_dup(me->pki_keypair));
500          }
501
502          /* Put a default cipher (not possible in the filed_conf.c structure */
503          if (!me->pki_cipher) {
504             me->pki_cipher = CRYPTO_CIPHER_AES_128_CBC;
505          }
506
507          /* Put a default digest (not possible in the filed_conf.c structure */
508          if (!me->pki_digest) {
509             me->pki_digest = CRYPTO_DIGEST_DEFAULT;
510          }
511
512          /* If additional keys have been specified, load them up */
513          if (me->pki_master_key_files) {
514             foreach_alist(filepath, me->pki_master_key_files) {
515                X509_KEYPAIR *keypair;
516
517                keypair = crypto_keypair_new();
518                if (!keypair) {
519                   Emsg0(M_FATAL, 0, _("Failed to allocate a new keypair object.\n"));
520                   OK = false;
521                } else {
522                   if (crypto_keypair_load_cert(keypair, filepath)) {
523                      me->pki_recipients->append(keypair);
524                   } else {
525                      Emsg3(M_FATAL, 0, _("Failed to load master key certificate"
526                         " from file %s for File daemon \"%s\" in %s.\n"), filepath, me->hdr.name, configfile);
527                      OK = false;
528                   }
529                }
530             }
531          }
532       }
533    }
534
535
536    /* Verify that a director record exists */
537    LockRes();
538    director = (DIRRES *)GetNextRes(R_DIRECTOR, NULL);
539    UnlockRes();
540    if (!director) {
541       Emsg1(M_FATAL, 0, _("No Director resource defined in %s\n"),
542             configfile);
543       OK = false;
544    }
545
546    foreach_res(director, R_DIRECTOR) {
547
548       /* Construct disabled command array */
549       for (i=0; cmds[i].cmd; i++) { }  /* Count commands */
550       if (director->disable_cmds) {
551          director->disabled_cmds_array = (bool *)malloc(i);
552          memset(director->disabled_cmds_array, 0, i);
553          foreach_alist(cmd, director->disable_cmds) {
554             found = false;
555             for (i=0; cmds[i].cmd; i++) {
556                if (strncasecmp(cmds[i].cmd, cmd, strlen(cmd)) == 0) {
557                   director->disabled_cmds_array[i] = true;
558                   found = true;
559                   break;
560                }
561             }
562             if (!found) {
563                Jmsg(NULL, M_FATAL, 0, _("Disable Command \"%s\" not found.\n"),
564                   cmd);
565                OK = false;
566             }
567          }
568       }
569
570 #ifdef xxxDEBUG
571       for (i=0; cmds[i].cmd; i++) { }  /* Count commands */
572       while (i-- >= 0) {
573          if (director->disabled_cmds_array[i]) {
574             Dmsg1(050, "Command: %s disabled for Director.\n", cmds[i].cmd);
575          }
576       }
577 #endif
578
579       /* tls_require implies tls_enable */
580       if (director->tls_require) {
581 #ifndef HAVE_TLS
582          Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
583          OK = false;
584          continue;
585 #else
586          director->tls_enable = true;
587 #endif
588       }
589       need_tls = director->tls_enable || director->tls_authenticate;
590
591       if (!director->tls_certfile && need_tls) {
592          Emsg2(M_FATAL, 0, _("\"TLS Certificate\" file not defined for Director \"%s\" in %s.\n"),
593                director->hdr.name, configfile);
594          OK = false;
595       }
596
597       if (!director->tls_keyfile && need_tls) {
598          Emsg2(M_FATAL, 0, _("\"TLS Key\" file not defined for Director \"%s\" in %s.\n"),
599                director->hdr.name, configfile);
600          OK = false;
601       }
602
603       if ((!director->tls_ca_certfile && !director->tls_ca_certdir) && need_tls && director->tls_verify_peer) {
604          Emsg2(M_FATAL, 0, _("Neither \"TLS CA Certificate\""
605                              " or \"TLS CA Certificate Dir\" are defined for Director \"%s\" in %s."
606                              " At least one CA certificate store is required"
607                              " when using \"TLS Verify Peer\".\n"),
608                              director->hdr.name, configfile);
609          OK = false;
610       }
611
612       /* If everything is well, attempt to initialize our per-resource TLS context */
613       if (OK && (need_tls || director->tls_require)) {
614          /* Initialize TLS context:
615           * Args: CA certfile, CA certdir, Certfile, Keyfile,
616           * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
617          director->tls_ctx = new_tls_context(director->tls_ca_certfile,
618             director->tls_ca_certdir, director->tls_certfile,
619             director->tls_keyfile, NULL, NULL, director->tls_dhfile,
620             director->tls_verify_peer);
621
622          if (!director->tls_ctx) {
623             Emsg2(M_FATAL, 0, _("Failed to initialize TLS context for Director \"%s\" in %s.\n"),
624                                 director->hdr.name, configfile);
625             OK = false;
626          }
627       }
628    }
629
630    CONSRES *console;
631    foreach_res(console, R_CONSOLE) {
632       /* tls_require implies tls_enable */
633       if (console->tls_require) {
634 #ifndef HAVE_TLS
635          Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
636          OK = false;
637          continue;
638 #else
639          console->tls_enable = true;
640 #endif
641       }
642       need_tls = console->tls_enable || console->tls_authenticate;
643
644       if (!console->tls_certfile && need_tls) {
645          Emsg2(M_FATAL, 0, _("\"TLS Certificate\" file not defined for Console \"%s\" in %s.\n"),
646                console->hdr.name, configfile);
647          OK = false;
648       }
649
650       if (!console->tls_keyfile && need_tls) {
651          Emsg2(M_FATAL, 0, _("\"TLS Key\" file not defined for Console \"%s\" in %s.\n"),
652                console->hdr.name, configfile);
653          OK = false;
654       }
655
656       if ((!console->tls_ca_certfile && !console->tls_ca_certdir) && need_tls && console->tls_verify_peer) {
657          Emsg2(M_FATAL, 0, _("Neither \"TLS CA Certificate\""
658                              " or \"TLS CA Certificate Dir\" are defined for Console \"%s\" in %s."
659                              " At least one CA certificate store is required"
660                              " when using \"TLS Verify Peer\".\n"),
661                              console->hdr.name, configfile);
662          OK = false;
663       }
664
665       /* If everything is well, attempt to initialize our per-resource TLS context */
666       if (OK && (need_tls || console->tls_require)) {
667          /* Initialize TLS context:
668           * Args: CA certfile, CA certdir, Certfile, Keyfile,
669           * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
670          console->tls_ctx = new_tls_context(console->tls_ca_certfile,
671             console->tls_ca_certdir, console->tls_certfile,
672             console->tls_keyfile, NULL, NULL, console->tls_dhfile,
673             console->tls_verify_peer);
674
675          if (!console->tls_ctx) {
676             Emsg2(M_FATAL, 0, _("Failed to initialize TLS context for Console \"%s\" in %s.\n"),
677                                 console->hdr.name, configfile);
678             OK = false;
679          }
680       }
681  
682    }
683    
684    UnlockRes();
685
686    if (OK) {
687       close_msg(NULL);                /* close temp message handler */
688       init_msg(NULL, me->messages);   /* open user specified message handler */
689    }
690
691    return OK;
692 }