]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/stored.c
Make a few tls ifdef tweaks
[bacula/bacula] / bacula / src / stored / stored.c
1 /*
2  * Second generation Storage daemon.
3  *
4  * It accepts a number of simple commands from the File daemon
5  * and acts on them. When a request to append data is made,
6  * it opens a data channel and accepts data from the
7  * File daemon.
8  *
9  *   Version $Id$
10  *
11  */
12 /*
13    Copyright (C) 2000-2005 Kern Sibbald
14
15    This program is free software; you can redistribute it and/or
16    modify it under the terms of the GNU General Public License as
17    published by the Free Software Foundation; either version 2 of
18    the License, or (at your option) any later version.
19
20    This program is distributed in the hope that it will be useful,
21    but WITHOUT ANY WARRANTY; without even the implied warranty of
22    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23    General Public License for more details.
24
25    You should have received a copy of the GNU General Public
26    License along with this program; if not, write to the Free
27    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
28    MA 02111-1307, USA.
29
30  */
31
32 #include "bacula.h"
33 #include "stored.h"
34
35 /* Imported functions */
36
37
38 /* Forward referenced functions */
39 void terminate_stored(int sig);
40 static int check_resources();
41
42 extern "C" void *device_initialization(void *arg);
43
44 #define CONFIG_FILE "bacula-sd.conf"  /* Default config file */
45
46 /* Global variables exported */
47 char OK_msg[]   = "3000 OK\n";
48 char TERM_msg[] = "3999 Terminate\n";
49 STORES *me = NULL;                    /* our Global resource */
50 bool forge_on = false;                /* proceed inspite of I/O errors */
51 pthread_mutex_t device_release_mutex = PTHREAD_MUTEX_INITIALIZER;
52 pthread_cond_t wait_device_release = PTHREAD_COND_INITIALIZER;
53
54
55 static uint32_t VolSessionId = 0;
56 uint32_t VolSessionTime;
57 char *configfile;
58
59 /* Global static variables */
60 static int foreground = 0;
61 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
62 static workq_t dird_workq;            /* queue for processing connections */
63
64
65 static void usage()
66 {
67    fprintf(stderr, _(
68 "Copyright (C) 2000-2005 Kern Sibbald.\n"
69 "\nVersion: " VERSION " (" BDATE ")\n\n"
70 "Usage: stored [options] [-c config_file] [config_file]\n"
71 "        -c <file>   use <file> as configuration file\n"
72 "        -dnn        set debug level to nn\n"
73 "        -f          run in foreground (for debugging)\n"
74 "        -g <group>  set groupid to group\n"
75 "        -p          proceed despite I/O errors\n"
76 "        -s          no signals (for debugging)\n"
77 "        -t          test - read config and exit\n"
78 "        -u <user>   userid to <user>\n"
79 "        -v          verbose user messages\n"
80 "        -?          print this message.\n"
81 "\n"));
82    exit(1);
83 }
84
85 /*********************************************************************
86  *
87  *  Main Bacula Unix Storage Daemon
88  *
89  */
90 int main (int argc, char *argv[])
91 {
92    int ch;
93    int no_signals = FALSE;
94    int test_config = FALSE;
95    pthread_t thid;
96    char *uid = NULL;
97    char *gid = NULL;
98
99    init_stack_dump();
100    my_name_is(argc, argv, "bacula-sd");
101    textdomain("bacula");
102    init_msg(NULL, NULL);
103    daemon_start_time = time(NULL);
104
105    /* Sanity checks */
106    if (TAPE_BSIZE % B_DEV_BSIZE != 0 || TAPE_BSIZE / B_DEV_BSIZE == 0) {
107       Emsg2(M_ABORT, 0, "Tape block size (%d) not multiple of system size (%d)\n",
108          TAPE_BSIZE, B_DEV_BSIZE);
109    }
110    if (TAPE_BSIZE != (1 << (ffs(TAPE_BSIZE)-1))) {
111       Emsg1(M_ABORT, 0, "Tape block size (%d) is not a power of 2\n", TAPE_BSIZE);
112    }
113
114    while ((ch = getopt(argc, argv, "c:d:fg:pstu:v?")) != -1) {
115       switch (ch) {
116       case 'c':                    /* configuration file */
117          if (configfile != NULL) {
118             free(configfile);
119          }
120          configfile = bstrdup(optarg);
121          break;
122
123       case 'd':                    /* debug level */
124          debug_level = atoi(optarg);
125          if (debug_level <= 0) {
126             debug_level = 1;
127          }
128          break;
129
130       case 'f':                    /* run in foreground */
131          foreground = TRUE;
132          break;
133
134       case 'g':                    /* set group id */
135          gid = optarg;
136          break;
137
138       case 'p':                    /* proceed in spite of I/O errors */
139          forge_on = true;
140          break;
141
142       case 's':                    /* no signals */
143          no_signals = TRUE;
144          break;
145
146       case 't':
147          test_config = TRUE;
148          break;
149
150       case 'u':                    /* set uid */
151          uid = optarg;
152          break;
153
154       case 'v':                    /* verbose */
155          verbose++;
156          break;
157
158       case '?':
159       default:
160          usage();
161          break;
162       }
163    }
164    argc -= optind;
165    argv += optind;
166
167    if (argc) {
168       if (configfile != NULL) {
169          free(configfile);
170       }
171       configfile = bstrdup(*argv);
172       argc--;
173       argv++;
174    }
175    if (argc)
176       usage();
177
178    if (!no_signals) {
179       init_signals(terminate_stored);
180    }
181
182    if (configfile == NULL) {
183       configfile = bstrdup(CONFIG_FILE);
184    }
185
186    parse_config(configfile);
187
188    if (init_tls() != 0) {
189       Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("TLS library initialization failed.\n"));
190    }
191
192    if (!check_resources()) {
193       Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
194    }
195
196    if (test_config) {
197       terminate_stored(0);
198    }
199
200    my_name_is(0, (char **)NULL, me->hdr.name);     /* Set our real name */
201
202    if (!foreground) {
203       daemon_start();                 /* become daemon */
204       init_stack_dump();              /* pick up new pid */
205    }
206
207    create_pid_file(me->pid_directory, "bacula-sd", get_first_port_host_order(me->sdaddrs));
208    read_state_file(me->working_directory, "bacula-sd", get_first_port_host_order(me->sdaddrs));
209
210    drop(uid, gid);
211
212    /* Ensure that Volume Session Time and Id are both
213     * set and are both non-zero.
214     */
215    VolSessionTime = (long)daemon_start_time;
216    if (VolSessionTime == 0) { /* paranoid */
217       Jmsg0(NULL, M_ABORT, 0, _("Volume Session Time is ZERO!\n"));
218    }
219
220    init_python_interpreter(me->hdr.name, me->scripts_directory, "SDStartUp");
221
222    /* Make sure on Solaris we can run concurrent, watch dog + servers + misc */
223    set_thread_concurrency(me->max_concurrent_jobs * 2 + 4);
224
225     /*
226      * Start the device allocation thread
227      */
228    if (pthread_create(&thid, NULL, device_initialization, NULL) != 0) {
229       Emsg1(M_ABORT, 0, _("Unable to create thread. ERR=%s\n"), strerror(errno));
230    }
231
232    start_watchdog();                  /* start watchdog thread */
233
234    init_jcr_subsystem();              /* start JCR watchdogs etc. */
235
236    /*
237     * Sleep a bit to give device thread a chance to lock the resource
238     * chain before we start the server.
239     */
240    bmicrosleep(1, 0);
241
242    /* Single server used for Director and File daemon */
243    bnet_thread_server(me->sdaddrs, me->max_concurrent_jobs * 2 + 1,
244                       &dird_workq, handle_connection_request);
245    exit(1);                           /* to keep compiler quiet */
246 }
247
248 /* Return a new Session Id */
249 uint32_t newVolSessionId()
250 {
251    uint32_t Id;
252
253    P(mutex);
254    VolSessionId++;
255    Id = VolSessionId;
256    V(mutex);
257    return Id;
258 }
259
260 /* Check Configuration file for necessary info */
261 static int check_resources()
262 {
263    bool OK = true;
264    AUTOCHANGER *changer;
265
266    LockRes();
267
268    me = (STORES *)GetNextRes(R_STORAGE, NULL);
269    if (!me) {
270       Jmsg1(NULL, M_ERROR, 0, _("No Storage resource defined in %s. Cannot continue.\n"),
271          configfile);
272       OK = false;
273    }
274
275    if (GetNextRes(R_STORAGE, (RES *)me) != NULL) {
276       Jmsg1(NULL, M_ERROR, 0, _("Only one Storage resource permitted in %s\n"),
277          configfile);
278       OK = false;
279    }
280    if (GetNextRes(R_DIRECTOR, NULL) == NULL) {
281       Jmsg1(NULL, M_ERROR, 0, _("No Director resource defined in %s. Cannot continue.\n"),
282          configfile);
283       OK = false;
284    }
285    if (GetNextRes(R_DEVICE, NULL) == NULL){
286       Jmsg1(NULL, M_ERROR, 0, _("No Device resource defined in %s. Cannot continue.\n"),
287            configfile);
288       OK = false;
289    }
290
291    if (!me->messages) {
292       me->messages = (MSGS *)GetNextRes(R_MSGS, NULL);
293       if (!me->messages) {
294          Jmsg1(NULL, M_ERROR, 0, _("No Messages resource defined in %s. Cannot continue.\n"),
295             configfile);
296          OK = false;
297       }
298    }
299
300    if (!me->working_directory) {
301       Jmsg1(NULL, M_ERROR, 0, _("No Working Directory defined in %s. Cannot continue.\n"),
302          configfile);
303       OK = false;
304    }
305
306 #ifdef HAVE_TLS
307    DIRRES *director;
308    STORES *store;
309    foreach_res(store, R_STORAGE) { 
310       /* tls_require implies tls_enable */
311       if (store->tls_require) {
312          store->tls_enable = true;
313       }
314
315       if (!store->tls_certfile && store->tls_enable) {
316          Jmsg(NULL, M_FATAL, 0, _("\"TLS Certificate\" file not defined for Storage \"%s\" in %s.\n"),
317               store->hdr.name, configfile);
318          OK = false;
319       }
320
321       if (!store->tls_keyfile && store->tls_enable) {
322          Jmsg(NULL, M_FATAL, 0, _("\"TLS Key\" file not defined for Storage \"%s\" in %s.\n"),
323               store->hdr.name, configfile);
324          OK = false;
325       }
326
327       if ((!store->tls_ca_certfile && !store->tls_ca_certdir) && store->tls_enable && store->tls_verify_peer) {
328          Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\""
329               " or \"TLS CA Certificate Dir\" are defined for Storage \"%s\" in %s."
330               " At least one CA certificate store is required"
331               " when using \"TLS Verify Peer\".\n"),
332               store->hdr.name, configfile);
333          OK = false;
334       }
335
336       /* If everything is well, attempt to initialize our per-resource TLS context */
337       if (OK && (store->tls_enable || store->tls_require)) {
338          /* Initialize TLS context:
339           * Args: CA certfile, CA certdir, Certfile, Keyfile,
340           * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
341          store->tls_ctx = new_tls_context(store->tls_ca_certfile,
342             store->tls_ca_certdir, store->tls_certfile,
343             store->tls_keyfile, NULL, NULL, store->tls_dhfile,
344             store->tls_verify_peer);
345
346          if (!store->tls_ctx) { 
347             Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for Storage \"%s\" in %s.\n"),
348                  store->hdr.name, configfile);
349             OK = false;
350          }
351       }
352    }
353
354    foreach_res(director, R_DIRECTOR) { 
355       /* tls_require implies tls_enable */
356       if (director->tls_require) {
357          director->tls_enable = true;
358       }
359
360       if (!director->tls_certfile && director->tls_enable) {
361          Jmsg(NULL, M_FATAL, 0, _("\"TLS Certificate\" file not defined for Director \"%s\" in %s.\n"),
362               director->hdr.name, configfile);
363          OK = false;
364       }
365
366       if (!director->tls_keyfile && director->tls_enable) {
367          Jmsg(NULL, M_FATAL, 0, _("\"TLS Key\" file not defined for Director \"%s\" in %s.\n"),
368               director->hdr.name, configfile);
369          OK = false;
370       }
371
372       if ((!director->tls_ca_certfile && !director->tls_ca_certdir) && director->tls_enable && director->tls_verify_peer) {
373          Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\""
374               " or \"TLS CA Certificate Dir\" are defined for Director \"%s\" in %s."
375               " At least one CA certificate store is required"
376               " when using \"TLS Verify Peer\".\n"),
377               director->hdr.name, configfile);
378          OK = false;
379       }
380
381       /* If everything is well, attempt to initialize our per-resource TLS context */
382       if (OK && (director->tls_enable || director->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          director->tls_ctx = new_tls_context(director->tls_ca_certfile,
387             director->tls_ca_certdir, director->tls_certfile,
388             director->tls_keyfile, NULL, NULL, director->tls_dhfile,
389             director->tls_verify_peer);
390
391          if (!director->tls_ctx) { 
392             Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for Director \"%s\" in %s.\n"),
393                  director->hdr.name, configfile);
394             OK = false;
395          }
396       }
397    }
398 #endif /* HAVE_TLS */
399
400    /* Ensure that the media_type for each device is the same */
401    foreach_res(changer, R_AUTOCHANGER) {
402       DEVRES *device;
403       char *media_type = NULL;
404       foreach_alist(device, changer->device) {
405          if (media_type == NULL) {
406             media_type = device->media_type;
407             continue;
408          }     
409          if (strcmp(media_type, device->media_type) != 0) {
410             Jmsg(NULL, M_ERROR, 0, 
411                _("Media Type not the same for all devices in changer %s. Cannot continue.\n"),
412                changer->hdr.name);
413             OK = false;
414             continue;
415          }
416          /*
417           * If the device does not have a changer name or changer command
418           * defined, used the one from the Autochanger resource 
419           */
420          if (!device->changer_name) {
421             device->changer_name = bstrdup(changer->changer_name);
422          }
423          if (!device->changer_command) {
424             device->changer_command = bstrdup(changer->changer_command);
425          }
426       }
427    }
428    
429    UnlockRes();
430
431    if (OK) {
432       close_msg(NULL);                   /* close temp message handler */
433       init_msg(NULL, me->messages);      /* open daemon message handler */
434       set_working_directory(me->working_directory);
435    }
436
437    return OK;
438 }
439
440 /*
441  * Here we attempt to init and open each device. This is done
442  *  once at startup in a separate thread.
443  */
444 extern "C"
445 void *device_initialization(void *arg)
446 {
447    DEVRES *device;
448
449    LockRes();
450    pthread_detach(pthread_self());
451
452    foreach_res(device, R_DEVICE) {
453       Dmsg1(90, "calling init_dev %s\n", device->device_name);
454       device->dev = init_dev(NULL, NULL, device);
455       Dmsg1(10, "SD init done %s\n", device->device_name);
456       if (!device->dev) {
457          Jmsg1(NULL, M_ERROR, 0, _("Could not initialize %s\n"), device->device_name);
458          continue;
459       }
460
461       if (device->cap_bits & CAP_ALWAYSOPEN) {
462          Dmsg1(20, "calling first_open_device %s\n", device->device_name);
463          if (!first_open_device(device->dev)) {
464             Jmsg1(NULL, M_ERROR, 0, _("Could not open device %s\n"), device->device_name);
465          }
466       }
467       if (device->cap_bits & CAP_AUTOMOUNT && device->dev &&
468           device->dev->is_open()) {
469          JCR *jcr;
470          DCR *dcr;
471          jcr = new_jcr(sizeof(JCR), stored_free_jcr);
472          jcr->JobType = JT_SYSTEM;
473          /* Initialize FD start condition variable */
474          int errstat = pthread_cond_init(&jcr->job_start_wait, NULL);
475          if (errstat != 0) {
476             Jmsg1(jcr, M_ABORT, 0, _("Unable to init job cond variable: ERR=%s\n"), strerror(errstat));
477          }
478          dcr = new_dcr(jcr, device->dev);
479          switch (read_dev_volume_label(dcr)) {
480          case VOL_OK:
481             memcpy(&dcr->dev->VolCatInfo, &dcr->VolCatInfo, sizeof(dcr->dev->VolCatInfo));
482             break;
483          default:
484             Jmsg1(NULL, M_WARNING, 0, _("Could not mount device %s\n"), device->device_name);
485             break;
486          }
487          free_jcr(jcr);
488       }
489    }
490    UnlockRes();
491    return NULL;
492 }
493
494
495 /* Clean up and then exit */
496 void terminate_stored(int sig)
497 {
498    static bool in_here = false;
499    DEVRES *device;
500    JCR *jcr;
501
502    if (in_here) {                     /* prevent loops */
503       exit(1);
504    }
505    in_here = true;
506
507    if (sig == SIGTERM) {              /* normal shutdown request? */
508       /*
509        * This is a normal shutdown request. We wiffle through
510        *   all open jobs canceling them and trying to wake
511        *   them up so that they will report back the correct
512        *   volume status.
513        */
514       lock_jcr_chain();
515       foreach_jcr(jcr) {
516          BSOCK *fd;
517          free_locked_jcr(jcr);
518          if (jcr->JobId == 0) {
519             continue;                 /* ignore console */
520          }
521          set_jcr_job_status(jcr, JS_Canceled);
522          fd = jcr->file_bsock;
523          if (fd) {
524             fd->timed_out = true;
525             Dmsg1(100, "term_stored killing JobId=%d\n", jcr->JobId);
526             pthread_kill(jcr->my_thread_id, TIMEOUT_SIGNAL);
527             /* ***FIXME*** wiffle through all dcrs */
528             if (jcr->dcr && jcr->dcr->dev && jcr->dcr->dev->dev_blocked) {
529                pthread_cond_broadcast(&jcr->dcr->dev->wait_next_vol);
530                pthread_cond_broadcast(&wait_device_release);
531             }
532             bmicrosleep(0, 50000);
533           }
534       }
535       unlock_jcr_chain();
536       bmicrosleep(0, 500000);         /* give them 1/2 sec to clean up */
537    }
538
539    write_state_file(me->working_directory, "bacula-sd", get_first_port_host_order(me->sdaddrs));
540    delete_pid_file(me->pid_directory, "bacula-sd", get_first_port_host_order(me->sdaddrs));
541
542    Dmsg1(200, "In terminate_stored() sig=%d\n", sig);
543
544    LockRes();
545    foreach_res(device, R_DEVICE) {
546       if (device->dev) {
547          term_dev(device->dev);
548       }
549    }
550    UnlockRes();
551
552    if (configfile)
553    free(configfile);
554    free_config_resources();
555
556    if (debug_level > 10) {
557       print_memory_pool_stats();
558    }
559    term_msg();
560    stop_watchdog();
561    cleanup_tls();
562    close_memory_pool();
563
564    sm_dump(false);                    /* dump orphaned buffers */
565    exit(sig);
566 }