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