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