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