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