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