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