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