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