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