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