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