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