Consistently use strdup_or_die() instead of strdup()
[privoxy.git] / errlog.c
1 const char errlog_rcs[] = "$Id: errlog.c,v 1.126 2016/02/26 12:29:38 fabiankeil Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/errlog.c,v $
5  *
6  * Purpose     :  Log errors to a designated destination in an elegant,
7  *                printf-like fashion.
8  *
9  * Copyright   :  Written by and Copyright (C) 2001-2014 the
10  *                Privoxy team. http://www.privoxy.org/
11  *
12  *                Based on the Internet Junkbuster originally written
13  *                by and Copyright (C) 1997 Anonymous Coders and
14  *                Junkbusters Corporation.  http://www.junkbusters.com
15  *
16  *                This program is free software; you can redistribute it
17  *                and/or modify it under the terms of the GNU General
18  *                Public License as published by the Free Software
19  *                Foundation; either version 2 of the License, or (at
20  *                your option) any later version.
21  *
22  *                This program is distributed in the hope that it will
23  *                be useful, but WITHOUT ANY WARRANTY; without even the
24  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
25  *                PARTICULAR PURPOSE.  See the GNU General Public
26  *                License for more details.
27  *
28  *                The GNU General Public License should be included with
29  *                this file.  If not, you can view it at
30  *                http://www.gnu.org/copyleft/gpl.html
31  *                or write to the Free Software Foundation, Inc., 59
32  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
33  *
34  *********************************************************************/
35
36
37 #include <stdlib.h>
38 #include <stdio.h>
39 #include <stdarg.h>
40 #include <string.h>
41 #include <ctype.h>
42
43 #include "config.h"
44 #include "miscutil.h"
45
46 /* For gettimeofday() */
47 #include <sys/time.h>
48
49 #if !defined(_WIN32) && !defined(__OS2__)
50 #include <unistd.h>
51 #endif /* !defined(_WIN32) && !defined(__OS2__) */
52
53 #include <errno.h>
54 #include <assert.h>
55
56 #ifdef _WIN32
57 #ifndef STRICT
58 #define STRICT
59 #endif
60 #include <windows.h>
61 #ifndef _WIN_CONSOLE
62 #include "w32log.h"
63 #endif /* ndef _WIN_CONSOLE */
64 #endif /* def _WIN32 */
65 #ifdef _MSC_VER
66 #define inline __inline
67 #endif /* def _MSC_VER */
68
69 #ifdef __OS2__
70 #include <sys/socket.h> /* For sock_errno */
71 #define INCL_DOS
72 #include <os2.h>
73 #endif
74
75 #include "errlog.h"
76 #include "project.h"
77 #include "jcc.h"
78 #ifdef FEATURE_EXTERNAL_FILTERS
79 #include "jbsockets.h"
80 #endif
81
82 const char errlog_h_rcs[] = ERRLOG_H_VERSION;
83
84
85 /*
86  * LOG_LEVEL_FATAL cannot be turned off.  (There are
87  * some exceptional situations where we need to get a
88  * message to the user).
89  */
90 #define LOG_LEVEL_MINIMUM  LOG_LEVEL_FATAL
91
92 /* where to log (default: stderr) */
93 static FILE *logfp = NULL;
94
95 /* logging detail level. XXX: stupid name. */
96 static int debug = (LOG_LEVEL_FATAL | LOG_LEVEL_ERROR);
97
98 /* static functions */
99 static void fatal_error(const char * error_message);
100 #ifdef _WIN32
101 static char *w32_socket_strerr(int errcode, char *tmp_buf);
102 #endif
103 #ifdef __OS2__
104 static char *os2_socket_strerr(int errcode, char *tmp_buf);
105 #endif
106
107 #ifdef MUTEX_LOCKS_AVAILABLE
108 static inline void lock_logfile(void)
109 {
110    privoxy_mutex_lock(&log_mutex);
111 }
112 static inline void unlock_logfile(void)
113 {
114    privoxy_mutex_unlock(&log_mutex);
115 }
116 static inline void lock_loginit(void)
117 {
118    privoxy_mutex_lock(&log_init_mutex);
119 }
120 static inline void unlock_loginit(void)
121 {
122    privoxy_mutex_unlock(&log_init_mutex);
123 }
124 #else /* ! MUTEX_LOCKS_AVAILABLE */
125 /*
126  * FIXME we need a cross-platform locking mechanism.
127  * The locking/unlocking functions below should be
128  * fleshed out for non-pthread implementations.
129  */
130 static inline void lock_logfile() {}
131 static inline void unlock_logfile() {}
132 static inline void lock_loginit() {}
133 static inline void unlock_loginit() {}
134 #endif
135
136 /*********************************************************************
137  *
138  * Function    :  fatal_error
139  *
140  * Description :  Displays a fatal error to standard error (or, on
141  *                a WIN32 GUI, to a dialog box), and exits Privoxy
142  *                with status code 1.
143  *
144  * Parameters  :
145  *          1  :  error_message = The error message to display.
146  *
147  * Returns     :  Does not return.
148  *
149  *********************************************************************/
150 static void fatal_error(const char *error_message)
151 {
152    if (logfp != NULL)
153    {
154       fputs(error_message, logfp);
155    }
156
157 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
158    {
159       /* Skip timestamp and thread id for the message box. */
160       const char *box_message = strstr(error_message, "Fatal error");
161       if (NULL == box_message)
162       {
163          /* Shouldn't happen but ... */
164          box_message = error_message;
165       }
166       MessageBox(g_hwndLogFrame, box_message, "Privoxy Error",
167          MB_OK | MB_ICONERROR | MB_TASKMODAL | MB_SETFOREGROUND | MB_TOPMOST);
168
169       /* Cleanup - remove taskbar icon etc. */
170       TermLogWindow();
171    }
172 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
173
174 #if defined(unix)
175    if (pidfile)
176    {
177       unlink(pidfile);
178    }
179 #endif /* unix */
180
181    exit(1);
182 }
183
184
185 /*********************************************************************
186  *
187  * Function    :  show_version
188  *
189  * Description :  Logs the Privoxy version and the program name.
190  *
191  * Parameters  :
192  *          1  :  prog_name = The program name.
193  *
194  * Returns     :  Nothing.
195  *
196  *********************************************************************/
197 void show_version(const char *prog_name)
198 {
199    log_error(LOG_LEVEL_INFO, "Privoxy version " VERSION);
200    if (prog_name != NULL)
201    {
202       log_error(LOG_LEVEL_INFO, "Program name: %s", prog_name);
203    }
204 }
205
206
207 /*********************************************************************
208  *
209  * Function    :  init_log_module
210  *
211  * Description :  Initializes the logging module to log to stderr.
212  *                Can only be called while stderr hasn't been closed
213  *                yet and is only supposed to be called once.
214  *
215  * Parameters  :
216  *          1  :  prog_name = The program name.
217  *
218  * Returns     :  Nothing.
219  *
220  *********************************************************************/
221 void init_log_module(void)
222 {
223    lock_logfile();
224    logfp = stderr;
225    unlock_logfile();
226    set_debug_level(debug);
227 }
228
229
230 /*********************************************************************
231  *
232  * Function    :  set_debug_level
233  *
234  * Description :  Sets the debug level to the provided value
235  *                plus LOG_LEVEL_MINIMUM.
236  *
237  *                XXX: we should only use the LOG_LEVEL_MINIMUM
238  *                until the first time the configuration file has
239  *                been parsed.
240  *
241  * Parameters  :  1: debug_level = The debug level to set.
242  *
243  * Returns     :  Nothing.
244  *
245  *********************************************************************/
246 void set_debug_level(int debug_level)
247 {
248 #ifdef FUZZ
249    if (LOG_LEVEL_STFU == debug_level)
250    {
251       debug = LOG_LEVEL_STFU;
252    }
253    if (LOG_LEVEL_STFU == debug)
254    {
255       return;
256    }
257 #endif
258
259    debug = debug_level | LOG_LEVEL_MINIMUM;
260 }
261
262
263 /*********************************************************************
264  *
265  * Function    :  debug_level_is_enabled
266  *
267  * Description :  Checks if a certain debug level is enabled.
268  *
269  * Parameters  :  1: debug_level = The debug level to check.
270  *
271  * Returns     :  Nothing.
272  *
273  *********************************************************************/
274 int debug_level_is_enabled(int debug_level)
275 {
276    return (0 != (debug & debug_level));
277 }
278
279
280 /*********************************************************************
281  *
282  * Function    :  disable_logging
283  *
284  * Description :  Disables logging.
285  *
286  * Parameters  :  None.
287  *
288  * Returns     :  Nothing.
289  *
290  *********************************************************************/
291 void disable_logging(void)
292 {
293    if (logfp != NULL)
294    {
295       log_error(LOG_LEVEL_INFO,
296          "No logfile configured. Please enable it before reporting any problems.");
297       lock_logfile();
298       fclose(logfp);
299       logfp = NULL;
300       unlock_logfile();
301    }
302 }
303
304
305 /*********************************************************************
306  *
307  * Function    :  init_error_log
308  *
309  * Description :  Initializes the logging module to log to a file.
310  *
311  *                XXX: should be renamed.
312  *
313  * Parameters  :
314  *          1  :  prog_name  = The program name.
315  *          2  :  logfname   = The logfile to (re)open.
316  *
317  * Returns     :  N/A
318  *
319  *********************************************************************/
320 void init_error_log(const char *prog_name, const char *logfname)
321 {
322    FILE *fp;
323
324    assert(NULL != logfname);
325
326    lock_loginit();
327
328    if ((logfp != NULL) && (logfp != stderr))
329    {
330       log_error(LOG_LEVEL_INFO, "(Re-)Opening logfile \'%s\'", logfname);
331    }
332
333    /* set the designated log file */
334    fp = fopen(logfname, "a");
335    if ((NULL == fp) && (logfp != NULL))
336    {
337       /*
338        * Some platforms (like OS/2) don't allow us to open
339        * the same file twice, therefore we give it another
340        * shot after closing the old file descriptor first.
341        *
342        * We don't do it right away because it prevents us
343        * from logging the "can't open logfile" message to
344        * the old logfile.
345        *
346        * XXX: this is a lame workaround and once the next
347        * release is out we should stop bothering reopening
348        * the logfile unless we have to.
349        *
350        * Currently we reopen it every time the config file
351        * has been reloaded, but actually we only have to
352        * reopen it if the file name changed or if the
353        * configuration reload was caused by a SIGHUP.
354        */
355       log_error(LOG_LEVEL_INFO, "Failed to reopen logfile: \'%s\'. "
356          "Retrying after closing the old file descriptor first. If that "
357          "doesn't work, Privoxy will exit without being able to log a message.",
358          logfname);
359       lock_logfile();
360       fclose(logfp);
361       logfp = NULL;
362       unlock_logfile();
363       fp = fopen(logfname, "a");
364    }
365
366    if (NULL == fp)
367    {
368       log_error(LOG_LEVEL_FATAL, "init_error_log(): can't open logfile: \'%s\'", logfname);
369    }
370
371 #ifdef FEATURE_EXTERNAL_FILTERS
372    mark_socket_for_close_on_execute(3);
373 #endif
374
375    /* set logging to be completely unbuffered */
376    setbuf(fp, NULL);
377
378    lock_logfile();
379    if (logfp != NULL)
380    {
381       fclose(logfp);
382    }
383 #ifdef unix
384    if (daemon_mode && (logfp == stderr))
385    {
386       if (dup2(1, 2) == -1)
387       {
388          /*
389           * We only use fatal_error() to clear the pid
390           * file and to exit. Given that stderr has just
391           * been closed, the user will not see the error
392           * message.
393           */
394          fatal_error("Failed to reserve fd 2.");
395       }
396    }
397 #endif
398    logfp = fp;
399    unlock_logfile();
400
401    show_version(prog_name);
402
403    unlock_loginit();
404
405 } /* init_error_log */
406
407
408 /*********************************************************************
409  *
410  * Function    :  get_thread_id
411  *
412  * Description :  Returns a number that is different for each thread.
413  *
414  *                XXX: Should be moved elsewhere (miscutil.c?)
415  *
416  * Parameters  :  None
417  *
418  * Returns     :  thread_id
419  *
420  *********************************************************************/
421 static long get_thread_id(void)
422 {
423    long this_thread;
424
425 #ifdef __OS2__
426    PTIB     ptib;
427    APIRET   ulrc; /* XXX: I have no clue what this does */
428 #endif /* __OS2__ */
429
430    /* FIXME get current thread id */
431 #ifdef FEATURE_PTHREAD
432    this_thread = (long)pthread_self();
433 #ifdef __MACH__
434    /*
435     * Mac OSX (and perhaps other Mach instances) doesn't have a unique
436     * value at the lowest order 4 bytes of pthread_self()'s return value, a pthread_t,
437     * so trim the three lowest-order bytes from the value (16^3).
438     */
439    this_thread = this_thread / 4096;
440 #endif /* def __MACH__ */
441 #elif defined(_WIN32)
442    this_thread = GetCurrentThreadId();
443 #elif defined(__OS2__)
444    ulrc = DosGetInfoBlocks(&ptib, NULL);
445    if (ulrc == 0)
446      this_thread = ptib -> tib_ptib2 -> tib2_ultid;
447 #else
448    /* Forking instead of threading. */
449    this_thread = 1;
450 #endif /* def FEATURE_PTHREAD */
451
452    return this_thread;
453 }
454
455
456 /*********************************************************************
457  *
458  * Function    :  get_log_timestamp
459  *
460  * Description :  Generates the time stamp for the log message prefix.
461  *
462  * Parameters  :
463  *          1  :  buffer = Storage buffer
464  *          2  :  buffer_size = Size of storage buffer
465  *
466  * Returns     :  Number of written characters or 0 for error.
467  *
468  *********************************************************************/
469 static inline size_t get_log_timestamp(char *buffer, size_t buffer_size)
470 {
471    size_t length;
472    time_t now;
473    struct tm tm_now;
474    struct timeval tv_now; /* XXX: stupid name */
475    long msecs;
476    int msecs_length = 0;
477
478    gettimeofday(&tv_now, NULL);
479    msecs = tv_now.tv_usec / 1000;
480    now = tv_now.tv_sec;
481
482 #ifdef HAVE_LOCALTIME_R
483    tm_now = *localtime_r(&now, &tm_now);
484 #elif defined(MUTEX_LOCKS_AVAILABLE)
485    privoxy_mutex_lock(&localtime_mutex);
486    tm_now = *localtime(&now);
487    privoxy_mutex_unlock(&localtime_mutex);
488 #else
489    tm_now = *localtime(&now);
490 #endif
491
492    length = strftime(buffer, buffer_size, "%Y-%m-%d %H:%M:%S", &tm_now);
493    if (length > (size_t)0)
494    {
495       msecs_length = snprintf(buffer+length, buffer_size - length, ".%.3ld", msecs);
496    }
497    if (msecs_length > 0)
498    {
499       length += (size_t)msecs_length;
500    }
501    else
502    {
503       length = 0;
504    }
505
506    return length;
507 }
508
509
510 /*********************************************************************
511  *
512  * Function    :  get_clf_timestamp
513  *
514  * Description :  Generates a Common Log Format time string.
515  *
516  * Parameters  :
517  *          1  :  buffer = Storage buffer
518  *          2  :  buffer_size = Size of storage buffer
519  *
520  * Returns     :  Number of written characters or 0 for error.
521  *
522  *********************************************************************/
523 static inline size_t get_clf_timestamp(char *buffer, size_t buffer_size)
524 {
525    /*
526     * Complex because not all OSs have tm_gmtoff or
527     * the %z field in strftime()
528     */
529    time_t now;
530    struct tm *tm_now;
531    struct tm gmt;
532 #ifdef HAVE_LOCALTIME_R
533    struct tm dummy;
534 #endif
535    int days, hrs, mins;
536    size_t length;
537    int tz_length = 0;
538
539    time (&now);
540 #ifdef HAVE_GMTIME_R
541    gmt = *gmtime_r(&now, &gmt);
542 #elif defined(MUTEX_LOCKS_AVAILABLE)
543    privoxy_mutex_lock(&gmtime_mutex);
544    gmt = *gmtime(&now);
545    privoxy_mutex_unlock(&gmtime_mutex);
546 #else
547    gmt = *gmtime(&now);
548 #endif
549 #ifdef HAVE_LOCALTIME_R
550    tm_now = localtime_r(&now, &dummy);
551 #elif defined(MUTEX_LOCKS_AVAILABLE)
552    privoxy_mutex_lock(&localtime_mutex);
553    tm_now = localtime(&now);
554    privoxy_mutex_unlock(&localtime_mutex);
555 #else
556    tm_now = localtime(&now);
557 #endif
558    days = tm_now->tm_yday - gmt.tm_yday;
559    hrs = ((days < -1 ? 24 : 1 < days ? -24 : days * 24) + tm_now->tm_hour - gmt.tm_hour);
560    mins = hrs * 60 + tm_now->tm_min - gmt.tm_min;
561
562    length = strftime(buffer, buffer_size, "%d/%b/%Y:%H:%M:%S ", tm_now);
563
564    if (length > (size_t)0)
565    {
566       tz_length = snprintf(buffer+length, buffer_size-length,
567                      "%+03d%02d", mins / 60, abs(mins) % 60);
568    }
569    if (tz_length > 0)
570    {
571       length += (size_t)tz_length;
572    }
573    else
574    {
575       length = 0;
576    }
577
578    return length;
579 }
580
581
582 /*********************************************************************
583  *
584  * Function    :  get_log_level_string
585  *
586  * Description :  Translates a numerical loglevel into a string.
587  *
588  * Parameters  :
589  *          1  :  loglevel = LOG_LEVEL_FOO
590  *
591  * Returns     :  Log level string.
592  *
593  *********************************************************************/
594 static inline const char *get_log_level_string(int loglevel)
595 {
596    char *log_level_string = NULL;
597
598    assert(0 < loglevel);
599
600    switch (loglevel)
601    {
602       case LOG_LEVEL_ERROR:
603          log_level_string = "Error";
604          break;
605       case LOG_LEVEL_FATAL:
606          log_level_string = "Fatal error";
607          break;
608       case LOG_LEVEL_GPC:
609          log_level_string = "Request";
610          break;
611       case LOG_LEVEL_CONNECT:
612          log_level_string = "Connect";
613          break;
614       case LOG_LEVEL_WRITING:
615          log_level_string = "Writing";
616          break;
617       case LOG_LEVEL_RECEIVED:
618          log_level_string = "Received";
619          break;
620       case LOG_LEVEL_HEADER:
621          log_level_string = "Header";
622          break;
623       case LOG_LEVEL_INFO:
624          log_level_string = "Info";
625          break;
626       case LOG_LEVEL_RE_FILTER:
627          log_level_string = "Re-Filter";
628          break;
629 #ifdef FEATURE_FORCE_LOAD
630       case LOG_LEVEL_FORCE:
631          log_level_string = "Force";
632          break;
633 #endif /* def FEATURE_FORCE_LOAD */
634       case LOG_LEVEL_REDIRECTS:
635          log_level_string = "Redirect";
636          break;
637       case LOG_LEVEL_DEANIMATE:
638          log_level_string = "Gif-Deanimate";
639          break;
640       case LOG_LEVEL_CRUNCH:
641          log_level_string = "Crunch";
642          break;
643       case LOG_LEVEL_CGI:
644          log_level_string = "CGI";
645          break;
646       case LOG_LEVEL_ACTIONS:
647          log_level_string = "Actions";
648          break;
649       default:
650          log_level_string = "Unknown log level";
651          break;
652    }
653    assert(NULL != log_level_string);
654
655    return log_level_string;
656 }
657
658
659 #define LOG_BUFFER_SIZE BUFFER_SIZE
660 /*********************************************************************
661  *
662  * Function    :  log_error
663  *
664  * Description :  This is the error-reporting and logging function.
665  *
666  * Parameters  :
667  *          1  :  loglevel  = the type of message to be logged
668  *          2  :  fmt       = the main string we want logged, printf-like
669  *          3  :  ...       = arguments to be inserted in fmt (printf-like).
670  *
671  * Returns     :  N/A
672  *
673  *********************************************************************/
674 void log_error(int loglevel, const char *fmt, ...)
675 {
676    va_list ap;
677    char *outbuf = NULL;
678    static char *outbuf_save = NULL;
679    char tempbuf[LOG_BUFFER_SIZE];
680    size_t length = 0;
681    const char * src = fmt;
682    long thread_id;
683    char timestamp[30];
684    /*
685     * XXX: Make this a config option,
686     * why else do we allocate instead of using
687     * an array?
688     */
689    size_t log_buffer_size = LOG_BUFFER_SIZE;
690
691 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
692    /*
693     * Irrespective of debug setting, a GET/POST/CONNECT makes
694     * the taskbar icon animate.  (There is an option to disable
695     * this but checking that is handled inside LogShowActivity()).
696     */
697    if ((loglevel == LOG_LEVEL_GPC) || (loglevel == LOG_LEVEL_CRUNCH))
698    {
699       LogShowActivity();
700    }
701 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
702
703    /*
704     * verify that the loglevel applies to current
705     * settings and that logging is enabled.
706     * Bail out otherwise.
707     */
708    if ((0 == (loglevel & debug))
709 #ifndef _WIN32
710       || (logfp == NULL)
711 #endif
712       )
713    {
714 #ifdef FUZZ
715       if (debug == LOG_LEVEL_STFU)
716       {
717          return;
718       }
719 #endif
720       if (loglevel == LOG_LEVEL_FATAL)
721       {
722          fatal_error("Fatal error. You're not supposed to"
723             "see this message. Please file a bug report.");
724       }
725       return;
726    }
727
728    thread_id = get_thread_id();
729    get_log_timestamp(timestamp, sizeof(timestamp));
730
731    /* protect the whole function because of the static buffer (outbuf) */
732    lock_logfile();
733
734    if (NULL == outbuf_save)
735    {
736       outbuf_save = zalloc_or_die(log_buffer_size + 1); /* +1 for paranoia */
737    }
738    outbuf = outbuf_save;
739
740    /*
741     * Memsetting the whole buffer to zero (in theory)
742     * makes things easier later on.
743     */
744    memset(outbuf, 0, log_buffer_size);
745
746    /* Add prefix for everything but Common Log Format messages */
747    if (loglevel != LOG_LEVEL_CLF)
748    {
749       length = (size_t)snprintf(outbuf, log_buffer_size, "%s %08lx %s: ",
750          timestamp, thread_id, get_log_level_string(loglevel));
751    }
752
753    /* get ready to scan var. args. */
754    va_start(ap, fmt);
755
756    /* build formatted message from fmt and var-args */
757    while ((*src) && (length < log_buffer_size-2))
758    {
759       const char *sval = NULL; /* %N string  */
760       int ival;                /* %N string length or an error code */
761       unsigned uval;           /* %u value */
762       long lval;               /* %l value */
763       unsigned long ulval;     /* %ul value */
764       char ch;
765       const char *format_string = tempbuf;
766
767       ch = *src++;
768       if (ch != '%')
769       {
770          outbuf[length++] = ch;
771          /*
772           * XXX: Only necessary on platforms where multiple threads
773           * can write to the buffer at the same time because we
774           * don't support mutexes (OS/2 for example).
775           */
776          outbuf[length] = '\0';
777          continue;
778       }
779       outbuf[length] = '\0';
780       ch = *src++;
781       switch (ch) {
782          case '%':
783             tempbuf[0] = '%';
784             tempbuf[1] = '\0';
785             break;
786          case 'd':
787             ival = va_arg(ap, int);
788             snprintf(tempbuf, sizeof(tempbuf), "%d", ival);
789             break;
790          case 'u':
791             uval = va_arg(ap, unsigned);
792             snprintf(tempbuf, sizeof(tempbuf), "%u", uval);
793             break;
794          case 'l':
795             /* this is a modifier that must be followed by u, lu, or d */
796             ch = *src++;
797             if (ch == 'd')
798             {
799                lval = va_arg(ap, long);
800                snprintf(tempbuf, sizeof(tempbuf), "%ld", lval);
801             }
802             else if (ch == 'u')
803             {
804                ulval = va_arg(ap, unsigned long);
805                snprintf(tempbuf, sizeof(tempbuf), "%lu", ulval);
806             }
807             else if ((ch == 'l') && (*src == 'u'))
808             {
809                unsigned long long lluval = va_arg(ap, unsigned long long);
810                snprintf(tempbuf, sizeof(tempbuf), "%llu", lluval);
811                src++;
812             }
813             else
814             {
815                snprintf(tempbuf, sizeof(tempbuf), "Bad format string: \"%s\"", fmt);
816                loglevel = LOG_LEVEL_FATAL;
817             }
818             break;
819          case 'c':
820             /*
821              * Note that char paramaters are converted to int, so we need to
822              * pass "int" to va_arg.  (See K&R, 2nd ed, section A7.3.2, page 202)
823              */
824             tempbuf[0] = (char) va_arg(ap, int);
825             tempbuf[1] = '\0';
826             break;
827          case 's':
828             format_string = va_arg(ap, char *);
829             if (format_string == NULL)
830             {
831                format_string = "[null]";
832             }
833             break;
834          case 'N':
835             /*
836              * Non-standard: Print a counted unterminated string,
837              * replacing unprintable bytes with their hex value.
838              * Takes 2 parameters: int length, const char * string.
839              */
840             ival = va_arg(ap, int);
841             assert(ival >= 0);
842             sval = va_arg(ap, char *);
843             assert(sval != NULL);
844
845             while ((ival-- > 0) && (length < log_buffer_size - 6))
846             {
847                if (isprint((int)*sval) && (*sval != '\\'))
848                {
849                   outbuf[length++] = *sval;
850                   outbuf[length] = '\0';
851                }
852                else
853                {
854                   int ret = snprintf(outbuf + length,
855                      log_buffer_size - length - 2, "\\x%.2x", (unsigned char)*sval);
856                   assert(ret == 4);
857                   length += 4;
858                }
859                sval++;
860             }
861             /*
862              * XXX: In case of printable characters at the end of
863              *      the %N string, we're not using the whole buffer.
864              */
865             format_string = (length < log_buffer_size - 6) ? "" : "[too long]";
866             break;
867          case 'E':
868             /* Non-standard: Print error code from errno */
869 #ifdef _WIN32
870             ival = WSAGetLastError();
871             format_string = w32_socket_strerr(ival, tempbuf);
872 #elif __OS2__
873             ival = sock_errno();
874             if (ival != 0)
875             {
876                format_string = os2_socket_strerr(ival, tempbuf);
877             }
878             else
879             {
880                ival = errno;
881                format_string = strerror(ival);
882             }
883 #else /* ifndef _WIN32 */
884             ival = errno;
885 #ifdef HAVE_STRERROR
886             format_string = strerror(ival);
887 #else /* ifndef HAVE_STRERROR */
888             format_string = NULL;
889 #endif /* ndef HAVE_STRERROR */
890             if (sval == NULL)
891             {
892                snprintf(tempbuf, sizeof(tempbuf), "(errno = %d)", ival);
893             }
894 #endif /* ndef _WIN32 */
895             break;
896          case 'T':
897             /* Non-standard: Print a Common Log File timestamp */
898             get_clf_timestamp(tempbuf, sizeof(tempbuf));
899             break;
900          default:
901             snprintf(tempbuf, sizeof(tempbuf), "Bad format string: \"%s\"", fmt);
902             loglevel = LOG_LEVEL_FATAL;
903             break;
904       }
905
906       assert(length < log_buffer_size);
907       length += strlcpy(outbuf + length, format_string, log_buffer_size - length);
908
909       if (length >= log_buffer_size-2)
910       {
911          static const char warning[] = "... [too long, truncated]";
912
913          length = log_buffer_size - sizeof(warning) - 1;
914          length += strlcpy(outbuf + length, warning, log_buffer_size - length);
915          assert(length < log_buffer_size);
916
917          break;
918       }
919    }
920
921    /* done with var. args */
922    va_end(ap);
923
924    assert(length < log_buffer_size);
925    length += strlcpy(outbuf + length, "\n", log_buffer_size - length);
926
927    /* Some sanity checks */
928    if ((length >= log_buffer_size)
929     || (outbuf[log_buffer_size-1] != '\0')
930     || (outbuf[log_buffer_size] != '\0')
931       )
932    {
933       /* Repeat as assertions */
934       assert(length < log_buffer_size);
935       assert(outbuf[log_buffer_size-1] == '\0');
936       /*
937        * outbuf's real size is log_buffer_size+1,
938        * so while this looks like an off-by-one,
939        * we're only checking our paranoia byte.
940        */
941       assert(outbuf[log_buffer_size] == '\0');
942
943       snprintf(outbuf, log_buffer_size,
944          "%s %08lx Fatal error: log_error()'s sanity checks failed."
945          "length: %d. Exiting.",
946          timestamp, thread_id, (int)length);
947       loglevel = LOG_LEVEL_FATAL;
948    }
949
950 #ifndef _WIN32
951    /*
952     * On Windows this is acceptable in case
953     * we are logging to the GUI window only.
954     */
955    assert(NULL != logfp);
956 #endif
957
958    if (loglevel == LOG_LEVEL_FATAL)
959    {
960       fatal_error(outbuf_save);
961       /* Never get here */
962    }
963    if (logfp != NULL)
964    {
965       fputs(outbuf_save, logfp);
966    }
967
968 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
969    /* Write to display */
970    LogPutString(outbuf_save);
971 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
972
973    unlock_logfile();
974
975 }
976
977
978 /*********************************************************************
979  *
980  * Function    :  jb_err_to_string
981  *
982  * Description :  Translates JB_ERR_FOO codes into strings.
983  *
984  *                XXX: the type of error codes is jb_err
985  *                but the typedef'inition is currently not
986  *                visible to all files that include errlog.h.
987  *
988  * Parameters  :
989  *          1  :  jb_error = a valid jb_err code
990  *
991  * Returns     :  A string with the jb_err translation
992  *
993  *********************************************************************/
994 const char *jb_err_to_string(int jb_error)
995 {
996    switch (jb_error)
997    {
998       case JB_ERR_OK:
999          return "Success, no error";
1000       case JB_ERR_MEMORY:
1001          return "Out of memory";
1002       case JB_ERR_CGI_PARAMS:
1003          return "Missing or corrupt CGI parameters";
1004       case JB_ERR_FILE:
1005          return "Error opening, reading or writing a file";
1006       case JB_ERR_PARSE:
1007          return "Parse error";
1008       case JB_ERR_MODIFIED:
1009          return "File has been modified outside of the CGI actions editor.";
1010       case JB_ERR_COMPRESS:
1011          return "(De)compression failure";
1012    }
1013    assert(0);
1014    return "Internal error";
1015 }
1016
1017 #ifdef _WIN32
1018 /*********************************************************************
1019  *
1020  * Function    :  w32_socket_strerr
1021  *
1022  * Description :  Translate the return value from WSAGetLastError()
1023  *                into a string.
1024  *
1025  * Parameters  :
1026  *          1  :  errcode = The return value from WSAGetLastError().
1027  *          2  :  tmp_buf = A temporary buffer that might be used to
1028  *                          store the string.
1029  *
1030  * Returns     :  String representing the error code.  This may be
1031  *                a global string constant or a string stored in
1032  *                tmp_buf.
1033  *
1034  *********************************************************************/
1035 static char *w32_socket_strerr(int errcode, char *tmp_buf)
1036 {
1037 #define TEXT_FOR_ERROR(code,text) \
1038    if (errcode == code)           \
1039    {                              \
1040       return #code " - " text;    \
1041    }
1042
1043    TEXT_FOR_ERROR(WSAEACCES, "Permission denied")
1044    TEXT_FOR_ERROR(WSAEADDRINUSE, "Address already in use.")
1045    TEXT_FOR_ERROR(WSAEADDRNOTAVAIL, "Cannot assign requested address.");
1046    TEXT_FOR_ERROR(WSAEAFNOSUPPORT, "Address family not supported by protocol family.");
1047    TEXT_FOR_ERROR(WSAEALREADY, "Operation already in progress.");
1048    TEXT_FOR_ERROR(WSAECONNABORTED, "Software caused connection abort.");
1049    TEXT_FOR_ERROR(WSAECONNREFUSED, "Connection refused.");
1050    TEXT_FOR_ERROR(WSAECONNRESET, "Connection reset by peer.");
1051    TEXT_FOR_ERROR(WSAEDESTADDRREQ, "Destination address required.");
1052    TEXT_FOR_ERROR(WSAEFAULT, "Bad address.");
1053    TEXT_FOR_ERROR(WSAEHOSTDOWN, "Host is down.");
1054    TEXT_FOR_ERROR(WSAEHOSTUNREACH, "No route to host.");
1055    TEXT_FOR_ERROR(WSAEINPROGRESS, "Operation now in progress.");
1056    TEXT_FOR_ERROR(WSAEINTR, "Interrupted function call.");
1057    TEXT_FOR_ERROR(WSAEINVAL, "Invalid argument.");
1058    TEXT_FOR_ERROR(WSAEISCONN, "Socket is already connected.");
1059    TEXT_FOR_ERROR(WSAEMFILE, "Too many open sockets.");
1060    TEXT_FOR_ERROR(WSAEMSGSIZE, "Message too long.");
1061    TEXT_FOR_ERROR(WSAENETDOWN, "Network is down.");
1062    TEXT_FOR_ERROR(WSAENETRESET, "Network dropped connection on reset.");
1063    TEXT_FOR_ERROR(WSAENETUNREACH, "Network is unreachable.");
1064    TEXT_FOR_ERROR(WSAENOBUFS, "No buffer space available.");
1065    TEXT_FOR_ERROR(WSAENOPROTOOPT, "Bad protocol option.");
1066    TEXT_FOR_ERROR(WSAENOTCONN, "Socket is not connected.");
1067    TEXT_FOR_ERROR(WSAENOTSOCK, "Socket operation on non-socket.");
1068    TEXT_FOR_ERROR(WSAEOPNOTSUPP, "Operation not supported.");
1069    TEXT_FOR_ERROR(WSAEPFNOSUPPORT, "Protocol family not supported.");
1070    TEXT_FOR_ERROR(WSAEPROCLIM, "Too many processes.");
1071    TEXT_FOR_ERROR(WSAEPROTONOSUPPORT, "Protocol not supported.");
1072    TEXT_FOR_ERROR(WSAEPROTOTYPE, "Protocol wrong type for socket.");
1073    TEXT_FOR_ERROR(WSAESHUTDOWN, "Cannot send after socket shutdown.");
1074    TEXT_FOR_ERROR(WSAESOCKTNOSUPPORT, "Socket type not supported.");
1075    TEXT_FOR_ERROR(WSAETIMEDOUT, "Connection timed out.");
1076    TEXT_FOR_ERROR(WSAEWOULDBLOCK, "Resource temporarily unavailable.");
1077    TEXT_FOR_ERROR(WSAHOST_NOT_FOUND, "Host not found.");
1078    TEXT_FOR_ERROR(WSANOTINITIALISED, "Successful WSAStartup not yet performed.");
1079    TEXT_FOR_ERROR(WSANO_DATA, "Valid name, no data record of requested type.");
1080    TEXT_FOR_ERROR(WSANO_RECOVERY, "This is a non-recoverable error.");
1081    TEXT_FOR_ERROR(WSASYSNOTREADY, "Network subsystem is unavailable.");
1082    TEXT_FOR_ERROR(WSATRY_AGAIN, "Non-authoritative host not found.");
1083    TEXT_FOR_ERROR(WSAVERNOTSUPPORTED, "WINSOCK.DLL version out of range.");
1084    TEXT_FOR_ERROR(WSAEDISCON, "Graceful shutdown in progress.");
1085    /*
1086     * The following error codes are documented in the Microsoft WinSock
1087     * reference guide, but don't actually exist.
1088     *
1089     * TEXT_FOR_ERROR(WSA_INVALID_HANDLE, "Specified event object handle is invalid.");
1090     * TEXT_FOR_ERROR(WSA_INVALID_PARAMETER, "One or more parameters are invalid.");
1091     * TEXT_FOR_ERROR(WSAINVALIDPROCTABLE, "Invalid procedure table from service provider.");
1092     * TEXT_FOR_ERROR(WSAINVALIDPROVIDER, "Invalid service provider version number.");
1093     * TEXT_FOR_ERROR(WSA_IO_PENDING, "Overlapped operations will complete later.");
1094     * TEXT_FOR_ERROR(WSA_IO_INCOMPLETE, "Overlapped I/O event object not in signaled state.");
1095     * TEXT_FOR_ERROR(WSA_NOT_ENOUGH_MEMORY, "Insufficient memory available.");
1096     * TEXT_FOR_ERROR(WSAPROVIDERFAILEDINIT, "Unable to initialize a service provider.");
1097     * TEXT_FOR_ERROR(WSASYSCALLFAILURE, "System call failure.");
1098     * TEXT_FOR_ERROR(WSA_OPERATION_ABORTED, "Overlapped operation aborted.");
1099     */
1100
1101    sprintf(tmp_buf, "(error number %d)", errcode);
1102    return tmp_buf;
1103 }
1104 #endif /* def _WIN32 */
1105
1106
1107 #ifdef __OS2__
1108 /*********************************************************************
1109  *
1110  * Function    :  os2_socket_strerr
1111  *
1112  * Description :  Translate the return value from sock_errno()
1113  *                into a string.
1114  *
1115  * Parameters  :
1116  *          1  :  errcode = The return value from sock_errno().
1117  *          2  :  tmp_buf = A temporary buffer that might be used to
1118  *                          store the string.
1119  *
1120  * Returns     :  String representing the error code.  This may be
1121  *                a global string constant or a string stored in
1122  *                tmp_buf.
1123  *
1124  *********************************************************************/
1125 static char *os2_socket_strerr(int errcode, char *tmp_buf)
1126 {
1127 #define TEXT_FOR_ERROR(code,text) \
1128    if (errcode == code)           \
1129    {                              \
1130       return #code " - " text;    \
1131    }
1132
1133    TEXT_FOR_ERROR(SOCEPERM          , "Not owner.")
1134    TEXT_FOR_ERROR(SOCESRCH          , "No such process.")
1135    TEXT_FOR_ERROR(SOCEINTR          , "Interrupted system call.")
1136    TEXT_FOR_ERROR(SOCENXIO          , "No such device or address.")
1137    TEXT_FOR_ERROR(SOCEBADF          , "Bad file number.")
1138    TEXT_FOR_ERROR(SOCEACCES         , "Permission denied.")
1139    TEXT_FOR_ERROR(SOCEFAULT         , "Bad address.")
1140    TEXT_FOR_ERROR(SOCEINVAL         , "Invalid argument.")
1141    TEXT_FOR_ERROR(SOCEMFILE         , "Too many open files.")
1142    TEXT_FOR_ERROR(SOCEPIPE          , "Broken pipe.")
1143    TEXT_FOR_ERROR(SOCEWOULDBLOCK    , "Operation would block.")
1144    TEXT_FOR_ERROR(SOCEINPROGRESS    , "Operation now in progress.")
1145    TEXT_FOR_ERROR(SOCEALREADY       , "Operation already in progress.")
1146    TEXT_FOR_ERROR(SOCENOTSOCK       , "Socket operation on non-socket.")
1147    TEXT_FOR_ERROR(SOCEDESTADDRREQ   , "Destination address required.")
1148    TEXT_FOR_ERROR(SOCEMSGSIZE       , "Message too long.")
1149    TEXT_FOR_ERROR(SOCEPROTOTYPE     , "Protocol wrong type for socket.")
1150    TEXT_FOR_ERROR(SOCENOPROTOOPT    , "Protocol not available.")
1151    TEXT_FOR_ERROR(SOCEPROTONOSUPPORT, "Protocol not supported.")
1152    TEXT_FOR_ERROR(SOCESOCKTNOSUPPORT, "Socket type not supported.")
1153    TEXT_FOR_ERROR(SOCEOPNOTSUPP     , "Operation not supported.")
1154    TEXT_FOR_ERROR(SOCEPFNOSUPPORT   , "Protocol family not supported.")
1155    TEXT_FOR_ERROR(SOCEAFNOSUPPORT   , "Address family not supported by protocol family.")
1156    TEXT_FOR_ERROR(SOCEADDRINUSE     , "Address already in use.")
1157    TEXT_FOR_ERROR(SOCEADDRNOTAVAIL  , "Can't assign requested address.")
1158    TEXT_FOR_ERROR(SOCENETDOWN       , "Network is down.")
1159    TEXT_FOR_ERROR(SOCENETUNREACH    , "Network is unreachable.")
1160    TEXT_FOR_ERROR(SOCENETRESET      , "Network dropped connection on reset.")
1161    TEXT_FOR_ERROR(SOCECONNABORTED   , "Software caused connection abort.")
1162    TEXT_FOR_ERROR(SOCECONNRESET     , "Connection reset by peer.")
1163    TEXT_FOR_ERROR(SOCENOBUFS        , "No buffer space available.")
1164    TEXT_FOR_ERROR(SOCEISCONN        , "Socket is already connected.")
1165    TEXT_FOR_ERROR(SOCENOTCONN       , "Socket is not connected.")
1166    TEXT_FOR_ERROR(SOCESHUTDOWN      , "Can't send after socket shutdown.")
1167    TEXT_FOR_ERROR(SOCETOOMANYREFS   , "Too many references: can't splice.")
1168    TEXT_FOR_ERROR(SOCETIMEDOUT      , "Operation timed out.")
1169    TEXT_FOR_ERROR(SOCECONNREFUSED   , "Connection refused.")
1170    TEXT_FOR_ERROR(SOCELOOP          , "Too many levels of symbolic links.")
1171    TEXT_FOR_ERROR(SOCENAMETOOLONG   , "File name too long.")
1172    TEXT_FOR_ERROR(SOCEHOSTDOWN      , "Host is down.")
1173    TEXT_FOR_ERROR(SOCEHOSTUNREACH   , "No route to host.")
1174    TEXT_FOR_ERROR(SOCENOTEMPTY      , "Directory not empty.")
1175    TEXT_FOR_ERROR(SOCEOS2ERR        , "OS/2 Error.")
1176
1177    sprintf(tmp_buf, "(error number %d)", errcode);
1178    return tmp_buf;
1179 }
1180 #endif /* def __OS2__ */
1181
1182
1183 /*
1184   Local Variables:
1185   tab-width: 3
1186   end:
1187 */