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