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