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