1 const char errlog_rcs[] = "$Id: errlog.c,v 1.23 2001/11/07 00:02:13 steudten 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 the SourceForge
10 * IJBSWA team. http://ijbswa.sourceforge.net
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.23 2001/11/07 00:02:13 steudten
37 * Add line number in error output for lineparsing for
38 * actionsfile and configfile.
39 * Special handling for CLF added.
41 * Revision 1.22 2001/11/05 23:43:05 steudten
42 * Add time+date to log files.
44 * Revision 1.21 2001/10/25 03:40:47 david__schmidt
45 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
46 * threads to call select() simultaneously. So, it's time to do a real, live,
47 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
48 * (native). Both versions will work, but using __OS2__ offers multi-threading.
50 * Revision 1.20 2001/09/16 23:04:34 jongfoster
53 * Revision 1.19 2001/09/13 20:08:06 jongfoster
54 * Adding support for LOG_LEVEL_CGI
56 * Revision 1.18 2001/09/10 11:27:24 oes
57 * Declaration of w32_socket_strerr now conditional
59 * Revision 1.17 2001/09/10 10:17:13 oes
60 * Removed unused variable; Fixed sprintf format
62 * Revision 1.16 2001/07/30 22:08:36 jongfoster
63 * Tidying up #defines:
64 * - All feature #defines are now of the form FEATURE_xxx
65 * - Permanently turned off WIN_GUI_EDIT
66 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
68 * Revision 1.15 2001/07/29 17:41:10 jongfoster
69 * Now prints thread ID for each message (pthreads only)
71 * Revision 1.14 2001/07/19 19:03:48 haroon
72 * - Added case for LOG_LEVEL_POPUPS
74 * Revision 1.13 2001/07/13 13:58:58 oes
75 * - Added case for LOG_LEVEL_DEANIMATE
76 * - Removed all #ifdef PCRS
78 * Revision 1.12 2001/06/09 10:55:28 jongfoster
79 * Changing BUFSIZ ==> BUFFER_SIZE
81 * Revision 1.11 2001/06/01 18:14:49 jongfoster
82 * Changing the calls to strerr() to check HAVE_STRERR (which is defined
83 * in config.h if appropriate) rather than the NO_STRERR macro.
85 * Revision 1.10 2001/05/29 11:52:21 oes
86 * Conditional compilation of w32_socket_error
88 * Revision 1.9 2001/05/28 16:15:17 jongfoster
89 * Improved reporting of errors under Win32.
91 * Revision 1.8 2001/05/26 17:25:14 jongfoster
92 * Added support for CLF (Common Log Format) and fixed LOG_LEVEL_LOG
94 * Revision 1.7 2001/05/26 15:21:28 jongfoster
95 * Activity animation in Win32 GUI now works even if debug==0
97 * Revision 1.6 2001/05/25 21:55:08 jongfoster
98 * Now cleans up properly on FATAL (removes taskbar icon etc)
100 * Revision 1.5 2001/05/22 18:46:04 oes
102 * - Enabled filtering banners by size rather than URL
103 * by adding patterns that replace all standard banner
104 * sizes with the "Junkbuster" gif to the re_filterfile
106 * - Enabled filtering WebBugs by providing a pattern
107 * which kills all 1x1 images
109 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
110 * which is selected by the (nonstandard and therefore
111 * capital) letter 'U' in the option string.
112 * It causes the quantifiers to be ungreedy by default.
113 * Appending a ? turns back to greedy (!).
115 * - Added a new interceptor ijb-send-banner, which
116 * sends back the "Junkbuster" gif. Without imagelist or
117 * MSIE detection support, or if tinygif = 1, or the
118 * URL isn't recognized as an imageurl, a lame HTML
119 * explanation is sent instead.
121 * - Added new feature, which permits blocking remote
122 * script redirects and firing back a local redirect
124 * The feature is conditionally compiled, i.e. it
125 * can be disabled with --disable-fast-redirects,
126 * plus it must be activated by a "fast-redirects"
127 * line in the config file, has its own log level
128 * and of course wants to be displayed by show-proxy-args
129 * Note: Boy, all the #ifdefs in 1001 locations and
130 * all the fumbling with configure.in and acconfig.h
131 * were *way* more work than the feature itself :-(
133 * - Because a generic redirect template was needed for
134 * this, tinygif = 3 now uses the same.
136 * - Moved GIFs, and other static HTTP response templates
141 * - Removed some >400 CRs again (Jon, you really worked
144 * Revision 1.4 2001/05/21 19:32:54 jongfoster
145 * Added another #ifdef _WIN_CONSOLE
147 * Revision 1.3 2001/05/20 01:11:40 jongfoster
148 * Added support for LOG_LEVEL_FATAL
149 * Renamed LOG_LEVEL_FRC to LOG_LEVEL_FORCE,
150 * and LOG_LEVEL_REF to LOG_LEVEL_RE_FILTER
152 * Revision 1.2 2001/05/17 22:42:01 oes
153 * - Cleaned CRLF's from the sources and related files
154 * - Repaired logging for REF and FRC
156 * Revision 1.1.1.1 2001/05/15 13:58:51 oes
157 * Initial import of version 2.9.3 source tree
160 *********************************************************************/
164 #include "miscutil.h"
171 #if !defined(_WIN32) && !defined(__OS2__)
173 #endif /* !defined(_WIN32) && !defined(__OS2__) */
177 #ifdef FEATURE_PTHREAD
179 #endif /* def FEATURE_PTHREAD */
185 #endif /* ndef _WIN_CONSOLE */
186 #endif /* def _WIN32 */
196 const char errlog_h_rcs[] = ERRLOG_H_VERSION;
200 * LOG_LEVEL_FATAL cannot be turned off. (There are
201 * some exceptional situations where we need to get a
202 * message to the user).
204 #define LOG_LEVEL_MINIMUM LOG_LEVEL_FATAL
206 /* where to log (default: stderr) */
207 static FILE *logfp = NULL;
209 /* logging detail level. */
210 static int debug = (LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
212 /* static functions */
213 static void fatal_error(const char * error_message);
215 static char *w32_socket_strerr(int errcode, char *tmp_buf);
218 /*********************************************************************
220 * Function : fatal_error
222 * Description : Displays a fatal error to standard error (or, on
223 * a WIN32 GUI, to a dialog box), and exits
224 * JunkBuster with status code 1.
227 * 1 : error_message = The error message to display.
229 * Returns : Does not return.
231 *********************************************************************/
232 static void fatal_error(const char * error_message)
234 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
235 MessageBox(g_hwndLogFrame, error_message, "Internet JunkBuster Error",
236 MB_OK | MB_ICONERROR | MB_TASKMODAL | MB_SETFOREGROUND | MB_TOPMOST);
238 /* Cleanup - remove taskbar icon etc. */
241 #else /* if !defined(_WIN32) || defined(_WIN_CONSOLE) */
242 fputs(error_message, stderr);
243 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
253 /*********************************************************************
255 * Function : init_errlog
257 * Description : Initializes the logging module. Must call before
261 * 1 : prog_name = The program name.
262 * 2 : logfname = The logfile name, or NULL for stderr.
263 * 3 : debuglevel = The debugging level.
267 *********************************************************************/
268 void init_error_log(const char *prog_name, const char *logfname, int debuglevel)
272 /* FIXME RACE HAZARD: should start critical section error_log_use here */
274 /* set the logging detail level */
275 debug = debuglevel | LOG_LEVEL_MINIMUM;
277 if ((logfp != NULL) && (logfp != stderr))
279 log_error(LOG_LEVEL_INFO, "(Re-)Open logfile %s", logfname ? logfname : "none");
284 /* set the designated log file */
287 if( !(fp = fopen(logfname, "a")) )
289 log_error(LOG_LEVEL_FATAL, "init_errlog(): can't open logfile: %s", logfname);
292 /* set logging to be completely unbuffered */
298 log_error(LOG_LEVEL_INFO, "Internet JunkBuster version " VERSION);
299 if (prog_name != NULL)
301 log_error(LOG_LEVEL_INFO, "Program name: %s", prog_name);
304 /* FIXME RACE HAZARD: should end critical section error_log_use here */
306 } /* init_error_log */
309 /*********************************************************************
311 * Function : log_error
313 * Description : This is the error-reporting and logging function.
316 * 1 : loglevel = the type of message to be logged
317 * 2 : fmt = the main string we want logged, printf-like
318 * 3 : ... = arguments to be inserted in fmt (printf-like).
322 *********************************************************************/
323 void log_error(int loglevel, char *fmt, ...)
327 char *outbuf_save = NULL;
330 long this_thread = 1; /* was: pthread_t this_thread;*/
336 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
338 * Irrespective of debug setting, a GET/POST/CONNECT makes
339 * the taskbar icon animate. (There is an option to disable
340 * this but checking that is handled inside LogShowActivity()).
342 if (loglevel == LOG_LEVEL_GPC)
346 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
348 /* verify if loglevel applies to current settings and bail out if negative */
349 if ((loglevel & debug) == 0)
354 /* FIXME get current thread id */
355 #ifdef FEATURE_PTHREAD
356 this_thread = (long)pthread_self();
359 ulrc = DosGetInfoBlocks(&ptib, NULL);
361 this_thread = ptib -> tib_ptib2 -> tib2_ultid;
362 #endif /* def FEATURE_PTHREAD */
364 outbuf_save = outbuf = (char*)malloc(BUFFER_SIZE);
369 * Write timestamp into tempbuf.
371 * Complex because not all OSs have tm_gmtoff or
372 * the %z field in strftime()
377 tm_now = localtime (&now);
378 strftime (outbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", tm_now);
379 outbuf += strlen( outbuf );
383 case LOG_LEVEL_ERROR:
384 outc = sprintf(outbuf, "IJB(%ld) Error: ", this_thread);
386 case LOG_LEVEL_FATAL:
387 outc = sprintf(outbuf, "IJB(%ld) Fatal error: ", this_thread);
390 outc = sprintf(outbuf, "IJB(%ld) Request: ", this_thread);
392 case LOG_LEVEL_CONNECT:
393 outc = sprintf(outbuf, "IJB(%ld) Connect: ", this_thread);
396 outc = sprintf(outbuf, "IJB(%ld) Writing: ", this_thread);
398 case LOG_LEVEL_HEADER:
399 outc = sprintf(outbuf, "IJB(%ld) Header: ", this_thread);
402 outc = sprintf(outbuf, "IJB(%ld) Info: ", this_thread);
404 case LOG_LEVEL_RE_FILTER:
405 outc = sprintf(outbuf, "IJB(%ld) Re-Filter: ", this_thread);
407 #ifdef FEATURE_FORCE_LOAD
408 case LOG_LEVEL_FORCE:
409 outc = sprintf(outbuf, "IJB(%ld) Force: ", this_thread);
411 #endif /* def FEATURE_FORCE_LOAD */
412 #ifdef FEATURE_FAST_REDIRECTS
413 case LOG_LEVEL_REDIRECTS:
414 outc = sprintf(outbuf, "IJB(%ld) Redirect: ", this_thread);
416 #endif /* def FEATURE_FAST_REDIRECTS */
417 case LOG_LEVEL_DEANIMATE:
418 outc = sprintf(outbuf, "IJB(%ld) Gif-Deanimate: ", this_thread);
421 outbuf = outbuf_save;
425 #ifdef FEATURE_KILL_POPUPS
426 case LOG_LEVEL_POPUPS:
427 outc = sprintf(outbuf, "IJB(%ld) Kill-Popups: ", this_thread);
429 #endif /* def FEATURE_KILL_POPUPS */
431 outc = sprintf(outbuf, "IJB(%ld) CGI: ", this_thread);
434 outc = sprintf(outbuf, "IJB(%ld) UNKNOWN LOG TYPE(%d): ", this_thread, loglevel);
438 /* get ready to scan var. args. */
441 /* build formatted message from fmt and var-args */
442 while ((*src) && (outc < BUFFER_SIZE-2))
444 char tempbuf[BUFFER_SIZE];
463 outbuf[outc++] = '%';
466 ival = va_arg( ap, int );
468 outc += sprintf(tempbuf, "%d", ival);
469 if (outc < BUFFER_SIZE-1)
471 strcpy(outbuf + oldoutc, tempbuf);
475 outbuf[oldoutc] = '\0';
479 uval = va_arg( ap, unsigned );
481 outc += sprintf(tempbuf, "%u", uval);
482 if (outc < BUFFER_SIZE-1)
484 strcpy(outbuf + oldoutc, tempbuf);
488 outbuf[oldoutc] = '\0';
492 /* this is a modifier that must be followed by u or d */
496 lval = va_arg( ap, long );
498 outc += sprintf(tempbuf, "%ld", lval);
502 ulval = va_arg( ap, unsigned long );
504 outc += sprintf(tempbuf, "%lu", ulval);
509 sprintf(outbuf, "IJB(%ld) Error: log_error(): Bad format string:\n"
511 "Exiting.", this_thread, fmt);
512 /* FIXME RACE HAZARD: should start critical section error_log_use here */
517 fputs(outbuf, logfp);
518 /* FIXME RACE HAZARD: should end critical section error_log_use here */
523 if (outc < BUFFER_SIZE-1)
525 strcpy(outbuf + oldoutc, tempbuf);
529 outbuf[oldoutc] = '\0';
534 * Note that char paramaters are converted to int, so we need to
535 * pass "int" to va_arg. (See K&R, 2nd ed, section A7.3.2, page 202)
537 outbuf[outc++] = (char) va_arg( ap, int );
540 sval = va_arg( ap, char * );
542 outc += strlen(sval);
543 if (outc < BUFFER_SIZE-1)
545 strcpy(outbuf + oldoutc, sval);
549 outbuf[oldoutc] = '\0';
553 /* Non-standard: Print a counted string. Takes 2 parameters:
554 * int length, const char * string
556 ival = va_arg( ap, int );
557 sval = va_arg( ap, char * );
564 if (outc < BUFFER_SIZE-1)
566 memcpy(outbuf + oldoutc, sval, ival);
570 outbuf[oldoutc] = '\0';
574 /* Non-standard: Print error code from errno */
576 ival = WSAGetLastError();
577 sval = w32_socket_strerr(ival, tempbuf);
578 #else /* ifndef _WIN32 */
581 sval = strerror(ival);
582 #else /* ifndef HAVE_STRERROR */
584 #endif /* ndef HAVE_STRERROR */
587 sprintf(tempbuf, "(errno = %d)", ival);
590 #endif /* ndef _WIN32 */
592 outc += strlen(sval);
593 if (outc < BUFFER_SIZE-1)
595 strcpy(outbuf + oldoutc, sval);
599 outbuf[oldoutc] = '\0';
603 /* Non-standard: Print a Common Log File timestamp */
606 * Write timestamp into tempbuf.
608 * Complex because not all OSs have tm_gmtoff or
609 * the %z field in strftime()
616 gmt = *gmtime (&now);
617 tm_now = localtime (&now);
618 days = tm_now->tm_yday - gmt.tm_yday;
619 hrs = ((days < -1 ? 24 : 1 < days ? -24 : days * 24) + tm_now->tm_hour - gmt.tm_hour);
620 mins = hrs * 60 + tm_now->tm_min - gmt.tm_min;
621 strftime (tempbuf, BUFFER_SIZE-6, "%d/%b/%Y:%H:%M:%S ", tm_now);
622 sprintf (tempbuf + strlen(tempbuf), "%+03d%02d", mins / 60, abs(mins) % 60);
625 outc += strlen(tempbuf);
626 if (outc < BUFFER_SIZE-1)
628 strcpy(outbuf + oldoutc, tempbuf);
632 outbuf[oldoutc] = '\0';
636 sprintf(outbuf, "IJB(%ld) Error: log_error(): Bad format string:\n"
638 "Exiting.", this_thread, fmt);
639 /* FIXME RACE HAZARD: should start critical section error_log_use here */
644 fputs(outbuf_save, logfp);
645 /* FIXME RACE HAZARD: should end critical section error_log_use here */
646 fatal_error(outbuf_save);
654 /* done with var. args */
657 if (outc >= BUFFER_SIZE-2)
659 /* insufficient room for newline and trailing null. */
661 static const char warning[] = "... [too long, truncated]\n";
663 if (outc < BUFFER_SIZE)
665 /* Need to add terminating null in this case. */
669 /* Truncate output */
670 outbuf[BUFFER_SIZE - sizeof(warning)] = '\0';
673 strcat(outbuf, warning);
677 /* Add terminating newline and null */
678 outbuf[outc++] = '\n';
682 /* FIXME RACE HAZARD: should start critical section error_log_use here */
684 /* deal with glibc stupidity - it won't let you initialize logfp */
690 fputs(outbuf_save, logfp);
692 if (loglevel == LOG_LEVEL_FATAL)
694 fatal_error(outbuf_save);
698 /* FIXME RACE HAZARD: should end critical section error_log_use here */
700 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
701 /* Write to display */
702 LogPutString(outbuf_save);
703 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
709 /*********************************************************************
711 * Function : w32_socket_strerr
713 * Description : Translate the return value from WSAGetLastError()
717 * 1 : errcode = The return value from WSAGetLastError().
718 * 2 : tmp_buf = A temporary buffer that might be used to
721 * Returns : String representing the error code. This may be
722 * a global string constant or a string stored in
725 *********************************************************************/
726 static char *w32_socket_strerr(int errcode, char *tmp_buf)
728 #define TEXT_FOR_ERROR(code,text) \
729 if (errcode == code) \
731 return #code " - " text; \
734 TEXT_FOR_ERROR(WSAEACCES, "Permission denied")
735 TEXT_FOR_ERROR(WSAEADDRINUSE, "Address already in use.")
736 TEXT_FOR_ERROR(WSAEADDRNOTAVAIL, "Cannot assign requested address.");
737 TEXT_FOR_ERROR(WSAEAFNOSUPPORT, "Address family not supported by protocol family.");
738 TEXT_FOR_ERROR(WSAEALREADY, "Operation already in progress.");
739 TEXT_FOR_ERROR(WSAECONNABORTED, "Software caused connection abort.");
740 TEXT_FOR_ERROR(WSAECONNREFUSED, "Connection refused.");
741 TEXT_FOR_ERROR(WSAECONNRESET, "Connection reset by peer.");
742 TEXT_FOR_ERROR(WSAEDESTADDRREQ, "Destination address required.");
743 TEXT_FOR_ERROR(WSAEFAULT, "Bad address.");
744 TEXT_FOR_ERROR(WSAEHOSTDOWN, "Host is down.");
745 TEXT_FOR_ERROR(WSAEHOSTUNREACH, "No route to host.");
746 TEXT_FOR_ERROR(WSAEINPROGRESS, "Operation now in progress.");
747 TEXT_FOR_ERROR(WSAEINTR, "Interrupted function call.");
748 TEXT_FOR_ERROR(WSAEINVAL, "Invalid argument.");
749 TEXT_FOR_ERROR(WSAEISCONN, "Socket is already connected.");
750 TEXT_FOR_ERROR(WSAEMFILE, "Too many open sockets.");
751 TEXT_FOR_ERROR(WSAEMSGSIZE, "Message too long.");
752 TEXT_FOR_ERROR(WSAENETDOWN, "Network is down.");
753 TEXT_FOR_ERROR(WSAENETRESET, "Network dropped connection on reset.");
754 TEXT_FOR_ERROR(WSAENETUNREACH, "Network is unreachable.");
755 TEXT_FOR_ERROR(WSAENOBUFS, "No buffer space available.");
756 TEXT_FOR_ERROR(WSAENOPROTOOPT, "Bad protocol option.");
757 TEXT_FOR_ERROR(WSAENOTCONN, "Socket is not connected.");
758 TEXT_FOR_ERROR(WSAENOTSOCK, "Socket operation on non-socket.");
759 TEXT_FOR_ERROR(WSAEOPNOTSUPP, "Operation not supported.");
760 TEXT_FOR_ERROR(WSAEPFNOSUPPORT, "Protocol family not supported.");
761 TEXT_FOR_ERROR(WSAEPROCLIM, "Too many processes.");
762 TEXT_FOR_ERROR(WSAEPROTONOSUPPORT, "Protocol not supported.");
763 TEXT_FOR_ERROR(WSAEPROTOTYPE, "Protocol wrong type for socket.");
764 TEXT_FOR_ERROR(WSAESHUTDOWN, "Cannot send after socket shutdown.");
765 TEXT_FOR_ERROR(WSAESOCKTNOSUPPORT, "Socket type not supported.");
766 TEXT_FOR_ERROR(WSAETIMEDOUT, "Connection timed out.");
767 TEXT_FOR_ERROR(WSAEWOULDBLOCK, "Resource temporarily unavailable.");
768 TEXT_FOR_ERROR(WSAHOST_NOT_FOUND, "Host not found.");
769 TEXT_FOR_ERROR(WSANOTINITIALISED, "Successful WSAStartup not yet performed.");
770 TEXT_FOR_ERROR(WSANO_DATA, "Valid name, no data record of requested type.");
771 TEXT_FOR_ERROR(WSANO_RECOVERY, "This is a non-recoverable error.");
772 TEXT_FOR_ERROR(WSASYSNOTREADY, "Network subsystem is unavailable.");
773 TEXT_FOR_ERROR(WSATRY_AGAIN, "Non-authoritative host not found.");
774 TEXT_FOR_ERROR(WSAVERNOTSUPPORTED, "WINSOCK.DLL version out of range.");
775 TEXT_FOR_ERROR(WSAEDISCON, "Graceful shutdown in progress.");
777 * The following error codes are documented in the Microsoft WinSock
778 * reference guide, but don't actually exist.
780 * TEXT_FOR_ERROR(WSA_INVALID_HANDLE, "Specified event object handle is invalid.");
781 * TEXT_FOR_ERROR(WSA_INVALID_PARAMETER, "One or more parameters are invalid.");
782 * TEXT_FOR_ERROR(WSAINVALIDPROCTABLE, "Invalid procedure table from service provider.");
783 * TEXT_FOR_ERROR(WSAINVALIDPROVIDER, "Invalid service provider version number.");
784 * TEXT_FOR_ERROR(WSA_IO_PENDING, "Overlapped operations will complete later.");
785 * TEXT_FOR_ERROR(WSA_IO_INCOMPLETE, "Overlapped I/O event object not in signaled state.");
786 * TEXT_FOR_ERROR(WSA_NOT_ENOUGH_MEMORY, "Insufficient memory available.");
787 * TEXT_FOR_ERROR(WSAPROVIDERFAILEDINIT, "Unable to initialize a service provider.");
788 * TEXT_FOR_ERROR(WSASYSCALLFAILURE, "System call failure.");
789 * TEXT_FOR_ERROR(WSA_OPERATION_ABORTED, "Overlapped operation aborted.");
792 sprintf(tmp_buf, "(error number %d)", errcode);
795 #endif /* def _WIN32 */