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