Debian: Compile --with-mbedtls to allow https-inspection.
[privoxy.git] / errlog.c
1 /*********************************************************************
2  *
3  * File        :  $Source: /cvsroot/ijbswa/current/errlog.c,v $
4  *
5  * Purpose     :  Log errors to a designated destination in an elegant,
6  *                printf-like fashion.
7  *
8  * Copyright   :  Written by and Copyright (C) 2001-2014 the
9  *                Privoxy team. https://www.privoxy.org/
10  *
11  *                Based on the Internet Junkbuster originally written
12  *                by and Copyright (C) 1997 Anonymous Coders and
13  *                Junkbusters Corporation.  http://www.junkbusters.com
14  *
15  *                This program is free software; you can redistribute it
16  *                and/or modify it under the terms of the GNU General
17  *                Public License as published by the Free Software
18  *                Foundation; either version 2 of the License, or (at
19  *                your option) any later version.
20  *
21  *                This program is distributed in the hope that it will
22  *                be useful, but WITHOUT ANY WARRANTY; without even the
23  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
24  *                PARTICULAR PURPOSE.  See the GNU General Public
25  *                License for more details.
26  *
27  *                The GNU General Public License should be included with
28  *                this file.  If not, you can view it at
29  *                http://www.gnu.org/copyleft/gpl.html
30  *                or write to the Free Software Foundation, Inc., 59
31  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
32  *
33  *********************************************************************/
34
35
36 #include <stdlib.h>
37 #include <stdio.h>
38 #include <stdarg.h>
39 #include <string.h>
40 #include <ctype.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 #ifdef FEATURE_EXTERNAL_FILTERS
78 #include "jbsockets.h"
79 #endif
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 (logfp != NULL)
149    {
150       fputs(error_message, logfp);
151    }
152
153 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
154    {
155       /* Skip timestamp and thread id for the message box. */
156       const char *box_message = strstr(error_message, "Fatal error");
157       if (NULL == box_message)
158       {
159          /* Shouldn't happen but ... */
160          box_message = error_message;
161       }
162       MessageBox(g_hwndLogFrame, box_message, "Privoxy Error",
163          MB_OK | MB_ICONERROR | MB_TASKMODAL | MB_SETFOREGROUND | MB_TOPMOST);
164
165       /* Cleanup - remove taskbar icon etc. */
166       TermLogWindow();
167    }
168 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
169
170 #if defined(unix)
171    if (pidfile)
172    {
173       unlink(pidfile);
174    }
175 #endif /* unix */
176
177    exit(1);
178 }
179
180
181 /*********************************************************************
182  *
183  * Function    :  show_version
184  *
185  * Description :  Logs the Privoxy version and the program name.
186  *
187  * Parameters  :
188  *          1  :  prog_name = The program name.
189  *
190  * Returns     :  Nothing.
191  *
192  *********************************************************************/
193 void show_version(const char *prog_name)
194 {
195    log_error(LOG_LEVEL_INFO, "Privoxy version " VERSION);
196    if (prog_name != NULL)
197    {
198       log_error(LOG_LEVEL_INFO, "Program name: %s", prog_name);
199    }
200 }
201
202
203 /*********************************************************************
204  *
205  * Function    :  init_log_module
206  *
207  * Description :  Initializes the logging module to log to stderr.
208  *                Can only be called while stderr hasn't been closed
209  *                yet and is only supposed to be called once.
210  *
211  * Parameters  :
212  *          1  :  prog_name = The program name.
213  *
214  * Returns     :  Nothing.
215  *
216  *********************************************************************/
217 void init_log_module(void)
218 {
219    lock_logfile();
220    logfp = stderr;
221    unlock_logfile();
222    set_debug_level(debug);
223 }
224
225
226 /*********************************************************************
227  *
228  * Function    :  set_debug_level
229  *
230  * Description :  Sets the debug level to the provided value
231  *                plus LOG_LEVEL_MINIMUM.
232  *
233  *                XXX: we should only use the LOG_LEVEL_MINIMUM
234  *                until the first time the configuration file has
235  *                been parsed.
236  *
237  * Parameters  :  1: debug_level = The debug level to set.
238  *
239  * Returns     :  Nothing.
240  *
241  *********************************************************************/
242 void set_debug_level(int debug_level)
243 {
244 #ifdef FUZZ
245    if (LOG_LEVEL_STFU == debug_level)
246    {
247       debug = LOG_LEVEL_STFU;
248    }
249    if (LOG_LEVEL_STFU == debug)
250    {
251       return;
252    }
253 #endif
254
255    debug = debug_level | LOG_LEVEL_MINIMUM;
256 }
257
258
259 /*********************************************************************
260  *
261  * Function    :  debug_level_is_enabled
262  *
263  * Description :  Checks if a certain debug level is enabled.
264  *
265  * Parameters  :  1: debug_level = The debug level to check.
266  *
267  * Returns     :  Nothing.
268  *
269  *********************************************************************/
270 int debug_level_is_enabled(int debug_level)
271 {
272    return (0 != (debug & debug_level));
273 }
274
275
276 /*********************************************************************
277  *
278  * Function    :  disable_logging
279  *
280  * Description :  Disables logging.
281  *
282  * Parameters  :  None.
283  *
284  * Returns     :  Nothing.
285  *
286  *********************************************************************/
287 void disable_logging(void)
288 {
289    if (logfp != NULL)
290    {
291       log_error(LOG_LEVEL_INFO,
292          "No logfile configured. Please enable it before reporting any problems.");
293       lock_logfile();
294       fclose(logfp);
295       logfp = NULL;
296       unlock_logfile();
297    }
298 }
299
300
301 /*********************************************************************
302  *
303  * Function    :  init_error_log
304  *
305  * Description :  Initializes the logging module to log to a file.
306  *
307  *                XXX: should be renamed.
308  *
309  * Parameters  :
310  *          1  :  prog_name  = The program name.
311  *          2  :  logfname   = The logfile to (re)open.
312  *
313  * Returns     :  N/A
314  *
315  *********************************************************************/
316 void init_error_log(const char *prog_name, const char *logfname)
317 {
318    FILE *fp;
319
320    assert(NULL != logfname);
321
322    lock_loginit();
323
324    if ((logfp != NULL) && (logfp != stderr))
325    {
326       log_error(LOG_LEVEL_INFO, "(Re-)Opening logfile \'%s\'", logfname);
327    }
328
329    /* set the designated log file */
330    fp = fopen(logfname, "a");
331    if ((NULL == fp) && (logfp != NULL))
332    {
333       /*
334        * Some platforms (like OS/2) don't allow us to open
335        * the same file twice, therefore we give it another
336        * shot after closing the old file descriptor first.
337        *
338        * We don't do it right away because it prevents us
339        * from logging the "can't open logfile" message to
340        * the old logfile.
341        *
342        * XXX: this is a lame workaround and once the next
343        * release is out we should stop bothering reopening
344        * the logfile unless we have to.
345        *
346        * Currently we reopen it every time the config file
347        * has been reloaded, but actually we only have to
348        * reopen it if the file name changed or if the
349        * configuration reload was caused by a SIGHUP.
350        */
351       log_error(LOG_LEVEL_INFO, "Failed to reopen logfile: \'%s\'. "
352          "Retrying after closing the old file descriptor first. If that "
353          "doesn't work, Privoxy will exit without being able to log a message.",
354          logfname);
355       lock_logfile();
356       fclose(logfp);
357       logfp = NULL;
358       unlock_logfile();
359       fp = fopen(logfname, "a");
360    }
361
362    if (NULL == fp)
363    {
364       log_error(LOG_LEVEL_FATAL, "init_error_log(): can't open logfile: \'%s\'", logfname);
365    }
366
367 #ifdef FEATURE_EXTERNAL_FILTERS
368    mark_socket_for_close_on_execute(3);
369 #endif
370
371    /* set logging to be completely unbuffered */
372    setbuf(fp, NULL);
373
374    lock_logfile();
375    if (logfp != NULL)
376    {
377       fclose(logfp);
378    }
379 #ifdef unix
380    if (daemon_mode && (logfp == stderr))
381    {
382       if (dup2(1, 2) == -1)
383       {
384          /*
385           * We only use fatal_error() to clear the pid
386           * file and to exit. Given that stderr has just
387           * been closed, the user will not see the error
388           * message.
389           */
390          fatal_error("Failed to reserve fd 2.");
391       }
392    }
393 #endif
394    logfp = fp;
395    unlock_logfile();
396
397    show_version(prog_name);
398
399    unlock_loginit();
400
401 } /* init_error_log */
402
403
404 /*********************************************************************
405  *
406  * Function    :  get_thread_id
407  *
408  * Description :  Returns a number that is different for each thread.
409  *
410  *                XXX: Should be moved elsewhere (miscutil.c?)
411  *
412  * Parameters  :  None
413  *
414  * Returns     :  thread_id
415  *
416  *********************************************************************/
417 static long get_thread_id(void)
418 {
419    long this_thread;
420
421 #ifdef __OS2__
422    PTIB     ptib;
423    APIRET   ulrc; /* XXX: I have no clue what this does */
424 #endif /* __OS2__ */
425
426    /* FIXME get current thread id */
427 #ifdef FEATURE_PTHREAD
428    this_thread = (long)pthread_self();
429 #ifdef __MACH__
430    /*
431     * Mac OSX (and perhaps other Mach instances) doesn't have a unique
432     * value at the lowest order 4 bytes of pthread_self()'s return value, a pthread_t,
433     * so trim the three lowest-order bytes from the value (16^3).
434     */
435    this_thread = this_thread / 4096;
436 #endif /* def __MACH__ */
437 #elif defined(_WIN32)
438    this_thread = GetCurrentThreadId();
439 #elif defined(__OS2__)
440    ulrc = DosGetInfoBlocks(&ptib, NULL);
441    if (ulrc == 0)
442      this_thread = ptib -> tib_ptib2 -> tib2_ultid;
443 #else
444    /* Forking instead of threading. */
445    this_thread = 1;
446 #endif /* def FEATURE_PTHREAD */
447
448    return this_thread;
449 }
450
451
452 /*********************************************************************
453  *
454  * Function    :  get_log_timestamp
455  *
456  * Description :  Generates the time stamp for the log message prefix.
457  *
458  * Parameters  :
459  *          1  :  buffer = Storage buffer
460  *          2  :  buffer_size = Size of storage buffer
461  *
462  * Returns     :  Number of written characters or 0 for error.
463  *
464  *********************************************************************/
465 static inline size_t get_log_timestamp(char *buffer, size_t buffer_size)
466 {
467    size_t length;
468    time_t now;
469    struct tm tm_now;
470    struct timeval tv_now; /* XXX: stupid name */
471    long msecs;
472    int msecs_length = 0;
473
474    gettimeofday(&tv_now, NULL);
475    msecs = tv_now.tv_usec / 1000;
476    now = tv_now.tv_sec;
477
478 #ifdef HAVE_LOCALTIME_R
479    tm_now = *localtime_r(&now, &tm_now);
480 #elif defined(MUTEX_LOCKS_AVAILABLE)
481    privoxy_mutex_lock(&localtime_mutex);
482    tm_now = *localtime(&now);
483    privoxy_mutex_unlock(&localtime_mutex);
484 #else
485    tm_now = *localtime(&now);
486 #endif
487
488    length = strftime(buffer, buffer_size, "%Y-%m-%d %H:%M:%S", &tm_now);
489    if (length > (size_t)0)
490    {
491       msecs_length = snprintf(buffer+length, buffer_size - length, ".%.3ld", msecs);
492    }
493    if (msecs_length > 0)
494    {
495       length += (size_t)msecs_length;
496    }
497    else
498    {
499       length = 0;
500    }
501
502    return length;
503 }
504
505
506 /*********************************************************************
507  *
508  * Function    :  get_clf_timestamp
509  *
510  * Description :  Generates a Common Log Format time string.
511  *
512  * Parameters  :
513  *          1  :  buffer = Storage buffer
514  *          2  :  buffer_size = Size of storage buffer
515  *
516  * Returns     :  Number of written characters or 0 for error.
517  *
518  *********************************************************************/
519 static inline size_t get_clf_timestamp(char *buffer, size_t buffer_size)
520 {
521    /*
522     * Complex because not all OSs have tm_gmtoff or
523     * the %z field in strftime()
524     */
525    time_t now;
526    struct tm *tm_now;
527    struct tm gmt;
528 #ifdef HAVE_LOCALTIME_R
529    struct tm dummy;
530 #endif
531    int days, hrs, mins;
532    size_t length;
533    int tz_length = 0;
534
535    time (&now);
536 #ifdef HAVE_GMTIME_R
537    gmt = *gmtime_r(&now, &gmt);
538 #elif defined(MUTEX_LOCKS_AVAILABLE)
539    privoxy_mutex_lock(&gmtime_mutex);
540    gmt = *gmtime(&now);
541    privoxy_mutex_unlock(&gmtime_mutex);
542 #else
543    gmt = *gmtime(&now);
544 #endif
545 #ifdef HAVE_LOCALTIME_R
546    tm_now = localtime_r(&now, &dummy);
547 #elif defined(MUTEX_LOCKS_AVAILABLE)
548    privoxy_mutex_lock(&localtime_mutex);
549    tm_now = localtime(&now);
550    privoxy_mutex_unlock(&localtime_mutex);
551 #else
552    tm_now = localtime(&now);
553 #endif
554    days = tm_now->tm_yday - gmt.tm_yday;
555    hrs = ((days < -1 ? 24 : 1 < days ? -24 : days * 24) + tm_now->tm_hour - gmt.tm_hour);
556    mins = hrs * 60 + tm_now->tm_min - gmt.tm_min;
557
558    length = strftime(buffer, buffer_size, "%d/%b/%Y:%H:%M:%S ", tm_now);
559
560    if (length > (size_t)0)
561    {
562       tz_length = snprintf(buffer+length, buffer_size-length,
563                      "%+03d%02d", mins / 60, abs(mins) % 60);
564    }
565    if (tz_length > 0)
566    {
567       length += (size_t)tz_length;
568    }
569    else
570    {
571       length = 0;
572    }
573
574    return length;
575 }
576
577
578 /*********************************************************************
579  *
580  * Function    :  get_log_level_string
581  *
582  * Description :  Translates a numerical loglevel into a string.
583  *
584  * Parameters  :
585  *          1  :  loglevel = LOG_LEVEL_FOO
586  *
587  * Returns     :  Log level string.
588  *
589  *********************************************************************/
590 static inline const char *get_log_level_string(int loglevel)
591 {
592    char *log_level_string = NULL;
593
594    assert(0 < loglevel);
595
596    switch (loglevel)
597    {
598       case LOG_LEVEL_ERROR:
599          log_level_string = "Error";
600          break;
601       case LOG_LEVEL_FATAL:
602          log_level_string = "Fatal error";
603          break;
604       case LOG_LEVEL_REQUEST:
605          log_level_string = "Request";
606          break;
607       case LOG_LEVEL_CONNECT:
608          log_level_string = "Connect";
609          break;
610       case LOG_LEVEL_WRITING:
611          log_level_string = "Writing";
612          break;
613       case LOG_LEVEL_RECEIVED:
614          log_level_string = "Received";
615          break;
616       case LOG_LEVEL_HEADER:
617          log_level_string = "Header";
618          break;
619       case LOG_LEVEL_INFO:
620          log_level_string = "Info";
621          break;
622       case LOG_LEVEL_RE_FILTER:
623          log_level_string = "Re-Filter";
624          break;
625 #ifdef FEATURE_FORCE_LOAD
626       case LOG_LEVEL_FORCE:
627          log_level_string = "Force";
628          break;
629 #endif /* def FEATURE_FORCE_LOAD */
630       case LOG_LEVEL_REDIRECTS:
631          log_level_string = "Redirect";
632          break;
633       case LOG_LEVEL_DEANIMATE:
634          log_level_string = "Gif-Deanimate";
635          break;
636       case LOG_LEVEL_CRUNCH:
637          log_level_string = "Crunch";
638          break;
639       case LOG_LEVEL_CGI:
640          log_level_string = "CGI";
641          break;
642       case LOG_LEVEL_ACTIONS:
643          log_level_string = "Actions";
644          break;
645       default:
646          log_level_string = "Unknown log level";
647          break;
648    }
649    assert(NULL != log_level_string);
650
651    return log_level_string;
652 }
653
654
655 #define LOG_BUFFER_SIZE BUFFER_SIZE
656 /*********************************************************************
657  *
658  * Function    :  log_error
659  *
660  * Description :  This is the error-reporting and logging function.
661  *
662  * Parameters  :
663  *          1  :  loglevel  = the type of message to be logged
664  *          2  :  fmt       = the main string we want logged, printf-like
665  *          3  :  ...       = arguments to be inserted in fmt (printf-like).
666  *
667  * Returns     :  N/A
668  *
669  *********************************************************************/
670 void log_error(int loglevel, const char *fmt, ...)
671 {
672    va_list ap;
673    char outbuf[LOG_BUFFER_SIZE+1];
674    char tempbuf[LOG_BUFFER_SIZE];
675    size_t length = 0;
676    const char * src = fmt;
677    long thread_id;
678    char timestamp[30];
679    const size_t log_buffer_size = LOG_BUFFER_SIZE;
680
681 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
682    /*
683     * Irrespective of debug setting, a GET/POST/CONNECT makes
684     * the taskbar icon animate.  (There is an option to disable
685     * this but checking that is handled inside LogShowActivity()).
686     */
687    if ((loglevel == LOG_LEVEL_REQUEST) || (loglevel == LOG_LEVEL_CRUNCH))
688    {
689       LogShowActivity();
690    }
691 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
692
693    /*
694     * verify that the loglevel applies to current
695     * settings and that logging is enabled.
696     * Bail out otherwise.
697     */
698    if ((0 == (loglevel & debug))
699 #ifndef _WIN32
700       || (logfp == NULL)
701 #endif
702       )
703    {
704 #ifdef FUZZ
705       if (debug == LOG_LEVEL_STFU)
706       {
707          return;
708       }
709 #endif
710       if (loglevel == LOG_LEVEL_FATAL)
711       {
712          fatal_error("Fatal error. You're not supposed to"
713             "see this message. Please file a bug report.");
714       }
715       return;
716    }
717
718    thread_id = get_thread_id();
719    get_log_timestamp(timestamp, sizeof(timestamp));
720
721    /*
722     * Memsetting the whole buffer to zero (in theory)
723     * makes things easier later on.
724     */
725    memset(outbuf, 0, sizeof(outbuf));
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 parameters 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    lock_logfile();
940
941    if (loglevel == LOG_LEVEL_FATAL)
942    {
943       fatal_error(outbuf);
944       /* Never get here */
945    }
946    if (logfp != NULL)
947    {
948       fputs(outbuf, logfp);
949    }
950
951 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
952    /* Write to display */
953    LogPutString(outbuf);
954 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
955
956    unlock_logfile();
957
958 }
959
960
961 /*********************************************************************
962  *
963  * Function    :  jb_err_to_string
964  *
965  * Description :  Translates JB_ERR_FOO codes into strings.
966  *
967  * Parameters  :
968  *          1  :  jb_error = a valid jb_err code
969  *
970  * Returns     :  A string with the jb_err translation
971  *
972  *********************************************************************/
973 const char *jb_err_to_string(jb_err jb_error)
974 {
975    switch (jb_error)
976    {
977       case JB_ERR_OK:
978          return "Success, no error";
979       case JB_ERR_MEMORY:
980          return "Out of memory";
981       case JB_ERR_CGI_PARAMS:
982          return "Missing or corrupt CGI parameters";
983       case JB_ERR_FILE:
984          return "Error opening, reading or writing a file";
985       case JB_ERR_PARSE:
986          return "Parse error";
987       case JB_ERR_MODIFIED:
988          return "File has been modified outside of the CGI actions editor.";
989       case JB_ERR_COMPRESS:
990          return "(De)compression failure";
991    }
992    assert(0);
993    return "Internal error";
994 }
995
996 #ifdef _WIN32
997 /*********************************************************************
998  *
999  * Function    :  w32_socket_strerr
1000  *
1001  * Description :  Translate the return value from WSAGetLastError()
1002  *                into a string.
1003  *
1004  * Parameters  :
1005  *          1  :  errcode = The return value from WSAGetLastError().
1006  *          2  :  tmp_buf = A temporary buffer that might be used to
1007  *                          store the string.
1008  *
1009  * Returns     :  String representing the error code.  This may be
1010  *                a global string constant or a string stored in
1011  *                tmp_buf.
1012  *
1013  *********************************************************************/
1014 static char *w32_socket_strerr(int errcode, char *tmp_buf)
1015 {
1016 #define TEXT_FOR_ERROR(code,text) \
1017    if (errcode == code)           \
1018    {                              \
1019       return #code " - " text;    \
1020    }
1021
1022    TEXT_FOR_ERROR(WSAEACCES, "Permission denied")
1023    TEXT_FOR_ERROR(WSAEADDRINUSE, "Address already in use.")
1024    TEXT_FOR_ERROR(WSAEADDRNOTAVAIL, "Cannot assign requested address.");
1025    TEXT_FOR_ERROR(WSAEAFNOSUPPORT, "Address family not supported by protocol family.");
1026    TEXT_FOR_ERROR(WSAEALREADY, "Operation already in progress.");
1027    TEXT_FOR_ERROR(WSAECONNABORTED, "Software caused connection abort.");
1028    TEXT_FOR_ERROR(WSAECONNREFUSED, "Connection refused.");
1029    TEXT_FOR_ERROR(WSAECONNRESET, "Connection reset by peer.");
1030    TEXT_FOR_ERROR(WSAEDESTADDRREQ, "Destination address required.");
1031    TEXT_FOR_ERROR(WSAEFAULT, "Bad address.");
1032    TEXT_FOR_ERROR(WSAEHOSTDOWN, "Host is down.");
1033    TEXT_FOR_ERROR(WSAEHOSTUNREACH, "No route to host.");
1034    TEXT_FOR_ERROR(WSAEINPROGRESS, "Operation now in progress.");
1035    TEXT_FOR_ERROR(WSAEINTR, "Interrupted function call.");
1036    TEXT_FOR_ERROR(WSAEINVAL, "Invalid argument.");
1037    TEXT_FOR_ERROR(WSAEISCONN, "Socket is already connected.");
1038    TEXT_FOR_ERROR(WSAEMFILE, "Too many open sockets.");
1039    TEXT_FOR_ERROR(WSAEMSGSIZE, "Message too long.");
1040    TEXT_FOR_ERROR(WSAENETDOWN, "Network is down.");
1041    TEXT_FOR_ERROR(WSAENETRESET, "Network dropped connection on reset.");
1042    TEXT_FOR_ERROR(WSAENETUNREACH, "Network is unreachable.");
1043    TEXT_FOR_ERROR(WSAENOBUFS, "No buffer space available.");
1044    TEXT_FOR_ERROR(WSAENOPROTOOPT, "Bad protocol option.");
1045    TEXT_FOR_ERROR(WSAENOTCONN, "Socket is not connected.");
1046    TEXT_FOR_ERROR(WSAENOTSOCK, "Socket operation on non-socket.");
1047    TEXT_FOR_ERROR(WSAEOPNOTSUPP, "Operation not supported.");
1048    TEXT_FOR_ERROR(WSAEPFNOSUPPORT, "Protocol family not supported.");
1049    TEXT_FOR_ERROR(WSAEPROCLIM, "Too many processes.");
1050    TEXT_FOR_ERROR(WSAEPROTONOSUPPORT, "Protocol not supported.");
1051    TEXT_FOR_ERROR(WSAEPROTOTYPE, "Protocol wrong type for socket.");
1052    TEXT_FOR_ERROR(WSAESHUTDOWN, "Cannot send after socket shutdown.");
1053    TEXT_FOR_ERROR(WSAESOCKTNOSUPPORT, "Socket type not supported.");
1054    TEXT_FOR_ERROR(WSAETIMEDOUT, "Connection timed out.");
1055    TEXT_FOR_ERROR(WSAEWOULDBLOCK, "Resource temporarily unavailable.");
1056    TEXT_FOR_ERROR(WSAHOST_NOT_FOUND, "Host not found.");
1057    TEXT_FOR_ERROR(WSANOTINITIALISED, "Successful WSAStartup not yet performed.");
1058    TEXT_FOR_ERROR(WSANO_DATA, "Valid name, no data record of requested type.");
1059    TEXT_FOR_ERROR(WSANO_RECOVERY, "This is a non-recoverable error.");
1060    TEXT_FOR_ERROR(WSASYSNOTREADY, "Network subsystem is unavailable.");
1061    TEXT_FOR_ERROR(WSATRY_AGAIN, "Non-authoritative host not found.");
1062    TEXT_FOR_ERROR(WSAVERNOTSUPPORTED, "WINSOCK.DLL version out of range.");
1063    TEXT_FOR_ERROR(WSAEDISCON, "Graceful shutdown in progress.");
1064    /*
1065     * The following error codes are documented in the Microsoft WinSock
1066     * reference guide, but don't actually exist.
1067     *
1068     * TEXT_FOR_ERROR(WSA_INVALID_HANDLE, "Specified event object handle is invalid.");
1069     * TEXT_FOR_ERROR(WSA_INVALID_PARAMETER, "One or more parameters are invalid.");
1070     * TEXT_FOR_ERROR(WSAINVALIDPROCTABLE, "Invalid procedure table from service provider.");
1071     * TEXT_FOR_ERROR(WSAINVALIDPROVIDER, "Invalid service provider version number.");
1072     * TEXT_FOR_ERROR(WSA_IO_PENDING, "Overlapped operations will complete later.");
1073     * TEXT_FOR_ERROR(WSA_IO_INCOMPLETE, "Overlapped I/O event object not in signaled state.");
1074     * TEXT_FOR_ERROR(WSA_NOT_ENOUGH_MEMORY, "Insufficient memory available.");
1075     * TEXT_FOR_ERROR(WSAPROVIDERFAILEDINIT, "Unable to initialize a service provider.");
1076     * TEXT_FOR_ERROR(WSASYSCALLFAILURE, "System call failure.");
1077     * TEXT_FOR_ERROR(WSA_OPERATION_ABORTED, "Overlapped operation aborted.");
1078     */
1079
1080    sprintf(tmp_buf, "(error number %d)", errcode);
1081    return tmp_buf;
1082 }
1083 #endif /* def _WIN32 */
1084
1085
1086 #ifdef __OS2__
1087 /*********************************************************************
1088  *
1089  * Function    :  os2_socket_strerr
1090  *
1091  * Description :  Translate the return value from sock_errno()
1092  *                into a string.
1093  *
1094  * Parameters  :
1095  *          1  :  errcode = The return value from sock_errno().
1096  *          2  :  tmp_buf = A temporary buffer that might be used to
1097  *                          store the string.
1098  *
1099  * Returns     :  String representing the error code.  This may be
1100  *                a global string constant or a string stored in
1101  *                tmp_buf.
1102  *
1103  *********************************************************************/
1104 static char *os2_socket_strerr(int errcode, char *tmp_buf)
1105 {
1106 #define TEXT_FOR_ERROR(code,text) \
1107    if (errcode == code)           \
1108    {                              \
1109       return #code " - " text;    \
1110    }
1111
1112    TEXT_FOR_ERROR(SOCEPERM          , "Not owner.")
1113    TEXT_FOR_ERROR(SOCESRCH          , "No such process.")
1114    TEXT_FOR_ERROR(SOCEINTR          , "Interrupted system call.")
1115    TEXT_FOR_ERROR(SOCENXIO          , "No such device or address.")
1116    TEXT_FOR_ERROR(SOCEBADF          , "Bad file number.")
1117    TEXT_FOR_ERROR(SOCEACCES         , "Permission denied.")
1118    TEXT_FOR_ERROR(SOCEFAULT         , "Bad address.")
1119    TEXT_FOR_ERROR(SOCEINVAL         , "Invalid argument.")
1120    TEXT_FOR_ERROR(SOCEMFILE         , "Too many open files.")
1121    TEXT_FOR_ERROR(SOCEPIPE          , "Broken pipe.")
1122    TEXT_FOR_ERROR(SOCEWOULDBLOCK    , "Operation would block.")
1123    TEXT_FOR_ERROR(SOCEINPROGRESS    , "Operation now in progress.")
1124    TEXT_FOR_ERROR(SOCEALREADY       , "Operation already in progress.")
1125    TEXT_FOR_ERROR(SOCENOTSOCK       , "Socket operation on non-socket.")
1126    TEXT_FOR_ERROR(SOCEDESTADDRREQ   , "Destination address required.")
1127    TEXT_FOR_ERROR(SOCEMSGSIZE       , "Message too long.")
1128    TEXT_FOR_ERROR(SOCEPROTOTYPE     , "Protocol wrong type for socket.")
1129    TEXT_FOR_ERROR(SOCENOPROTOOPT    , "Protocol not available.")
1130    TEXT_FOR_ERROR(SOCEPROTONOSUPPORT, "Protocol not supported.")
1131    TEXT_FOR_ERROR(SOCESOCKTNOSUPPORT, "Socket type not supported.")
1132    TEXT_FOR_ERROR(SOCEOPNOTSUPP     , "Operation not supported.")
1133    TEXT_FOR_ERROR(SOCEPFNOSUPPORT   , "Protocol family not supported.")
1134    TEXT_FOR_ERROR(SOCEAFNOSUPPORT   , "Address family not supported by protocol family.")
1135    TEXT_FOR_ERROR(SOCEADDRINUSE     , "Address already in use.")
1136    TEXT_FOR_ERROR(SOCEADDRNOTAVAIL  , "Can't assign requested address.")
1137    TEXT_FOR_ERROR(SOCENETDOWN       , "Network is down.")
1138    TEXT_FOR_ERROR(SOCENETUNREACH    , "Network is unreachable.")
1139    TEXT_FOR_ERROR(SOCENETRESET      , "Network dropped connection on reset.")
1140    TEXT_FOR_ERROR(SOCECONNABORTED   , "Software caused connection abort.")
1141    TEXT_FOR_ERROR(SOCECONNRESET     , "Connection reset by peer.")
1142    TEXT_FOR_ERROR(SOCENOBUFS        , "No buffer space available.")
1143    TEXT_FOR_ERROR(SOCEISCONN        , "Socket is already connected.")
1144    TEXT_FOR_ERROR(SOCENOTCONN       , "Socket is not connected.")
1145    TEXT_FOR_ERROR(SOCESHUTDOWN      , "Can't send after socket shutdown.")
1146    TEXT_FOR_ERROR(SOCETOOMANYREFS   , "Too many references: can't splice.")
1147    TEXT_FOR_ERROR(SOCETIMEDOUT      , "Operation timed out.")
1148    TEXT_FOR_ERROR(SOCECONNREFUSED   , "Connection refused.")
1149    TEXT_FOR_ERROR(SOCELOOP          , "Too many levels of symbolic links.")
1150    TEXT_FOR_ERROR(SOCENAMETOOLONG   , "File name too long.")
1151    TEXT_FOR_ERROR(SOCEHOSTDOWN      , "Host is down.")
1152    TEXT_FOR_ERROR(SOCEHOSTUNREACH   , "No route to host.")
1153    TEXT_FOR_ERROR(SOCENOTEMPTY      , "Directory not empty.")
1154    TEXT_FOR_ERROR(SOCEOS2ERR        , "OS/2 Error.")
1155
1156    sprintf(tmp_buf, "(error number %d)", errcode);
1157    return tmp_buf;
1158 }
1159 #endif /* def __OS2__ */
1160
1161
1162 /*
1163   Local Variables:
1164   tab-width: 3
1165   end:
1166 */