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