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