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