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