]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/filed/filed.c
Merge branch 'master' into basejobv3
[bacula/bacula] / bacula / src / filed / filed.c
1 /*
2    Bacula® - The Network Backup Solution
3
4    Copyright (C) 2000-2008 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 two of the GNU 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 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  *   Version $Id$
34  *
35  */
36
37 #include "bacula.h"
38 #include "filed.h"
39
40 #ifdef HAVE_PYTHON
41
42 #undef _POSIX_C_SOURCE
43 #include <Python.h>
44
45 #include "lib/pythonlib.h"
46
47 /* Imported Functions */
48 extern PyObject *job_getattr(PyObject *self, char *attrname);
49 extern int job_setattr(PyObject *self, char *attrname, PyObject *value);
50
51 #endif /* HAVE_PYTHON */
52
53 /* Imported Functions */
54 extern void *handle_client_request(void *dir_sock);
55 extern bool parse_fd_config(CONFIG *config, const char *configfile, int exit_code);
56
57 /* Forward referenced functions */
58 void terminate_filed(int sig);
59 static bool check_resources();
60
61 /* Exported variables */
62 CLIENT *me;                           /* my resource */
63 bool no_signals = false;
64 void *start_heap;
65
66 #define CONFIG_FILE "bacula-fd.conf" /* default config file */
67
68 char *configfile = NULL;
69 static bool foreground = false;
70 static workq_t dir_workq;             /* queue of work from Director */
71 static pthread_t server_tid;
72 static CONFIG *config;
73
74 static void usage()
75 {
76    Pmsg3(-1, _(
77 PROG_COPYRIGHT
78 "\nVersion: %s (%s)\n\n"
79 "Usage: bacula-fd [-f -s] [-c config_file] [-d debug_level]\n"
80 "        -c <file>   use <file> as configuration file\n"
81 "        -d <nn>     set debug level to <nn>\n"
82 "        -dt         print a timestamp in debug output\n"
83 "        -f          run in foreground (for debugging)\n"
84 "        -g          groupid\n"
85 "        -k          keep readall capabilities\n"
86 "        -s          no signals (for debugging)\n"
87 "        -t          test configuration file and exit\n"
88 "        -u          userid\n"
89 "        -v          verbose user messages\n"
90 "        -?          print this message.\n"
91 "\n"), 2000, VERSION, BDATE);
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:kstu: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 's':
159          no_signals = true;
160          break;
161
162       case 't':
163          test_config = true;
164          break;
165
166       case 'u':                    /* set userid */
167          uid = optarg;
168          break;
169
170       case 'v':                    /* verbose */
171          verbose++;
172          break;
173
174       case '?':
175       default:
176          usage();
177
178       }
179    }
180    argc -= optind;
181    argv += optind;
182
183    if (argc) {
184       if (configfile != NULL)
185          free(configfile);
186       configfile = bstrdup(*argv);
187       argc--;
188       argv++;
189    }
190    if (argc) {
191       usage();
192    }
193
194    if (!uid && keep_readall_caps) {
195       Emsg0(M_ERROR_TERM, 0, _("-k option has no meaning without -u option.\n"));
196    }
197
198    server_tid = pthread_self();
199    if (!no_signals) {
200       init_signals(terminate_filed);
201    } else {
202       /* This reduces the number of signals facilitating debugging */
203       watchdog_sleep_time = 120;      /* long timeout for debugging */
204    }
205
206    if (configfile == NULL) {
207       configfile = bstrdup(CONFIG_FILE);
208    }
209
210    config = new_config_parser();
211    parse_fd_config(config, configfile, M_ERROR_TERM);
212
213    if (init_crypto() != 0) {
214       Emsg0(M_ERROR, 0, _("Cryptography library initialization failed.\n"));
215       terminate_filed(1);
216    }
217
218    if (!check_resources()) {
219       Emsg1(M_ERROR, 0, _("Please correct configuration file: %s\n"), configfile);
220       terminate_filed(1);
221    }
222
223    set_working_directory(me->working_directory);
224
225    if (test_config) {
226       terminate_filed(0);
227    }
228
229    if (!foreground) {
230       daemon_start();
231       init_stack_dump();              /* set new pid */
232    }
233
234    set_thread_concurrency(me->MaxConcurrentJobs + 10);
235    lmgr_init_thread(); /* initialize the lockmanager stack */
236
237    /* Maximum 1 daemon at a time */
238    create_pid_file(me->pid_directory, "bacula-fd",
239                    get_first_port_host_order(me->FDaddrs));
240    read_state_file(me->working_directory, "bacula-fd",
241                    get_first_port_host_order(me->FDaddrs));
242
243    load_fd_plugins(me->plugin_directory);
244
245    drop(uid, gid, keep_readall_caps);
246
247 #ifdef BOMB
248    me += 1000000;
249 #endif
250
251 #ifdef HAVE_PYTHON
252    python_args.progname = me->hdr.name;
253    python_args.scriptdir = me->scripts_directory;
254    python_args.modulename = "FDStartUp";
255    python_args.configfile = configfile;
256    python_args.workingdir = me->working_directory;
257    python_args.job_getattr = job_getattr;
258    python_args.job_setattr = job_setattr;
259
260    init_python_interpreter(&python_args);
261 #endif /* HAVE_PYTHON */
262
263    if (!no_signals) {
264       start_watchdog();               /* start watchdog thread */
265       init_jcr_subsystem();           /* start JCR watchdogs etc. */
266    }
267    server_tid = pthread_self();
268
269    /* Become server, and handle requests */
270    IPADDR *p;
271    foreach_dlist(p, me->FDaddrs) {
272       Dmsg1(10, "filed: listening on port %d\n", p->get_port_host_order());
273    }
274    bnet_thread_server(me->FDaddrs, me->MaxConcurrentJobs, &dir_workq, handle_client_request);
275
276    terminate_filed(0);
277    exit(0);                           /* should never get here */
278 }
279
280 void terminate_filed(int sig)
281 {
282    static bool already_here = false;
283
284    if (already_here) {
285       bmicrosleep(2, 0);              /* yield */
286       exit(1);                        /* prevent loops */
287    }
288    already_here = true;
289    debug_level = 0;                   /* turn off debug */
290    stop_watchdog();
291
292    bnet_stop_thread_server(server_tid);
293    generate_daemon_event(NULL, "Exit");
294    unload_plugins();
295    write_state_file(me->working_directory, "bacula-fd", get_first_port_host_order(me->FDaddrs));
296    delete_pid_file(me->pid_directory, "bacula-fd", get_first_port_host_order(me->FDaddrs));
297
298    if (configfile != NULL) {
299       free(configfile);
300    }
301
302    if (debug_level > 0) {
303       print_memory_pool_stats();
304    }
305    if (config) {
306       config->free_resources();
307       free(config);
308       config = NULL;
309    }
310    term_msg();
311    cleanup_crypto();
312    close_memory_pool();               /* release free memory in pool */
313    lmgr_cleanup_main();
314    sm_dump(false);                    /* dump orphaned buffers */
315    exit(sig);
316 }
317
318 /*
319 * Make a quick check to see that we have all the
320 * resources needed.
321 */
322 static bool check_resources()
323 {
324    bool OK = true;
325    DIRRES *director;
326    bool need_tls;
327
328    LockRes();
329
330    me = (CLIENT *)GetNextRes(R_CLIENT, NULL);
331    if (!me) {
332       Emsg1(M_FATAL, 0, _("No File daemon resource defined in %s\n"
333             "Without that I don't know who I am :-(\n"), configfile);
334       OK = false;
335    } else {
336       if (GetNextRes(R_CLIENT, (RES *) me) != NULL) {
337          Emsg1(M_FATAL, 0, _("Only one Client resource permitted in %s\n"),
338               configfile);
339          OK = false;
340       }
341       my_name_is(0, NULL, me->hdr.name);
342       if (!me->messages) {
343          me->messages = (MSGS *)GetNextRes(R_MSGS, NULL);
344          if (!me->messages) {
345              Emsg1(M_FATAL, 0, _("No Messages resource defined in %s\n"), configfile);
346              OK = false;
347          }
348       }
349       /* tls_require implies tls_enable */
350       if (me->tls_require) {
351 #ifndef HAVE_TLS
352          Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
353          OK = false;
354 #else
355          me->tls_enable = true;
356 #endif
357       }
358       need_tls = me->tls_enable || me->tls_authenticate;
359
360       if ((!me->tls_ca_certfile && !me->tls_ca_certdir) && need_tls) {
361          Emsg1(M_FATAL, 0, _("Neither \"TLS CA Certificate\""
362             " or \"TLS CA Certificate Dir\" are defined for File daemon in %s.\n"),
363                             configfile);
364         OK = false;
365       }
366
367       /* If everything is well, attempt to initialize our per-resource TLS context */
368       if (OK && (need_tls || me->tls_require)) {
369          /* Initialize TLS context:
370           * Args: CA certfile, CA certdir, Certfile, Keyfile,
371           * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
372          me->tls_ctx = new_tls_context(me->tls_ca_certfile,
373             me->tls_ca_certdir, me->tls_certfile, me->tls_keyfile,
374             NULL, NULL, NULL, true);
375
376          if (!me->tls_ctx) { 
377             Emsg2(M_FATAL, 0, _("Failed to initialize TLS context for File daemon \"%s\" in %s.\n"),
378                                 me->hdr.name, configfile);
379             OK = false;
380          }
381       }
382
383       if (me->pki_encrypt || me->pki_sign) {
384 #ifndef HAVE_CRYPTO
385          Jmsg(NULL, M_FATAL, 0, _("PKI encryption/signing enabled but not compiled into Bacula.\n"));
386          OK = false;
387 #endif
388       }
389
390       /* pki_encrypt implies pki_sign */
391       if (me->pki_encrypt) {
392          me->pki_sign = true;
393       }
394
395       if ((me->pki_encrypt || me->pki_sign) && !me->pki_keypair_file) {
396          Emsg2(M_FATAL, 0, _("\"PKI Key Pair\" must be defined for File"
397             " daemon \"%s\" in %s if either \"PKI Sign\" or"
398             " \"PKI Encrypt\" are enabled.\n"), me->hdr.name, configfile);
399          OK = false;
400       }
401
402       /* If everything is well, attempt to initialize our public/private keys */
403       if (OK && (me->pki_encrypt || me->pki_sign)) {
404          char *filepath;
405          /* Load our keypair */
406          me->pki_keypair = crypto_keypair_new();
407          if (!me->pki_keypair) {
408             Emsg0(M_FATAL, 0, _("Failed to allocate a new keypair object.\n"));
409             OK = false;
410          } else {
411             if (!crypto_keypair_load_cert(me->pki_keypair, me->pki_keypair_file)) {
412                Emsg2(M_FATAL, 0, _("Failed to load public certificate for File"
413                      " daemon \"%s\" in %s.\n"), me->hdr.name, configfile);
414                OK = false;
415             }
416
417             if (!crypto_keypair_load_key(me->pki_keypair, me->pki_keypair_file, NULL, NULL)) {
418                Emsg2(M_FATAL, 0, _("Failed to load private key for File"
419                      " daemon \"%s\" in %s.\n"), me->hdr.name, configfile);
420                OK = false;
421             }
422          }
423
424          /*
425           * Trusted Signers. We're always trusted.
426           */
427          me->pki_signers = New(alist(10, not_owned_by_alist));
428          if (me->pki_keypair) {
429             me->pki_signers->append(crypto_keypair_dup(me->pki_keypair));
430          }
431
432          /* If additional signing public keys have been specified, load them up */
433          if (me->pki_signing_key_files) {
434             foreach_alist(filepath, me->pki_signing_key_files) {
435                X509_KEYPAIR *keypair;
436
437                keypair = crypto_keypair_new();
438                if (!keypair) {
439                   Emsg0(M_FATAL, 0, _("Failed to allocate a new keypair object.\n"));
440                   OK = false;
441                } else {
442                   if (crypto_keypair_load_cert(keypair, filepath)) {
443                      me->pki_signers->append(keypair);
444
445                      /* Attempt to load a private key, if available */
446                      if (crypto_keypair_has_key(filepath)) {
447                         if (!crypto_keypair_load_key(keypair, filepath, NULL, NULL)) {
448                            Emsg3(M_FATAL, 0, _("Failed to load private key from file %s for File"
449                               " daemon \"%s\" in %s.\n"), filepath, me->hdr.name, configfile);
450                            OK = false;
451                         }
452                      }
453
454                   } else {
455                      Emsg3(M_FATAL, 0, _("Failed to load trusted signer certificate"
456                         " from file %s for File daemon \"%s\" in %s.\n"), filepath, me->hdr.name, configfile);
457                      OK = false;
458                   }
459                }
460             }
461          }
462
463          /*
464           * Crypto recipients. We're always included as a recipient.
465           * The symmetric session key will be encrypted for each of these readers.
466           */
467          me->pki_recipients = New(alist(10, not_owned_by_alist));
468          if (me->pki_keypair) {
469             me->pki_recipients->append(crypto_keypair_dup(me->pki_keypair));
470          }
471
472
473          /* If additional keys have been specified, load them up */
474          if (me->pki_master_key_files) {
475             foreach_alist(filepath, me->pki_master_key_files) {
476                X509_KEYPAIR *keypair;
477
478                keypair = crypto_keypair_new();
479                if (!keypair) {
480                   Emsg0(M_FATAL, 0, _("Failed to allocate a new keypair object.\n"));
481                   OK = false;
482                } else {
483                   if (crypto_keypair_load_cert(keypair, filepath)) {
484                      me->pki_recipients->append(keypair);
485                   } else {
486                      Emsg3(M_FATAL, 0, _("Failed to load master key certificate"
487                         " from file %s for File daemon \"%s\" in %s.\n"), filepath, me->hdr.name, configfile);
488                      OK = false;
489                   }
490                }
491             }
492          }
493       }
494    }
495
496
497    /* Verify that a director record exists */
498    LockRes();
499    director = (DIRRES *)GetNextRes(R_DIRECTOR, NULL);
500    UnlockRes();
501    if (!director) {
502       Emsg1(M_FATAL, 0, _("No Director resource defined in %s\n"),
503             configfile);
504       OK = false;
505    }
506
507    foreach_res(director, R_DIRECTOR) { 
508       /* tls_require implies tls_enable */
509       if (director->tls_require) {
510 #ifndef HAVE_TLS
511          Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
512          OK = false;
513          continue;
514 #else
515          director->tls_enable = true;
516 #endif
517       }
518       need_tls = director->tls_enable || director->tls_authenticate;
519
520       if (!director->tls_certfile && need_tls) {
521          Emsg2(M_FATAL, 0, _("\"TLS Certificate\" file not defined for Director \"%s\" in %s.\n"),
522                director->hdr.name, configfile);
523          OK = false;
524       }
525
526       if (!director->tls_keyfile && need_tls) {
527          Emsg2(M_FATAL, 0, _("\"TLS Key\" file not defined for Director \"%s\" in %s.\n"),
528                director->hdr.name, configfile);
529          OK = false;
530       }
531
532       if ((!director->tls_ca_certfile && !director->tls_ca_certdir) && need_tls && director->tls_verify_peer) {
533          Emsg2(M_FATAL, 0, _("Neither \"TLS CA Certificate\""
534                              " or \"TLS CA Certificate Dir\" are defined for Director \"%s\" in %s."
535                              " At least one CA certificate store is required"
536                              " when using \"TLS Verify Peer\".\n"),
537                              director->hdr.name, configfile);
538          OK = false;
539       }
540
541       /* If everything is well, attempt to initialize our per-resource TLS context */
542       if (OK && (need_tls || director->tls_require)) {
543          /* Initialize TLS context:
544           * Args: CA certfile, CA certdir, Certfile, Keyfile,
545           * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
546          director->tls_ctx = new_tls_context(director->tls_ca_certfile,
547             director->tls_ca_certdir, director->tls_certfile,
548             director->tls_keyfile, NULL, NULL, director->tls_dhfile,
549             director->tls_verify_peer);
550
551          if (!director->tls_ctx) { 
552             Emsg2(M_FATAL, 0, _("Failed to initialize TLS context for Director \"%s\" in %s.\n"),
553                                 director->hdr.name, configfile);
554             OK = false;
555          }
556       }
557    }
558
559    UnlockRes();
560
561    if (OK) {
562       close_msg(NULL);                /* close temp message handler */
563       init_msg(NULL, me->messages);   /* open user specified message handler */
564    }
565
566    return OK;
567 }