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