1 const char errlog_rcs[] = "$Id: errlog.c,v 1.70 2008/06/28 17:10:29 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/errlog.c,v $
6 * Purpose : Log errors to a designated destination in an elegant,
9 * Copyright : Written by and Copyright (C) 2001-2007 the SourceForge
10 * Privoxy team. http://www.privoxy.org/
12 * Based on the Internet Junkbuster originally written
13 * by and Copyright (C) 1997 Anonymous Coders and
14 * Junkbusters Corporation. http://www.junkbusters.com
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.
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.
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.
36 * Revision 1.70 2008/06/28 17:10:29 fabiankeil
37 * Remove stray semicolon in get_log_timestamp().
38 * Reported by Jochen Voss in #2005221.
40 * Revision 1.69 2008/05/30 15:55:25 fabiankeil
41 * Declare variable "debug" static and complain about its name.
43 * Revision 1.68 2008/04/27 16:50:46 fabiankeil
44 * Remove an incorrect assertion. The value of debug may change if
45 * the configuration is reloaded in another thread. While we could
46 * cache the initial value, the assertion doesn't seem worth it.
48 * Revision 1.67 2008/03/27 18:27:23 fabiankeil
49 * Remove kill-popups action.
51 * Revision 1.66 2008/01/31 15:38:14 fabiankeil
52 * - Make the logfp assertion more strict. As of 1.63, the "||" could
53 * have been an "&&", which means we can use two separate assertions
54 * and skip on of them on Windows.
55 * - Break a long commit message line in two.
57 * Revision 1.65 2008/01/31 14:44:33 fabiankeil
58 * Use (a != b) instead of !(a == b) so the sanity check looks less insane.
60 * Revision 1.64 2008/01/21 18:56:46 david__schmidt
61 * Swap #def from negative to positive, re-joined it so it didn't
62 * span an assertion (compilation failure on OS/2)
64 * Revision 1.63 2007/12/15 19:49:32 fabiankeil
65 * Stop overloading logfile to control the mingw32 log window as well.
66 * It's no longer necessary now that we disable all debug lines by default
67 * and at least one user perceived it as a regression (added in 1.55).
69 * Revision 1.62 2007/11/30 15:33:46 fabiankeil
70 * Unbreak LOG_LEVEL_FATAL. It wasn't fatal with logging disabled
71 * and on mingw32 fatal log messages didn't end up in the log file.
73 * Revision 1.61 2007/11/04 19:03:01 fabiankeil
74 * Fix another deadlock Hal spotted and that mysteriously didn't affect FreeBSD.
76 * Revision 1.60 2007/11/03 19:03:31 fabiankeil
77 * - Prevent the Windows GUI from showing the version two times in a row.
78 * - Stop using the imperative in the "(Re-)Open logfile" message.
79 * - Ditch the "Switching to daemon mode" message as the detection
80 * whether or not we're already in daemon mode doesn't actually work.
82 * Revision 1.59 2007/11/01 12:50:56 fabiankeil
83 * Here's looking at you, deadlock.
85 * Revision 1.58 2007/10/28 19:04:21 fabiankeil
86 * Don't mention daemon mode in "Logging disabled" message. Some
87 * platforms call it differently and it's not really relevant anyway.
89 * Revision 1.57 2007/10/27 13:02:26 fabiankeil
90 * Relocate daemon-mode-related log messages to make sure
91 * they aren't shown again in case of configuration reloads.
93 * Revision 1.56 2007/10/14 14:26:56 fabiankeil
94 * Remove the old log_error() version.
96 * Revision 1.55 2007/10/14 14:12:41 fabiankeil
97 * When in daemon mode, close stderr after the configuration file has been
98 * parsed the first time. If logfile isn't set, stop logging. Fixes BR#897436.
100 * Revision 1.54 2007/09/22 16:15:34 fabiankeil
101 * - Let it compile with pcc.
102 * - Move our includes below system includes to prevent macro conflicts.
104 * Revision 1.53 2007/08/05 13:53:14 fabiankeil
105 * #1763173 from Stefan Huehner: declare some more functions
106 * static and use void instead of empty parameter lists.
108 * Revision 1.52 2007/07/14 07:28:47 fabiankeil
109 * Add translation function for JB_ERR_FOO codes.
111 * Revision 1.51 2007/05/11 11:51:34 fabiankeil
112 * Fix a type mismatch warning.
114 * Revision 1.50 2007/04/11 10:55:44 fabiankeil
115 * Enforce some assertions that could be triggered
116 * on mingw32 and other systems where we use threads
119 * Revision 1.49 2007/04/08 16:44:15 fabiankeil
120 * We need <sys/time.h> for gettimeofday(), not <time.h>.
122 * Revision 1.48 2007/03/31 13:33:28 fabiankeil
123 * Add alternative log_error() with timestamps
124 * that contain milliseconds and without using
125 * strcpy(), strcat() or sprintf().
127 * Revision 1.47 2006/11/28 15:25:15 fabiankeil
128 * Only unlink the pidfile if it's actually used.
130 * Revision 1.46 2006/11/13 19:05:51 fabiankeil
131 * Make pthread mutex locking more generic. Instead of
132 * checking for OSX and OpenBSD, check for FEATURE_PTHREAD
133 * and use mutex locking unless there is an _r function
134 * available. Better safe than sorry.
136 * Fixes "./configure --disable-pthread" and should result
137 * in less threading-related problems on pthread-using platforms,
138 * but it still doesn't fix BR#1122404.
140 * Revision 1.45 2006/08/21 11:15:54 david__schmidt
141 * MS Visual C++ build updates
143 * Revision 1.44 2006/08/18 16:03:16 david__schmidt
144 * Tweak for OS/2 build happiness.
146 * Revision 1.43 2006/08/03 02:46:41 david__schmidt
147 * Incorporate Fabian Keil's patch work:
148 * http://www.fabiankeil.de/sourcecode/privoxy/
150 * Revision 1.42 2006/07/18 14:48:46 david__schmidt
151 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
152 * with what was really the latest development (the v_3_0_branch branch)
154 * Revision 1.40.2.4 2005/04/03 20:10:50 david__schmidt
155 * Thanks to Jindrich Makovicka for a race condition fix for the log
156 * file. The race condition remains for non-pthread implementations.
157 * Reference patch #1175720.
159 * Revision 1.40.2.3 2003/03/07 03:41:04 david__schmidt
160 * Wrapping all *_r functions (the non-_r versions of them) with mutex
161 * semaphores for OSX. Hopefully this will take care of all of those pesky
164 * Revision 1.40.2.2 2002/09/28 00:30:57 david__schmidt
165 * Update error logging to give sane values for thread IDs on Mach kernels.
166 * It's still a hack, but at least it looks farily normal. We print the
167 * absolute value of the first 4 bytes of the pthread_t modded with 1000.
169 * Revision 1.40.2.1 2002/09/25 12:47:42 oes
170 * Make log_error safe against NULL string arguments
172 * Revision 1.40 2002/05/22 01:27:27 david__schmidt
174 * Add os2_socket_strerr mirroring w32_socket_strerr.
176 * Revision 1.39 2002/04/03 17:15:27 gliptak
177 * zero padding thread ids in log
179 * Revision 1.38 2002/03/31 17:18:59 jongfoster
180 * Win32 only: Enabling STRICT to fix a VC++ compile warning.
182 * Revision 1.37 2002/03/27 14:32:43 david__schmidt
183 * More compiler warning message maintenance
185 * Revision 1.36 2002/03/26 22:29:54 swa
186 * we have a new homepage!
188 * Revision 1.35 2002/03/24 15:23:33 jongfoster
191 * Revision 1.34 2002/03/24 13:25:43 swa
192 * name change related issues
194 * Revision 1.33 2002/03/13 00:27:04 jongfoster
197 * Revision 1.32 2002/03/07 03:46:17 oes
198 * Fixed compiler warnings
200 * Revision 1.31 2002/03/06 23:02:57 jongfoster
203 * Revision 1.30 2002/03/05 22:43:45 david__schmidt
204 * - Better error reporting on OS/2
205 * - Fix double-slash comment (oops)
207 * Revision 1.29 2002/03/04 23:45:13 jongfoster
208 * Printing thread ID if using Win32 native threads
210 * Revision 1.28 2002/03/04 17:59:59 oes
211 * Deleted deletePidFile(), cosmetics
213 * Revision 1.27 2002/03/04 02:08:01 david__schmidt
214 * Enable web editing of actions file on OS/2 (it had been broken all this time!)
216 * Revision 1.26 2002/01/09 19:05:45 steudten
217 * Fix big memory leak.
219 * Revision 1.25 2002/01/09 14:32:08 oes
220 * Added support for gmtime_r and localtime_r.
222 * Revision 1.24 2001/12/30 14:07:32 steudten
223 * - Add signal handling (unix)
224 * - Add SIGHUP handler (unix)
225 * - Add creation of pidfile (unix)
226 * - Add action 'top' in rc file (RH)
227 * - Add entry 'SIGNALS' to manpage
228 * - Add exit message to logfile (unix)
230 * Revision 1.23 2001/11/07 00:02:13 steudten
231 * Add line number in error output for lineparsing for
232 * actionsfile and configfile.
233 * Special handling for CLF added.
235 * Revision 1.22 2001/11/05 23:43:05 steudten
236 * Add time+date to log files.
238 * Revision 1.21 2001/10/25 03:40:47 david__schmidt
239 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
240 * threads to call select() simultaneously. So, it's time to do a real, live,
241 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
242 * (native). Both versions will work, but using __OS2__ offers multi-threading.
244 * Revision 1.20 2001/09/16 23:04:34 jongfoster
247 * Revision 1.19 2001/09/13 20:08:06 jongfoster
248 * Adding support for LOG_LEVEL_CGI
250 * Revision 1.18 2001/09/10 11:27:24 oes
251 * Declaration of w32_socket_strerr now conditional
253 * Revision 1.17 2001/09/10 10:17:13 oes
254 * Removed unused variable; Fixed sprintf format
256 * Revision 1.16 2001/07/30 22:08:36 jongfoster
257 * Tidying up #defines:
258 * - All feature #defines are now of the form FEATURE_xxx
259 * - Permanently turned off WIN_GUI_EDIT
260 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
262 * Revision 1.15 2001/07/29 17:41:10 jongfoster
263 * Now prints thread ID for each message (pthreads only)
265 * Revision 1.14 2001/07/19 19:03:48 haroon
266 * - Added case for LOG_LEVEL_POPUPS
268 * Revision 1.13 2001/07/13 13:58:58 oes
269 * - Added case for LOG_LEVEL_DEANIMATE
270 * - Removed all #ifdef PCRS
272 * Revision 1.12 2001/06/09 10:55:28 jongfoster
273 * Changing BUFSIZ ==> BUFFER_SIZE
275 * Revision 1.11 2001/06/01 18:14:49 jongfoster
276 * Changing the calls to strerr() to check HAVE_STRERR (which is defined
277 * in config.h if appropriate) rather than the NO_STRERR macro.
279 * Revision 1.10 2001/05/29 11:52:21 oes
280 * Conditional compilation of w32_socket_error
282 * Revision 1.9 2001/05/28 16:15:17 jongfoster
283 * Improved reporting of errors under Win32.
285 * Revision 1.8 2001/05/26 17:25:14 jongfoster
286 * Added support for CLF (Common Log Format) and fixed LOG_LEVEL_LOG
288 * Revision 1.7 2001/05/26 15:21:28 jongfoster
289 * Activity animation in Win32 GUI now works even if debug==0
291 * Revision 1.6 2001/05/25 21:55:08 jongfoster
292 * Now cleans up properly on FATAL (removes taskbar icon etc)
294 * Revision 1.5 2001/05/22 18:46:04 oes
296 * - Enabled filtering banners by size rather than URL
297 * by adding patterns that replace all standard banner
298 * sizes with the "Junkbuster" gif to the re_filterfile
300 * - Enabled filtering WebBugs by providing a pattern
301 * which kills all 1x1 images
303 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
304 * which is selected by the (nonstandard and therefore
305 * capital) letter 'U' in the option string.
306 * It causes the quantifiers to be ungreedy by default.
307 * Appending a ? turns back to greedy (!).
309 * - Added a new interceptor ijb-send-banner, which
310 * sends back the "Junkbuster" gif. Without imagelist or
311 * MSIE detection support, or if tinygif = 1, or the
312 * URL isn't recognized as an imageurl, a lame HTML
313 * explanation is sent instead.
315 * - Added new feature, which permits blocking remote
316 * script redirects and firing back a local redirect
318 * The feature is conditionally compiled, i.e. it
319 * can be disabled with --disable-fast-redirects,
320 * plus it must be activated by a "fast-redirects"
321 * line in the config file, has its own log level
322 * and of course wants to be displayed by show-proxy-args
323 * Note: Boy, all the #ifdefs in 1001 locations and
324 * all the fumbling with configure.in and acconfig.h
325 * were *way* more work than the feature itself :-(
327 * - Because a generic redirect template was needed for
328 * this, tinygif = 3 now uses the same.
330 * - Moved GIFs, and other static HTTP response templates
335 * - Removed some >400 CRs again (Jon, you really worked
338 * Revision 1.4 2001/05/21 19:32:54 jongfoster
339 * Added another #ifdef _WIN_CONSOLE
341 * Revision 1.3 2001/05/20 01:11:40 jongfoster
342 * Added support for LOG_LEVEL_FATAL
343 * Renamed LOG_LEVEL_FRC to LOG_LEVEL_FORCE,
344 * and LOG_LEVEL_REF to LOG_LEVEL_RE_FILTER
346 * Revision 1.2 2001/05/17 22:42:01 oes
347 * - Cleaned CRLF's from the sources and related files
348 * - Repaired logging for REF and FRC
350 * Revision 1.1.1.1 2001/05/15 13:58:51 oes
351 * Initial import of version 2.9.3 source tree
354 *********************************************************************/
363 #include "miscutil.h"
365 /* For gettimeofday() */
366 #include <sys/time.h>
368 #if !defined(_WIN32) && !defined(__OS2__)
370 #endif /* !defined(_WIN32) && !defined(__OS2__) */
382 #endif /* ndef _WIN_CONSOLE */
383 #endif /* def _WIN32 */
385 #define inline __inline
386 #endif /* def _MSC_VER */
389 #include <sys/socket.h> /* For sock_errno */
398 const char errlog_h_rcs[] = ERRLOG_H_VERSION;
402 * LOG_LEVEL_FATAL cannot be turned off. (There are
403 * some exceptional situations where we need to get a
404 * message to the user).
406 #define LOG_LEVEL_MINIMUM LOG_LEVEL_FATAL
408 /* where to log (default: stderr) */
409 static FILE *logfp = NULL;
411 /* logging detail level. XXX: stupid name. */
412 static int debug = (LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
414 /* static functions */
415 static void fatal_error(const char * error_message);
417 static char *w32_socket_strerr(int errcode, char *tmp_buf);
420 static char *os2_socket_strerr(int errcode, char *tmp_buf);
423 #ifdef FEATURE_PTHREAD
424 static inline void lock_logfile(void)
426 pthread_mutex_lock(&log_mutex);
428 static inline void unlock_logfile(void)
430 pthread_mutex_unlock(&log_mutex);
432 static inline void lock_loginit(void)
434 pthread_mutex_lock(&log_init_mutex);
436 static inline void unlock_loginit(void)
438 pthread_mutex_unlock(&log_init_mutex);
440 #else /* ! FEATURE_PTHREAD */
442 * FIXME we need a cross-platform locking mechanism.
443 * The locking/unlocking functions below should be
444 * fleshed out for non-pthread implementations.
446 static inline void lock_logfile() {}
447 static inline void unlock_logfile() {}
448 static inline void lock_loginit() {}
449 static inline void unlock_loginit() {}
452 /*********************************************************************
454 * Function : fatal_error
456 * Description : Displays a fatal error to standard error (or, on
457 * a WIN32 GUI, to a dialog box), and exits
458 * JunkBuster with status code 1.
461 * 1 : error_message = The error message to display.
463 * Returns : Does not return.
465 *********************************************************************/
466 static void fatal_error(const char * error_message)
468 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
469 MessageBox(g_hwndLogFrame, error_message, "Privoxy Error",
470 MB_OK | MB_ICONERROR | MB_TASKMODAL | MB_SETFOREGROUND | MB_TOPMOST);
472 /* Cleanup - remove taskbar icon etc. */
474 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
478 fputs(error_message, logfp);
492 /*********************************************************************
494 * Function : show_version
496 * Description : Logs the Privoxy version and the program name.
499 * 1 : prog_name = The program name.
503 *********************************************************************/
504 static void show_version(const char *prog_name)
506 log_error(LOG_LEVEL_INFO, "Privoxy version " VERSION);
507 if (prog_name != NULL)
509 log_error(LOG_LEVEL_INFO, "Program name: %s", prog_name);
514 /*********************************************************************
516 * Function : init_log_module
518 * Description : Initializes the logging module to log to stderr.
519 * Can only be called while stderr hasn't been closed
520 * yet and is only supposed to be called once.
523 * 1 : prog_name = The program name.
527 *********************************************************************/
528 void init_log_module(const char *prog_name)
533 set_debug_level(debug);
534 show_version(prog_name);
538 /*********************************************************************
540 * Function : set_debug_level
542 * Description : Sets the debug level to the provided value
543 * plus LOG_LEVEL_MINIMUM.
545 * XXX: we should only use the LOG_LEVEL_MINIMUM
546 * until the frist time the configuration file has
549 * Parameters : 1: debug_level = The debug level to set.
553 *********************************************************************/
554 void set_debug_level(int debug_level)
556 debug = debug_level | LOG_LEVEL_MINIMUM;
560 /*********************************************************************
562 * Function : disable_logging
564 * Description : Disables logging.
570 *********************************************************************/
571 void disable_logging(void)
575 log_error(LOG_LEVEL_INFO,
576 "No logfile configured. Please enable it before reporting any problems.");
585 /*********************************************************************
587 * Function : init_error_log
589 * Description : Initializes the logging module to log to a file.
591 * XXX: should be renamed.
594 * 1 : prog_name = The program name.
595 * 2 : logfname = The logfile name, or NULL for stderr.
596 * 3 : debuglevel = The debugging level.
600 *********************************************************************/
601 void init_error_log(const char *prog_name, const char *logfname)
605 assert(NULL != logfname);
611 log_error(LOG_LEVEL_INFO, "(Re-)Opening logfile \'%s\'", logfname);
614 /* set the designated log file */
615 fp = fopen(logfname, "a");
618 log_error(LOG_LEVEL_FATAL, "init_error_log(): can't open logfile: \'%s\'", logfname);
621 /* set logging to be completely unbuffered */
634 * Prevent the Windows GUI from showing the version two
635 * times in a row on startup. It already displayed the show_version()
636 * call from init_log_module() that other systems write to stderr.
638 * This means mingw32 users will never see the version in their
639 * log file, but I assume they wouldn't look for it there anyway
640 * and simply use the "Help/About Privoxy" menu.
642 show_version(prog_name);
643 #endif /* def unix */
647 } /* init_error_log */
650 /*********************************************************************
652 * Function : get_thread_id
654 * Description : Returns a number that is different for each thread.
656 * XXX: Should be moved elsewhere (miscutil.c?)
660 * Returns : thread_id
662 *********************************************************************/
663 static long get_thread_id(void)
665 long this_thread = 1; /* was: pthread_t this_thread;*/
669 APIRET ulrc; /* XXX: I have no clue what this does */
672 /* FIXME get current thread id */
673 #ifdef FEATURE_PTHREAD
674 this_thread = (long)pthread_self();
677 * Mac OSX (and perhaps other Mach instances) doesn't have a debuggable
678 * value at the first 4 bytes of pthread_self()'s return value, a pthread_t.
679 * pthread_t is supposed to be opaque... but it's fairly random, though, so
680 * we make it mostly presentable.
682 this_thread = abs(this_thread % 1000);
683 #endif /* def __MACH__ */
684 #elif defined(_WIN32)
685 this_thread = GetCurrentThreadId();
686 #elif defined(__OS2__)
687 ulrc = DosGetInfoBlocks(&ptib, NULL);
689 this_thread = ptib -> tib_ptib2 -> tib2_ultid;
690 #endif /* def FEATURE_PTHREAD */
696 /*********************************************************************
698 * Function : get_log_timestamp
700 * Description : Generates the time stamp for the log message prefix.
703 * 1 : buffer = Storage buffer
704 * 2 : buffer_size = Size of storage buffer
706 * Returns : Number of written characters or 0 for error.
708 *********************************************************************/
709 static inline size_t get_log_timestamp(char *buffer, size_t buffer_size)
714 struct timeval tv_now; /* XXX: stupid name */
716 int msecs_length = 0;
718 gettimeofday(&tv_now, NULL);
719 msecs = tv_now.tv_usec / 1000;
723 #ifdef HAVE_LOCALTIME_R
724 tm_now = *localtime_r(&now, &tm_now);
725 #elif FEATURE_PTHREAD
726 pthread_mutex_lock(&localtime_mutex);
727 tm_now = *localtime(&now);
728 pthread_mutex_unlock(&localtime_mutex);
730 tm_now = *localtime(&now);
733 length = strftime(buffer, buffer_size, "%b %d %H:%M:%S", &tm_now);
736 msecs_length = snprintf(buffer+length, buffer_size - length, ".%.3ld", msecs);
738 if (msecs_length > 0)
740 length += (size_t)msecs_length;
751 /*********************************************************************
753 * Function : get_clf_timestamp
755 * Description : Generates a Common Log Format time string.
758 * 1 : buffer = Storage buffer
759 * 2 : buffer_size = Size of storage buffer
761 * Returns : Number of written characters or 0 for error.
763 *********************************************************************/
764 static inline size_t get_clf_timestamp(char *buffer, size_t buffer_size)
767 * Complex because not all OSs have tm_gmtoff or
768 * the %z field in strftime()
773 #ifdef HAVE_LOCALTIME_R
782 gmt = *gmtime_r(&now, &gmt);
783 #elif FEATURE_PTHREAD
784 pthread_mutex_lock(&gmtime_mutex);
786 pthread_mutex_unlock(&gmtime_mutex);
790 #ifdef HAVE_LOCALTIME_R
791 tm_now = localtime_r(&now, &dummy);
792 #elif FEATURE_PTHREAD
793 pthread_mutex_lock(&localtime_mutex);
794 tm_now = localtime(&now);
795 pthread_mutex_unlock(&localtime_mutex);
797 tm_now = localtime(&now);
799 days = tm_now->tm_yday - gmt.tm_yday;
800 hrs = ((days < -1 ? 24 : 1 < days ? -24 : days * 24) + tm_now->tm_hour - gmt.tm_hour);
801 mins = hrs * 60 + tm_now->tm_min - gmt.tm_min;
803 length = strftime(buffer, buffer_size, "%d/%b/%Y:%H:%M:%S ", tm_now);
807 tz_length = snprintf(buffer+length, buffer_size-length,
808 "%+03d%02d", mins / 60, abs(mins) % 60);
812 length += (size_t)tz_length;
823 /*********************************************************************
825 * Function : get_log_level_string
827 * Description : Translates a numerical loglevel into a string.
830 * 1 : loglevel = LOG_LEVEL_FOO
832 * Returns : Log level string.
834 *********************************************************************/
835 static inline const char *get_log_level_string(int loglevel)
837 char *log_level_string = NULL;
839 assert(0 < loglevel);
843 case LOG_LEVEL_ERROR:
844 log_level_string = "Error";
846 case LOG_LEVEL_FATAL:
847 log_level_string = "Fatal error";
850 log_level_string = "Request";
852 case LOG_LEVEL_CONNECT:
853 log_level_string = "Connect";
856 log_level_string = "Writing";
858 case LOG_LEVEL_HEADER:
859 log_level_string = "Header";
862 log_level_string = "Info";
864 case LOG_LEVEL_RE_FILTER:
865 log_level_string = "Re-Filter";
867 #ifdef FEATURE_FORCE_LOAD
868 case LOG_LEVEL_FORCE:
869 log_level_string = "Force";
871 #endif /* def FEATURE_FORCE_LOAD */
872 #ifdef FEATURE_FAST_REDIRECTS
873 case LOG_LEVEL_REDIRECTS:
874 log_level_string = "Redirect";
876 #endif /* def FEATURE_FAST_REDIRECTS */
877 case LOG_LEVEL_DEANIMATE:
878 log_level_string = "Gif-Deanimate";
881 log_level_string = "CGI";
884 log_level_string = "Unknown log level";
887 assert(NULL != log_level_string);
889 return log_level_string;
893 /*********************************************************************
895 * Function : log_error
897 * Description : This is the error-reporting and logging function.
900 * 1 : loglevel = the type of message to be logged
901 * 2 : fmt = the main string we want logged, printf-like
902 * 3 : ... = arguments to be inserted in fmt (printf-like).
906 *********************************************************************/
907 void log_error(int loglevel, const char *fmt, ...)
911 static char *outbuf_save = NULL;
912 char tempbuf[BUFFER_SIZE];
914 const char * src = fmt;
918 * XXX: Make this a config option,
919 * why else do we allocate instead of using
922 size_t log_buffer_size = BUFFER_SIZE;
924 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
926 * Irrespective of debug setting, a GET/POST/CONNECT makes
927 * the taskbar icon animate. (There is an option to disable
928 * this but checking that is handled inside LogShowActivity()).
930 if (loglevel == LOG_LEVEL_GPC)
934 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
937 * verify that the loglevel applies to current
938 * settings and that logging is enabled.
939 * Bail out otherwise.
941 if ((0 == (loglevel & debug))
950 thread_id = get_thread_id();
951 get_log_timestamp(timestamp, sizeof(timestamp));
953 /* protect the whole function because of the static buffer (outbuf) */
956 if (NULL == outbuf_save)
958 outbuf_save = (char*)zalloc(log_buffer_size + 1); /* +1 for paranoia */
959 if (NULL == outbuf_save)
961 snprintf(tempbuf, sizeof(tempbuf),
962 "%s Privoxy(%08lx) Fatal error: log_error() failed to allocate buffer memory.\n"
963 "\nExiting.", timestamp, thread_id);
964 fatal_error(tempbuf); /* Exit */
967 outbuf = outbuf_save;
970 * Memsetting the whole buffer to zero (in theory)
971 * makes things easier later on.
973 memset(outbuf, 0, log_buffer_size);
975 /* Add prefix for everything but Common Log Format messages */
976 if (loglevel != LOG_LEVEL_CLF)
978 length = (size_t)snprintf(outbuf, log_buffer_size, "%s Privoxy(%08lx) %s: ",
979 timestamp, thread_id, get_log_level_string(loglevel));
982 /* get ready to scan var. args. */
985 /* build formatted message from fmt and var-args */
986 while ((*src) && (length < log_buffer_size-2))
988 const char *sval = NULL; /* %N string */
989 int ival; /* %N string length or an error code */
990 unsigned uval; /* %u value */
991 long lval; /* %l value */
992 unsigned long ulval; /* %ul value */
994 const char *format_string = tempbuf;
999 outbuf[length++] = ch;
1001 * XXX: Only necessary on platforms which don't use pthread
1002 * mutexes (mingw32 for example), where multiple threads can
1003 * write to the buffer at the same time.
1005 outbuf[length] = '\0';
1008 outbuf[length] = '\0';
1016 ival = va_arg( ap, int );
1017 snprintf(tempbuf, sizeof(tempbuf), "%d", ival);
1020 uval = va_arg( ap, unsigned );
1021 snprintf(tempbuf, sizeof(tempbuf), "%u", uval);
1024 /* this is a modifier that must be followed by u or d */
1028 lval = va_arg( ap, long );
1029 snprintf(tempbuf, sizeof(tempbuf), "%ld", lval);
1033 ulval = va_arg( ap, unsigned long );
1034 snprintf(tempbuf, sizeof(tempbuf), "%lu", ulval);
1038 snprintf(tempbuf, sizeof(tempbuf), "Bad format string: \"%s\"", fmt);
1039 loglevel = LOG_LEVEL_FATAL;
1044 * Note that char paramaters are converted to int, so we need to
1045 * pass "int" to va_arg. (See K&R, 2nd ed, section A7.3.2, page 202)
1047 tempbuf[0] = (char) va_arg(ap, int);
1051 format_string = va_arg(ap, char *);
1052 if (format_string == NULL)
1054 format_string = "[null]";
1059 * Non-standard: Print a counted unterminated string.
1060 * Takes 2 parameters: int length, const char * string.
1062 ival = va_arg(ap, int);
1063 sval = va_arg(ap, char *);
1066 format_string = "[null]";
1072 /* That's ok (but stupid) */
1078 * That's not ok (and even more stupid)
1081 format_string = "[counted string lenght < 0]";
1084 else if (ival >= sizeof(tempbuf))
1087 * String is too long, copy as much as possible.
1088 * It will be further truncated later.
1090 memcpy(tempbuf, sval, sizeof(tempbuf)-1);
1091 tempbuf[sizeof(tempbuf)-1] = '\0';
1095 memcpy(tempbuf, sval, (size_t) ival);
1096 tempbuf[ival] = '\0';
1100 /* Non-standard: Print error code from errno */
1102 ival = WSAGetLastError();
1103 format_string = w32_socket_strerr(ival, tempbuf);
1105 ival = sock_errno();
1108 format_string = os2_socket_strerr(ival, tempbuf);
1113 format_string = strerror(ival);
1115 #else /* ifndef _WIN32 */
1117 #ifdef HAVE_STRERROR
1118 format_string = strerror(ival);
1119 #else /* ifndef HAVE_STRERROR */
1120 format_string = NULL;
1121 #endif /* ndef HAVE_STRERROR */
1124 snprintf(tempbuf, sizeof(tempbuf), "(errno = %d)", ival);
1126 #endif /* ndef _WIN32 */
1129 /* Non-standard: Print a Common Log File timestamp */
1130 get_clf_timestamp(tempbuf, sizeof(tempbuf));
1133 snprintf(tempbuf, sizeof(tempbuf), "Bad format string: \"%s\"", fmt);
1134 loglevel = LOG_LEVEL_FATAL;
1138 assert(length < log_buffer_size);
1139 length += strlcpy(outbuf + length, format_string, log_buffer_size - length);
1141 if (length >= log_buffer_size-2)
1143 static char warning[] = "... [too long, truncated]";
1145 length = log_buffer_size - sizeof(warning) - 1;
1146 length += strlcpy(outbuf + length, warning, log_buffer_size - length);
1147 assert(length < log_buffer_size);
1151 } /* for( p ... ) */
1153 /* done with var. args */
1156 assert(length < log_buffer_size);
1157 length += strlcpy(outbuf + length, "\n", log_buffer_size - length);
1159 /* Some sanity checks */
1160 if ((length >= log_buffer_size)
1161 || (outbuf[log_buffer_size-1] != '\0')
1162 || (outbuf[log_buffer_size] != '\0')
1165 /* Repeat as assertions */
1166 assert(length < log_buffer_size);
1167 assert(outbuf[log_buffer_size-1] == '\0');
1169 * outbuf's real size is log_buffer_size+1,
1170 * so while this looks like an off-by-one,
1171 * we're only checking our paranoia byte.
1173 assert(outbuf[log_buffer_size] == '\0');
1175 snprintf(outbuf, log_buffer_size,
1176 "%s Privoxy(%08lx) Fatal error: log_error()'s sanity checks failed. length: %d\n"
1177 "Exiting.", timestamp, thread_id, (int)length);
1178 loglevel = LOG_LEVEL_FATAL;
1183 * On Windows this is acceptable in case
1184 * we are logging to the GUI window only.
1186 assert(NULL != logfp);
1189 if (loglevel == LOG_LEVEL_FATAL)
1191 fatal_error(outbuf_save);
1192 /* Never get here */
1196 fputs(outbuf_save, logfp);
1200 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
1201 /* Write to display */
1202 LogPutString(outbuf_save);
1203 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
1208 /*********************************************************************
1210 * Function : jb_err_to_string
1212 * Description : Translates JB_ERR_FOO codes into strings.
1214 * XXX: the type of error codes is jb_err
1215 * but the typedef'inition is currently not
1216 * visible to all files that include errlog.h.
1219 * 1 : error = a valid jb_err code
1221 * Returns : A string with the jb_err translation
1223 *********************************************************************/
1224 const char *jb_err_to_string(int error)
1229 return "Success, no error";
1231 return "Out of memory";
1232 case JB_ERR_CGI_PARAMS:
1233 return "Missing or corrupt CGI parameters";
1235 return "Error opening, reading or writing a file";
1237 return "Parse error";
1238 case JB_ERR_MODIFIED:
1239 return "File has been modified outside of the CGI actions editor.";
1240 case JB_ERR_COMPRESS:
1241 return "(De)compression failure";
1244 return "Unknown error";
1247 return "Internal error";
1251 /*********************************************************************
1253 * Function : w32_socket_strerr
1255 * Description : Translate the return value from WSAGetLastError()
1259 * 1 : errcode = The return value from WSAGetLastError().
1260 * 2 : tmp_buf = A temporary buffer that might be used to
1263 * Returns : String representing the error code. This may be
1264 * a global string constant or a string stored in
1267 *********************************************************************/
1268 static char *w32_socket_strerr(int errcode, char *tmp_buf)
1270 #define TEXT_FOR_ERROR(code,text) \
1271 if (errcode == code) \
1273 return #code " - " text; \
1276 TEXT_FOR_ERROR(WSAEACCES, "Permission denied")
1277 TEXT_FOR_ERROR(WSAEADDRINUSE, "Address already in use.")
1278 TEXT_FOR_ERROR(WSAEADDRNOTAVAIL, "Cannot assign requested address.");
1279 TEXT_FOR_ERROR(WSAEAFNOSUPPORT, "Address family not supported by protocol family.");
1280 TEXT_FOR_ERROR(WSAEALREADY, "Operation already in progress.");
1281 TEXT_FOR_ERROR(WSAECONNABORTED, "Software caused connection abort.");
1282 TEXT_FOR_ERROR(WSAECONNREFUSED, "Connection refused.");
1283 TEXT_FOR_ERROR(WSAECONNRESET, "Connection reset by peer.");
1284 TEXT_FOR_ERROR(WSAEDESTADDRREQ, "Destination address required.");
1285 TEXT_FOR_ERROR(WSAEFAULT, "Bad address.");
1286 TEXT_FOR_ERROR(WSAEHOSTDOWN, "Host is down.");
1287 TEXT_FOR_ERROR(WSAEHOSTUNREACH, "No route to host.");
1288 TEXT_FOR_ERROR(WSAEINPROGRESS, "Operation now in progress.");
1289 TEXT_FOR_ERROR(WSAEINTR, "Interrupted function call.");
1290 TEXT_FOR_ERROR(WSAEINVAL, "Invalid argument.");
1291 TEXT_FOR_ERROR(WSAEISCONN, "Socket is already connected.");
1292 TEXT_FOR_ERROR(WSAEMFILE, "Too many open sockets.");
1293 TEXT_FOR_ERROR(WSAEMSGSIZE, "Message too long.");
1294 TEXT_FOR_ERROR(WSAENETDOWN, "Network is down.");
1295 TEXT_FOR_ERROR(WSAENETRESET, "Network dropped connection on reset.");
1296 TEXT_FOR_ERROR(WSAENETUNREACH, "Network is unreachable.");
1297 TEXT_FOR_ERROR(WSAENOBUFS, "No buffer space available.");
1298 TEXT_FOR_ERROR(WSAENOPROTOOPT, "Bad protocol option.");
1299 TEXT_FOR_ERROR(WSAENOTCONN, "Socket is not connected.");
1300 TEXT_FOR_ERROR(WSAENOTSOCK, "Socket operation on non-socket.");
1301 TEXT_FOR_ERROR(WSAEOPNOTSUPP, "Operation not supported.");
1302 TEXT_FOR_ERROR(WSAEPFNOSUPPORT, "Protocol family not supported.");
1303 TEXT_FOR_ERROR(WSAEPROCLIM, "Too many processes.");
1304 TEXT_FOR_ERROR(WSAEPROTONOSUPPORT, "Protocol not supported.");
1305 TEXT_FOR_ERROR(WSAEPROTOTYPE, "Protocol wrong type for socket.");
1306 TEXT_FOR_ERROR(WSAESHUTDOWN, "Cannot send after socket shutdown.");
1307 TEXT_FOR_ERROR(WSAESOCKTNOSUPPORT, "Socket type not supported.");
1308 TEXT_FOR_ERROR(WSAETIMEDOUT, "Connection timed out.");
1309 TEXT_FOR_ERROR(WSAEWOULDBLOCK, "Resource temporarily unavailable.");
1310 TEXT_FOR_ERROR(WSAHOST_NOT_FOUND, "Host not found.");
1311 TEXT_FOR_ERROR(WSANOTINITIALISED, "Successful WSAStartup not yet performed.");
1312 TEXT_FOR_ERROR(WSANO_DATA, "Valid name, no data record of requested type.");
1313 TEXT_FOR_ERROR(WSANO_RECOVERY, "This is a non-recoverable error.");
1314 TEXT_FOR_ERROR(WSASYSNOTREADY, "Network subsystem is unavailable.");
1315 TEXT_FOR_ERROR(WSATRY_AGAIN, "Non-authoritative host not found.");
1316 TEXT_FOR_ERROR(WSAVERNOTSUPPORTED, "WINSOCK.DLL version out of range.");
1317 TEXT_FOR_ERROR(WSAEDISCON, "Graceful shutdown in progress.");
1319 * The following error codes are documented in the Microsoft WinSock
1320 * reference guide, but don't actually exist.
1322 * TEXT_FOR_ERROR(WSA_INVALID_HANDLE, "Specified event object handle is invalid.");
1323 * TEXT_FOR_ERROR(WSA_INVALID_PARAMETER, "One or more parameters are invalid.");
1324 * TEXT_FOR_ERROR(WSAINVALIDPROCTABLE, "Invalid procedure table from service provider.");
1325 * TEXT_FOR_ERROR(WSAINVALIDPROVIDER, "Invalid service provider version number.");
1326 * TEXT_FOR_ERROR(WSA_IO_PENDING, "Overlapped operations will complete later.");
1327 * TEXT_FOR_ERROR(WSA_IO_INCOMPLETE, "Overlapped I/O event object not in signaled state.");
1328 * TEXT_FOR_ERROR(WSA_NOT_ENOUGH_MEMORY, "Insufficient memory available.");
1329 * TEXT_FOR_ERROR(WSAPROVIDERFAILEDINIT, "Unable to initialize a service provider.");
1330 * TEXT_FOR_ERROR(WSASYSCALLFAILURE, "System call failure.");
1331 * TEXT_FOR_ERROR(WSA_OPERATION_ABORTED, "Overlapped operation aborted.");
1334 sprintf(tmp_buf, "(error number %d)", errcode);
1337 #endif /* def _WIN32 */
1341 /*********************************************************************
1343 * Function : os2_socket_strerr
1345 * Description : Translate the return value from sock_errno()
1349 * 1 : errcode = The return value from sock_errno().
1350 * 2 : tmp_buf = A temporary buffer that might be used to
1353 * Returns : String representing the error code. This may be
1354 * a global string constant or a string stored in
1357 *********************************************************************/
1358 static char *os2_socket_strerr(int errcode, char *tmp_buf)
1360 #define TEXT_FOR_ERROR(code,text) \
1361 if (errcode == code) \
1363 return #code " - " text; \
1366 TEXT_FOR_ERROR(SOCEPERM , "Not owner.")
1367 TEXT_FOR_ERROR(SOCESRCH , "No such process.")
1368 TEXT_FOR_ERROR(SOCEINTR , "Interrupted system call.")
1369 TEXT_FOR_ERROR(SOCENXIO , "No such device or address.")
1370 TEXT_FOR_ERROR(SOCEBADF , "Bad file number.")
1371 TEXT_FOR_ERROR(SOCEACCES , "Permission denied.")
1372 TEXT_FOR_ERROR(SOCEFAULT , "Bad address.")
1373 TEXT_FOR_ERROR(SOCEINVAL , "Invalid argument.")
1374 TEXT_FOR_ERROR(SOCEMFILE , "Too many open files.")
1375 TEXT_FOR_ERROR(SOCEPIPE , "Broken pipe.")
1376 TEXT_FOR_ERROR(SOCEWOULDBLOCK , "Operation would block.")
1377 TEXT_FOR_ERROR(SOCEINPROGRESS , "Operation now in progress.")
1378 TEXT_FOR_ERROR(SOCEALREADY , "Operation already in progress.")
1379 TEXT_FOR_ERROR(SOCENOTSOCK , "Socket operation on non-socket.")
1380 TEXT_FOR_ERROR(SOCEDESTADDRREQ , "Destination address required.")
1381 TEXT_FOR_ERROR(SOCEMSGSIZE , "Message too long.")
1382 TEXT_FOR_ERROR(SOCEPROTOTYPE , "Protocol wrong type for socket.")
1383 TEXT_FOR_ERROR(SOCENOPROTOOPT , "Protocol not available.")
1384 TEXT_FOR_ERROR(SOCEPROTONOSUPPORT, "Protocol not supported.")
1385 TEXT_FOR_ERROR(SOCESOCKTNOSUPPORT, "Socket type not supported.")
1386 TEXT_FOR_ERROR(SOCEOPNOTSUPP , "Operation not supported.")
1387 TEXT_FOR_ERROR(SOCEPFNOSUPPORT , "Protocol family not supported.")
1388 TEXT_FOR_ERROR(SOCEAFNOSUPPORT , "Address family not supported by protocol family.")
1389 TEXT_FOR_ERROR(SOCEADDRINUSE , "Address already in use.")
1390 TEXT_FOR_ERROR(SOCEADDRNOTAVAIL , "Can't assign requested address.")
1391 TEXT_FOR_ERROR(SOCENETDOWN , "Network is down.")
1392 TEXT_FOR_ERROR(SOCENETUNREACH , "Network is unreachable.")
1393 TEXT_FOR_ERROR(SOCENETRESET , "Network dropped connection on reset.")
1394 TEXT_FOR_ERROR(SOCECONNABORTED , "Software caused connection abort.")
1395 TEXT_FOR_ERROR(SOCECONNRESET , "Connection reset by peer.")
1396 TEXT_FOR_ERROR(SOCENOBUFS , "No buffer space available.")
1397 TEXT_FOR_ERROR(SOCEISCONN , "Socket is already connected.")
1398 TEXT_FOR_ERROR(SOCENOTCONN , "Socket is not connected.")
1399 TEXT_FOR_ERROR(SOCESHUTDOWN , "Can't send after socket shutdown.")
1400 TEXT_FOR_ERROR(SOCETOOMANYREFS , "Too many references: can't splice.")
1401 TEXT_FOR_ERROR(SOCETIMEDOUT , "Operation timed out.")
1402 TEXT_FOR_ERROR(SOCECONNREFUSED , "Connection refused.")
1403 TEXT_FOR_ERROR(SOCELOOP , "Too many levels of symbolic links.")
1404 TEXT_FOR_ERROR(SOCENAMETOOLONG , "File name too long.")
1405 TEXT_FOR_ERROR(SOCEHOSTDOWN , "Host is down.")
1406 TEXT_FOR_ERROR(SOCEHOSTUNREACH , "No route to host.")
1407 TEXT_FOR_ERROR(SOCENOTEMPTY , "Directory not empty.")
1408 TEXT_FOR_ERROR(SOCEOS2ERR , "OS/2 Error.")
1410 sprintf(tmp_buf, "(error number %d)", errcode);
1413 #endif /* def __OS2__ */