Add jwz to contributors/testers.
[privoxy.git] / errlog.c
1 const char errlog_rcs[] = "$Id: errlog.c,v 1.39 2002/04/03 17:15:27 gliptak 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 the SourceForge
10  *                Privoxy team. http://www.privoxy.org/
11  *
12  *                Based on the Internet Junkbuster originally written
13  *                by and Copyright (C) 1997 Anonymous Coders and 
14  *                Junkbusters Corporation.  http://www.junkbusters.com
15  *
16  *                This program is free software; you can redistribute it 
17  *                and/or modify it under the terms of the GNU General
18  *                Public License as published by the Free Software
19  *                Foundation; either version 2 of the License, or (at
20  *                your option) any later version.
21  *
22  *                This program is distributed in the hope that it will
23  *                be useful, but WITHOUT ANY WARRANTY; without even the
24  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
25  *                PARTICULAR PURPOSE.  See the GNU General Public
26  *                License for more details.
27  *
28  *                The GNU General Public License should be included with
29  *                this file.  If not, you can view it at
30  *                http://www.gnu.org/copyleft/gpl.html
31  *                or write to the Free Software Foundation, Inc., 59
32  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
33  *
34  * Revisions   :
35  *    $Log: errlog.c,v $
36  *    Revision 1.39  2002/04/03 17:15:27  gliptak
37  *    zero padding thread ids in log
38  *
39  *    Revision 1.38  2002/03/31 17:18:59  jongfoster
40  *    Win32 only: Enabling STRICT to fix a VC++ compile warning.
41  *
42  *    Revision 1.37  2002/03/27 14:32:43  david__schmidt
43  *    More compiler warning message maintenance
44  *
45  *    Revision 1.36  2002/03/26 22:29:54  swa
46  *    we have a new homepage!
47  *
48  *    Revision 1.35  2002/03/24 15:23:33  jongfoster
49  *    Name changes
50  *
51  *    Revision 1.34  2002/03/24 13:25:43  swa
52  *    name change related issues
53  *
54  *    Revision 1.33  2002/03/13 00:27:04  jongfoster
55  *    Killing warnings
56  *
57  *    Revision 1.32  2002/03/07 03:46:17  oes
58  *    Fixed compiler warnings
59  *
60  *    Revision 1.31  2002/03/06 23:02:57  jongfoster
61  *    Removing tabs
62  *
63  *    Revision 1.30  2002/03/05 22:43:45  david__schmidt
64  *    - Better error reporting on OS/2
65  *    - Fix double-slash comment (oops)
66  *
67  *    Revision 1.29  2002/03/04 23:45:13  jongfoster
68  *    Printing thread ID if using Win32 native threads
69  *
70  *    Revision 1.28  2002/03/04 17:59:59  oes
71  *    Deleted deletePidFile(), cosmetics
72  *
73  *    Revision 1.27  2002/03/04 02:08:01  david__schmidt
74  *    Enable web editing of actions file on OS/2 (it had been broken all this time!)
75  *
76  *    Revision 1.26  2002/01/09 19:05:45  steudten
77  *    Fix big memory leak.
78  *
79  *    Revision 1.25  2002/01/09 14:32:08  oes
80  *    Added support for gmtime_r and localtime_r.
81  *
82  *    Revision 1.24  2001/12/30 14:07:32  steudten
83  *    - Add signal handling (unix)
84  *    - Add SIGHUP handler (unix)
85  *    - Add creation of pidfile (unix)
86  *    - Add action 'top' in rc file (RH)
87  *    - Add entry 'SIGNALS' to manpage
88  *    - Add exit message to logfile (unix)
89  *
90  *    Revision 1.23  2001/11/07 00:02:13  steudten
91  *    Add line number in error output for lineparsing for
92  *    actionsfile and configfile.
93  *    Special handling for CLF added.
94  *
95  *    Revision 1.22  2001/11/05 23:43:05  steudten
96  *    Add time+date to log files.
97  *
98  *    Revision 1.21  2001/10/25 03:40:47  david__schmidt
99  *    Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
100  *    threads to call select() simultaneously.  So, it's time to do a real, live,
101  *    native OS/2 port.  See defines for __EMX__ (the porting layer) vs. __OS2__
102  *    (native). Both versions will work, but using __OS2__ offers multi-threading.
103  *
104  *    Revision 1.20  2001/09/16 23:04:34  jongfoster
105  *    Fixing a warning
106  *
107  *    Revision 1.19  2001/09/13 20:08:06  jongfoster
108  *    Adding support for LOG_LEVEL_CGI
109  *
110  *    Revision 1.18  2001/09/10 11:27:24  oes
111  *    Declaration of w32_socket_strerr now conditional
112  *
113  *    Revision 1.17  2001/09/10 10:17:13  oes
114  *    Removed unused variable; Fixed sprintf format
115  *
116  *    Revision 1.16  2001/07/30 22:08:36  jongfoster
117  *    Tidying up #defines:
118  *    - All feature #defines are now of the form FEATURE_xxx
119  *    - Permanently turned off WIN_GUI_EDIT
120  *    - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
121  *
122  *    Revision 1.15  2001/07/29 17:41:10  jongfoster
123  *    Now prints thread ID for each message (pthreads only)
124  *
125  *    Revision 1.14  2001/07/19 19:03:48  haroon
126  *    - Added case for LOG_LEVEL_POPUPS
127  *
128  *    Revision 1.13  2001/07/13 13:58:58  oes
129  *     - Added case for LOG_LEVEL_DEANIMATE
130  *     - Removed all #ifdef PCRS
131  *
132  *    Revision 1.12  2001/06/09 10:55:28  jongfoster
133  *    Changing BUFSIZ ==> BUFFER_SIZE
134  *
135  *    Revision 1.11  2001/06/01 18:14:49  jongfoster
136  *    Changing the calls to strerr() to check HAVE_STRERR (which is defined
137  *    in config.h if appropriate) rather than the NO_STRERR macro.
138  *
139  *    Revision 1.10  2001/05/29 11:52:21  oes
140  *    Conditional compilation of w32_socket_error
141  *
142  *    Revision 1.9  2001/05/28 16:15:17  jongfoster
143  *    Improved reporting of errors under Win32.
144  *
145  *    Revision 1.8  2001/05/26 17:25:14  jongfoster
146  *    Added support for CLF (Common Log Format) and fixed LOG_LEVEL_LOG
147  *
148  *    Revision 1.7  2001/05/26 15:21:28  jongfoster
149  *    Activity animation in Win32 GUI now works even if debug==0
150  *
151  *    Revision 1.6  2001/05/25 21:55:08  jongfoster
152  *    Now cleans up properly on FATAL (removes taskbar icon etc)
153  *
154  *    Revision 1.5  2001/05/22 18:46:04  oes
155  *
156  *    - Enabled filtering banners by size rather than URL
157  *      by adding patterns that replace all standard banner
158  *      sizes with the "Junkbuster" gif to the re_filterfile
159  *
160  *    - Enabled filtering WebBugs by providing a pattern
161  *      which kills all 1x1 images
162  *
163  *    - Added support for PCRE_UNGREEDY behaviour to pcrs,
164  *      which is selected by the (nonstandard and therefore
165  *      capital) letter 'U' in the option string.
166  *      It causes the quantifiers to be ungreedy by default.
167  *      Appending a ? turns back to greedy (!).
168  *
169  *    - Added a new interceptor ijb-send-banner, which
170  *      sends back the "Junkbuster" gif. Without imagelist or
171  *      MSIE detection support, or if tinygif = 1, or the
172  *      URL isn't recognized as an imageurl, a lame HTML
173  *      explanation is sent instead.
174  *
175  *    - Added new feature, which permits blocking remote
176  *      script redirects and firing back a local redirect
177  *      to the browser.
178  *      The feature is conditionally compiled, i.e. it
179  *      can be disabled with --disable-fast-redirects,
180  *      plus it must be activated by a "fast-redirects"
181  *      line in the config file, has its own log level
182  *      and of course wants to be displayed by show-proxy-args
183  *      Note: Boy, all the #ifdefs in 1001 locations and
184  *      all the fumbling with configure.in and acconfig.h
185  *      were *way* more work than the feature itself :-(
186  *
187  *    - Because a generic redirect template was needed for
188  *      this, tinygif = 3 now uses the same.
189  *
190  *    - Moved GIFs, and other static HTTP response templates
191  *      to project.h
192  *
193  *    - Some minor fixes
194  *
195  *    - Removed some >400 CRs again (Jon, you really worked
196  *      a lot! ;-)
197  *
198  *    Revision 1.4  2001/05/21 19:32:54  jongfoster
199  *    Added another #ifdef _WIN_CONSOLE
200  *
201  *    Revision 1.3  2001/05/20 01:11:40  jongfoster
202  *    Added support for LOG_LEVEL_FATAL
203  *    Renamed LOG_LEVEL_FRC to LOG_LEVEL_FORCE,
204  *    and LOG_LEVEL_REF to LOG_LEVEL_RE_FILTER
205  *
206  *    Revision 1.2  2001/05/17 22:42:01  oes
207  *     - Cleaned CRLF's from the sources and related files
208  *     - Repaired logging for REF and FRC
209  *
210  *    Revision 1.1.1.1  2001/05/15 13:58:51  oes
211  *    Initial import of version 2.9.3 source tree
212  *
213  *
214  *********************************************************************/
215 \f
216
217 #include "config.h"
218 #include "miscutil.h"
219
220 #include <stdlib.h>
221 #include <stdio.h>
222 #include <stdarg.h>
223 #include <string.h>
224
225 #if !defined(_WIN32) && !defined(__OS2__)
226 #include <unistd.h>
227 #endif /* !defined(_WIN32) && !defined(__OS2__) */
228
229 #include <errno.h>
230 #include <assert.h>
231 #ifdef FEATURE_PTHREAD
232 #include <pthread.h>
233 #endif /* def FEATURE_PTHREAD */
234
235 #ifdef _WIN32
236 #ifndef STRICT
237 #define STRICT
238 #endif
239 #include <windows.h>
240 #ifndef _WIN_CONSOLE
241 #include "w32log.h"
242 #endif /* ndef _WIN_CONSOLE */
243 #endif /* def _WIN32 */
244
245 #ifdef __OS2__
246 #include <sys/socket.h> /* For sock_errno */
247 #define INCL_DOS
248 #include <os2.h>
249 #endif
250
251 #include "errlog.h"
252 #include "project.h"
253 #include "jcc.h"
254
255 const char errlog_h_rcs[] = ERRLOG_H_VERSION;
256
257
258 /*
259  * LOG_LEVEL_FATAL cannot be turned off.  (There are
260  * some exceptional situations where we need to get a
261  * message to the user).
262  */
263 #define LOG_LEVEL_MINIMUM  LOG_LEVEL_FATAL
264
265 /* where to log (default: stderr) */
266 static FILE *logfp = NULL;
267
268 /* logging detail level.  */
269 static int debug = (LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);  
270
271 /* static functions */
272 static void fatal_error(const char * error_message);
273 #ifdef _WIN32
274 static char *w32_socket_strerr(int errcode, char *tmp_buf);
275 #endif
276 #ifdef __OS2__
277 static char *os2_socket_strerr(int errcode, char *tmp_buf);
278 #endif
279
280 /*********************************************************************
281  *
282  * Function    :  fatal_error
283  *
284  * Description :  Displays a fatal error to standard error (or, on 
285  *                a WIN32 GUI, to a dialog box), and exits
286  *                JunkBuster with status code 1.
287  *
288  * Parameters  :
289  *          1  :  error_message = The error message to display.
290  *
291  * Returns     :  Does not return.
292  *
293  *********************************************************************/
294 static void fatal_error(const char * error_message)
295 {
296 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
297    MessageBox(g_hwndLogFrame, error_message, "Privoxy Error", 
298       MB_OK | MB_ICONERROR | MB_TASKMODAL | MB_SETFOREGROUND | MB_TOPMOST);  
299
300    /* Cleanup - remove taskbar icon etc. */
301    TermLogWindow();
302
303 #else /* if !defined(_WIN32) || defined(_WIN_CONSOLE) */
304    fputs(error_message, stderr);
305 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
306
307 #if defined(unix)
308    unlink(pidfile);
309 #endif /* unix */
310
311    exit(1);
312 }
313
314
315 /*********************************************************************
316  *
317  * Function    :  init_error_log
318  *
319  * Description :  Initializes the logging module.  Must call before
320  *                calling log_error.
321  *
322  * Parameters  :
323  *          1  :  prog_name  = The program name.
324  *          2  :  logfname   = The logfile name, or NULL for stderr.
325  *          3  :  debuglevel = The debugging level.
326  *
327  * Returns     :  N/A
328  *
329  *********************************************************************/
330 void init_error_log(const char *prog_name, const char *logfname, int debuglevel)
331 {
332    FILE *fp;
333
334    /* FIXME RACE HAZARD: should start critical section error_log_use here */
335
336    /* set the logging detail level */
337    debug = debuglevel | LOG_LEVEL_MINIMUM;
338
339    if ((logfp != NULL) && (logfp != stderr))
340    {
341       log_error(LOG_LEVEL_INFO, "(Re-)Open logfile %s", logfname ? logfname : "none");
342       fclose(logfp);
343    }
344    logfp = stderr;
345
346    /* set the designated log file */
347    if( logfname )
348    {
349       if( NULL == (fp = fopen(logfname, "a")) )
350       {
351          log_error(LOG_LEVEL_FATAL, "init_error_log(): can't open logfile: %s", logfname);
352       }
353
354       /* set logging to be completely unbuffered */
355       setbuf(fp, NULL);
356
357       logfp = fp;
358    }
359
360    log_error(LOG_LEVEL_INFO, "Privoxy version " VERSION);
361    if (prog_name != NULL)
362    {
363       log_error(LOG_LEVEL_INFO, "Program name: %s", prog_name);
364    }
365
366    /* FIXME RACE HAZARD: should end critical section error_log_use here */
367
368 } /* init_error_log */
369
370
371 /*********************************************************************
372  *
373  * Function    :  log_error
374  *
375  * Description :  This is the error-reporting and logging function.
376  *
377  * Parameters  :
378  *          1  :  loglevel  = the type of message to be logged
379  *          2  :  fmt       = the main string we want logged, printf-like
380  *          3  :  ...       = arguments to be inserted in fmt (printf-like).
381  *
382  * Returns     :  N/A
383  *
384  *********************************************************************/
385 void log_error(int loglevel, char *fmt, ...)
386 {
387    va_list ap;
388    char *outbuf= NULL;
389    static char *outbuf_save = NULL;
390    char * src = fmt;
391    int outc = 0;
392    long this_thread = 1;  /* was: pthread_t this_thread;*/
393 #ifdef __OS2__
394    PTIB     ptib;
395    APIRET   ulrc;
396 #endif /* __OS2__ */
397
398 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
399    /*
400     * Irrespective of debug setting, a GET/POST/CONNECT makes
401     * the taskbar icon animate.  (There is an option to disable
402     * this but checking that is handled inside LogShowActivity()).
403     */
404    if (loglevel == LOG_LEVEL_GPC)
405    {
406       LogShowActivity();
407    }
408 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
409
410    /* verify if loglevel applies to current settings and bail out if negative */
411    if ((loglevel & debug) == 0)
412    {
413       return;
414    }
415
416    /* FIXME get current thread id */
417 #ifdef FEATURE_PTHREAD
418    this_thread = (long)pthread_self();
419 #elif defined(_WIN32)
420    this_thread = GetCurrentThreadId();
421 #elif defined(__OS2__)
422    ulrc = DosGetInfoBlocks(&ptib, NULL);
423    if (ulrc == 0)
424      this_thread = ptib -> tib_ptib2 -> tib2_ultid;
425 #endif /* def FEATURE_PTHREAD */
426
427    if ( !outbuf_save ) 
428    {
429       outbuf_save = outbuf = (char*)malloc(BUFFER_SIZE);
430       assert(outbuf);
431    }
432    outbuf = outbuf_save;
433
434     {
435        /*
436         * Write timestamp into tempbuf.
437         *
438         * Complex because not all OSs have tm_gmtoff or
439         * the %z field in strftime()
440         */
441        time_t now; 
442        struct tm tm_now; 
443        time (&now);
444 #ifdef HAVE_LOCALTIME_R
445        tm_now = *localtime_r(&now, &tm_now);
446 #else
447        tm_now = *localtime (&now); 
448 #endif
449        strftime(outbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now); 
450        outbuf += strlen( outbuf );
451     }
452    switch (loglevel)
453    {
454       case LOG_LEVEL_ERROR:
455          outc = sprintf(outbuf, "Privoxy(%05ld) Error: ", this_thread);
456          break;
457       case LOG_LEVEL_FATAL:
458          outc = sprintf(outbuf, "Privoxy(%05ld) Fatal error: ", this_thread);
459          break;
460       case LOG_LEVEL_GPC:
461          outc = sprintf(outbuf, "Privoxy(%05ld) Request: ", this_thread);
462          break;
463       case LOG_LEVEL_CONNECT:
464          outc = sprintf(outbuf, "Privoxy(%05ld) Connect: ", this_thread);
465          break;
466       case LOG_LEVEL_LOG:
467          outc = sprintf(outbuf, "Privoxy(%05ld) Writing: ", this_thread);
468          break;
469       case LOG_LEVEL_HEADER:
470          outc = sprintf(outbuf, "Privoxy(%05ld) Header: ", this_thread);
471          break;
472       case LOG_LEVEL_INFO:
473          outc = sprintf(outbuf, "Privoxy(%05ld) Info: ", this_thread);
474          break;
475       case LOG_LEVEL_RE_FILTER:
476          outc = sprintf(outbuf, "Privoxy(%05ld) Re-Filter: ", this_thread);
477          break;
478 #ifdef FEATURE_FORCE_LOAD
479       case LOG_LEVEL_FORCE:
480          outc = sprintf(outbuf, "Privoxy(%05ld) Force: ", this_thread);
481          break;
482 #endif /* def FEATURE_FORCE_LOAD */
483 #ifdef FEATURE_FAST_REDIRECTS
484       case LOG_LEVEL_REDIRECTS:
485          outc = sprintf(outbuf, "Privoxy(%05ld) Redirect: ", this_thread);
486          break;
487 #endif /* def FEATURE_FAST_REDIRECTS */
488       case LOG_LEVEL_DEANIMATE:
489          outc = sprintf(outbuf, "Privoxy(%05ld) Gif-Deanimate: ", this_thread);
490          break;
491       case LOG_LEVEL_CLF:
492          outbuf = outbuf_save;
493          outc = 0;
494          outbuf[0] = '\0';
495          break;
496 #ifdef FEATURE_KILL_POPUPS
497       case LOG_LEVEL_POPUPS:
498          outc = sprintf(outbuf, "Privoxy(%05ld) Kill-Popups: ", this_thread);
499          break;
500 #endif /* def FEATURE_KILL_POPUPS */
501       case LOG_LEVEL_CGI:
502          outc = sprintf(outbuf, "Privoxy(%05ld) CGI: ", this_thread);
503          break;
504       default:
505          outc = sprintf(outbuf, "Privoxy(%05ld) UNKNOWN LOG TYPE(%d): ", this_thread, loglevel);
506          break;
507    }
508    
509    /* get ready to scan var. args. */
510    va_start( ap, fmt );
511
512    /* build formatted message from fmt and var-args */
513    while ((*src) && (outc < BUFFER_SIZE-2))
514    {
515       char tempbuf[BUFFER_SIZE];
516       char *sval = NULL;
517       int ival;
518       unsigned uval;
519       long lval;
520       unsigned long ulval;
521       int oldoutc;
522       char ch;
523       
524       ch = *src++;
525       if( ch != '%' )
526       {
527          outbuf[outc++] = ch;
528          continue;
529       }
530
531       ch = *src++;
532       switch (ch) {
533          case '%':
534             outbuf[outc++] = '%';
535             break;
536          case 'd':
537             ival = va_arg( ap, int );
538             oldoutc = outc;
539             outc += sprintf(tempbuf, "%d", ival);
540             if (outc < BUFFER_SIZE-1) 
541             {
542                strcpy(outbuf + oldoutc, tempbuf);
543             }
544             else
545             {
546                outbuf[oldoutc] = '\0';
547             }
548             break;
549          case 'u':
550             uval = va_arg( ap, unsigned );
551             oldoutc = outc;
552             outc += sprintf(tempbuf, "%u", uval);
553             if (outc < BUFFER_SIZE-1) 
554             {
555                strcpy(outbuf + oldoutc, tempbuf);
556             }
557             else
558             {
559                outbuf[oldoutc] = '\0';
560             }
561             break;
562          case 'l':
563             /* this is a modifier that must be followed by u or d */
564             ch = *src++;
565             if (ch == 'd')
566             {
567                lval = va_arg( ap, long );
568                oldoutc = outc;
569                outc += sprintf(tempbuf, "%ld", lval);
570             }
571             else if (ch == 'u')
572             {
573                ulval = va_arg( ap, unsigned long );
574                oldoutc = outc;
575                outc += sprintf(tempbuf, "%lu", ulval);
576             }
577             else
578             {
579                /* Error */
580                sprintf(outbuf, "Privoxy(%ld) Error: log_error(): Bad format string:\n"
581                                "Format = \"%s\"\n"
582                                "Exiting.", this_thread, fmt);
583                /* FIXME RACE HAZARD: should start critical section error_log_use here */
584                if( !logfp )
585                {
586                   logfp = stderr;
587                }
588                fputs(outbuf, logfp);
589                /* FIXME RACE HAZARD: should end critical section error_log_use here */
590                fatal_error(outbuf);
591                /* Never get here */
592                break;
593             }
594             if (outc < BUFFER_SIZE-1) 
595             {
596                strcpy(outbuf + oldoutc, tempbuf);
597             }
598             else
599             {
600                outbuf[oldoutc] = '\0';
601             }
602             break;
603          case 'c':
604             /*
605              * Note that char paramaters are converted to int, so we need to
606              * pass "int" to va_arg.  (See K&R, 2nd ed, section A7.3.2, page 202)
607              */
608             outbuf[outc++] = (char) va_arg( ap, int );
609             break;
610          case 's':
611             sval = va_arg( ap, char * );
612             oldoutc = outc;
613             outc += strlen(sval);
614             if (outc < BUFFER_SIZE-1) 
615             {
616                strcpy(outbuf + oldoutc, sval);
617             }
618             else
619             {
620                outbuf[oldoutc] = '\0';
621             }
622             break;
623          case 'N':
624             /* Non-standard: Print a counted string.  Takes 2 parameters:
625              * int length, const char * string
626              */
627             ival = va_arg( ap, int );
628             sval = va_arg( ap, char * );
629             if (ival < 0)
630             {
631                ival = 0;
632             }
633             oldoutc = outc;
634             outc += ival;
635             if (outc < BUFFER_SIZE-1)
636             {
637                memcpy(outbuf + oldoutc, sval, (size_t) ival);
638             }
639             else
640             {
641                outbuf[oldoutc] = '\0';
642             }
643             break;
644          case 'E':
645             /* Non-standard: Print error code from errno */
646 #ifdef _WIN32
647             ival = WSAGetLastError();
648             sval = w32_socket_strerr(ival, tempbuf);
649 #elif __OS2__
650             ival = sock_errno();
651             if (ival != 0)
652               sval = os2_socket_strerr(ival, tempbuf);
653             else
654             {
655               ival = errno;
656               sval = strerror(ival);
657             }
658 #else /* ifndef _WIN32 */
659             ival = errno; 
660 #ifdef HAVE_STRERROR
661             sval = strerror(ival);
662 #else /* ifndef HAVE_STRERROR */
663             sval = NULL;
664 #endif /* ndef HAVE_STRERROR */
665             if (sval == NULL)
666             {
667                sprintf(tempbuf, "(errno = %d)", ival);
668                sval = tempbuf;
669             }
670 #endif /* ndef _WIN32 */
671             oldoutc = outc;
672             outc += strlen(sval);
673             if (outc < BUFFER_SIZE-1) 
674             {
675                strcpy(outbuf + oldoutc, sval);
676             }
677             else
678             {
679                outbuf[oldoutc] = '\0';
680             }
681             break;
682          case 'T':
683             /* Non-standard: Print a Common Log File timestamp */
684             {
685                /*
686                 * Write timestamp into tempbuf.
687                 *
688                 * Complex because not all OSs have tm_gmtoff or
689                 * the %z field in strftime()
690                 */
691                time_t now; 
692                struct tm *tm_now; 
693                struct tm gmt;
694 #ifdef HAVE_LOCALTIME_R
695                struct tm dummy;
696 #endif
697                int days, hrs, mins; 
698                time (&now); 
699 #ifdef HAVE_GMTIME_R
700                gmt = *gmtime_r(&now, &gmt);
701 #else
702                gmt = *gmtime(&now);
703 #endif
704 #ifdef HAVE_LOCALTIME_R
705                tm_now = localtime_r(&now, &dummy);
706 #else
707                tm_now = localtime (&now); 
708 #endif
709                days = tm_now->tm_yday - gmt.tm_yday; 
710                hrs = ((days < -1 ? 24 : 1 < days ? -24 : days * 24) + tm_now->tm_hour - gmt.tm_hour); 
711                mins = hrs * 60 + tm_now->tm_min - gmt.tm_min; 
712                strftime (tempbuf, BUFFER_SIZE-6, "%d/%b/%Y:%H:%M:%S ", tm_now); 
713                sprintf (tempbuf + strlen(tempbuf), "%+03d%02d", mins / 60, abs(mins) % 60); 
714             }
715             oldoutc = outc;
716             outc += strlen(tempbuf);
717             if (outc < BUFFER_SIZE-1) 
718             {
719                strcpy(outbuf + oldoutc, tempbuf);
720             }
721             else
722             {
723                outbuf[oldoutc] = '\0';
724             }
725             break;
726          default:
727             sprintf(outbuf, "Privoxy(%ld) Error: log_error(): Bad format string:\n"
728                             "Format = \"%s\"\n"
729                             "Exiting.", this_thread, fmt);
730             /* FIXME RACE HAZARD: should start critical section error_log_use here */
731             if( !logfp )
732             {
733                logfp = stderr;
734             }
735             fputs(outbuf_save, logfp);
736             /* FIXME RACE HAZARD: should end critical section error_log_use here */
737             fatal_error(outbuf_save);
738             /* Never get here */
739             break;
740
741       } /* switch( p ) */
742
743    } /* for( p ... ) */
744    
745    /* done with var. args */
746    va_end( ap );
747    
748    if (outc >= BUFFER_SIZE-2)
749    {
750       /* insufficient room for newline and trailing null. */
751
752       static const char warning[] = "... [too long, truncated]\n";
753
754       if (outc < BUFFER_SIZE)
755       {
756          /* Need to add terminating null in this case. */
757          outbuf[outc] = '\0';
758       }
759
760       /* Truncate output */
761       outbuf[BUFFER_SIZE - sizeof(warning)] = '\0';
762
763       /* Append warning */
764       strcat(outbuf, warning);
765    }
766    else
767    {
768       /* Add terminating newline and null */
769       outbuf[outc++] = '\n';
770       outbuf[outc] = '\0';
771    }
772
773    /* FIXME RACE HAZARD: should start critical section error_log_use here */
774
775    /* deal with glibc stupidity - it won't let you initialize logfp */
776    if( !logfp )
777    {
778       logfp = stderr;
779    }
780
781    fputs(outbuf_save, logfp);
782
783    if (loglevel == LOG_LEVEL_FATAL)
784    {
785       fatal_error(outbuf_save);
786       /* Never get here */
787    }
788
789    /* FIXME RACE HAZARD: should end critical section error_log_use here */
790
791 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
792    /* Write to display */
793    LogPutString(outbuf_save);
794 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
795
796 }
797
798
799 #ifdef _WIN32
800 /*********************************************************************
801  *
802  * Function    :  w32_socket_strerr
803  *
804  * Description :  Translate the return value from WSAGetLastError()
805  *                into a string.
806  *
807  * Parameters  :
808  *          1  :  errcode = The return value from WSAGetLastError().
809  *          2  :  tmp_buf = A temporary buffer that might be used to
810  *                          store the string.
811  *
812  * Returns     :  String representing the error code.  This may be
813  *                a global string constant or a string stored in
814  *                tmp_buf.
815  *
816  *********************************************************************/
817 static char *w32_socket_strerr(int errcode, char *tmp_buf)
818 {
819 #define TEXT_FOR_ERROR(code,text) \
820    if (errcode == code)           \
821    {                              \
822       return #code " - " text;    \
823    }
824
825    TEXT_FOR_ERROR(WSAEACCES, "Permission denied")
826    TEXT_FOR_ERROR(WSAEADDRINUSE, "Address already in use.")
827    TEXT_FOR_ERROR(WSAEADDRNOTAVAIL, "Cannot assign requested address.");
828    TEXT_FOR_ERROR(WSAEAFNOSUPPORT, "Address family not supported by protocol family.");
829    TEXT_FOR_ERROR(WSAEALREADY, "Operation already in progress.");
830    TEXT_FOR_ERROR(WSAECONNABORTED, "Software caused connection abort.");
831    TEXT_FOR_ERROR(WSAECONNREFUSED, "Connection refused.");
832    TEXT_FOR_ERROR(WSAECONNRESET, "Connection reset by peer.");
833    TEXT_FOR_ERROR(WSAEDESTADDRREQ, "Destination address required.");
834    TEXT_FOR_ERROR(WSAEFAULT, "Bad address.");
835    TEXT_FOR_ERROR(WSAEHOSTDOWN, "Host is down.");
836    TEXT_FOR_ERROR(WSAEHOSTUNREACH, "No route to host.");
837    TEXT_FOR_ERROR(WSAEINPROGRESS, "Operation now in progress.");
838    TEXT_FOR_ERROR(WSAEINTR, "Interrupted function call.");
839    TEXT_FOR_ERROR(WSAEINVAL, "Invalid argument.");
840    TEXT_FOR_ERROR(WSAEISCONN, "Socket is already connected.");
841    TEXT_FOR_ERROR(WSAEMFILE, "Too many open sockets.");
842    TEXT_FOR_ERROR(WSAEMSGSIZE, "Message too long.");
843    TEXT_FOR_ERROR(WSAENETDOWN, "Network is down.");
844    TEXT_FOR_ERROR(WSAENETRESET, "Network dropped connection on reset.");
845    TEXT_FOR_ERROR(WSAENETUNREACH, "Network is unreachable.");
846    TEXT_FOR_ERROR(WSAENOBUFS, "No buffer space available.");
847    TEXT_FOR_ERROR(WSAENOPROTOOPT, "Bad protocol option.");
848    TEXT_FOR_ERROR(WSAENOTCONN, "Socket is not connected.");
849    TEXT_FOR_ERROR(WSAENOTSOCK, "Socket operation on non-socket.");
850    TEXT_FOR_ERROR(WSAEOPNOTSUPP, "Operation not supported.");
851    TEXT_FOR_ERROR(WSAEPFNOSUPPORT, "Protocol family not supported.");
852    TEXT_FOR_ERROR(WSAEPROCLIM, "Too many processes.");
853    TEXT_FOR_ERROR(WSAEPROTONOSUPPORT, "Protocol not supported.");
854    TEXT_FOR_ERROR(WSAEPROTOTYPE, "Protocol wrong type for socket.");
855    TEXT_FOR_ERROR(WSAESHUTDOWN, "Cannot send after socket shutdown.");
856    TEXT_FOR_ERROR(WSAESOCKTNOSUPPORT, "Socket type not supported.");
857    TEXT_FOR_ERROR(WSAETIMEDOUT, "Connection timed out.");
858    TEXT_FOR_ERROR(WSAEWOULDBLOCK, "Resource temporarily unavailable.");
859    TEXT_FOR_ERROR(WSAHOST_NOT_FOUND, "Host not found.");
860    TEXT_FOR_ERROR(WSANOTINITIALISED, "Successful WSAStartup not yet performed.");
861    TEXT_FOR_ERROR(WSANO_DATA, "Valid name, no data record of requested type.");
862    TEXT_FOR_ERROR(WSANO_RECOVERY, "This is a non-recoverable error.");
863    TEXT_FOR_ERROR(WSASYSNOTREADY, "Network subsystem is unavailable.");
864    TEXT_FOR_ERROR(WSATRY_AGAIN, "Non-authoritative host not found.");
865    TEXT_FOR_ERROR(WSAVERNOTSUPPORTED, "WINSOCK.DLL version out of range.");
866    TEXT_FOR_ERROR(WSAEDISCON, "Graceful shutdown in progress.");
867    /*
868     * The following error codes are documented in the Microsoft WinSock
869     * reference guide, but don't actually exist.
870     *
871     * TEXT_FOR_ERROR(WSA_INVALID_HANDLE, "Specified event object handle is invalid.");
872     * TEXT_FOR_ERROR(WSA_INVALID_PARAMETER, "One or more parameters are invalid.");
873     * TEXT_FOR_ERROR(WSAINVALIDPROCTABLE, "Invalid procedure table from service provider.");
874     * TEXT_FOR_ERROR(WSAINVALIDPROVIDER, "Invalid service provider version number.");
875     * TEXT_FOR_ERROR(WSA_IO_PENDING, "Overlapped operations will complete later.");
876     * TEXT_FOR_ERROR(WSA_IO_INCOMPLETE, "Overlapped I/O event object not in signaled state.");
877     * TEXT_FOR_ERROR(WSA_NOT_ENOUGH_MEMORY, "Insufficient memory available.");
878     * TEXT_FOR_ERROR(WSAPROVIDERFAILEDINIT, "Unable to initialize a service provider.");
879     * TEXT_FOR_ERROR(WSASYSCALLFAILURE, "System call failure.");
880     * TEXT_FOR_ERROR(WSA_OPERATION_ABORTED, "Overlapped operation aborted.");
881     */
882
883    sprintf(tmp_buf, "(error number %d)", errcode);
884    return tmp_buf;
885 }
886 #endif /* def _WIN32 */
887
888
889 #ifdef __OS2__
890 /*********************************************************************
891  *
892  * Function    :  os2_socket_strerr
893  *
894  * Description :  Translate the return value from sock_errno()
895  *                into a string.
896  *
897  * Parameters  :
898  *          1  :  errcode = The return value from sock_errno().
899  *          2  :  tmp_buf = A temporary buffer that might be used to
900  *                          store the string.
901  *
902  * Returns     :  String representing the error code.  This may be
903  *                a global string constant or a string stored in
904  *                tmp_buf.
905  *
906  *********************************************************************/
907 static char *os2_socket_strerr(int errcode, char *tmp_buf)
908 {
909 #define TEXT_FOR_ERROR(code,text) \
910    if (errcode == code)           \
911    {                              \
912       return #code " - " text;    \
913    }
914
915    TEXT_FOR_ERROR(SOCEPERM          , "Not owner.")
916    TEXT_FOR_ERROR(SOCESRCH          , "No such process.")
917    TEXT_FOR_ERROR(SOCEINTR          , "Interrupted system call.")
918    TEXT_FOR_ERROR(SOCENXIO          , "No such device or address.")
919    TEXT_FOR_ERROR(SOCEBADF          , "Bad file number.")
920    TEXT_FOR_ERROR(SOCEACCES         , "Permission denied.")
921    TEXT_FOR_ERROR(SOCEFAULT         , "Bad address.")
922    TEXT_FOR_ERROR(SOCEINVAL         , "Invalid argument.")
923    TEXT_FOR_ERROR(SOCEMFILE         , "Too many open files.")
924    TEXT_FOR_ERROR(SOCEPIPE          , "Broken pipe.")
925    TEXT_FOR_ERROR(SOCEWOULDBLOCK    , "Operation would block.")
926    TEXT_FOR_ERROR(SOCEINPROGRESS    , "Operation now in progress.")
927    TEXT_FOR_ERROR(SOCEALREADY       , "Operation already in progress.")
928    TEXT_FOR_ERROR(SOCENOTSOCK       , "Socket operation on non-socket.")
929    TEXT_FOR_ERROR(SOCEDESTADDRREQ   , "Destination address required.")
930    TEXT_FOR_ERROR(SOCEMSGSIZE       , "Message too long.")
931    TEXT_FOR_ERROR(SOCEPROTOTYPE     , "Protocol wrong type for socket.")
932    TEXT_FOR_ERROR(SOCENOPROTOOPT    , "Protocol not available.")
933    TEXT_FOR_ERROR(SOCEPROTONOSUPPORT, "Protocol not supported.")
934    TEXT_FOR_ERROR(SOCESOCKTNOSUPPORT, "Socket type not supported.")
935    TEXT_FOR_ERROR(SOCEOPNOTSUPP     , "Operation not supported.")
936    TEXT_FOR_ERROR(SOCEPFNOSUPPORT   , "Protocol family not supported.")
937    TEXT_FOR_ERROR(SOCEAFNOSUPPORT   , "Address family not supported by protocol family.")
938    TEXT_FOR_ERROR(SOCEADDRINUSE     , "Address already in use.")
939    TEXT_FOR_ERROR(SOCEADDRNOTAVAIL  , "Can't assign requested address.")
940    TEXT_FOR_ERROR(SOCENETDOWN       , "Network is down.")
941    TEXT_FOR_ERROR(SOCENETUNREACH    , "Network is unreachable.")
942    TEXT_FOR_ERROR(SOCENETRESET      , "Network dropped connection on reset.")
943    TEXT_FOR_ERROR(SOCECONNABORTED   , "Software caused connection abort.")
944    TEXT_FOR_ERROR(SOCECONNRESET     , "Connection reset by peer.")
945    TEXT_FOR_ERROR(SOCENOBUFS        , "No buffer space available.")
946    TEXT_FOR_ERROR(SOCEISCONN        , "Socket is already connected.")
947    TEXT_FOR_ERROR(SOCENOTCONN       , "Socket is not connected.")
948    TEXT_FOR_ERROR(SOCESHUTDOWN      , "Can't send after socket shutdown.")
949    TEXT_FOR_ERROR(SOCETOOMANYREFS   , "Too many references: can't splice.")
950    TEXT_FOR_ERROR(SOCETIMEDOUT      , "Operation timed out.")
951    TEXT_FOR_ERROR(SOCECONNREFUSED   , "Connection refused.")
952    TEXT_FOR_ERROR(SOCELOOP          , "Too many levels of symbolic links.")
953    TEXT_FOR_ERROR(SOCENAMETOOLONG   , "File name too long.")
954    TEXT_FOR_ERROR(SOCEHOSTDOWN      , "Host is down.")
955    TEXT_FOR_ERROR(SOCEHOSTUNREACH   , "No route to host.")
956    TEXT_FOR_ERROR(SOCENOTEMPTY      , "Directory not empty.")
957    TEXT_FOR_ERROR(SOCEOS2ERR        , "OS/2 Error.")
958
959    sprintf(tmp_buf, "(error number %d)", errcode);
960    return tmp_buf;
961 }
962 #endif /* def __OS2__ */
963
964
965 /*
966   Local Variables:
967   tab-width: 3
968   end:
969 */