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