]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/filed/filed.c
677d1721909799533f7d0663ec78ae4c586d36c0
[bacula/bacula] / bacula / src / filed / filed.c
1 /*
2    Bacula(R) - The Network Backup Solution
3
4    Copyright (C) 2000-2015 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
26 #include "bacula.h"
27 #include "filed.h"
28
29 /* Imported Functions */
30 extern void *handle_connection_request(void *dir_sock);
31 extern bool parse_fd_config(CONFIG *config, const char *configfile, int exit_code);
32
33 /* Forward referenced functions */
34 static bool check_resources();
35
36 /* Exported variables */
37 CLIENT *me;                           /* my resource */
38 bool no_signals = false;
39 void *start_heap;
40 extern struct s_cmds cmds[];
41
42 #ifndef CONFIG_FILE                   /* Might be overwritten */
43  #define CONFIG_FILE "bacula-fd.conf" /* default config file */
44  #define PROG_NAME   "bacula-fd"
45 #endif
46
47 char *configfile = NULL;
48 static bool test_config = false;
49 static bool foreground = false;
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       "     -s               no signals (for debugging)\n"
68       "     -t               test configuration file and exit\n"
69       "     -T               set trace on\n"
70       "     -u               userid\n"
71       "     -v               verbose user messages\n"
72       "     -?               print this message.\n"
73       "\n"), 2000, VERSION, BDATE);
74
75    exit(1);
76 }
77
78
79 /*********************************************************************
80  *
81  *  Main Bacula Unix Client Program
82  *
83  */
84
85 int main (int argc, char *argv[])
86 {
87    int ch;
88    bool keep_readall_caps = false;
89    char *uid = NULL;
90    char *gid = NULL;
91
92    start_heap = sbrk(0);
93    setlocale(LC_ALL, "");
94    bindtextdomain("bacula", LOCALEDIR);
95    textdomain("bacula");
96
97    init_stack_dump();
98    my_name_is(argc, argv, PROG_NAME);
99    init_msg(NULL, NULL);
100    daemon_start_time = time(NULL);
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    if (!no_signals) {
192       init_signals(terminate_filed);
193    } else {
194       /* This reduces the number of signals facilitating debugging */
195       watchdog_sleep_time = 120;      /* long timeout for debugging */
196    }
197
198    if (configfile == NULL) {
199       configfile = bstrdup(CONFIG_FILE);
200    }
201
202    if (!foreground) {
203       daemon_start();
204       init_stack_dump();              /* set new pid */
205    }
206
207    config = new_config_parser();
208    parse_fd_config(config, configfile, M_ERROR_TERM);
209
210    if (init_crypto() != 0) {
211       Emsg0(M_ERROR, 0, _("Cryptography library initialization failed.\n"));
212       terminate_filed(1);
213    }
214
215    if (!check_resources()) {
216       Emsg1(M_ERROR, 0, _("Please correct configuration file: %s\n"), configfile);
217       terminate_filed(1);
218    }
219
220    set_working_directory(me->working_directory);
221
222    if (test_config) {
223       terminate_filed(0);
224    }
225
226    set_thread_concurrency(me->MaxConcurrentJobs + 10);
227    lmgr_init_thread(); /* initialize the lockmanager stack */
228
229    /* Maximum 1 daemon at a time */
230    create_pid_file(me->pid_directory, PROG_NAME,
231                    get_first_port_host_order(me->FDaddrs));
232    read_state_file(me->working_directory, PROG_NAME,
233                    get_first_port_host_order(me->FDaddrs));
234
235    load_fd_plugins(me->plugin_directory);
236
237    drop(uid, gid, keep_readall_caps);
238
239 #ifdef BOMB
240    me += 1000000;
241 #endif
242
243    /* Setup default value for the the snapshot handler */
244    if (!me->snapshot_command) {
245       me->snapshot_command = snapshot_get_command();
246    }
247
248    if (!no_signals) {
249       start_watchdog();               /* start watchdog thread */
250       init_jcr_subsystem();           /* start JCR watchdogs etc. */
251    }
252    server_tid = pthread_self();
253
254    /* Become server, and handle requests */
255    IPADDR *p;
256    foreach_dlist(p, me->FDaddrs) {
257       Dmsg1(10, "filed: listening on port %d\n", p->get_port_host_order());
258    }
259    bnet_thread_server(me->FDaddrs, me->MaxConcurrentJobs, &dir_workq,
260       handle_connection_request);
261
262    terminate_filed(0);
263    exit(0);                           /* should never get here */
264 }
265
266 void terminate_filed(int sig)
267 {
268    static bool already_here = false;
269
270    if (already_here) {
271       bmicrosleep(2, 0);              /* yield */
272       exit(1);                        /* prevent loops */
273    }
274    already_here = true;
275    debug_level = 0;                   /* turn off debug */
276    stop_watchdog();
277
278    bnet_stop_thread_server(server_tid);
279    generate_daemon_event(NULL, "Exit");
280    unload_plugins();
281
282    if (!test_config) {
283       write_state_file(me->working_directory,
284                        "bacula-fd", get_first_port_host_order(me->FDaddrs));
285       delete_pid_file(me->pid_directory,
286                       "bacula-fd", get_first_port_host_order(me->FDaddrs));
287    }
288
289    if (configfile != NULL) {
290       free(configfile);
291    }
292
293    if (debug_level > 0) {
294       print_memory_pool_stats();
295    }
296
297    if (config) {
298       config->free_resources();
299       free(config);
300       config = NULL;
301    }
302    term_msg();
303    cleanup_crypto();
304    close_memory_pool();               /* release free memory in pool */
305    lmgr_cleanup_main();
306    sm_dump(false);                    /* dump orphaned buffers */
307    exit(sig);
308 }
309
310 /*
311 * Make a quick check to see that we have all the
312 * resources needed.
313 */
314 static bool check_resources()
315 {
316    int i;
317    bool found;
318    char *cmd;
319    bool OK = true;
320    DIRRES *director;
321    bool need_tls;
322
323    LockRes();
324
325    me = (CLIENT *)GetNextRes(R_CLIENT, NULL);
326    if (!me) {
327       Emsg1(M_FATAL, 0, _("No File daemon resource defined in %s\n"
328             "Without that I don't know who I am :-(\n"), configfile);
329       OK = false;
330    } else {
331       if (GetNextRes(R_CLIENT, (RES *) me) != NULL) {
332          Emsg1(M_FATAL, 0, _("Only one Client resource permitted in %s\n"),
333               configfile);
334          OK = false;
335       }
336       my_name_is(0, NULL, me->hdr.name);
337       if (!me->messages) {
338          me->messages = (MSGS *)GetNextRes(R_MSGS, NULL);
339          if (!me->messages) {
340              Emsg1(M_FATAL, 0, _("No Messages resource defined in %s\n"), configfile);
341              OK = false;
342          }
343       }
344
345       /* Construct disabled command array */
346       for (i=0; cmds[i].cmd; i++) { }  /* Count commands */
347       if (me->disable_cmds) {
348          me->disabled_cmds_array = (bool *)malloc(i);
349          memset(me->disabled_cmds_array, 0, i);
350          foreach_alist(cmd, me->disable_cmds) {
351             found = false;
352             for (i=0; cmds[i].cmd; i++) {
353                if (strncasecmp(cmds[i].cmd, cmd, strlen(cmd)) == 0) {
354                   me->disabled_cmds_array[i] = true;
355                   found = true;
356                   break;
357                }
358             }
359             if (!found) {
360                Jmsg(NULL, M_FATAL, 0, _("Disable Command \"%s\" not found.\n"),
361                   cmd);
362                OK = false;
363             }
364          }
365       }
366 #ifdef xxxDEBUG
367       for (i=0; cmds[i].cmd; i++) { }  /* Count commands */
368       while (i-- >= 0) {
369          if (me->disabled_cmds_array[i]) {
370             Dmsg1(050, "Command: %s disabled.\n", cmds[i].cmd);
371          }
372       }
373 #endif
374
375       /* tls_require implies tls_enable */
376       if (me->tls_require) {
377 #ifndef HAVE_TLS
378          Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
379          OK = false;
380 #else
381          me->tls_enable = true;
382 #endif
383       }
384       need_tls = me->tls_enable || me->tls_authenticate;
385
386       if ((!me->tls_ca_certfile && !me->tls_ca_certdir) && need_tls) {
387          Emsg1(M_FATAL, 0, _("Neither \"TLS CA Certificate\""
388             " or \"TLS CA Certificate Dir\" are defined for File daemon in %s.\n"),
389                             configfile);
390         OK = false;
391       }
392
393       /* If everything is well, attempt to initialize our per-resource TLS context */
394       if (OK && (need_tls || me->tls_require)) {
395          /* Initialize TLS context:
396           * Args: CA certfile, CA certdir, Certfile, Keyfile,
397           * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
398          me->tls_ctx = new_tls_context(me->tls_ca_certfile,
399             me->tls_ca_certdir, me->tls_certfile, me->tls_keyfile,
400             NULL, NULL, NULL, true);
401
402          if (!me->tls_ctx) {
403             Emsg2(M_FATAL, 0, _("Failed to initialize TLS context for File daemon \"%s\" in %s.\n"),
404                                 me->hdr.name, configfile);
405             OK = false;
406          }
407       }
408
409       if (me->pki_encrypt || me->pki_sign) {
410 #ifndef HAVE_CRYPTO
411          Jmsg(NULL, M_FATAL, 0, _("PKI encryption/signing enabled but not compiled into Bacula.\n"));
412          OK = false;
413 #endif
414       }
415
416       /* pki_encrypt implies pki_sign */
417       if (me->pki_encrypt) {
418          me->pki_sign = true;
419       }
420
421       if ((me->pki_encrypt || me->pki_sign) && !me->pki_keypair_file) {
422          Emsg2(M_FATAL, 0, _("\"PKI Key Pair\" must be defined for File"
423             " daemon \"%s\" in %s if either \"PKI Sign\" or"
424             " \"PKI Encrypt\" are enabled.\n"), me->hdr.name, configfile);
425          OK = false;
426       }
427
428       /* If everything is well, attempt to initialize our public/private keys */
429       if (OK && (me->pki_encrypt || me->pki_sign)) {
430          char *filepath;
431          /* Load our keypair */
432          me->pki_keypair = crypto_keypair_new();
433          if (!me->pki_keypair) {
434             Emsg0(M_FATAL, 0, _("Failed to allocate a new keypair object.\n"));
435             OK = false;
436          } else {
437             if (!crypto_keypair_load_cert(me->pki_keypair, me->pki_keypair_file)) {
438                Emsg2(M_FATAL, 0, _("Failed to load public certificate for File"
439                      " daemon \"%s\" in %s.\n"), me->hdr.name, configfile);
440                OK = false;
441             }
442
443             if (!crypto_keypair_load_key(me->pki_keypair, me->pki_keypair_file, NULL, NULL)) {
444                Emsg2(M_FATAL, 0, _("Failed to load private key for File"
445                      " daemon \"%s\" in %s.\n"), me->hdr.name, configfile);
446                OK = false;
447             }
448          }
449
450          /*
451           * Trusted Signers. We're always trusted.
452           */
453          me->pki_signers = New(alist(10, not_owned_by_alist));
454          if (me->pki_keypair) {
455             me->pki_signers->append(crypto_keypair_dup(me->pki_keypair));
456          }
457
458          /* If additional signing public keys have been specified, load them up */
459          if (me->pki_signing_key_files) {
460             foreach_alist(filepath, me->pki_signing_key_files) {
461                X509_KEYPAIR *keypair;
462
463                keypair = crypto_keypair_new();
464                if (!keypair) {
465                   Emsg0(M_FATAL, 0, _("Failed to allocate a new keypair object.\n"));
466                   OK = false;
467                } else {
468                   if (crypto_keypair_load_cert(keypair, filepath)) {
469                      me->pki_signers->append(keypair);
470
471                      /* Attempt to load a private key, if available */
472                      if (crypto_keypair_has_key(filepath)) {
473                         if (!crypto_keypair_load_key(keypair, filepath, NULL, NULL)) {
474                            Emsg3(M_FATAL, 0, _("Failed to load private key from file %s for File"
475                               " daemon \"%s\" in %s.\n"), filepath, me->hdr.name, configfile);
476                            OK = false;
477                         }
478                      }
479
480                   } else {
481                      Emsg3(M_FATAL, 0, _("Failed to load trusted signer certificate"
482                         " from file %s for File daemon \"%s\" in %s.\n"), filepath, me->hdr.name, configfile);
483                      OK = false;
484                   }
485                }
486             }
487          }
488
489          /*
490           * Crypto recipients. We're always included as a recipient.
491           * The symmetric session key will be encrypted for each of these readers.
492           */
493          me->pki_recipients = New(alist(10, not_owned_by_alist));
494          if (me->pki_keypair) {
495             me->pki_recipients->append(crypto_keypair_dup(me->pki_keypair));
496          }
497
498          /* Put a default cipher (not possible in the filed_conf.c structure */
499          if (!me->pki_cipher) {
500             me->pki_cipher = CRYPTO_CIPHER_AES_128_CBC;
501          }
502
503          /* Put a default digest (not possible in the filed_conf.c structure */
504          if (!me->pki_digest) {
505             me->pki_digest = CRYPTO_DIGEST_DEFAULT;
506          }
507
508          /* If additional keys have been specified, load them up */
509          if (me->pki_master_key_files) {
510             foreach_alist(filepath, me->pki_master_key_files) {
511                X509_KEYPAIR *keypair;
512
513                keypair = crypto_keypair_new();
514                if (!keypair) {
515                   Emsg0(M_FATAL, 0, _("Failed to allocate a new keypair object.\n"));
516                   OK = false;
517                } else {
518                   if (crypto_keypair_load_cert(keypair, filepath)) {
519                      me->pki_recipients->append(keypair);
520                   } else {
521                      Emsg3(M_FATAL, 0, _("Failed to load master key certificate"
522                         " from file %s for File daemon \"%s\" in %s.\n"), filepath, me->hdr.name, configfile);
523                      OK = false;
524                   }
525                }
526             }
527          }
528       }
529    }
530
531
532    /* Verify that a director record exists */
533    LockRes();
534    director = (DIRRES *)GetNextRes(R_DIRECTOR, NULL);
535    UnlockRes();
536    if (!director) {
537       Emsg1(M_FATAL, 0, _("No Director resource defined in %s\n"),
538             configfile);
539       OK = false;
540    }
541
542    foreach_res(director, R_DIRECTOR) {
543
544       /* Construct disabled command array */
545       for (i=0; cmds[i].cmd; i++) { }  /* Count commands */
546       if (director->disable_cmds) {
547          director->disabled_cmds_array = (bool *)malloc(i);
548          memset(director->disabled_cmds_array, 0, i);
549          foreach_alist(cmd, director->disable_cmds) {
550             found = false;
551             for (i=0; cmds[i].cmd; i++) {
552                if (strncasecmp(cmds[i].cmd, cmd, strlen(cmd)) == 0) {
553                   director->disabled_cmds_array[i] = true;
554                   found = true;
555                   break;
556                }
557             }
558             if (!found) {
559                Jmsg(NULL, M_FATAL, 0, _("Disable Command \"%s\" not found.\n"),
560                   cmd);
561                OK = false;
562             }
563          }
564       }
565
566 #ifdef xxxDEBUG
567       for (i=0; cmds[i].cmd; i++) { }  /* Count commands */
568       while (i-- >= 0) {
569          if (director->disabled_cmds_array[i]) {
570             Dmsg1(050, "Command: %s disabled for Director.\n", cmds[i].cmd);
571          }
572       }
573 #endif
574
575       /* tls_require implies tls_enable */
576       if (director->tls_require) {
577 #ifndef HAVE_TLS
578          Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
579          OK = false;
580          continue;
581 #else
582          director->tls_enable = true;
583 #endif
584       }
585       need_tls = director->tls_enable || director->tls_authenticate;
586
587       if (!director->tls_certfile && need_tls) {
588          Emsg2(M_FATAL, 0, _("\"TLS Certificate\" file not defined for Director \"%s\" in %s.\n"),
589                director->hdr.name, configfile);
590          OK = false;
591       }
592
593       if (!director->tls_keyfile && need_tls) {
594          Emsg2(M_FATAL, 0, _("\"TLS Key\" file not defined for Director \"%s\" in %s.\n"),
595                director->hdr.name, configfile);
596          OK = false;
597       }
598
599       if ((!director->tls_ca_certfile && !director->tls_ca_certdir) && need_tls && director->tls_verify_peer) {
600          Emsg2(M_FATAL, 0, _("Neither \"TLS CA Certificate\""
601                              " or \"TLS CA Certificate Dir\" are defined for Director \"%s\" in %s."
602                              " At least one CA certificate store is required"
603                              " when using \"TLS Verify Peer\".\n"),
604                              director->hdr.name, configfile);
605          OK = false;
606       }
607
608       /* If everything is well, attempt to initialize our per-resource TLS context */
609       if (OK && (need_tls || director->tls_require)) {
610          /* Initialize TLS context:
611           * Args: CA certfile, CA certdir, Certfile, Keyfile,
612           * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
613          director->tls_ctx = new_tls_context(director->tls_ca_certfile,
614             director->tls_ca_certdir, director->tls_certfile,
615             director->tls_keyfile, NULL, NULL, director->tls_dhfile,
616             director->tls_verify_peer);
617
618          if (!director->tls_ctx) {
619             Emsg2(M_FATAL, 0, _("Failed to initialize TLS context for Director \"%s\" in %s.\n"),
620                                 director->hdr.name, configfile);
621             OK = false;
622          }
623       }
624    }
625
626    UnlockRes();
627
628    if (OK) {
629       close_msg(NULL);                /* close temp message handler */
630       init_msg(NULL, me->messages);   /* open user specified message handler */
631    }
632
633    return OK;
634 }