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