]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/stored.c
Backport Enterprise code
[bacula/bacula] / bacula / src / stored / stored.c
1 /*
2    Bacula(R) - The Network Backup Solution
3
4    Copyright (C) 2000-2017 Kern Sibbald
5
6    The original author of Bacula is Kern Sibbald, with contributions
7    from many others, a complete list can be found in the file AUTHORS.
8
9    You may use this file and others of this release according to the
10    license defined in the LICENSE file, which includes the Affero General
11    Public License, v3.0 ("AGPLv3") and some additional permissions and
12    terms pursuant to its AGPLv3 Section 7.
13
14    This notice must be preserved when any source code is
15    conveyed and/or propagated.
16
17    Bacula(R) is a registered trademark of Kern Sibbald.
18 */
19 /*
20  * Third generation Storage daemon.
21  *
22  *  Written by Kern Sibbald, MM
23  *
24  * It accepts a number of simple commands from the File daemon
25  * and acts on them. When a request to append data is made,
26  * it opens a data channel and accepts data from the
27  * File daemon.
28  *
29  */
30
31 #include "bacula.h"
32 #include "stored.h"
33
34 /* TODO: fix problem with bls, bextract
35  * that use findlib and already declare
36  * filed plugins
37  */
38 #include "sd_plugins.h"
39
40 /* Imported functions and variables */
41 extern bool parse_sd_config(CONFIG *config, const char *configfile, int exit_code);
42
43 /* Forward referenced functions */
44 void terminate_stored(int sig);
45 static int check_resources();
46 static void cleanup_old_files();
47
48 extern "C" void *device_initialization(void *arg);
49
50 #define CONFIG_FILE "bacula-sd.conf"  /* Default config file */
51
52 /* Global variables exported */
53 char OK_msg[]   = "3000 OK\n";
54 char TERM_msg[] = "3999 Terminate\n";
55 void *start_heap;
56 static bool test_config = false;
57
58
59 static uint32_t VolSessionId = 0;
60 uint32_t VolSessionTime;
61 char *configfile = NULL;
62 bool init_done = false;
63 static pthread_t server_tid;
64 static bool server_tid_valid = false;
65
66 /* Global static variables */
67 static bool foreground = 0;
68 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
69 static workq_t dird_workq;            /* queue for processing connections */
70 static CONFIG *config;
71
72
73 static void usage()
74 {
75    fprintf(stderr, _(
76       PROG_COPYRIGHT
77       "\n%sVersion: %s (%s)\n\n"
78       "Usage: bacula-sd [options] [-c config_file] [config_file]\n"
79       "     -c <file>         use <file> as configuration file\n"
80       "     -d <nn>[,<tags>]  set debug level to <nn>, debug tags to <tags>\n"
81       "     -dt               print timestamp in debug output\n"
82       "     -T                set trace on\n"
83       "     -f                run in foreground (for debugging)\n"
84       "     -g <group>        set groupid to group\n"
85       "     -m                print kaboom output (for debugging)\n"
86       "     -p                proceed despite I/O errors\n"
87       "     -s                no signals (for debugging)\n"
88       "     -t                test - read config and exit\n"
89       "     -u <user>         userid to <user>\n"
90       "     -v                verbose user messages\n"
91       "     -?                print this message.\n"
92       "\n"), 2000, "", VERSION, BDATE);
93    exit(1);
94 }
95
96 /*
97  * !!! WARNING !!! Use this function only when bacula is stopped.
98  * ie, after a fatal signal and before exiting the program
99  * Print information about a JCR
100  */
101 static void sd_debug_print(JCR *jcr, FILE *fp)
102 {
103    if (jcr->dcr) {
104       DCR *dcr = jcr->dcr;
105       fprintf(fp, "\tdcr=%p volumename=%s dev=%p newvol=%d reserved=%d locked=%d\n",
106               dcr, dcr->VolumeName, dcr->dev, dcr->NewVol,
107               dcr->is_reserved(),
108               dcr->is_dev_locked());
109    } else {
110       fprintf(fp, "dcr=*None*\n");
111    }
112 }
113
114 /*********************************************************************
115  *
116  *  Main Bacula Unix Storage Daemon
117  *
118  */
119 #if defined(HAVE_WIN32)
120 #define main BaculaMain
121 #endif
122
123 int main (int argc, char *argv[])
124 {
125    int ch;
126    bool no_signals = false;
127    pthread_t thid;
128    char *uid = NULL;
129    char *gid = NULL;
130
131    start_heap = sbrk(0);
132    setlocale(LC_ALL, "");
133    bindtextdomain("bacula", LOCALEDIR);
134    textdomain("bacula");
135
136    init_stack_dump();
137    my_name_is(argc, argv, "bacula-sd");
138    init_msg(NULL, NULL);
139    daemon_start_time = time(NULL);
140    setup_daemon_message_queue();
141
142    /* Sanity checks */
143    if (TAPE_BSIZE % B_DEV_BSIZE != 0 || TAPE_BSIZE / B_DEV_BSIZE == 0) {
144       Jmsg2(NULL, M_ABORT, 0, _("Tape block size (%d) not multiple of system size (%d)\n"),
145          TAPE_BSIZE, B_DEV_BSIZE);
146    }
147    if (TAPE_BSIZE != (1 << (ffs(TAPE_BSIZE)-1))) {
148       Jmsg1(NULL, M_ABORT, 0, _("Tape block size (%d) is not a power of 2\n"), TAPE_BSIZE);
149    }
150
151    while ((ch = getopt(argc, argv, "c:d:fg:mpstu:v?Ti")) != -1) {
152       switch (ch) {
153       case 'c':                    /* configuration file */
154          if (configfile != NULL) {
155             free(configfile);
156          }
157          configfile = bstrdup(optarg);
158          break;
159
160       case 'd':                    /* debug level */
161          if (*optarg == 't') {
162             dbg_timestamp = true;
163          } else {
164             char *p;
165             /* We probably find a tag list -d 10,sql,bvfs */
166             if ((p = strchr(optarg, ',')) != NULL) {
167                *p = 0;
168             }
169             debug_level = atoi(optarg);
170             if (debug_level <= 0) {
171                debug_level = 1;
172             }
173             if (p) {
174                debug_parse_tags(p+1, &debug_level_tags);
175             }
176          }
177          break;
178
179       case 'T':
180          set_trace(true);
181          break;
182
183       case 'f':                    /* run in foreground */
184          foreground = true;
185          break;
186
187       case 'g':                    /* set group id */
188          gid = optarg;
189          break;
190
191       case 'm':                    /* print kaboom output */
192          prt_kaboom = true;
193          break;
194
195       case 'p':                    /* proceed in spite of I/O errors */
196          forge_on = true;
197          break;
198
199       case 's':                    /* no signals */
200          no_signals = true;
201          break;
202
203       case 't':
204          test_config = true;
205          break;
206
207       case 'u':                    /* set uid */
208          uid = optarg;
209          break;
210
211       case 'v':                    /* verbose */
212          verbose++;
213          break;
214
215       /* Temp code to enable new match_bsr() code, not documented */
216       case 'i':
217          use_new_match_all = 1;
218          break;
219
220       case '?':
221       default:
222          usage();
223          break;
224       }
225    }
226    argc -= optind;
227    argv += optind;
228
229    if (argc) {
230       if (configfile != NULL) {
231          free(configfile);
232       }
233       configfile = bstrdup(*argv);
234       argc--;
235       argv++;
236    }
237    if (argc) {
238       usage();
239    }
240
241    if (!foreground && !test_config) {
242       daemon_start();                 /* become daemon */
243       init_stack_dump();              /* pick up new pid */
244    }
245
246    if (!no_signals) {
247       init_signals(terminate_stored);
248    }
249
250    if (configfile == NULL) {
251       configfile = bstrdup(CONFIG_FILE);
252    }
253
254    config = New(CONFIG());
255    parse_sd_config(config, configfile, M_ERROR_TERM);
256
257    if (init_crypto() != 0) {
258       Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Cryptography library initialization failed.\n"));
259    }
260
261    if (!check_resources()) {
262       Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
263    }
264
265    init_reservations_lock();
266
267    if (test_config) {
268       terminate_stored(0);
269    }
270
271    my_name_is(0, (char **)NULL, me->hdr.name);     /* Set our real name */
272
273
274    create_pid_file(me->pid_directory, "bacula-sd",
275                    get_first_port_host_order(me->sdaddrs));
276    read_state_file(me->working_directory, "bacula-sd",
277                    get_first_port_host_order(me->sdaddrs));
278
279    set_jcr_in_tsd(INVALID_JCR);
280    /* Make sure on Solaris we can run concurrent, watch dog + servers + misc */
281    set_thread_concurrency(me->max_concurrent_jobs * 2 + 4);
282    lmgr_init_thread(); /* initialize the lockmanager stack */
283
284    load_sd_plugins(me->plugin_directory);
285
286    drop(uid, gid, false);
287
288    cleanup_old_files();
289
290    /* Ensure that Volume Session Time and Id are both
291     * set and are both non-zero.
292     */
293    VolSessionTime = (uint32_t)daemon_start_time;
294    if (VolSessionTime == 0) { /* paranoid */
295       Jmsg0(NULL, M_ABORT, 0, _("Volume Session Time is ZERO!\n"));
296    }
297
298    /*
299     * Start the device allocation thread
300     */
301    create_volume_lists();             /* do before device_init */
302    if (pthread_create(&thid, NULL, device_initialization, NULL) != 0) {
303       berrno be;
304       Jmsg1(NULL, M_ABORT, 0, _("Unable to create thread. ERR=%s\n"), be.bstrerror());
305    }
306
307    start_watchdog();                  /* start watchdog thread */
308    init_jcr_subsystem();              /* start JCR watchdogs etc. */
309    dbg_jcr_add_hook(sd_debug_print); /* used to director variables */
310
311    /* Single server used for Director and File daemon */
312    server_tid = pthread_self();
313    server_tid_valid = true;
314    bnet_thread_server(me->sdaddrs, me->max_concurrent_jobs * 2 + 1,
315                       &dird_workq, handle_connection_request);
316    exit(1);                           /* to keep compiler quiet */
317 }
318
319 /* Return a new Session Id */
320 uint32_t newVolSessionId()
321 {
322    uint32_t Id;
323
324    P(mutex);
325    VolSessionId++;
326    Id = VolSessionId;
327    V(mutex);
328    return Id;
329 }
330
331 /* Check Configuration file for necessary info */
332 static int check_resources()
333 {
334    bool OK = true;
335    bool tls_needed;
336    AUTOCHANGER *changer;
337    DEVRES *device;
338
339    me = (STORES *)GetNextRes(R_STORAGE, NULL);
340    if (!me) {
341       Jmsg1(NULL, M_ERROR, 0, _("No Storage resource defined in %s. Cannot continue.\n"),
342          configfile);
343       OK = false;
344    }
345
346    if (GetNextRes(R_STORAGE, (RES *)me) != NULL) {
347       Jmsg1(NULL, M_ERROR, 0, _("Only one Storage resource permitted in %s\n"),
348          configfile);
349       OK = false;
350    }
351    if (GetNextRes(R_DIRECTOR, NULL) == NULL) {
352       Jmsg1(NULL, M_ERROR, 0, _("No Director resource defined in %s. Cannot continue.\n"),
353          configfile);
354       OK = false;
355    }
356    if (GetNextRes(R_DEVICE, NULL) == NULL){
357       Jmsg1(NULL, M_ERROR, 0, _("No Device resource defined in %s. Cannot continue.\n"),
358            configfile);
359       OK = false;
360    }
361
362    if (!me->messages) {
363       me->messages = (MSGS *)GetNextRes(R_MSGS, NULL);
364       if (!me->messages) {
365          Jmsg1(NULL, M_ERROR, 0, _("No Messages resource defined in %s. Cannot continue.\n"),
366             configfile);
367          OK = false;
368       }
369    }
370
371    if (!me->working_directory) {
372       Jmsg1(NULL, M_ERROR, 0, _("No Working Directory defined in %s. Cannot continue.\n"),
373          configfile);
374       OK = false;
375    }
376
377    DIRRES *director;
378    STORES *store;
379    foreach_res(store, R_STORAGE) {
380       /* tls_require implies tls_enable */
381       if (store->tls_require) {
382          if (have_tls) {
383             store->tls_enable = true;
384          } else {
385             Jmsg(NULL, M_FATAL, 0, _("TLS required but not configured in Bacula.\n"));
386             OK = false;
387             continue;
388          }
389       }
390
391       tls_needed = store->tls_enable || store->tls_authenticate;
392
393       if (!store->tls_certfile && tls_needed) {
394          Jmsg(NULL, M_FATAL, 0, _("\"TLS Certificate\" file not defined for Storage \"%s\" in %s.\n"),
395               store->hdr.name, configfile);
396          OK = false;
397       }
398
399       if (!store->tls_keyfile && tls_needed) {
400          Jmsg(NULL, M_FATAL, 0, _("\"TLS Key\" file not defined for Storage \"%s\" in %s.\n"),
401               store->hdr.name, configfile);
402          OK = false;
403       }
404
405       if ((!store->tls_ca_certfile && !store->tls_ca_certdir) && tls_needed && store->tls_verify_peer) {
406          Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\""
407               " or \"TLS CA Certificate Dir\" are defined for Storage \"%s\" in %s."
408               " At least one CA certificate store is required"
409               " when using \"TLS Verify Peer\".\n"),
410               store->hdr.name, configfile);
411          OK = false;
412       }
413
414       /* If everything is well, attempt to initialize our per-resource TLS context */
415       if (OK && (tls_needed || store->tls_require)) {
416          /* Initialize TLS context:
417           * Args: CA certfile, CA certdir, Certfile, Keyfile,
418           * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
419          store->tls_ctx = new_tls_context(store->tls_ca_certfile,
420             store->tls_ca_certdir, store->tls_certfile,
421             store->tls_keyfile, NULL, NULL, store->tls_dhfile,
422             store->tls_verify_peer);
423
424          if (!store->tls_ctx) {
425             Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for Storage \"%s\" in %s.\n"),
426                  store->hdr.name, configfile);
427             OK = false;
428          }
429       }
430    }
431
432    foreach_res(director, R_DIRECTOR) {
433       /* tls_require implies tls_enable */
434       if (director->tls_require) {
435          director->tls_enable = true;
436       }
437
438       tls_needed = director->tls_enable || director->tls_authenticate;
439
440       if (!director->tls_certfile && tls_needed) {
441          Jmsg(NULL, M_FATAL, 0, _("\"TLS Certificate\" file not defined for Director \"%s\" in %s.\n"),
442               director->hdr.name, configfile);
443          OK = false;
444       }
445
446       if (!director->tls_keyfile && tls_needed) {
447          Jmsg(NULL, M_FATAL, 0, _("\"TLS Key\" file not defined for Director \"%s\" in %s.\n"),
448               director->hdr.name, configfile);
449          OK = false;
450       }
451
452       if ((!director->tls_ca_certfile && !director->tls_ca_certdir) && tls_needed && director->tls_verify_peer) {
453          Jmsg(NULL, M_FATAL, 0, _("Neither \"TLS CA Certificate\""
454               " or \"TLS CA Certificate Dir\" are defined for Director \"%s\" in %s."
455               " At least one CA certificate store is required"
456               " when using \"TLS Verify Peer\".\n"),
457               director->hdr.name, configfile);
458          OK = false;
459       }
460
461       /* If everything is well, attempt to initialize our per-resource TLS context */
462       if (OK && (tls_needed || director->tls_require)) {
463          /* Initialize TLS context:
464           * Args: CA certfile, CA certdir, Certfile, Keyfile,
465           * Keyfile PEM Callback, Keyfile CB Userdata, DHfile, Verify Peer */
466          director->tls_ctx = new_tls_context(director->tls_ca_certfile,
467             director->tls_ca_certdir, director->tls_certfile,
468             director->tls_keyfile, NULL, NULL, director->tls_dhfile,
469             director->tls_verify_peer);
470
471          if (!director->tls_ctx) {
472             Jmsg(NULL, M_FATAL, 0, _("Failed to initialize TLS context for Director \"%s\" in %s.\n"),
473                  director->hdr.name, configfile);
474             OK = false;
475          }
476       }
477    }
478
479    foreach_res(changer, R_AUTOCHANGER) {
480       foreach_alist(device, changer->device) {
481          device->cap_bits |= CAP_AUTOCHANGER;
482       }
483    }
484
485    if (OK) {
486       OK = init_autochangers();
487    }
488
489    if (OK) {
490       close_msg(NULL);                   /* close temp message handler */
491       init_msg(NULL, me->messages);      /* open daemon message handler */
492       set_working_directory(me->working_directory);
493    }
494
495    return OK;
496 }
497
498 /*
499  * Remove old .spool files written by me from the working directory.
500  */
501 static void cleanup_old_files()
502 {
503    DIR* dp;
504    struct dirent *entry, *result;
505    int rc, name_max;
506    int my_name_len = strlen(my_name);
507    int len = strlen(me->working_directory);
508    POOLMEM *cleanup = get_pool_memory(PM_MESSAGE);
509    POOLMEM *basename = get_pool_memory(PM_MESSAGE);
510    regex_t preg1;
511    char prbuf[500];
512    const int nmatch = 30;
513    regmatch_t pmatch[nmatch];
514    berrno be;
515
516    /* Look for .spool files but don't allow spaces */
517    const char *pat1 = "^[^ ]+\\.spool$";
518
519    /* Setup working directory prefix */
520    pm_strcpy(basename, me->working_directory);
521    if (len > 0 && !IsPathSeparator(me->working_directory[len-1])) {
522       pm_strcat(basename, "/");
523    }
524
525    /* Compile regex expressions */
526    rc = regcomp(&preg1, pat1, REG_EXTENDED);
527    if (rc != 0) {
528       regerror(rc, &preg1, prbuf, sizeof(prbuf));
529       Pmsg2(000,  _("Could not compile regex pattern \"%s\" ERR=%s\n"),
530            pat1, prbuf);
531       goto get_out2;
532    }
533
534    name_max = pathconf(".", _PC_NAME_MAX);
535    if (name_max < 1024) {
536       name_max = 1024;
537    }
538
539    if (!(dp = opendir(me->working_directory))) {
540       berrno be;
541       Pmsg2(000, "Failed to open working dir %s for cleanup: ERR=%s\n",
542             me->working_directory, be.bstrerror());
543       goto get_out1;
544    }
545
546    entry = (struct dirent *)malloc(sizeof(struct dirent) + name_max + 1000);
547    while (1) {
548       if ((readdir_r(dp, entry, &result) != 0) || (result == NULL)) {
549          break;
550       }
551       /* Exclude any name with ., .., not my_name or containing a space */
552       if (strcmp(result->d_name, ".") == 0 || strcmp(result->d_name, "..") == 0 ||
553           strncmp(result->d_name, my_name, my_name_len) != 0) {
554          Dmsg1(500, "Skipped: %s\n", result->d_name);
555          continue;
556       }
557
558       /* Unlink files that match regex */
559       if (regexec(&preg1, result->d_name, nmatch, pmatch,  0) == 0) {
560          pm_strcpy(cleanup, basename);
561          pm_strcat(cleanup, result->d_name);
562          Dmsg1(500, "Unlink: %s\n", cleanup);
563          unlink(cleanup);
564       }
565    }
566    free(entry);
567    closedir(dp);
568
569 get_out1:
570    regfree(&preg1);
571 get_out2:
572    free_pool_memory(cleanup);
573    free_pool_memory(basename);
574 }
575
576 /*
577  * Here we attempt to init and open each device. This is done
578  *  once at startup in a separate thread.
579  */
580 extern "C"
581 void *device_initialization(void *arg)
582 {
583    DEVRES *device;
584    DCR *dcr;
585    JCR *jcr;
586    DEVICE *dev;
587    struct stat statp;
588
589    LockRes();
590
591    pthread_detach(pthread_self());
592    jcr = new_jcr(sizeof(JCR), stored_free_jcr);
593    new_plugins(jcr);  /* instantiate plugins */
594    jcr->setJobType(JT_SYSTEM);
595    /* Initialize FD start condition variable */
596    int errstat = pthread_cond_init(&jcr->job_start_wait, NULL);
597    if (errstat != 0) {
598       berrno be;
599       Jmsg1(jcr, M_ABORT, 0, _("Unable to init job cond variable: ERR=%s\n"), be.bstrerror(errstat));
600    }
601
602    foreach_res(device, R_DEVICE) {
603       Dmsg1(90, "calling init_dev %s\n", device->hdr.name);
604       dev = init_dev(NULL, device);
605       Dmsg1(10, "SD init done %s\n", device->hdr.name);
606       if (!dev) {
607          Jmsg1(NULL, M_ERROR, 0, _("Could not initialize SD device \"%s\"\n"), device->hdr.name);
608          continue;
609       }
610
611       jcr->dcr = dcr = new_dcr(jcr, NULL, dev);
612       generate_plugin_event(jcr, bsdEventDeviceInit, dcr);
613
614       if (device->control_name && stat(device->control_name, &statp) < 0) {
615          berrno be;
616          Jmsg2(jcr, M_ERROR_TERM, 0, _("Unable to stat ControlDevice %s: ERR=%s\n"),
617             device->control_name, be.bstrerror());
618       }
619
620       if ((device->lock_command && device->control_name) &&
621           !me->plugin_directory) {
622          Jmsg0(jcr, M_ERROR_TERM, 0, _("No plugin directory configured for SAN shared storage\n"));
623       }
624
625
626       /*
627        * Note: be careful setting the slot here. If the drive
628        *  is shared storage, the contents can change before
629        *  the drive is used.
630        */
631       if (device->cap_bits & CAP_ALWAYSOPEN) {
632          if (dev->is_autochanger()) {
633             /* If autochanger set slot in dev sturcture */
634             get_autochanger_loaded_slot(dcr);
635          }
636          Dmsg1(20, "calling first_open_device %s\n", dev->print_name());
637          if (generate_plugin_event(jcr, bsdEventDeviceOpen, dcr) != bRC_OK) {
638             Jmsg(jcr, M_FATAL, 0, _("generate_plugin_event(bsdEventDeviceOpen) Failed\n"));
639             continue;
640          }
641
642          if (!first_open_device(dcr)) {
643             Jmsg1(NULL, M_ERROR, 0, _("Could not open device %s\n"), dev->print_name());
644             Dmsg1(20, "Could not open device %s\n", dev->print_name());
645             generate_plugin_event(jcr, bsdEventDeviceClose, dcr);
646             free_dcr(dcr);
647             jcr->dcr = NULL;
648             continue;
649          }
650       } else {
651          /* If not always open, we don't know what is in the drive */
652          dev->clear_slot();
653       }
654       if (device->cap_bits & CAP_AUTOMOUNT && dev->is_open()) {
655          switch (dev->read_dev_volume_label(dcr)) {
656          case VOL_OK:
657             memcpy(&dev->VolCatInfo, &dcr->VolCatInfo, sizeof(dev->VolCatInfo));
658             volume_unused(dcr);             /* mark volume "released" */
659             break;
660          default:
661             Jmsg1(NULL, M_WARNING, 0, _("Could not mount device %s\n"), dev->print_name());
662             break;
663          }
664       }
665
666       free_dcr(dcr);
667       jcr->dcr = NULL;
668    }
669
670
671 #ifdef xxx
672    if (jcr->dcr) {
673       Pmsg1(000, "free_dcr=%p\n", jcr->dcr);
674       free_dcr(jcr->dcr);
675       jcr->dcr = NULL;
676    }
677 #endif
678    free_plugins(jcr);
679    free_jcr(jcr);
680    init_done = true;
681    UnlockRes();
682    return NULL;
683 }
684
685
686 /* Clean up and then exit */
687 void terminate_stored(int sig)
688 {
689    static bool in_here = false;
690    DEVRES *device;
691    JCR *jcr;
692
693    if (in_here) {                     /* prevent loops */
694       bmicrosleep(2, 0);              /* yield */
695       exit(1);
696    }
697    in_here = true;
698    debug_level = 0;                   /* turn off any debug */
699    stop_watchdog();
700
701    if (sig == SIGTERM || sig == SIGINT) { /* normal shutdown request? or ^C */
702       /*
703        * This is a normal shutdown request. We wiffle through
704        *   all open jobs canceling them and trying to wake
705        *   them up so that they will report back the correct
706        *   volume status.
707        */
708       foreach_jcr(jcr) {
709          BSOCK *fd;
710          if (jcr->JobId == 0) {
711             free_jcr(jcr);
712             continue;                 /* ignore console */
713          }
714          if (jcr->dcr) {
715             /* Make sure no device remains locked */
716             generate_plugin_event(jcr, bsdEventDeviceClose, jcr->dcr);
717          }
718          jcr->setJobStatus(JS_Canceled);
719          fd = jcr->file_bsock;
720          if (fd) {
721             fd->set_timed_out();
722             jcr->my_thread_send_signal(TIMEOUT_SIGNAL);
723             Dmsg1(100, "term_stored killing JobId=%d\n", jcr->JobId);
724             /* ***FIXME*** wiffle through all dcrs */
725             if (jcr->dcr && jcr->dcr->dev && jcr->dcr->dev->blocked()) {
726                pthread_cond_broadcast(&jcr->dcr->dev->wait_next_vol);
727                Dmsg1(100, "JobId=%u broadcast wait_device_release\n", (uint32_t)jcr->JobId);
728                pthread_cond_broadcast(&wait_device_release);
729             }
730             if (jcr->read_dcr && jcr->read_dcr->dev && jcr->read_dcr->dev->blocked()) {
731                pthread_cond_broadcast(&jcr->read_dcr->dev->wait_next_vol);
732                pthread_cond_broadcast(&wait_device_release);
733             }
734             bmicrosleep(0, 50000);
735          }
736          free_jcr(jcr);
737       }
738       bmicrosleep(0, 500000);         /* give them 1/2 sec to clean up */
739    }
740
741    if (!test_config) {
742       write_state_file(me->working_directory,
743                        "bacula-sd", get_first_port_host_order(me->sdaddrs));
744       delete_pid_file(me->pid_directory,
745                       "bacula-sd", get_first_port_host_order(me->sdaddrs));
746    }
747
748    Dmsg1(200, "In terminate_stored() sig=%d\n", sig);
749
750    unload_plugins();
751    free_volume_lists();
752
753    free_daemon_message_queue();
754
755    foreach_res(device, R_DEVICE) {
756       Dmsg2(10, "Term device %s %s\n", device->hdr.name, device->device_name);
757       if (device->dev) {
758          device->dev->clear_volhdr();
759          device->dev->term(NULL);
760          device->dev = NULL;
761       } else {
762          Dmsg2(10, "No dev structure %s %s\n", device->hdr.name, device->device_name);
763       }
764    }
765    if (server_tid_valid) {
766       bnet_stop_thread_server(server_tid);
767    }
768
769    if (configfile) {
770       free(configfile);
771       configfile = NULL;
772    }
773    if (config) {
774       delete config;
775       config = NULL;
776    }
777
778    if (chk_dbglvl(10)) {
779       print_memory_pool_stats();
780    }
781    term_msg();
782    cleanup_crypto();
783    term_reservations_lock();
784    free(res_head);
785    res_head = NULL;
786    close_memory_pool();
787    lmgr_cleanup_main();
788
789    sm_dump(false);                    /* dump orphaned buffers */
790    exit(sig);
791 }