]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/lib/message.c
New tree commands lsmark+estimate
[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-2003 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 #define FULL_LOCATION 1               /* set for file:line in Debug messages */
35
36 /* 
37  *  This is where we define "Globals" because all the
38  *    daemons include this file.
39  */
40 char *working_directory = NULL;       /* working directory path stored here */
41 int verbose = 0;                      /* increase User messages */
42 int debug_level = 0;                  /* debug level */
43 time_t daemon_start_time = 0;         /* Daemon start time */
44 char *version = VERSION " (" BDATE ")";
45 char my_name[30];                     /* daemon name is stored here */
46 char *exepath = (char *)NULL;
47 char *exename = (char *)NULL;
48 int console_msg_pending = 0;
49 char con_fname[500];                  /* Console filename */
50 FILE *con_fd = NULL;                  /* Console file descriptor */
51 brwlock_t con_lock;                   /* Console lock structure */
52 FILE *trace_fd = NULL;
53
54 #ifdef HAVE_MYSQL
55 char catalog_db[] = "MySQL";
56 #else 
57 #ifdef HAVE_SQLITE
58 char catalog_db[] = "SQLite";
59 #else
60 char catalog_db[] = "Internal";
61 #endif
62 #endif
63
64 char *host_os = HOST_OS;
65 char *distname = DISTNAME;
66 char *distver = DISTVER;
67
68 /* Forward referenced functions */
69
70 /* Imported functions */
71
72
73 /* Static storage */
74
75 static MSGS *daemon_msgs;              /* global messages */
76
77 /* 
78  * Set daemon name. Also, find canonical execution
79  *  path.  Note, exepath has spare room for tacking on
80  *  the exename so that we can reconstruct the full name.
81  *
82  * Note, this routine can get called multiple times
83  *  The second time is to put the name as found in the
84  *  Resource record. On the second call, generally,
85  *  argv is NULL to avoid doing the path code twice.
86  */
87 #define BTRACE_EXTRA 20
88 void my_name_is(int argc, char *argv[], char *name)
89 {
90    char *l, *p, *q;
91    char cpath[400], npath[400];
92    int len;
93
94    bstrncpy(my_name, name, sizeof(my_name));
95    if (argc>0 && argv && argv[0]) {
96       /* strip trailing filename and save exepath */
97       for (l=p=argv[0]; *p; p++) {
98          if (*p == '/') {
99             l = p;                       /* set pos of last slash */
100          }
101       }
102       if (*l == '/') {
103          l++;
104       } else {
105          l = argv[0];
106 #ifdef HAVE_CYGWIN
107          /* On Windows allow c: junk */
108          if (l[1] == ':') {
109             l += 2;
110          }
111 #endif
112       }
113       len = strlen(l) + 1;
114       if (exename) {
115          free(exename);
116       }
117       exename = (char *)malloc(len);
118       strcpy(exename, l);
119
120       if (exepath) {
121          free(exepath);
122       }
123       exepath = (char *)malloc(strlen(argv[0]) + 1 + len);
124       for (p=argv[0],q=exepath; p < l; ) {
125          *q++ = *p++;
126       }
127       *q = 0;
128       Dmsg1(200, "exepath=%s\n", exepath);
129       if (strchr(exepath, '.') || exepath[0] != '/') {
130          npath[0] = 0;
131          if (getcwd(cpath, sizeof(cpath))) {
132             if (chdir(exepath) == 0) {
133                if (!getcwd(npath, sizeof(npath))) {
134                   npath[0] = 0;
135                }
136                chdir(cpath);
137             }
138             if (npath[0]) {
139                free(exepath);
140                exepath = (char *)malloc(strlen(npath) + 1 + len);
141                strcpy(exepath, npath);
142             }
143          }
144          Dmsg1(200, "Normalized exepath=%s\n", exepath);
145       }
146    }
147 }
148
149 /* 
150  * Initialize message handler for a daemon or a Job
151  *   We make a copy of the MSGS resource passed, so it belows
152  *   to the job or daemon and thus can be modified.
153  * 
154  *   NULL for jcr -> initialize global messages for daemon
155  *   non-NULL     -> initialize jcr using Message resource
156  */
157 void
158 init_msg(JCR *jcr, MSGS *msg)
159 {
160    DEST *d, *dnew, *temp_chain = NULL;
161    int i, fd;
162
163    /*
164     * Make sure we have fd's 0, 1, 2 open
165     *  If we don't do this one of our sockets may open
166     *  there and if we then use stdout, it could
167     *  send total garbage to our socket.
168     *
169     */
170    fd = open("/dev/null", O_RDONLY, 0644);
171    if (fd > 2) {
172       close(fd);
173    } else {
174       for(i=1; fd + i <= 2; i++) {
175          dup2(fd, fd+i);
176       }
177    }
178
179
180    /*
181     * If msg is NULL, initialize global chain for STDOUT and syslog
182     */
183    if (msg == NULL) {
184       daemon_msgs = (MSGS *)malloc(sizeof(MSGS));
185       memset(daemon_msgs, 0, sizeof(MSGS));
186       for (i=1; i<=M_MAX; i++) {
187          add_msg_dest(daemon_msgs, MD_STDOUT, i, NULL, NULL);
188          add_msg_dest(daemon_msgs, MD_SYSLOG, i, NULL, NULL);
189       }
190       Dmsg1(050, "Create daemon global message resource 0x%x\n", daemon_msgs);
191       return;
192    }
193
194    /*
195     * Walk down the message resource chain duplicating it
196     * for the current Job.
197     */
198    for (d=msg->dest_chain; d; d=d->next) {
199       dnew = (DEST *)malloc(sizeof(DEST));
200       memcpy(dnew, d, sizeof(DEST));
201       dnew->next = temp_chain;
202       dnew->fd = NULL;
203       dnew->mail_filename = NULL;
204       if (d->mail_cmd) {
205          dnew->mail_cmd = bstrdup(d->mail_cmd);
206       }
207       if (d->where) {
208          dnew->where = bstrdup(d->where);
209       }
210       temp_chain = dnew;
211    }
212
213    if (jcr) {
214       jcr->jcr_msgs = (MSGS *)malloc(sizeof(MSGS));
215       memset(jcr->jcr_msgs, 0, sizeof(MSGS));
216       jcr->jcr_msgs->dest_chain = temp_chain;
217       memcpy(jcr->jcr_msgs->send_msg, msg->send_msg, sizeof(msg->send_msg));
218    } else {
219       /* If we have default values, release them now */
220       if (daemon_msgs) {
221          free_msgs_res(daemon_msgs);
222       }
223       daemon_msgs = (MSGS *)malloc(sizeof(MSGS));
224       memset(daemon_msgs, 0, sizeof(MSGS));
225       daemon_msgs->dest_chain = temp_chain;
226       memcpy(daemon_msgs->send_msg, msg->send_msg, sizeof(msg->send_msg));
227    }
228    Dmsg2(050, "Copy message resource 0x%x to 0x%x\n", msg, temp_chain);
229
230 }
231
232 /* Initialize so that the console (User Agent) can
233  * receive messages -- stored in a file.
234  */
235 void init_console_msg(char *wd)
236 {
237    int fd;
238
239    bsnprintf(con_fname, sizeof(con_fname), "%s/%s.conmsg", wd, my_name);
240    fd = open(con_fname, O_CREAT|O_RDWR|O_BINARY, 0600);
241    if (fd == -1) {
242       Emsg2(M_ERROR_TERM, 0, _("Could not open console message file %s: ERR=%s\n"),
243           con_fname, strerror(errno));
244    }
245    if (lseek(fd, 0, SEEK_END) > 0) {
246       console_msg_pending = 1;
247    }
248    close(fd);
249    con_fd = fopen(con_fname, "a+");
250    if (!con_fd) {
251       Emsg2(M_ERROR, 0, _("Could not open console message file %s: ERR=%s\n"),
252           con_fname, strerror(errno));
253    }
254    if (rwl_init(&con_lock) != 0) {
255       Emsg1(M_ERROR_TERM, 0, _("Could not get con mutex: ERR=%s\n"), 
256          strerror(errno));
257    }
258 }
259
260 /* 
261  * Called only during parsing of the config file.
262  *
263  * Add a message destination. I.e. associate a message type with
264  *  a destination (code).
265  * Note, where in the case of dest_code FILE is a filename,
266  *  but in the case of MAIL is a space separated list of
267  *  email addresses, ...
268  */
269 void add_msg_dest(MSGS *msg, int dest_code, int msg_type, char *where, char *mail_cmd)
270 {
271    DEST *d; 
272    /*
273     * First search the existing chain and see if we
274     * can simply add this msg_type to an existing entry.
275     */
276    for (d=msg->dest_chain; d; d=d->next) {
277       if (dest_code == d->dest_code && ((where == NULL && d->where == NULL) ||
278                      (strcmp(where, d->where) == 0))) {  
279          Dmsg4(200, "Add to existing d=%x msgtype=%d destcode=%d where=%s\n", 
280              d, msg_type, dest_code, NPRT(where));
281          set_bit(msg_type, d->msg_types);
282          set_bit(msg_type, msg->send_msg);  /* set msg_type bit in our local */
283          return;
284       }
285    }
286    /* Not found, create a new entry */
287    d = (DEST *)malloc(sizeof(DEST));
288    memset(d, 0, sizeof(DEST));
289    d->next = msg->dest_chain;
290    d->dest_code = dest_code;
291    set_bit(msg_type, d->msg_types);      /* set type bit in structure */
292    set_bit(msg_type, msg->send_msg);     /* set type bit in our local */
293    if (where) {
294       d->where = bstrdup(where);
295    }
296    if (mail_cmd) {
297       d->mail_cmd = bstrdup(mail_cmd);
298    }
299    Dmsg5(200, "add new d=%x msgtype=%d destcode=%d where=%s mailcmd=%s\n", 
300           d, msg_type, dest_code, NPRT(where), NPRT(d->mail_cmd));
301    msg->dest_chain = d;
302 }
303
304 /* 
305  * Called only during parsing of the config file.
306  *
307  * Remove a message destination   
308  */
309 void rem_msg_dest(MSGS *msg, int dest_code, int msg_type, char *where)
310 {
311    DEST *d;
312
313    for (d=msg->dest_chain; d; d=d->next) {
314       Dmsg2(200, "Remove_msg_dest d=%x where=%s\n", d, NPRT(d->where));
315       if (bit_is_set(msg_type, d->msg_types) && (dest_code == d->dest_code) &&
316           ((where == NULL && d->where == NULL) ||
317                      (strcmp(where, d->where) == 0))) {  
318          Dmsg3(200, "Found for remove d=%x msgtype=%d destcode=%d\n", 
319                d, msg_type, dest_code);
320          clear_bit(msg_type, d->msg_types);
321          Dmsg0(200, "Return rem_msg_dest\n");
322          return;
323       }
324    }
325 }
326
327 static void make_unique_spool_filename(JCR *jcr, POOLMEM **name, int fd)
328 {
329    Mmsg(name, "%s/%s.spool.%s.%d", working_directory, my_name,
330       jcr->Job, fd);
331 }
332
333 int open_spool_file(JCR *jcr, BSOCK *bs)
334 {
335     POOLMEM *name  = get_pool_memory(PM_MESSAGE);
336
337     make_unique_spool_filename(jcr, &name, bs->fd);
338     bs->spool_fd = fopen(mp_chr(name), "w+");
339     if (!bs->spool_fd) {
340        Jmsg(jcr, M_ERROR, 0, "fopen spool file %s failed: ERR=%s\n", name, strerror(errno));
341        free_pool_memory(name);
342        return 0;
343     }
344     free_pool_memory(name);
345     return 1;
346 }
347
348 int close_spool_file(JCR *jcr, BSOCK *bs)
349 {
350     POOLMEM *name  = get_pool_memory(PM_MESSAGE);
351
352     make_unique_spool_filename(jcr, &name, bs->fd);
353     fclose(bs->spool_fd);
354     unlink(mp_chr(name));
355     free_pool_memory(name);
356     bs->spool_fd = NULL;
357     bs->spool = 0;
358     return 1;
359 }
360
361 /*
362  * Create a unique filename for the mail command
363  */
364 static void make_unique_mail_filename(JCR *jcr, POOLMEM **name, DEST *d)
365 {
366    if (jcr) {
367       Mmsg(name, "%s/%s.mail.%s.%d", working_directory, my_name,
368                  jcr->Job, (int)d);
369    } else {
370       Mmsg(name, "%s/%s.mail.%s.%d", working_directory, my_name,
371                  my_name, (int)d);
372    }
373    Dmsg1(200, "mailname=%s\n", *name);
374 }
375
376 /*
377  * Open a mail pipe
378  */
379 static BPIPE *open_mail_pipe(JCR *jcr, POOLMEM **cmd, DEST *d)
380 {
381    BPIPE *bpipe;
382
383    if (d->mail_cmd && jcr) {
384       *cmd = edit_job_codes(jcr, *cmd, d->mail_cmd, d->where);
385    } else {
386       Mmsg(cmd, "mail -s \"Bacula Message\" %s", d->where);
387    }
388    fflush(stdout);
389
390    if (!(bpipe = open_bpipe(*cmd, 120, "rw"))) {
391       Jmsg(jcr, M_ERROR, 0, "open mail pipe %s failed: ERR=%s\n", 
392          *cmd, strerror(errno));
393    } 
394    return bpipe;
395 }
396
397 /* 
398  * Close the messages for this Messages resource, which means to close
399  *  any open files, and dispatch any pending email messages.
400  */
401 void close_msg(JCR *jcr)
402 {
403    MSGS *msgs;
404    DEST *d;
405    BPIPE *bpipe;
406    POOLMEM *cmd, *line;
407    int len, stat;
408    
409    Dmsg1(050, "Close_msg jcr=0x%x\n", jcr);
410
411    if (jcr == NULL) {                /* NULL -> global chain */
412       msgs = daemon_msgs;
413    } else {
414       msgs = jcr->jcr_msgs;
415       jcr->jcr_msgs = NULL;
416    }
417    if (msgs == NULL) {
418       return;
419    }
420    Dmsg1(150, "===Begin close msg resource at 0x%x\n", msgs);
421    cmd = get_pool_memory(PM_MESSAGE);
422    for (d=msgs->dest_chain; d; ) {
423       if (d->fd) {
424          switch (d->dest_code) {
425          case MD_FILE:
426          case MD_APPEND:
427             if (d->fd) {
428                fclose(d->fd);            /* close open file descriptor */
429             }
430             break;
431          case MD_MAIL:
432          case MD_MAIL_ON_ERROR:
433             Dmsg0(150, "Got MD_MAIL or MD_MAIL_ON_ERROR\n");
434             if (!d->fd) {
435                break;
436             }
437             if (d->dest_code == MD_MAIL_ON_ERROR && jcr &&
438                 jcr->JobStatus == JS_Terminated) {
439                goto rem_temp_file;
440             }
441             
442             if (!(bpipe=open_mail_pipe(jcr, &cmd, d))) {
443                Pmsg0(000, "open mail pipe failed.\n");
444                goto rem_temp_file;
445             }
446             Dmsg0(150, "Opened mail pipe\n");
447             len = d->max_len+10;
448             line = get_memory(len);
449             rewind(d->fd);
450             while (fgets(mp_chr(line), len, d->fd)) {
451                fputs(line, bpipe->wfd);
452             }
453             if (!close_wpipe(bpipe)) {       /* close write pipe sending mail */
454                Pmsg1(000, "close error: ERR=%s\n", strerror(errno));
455             }
456
457             /*
458              * Since we are closing all messages, before "recursing"
459              * make sure we are not closing the daemon messages, otherwise
460              * kaboom.
461              */
462             if (msgs != daemon_msgs) {
463                /* read what mail prog returned -- should be nothing */
464                while (fgets(mp_chr(line), len, bpipe->rfd)) {
465                   Jmsg1(jcr, M_INFO, 0, _("Mail prog: %s"), line);
466                }
467             }
468
469             stat = close_bpipe(bpipe);
470             if (stat != 0 && msgs != daemon_msgs) {
471                Dmsg1(150, "Calling emsg. CMD=%s\n", cmd);
472                Jmsg2(jcr, M_ERROR, 0, _("Mail program terminated in error. stat=%d\n"
473                                         "CMD=%s\n"), stat, cmd);
474             }
475             free_memory(line);
476 rem_temp_file:
477             /* Remove temp file */
478             fclose(d->fd);
479             unlink(mp_chr(d->mail_filename));
480             free_pool_memory(d->mail_filename);
481             d->mail_filename = NULL;
482             Dmsg0(150, "end mail or mail on error\n");
483             break;
484          default:
485             break;
486          }
487          d->fd = NULL;
488       }
489       d = d->next;                    /* point to next buffer */
490    }
491    free_pool_memory(cmd);
492    Dmsg0(150, "Done walking message chain.\n");
493    if (jcr) {
494       free_msgs_res(msgs);
495       msgs = NULL;
496    }
497    Dmsg0(150, "===End close msg resource\n");
498 }
499
500 /*
501  * Free memory associated with Messages resource  
502  */
503 void free_msgs_res(MSGS *msgs)
504 {
505    DEST *d, *old;
506
507    /* Walk down the message chain releasing allocated buffers */
508    for (d=msgs->dest_chain; d; ) {
509       if (d->where) {
510          free(d->where);
511       }
512       if (d->mail_cmd) {
513          free(d->mail_cmd);
514       }
515       old = d;                        /* save pointer to release */
516       d = d->next;                    /* point to next buffer */
517       free(old);                      /* free the destination item */
518    }
519    msgs->dest_chain = NULL;
520    free(msgs);                        /* free the head */
521 }
522
523
524 /* 
525  * Terminate the message handler for good. 
526  * Release the global destination chain.
527  * 
528  * Also, clean up a few other items (cons, exepath). Note,
529  *   these really should be done elsewhere.
530  */
531 void term_msg()
532 {
533    Dmsg0(100, "Enter term_msg\n");
534    close_msg(NULL);                   /* close global chain */
535    free_msgs_res(daemon_msgs);        /* free the resources */
536    daemon_msgs = NULL;
537    if (con_fd) {
538       fflush(con_fd);
539       fclose(con_fd);
540       con_fd = NULL;
541    }
542    if (exepath) {
543       free(exepath);
544       exepath = NULL;
545    }
546    if (exename) {
547       free(exename);
548       exename = NULL;
549    }
550    if (trace_fd) {
551       fclose(trace_fd);
552       trace_fd = NULL;
553    }
554 }
555
556
557
558 /*
559  * Handle sending the message to the appropriate place
560  */
561 void dispatch_message(JCR *jcr, int type, int level, char *msg)
562 {
563     DEST *d;   
564     char dt[MAX_TIME_LENGTH];
565     POOLMEM *mcmd;
566     int len;
567     MSGS *msgs;
568     BPIPE *bpipe;
569
570     Dmsg2(800, "Enter dispatch_msg type=%d msg=%s\n", type, msg);
571
572     if (type == M_ABORT || type == M_ERROR_TERM) {
573        fputs(msg, stdout);         /* print this here to INSURE that it is printed */
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                       Emsg1(M_ERROR, 0, _("Operator mail program terminated in error.\nCMD=%s\n"),
631                          mcmd);
632                    }
633                 }
634                 free_pool_memory(mcmd);
635                 break;
636              case MD_MAIL:
637              case MD_MAIL_ON_ERROR:
638                 Dmsg1(800, "MAIL for following msg: %s", msg);
639                 if (!d->fd) {
640                    POOLMEM *name = get_pool_memory(PM_MESSAGE);
641                    make_unique_mail_filename(jcr, &mp_chr(name), d);
642                    d->fd = fopen(mp_chr(name), "w+");
643                    if (!d->fd) {
644                       d->fd = stdout;
645                       Emsg2(M_ERROR, 0, "fopen %s failed: ERR=%s\n", name, strerror(errno));
646                       d->fd = NULL;
647                       free_pool_memory(name);
648                       break;
649                    }
650                    d->mail_filename = name;
651                 }
652                 len = strlen(msg);
653                 if (len > d->max_len) {
654                    d->max_len = len;      /* keep max line length */
655                 }
656                 fputs(msg, d->fd);
657                 break;
658              case MD_FILE:
659                 Dmsg1(800, "FILE for following msg: %s", msg);
660                 if (!d->fd) {
661                    d->fd = fopen(d->where, "w+");
662                    if (!d->fd) {
663                       d->fd = stdout;
664                       Emsg2(M_ERROR, 0, "fopen %s failed: ERR=%s\n", d->where, strerror(errno));
665                       d->fd = NULL;
666                       break;
667                    }
668                 }
669                 fputs(msg, d->fd);
670                 break;
671              case MD_APPEND:
672                 Dmsg1(800, "APPEND for following msg: %s", msg);
673                 if (!d->fd) {
674                    d->fd = fopen(d->where, "a");
675                    if (!d->fd) {
676                       d->fd = stdout;
677                       Emsg2(M_ERROR, 0, "fopen %s failed: ERR=%s\n", d->where, strerror(errno));
678                       d->fd = NULL;
679                       break;
680                    }
681                 }
682                 fputs(msg, d->fd);
683                 break;
684              case MD_DIRECTOR:
685                 Dmsg1(800, "DIRECTOR for following msg: %s", msg);
686                 if (jcr && jcr->dir_bsock && !jcr->dir_bsock->errors) {
687                    bnet_fsend(jcr->dir_bsock, "Jmsg Job=%s type=%d level=%d %s", 
688                       jcr->Job, type, level, msg);
689                 }
690                 break;
691              case MD_STDOUT:
692                 Dmsg1(800, "STDOUT for following msg: %s", msg);
693                 if (type != M_ABORT && type != M_ERROR_TERM) { /* already printed */
694                    fputs(msg, stdout);
695                 }
696                 break;
697              case MD_STDERR:
698                 Dmsg1(800, "STDERR for following msg: %s", msg);
699                 fputs(msg, stderr);
700                 break;
701              default:
702                 break;
703           }
704        }
705     }
706 }
707
708
709 /*********************************************************************
710  *
711  *  This subroutine prints a debug message if the level number
712  *  is less than or equal the debug_level. File and line numbers
713  *  are included for more detail if desired, but not currently
714  *  printed.
715  *  
716  *  If the level is negative, the details of file and line number
717  *  are not printed.
718  */
719 void 
720 d_msg(char *file, int line, int level, char *fmt,...)
721 {
722     char      buf[5000];
723     int       len;
724     va_list   arg_ptr;
725     int       details = TRUE;
726
727     if (level < 0) {
728        details = FALSE;
729        level = -level;
730     }
731
732     if (level <= debug_level) {
733 #ifdef SEND_DMSG_TO_FILE
734        if (!trace_fd) {
735           bsnprintf(buf, sizeof(buf), "%s/bacula.trace", working_directory);
736           trace_fd = fopen(buf, "a+");
737           if (!trace_fd) {
738              Emsg2(M_ABORT, 0, _("Cannot open %s: ERR=%s\n"),
739                   buf, strerror(errno));
740           }
741        }
742 #endif
743 #ifdef FULL_LOCATION
744        if (details) {
745           len = sprintf(buf, "%s: %s:%d ", my_name, file, line);
746        } else {
747           len = 0;
748        }
749 #else
750        len = 0;
751 #endif
752        va_start(arg_ptr, fmt);
753        bvsnprintf(buf+len, sizeof(buf)-len, (char *)fmt, arg_ptr);
754        va_end(arg_ptr);
755
756 #ifdef SEND_DMSG_TO_FILE
757        fputs(buf, trace_fd);
758        fflush(trace_fd);
759 #else
760        fputs(buf, stdout);
761 #endif
762     }
763 }
764
765
766 /*********************************************************************
767  *
768  *  This subroutine prints a message regardless of the debug level
769  *  
770  *  If the level is negative, the details of file and line number
771  *  are not printed.
772  */
773 void 
774 p_msg(char *file, int line, int level, char *fmt,...)
775 {
776     char      buf[5000];
777     int       len;
778     va_list   arg_ptr;
779
780 #ifdef FULL_LOCATION
781     if (level >= 0) {
782        len = sprintf(buf, "%s: %s:%d ", my_name, file, line);
783     } else {
784        len = 0;
785     }
786 #else
787     len = 0;
788 #endif
789     va_start(arg_ptr, fmt);
790     bvsnprintf(buf+len, sizeof(buf)-len, (char *)fmt, arg_ptr);
791     va_end(arg_ptr);
792     fputs(buf, stdout);
793 }
794
795
796 /*********************************************************************
797  *
798  *  subroutine writes a debug message to the trace file if the level number
799  *  is less than or equal the debug_level. File and line numbers
800  *  are included for more detail if desired, but not currently
801  *  printed.
802  *  
803  *  If the level is negative, the details of file and line number
804  *  are not printed.
805  */
806 void 
807 t_msg(char *file, int line, int level, char *fmt,...)
808 {
809     char      buf[5000];
810     int       len;
811     va_list   arg_ptr;
812     int       details = TRUE;
813
814     if (level < 0) {
815        details = FALSE;
816        level = -level;
817     }
818
819     if (level <= debug_level) {
820        if (!trace_fd) {
821           bsnprintf(buf, sizeof(buf), "%s/bacula.trace", working_directory);
822           trace_fd = fopen(buf, "a+");
823           if (!trace_fd) {
824              Emsg2(M_ABORT, 0, _("Cannot open %s: ERR=%s\n"),
825                   buf, strerror(errno));
826           }
827        }
828     
829 #ifdef FULL_LOCATION
830        if (details) {
831           len = sprintf(buf, "%s: %s:%d ", my_name, file, line);
832        } else {
833           len = 0;
834        }
835 #else
836        len = 0;
837 #endif
838        va_start(arg_ptr, fmt);
839        bvsnprintf(buf+len, sizeof(buf)-len, (char *)fmt, arg_ptr);
840        va_end(arg_ptr);
841
842        fputs(buf, trace_fd);
843        fflush(trace_fd);
844     }
845 }
846
847
848
849 /* *********************************************************
850  *
851  * print an error message
852  *
853  */
854 void 
855 e_msg(char *file, int line, int type, int level, char *fmt,...)
856 {
857     char     buf[5000];
858     va_list   arg_ptr;
859     int len;
860
861     /* 
862      * Check if we have a message destination defined.  
863      * We always report M_ABORT and M_ERROR_TERM 
864      */
865     if (!daemon_msgs || ((type != M_ABORT && type != M_ERROR_TERM) && 
866                          !bit_is_set(type, daemon_msgs->send_msg))) {
867        return;                        /* no destination */
868     }
869     switch (type) {
870        case M_ABORT:
871           len = sprintf(buf, "%s: ABORTING due to ERROR in %s:%d\n", 
872                   my_name, file, line);
873           break;
874        case M_ERROR_TERM:
875           len = sprintf(buf, "%s: ERROR TERMINATION at %s:%d\n", 
876                   my_name, file, line);
877           break;
878        case M_FATAL:
879           if (level == -1)            /* skip details */
880              len = sprintf(buf, "%s: Fatal Error because: ", my_name);
881           else
882              len = sprintf(buf, "%s: Fatal Error at %s:%d because:\n", my_name, file, line);
883           break;
884        case M_ERROR:
885           if (level == -1)            /* skip details */
886              len = sprintf(buf, "%s: Error: ", my_name);
887           else
888              len = sprintf(buf, "%s: Error in %s:%d ", my_name, file, line);
889           break;
890        case M_WARNING:
891           len = sprintf(buf, "%s: Warning: ", my_name);
892           break;
893        default:
894           len = sprintf(buf, "%s: ", my_name);
895           break;
896     }
897
898     va_start(arg_ptr, fmt);
899     bvsnprintf(buf+len, sizeof(buf)-len, (char *)fmt, arg_ptr);
900     va_end(arg_ptr);
901
902     dispatch_message(NULL, type, level, buf);
903
904     if (type == M_ABORT) {
905        char *p = 0;
906        p[0] = 0;                      /* generate segmentation violation */
907     }
908     if (type == M_ERROR_TERM) {
909        _exit(1);
910     }
911 }
912
913 /* *********************************************************
914  *
915  * Generate a Job message
916  *
917  */
918 void 
919 Jmsg(JCR *jcr, int type, int level, char *fmt,...)
920 {
921     char     rbuf[5000];
922     va_list   arg_ptr;
923     int len;
924     MSGS *msgs;
925     char *job;
926
927     
928     Dmsg1(800, "Enter Jmsg type=%d\n", type);
929
930     /* Special case for the console, which has a dir_bsock and JobId==0,
931      *  in that case, we send the message directly back to the
932      *  dir_bsock.  
933      */
934     if (jcr && jcr->JobId == 0 && jcr->dir_bsock) {
935        BSOCK *dir = jcr->dir_bsock;
936        va_start(arg_ptr, fmt);
937        dir->msglen = bvsnprintf(mp_chr(dir->msg), sizeof_pool_memory(dir->msg), 
938                                 fmt, arg_ptr);
939        va_end(arg_ptr);
940        bnet_send(jcr->dir_bsock);
941        return;
942     }
943
944     msgs = NULL;
945     job = NULL;
946     if (jcr) {
947        msgs = jcr->jcr_msgs;
948        job = jcr->Job;
949     } 
950     if (!msgs) {
951        msgs = daemon_msgs;            /* if no jcr, we use daemon handler */
952     }
953     if (!job) {
954        job = "";                      /* Set null job name if none */
955     }
956
957     /* 
958      * Check if we have a message destination defined.  
959      * We always report M_ABORT and M_ERROR_TERM 
960      */
961     if (msgs && (type != M_ABORT && type != M_ERROR_TERM) &&
962          !bit_is_set(type, msgs->send_msg)) {
963        return;                        /* no destination */
964     }
965     switch (type) {
966     case M_ABORT:
967        len = sprintf(rbuf, "%s ABORTING due to ERROR\n", my_name);
968        break;
969     case M_ERROR_TERM:
970        len = sprintf(rbuf, "%s ERROR TERMINATION\n", my_name);
971        break;
972     case M_FATAL:
973        len = sprintf(rbuf, "%s: %s Fatal error: ", my_name, job);
974        if (jcr) {
975           set_jcr_job_status(jcr, JS_FatalError);
976        }
977        break;
978     case M_ERROR:
979        len = sprintf(rbuf, "%s: %s Error: ", my_name, job);
980        if (jcr) {
981           jcr->Errors++;
982        }
983        break;
984     case M_WARNING:
985        len = sprintf(rbuf, "%s: %s Warning: ", my_name, job);
986        break;
987     default:
988        len = sprintf(rbuf, "%s: ", my_name);
989        break;
990     }
991
992     va_start(arg_ptr, fmt);
993     bvsnprintf(rbuf+len,  sizeof(rbuf)-len, fmt, arg_ptr);
994     va_end(arg_ptr);
995
996     dispatch_message(jcr, type, level, rbuf);
997
998     if (type == M_ABORT){
999        char *p = 0;
1000        p[0] = 0;                      /* generate segmentation violation */
1001     }
1002     if (type == M_ERROR_TERM) {
1003        _exit(1);
1004     }
1005 }
1006
1007 /*
1008  * Edit a message into a Pool memory buffer, with file:lineno
1009  */
1010 int m_msg(char *file, int line, POOLMEM **pool_buf, char *fmt, ...)
1011 {
1012    va_list   arg_ptr;
1013    int i, len, maxlen;
1014
1015    i = sprintf(mp_chr(*pool_buf), "%s:%d ", file, line);
1016
1017 again:
1018    maxlen = sizeof_pool_memory(*pool_buf) - i - 1; 
1019    va_start(arg_ptr, fmt);
1020    len = bvsnprintf(*pool_buf+i, maxlen, fmt, arg_ptr);
1021    va_end(arg_ptr);
1022    if (len < 0 || len >= maxlen) {
1023       *pool_buf = realloc_pool_memory(*pool_buf, maxlen + i + 200);
1024       goto again;
1025    }
1026    return len;
1027 }
1028
1029 /*
1030  * Edit a message into a Pool Memory buffer NO file:lineno
1031  *  Returns: string length of what was edited.
1032  */
1033 int Mmsg(POOLMEM **pool_buf, char *fmt, ...)
1034 {
1035    va_list   arg_ptr;
1036    int len, maxlen;
1037
1038 again:
1039    maxlen = sizeof_pool_memory(*pool_buf) - 1; 
1040    va_start(arg_ptr, fmt);
1041    len = bvsnprintf(*pool_buf, maxlen, fmt, arg_ptr);
1042    va_end(arg_ptr);
1043    if (len < 0 || len >= maxlen) {
1044       *pool_buf = realloc_pool_memory(*pool_buf, maxlen + 200);
1045       goto again;
1046    }
1047    return len;
1048 }
1049
1050
1051 /*
1052  * If we come here, prefix the message with the file:line-number,
1053  *  then pass it on to the normal Jmsg routine.
1054  */
1055 void j_msg(char *file, int line, JCR *jcr, int type, int level, char *fmt,...)
1056 {
1057    va_list   arg_ptr;
1058    int i, len, maxlen;
1059    POOLMEM *pool_buf;
1060
1061    pool_buf = get_pool_memory(PM_EMSG);
1062    i = sprintf(pool_buf, "%s:%d ", file, line);
1063
1064 again:
1065    maxlen = sizeof_pool_memory(pool_buf) - i - 1; 
1066    va_start(arg_ptr, fmt);
1067    len = bvsnprintf(pool_buf+i, maxlen, fmt, arg_ptr);
1068    va_end(arg_ptr);
1069    if (len < 0 || len >= maxlen) {
1070       pool_buf = realloc_pool_memory(pool_buf, maxlen + i + 200);
1071       goto again;
1072    }
1073
1074    Jmsg(jcr, type, level, "%s", pool_buf);
1075    free_memory(pool_buf);
1076 }