]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/message.c
- Fix exepath when Bacula executed without path.
[bacula/bacula] / bacula / src / lib / message.c
1 /*
2  * Bacula message handling routines
3  *
4  *   Kern Sibbald, April 2000 
5  *
6  *   Version $Id$
7  *
8  */
9
10 /*
11    Copyright (C) 2000-2004 Kern Sibbald and John Walker
12
13    This program is free software; you can redistribute it and/or
14    modify it under the terms of the GNU General Public License as
15    published by the Free Software Foundation; either version 2 of
16    the License, or (at your option) any later version.
17
18    This program is distributed in the hope that it will be useful,
19    but WITHOUT ANY WARRANTY; without even the implied warranty of
20    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21    General Public License for more details.
22
23    You should have received a copy of the GNU General Public
24    License along with this program; if not, write to the Free
25    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
26    MA 02111-1307, USA.
27
28  */
29
30
31 #include "bacula.h"
32 #include "jcr.h"
33
34 #if !defined(HAVE_CONSOLE)
35 #if defined(HAVE_CYGWIN) || defined(HAVE_WIN32)
36 #include <windows.h>
37 #endif
38 #endif
39
40 #define FULL_LOCATION 1               /* set for file:line in Debug messages */
41
42 /* 
43  *  This is where we define "Globals" because all the
44  *    daemons include this file.
45  */
46 const char *working_directory = NULL;       /* working directory path stored here */
47 int verbose = 0;                      /* increase User messages */
48 int debug_level = 0;                  /* debug level */
49 time_t daemon_start_time = 0;         /* Daemon start time */
50 const char *version = VERSION " (" BDATE ")";
51 char my_name[30];                     /* daemon name is stored here */
52 char *exepath = (char *)NULL;
53 char *exename = (char *)NULL;
54 int console_msg_pending = 0;
55 char con_fname[500];                  /* Console filename */
56 FILE *con_fd = NULL;                  /* Console file descriptor */
57 brwlock_t con_lock;                   /* Console lock structure */
58
59 #ifdef HAVE_POSTGRESQL
60 char catalog_db[] = "PostgreSQL";
61 #else
62 #ifdef HAVE_MYSQL
63 char catalog_db[] = "MySQL";
64 #else 
65 #ifdef HAVE_SQLITE
66 char catalog_db[] = "SQLite";
67 #else
68 char catalog_db[] = "Internal";
69 #endif
70 #endif
71 #endif
72
73 const char *host_os = HOST_OS;
74 const char *distname = DISTNAME;
75 const char *distver = DISTVER;
76 static FILE *trace_fd = NULL;
77 #ifdef HAVE_WIN32
78 static bool trace = true;
79 #else
80 static bool trace = false;
81 #endif
82
83 /* Forward referenced functions */
84
85 /* Imported functions */
86
87
88 /* Static storage */
89
90 /* Used to allow only one thread close the daemon messages at a time */
91 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
92 static MSGS *daemon_msgs;              /* global messages */
93
94 /* Define if e_msg must exit when M_ERROR_TERM is received */
95 static int exit_on_error = 1;
96
97 /* 
98  * Set daemon name. Also, find canonical execution
99  *  path.  Note, exepath has spare room for tacking on
100  *  the exename so that we can reconstruct the full name.
101  *
102  * Note, this routine can get called multiple times
103  *  The second time is to put the name as found in the
104  *  Resource record. On the second call, generally,
105  *  argv is NULL to avoid doing the path code twice.
106  */
107 #define BTRACE_EXTRA 20
108 void my_name_is(int argc, char *argv[], const char *name)
109 {
110    char *l, *p, *q;
111    char cpath[1024];
112    int len;
113
114    bstrncpy(my_name, name, sizeof(my_name));
115    if (argc>0 && argv && argv[0]) {
116       /* strip trailing filename and save exepath */
117       for (l=p=argv[0]; *p; p++) {
118          if (*p == '/') {
119             l = p;                       /* set pos of last slash */
120          }
121       }
122       if (*l == '/') {
123          l++;
124       } else {
125          l = argv[0];
126 #if defined(HAVE_CYGWIN) || defined(HAVE_WIN32)
127          /* On Windows allow c: junk */
128          if (l[1] == ':') {
129             l += 2;
130          }
131 #endif
132       }
133       len = strlen(l) + 1;
134       if (exename) {
135          free(exename);
136       }
137       exename = (char *)malloc(len);
138       strcpy(exename, l);
139
140       if (exepath) {
141          free(exepath);
142       }
143       exepath = (char *)malloc(strlen(argv[0]) + 1 + len);
144       for (p=argv[0],q=exepath; p < l; ) {
145          *q++ = *p++;
146       }
147       *q = 0;
148       if (strchr(exepath, '.') || exepath[0] != '/') {
149          if (getcwd(cpath, sizeof(cpath))) {
150             free(exepath);
151             exepath = (char *)malloc(strlen(cpath) + 1 + len);
152             strcpy(exepath, cpath);
153          }
154       }
155       Dmsg2(500, "exepath=%s\nexename=%s\n", exepath, exename);
156    }
157 }
158
159 /* 
160  * Initialize message handler for a daemon or a Job
161  *   We make a copy of the MSGS resource passed, so it belows
162  *   to the job or daemon and thus can be modified.
163  * 
164  *   NULL for jcr -> initialize global messages for daemon
165  *   non-NULL     -> initialize jcr using Message resource
166  */
167 void
168 init_msg(JCR *jcr, MSGS *msg)
169 {
170    DEST *d, *dnew, *temp_chain = NULL;
171    int i;
172
173    if (jcr == NULL && msg == NULL) {
174       init_last_jobs_list();
175    }
176
177 #ifndef HAVE_WIN32
178    /*
179     * Make sure we have fd's 0, 1, 2 open
180     *  If we don't do this one of our sockets may open
181     *  there and if we then use stdout, it could
182     *  send total garbage to our socket.
183     *
184     */
185    int fd;
186    fd = open("/dev/null", O_RDONLY, 0644);
187    if (fd > 2) {
188       close(fd);
189    } else {
190       for(i=1; fd + i <= 2; i++) {
191          dup2(fd, fd+i);
192       }
193    }
194
195 #endif
196    /*
197     * If msg is NULL, initialize global chain for STDOUT and syslog
198     */
199    if (msg == NULL) {
200       daemon_msgs = (MSGS *)malloc(sizeof(MSGS));
201       memset(daemon_msgs, 0, sizeof(MSGS));
202       for (i=1; i<=M_MAX; i++) {
203 #ifndef WIN32
204          add_msg_dest(daemon_msgs, MD_STDOUT, i, NULL, NULL);
205 #endif
206          add_msg_dest(daemon_msgs, MD_SYSLOG, i, NULL, NULL);
207       }
208       Dmsg1(050, "Create daemon global message resource 0x%x\n", daemon_msgs);
209       return;
210    }
211
212    /*
213     * Walk down the message resource chain duplicating it
214     * for the current Job.
215     */
216    for (d=msg->dest_chain; d; d=d->next) {
217       dnew = (DEST *)malloc(sizeof(DEST));
218       memcpy(dnew, d, sizeof(DEST));
219       dnew->next = temp_chain;
220       dnew->fd = NULL;
221       dnew->mail_filename = NULL;
222       if (d->mail_cmd) {
223          dnew->mail_cmd = bstrdup(d->mail_cmd);
224       }
225       if (d->where) {
226          dnew->where = bstrdup(d->where);
227       }
228       temp_chain = dnew;
229    }
230
231    if (jcr) {
232       jcr->jcr_msgs = (MSGS *)malloc(sizeof(MSGS));
233       memset(jcr->jcr_msgs, 0, sizeof(MSGS));
234       jcr->jcr_msgs->dest_chain = temp_chain;
235       memcpy(jcr->jcr_msgs->send_msg, msg->send_msg, sizeof(msg->send_msg));
236    } else {
237       /* If we have default values, release them now */
238       if (daemon_msgs) {
239          free_msgs_res(daemon_msgs);
240       }
241       daemon_msgs = (MSGS *)malloc(sizeof(MSGS));
242       memset(daemon_msgs, 0, sizeof(MSGS));
243       daemon_msgs->dest_chain = temp_chain;
244       memcpy(daemon_msgs->send_msg, msg->send_msg, sizeof(msg->send_msg));
245    }
246    Dmsg2(050, "Copy message resource 0x%x to 0x%x\n", msg, temp_chain);
247
248 }
249
250 /* Initialize so that the console (User Agent) can
251  * receive messages -- stored in a file.
252  */
253 void init_console_msg(const char *wd)
254 {
255    int fd;
256
257    bsnprintf(con_fname, sizeof(con_fname), "%s/%s.conmsg", wd, my_name);
258    fd = open(con_fname, O_CREAT|O_RDWR|O_BINARY, 0600);
259    if (fd == -1) {
260       Emsg2(M_ERROR_TERM, 0, _("Could not open console message file %s: ERR=%s\n"),
261           con_fname, strerror(errno));
262    }
263    if (lseek(fd, 0, SEEK_END) > 0) {
264       console_msg_pending = 1;
265    }
266    close(fd);
267    con_fd = fopen(con_fname, "a+");
268    if (!con_fd) {
269       Emsg2(M_ERROR, 0, _("Could not open console message file %s: ERR=%s\n"),
270           con_fname, strerror(errno));
271    }
272    if (rwl_init(&con_lock) != 0) {
273       Emsg1(M_ERROR_TERM, 0, _("Could not get con mutex: ERR=%s\n"), 
274          strerror(errno));
275    }
276 }
277
278 /* 
279  * Called only during parsing of the config file.
280  *
281  * Add a message destination. I.e. associate a message type with
282  *  a destination (code).
283  * Note, where in the case of dest_code FILE is a filename,
284  *  but in the case of MAIL is a space separated list of
285  *  email addresses, ...
286  */
287 void add_msg_dest(MSGS *msg, int dest_code, int msg_type, char *where, char *mail_cmd)
288 {
289    DEST *d; 
290    /*
291     * First search the existing chain and see if we
292     * can simply add this msg_type to an existing entry.
293     */
294    for (d=msg->dest_chain; d; d=d->next) {
295       if (dest_code == d->dest_code && ((where == NULL && d->where == NULL) ||
296                      (strcmp(where, d->where) == 0))) {  
297          Dmsg4(200, "Add to existing d=%x msgtype=%d destcode=%d where=%s\n", 
298              d, msg_type, dest_code, NPRT(where));
299          set_bit(msg_type, d->msg_types);
300          set_bit(msg_type, msg->send_msg);  /* set msg_type bit in our local */
301          return;
302       }
303    }
304    /* Not found, create a new entry */
305    d = (DEST *)malloc(sizeof(DEST));
306    memset(d, 0, sizeof(DEST));
307    d->next = msg->dest_chain;
308    d->dest_code = dest_code;
309    set_bit(msg_type, d->msg_types);      /* set type bit in structure */
310    set_bit(msg_type, msg->send_msg);     /* set type bit in our local */
311    if (where) {
312       d->where = bstrdup(where);
313    }
314    if (mail_cmd) {
315       d->mail_cmd = bstrdup(mail_cmd);
316    }
317    Dmsg5(200, "add new d=%x msgtype=%d destcode=%d where=%s mailcmd=%s\n", 
318           d, msg_type, dest_code, NPRT(where), NPRT(d->mail_cmd));
319    msg->dest_chain = d;
320 }
321
322 /* 
323  * Called only during parsing of the config file.
324  *
325  * Remove a message destination   
326  */
327 void rem_msg_dest(MSGS *msg, int dest_code, int msg_type, char *where)
328 {
329    DEST *d;
330
331    for (d=msg->dest_chain; d; d=d->next) {
332       Dmsg2(200, "Remove_msg_dest d=%x where=%s\n", d, NPRT(d->where));
333       if (bit_is_set(msg_type, d->msg_types) && (dest_code == d->dest_code) &&
334           ((where == NULL && d->where == NULL) ||
335                      (strcmp(where, d->where) == 0))) {  
336          Dmsg3(200, "Found for remove d=%x msgtype=%d destcode=%d\n", 
337                d, msg_type, dest_code);
338          clear_bit(msg_type, d->msg_types);
339          Dmsg0(200, "Return rem_msg_dest\n");
340          return;
341       }
342    }
343 }
344
345
346 /*
347  * Create a unique filename for the mail command
348  */
349 static void make_unique_mail_filename(JCR *jcr, POOLMEM *&name, DEST *d)
350 {
351    if (jcr) {
352       Mmsg(name, "%s/%s.mail.%s.%d", working_directory, my_name,
353                  jcr->Job, (int)(long)d);
354    } else {
355       Mmsg(name, "%s/%s.mail.%s.%d", working_directory, my_name,
356                  my_name, (int)(long)d);
357    }
358    Dmsg1(200, "mailname=%s\n", name);
359 }
360
361 /*
362  * Open a mail pipe
363  */
364 static BPIPE *open_mail_pipe(JCR *jcr, POOLMEM *&cmd, DEST *d)
365 {
366    BPIPE *bpipe;
367        
368    if (d->mail_cmd) {
369       cmd = edit_job_codes(jcr, cmd, d->mail_cmd, d->where);
370    } else {
371       Mmsg(cmd, "/usr/lib/sendmail -F Bacula %s", d->where);
372    }
373    fflush(stdout);
374
375    if (!(bpipe = open_bpipe(cmd, 120, "rw"))) {
376       berrno be;
377       Jmsg(jcr, M_ERROR, 0, "open mail pipe %s failed: ERR=%s\n", 
378          cmd, be.strerror());
379    }
380
381    /* If we had to use sendmail, add subject */
382    if (!d->mail_cmd) {
383        fprintf(bpipe->wfd, "Subject: Bacula Message\r\n\r\n");
384    }
385    
386    return bpipe;
387 }
388
389 /* 
390  * Close the messages for this Messages resource, which means to close
391  *  any open files, and dispatch any pending email messages.
392  */
393 void close_msg(JCR *jcr)
394 {
395    MSGS *msgs;
396    DEST *d;
397    BPIPE *bpipe;
398    POOLMEM *cmd, *line;
399    int len, stat;
400    
401    Dmsg1(350, "Close_msg jcr=0x%x\n", jcr);
402
403    if (jcr == NULL) {                /* NULL -> global chain */
404       msgs = daemon_msgs;
405       P(mutex);                       /* only one thread walking the chain */
406    } else {
407       msgs = jcr->jcr_msgs;
408       jcr->jcr_msgs = NULL;
409    }
410    if (msgs == NULL) {
411       return;
412    }
413    Dmsg1(350, "===Begin close msg resource at 0x%x\n", msgs);
414    cmd = get_pool_memory(PM_MESSAGE);
415    for (d=msgs->dest_chain; d; ) {
416       if (d->fd) {
417          switch (d->dest_code) {
418          case MD_FILE:
419          case MD_APPEND:
420             if (d->fd) {
421                fclose(d->fd);            /* close open file descriptor */
422             }
423             break;
424          case MD_MAIL:
425          case MD_MAIL_ON_ERROR:
426             Dmsg0(350, "Got MD_MAIL or MD_MAIL_ON_ERROR\n");
427             if (!d->fd) {
428                break;
429             }
430             if (d->dest_code == MD_MAIL_ON_ERROR && jcr &&
431                 jcr->JobStatus == JS_Terminated) {
432                goto rem_temp_file;
433             }
434             
435             if (!(bpipe=open_mail_pipe(jcr, cmd, d))) {
436                Pmsg0(000, "open mail pipe failed.\n");
437                goto rem_temp_file;
438             }
439             Dmsg0(350, "Opened mail pipe\n");
440             len = d->max_len+10;
441             line = get_memory(len);
442             rewind(d->fd);
443             while (fgets(line, len, d->fd)) {
444                fputs(line, bpipe->wfd);
445             }
446             if (!close_wpipe(bpipe)) {       /* close write pipe sending mail */
447                Pmsg1(000, "close error: ERR=%s\n", strerror(errno));
448             }
449
450             /*
451              * Since we are closing all messages, before "recursing"
452              * make sure we are not closing the daemon messages, otherwise
453              * kaboom.
454              */
455             if (msgs != daemon_msgs) {
456                /* read what mail prog returned -- should be nothing */
457                while (fgets(line, len, bpipe->rfd)) {
458                   Jmsg1(jcr, M_INFO, 0, _("Mail prog: %s"), line);
459                }
460             }
461
462             stat = close_bpipe(bpipe);
463             if (stat != 0 && msgs != daemon_msgs) {
464                berrno be;
465                be.set_errno(stat);
466                Dmsg1(350, "Calling emsg. CMD=%s\n", cmd);
467                Jmsg2(jcr, M_ERROR, 0, _("Mail program terminated in error.\n"
468                                         "CMD=%s\n"
469                                         "ERR=%s\n"), cmd, be.strerror());
470             }
471             free_memory(line);
472 rem_temp_file:
473             /* Remove temp file */
474             fclose(d->fd);
475             unlink(d->mail_filename);
476             free_pool_memory(d->mail_filename);
477             d->mail_filename = NULL;
478             Dmsg0(350, "end mail or mail on error\n");
479             break;
480          default:
481             break;
482          }
483          d->fd = NULL;
484       }
485       d = d->next;                    /* point to next buffer */
486    }
487    free_pool_memory(cmd);
488    Dmsg0(350, "Done walking message chain.\n");
489    if (jcr) {
490       free_msgs_res(msgs);
491       msgs = NULL;
492    } else {
493       V(mutex);
494    }
495    Dmsg0(350, "===End close msg resource\n");
496 }
497
498 /*
499  * Free memory associated with Messages resource  
500  */
501 void free_msgs_res(MSGS *msgs)
502 {
503    DEST *d, *old;
504
505    /* Walk down the message chain releasing allocated buffers */
506    for (d=msgs->dest_chain; d; ) {
507       if (d->where) {
508          free(d->where);
509       }
510       if (d->mail_cmd) {
511          free(d->mail_cmd);
512       }
513       old = d;                        /* save pointer to release */
514       d = d->next;                    /* point to next buffer */
515       free(old);                      /* free the destination item */
516    }
517    msgs->dest_chain = NULL;
518    free(msgs);                        /* free the head */
519 }
520
521
522 /* 
523  * Terminate the message handler for good. 
524  * Release the global destination chain.
525  * 
526  * Also, clean up a few other items (cons, exepath). Note,
527  *   these really should be done elsewhere.
528  */
529 void term_msg()
530 {
531    Dmsg0(300, "Enter term_msg\n");
532    close_msg(NULL);                   /* close global chain */
533    free_msgs_res(daemon_msgs);        /* free the resources */
534    daemon_msgs = NULL;
535    if (con_fd) {
536       fflush(con_fd);
537       fclose(con_fd);
538       con_fd = NULL;
539    }
540    if (exepath) {
541       free(exepath);
542       exepath = NULL;
543    }
544    if (exename) {
545       free(exename);
546       exename = NULL;
547    }
548    if (trace_fd) {
549       fclose(trace_fd);
550       trace_fd = NULL;
551    }
552    term_last_jobs_list();
553 }
554
555
556
557 /*
558  * Handle sending the message to the appropriate place
559  */
560 void dispatch_message(JCR *jcr, int type, int level, char *msg)
561 {
562     DEST *d;   
563     char dt[MAX_TIME_LENGTH];
564     POOLMEM *mcmd;
565     int len;
566     MSGS *msgs;
567     BPIPE *bpipe;
568
569     Dmsg2(800, "Enter dispatch_msg type=%d msg=%s\n", type, msg);
570
571     if (type == M_ABORT || type == M_ERROR_TERM) {
572 #ifndef HAVE_WIN32
573        fputs(msg, stdout);         /* print this here to INSURE that it is printed */
574        fflush(stdout);
575 #endif
576 #if !defined(HAVE_CONSOLE)
577 #if defined(HAVE_CYGWIN) || defined(HAVE_WIN32)
578        /* If we don't exit on error, error messages are parsed by UA */
579        if (exit_on_error) {
580           MessageBox(NULL, msg, "Bacula", MB_OK);
581        }
582 #endif
583 #endif
584     }
585
586     /* Now figure out where to send the message */
587     msgs = NULL;
588     if (jcr) {
589        msgs = jcr->jcr_msgs;
590     } 
591     if (msgs == NULL) {
592        msgs = daemon_msgs;
593     }
594     for (d=msgs->dest_chain; d; d=d->next) {
595        if (bit_is_set(type, d->msg_types)) {
596           switch (d->dest_code) {
597              case MD_CONSOLE:
598                 Dmsg1(800, "CONSOLE for following msg: %s", msg);
599                 if (!con_fd) {
600                    con_fd = fopen(con_fname, "a+");
601                    Dmsg0(800, "Console file not open.\n");
602                 }
603                 if (con_fd) {
604                    Pw(con_lock);      /* get write lock on console message file */
605                    errno = 0;
606                    bstrftime(dt, sizeof(dt), time(NULL));
607                    len = strlen(dt);
608                    dt[len++] = ' ';
609                    fwrite(dt, len, 1, con_fd);
610                    len = strlen(msg);
611                    if (len > 0) {
612                       fwrite(msg, len, 1, con_fd);
613                       if (msg[len-1] != '\n') {
614                          fwrite("\n", 2, 1, con_fd);
615                       }
616                    } else {
617                       fwrite("\n", 2, 1, con_fd);
618                    }
619                    fflush(con_fd);
620                    console_msg_pending = TRUE;
621                    Vw(con_lock);
622                 }
623                 break;
624              case MD_SYSLOG:
625                 Dmsg1(800, "SYSLOG for collowing msg: %s\n", msg);
626                 /*
627                  * We really should do an openlog() here.  
628                  */
629                 syslog(LOG_DAEMON|LOG_ERR, "%s", msg);
630                 break;
631              case MD_OPERATOR:
632                 Dmsg1(800, "OPERATOR for collowing msg: %s\n", msg);
633                 mcmd = get_pool_memory(PM_MESSAGE);
634                 if ((bpipe=open_mail_pipe(jcr, mcmd, d))) {
635                    int stat;
636                    fputs(msg, bpipe->wfd);
637                    /* Messages to the operator go one at a time */
638                    stat = close_bpipe(bpipe);
639                    if (stat != 0) {
640                       berrno be;
641                       be.set_errno(stat);
642                       Qmsg2(jcr, M_ERROR, 0, _("Operator mail program terminated in error.\n"
643                             "CMD=%s\n"
644                             "ERR=%s\n"), mcmd, be.strerror());
645                    }
646                 }
647                 free_pool_memory(mcmd);
648                 break;
649              case MD_MAIL:
650              case MD_MAIL_ON_ERROR:
651                 Dmsg1(800, "MAIL for following msg: %s", msg);
652                 if (!d->fd) {
653                    POOLMEM *name = get_pool_memory(PM_MESSAGE);
654                    make_unique_mail_filename(jcr, name, d);
655                    d->fd = fopen(name, "w+");
656                    if (!d->fd) {
657                       d->fd = stdout;
658                       Qmsg2(jcr, M_ERROR, 0, "fopen %s failed: ERR=%s\n", name, strerror(errno));
659                       d->fd = NULL;
660                       free_pool_memory(name);
661                       break;
662                    }
663                    d->mail_filename = name;
664                 }
665                 len = strlen(msg);
666                 if (len > d->max_len) {
667                    d->max_len = len;      /* keep max line length */
668                 }
669                 fputs(msg, d->fd);
670                 break;
671              case MD_FILE:
672                 Dmsg1(800, "FILE for following msg: %s", msg);
673                 if (!d->fd) {
674                    d->fd = fopen(d->where, "w+");
675                    if (!d->fd) {
676                       d->fd = stdout;
677                       Qmsg2(jcr, M_ERROR, 0, "fopen %s failed: ERR=%s\n", d->where, strerror(errno));
678                       d->fd = NULL;
679                       break;
680                    }
681                 }
682                 fputs(msg, d->fd);
683                 break;
684              case MD_APPEND:
685                 Dmsg1(800, "APPEND for following msg: %s", msg);
686                 if (!d->fd) {
687                    d->fd = fopen(d->where, "a");
688                    if (!d->fd) {
689                       d->fd = stdout;
690                       Qmsg2(jcr, M_ERROR, 0, "fopen %s failed: ERR=%s\n", d->where, strerror(errno));
691                       d->fd = NULL;
692                       break;
693                    }
694                 }
695                 fputs(msg, d->fd);
696                 break;
697              case MD_DIRECTOR:
698                 Dmsg1(800, "DIRECTOR for following msg: %s", msg);
699                 if (jcr && jcr->dir_bsock && !jcr->dir_bsock->errors) {
700                    bnet_fsend(jcr->dir_bsock, "Jmsg Job=%s type=%d level=%d %s", 
701                       jcr->Job, type, level, msg);
702                 }
703                 break;
704              case MD_STDOUT:
705                 Dmsg1(800, "STDOUT for following msg: %s", msg);
706                 if (type != M_ABORT && type != M_ERROR_TERM) { /* already printed */
707                    fputs(msg, stdout);
708                 }
709                 break;
710              case MD_STDERR:
711                 Dmsg1(800, "STDERR for following msg: %s", msg);
712                 fputs(msg, stderr);
713                 break;
714              default:
715                 break;
716           }
717        }
718     }
719 }
720
721
722 /*********************************************************************
723  *
724  *  This subroutine prints a debug message if the level number
725  *  is less than or equal the debug_level. File and line numbers
726  *  are included for more detail if desired, but not currently
727  *  printed.
728  *  
729  *  If the level is negative, the details of file and line number
730  *  are not printed.
731  */
732 void 
733 d_msg(const char *file, int line, int level, const char *fmt,...)
734 {
735     char      buf[5000];
736     int       len;
737     va_list   arg_ptr;
738     int       details = TRUE;
739
740     if (level < 0) {
741        details = FALSE;
742        level = -level;
743     }
744
745     if (level <= debug_level) {
746 #ifdef FULL_LOCATION
747        if (details) {
748           /* visual studio passes the whole path to the file as well
749            * which makes for very long lines
750            */
751           const char *f = strrchr(file, '\\');
752           if (f) file = f + 1;
753           len = bsnprintf(buf, sizeof(buf), "%s: %s:%d ", my_name, file, line);
754        } else {
755           len = 0;
756        }
757 #else
758        len = 0;
759 #endif
760        va_start(arg_ptr, fmt);
761        bvsnprintf(buf+len, sizeof(buf)-len, (char *)fmt, arg_ptr);
762        va_end(arg_ptr);
763
764        /* 
765         * Used the "trace on" command in the console to turn on
766         *  output to the trace file.  "trace off" will close the file.
767         */
768        if (trace) {
769           if (!trace_fd) {
770              bsnprintf(buf, sizeof(buf), "%s/bacula.trace", working_directory ? working_directory : ".");
771              trace_fd = fopen(buf, "a+");
772           }
773           if (trace_fd) {
774              fputs(buf, trace_fd);
775              fflush(trace_fd);
776           }
777        } else {   /* not tracing */
778           fputs(buf, stdout);
779        }
780     }
781 }
782
783 /*
784  * Set trace flag on/off. If argument is negative, there is no change 
785  */
786 void set_trace(int trace_flag)
787 {
788    if (trace_flag < 0) {
789       return;
790    } else if (trace_flag > 0) {
791       trace = true;
792    } else {
793       trace = false;
794    }
795    if (!trace && trace_fd) {
796       FILE *ltrace_fd = trace_fd;
797       trace_fd = NULL;
798       bmicrosleep(0, 100000);         /* yield to prevent seg faults */
799       fclose(ltrace_fd);
800    }
801 }
802
803 bool get_trace(void)
804 {
805    return trace;
806 }
807
808 /*********************************************************************
809  *
810  *  This subroutine prints a message regardless of the debug level
811  *  
812  *  If the level is negative, the details of file and line number
813  *  are not printed.
814  */
815 void 
816 p_msg(const char *file, int line, int level, const char *fmt,...)
817 {
818     char      buf[5000];
819     int       len;
820     va_list   arg_ptr;
821
822 #ifdef FULL_LOCATION
823     if (level >= 0) {
824        len = bsnprintf(buf, sizeof(buf), "%s: %s:%d ", my_name, file, line);
825     } else {
826        len = 0;
827     }
828 #else
829     len = 0;
830 #endif
831     va_start(arg_ptr, fmt);
832     bvsnprintf(buf+len, sizeof(buf)-len, (char *)fmt, arg_ptr);
833     va_end(arg_ptr);
834     fputs(buf, stdout);
835 }
836
837
838 /*********************************************************************
839  *
840  *  subroutine writes a debug message to the trace file if the level number
841  *  is less than or equal the debug_level. File and line numbers
842  *  are included for more detail if desired, but not currently
843  *  printed.
844  *  
845  *  If the level is negative, the details of file and line number
846  *  are not printed.
847  */
848 void 
849 t_msg(const char *file, int line, int level, const char *fmt,...)
850 {
851     char      buf[5000];
852     int       len;
853     va_list   arg_ptr;
854     int       details = TRUE;
855
856     if (level < 0) {
857        details = FALSE;
858        level = -level;
859     }
860
861     if (level <= debug_level) {
862        if (!trace_fd) {
863           bsnprintf(buf, sizeof(buf), "%s/bacula.trace", working_directory);
864           trace_fd = fopen(buf, "a+");
865        }
866     
867 #ifdef FULL_LOCATION
868        if (details) {
869           len = bsnprintf(buf, sizeof(buf), "%s: %s:%d ", my_name, file, line);
870        } else {
871           len = 0;
872        }
873 #else
874        len = 0;
875 #endif
876        va_start(arg_ptr, fmt);
877        bvsnprintf(buf+len, sizeof(buf)-len, (char *)fmt, arg_ptr);
878        va_end(arg_ptr);
879        if (trace_fd != NULL) {
880            fputs(buf, trace_fd);
881            fflush(trace_fd);
882        }
883    }
884 }
885
886
887
888 /* *********************************************************
889  *
890  * print an error message
891  *
892  */
893 void 
894 e_msg(const char *file, int line, int type, int level, const char *fmt,...)
895 {
896     char     buf[5000];
897     va_list   arg_ptr;
898     int len;
899
900     /* 
901      * Check if we have a message destination defined.  
902      * We always report M_ABORT and M_ERROR_TERM 
903      */
904     if (!daemon_msgs || ((type != M_ABORT && type != M_ERROR_TERM) && 
905                          !bit_is_set(type, daemon_msgs->send_msg))) {
906        return;                        /* no destination */
907     }
908     switch (type) {
909     case M_ABORT:
910        len = bsnprintf(buf, sizeof(buf), "%s: ABORTING due to ERROR in %s:%d\n", 
911                my_name, file, line);
912        break;
913     case M_ERROR_TERM:
914        len = bsnprintf(buf, sizeof(buf), "%s: ERROR TERMINATION at %s:%d\n", 
915                my_name, file, line);
916        break;
917     case M_FATAL:
918        if (level == -1)            /* skip details */
919           len = bsnprintf(buf, sizeof(buf), "%s: Fatal Error because: ", my_name);
920        else
921           len = bsnprintf(buf, sizeof(buf), "%s: Fatal Error at %s:%d because:\n", my_name, file, line);
922        break;
923     case M_ERROR:
924        if (level == -1)            /* skip details */
925           len = bsnprintf(buf, sizeof(buf), "%s: ERROR: ", my_name);
926        else
927           len = bsnprintf(buf, sizeof(buf), "%s: ERROR in %s:%d ", my_name, file, line);
928        break;
929     case M_WARNING:
930        len = bsnprintf(buf, sizeof(buf), "%s: Warning: ", my_name);
931        break;
932     case M_SECURITY:
933        len = bsnprintf(buf, sizeof(buf), "%s: Security violation: ", my_name);
934        break;
935     default:
936        len = bsnprintf(buf, sizeof(buf), "%s: ", my_name);
937        break;
938     }
939
940     va_start(arg_ptr, fmt);
941     bvsnprintf(buf+len, sizeof(buf)-len, (char *)fmt, arg_ptr);
942     va_end(arg_ptr);
943
944     dispatch_message(NULL, type, level, buf);
945
946     if (type == M_ABORT) {
947        char *p = 0;
948        p[0] = 0;                      /* generate segmentation violation */
949     }
950     if ((type == M_ERROR_TERM) && exit_on_error) {
951        exit(1);
952     }
953 }
954
955 /* *********************************************************
956  *
957  * Generate a Job message
958  *
959  */
960 void 
961 Jmsg(JCR *jcr, int type, int level, const char *fmt,...)
962 {
963     char     rbuf[5000];
964     va_list   arg_ptr;
965     int len;
966     MSGS *msgs;
967     const char *job;
968
969     
970     Dmsg1(800, "Enter Jmsg type=%d\n", type);
971
972     /* Special case for the console, which has a dir_bsock and JobId==0,
973      *  in that case, we send the message directly back to the
974      *  dir_bsock.  
975      */
976     if (jcr && jcr->JobId == 0 && jcr->dir_bsock) {
977        BSOCK *dir = jcr->dir_bsock;
978        va_start(arg_ptr, fmt);
979        dir->msglen = bvsnprintf(dir->msg, sizeof_pool_memory(dir->msg), 
980                                 fmt, arg_ptr);
981        va_end(arg_ptr);
982        bnet_send(jcr->dir_bsock);
983        return;
984     }
985
986     msgs = NULL;
987     job = NULL;
988     if (jcr) {
989        msgs = jcr->jcr_msgs;
990        job = jcr->Job;
991     } 
992     if (!msgs) {
993        msgs = daemon_msgs;            /* if no jcr, we use daemon handler */
994     }
995     if (!job) {
996        job = "";                      /* Set null job name if none */
997     }
998
999     /* 
1000      * Check if we have a message destination defined.  
1001      * We always report M_ABORT and M_ERROR_TERM 
1002      */
1003     if (msgs && (type != M_ABORT && type != M_ERROR_TERM) &&
1004          !bit_is_set(type, msgs->send_msg)) {
1005        return;                        /* no destination */
1006     }
1007     switch (type) {
1008     case M_ABORT:
1009        len = bsnprintf(rbuf, sizeof(rbuf), "%s ABORTING due to ERROR\n", my_name);
1010        break;
1011     case M_ERROR_TERM:
1012        len = bsnprintf(rbuf, sizeof(rbuf), "%s ERROR TERMINATION\n", my_name);
1013        break;
1014     case M_FATAL:
1015        len = bsnprintf(rbuf, sizeof(rbuf), "%s: %s Fatal error: ", my_name, job);
1016        if (jcr) {
1017           set_jcr_job_status(jcr, JS_FatalError);
1018        }
1019        break;
1020     case M_ERROR:
1021        len = bsnprintf(rbuf, sizeof(rbuf), "%s: %s Error: ", my_name, job);
1022        if (jcr) {
1023           jcr->Errors++;
1024        }
1025        break;
1026     case M_WARNING:
1027        len = bsnprintf(rbuf, sizeof(rbuf), "%s: %s Warning: ", my_name, job);
1028        break;
1029     case M_SECURITY:
1030        len = bsnprintf(rbuf, sizeof(rbuf), "%s: %s Security violation: ", my_name, job);
1031        break;
1032     default:
1033        len = bsnprintf(rbuf, sizeof(rbuf), "%s: ", my_name);
1034        break;
1035     }
1036
1037     va_start(arg_ptr, fmt);
1038     bvsnprintf(rbuf+len,  sizeof(rbuf)-len, fmt, arg_ptr);
1039     va_end(arg_ptr);
1040
1041     dispatch_message(jcr, type, level, rbuf);
1042
1043     if (type == M_ABORT){
1044        char *p = 0;
1045        p[0] = 0;                      /* generate segmentation violation */
1046     }
1047     if ((type == M_ERROR_TERM) && exit_on_error) {
1048        exit(1);
1049     }
1050 }
1051
1052 /*
1053  * If we come here, prefix the message with the file:line-number,
1054  *  then pass it on to the normal Jmsg routine.
1055  */
1056 void j_msg(const char *file, int line, JCR *jcr, int type, int level, const char *fmt,...)
1057 {
1058    va_list   arg_ptr;
1059    int i, len, maxlen;
1060    POOLMEM *pool_buf;
1061
1062    pool_buf = get_pool_memory(PM_EMSG);
1063    i = Mmsg(pool_buf, "%s:%d ", file, line);
1064
1065    for (;;) {
1066       maxlen = sizeof_pool_memory(pool_buf) - i - 1; 
1067       va_start(arg_ptr, fmt);
1068       len = bvsnprintf(pool_buf+i, maxlen, fmt, arg_ptr);
1069       va_end(arg_ptr);
1070       if (len < 0 || len >= (maxlen-5)) {
1071          pool_buf = realloc_pool_memory(pool_buf, maxlen + i + maxlen/2);
1072          continue;
1073       }
1074       break;
1075    }
1076
1077    Jmsg(jcr, type, level, "%s", pool_buf);
1078    free_memory(pool_buf);
1079 }
1080
1081
1082 /*
1083  * Edit a message into a Pool memory buffer, with file:lineno
1084  */                                                  
1085 int m_msg(const char *file, int line, POOLMEM **pool_buf, const char *fmt, ...)
1086 {
1087    va_list   arg_ptr;
1088    int i, len, maxlen;
1089
1090    i = sprintf(*pool_buf, "%s:%d ", file, line);
1091
1092    for (;;) {
1093       maxlen = sizeof_pool_memory(*pool_buf) - i - 1; 
1094       va_start(arg_ptr, fmt);
1095       len = bvsnprintf(*pool_buf+i, maxlen, fmt, arg_ptr);
1096       va_end(arg_ptr);
1097       if (len < 0 || len >= (maxlen-5)) {
1098          *pool_buf = realloc_pool_memory(*pool_buf, maxlen + i + maxlen/2);
1099          continue;
1100       }
1101       break;
1102    }
1103    return len;
1104 }
1105
1106 int m_msg(const char *file, int line, POOLMEM *&pool_buf, const char *fmt, ...)
1107 {
1108    va_list   arg_ptr;
1109    int i, len, maxlen;
1110
1111    i = sprintf(pool_buf, "%s:%d ", file, line);
1112
1113    for (;;) {
1114       maxlen = sizeof_pool_memory(pool_buf) - i - 1; 
1115       va_start(arg_ptr, fmt);
1116       len = bvsnprintf(pool_buf+i, maxlen, fmt, arg_ptr);
1117       va_end(arg_ptr);
1118       if (len < 0 || len >= (maxlen-5)) {
1119          pool_buf = realloc_pool_memory(pool_buf, maxlen + i + maxlen/2);
1120          continue;
1121       }
1122       break;
1123    }
1124    return len;
1125 }
1126
1127
1128 /*
1129  * Edit a message into a Pool Memory buffer NO file:lineno
1130  *  Returns: string length of what was edited.
1131  */
1132 int Mmsg(POOLMEM **pool_buf, const char *fmt, ...)
1133 {
1134    va_list   arg_ptr;
1135    int len, maxlen;
1136
1137    for (;;) {
1138       maxlen = sizeof_pool_memory(*pool_buf) - 1; 
1139       va_start(arg_ptr, fmt);
1140       len = bvsnprintf(*pool_buf, maxlen, fmt, arg_ptr);
1141       va_end(arg_ptr);
1142       if (len < 0 || len >= (maxlen-5)) {
1143          *pool_buf = realloc_pool_memory(*pool_buf, maxlen + maxlen/2);
1144          continue;
1145       }
1146       break;
1147    }
1148    return len;
1149 }
1150
1151 int Mmsg(POOLMEM *&pool_buf, const char *fmt, ...)
1152 {
1153    va_list   arg_ptr;
1154    int len, maxlen;
1155
1156    for (;;) {
1157       maxlen = sizeof_pool_memory(pool_buf) - 1; 
1158       va_start(arg_ptr, fmt);
1159       len = bvsnprintf(pool_buf, maxlen, fmt, arg_ptr);
1160       va_end(arg_ptr);
1161       if (len < 0 || len >= (maxlen-5)) {
1162          pool_buf = realloc_pool_memory(pool_buf, maxlen + maxlen/2);
1163          continue;
1164       }
1165       break;
1166    }
1167    return len;
1168 }
1169
1170 int Mmsg(POOL_MEM &pool_buf, const char *fmt, ...)
1171 {
1172    va_list   arg_ptr;
1173    int len, maxlen;
1174
1175    for (;;) {
1176       maxlen = pool_buf.max_size() - 1; 
1177       va_start(arg_ptr, fmt);
1178       len = bvsnprintf(pool_buf.c_str(), maxlen, fmt, arg_ptr);
1179       va_end(arg_ptr);
1180       if (len < 0 || len >= (maxlen-5)) {
1181          pool_buf.realloc_pm(maxlen + maxlen/2);
1182          continue;
1183       }
1184       break;
1185    }
1186    return len;
1187 }
1188
1189
1190 static pthread_mutex_t msg_queue_mutex = PTHREAD_MUTEX_INITIALIZER;
1191
1192 /*
1193  * We queue messages rather than print them directly. This
1194  *  is generally used in low level routines (msg handler, bnet)
1195  *  to prevent recursion (i.e. if you are in the middle of 
1196  *  sending a message, it is a bit messy to recursively call
1197  *  yourself when the bnet packet is not reentrant).
1198  */
1199 void Qmsg(JCR *jcr, int type, int level, const char *fmt,...)
1200 {
1201    va_list   arg_ptr;
1202    int len, maxlen;
1203    POOLMEM *pool_buf;
1204    MQUEUE_ITEM *item;
1205
1206    pool_buf = get_pool_memory(PM_EMSG);
1207
1208    for (;;) {
1209       maxlen = sizeof_pool_memory(pool_buf) - 1; 
1210       va_start(arg_ptr, fmt);
1211       len = bvsnprintf(pool_buf, maxlen, fmt, arg_ptr);
1212       va_end(arg_ptr);
1213       if (len < 0 || len >= (maxlen-5)) {
1214          pool_buf = realloc_pool_memory(pool_buf, maxlen + maxlen/2);
1215          continue;
1216       }
1217       break;
1218    }
1219    item = (MQUEUE_ITEM *)malloc(sizeof(MQUEUE_ITEM) + strlen(pool_buf) + 1);
1220    item->type = type;
1221    item->level = level;
1222    strcpy(item->msg, pool_buf);  
1223    P(msg_queue_mutex);
1224    /* If no jcr or dequeuing send to daemon to avoid recursion */
1225    if (!jcr || jcr->dequeuing) {
1226       /* jcr==NULL => daemon message, safe to send now */
1227       Jmsg(NULL, item->type, item->level, "%s", item->msg);
1228       free(item);
1229    } else {
1230       /* Queue message for later sending */
1231       jcr->msg_queue->append(item);
1232 //    Dmsg1(000, "queue item=%lu\n", (long unsigned)item);
1233    }
1234    V(msg_queue_mutex);
1235    free_memory(pool_buf);
1236 }
1237
1238 /*
1239  * Dequeue messages 
1240  */
1241 void dequeue_messages(JCR *jcr)
1242 {
1243    MQUEUE_ITEM *item;
1244    P(msg_queue_mutex);
1245    jcr->dequeuing = true;
1246    foreach_dlist(item, jcr->msg_queue) {
1247 //    Dmsg1(000, "dequeue item=%lu\n", (long unsigned)item);
1248       Jmsg(jcr, item->type, item->level, "%s", item->msg);
1249    }
1250    jcr->msg_queue->destroy();
1251    jcr->dequeuing = false;
1252    V(msg_queue_mutex);
1253 }                                                 
1254
1255
1256 /*
1257  * If we come here, prefix the message with the file:line-number,
1258  *  then pass it on to the normal Qmsg routine.
1259  */
1260 void q_msg(const char *file, int line, JCR *jcr, int type, int level, const char *fmt,...)
1261 {
1262    va_list   arg_ptr;
1263    int i, len, maxlen;
1264    POOLMEM *pool_buf;
1265
1266    pool_buf = get_pool_memory(PM_EMSG);
1267    i = Mmsg(pool_buf, "%s:%d ", file, line);
1268
1269    for (;;) {
1270       maxlen = sizeof_pool_memory(pool_buf) - i - 1; 
1271       va_start(arg_ptr, fmt);
1272       len = bvsnprintf(pool_buf+i, maxlen, fmt, arg_ptr);
1273       va_end(arg_ptr);
1274       if (len < 0 || len >= (maxlen-5)) {
1275          pool_buf = realloc_pool_memory(pool_buf, maxlen + i + maxlen/2);
1276          continue;
1277       }
1278       break;
1279    }
1280
1281    Qmsg(jcr, type, level, "%s", pool_buf);
1282    free_memory(pool_buf);
1283 }
1284
1285 /* 
1286  * Define if e_msg must exit when M_ERROR_TERM is received
1287  */
1288 void set_exit_on_error(int value) {
1289    exit_on_error = value;
1290 }