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