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