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