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