We need <sys/time.h> for gettimeofday(), not <time.h>.
[privoxy.git] / errlog.c
1 const char errlog_rcs[] = "$Id: errlog.c,v 1.48 2007/03/31 13:33:28 fabiankeil 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-2007 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.48  2007/03/31 13:33:28  fabiankeil
37  *    Add alternative log_error() with timestamps
38  *    that contain milliseconds and without using
39  *    strcpy(), strcat() or sprintf().
40  *
41  *    Revision 1.47  2006/11/28 15:25:15  fabiankeil
42  *    Only unlink the pidfile if it's actually used.
43  *
44  *    Revision 1.46  2006/11/13 19:05:51  fabiankeil
45  *    Make pthread mutex locking more generic. Instead of
46  *    checking for OSX and OpenBSD, check for FEATURE_PTHREAD
47  *    and use mutex locking unless there is an _r function
48  *    available. Better safe than sorry.
49  *
50  *    Fixes "./configure --disable-pthread" and should result
51  *    in less threading-related problems on pthread-using platforms,
52  *    but it still doesn't fix BR#1122404.
53  *
54  *    Revision 1.45  2006/08/21 11:15:54  david__schmidt
55  *    MS Visual C++ build updates
56  *
57  *    Revision 1.44  2006/08/18 16:03:16  david__schmidt
58  *    Tweak for OS/2 build happiness.
59  *
60  *    Revision 1.43  2006/08/03 02:46:41  david__schmidt
61  *    Incorporate Fabian Keil's patch work:
62  *    http://www.fabiankeil.de/sourcecode/privoxy/
63  *
64  *    Revision 1.42  2006/07/18 14:48:46  david__schmidt
65  *    Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
66  *    with what was really the latest development (the v_3_0_branch branch)
67  *
68  *    Revision 1.40.2.4  2005/04/03 20:10:50  david__schmidt
69  *    Thanks to Jindrich Makovicka for a race condition fix for the log
70  *    file.  The race condition remains for non-pthread implementations.
71  *    Reference patch #1175720.
72  *
73  *    Revision 1.40.2.3  2003/03/07 03:41:04  david__schmidt
74  *    Wrapping all *_r functions (the non-_r versions of them) with mutex 
75  *    semaphores for OSX.  Hopefully this will take care of all of those pesky
76  *    crash reports.
77  *
78  *    Revision 1.40.2.2  2002/09/28 00:30:57  david__schmidt
79  *    Update error logging to give sane values for thread IDs on Mach kernels.
80  *    It's still a hack, but at least it looks farily normal.  We print the
81  *    absolute value of the first 4 bytes of the pthread_t modded with 1000.
82  *
83  *    Revision 1.40.2.1  2002/09/25 12:47:42  oes
84  *    Make log_error safe against NULL string arguments
85  *
86  *    Revision 1.40  2002/05/22 01:27:27  david__schmidt
87  *
88  *    Add os2_socket_strerr mirroring w32_socket_strerr.
89  *
90  *    Revision 1.39  2002/04/03 17:15:27  gliptak
91  *    zero padding thread ids in log
92  *
93  *    Revision 1.38  2002/03/31 17:18:59  jongfoster
94  *    Win32 only: Enabling STRICT to fix a VC++ compile warning.
95  *
96  *    Revision 1.37  2002/03/27 14:32:43  david__schmidt
97  *    More compiler warning message maintenance
98  *
99  *    Revision 1.36  2002/03/26 22:29:54  swa
100  *    we have a new homepage!
101  *
102  *    Revision 1.35  2002/03/24 15:23:33  jongfoster
103  *    Name changes
104  *
105  *    Revision 1.34  2002/03/24 13:25:43  swa
106  *    name change related issues
107  *
108  *    Revision 1.33  2002/03/13 00:27:04  jongfoster
109  *    Killing warnings
110  *
111  *    Revision 1.32  2002/03/07 03:46:17  oes
112  *    Fixed compiler warnings
113  *
114  *    Revision 1.31  2002/03/06 23:02:57  jongfoster
115  *    Removing tabs
116  *
117  *    Revision 1.30  2002/03/05 22:43:45  david__schmidt
118  *    - Better error reporting on OS/2
119  *    - Fix double-slash comment (oops)
120  *
121  *    Revision 1.29  2002/03/04 23:45:13  jongfoster
122  *    Printing thread ID if using Win32 native threads
123  *
124  *    Revision 1.28  2002/03/04 17:59:59  oes
125  *    Deleted deletePidFile(), cosmetics
126  *
127  *    Revision 1.27  2002/03/04 02:08:01  david__schmidt
128  *    Enable web editing of actions file on OS/2 (it had been broken all this time!)
129  *
130  *    Revision 1.26  2002/01/09 19:05:45  steudten
131  *    Fix big memory leak.
132  *
133  *    Revision 1.25  2002/01/09 14:32:08  oes
134  *    Added support for gmtime_r and localtime_r.
135  *
136  *    Revision 1.24  2001/12/30 14:07:32  steudten
137  *    - Add signal handling (unix)
138  *    - Add SIGHUP handler (unix)
139  *    - Add creation of pidfile (unix)
140  *    - Add action 'top' in rc file (RH)
141  *    - Add entry 'SIGNALS' to manpage
142  *    - Add exit message to logfile (unix)
143  *
144  *    Revision 1.23  2001/11/07 00:02:13  steudten
145  *    Add line number in error output for lineparsing for
146  *    actionsfile and configfile.
147  *    Special handling for CLF added.
148  *
149  *    Revision 1.22  2001/11/05 23:43:05  steudten
150  *    Add time+date to log files.
151  *
152  *    Revision 1.21  2001/10/25 03:40:47  david__schmidt
153  *    Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
154  *    threads to call select() simultaneously.  So, it's time to do a real, live,
155  *    native OS/2 port.  See defines for __EMX__ (the porting layer) vs. __OS2__
156  *    (native). Both versions will work, but using __OS2__ offers multi-threading.
157  *
158  *    Revision 1.20  2001/09/16 23:04:34  jongfoster
159  *    Fixing a warning
160  *
161  *    Revision 1.19  2001/09/13 20:08:06  jongfoster
162  *    Adding support for LOG_LEVEL_CGI
163  *
164  *    Revision 1.18  2001/09/10 11:27:24  oes
165  *    Declaration of w32_socket_strerr now conditional
166  *
167  *    Revision 1.17  2001/09/10 10:17:13  oes
168  *    Removed unused variable; Fixed sprintf format
169  *
170  *    Revision 1.16  2001/07/30 22:08:36  jongfoster
171  *    Tidying up #defines:
172  *    - All feature #defines are now of the form FEATURE_xxx
173  *    - Permanently turned off WIN_GUI_EDIT
174  *    - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
175  *
176  *    Revision 1.15  2001/07/29 17:41:10  jongfoster
177  *    Now prints thread ID for each message (pthreads only)
178  *
179  *    Revision 1.14  2001/07/19 19:03:48  haroon
180  *    - Added case for LOG_LEVEL_POPUPS
181  *
182  *    Revision 1.13  2001/07/13 13:58:58  oes
183  *     - Added case for LOG_LEVEL_DEANIMATE
184  *     - Removed all #ifdef PCRS
185  *
186  *    Revision 1.12  2001/06/09 10:55:28  jongfoster
187  *    Changing BUFSIZ ==> BUFFER_SIZE
188  *
189  *    Revision 1.11  2001/06/01 18:14:49  jongfoster
190  *    Changing the calls to strerr() to check HAVE_STRERR (which is defined
191  *    in config.h if appropriate) rather than the NO_STRERR macro.
192  *
193  *    Revision 1.10  2001/05/29 11:52:21  oes
194  *    Conditional compilation of w32_socket_error
195  *
196  *    Revision 1.9  2001/05/28 16:15:17  jongfoster
197  *    Improved reporting of errors under Win32.
198  *
199  *    Revision 1.8  2001/05/26 17:25:14  jongfoster
200  *    Added support for CLF (Common Log Format) and fixed LOG_LEVEL_LOG
201  *
202  *    Revision 1.7  2001/05/26 15:21:28  jongfoster
203  *    Activity animation in Win32 GUI now works even if debug==0
204  *
205  *    Revision 1.6  2001/05/25 21:55:08  jongfoster
206  *    Now cleans up properly on FATAL (removes taskbar icon etc)
207  *
208  *    Revision 1.5  2001/05/22 18:46:04  oes
209  *
210  *    - Enabled filtering banners by size rather than URL
211  *      by adding patterns that replace all standard banner
212  *      sizes with the "Junkbuster" gif to the re_filterfile
213  *
214  *    - Enabled filtering WebBugs by providing a pattern
215  *      which kills all 1x1 images
216  *
217  *    - Added support for PCRE_UNGREEDY behaviour to pcrs,
218  *      which is selected by the (nonstandard and therefore
219  *      capital) letter 'U' in the option string.
220  *      It causes the quantifiers to be ungreedy by default.
221  *      Appending a ? turns back to greedy (!).
222  *
223  *    - Added a new interceptor ijb-send-banner, which
224  *      sends back the "Junkbuster" gif. Without imagelist or
225  *      MSIE detection support, or if tinygif = 1, or the
226  *      URL isn't recognized as an imageurl, a lame HTML
227  *      explanation is sent instead.
228  *
229  *    - Added new feature, which permits blocking remote
230  *      script redirects and firing back a local redirect
231  *      to the browser.
232  *      The feature is conditionally compiled, i.e. it
233  *      can be disabled with --disable-fast-redirects,
234  *      plus it must be activated by a "fast-redirects"
235  *      line in the config file, has its own log level
236  *      and of course wants to be displayed by show-proxy-args
237  *      Note: Boy, all the #ifdefs in 1001 locations and
238  *      all the fumbling with configure.in and acconfig.h
239  *      were *way* more work than the feature itself :-(
240  *
241  *    - Because a generic redirect template was needed for
242  *      this, tinygif = 3 now uses the same.
243  *
244  *    - Moved GIFs, and other static HTTP response templates
245  *      to project.h
246  *
247  *    - Some minor fixes
248  *
249  *    - Removed some >400 CRs again (Jon, you really worked
250  *      a lot! ;-)
251  *
252  *    Revision 1.4  2001/05/21 19:32:54  jongfoster
253  *    Added another #ifdef _WIN_CONSOLE
254  *
255  *    Revision 1.3  2001/05/20 01:11:40  jongfoster
256  *    Added support for LOG_LEVEL_FATAL
257  *    Renamed LOG_LEVEL_FRC to LOG_LEVEL_FORCE,
258  *    and LOG_LEVEL_REF to LOG_LEVEL_RE_FILTER
259  *
260  *    Revision 1.2  2001/05/17 22:42:01  oes
261  *     - Cleaned CRLF's from the sources and related files
262  *     - Repaired logging for REF and FRC
263  *
264  *    Revision 1.1.1.1  2001/05/15 13:58:51  oes
265  *    Initial import of version 2.9.3 source tree
266  *
267  *
268  *********************************************************************/
269 \f
270
271 #include "config.h"
272 #include "miscutil.h"
273
274 #include <stdlib.h>
275 #include <stdio.h>
276 #include <stdarg.h>
277 #include <string.h>
278
279 #if defined(HAVE_STRLCPY) && defined(HAVE_GETTIMEOFDAY)
280 #define USE_NEW_LOG_ERROR
281 /* For gettimeofday() */
282 #include <sys/time.h>
283 #endif /* defined(HAVE_STRLCPY) && defined(HAVE_GETTIMEOFDAY) */
284
285 #if !defined(_WIN32) && !defined(__OS2__)
286 #include <unistd.h>
287 #endif /* !defined(_WIN32) && !defined(__OS2__) */
288
289 #include <errno.h>
290 #include <assert.h>
291
292 #ifdef _WIN32
293 #ifndef STRICT
294 #define STRICT
295 #endif
296 #include <windows.h>
297 #ifndef _WIN_CONSOLE
298 #include "w32log.h"
299 #endif /* ndef _WIN_CONSOLE */
300 #endif /* def _WIN32 */
301 #ifdef _MSC_VER
302 #define inline __inline
303 #endif /* def _MSC_VER */
304
305 #ifdef __OS2__
306 #include <sys/socket.h> /* For sock_errno */
307 #define INCL_DOS
308 #include <os2.h>
309 #endif
310
311 #include "errlog.h"
312 #include "project.h"
313 #include "jcc.h"
314
315 const char errlog_h_rcs[] = ERRLOG_H_VERSION;
316
317
318 /*
319  * LOG_LEVEL_FATAL cannot be turned off.  (There are
320  * some exceptional situations where we need to get a
321  * message to the user).
322  */
323 #define LOG_LEVEL_MINIMUM  LOG_LEVEL_FATAL
324
325 /* where to log (default: stderr) */
326 static FILE *logfp = NULL;
327
328 /* logging detail level.  */
329 int debug = (LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);  
330
331 /* static functions */
332 static void fatal_error(const char * error_message);
333 #ifdef _WIN32
334 static char *w32_socket_strerr(int errcode, char *tmp_buf);
335 #endif
336 #ifdef __OS2__
337 static char *os2_socket_strerr(int errcode, char *tmp_buf);
338 #endif
339
340 #ifdef FEATURE_PTHREAD
341 static inline void lock_logfile()
342 {
343    pthread_mutex_lock(&log_mutex);
344 }
345 static inline void unlock_logfile()
346 {
347    pthread_mutex_unlock(&log_mutex);
348 }
349 static inline void lock_loginit()
350 {
351    pthread_mutex_lock(&log_init_mutex);
352 }
353 static inline void unlock_loginit()
354 {
355    pthread_mutex_unlock(&log_init_mutex);
356 }
357 #else /* ! FEATURE_PTHREAD */
358 /*
359  * FIXME we need a cross-platform locking mechanism.
360  * The locking/unlocking functions below should be 
361  * fleshed out for non-pthread implementations.
362  */ 
363 static inline void lock_logfile() {}
364 static inline void unlock_logfile() {}
365 static inline void lock_loginit() {}
366 static inline void unlock_loginit() {}
367 #endif
368
369 /*********************************************************************
370  *
371  * Function    :  fatal_error
372  *
373  * Description :  Displays a fatal error to standard error (or, on 
374  *                a WIN32 GUI, to a dialog box), and exits
375  *                JunkBuster with status code 1.
376  *
377  * Parameters  :
378  *          1  :  error_message = The error message to display.
379  *
380  * Returns     :  Does not return.
381  *
382  *********************************************************************/
383 static void fatal_error(const char * error_message)
384 {
385 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
386    MessageBox(g_hwndLogFrame, error_message, "Privoxy Error", 
387       MB_OK | MB_ICONERROR | MB_TASKMODAL | MB_SETFOREGROUND | MB_TOPMOST);  
388
389    /* Cleanup - remove taskbar icon etc. */
390    TermLogWindow();
391
392 #else /* if !defined(_WIN32) || defined(_WIN_CONSOLE) */
393    fputs(error_message, stderr);
394 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
395
396 #if defined(unix)
397    if(pidfile)
398    {
399       unlink(pidfile);
400    }
401 #endif /* unix */
402
403    exit(1);
404 }
405
406
407 /*********************************************************************
408  *
409  * Function    :  init_error_log
410  *
411  * Description :  Initializes the logging module.  Must call before
412  *                calling log_error.
413  *
414  * Parameters  :
415  *          1  :  prog_name  = The program name.
416  *          2  :  logfname   = The logfile name, or NULL for stderr.
417  *          3  :  debuglevel = The debugging level.
418  *
419  * Returns     :  N/A
420  *
421  *********************************************************************/
422 void init_error_log(const char *prog_name, const char *logfname, int debuglevel)
423 {
424    FILE *fp;
425
426    lock_loginit();
427
428    /* set the logging detail level */
429    debug = debuglevel | LOG_LEVEL_MINIMUM;
430
431    if ((logfp != NULL) && (logfp != stderr))
432    {
433       log_error(LOG_LEVEL_INFO, "(Re-)Open logfile %s", logfname ? logfname : "none");
434       lock_logfile();
435       fclose(logfp);
436    } else {
437       lock_logfile();
438    }
439    logfp = stderr;
440    unlock_logfile();
441
442    /* set the designated log file */
443    if( logfname )
444    {
445       if( NULL == (fp = fopen(logfname, "a")) )
446       {
447          log_error(LOG_LEVEL_FATAL, "init_error_log(): can't open logfile: %s", logfname);
448       }
449
450       /* set logging to be completely unbuffered */
451       setbuf(fp, NULL);
452
453       lock_logfile();
454       logfp = fp;
455       unlock_logfile();
456    }
457
458    log_error(LOG_LEVEL_INFO, "Privoxy version " VERSION);
459    if (prog_name != NULL)
460    {
461       log_error(LOG_LEVEL_INFO, "Program name: %s", prog_name);
462    }
463
464    unlock_loginit();
465
466 } /* init_error_log */
467
468 #if defined(USE_NEW_LOG_ERROR)
469 /*
470  * Use an alternative log_error version and its helper functions.
471  *
472  * The code is mostly copied from the old log_error
473  * function but it's divided into multiple functions,
474  * doesn't use strcpy, strcat or sprintf and compiles
475  * with gcc43 without warnings (on FreeBSD that is).
476  *
477  * It should behave like the old log_error function with
478  * two exceptions:
479  *
480  * - too long format strings are logged truncated instead
481  *   of completely replaced with the truncation warning,
482  * - its time stamps contain milliseconds.
483  */
484
485 /*********************************************************************
486  *
487  * Function    :  get_thread_id
488  *
489  * Description :  Returns a number that is different for each thread.
490  *
491  *                XXX: Should be moved elsewhere (miscutil.c?)
492  *                
493  * Parameters  :  None
494  *
495  * Returns     :  thread_id
496  *
497  *********************************************************************/
498 long get_thread_id(void)
499 {
500    long this_thread = 1;  /* was: pthread_t this_thread;*/
501
502 #ifdef __OS2__
503    PTIB     ptib;
504    APIRET   ulrc; /* XXX: I have no clue what this does */
505 #endif /* __OS2__ */
506
507    /* FIXME get current thread id */
508 #ifdef FEATURE_PTHREAD
509    this_thread = (long)pthread_self();
510 #ifdef __MACH__
511    /*
512     * Mac OSX (and perhaps other Mach instances) doesn't have a debuggable
513     * value at the first 4 bytes of pthread_self()'s return value, a pthread_t.
514     * pthread_t is supposed to be opaque... but it's fairly random, though, so
515     * we make it mostly presentable.
516     */
517    this_thread = abs(this_thread % 1000);
518 #endif /* def __MACH__ */
519 #elif defined(_WIN32)
520    this_thread = GetCurrentThreadId();
521 #elif defined(__OS2__)
522    ulrc = DosGetInfoBlocks(&ptib, NULL);
523    if (ulrc == 0)
524      this_thread = ptib -> tib_ptib2 -> tib2_ultid;
525 #endif /* def FEATURE_PTHREAD */
526
527    return this_thread;
528 }
529
530
531 /*********************************************************************
532  *
533  * Function    :  get_log_timestamp
534  *
535  * Description :  Generates the time stamp for the log message prefix.
536  *
537  * Parameters  :
538  *          1  :  buffer = Storage buffer
539  *          2  :  buffer_size = Size of storage buffer
540  *
541  * Returns     :  Number of written characters or 0 for error.
542  *
543  *********************************************************************/
544 static inline size_t get_log_timestamp(char *buffer, size_t buffer_size)
545 {
546    size_t length;
547    time_t now; 
548    struct tm tm_now;
549    struct timeval tv_now; /* XXX: stupid name */
550    gettimeofday(&tv_now, NULL);
551    long msecs = tv_now.tv_usec / 1000;
552    int msecs_length = 0;
553
554    time(&now);
555
556 #ifdef HAVE_LOCALTIME_R
557    tm_now = *localtime_r(&now, &tm_now);
558 #elif FEATURE_PTHREAD
559    pthread_mutex_lock(&localtime_mutex);
560    tm_now = *localtime(&now); 
561    pthread_mutex_unlock(&localtime_mutex);
562 #else
563    tm_now = *localtime(&now); 
564 #endif
565
566    length = strftime(buffer, buffer_size, "%b %d %H:%M:%S", &tm_now);
567    if (length > 0);
568    {
569       msecs_length = snprintf(buffer+length, buffer_size - length, ".%.3ld", msecs);               
570    }
571    if (msecs_length > 0)
572    {
573       length += (size_t)msecs_length;
574    }
575    else
576    {
577       length = 0;
578    }
579
580    return length;
581 }
582
583
584 /*********************************************************************
585  *
586  * Function    :  get_clf_timestamp
587  *
588  * Description :  Generates a Common Log Format time string.
589  *
590  * Parameters  :
591  *          1  :  buffer = Storage buffer
592  *          2  :  buffer_size = Size of storage buffer
593  *
594  * Returns     :  Number of written characters or 0 for error.
595  *
596  *********************************************************************/
597 static inline size_t get_clf_timestamp(char *buffer, size_t buffer_size)
598 {
599    /*
600     * Complex because not all OSs have tm_gmtoff or
601     * the %z field in strftime()
602     */
603    time_t now;
604    struct tm *tm_now; 
605    struct tm gmt;
606 #ifdef HAVE_LOCALTIME_R
607    struct tm dummy;
608 #endif
609    int days, hrs, mins;
610    size_t length;
611    int tz_length = 0;
612
613    time (&now); 
614 #ifdef HAVE_GMTIME_R
615    gmt = *gmtime_r(&now, &gmt);
616 #elif FEATURE_PTHREAD
617    pthread_mutex_lock(&gmtime_mutex);
618    gmt = *gmtime(&now);
619    pthread_mutex_unlock(&gmtime_mutex);
620 #else
621    gmt = *gmtime(&now);
622 #endif
623 #ifdef HAVE_LOCALTIME_R
624    tm_now = localtime_r(&now, &dummy);
625 #elif FEATURE_PTHREAD
626    pthread_mutex_lock(&localtime_mutex);
627    tm_now = localtime(&now); 
628    pthread_mutex_unlock(&localtime_mutex);
629 #else
630    tm_now = localtime(&now); 
631 #endif
632    days = tm_now->tm_yday - gmt.tm_yday; 
633    hrs = ((days < -1 ? 24 : 1 < days ? -24 : days * 24) + tm_now->tm_hour - gmt.tm_hour); 
634    mins = hrs * 60 + tm_now->tm_min - gmt.tm_min; 
635
636    length = strftime(buffer, buffer_size, "%d/%b/%Y:%H:%M:%S ", tm_now);
637
638    if (length > 0);
639    {
640       tz_length = snprintf(buffer+length, buffer_size-length,
641                      "%+03d%02d", mins / 60, abs(mins) % 60);
642    }
643    if (tz_length > 0)
644    {
645       length += (size_t)tz_length;
646    }
647    else
648    {
649       length = 0;
650    }
651
652    return length;
653 }
654
655
656 /*********************************************************************
657  *
658  * Function    :  get_log_level_string
659  *
660  * Description :  Translates a numerical loglevel into a string.
661  *
662  * Parameters  :  
663  *          1  :  loglevel = LOG_LEVEL_FOO
664  *
665  * Returns     :  Log level string.
666  *
667  *********************************************************************/
668 inline const char *get_log_level_string(int loglevel)
669 {
670    char *log_level_string = NULL;
671
672    assert(0 < loglevel);
673
674    switch (loglevel)
675    {
676       case LOG_LEVEL_ERROR:
677          log_level_string = "Error";
678          break;
679       case LOG_LEVEL_FATAL:
680          log_level_string = "Fatal error";
681          break;
682       case LOG_LEVEL_GPC:
683          log_level_string = "Request";
684          break;
685       case LOG_LEVEL_CONNECT:
686          log_level_string = "Connect";
687          break;
688       case LOG_LEVEL_LOG:
689          log_level_string = "Writing";
690          break;
691       case LOG_LEVEL_HEADER:
692          log_level_string = "Header";
693          break;
694       case LOG_LEVEL_INFO:
695          log_level_string = "Info";
696          break;
697       case LOG_LEVEL_RE_FILTER:
698          log_level_string = "Re-Filter";
699          break;
700 #ifdef FEATURE_FORCE_LOAD
701       case LOG_LEVEL_FORCE:
702          log_level_string = "Force";
703          break;
704 #endif /* def FEATURE_FORCE_LOAD */
705 #ifdef FEATURE_FAST_REDIRECTS
706       case LOG_LEVEL_REDIRECTS:
707          log_level_string = "Redirect";
708          break;
709 #endif /* def FEATURE_FAST_REDIRECTS */
710       case LOG_LEVEL_DEANIMATE:
711          log_level_string = "Gif-Deanimate";
712          break;
713 #ifdef FEATURE_KILL_POPUPS
714       case LOG_LEVEL_POPUPS:
715          log_level_string = "Kill-Popups";
716          break;
717 #endif /* def FEATURE_KILL_POPUPS */
718       case LOG_LEVEL_CGI:
719          log_level_string = "CGI";
720          break;
721       default:
722          log_level_string = "Unknown log level";
723          break;
724    }
725    assert(NULL != log_level_string);
726
727    return log_level_string;
728 }
729
730
731 /*********************************************************************
732  *
733  * Function    :  log_error
734  *
735  * Description :  This is the error-reporting and logging function.
736  *
737  * Parameters  :
738  *          1  :  loglevel  = the type of message to be logged
739  *          2  :  fmt       = the main string we want logged, printf-like
740  *          3  :  ...       = arguments to be inserted in fmt (printf-like).
741  *
742  * Returns     :  N/A
743  *
744  *********************************************************************/
745 void log_error(int loglevel, const char *fmt, ...)
746 {
747    va_list ap;
748    char *outbuf = NULL;
749    static char *outbuf_save = NULL;
750    char tempbuf[BUFFER_SIZE];
751    size_t length = 0;
752    const char * src = fmt;
753    long thread_id;
754    char timestamp[30];
755    /*
756     * XXX: Make this a config option,
757     * why else do we allocate instead of using
758     * an array?
759     */
760    size_t log_buffer_size = BUFFER_SIZE;
761
762 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
763    /*
764     * Irrespective of debug setting, a GET/POST/CONNECT makes
765     * the taskbar icon animate.  (There is an option to disable
766     * this but checking that is handled inside LogShowActivity()).
767     */
768    if (loglevel == LOG_LEVEL_GPC)
769    {
770       LogShowActivity();
771    }
772 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
773
774    /* verify if loglevel applies to current settings and bail out if negative */
775    if ((loglevel & debug) == 0)
776    {
777       return;
778    }
779
780    thread_id = get_thread_id();
781    get_log_timestamp(timestamp, sizeof(timestamp));
782
783    /* protect the whole function because of the static buffer (outbuf) */
784    lock_logfile();
785
786    if (NULL == outbuf_save) 
787    {
788       outbuf_save = (char*)zalloc(log_buffer_size + 1); /* +1 for paranoia */
789       if (NULL == outbuf_save)
790       {
791          snprintf(tempbuf, sizeof(tempbuf),
792             "%s Privoxy(%08lx) Fatal error: log_error() failed to allocate buffer memory.\n"
793             "\nExiting.", timestamp, thread_id);
794          if( !logfp )
795          {
796             logfp = stderr;
797          }
798          fputs(tempbuf, logfp);
799          unlock_logfile();
800          fatal_error(tempbuf); /* Exit */
801       }
802    }
803    outbuf = outbuf_save;
804
805    /*
806     * Memsetting the whole buffer to zero
807     * here make things easier later on.
808     */
809    memset(outbuf, 0, log_buffer_size);
810
811    /* Add prefix for everything but Common Log Format messages */
812    if (loglevel != LOG_LEVEL_CLF)
813    {
814       length = (size_t)snprintf(outbuf, log_buffer_size, "%s Privoxy(%08lx) %s: ",
815                                 timestamp, thread_id, get_log_level_string(loglevel));
816    }
817
818    /* get ready to scan var. args. */
819    va_start(ap, fmt);
820
821    /* build formatted message from fmt and var-args */
822    while ((*src) && (length < log_buffer_size-2))
823    {
824       const char *sval = NULL; /* %N string  */
825       int ival;                /* %N string length or an error code */
826       unsigned uval;           /* %u value */
827       long lval;               /* %l value */
828       unsigned long ulval;     /* %ul value */
829       char ch;
830       const char *format_string = tempbuf;
831
832       ch = *src++;
833       if (ch != '%')
834       {
835          outbuf[length++] = ch;
836          assert(outbuf[length] == '\0');
837          continue;
838       }
839       assert(outbuf[length] == '\0');
840       ch = *src++;
841       switch (ch) {
842          case '%':
843             tempbuf[0] = '%';
844             tempbuf[1] = '\0';
845             break;
846          case 'd':
847             ival = va_arg( ap, int );
848             snprintf(tempbuf, sizeof(tempbuf), "%d", ival);
849             break;
850          case 'u':
851             uval = va_arg( ap, unsigned );
852             snprintf(tempbuf, sizeof(tempbuf), "%u", uval);
853             break;
854          case 'l':
855             /* this is a modifier that must be followed by u or d */
856             ch = *src++;
857             if (ch == 'd')
858             {
859                lval = va_arg( ap, long );
860                snprintf(tempbuf, sizeof(tempbuf), "%ld", lval);
861             }
862             else if (ch == 'u')
863             {
864                ulval = va_arg( ap, unsigned long );
865                snprintf(tempbuf, sizeof(tempbuf), "%lu", ulval);
866             }
867             else
868             {
869                snprintf(tempbuf, sizeof(tempbuf), "Bad format string: \"%s\"", fmt);
870                loglevel = LOG_LEVEL_FATAL;
871             }
872             break;
873          case 'c':
874             /*
875              * Note that char paramaters are converted to int, so we need to
876              * pass "int" to va_arg.  (See K&R, 2nd ed, section A7.3.2, page 202)
877              */
878             tempbuf[0] = (char) va_arg(ap, int);
879             tempbuf[1] = '\0';
880             break;
881          case 's':
882             format_string = va_arg(ap, char *);
883             if (format_string == NULL)
884             {
885                format_string = "[null]";
886             }
887             break;
888          case 'N':
889             /*
890              * Non-standard: Print a counted unterminated string.
891              * Takes 2 parameters: int length, const char * string.
892              */
893             ival = va_arg(ap, int);
894             sval = va_arg(ap, char *);
895             if (sval == NULL)
896             {
897                format_string = "[null]";
898             }
899             else if (ival <= 0)
900             {
901                if (0 == ival)
902                {
903                   /* That's ok (but stupid) */
904                   tempbuf[0] = '\0';
905                }
906                else
907                {
908                   /*
909                    * That's not ok (and even more stupid)
910                    */
911                   assert(ival >= 0);
912                   format_string = "[counted string lenght < 0]";
913                }
914             }
915             else if (ival >= sizeof(tempbuf))
916             {
917                /*
918                 * String is too long, copy as much as possible.
919                 * It will be further truncated later.
920                 */
921                memcpy(tempbuf, sval, sizeof(tempbuf)-1);
922                tempbuf[sizeof(tempbuf)-1] = '\0';
923             }
924             else
925             {
926                memcpy(tempbuf, sval, (size_t) ival);
927                tempbuf[ival] = '\0';
928             }
929             break;
930          case 'E':
931             /* Non-standard: Print error code from errno */
932 #ifdef _WIN32
933             ival = WSAGetLastError();
934             format_string = w32_socket_strerr(ival, tempbuf);
935 #elif __OS2__
936             ival = sock_errno();
937             if (ival != 0)
938             {
939                format_string = os2_socket_strerr(ival, tempbuf);
940             }
941             else
942             {
943                ival = errno;
944                format_string = strerror(ival);
945             }
946 #else /* ifndef _WIN32 */
947             ival = errno; 
948 #ifdef HAVE_STRERROR
949             format_string = strerror(ival);
950 #else /* ifndef HAVE_STRERROR */
951             format_string = NULL;
952 #endif /* ndef HAVE_STRERROR */
953             if (sval == NULL)
954             {
955                snprintf(tempbuf, sizeof(tempbuf), "(errno = %d)", ival);
956             }
957 #endif /* ndef _WIN32 */
958             break;
959          case 'T':
960             /* Non-standard: Print a Common Log File timestamp */
961             get_clf_timestamp(tempbuf, sizeof(tempbuf));
962             break;
963          default:
964             snprintf(tempbuf, sizeof(tempbuf), "Bad format string: \"%s\"", fmt);
965             loglevel = LOG_LEVEL_FATAL;
966             break;
967       } /* switch( p ) */
968
969       assert(length < log_buffer_size);
970       length += strlcpy(outbuf + length, format_string, log_buffer_size - length);
971
972       if (length >= log_buffer_size-2)
973       {
974          static char warning[] = "... [too long, truncated]";
975
976          length = log_buffer_size - sizeof(warning) - 1;
977          length += strlcpy(outbuf + length, warning, log_buffer_size - length);
978          assert(length < log_buffer_size);
979
980          break;
981       }
982    } /* for( p ... ) */
983
984    /* done with var. args */
985    va_end(ap);
986
987    assert(length < log_buffer_size);
988    length += strlcpy(outbuf + length, "\n", log_buffer_size - length);
989
990    /* Some sanity checks */
991    if (!(length < log_buffer_size)
992     || !(outbuf[log_buffer_size-1] == '\0')
993     || !(outbuf[log_buffer_size] == '\0')
994       )
995    {
996       /* Repeat as assertions */
997       assert(length < log_buffer_size);
998       assert(outbuf[log_buffer_size-1] == '\0');
999       /*
1000        * outbuf's real size is log_buffer_size+1,
1001        * so while this looks like an off-by-one,
1002        * we're only checking our paranoia byte.
1003        */
1004       assert(outbuf[log_buffer_size] == '\0');
1005
1006       snprintf(outbuf, log_buffer_size,
1007          "%s Privoxy(%08lx) Fatal error: log_error()'s sanity checks failed. length: %u\n"
1008          "Exiting.", timestamp, thread_id, length);
1009       loglevel = LOG_LEVEL_FATAL;
1010    }
1011
1012    /* deal with glibc stupidity - it won't let you initialize logfp */
1013    /* XXX: Still necessary? */
1014    if(NULL == logfp)
1015    {
1016       logfp = stderr;
1017    }
1018
1019    fputs(outbuf_save, logfp);
1020
1021    if (loglevel == LOG_LEVEL_FATAL)
1022    {
1023       fatal_error(outbuf_save);
1024       /* Never get here */
1025    }
1026
1027    unlock_logfile();
1028
1029 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
1030    /* Write to display */
1031    LogPutString(outbuf_save);
1032 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
1033
1034 }
1035
1036 #else /* use traditional log_error version */
1037
1038 /*********************************************************************
1039  *
1040  * Function    :  log_error
1041  *
1042  * Description :  This is the error-reporting and logging function.
1043  *
1044  * Parameters  :
1045  *          1  :  loglevel  = the type of message to be logged
1046  *          2  :  fmt       = the main string we want logged, printf-like
1047  *          3  :  ...       = arguments to be inserted in fmt (printf-like).
1048  *
1049  * Returns     :  N/A
1050  *
1051  *********************************************************************/
1052 void log_error(int loglevel, const char *fmt, ...)
1053 {
1054    va_list ap;
1055    char *outbuf= NULL;
1056    static char *outbuf_save = NULL;
1057    const char * src = fmt;
1058    int outc = 0;
1059    long this_thread = 1;  /* was: pthread_t this_thread;*/
1060 #ifdef __OS2__
1061    PTIB     ptib;
1062    APIRET   ulrc;
1063 #endif /* __OS2__ */
1064
1065 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
1066    /*
1067     * Irrespective of debug setting, a GET/POST/CONNECT makes
1068     * the taskbar icon animate.  (There is an option to disable
1069     * this but checking that is handled inside LogShowActivity()).
1070     */
1071    if (loglevel == LOG_LEVEL_GPC)
1072    {
1073       LogShowActivity();
1074    }
1075 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
1076
1077    /* verify if loglevel applies to current settings and bail out if negative */
1078    if ((loglevel & debug) == 0)
1079    {
1080       return;
1081    }
1082
1083    /* protect the whole function because of the static buffer (outbuf) */
1084    lock_logfile();
1085
1086    /* FIXME get current thread id */
1087 #ifdef FEATURE_PTHREAD
1088    this_thread = (long)pthread_self();
1089 #ifdef __MACH__
1090    /*
1091     * Mac OSX (and perhaps other Mach instances) doesn't have a debuggable
1092     * value at the first 4 bytes of pthread_self()'s return value, a pthread_t.
1093     * pthread_t is supposed to be opaque... but it's fairly random, though, so
1094     * we make it mostly presentable.
1095     */
1096    this_thread = abs(this_thread % 1000);
1097 #endif /* def __MACH__ */
1098 #elif defined(_WIN32)
1099    this_thread = GetCurrentThreadId();
1100 #elif defined(__OS2__)
1101    ulrc = DosGetInfoBlocks(&ptib, NULL);
1102    if (ulrc == 0)
1103      this_thread = ptib -> tib_ptib2 -> tib2_ultid;
1104 #endif /* def FEATURE_PTHREAD */
1105
1106    if ( !outbuf_save ) 
1107    {
1108       outbuf_save = outbuf = (char*)malloc(BUFFER_SIZE);
1109       if (NULL == outbuf_save)
1110       {
1111          fatal_error("Privoxy failed to allocate log buffer.");
1112       }
1113    }
1114    outbuf = outbuf_save;
1115
1116     {
1117        /*
1118         * Write timestamp into tempbuf.
1119         *
1120         * Complex because not all OSs have tm_gmtoff or
1121         * the %z field in strftime()
1122         */
1123        time_t now; 
1124        struct tm tm_now; 
1125        time (&now);
1126 #ifdef HAVE_LOCALTIME_R
1127        tm_now = *localtime_r(&now, &tm_now);
1128 #elif FEATURE_PTHREAD
1129        pthread_mutex_lock(&localtime_mutex);
1130        tm_now = *localtime (&now); 
1131        pthread_mutex_unlock(&localtime_mutex);
1132 #else
1133        tm_now = *localtime (&now); 
1134 #endif
1135        strftime(outbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now); 
1136        outbuf += strlen( outbuf );
1137     }
1138    switch (loglevel)
1139    {
1140       case LOG_LEVEL_ERROR:
1141          outc = sprintf(outbuf, "Privoxy(%08lx) Error: ", this_thread);
1142          break;
1143       case LOG_LEVEL_FATAL:
1144          outc = sprintf(outbuf, "Privoxy(%08lx) Fatal error: ", this_thread);
1145          break;
1146       case LOG_LEVEL_GPC:
1147          outc = sprintf(outbuf, "Privoxy(%08lx) Request: ", this_thread);
1148          break;
1149       case LOG_LEVEL_CONNECT:
1150          outc = sprintf(outbuf, "Privoxy(%08lx) Connect: ", this_thread);
1151          break;
1152       case LOG_LEVEL_LOG:
1153          outc = sprintf(outbuf, "Privoxy(%08lx) Writing: ", this_thread);
1154          break;
1155       case LOG_LEVEL_HEADER:
1156          outc = sprintf(outbuf, "Privoxy(%08lx) Header: ", this_thread);
1157          break;
1158       case LOG_LEVEL_INFO:
1159          outc = sprintf(outbuf, "Privoxy(%08lx) Info: ", this_thread);
1160          break;
1161       case LOG_LEVEL_RE_FILTER:
1162          outc = sprintf(outbuf, "Privoxy(%08lx) Re-Filter: ", this_thread);
1163          break;
1164 #ifdef FEATURE_FORCE_LOAD
1165       case LOG_LEVEL_FORCE:
1166          outc = sprintf(outbuf, "Privoxy(%08lx) Force: ", this_thread);
1167          break;
1168 #endif /* def FEATURE_FORCE_LOAD */
1169 #ifdef FEATURE_FAST_REDIRECTS
1170       case LOG_LEVEL_REDIRECTS:
1171          outc = sprintf(outbuf, "Privoxy(%08lx) Redirect: ", this_thread);
1172          break;
1173 #endif /* def FEATURE_FAST_REDIRECTS */
1174       case LOG_LEVEL_DEANIMATE:
1175          outc = sprintf(outbuf, "Privoxy(%08lx) Gif-Deanimate: ", this_thread);
1176          break;
1177       case LOG_LEVEL_CLF:
1178          outbuf = outbuf_save;
1179          outc = 0;
1180          outbuf[0] = '\0';
1181          break;
1182 #ifdef FEATURE_KILL_POPUPS
1183       case LOG_LEVEL_POPUPS:
1184          outc = sprintf(outbuf, "Privoxy(%08lx) Kill-Popups: ", this_thread);
1185          break;
1186 #endif /* def FEATURE_KILL_POPUPS */
1187       case LOG_LEVEL_CGI:
1188          outc = sprintf(outbuf, "Privoxy(%08lx) CGI: ", this_thread);
1189          break;
1190       default:
1191          outc = sprintf(outbuf, "Privoxy(%08lx) UNKNOWN LOG TYPE(%d): ", this_thread, loglevel);
1192          break;
1193    }
1194    
1195    /* get ready to scan var. args. */
1196    va_start( ap, fmt );
1197
1198    /* build formatted message from fmt and var-args */
1199    while ((*src) && (outc < BUFFER_SIZE-2))
1200    {
1201       char tempbuf[BUFFER_SIZE];
1202       char *sval = NULL;
1203       int ival;
1204       unsigned uval;
1205       long lval;
1206       unsigned long ulval;
1207       int oldoutc;
1208       char ch;
1209       
1210       ch = *src++;
1211       if( ch != '%' )
1212       {
1213          outbuf[outc++] = ch;
1214          continue;
1215       }
1216
1217       ch = *src++;
1218       switch (ch) {
1219          case '%':
1220             outbuf[outc++] = '%';
1221             break;
1222          case 'd':
1223             ival = va_arg( ap, int );
1224             oldoutc = outc;
1225             outc += sprintf(tempbuf, "%d", ival);
1226             if (outc < BUFFER_SIZE-1) 
1227             {
1228                strcpy(outbuf + oldoutc, tempbuf);
1229             }
1230             else
1231             {
1232                outbuf[oldoutc] = '\0';
1233             }
1234             break;
1235          case 'u':
1236             uval = va_arg( ap, unsigned );
1237             oldoutc = outc;
1238             outc += sprintf(tempbuf, "%u", uval);
1239             if (outc < BUFFER_SIZE-1) 
1240             {
1241                strcpy(outbuf + oldoutc, tempbuf);
1242             }
1243             else
1244             {
1245                outbuf[oldoutc] = '\0';
1246             }
1247             break;
1248          case 'l':
1249             /* this is a modifier that must be followed by u or d */
1250             ch = *src++;
1251             if (ch == 'd')
1252             {
1253                lval = va_arg( ap, long );
1254                oldoutc = outc;
1255                outc += sprintf(tempbuf, "%ld", lval);
1256             }
1257             else if (ch == 'u')
1258             {
1259                ulval = va_arg( ap, unsigned long );
1260                oldoutc = outc;
1261                outc += sprintf(tempbuf, "%lu", ulval);
1262             }
1263             else
1264             {
1265                /* Error */
1266                sprintf(outbuf, "Privoxy(%08lx) Error: log_error(): Bad format string:\n"
1267                                "Format = \"%s\"\n"
1268                                "Exiting.", this_thread, fmt);
1269                if( !logfp )
1270                {
1271                   logfp = stderr;
1272                }
1273                fputs(outbuf, logfp);
1274                fatal_error(outbuf);
1275                /* Never get here */
1276                break;
1277             }
1278             if (outc < BUFFER_SIZE-1) 
1279             {
1280                strcpy(outbuf + oldoutc, tempbuf);
1281             }
1282             else
1283             {
1284                outbuf[oldoutc] = '\0';
1285             }
1286             break;
1287          case 'c':
1288             /*
1289              * Note that char paramaters are converted to int, so we need to
1290              * pass "int" to va_arg.  (See K&R, 2nd ed, section A7.3.2, page 202)
1291              */
1292             outbuf[outc++] = (char) va_arg( ap, int );
1293             break;
1294          case 's':
1295             sval = va_arg( ap, char * );
1296             if (sval == NULL)
1297             {
1298                sval = "[null]";
1299             }
1300             oldoutc = outc;
1301             outc += strlen(sval);
1302             if (outc < BUFFER_SIZE-1) 
1303             {
1304                strcpy(outbuf + oldoutc, sval);
1305             }
1306             else
1307             {
1308                outbuf[oldoutc] = '\0';
1309             }
1310             break;
1311          case 'N':
1312             /* Non-standard: Print a counted string.  Takes 2 parameters:
1313              * int length, const char * string
1314              */
1315             ival = va_arg( ap, int );
1316             sval = va_arg( ap, char * );
1317             if (sval == NULL)
1318             {
1319                sval = "[null]";
1320             }
1321             if (ival < 0)
1322             {
1323                ival = 0;
1324             }
1325             oldoutc = outc;
1326             outc += ival;
1327             if (outc < BUFFER_SIZE-1)
1328             {
1329                memcpy(outbuf + oldoutc, sval, (size_t) ival);
1330             }
1331             else
1332             {
1333                outbuf[oldoutc] = '\0';
1334             }
1335             break;
1336          case 'E':
1337             /* Non-standard: Print error code from errno */
1338 #ifdef _WIN32
1339             ival = WSAGetLastError();
1340             sval = w32_socket_strerr(ival, tempbuf);
1341 #elif __OS2__
1342             ival = sock_errno();
1343             if (ival != 0)
1344               sval = os2_socket_strerr(ival, tempbuf);
1345             else
1346             {
1347               ival = errno;
1348               sval = strerror(ival);
1349             }
1350 #else /* ifndef _WIN32 */
1351             ival = errno; 
1352 #ifdef HAVE_STRERROR
1353             sval = strerror(ival);
1354 #else /* ifndef HAVE_STRERROR */
1355             sval = NULL;
1356 #endif /* ndef HAVE_STRERROR */
1357             if (sval == NULL)
1358             {
1359                sprintf(tempbuf, "(errno = %d)", ival);
1360                sval = tempbuf;
1361             }
1362 #endif /* ndef _WIN32 */
1363             oldoutc = outc;
1364             outc += strlen(sval);
1365             if (outc < BUFFER_SIZE-1) 
1366             {
1367                strcpy(outbuf + oldoutc, sval);
1368             }
1369             else
1370             {
1371                outbuf[oldoutc] = '\0';
1372             }
1373             break;
1374          case 'T':
1375             /* Non-standard: Print a Common Log File timestamp */
1376             {
1377                /*
1378                 * Write timestamp into tempbuf.
1379                 *
1380                 * Complex because not all OSs have tm_gmtoff or
1381                 * the %z field in strftime()
1382                 */
1383                time_t now; 
1384                struct tm *tm_now; 
1385                struct tm gmt;
1386 #ifdef HAVE_LOCALTIME_R
1387                struct tm dummy;
1388 #endif
1389                int days, hrs, mins; 
1390                time (&now); 
1391 #ifdef HAVE_GMTIME_R
1392                gmt = *gmtime_r(&now, &gmt);
1393 #elif FEATURE_PTHREAD
1394                pthread_mutex_lock(&gmtime_mutex);
1395                gmt = *gmtime(&now);
1396                pthread_mutex_unlock(&gmtime_mutex);
1397 #else
1398                gmt = *gmtime(&now);
1399 #endif
1400 #ifdef HAVE_LOCALTIME_R
1401                tm_now = localtime_r(&now, &dummy);
1402 #elif FEATURE_PTHREAD
1403                pthread_mutex_lock(&localtime_mutex);
1404                tm_now = localtime (&now); 
1405                pthread_mutex_unlock(&localtime_mutex);
1406 #else
1407                tm_now = localtime (&now); 
1408 #endif
1409                days = tm_now->tm_yday - gmt.tm_yday; 
1410                hrs = ((days < -1 ? 24 : 1 < days ? -24 : days * 24) + tm_now->tm_hour - gmt.tm_hour); 
1411                mins = hrs * 60 + tm_now->tm_min - gmt.tm_min; 
1412                strftime (tempbuf, BUFFER_SIZE-6, "%d/%b/%Y:%H:%M:%S ", tm_now); 
1413                sprintf (tempbuf + strlen(tempbuf), "%+03d%02d", mins / 60, abs(mins) % 60); 
1414             }
1415             oldoutc = outc;
1416             outc += strlen(tempbuf);
1417             if (outc < BUFFER_SIZE-1) 
1418             {
1419                strcpy(outbuf + oldoutc, tempbuf);
1420             }
1421             else
1422             {
1423                outbuf[oldoutc] = '\0';
1424             }
1425             break;
1426          default:
1427             sprintf(outbuf, "Privoxy(%08lx) Error: log_error(): Bad format string:\n"
1428                             "Format = \"%s\"\n"
1429                             "Exiting.", this_thread, fmt);
1430             if( !logfp )
1431             {
1432                logfp = stderr;
1433             }
1434             fputs(outbuf_save, logfp);
1435             unlock_logfile();
1436             fatal_error(outbuf_save);
1437             /* Never get here */
1438             break;
1439
1440       } /* switch( p ) */
1441
1442    } /* for( p ... ) */
1443    
1444    /* done with var. args */
1445    va_end( ap );
1446    
1447    if (outc >= BUFFER_SIZE-2)
1448    {
1449       /* insufficient room for newline and trailing null. */
1450
1451       static const char warning[] = "... [too long, truncated]\n";
1452
1453       if (outc < BUFFER_SIZE)
1454       {
1455          /* Need to add terminating null in this case. */
1456          outbuf[outc] = '\0';
1457       }
1458
1459       /* Truncate output */
1460       outbuf[BUFFER_SIZE - sizeof(warning)] = '\0';
1461
1462       /* Append warning */
1463       strcat(outbuf, warning);
1464    }
1465    else
1466    {
1467       /* Add terminating newline and null */
1468       outbuf[outc++] = '\n';
1469       outbuf[outc] = '\0';
1470    }
1471
1472    /* deal with glibc stupidity - it won't let you initialize logfp */
1473    if( !logfp )
1474    {
1475       logfp = stderr;
1476    }
1477
1478    fputs(outbuf_save, logfp);
1479
1480    if (loglevel == LOG_LEVEL_FATAL)
1481    {
1482       fatal_error(outbuf_save);
1483       /* Never get here */
1484    }
1485
1486    unlock_logfile();
1487
1488 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
1489    /* Write to display */
1490    LogPutString(outbuf_save);
1491 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
1492
1493 }
1494 #endif /* defined(USE_NEW_LOG_ERROR) */
1495
1496
1497 #ifdef _WIN32
1498 /*********************************************************************
1499  *
1500  * Function    :  w32_socket_strerr
1501  *
1502  * Description :  Translate the return value from WSAGetLastError()
1503  *                into a string.
1504  *
1505  * Parameters  :
1506  *          1  :  errcode = The return value from WSAGetLastError().
1507  *          2  :  tmp_buf = A temporary buffer that might be used to
1508  *                          store the string.
1509  *
1510  * Returns     :  String representing the error code.  This may be
1511  *                a global string constant or a string stored in
1512  *                tmp_buf.
1513  *
1514  *********************************************************************/
1515 static char *w32_socket_strerr(int errcode, char *tmp_buf)
1516 {
1517 #define TEXT_FOR_ERROR(code,text) \
1518    if (errcode == code)           \
1519    {                              \
1520       return #code " - " text;    \
1521    }
1522
1523    TEXT_FOR_ERROR(WSAEACCES, "Permission denied")
1524    TEXT_FOR_ERROR(WSAEADDRINUSE, "Address already in use.")
1525    TEXT_FOR_ERROR(WSAEADDRNOTAVAIL, "Cannot assign requested address.");
1526    TEXT_FOR_ERROR(WSAEAFNOSUPPORT, "Address family not supported by protocol family.");
1527    TEXT_FOR_ERROR(WSAEALREADY, "Operation already in progress.");
1528    TEXT_FOR_ERROR(WSAECONNABORTED, "Software caused connection abort.");
1529    TEXT_FOR_ERROR(WSAECONNREFUSED, "Connection refused.");
1530    TEXT_FOR_ERROR(WSAECONNRESET, "Connection reset by peer.");
1531    TEXT_FOR_ERROR(WSAEDESTADDRREQ, "Destination address required.");
1532    TEXT_FOR_ERROR(WSAEFAULT, "Bad address.");
1533    TEXT_FOR_ERROR(WSAEHOSTDOWN, "Host is down.");
1534    TEXT_FOR_ERROR(WSAEHOSTUNREACH, "No route to host.");
1535    TEXT_FOR_ERROR(WSAEINPROGRESS, "Operation now in progress.");
1536    TEXT_FOR_ERROR(WSAEINTR, "Interrupted function call.");
1537    TEXT_FOR_ERROR(WSAEINVAL, "Invalid argument.");
1538    TEXT_FOR_ERROR(WSAEISCONN, "Socket is already connected.");
1539    TEXT_FOR_ERROR(WSAEMFILE, "Too many open sockets.");
1540    TEXT_FOR_ERROR(WSAEMSGSIZE, "Message too long.");
1541    TEXT_FOR_ERROR(WSAENETDOWN, "Network is down.");
1542    TEXT_FOR_ERROR(WSAENETRESET, "Network dropped connection on reset.");
1543    TEXT_FOR_ERROR(WSAENETUNREACH, "Network is unreachable.");
1544    TEXT_FOR_ERROR(WSAENOBUFS, "No buffer space available.");
1545    TEXT_FOR_ERROR(WSAENOPROTOOPT, "Bad protocol option.");
1546    TEXT_FOR_ERROR(WSAENOTCONN, "Socket is not connected.");
1547    TEXT_FOR_ERROR(WSAENOTSOCK, "Socket operation on non-socket.");
1548    TEXT_FOR_ERROR(WSAEOPNOTSUPP, "Operation not supported.");
1549    TEXT_FOR_ERROR(WSAEPFNOSUPPORT, "Protocol family not supported.");
1550    TEXT_FOR_ERROR(WSAEPROCLIM, "Too many processes.");
1551    TEXT_FOR_ERROR(WSAEPROTONOSUPPORT, "Protocol not supported.");
1552    TEXT_FOR_ERROR(WSAEPROTOTYPE, "Protocol wrong type for socket.");
1553    TEXT_FOR_ERROR(WSAESHUTDOWN, "Cannot send after socket shutdown.");
1554    TEXT_FOR_ERROR(WSAESOCKTNOSUPPORT, "Socket type not supported.");
1555    TEXT_FOR_ERROR(WSAETIMEDOUT, "Connection timed out.");
1556    TEXT_FOR_ERROR(WSAEWOULDBLOCK, "Resource temporarily unavailable.");
1557    TEXT_FOR_ERROR(WSAHOST_NOT_FOUND, "Host not found.");
1558    TEXT_FOR_ERROR(WSANOTINITIALISED, "Successful WSAStartup not yet performed.");
1559    TEXT_FOR_ERROR(WSANO_DATA, "Valid name, no data record of requested type.");
1560    TEXT_FOR_ERROR(WSANO_RECOVERY, "This is a non-recoverable error.");
1561    TEXT_FOR_ERROR(WSASYSNOTREADY, "Network subsystem is unavailable.");
1562    TEXT_FOR_ERROR(WSATRY_AGAIN, "Non-authoritative host not found.");
1563    TEXT_FOR_ERROR(WSAVERNOTSUPPORTED, "WINSOCK.DLL version out of range.");
1564    TEXT_FOR_ERROR(WSAEDISCON, "Graceful shutdown in progress.");
1565    /*
1566     * The following error codes are documented in the Microsoft WinSock
1567     * reference guide, but don't actually exist.
1568     *
1569     * TEXT_FOR_ERROR(WSA_INVALID_HANDLE, "Specified event object handle is invalid.");
1570     * TEXT_FOR_ERROR(WSA_INVALID_PARAMETER, "One or more parameters are invalid.");
1571     * TEXT_FOR_ERROR(WSAINVALIDPROCTABLE, "Invalid procedure table from service provider.");
1572     * TEXT_FOR_ERROR(WSAINVALIDPROVIDER, "Invalid service provider version number.");
1573     * TEXT_FOR_ERROR(WSA_IO_PENDING, "Overlapped operations will complete later.");
1574     * TEXT_FOR_ERROR(WSA_IO_INCOMPLETE, "Overlapped I/O event object not in signaled state.");
1575     * TEXT_FOR_ERROR(WSA_NOT_ENOUGH_MEMORY, "Insufficient memory available.");
1576     * TEXT_FOR_ERROR(WSAPROVIDERFAILEDINIT, "Unable to initialize a service provider.");
1577     * TEXT_FOR_ERROR(WSASYSCALLFAILURE, "System call failure.");
1578     * TEXT_FOR_ERROR(WSA_OPERATION_ABORTED, "Overlapped operation aborted.");
1579     */
1580
1581    sprintf(tmp_buf, "(error number %d)", errcode);
1582    return tmp_buf;
1583 }
1584 #endif /* def _WIN32 */
1585
1586
1587 #ifdef __OS2__
1588 /*********************************************************************
1589  *
1590  * Function    :  os2_socket_strerr
1591  *
1592  * Description :  Translate the return value from sock_errno()
1593  *                into a string.
1594  *
1595  * Parameters  :
1596  *          1  :  errcode = The return value from sock_errno().
1597  *          2  :  tmp_buf = A temporary buffer that might be used to
1598  *                          store the string.
1599  *
1600  * Returns     :  String representing the error code.  This may be
1601  *                a global string constant or a string stored in
1602  *                tmp_buf.
1603  *
1604  *********************************************************************/
1605 static char *os2_socket_strerr(int errcode, char *tmp_buf)
1606 {
1607 #define TEXT_FOR_ERROR(code,text) \
1608    if (errcode == code)           \
1609    {                              \
1610       return #code " - " text;    \
1611    }
1612
1613    TEXT_FOR_ERROR(SOCEPERM          , "Not owner.")
1614    TEXT_FOR_ERROR(SOCESRCH          , "No such process.")
1615    TEXT_FOR_ERROR(SOCEINTR          , "Interrupted system call.")
1616    TEXT_FOR_ERROR(SOCENXIO          , "No such device or address.")
1617    TEXT_FOR_ERROR(SOCEBADF          , "Bad file number.")
1618    TEXT_FOR_ERROR(SOCEACCES         , "Permission denied.")
1619    TEXT_FOR_ERROR(SOCEFAULT         , "Bad address.")
1620    TEXT_FOR_ERROR(SOCEINVAL         , "Invalid argument.")
1621    TEXT_FOR_ERROR(SOCEMFILE         , "Too many open files.")
1622    TEXT_FOR_ERROR(SOCEPIPE          , "Broken pipe.")
1623    TEXT_FOR_ERROR(SOCEWOULDBLOCK    , "Operation would block.")
1624    TEXT_FOR_ERROR(SOCEINPROGRESS    , "Operation now in progress.")
1625    TEXT_FOR_ERROR(SOCEALREADY       , "Operation already in progress.")
1626    TEXT_FOR_ERROR(SOCENOTSOCK       , "Socket operation on non-socket.")
1627    TEXT_FOR_ERROR(SOCEDESTADDRREQ   , "Destination address required.")
1628    TEXT_FOR_ERROR(SOCEMSGSIZE       , "Message too long.")
1629    TEXT_FOR_ERROR(SOCEPROTOTYPE     , "Protocol wrong type for socket.")
1630    TEXT_FOR_ERROR(SOCENOPROTOOPT    , "Protocol not available.")
1631    TEXT_FOR_ERROR(SOCEPROTONOSUPPORT, "Protocol not supported.")
1632    TEXT_FOR_ERROR(SOCESOCKTNOSUPPORT, "Socket type not supported.")
1633    TEXT_FOR_ERROR(SOCEOPNOTSUPP     , "Operation not supported.")
1634    TEXT_FOR_ERROR(SOCEPFNOSUPPORT   , "Protocol family not supported.")
1635    TEXT_FOR_ERROR(SOCEAFNOSUPPORT   , "Address family not supported by protocol family.")
1636    TEXT_FOR_ERROR(SOCEADDRINUSE     , "Address already in use.")
1637    TEXT_FOR_ERROR(SOCEADDRNOTAVAIL  , "Can't assign requested address.")
1638    TEXT_FOR_ERROR(SOCENETDOWN       , "Network is down.")
1639    TEXT_FOR_ERROR(SOCENETUNREACH    , "Network is unreachable.")
1640    TEXT_FOR_ERROR(SOCENETRESET      , "Network dropped connection on reset.")
1641    TEXT_FOR_ERROR(SOCECONNABORTED   , "Software caused connection abort.")
1642    TEXT_FOR_ERROR(SOCECONNRESET     , "Connection reset by peer.")
1643    TEXT_FOR_ERROR(SOCENOBUFS        , "No buffer space available.")
1644    TEXT_FOR_ERROR(SOCEISCONN        , "Socket is already connected.")
1645    TEXT_FOR_ERROR(SOCENOTCONN       , "Socket is not connected.")
1646    TEXT_FOR_ERROR(SOCESHUTDOWN      , "Can't send after socket shutdown.")
1647    TEXT_FOR_ERROR(SOCETOOMANYREFS   , "Too many references: can't splice.")
1648    TEXT_FOR_ERROR(SOCETIMEDOUT      , "Operation timed out.")
1649    TEXT_FOR_ERROR(SOCECONNREFUSED   , "Connection refused.")
1650    TEXT_FOR_ERROR(SOCELOOP          , "Too many levels of symbolic links.")
1651    TEXT_FOR_ERROR(SOCENAMETOOLONG   , "File name too long.")
1652    TEXT_FOR_ERROR(SOCEHOSTDOWN      , "Host is down.")
1653    TEXT_FOR_ERROR(SOCEHOSTUNREACH   , "No route to host.")
1654    TEXT_FOR_ERROR(SOCENOTEMPTY      , "Directory not empty.")
1655    TEXT_FOR_ERROR(SOCEOS2ERR        , "OS/2 Error.")
1656
1657    sprintf(tmp_buf, "(error number %d)", errcode);
1658    return tmp_buf;
1659 }
1660 #endif /* def __OS2__ */
1661
1662
1663 /*
1664   Local Variables:
1665   tab-width: 3
1666   end:
1667 */