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