1 const char errlog_rcs[] = "$Id: errlog.c,v 1.22 2001/11/05 23:43:05 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.22 2001/11/05 23:43:05 steudten
37 * Add time+date to log files.
39 * Revision 1.21 2001/10/25 03:40:47 david__schmidt
40 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
41 * threads to call select() simultaneously. So, it's time to do a real, live,
42 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
43 * (native). Both versions will work, but using __OS2__ offers multi-threading.
45 * Revision 1.20 2001/09/16 23:04:34 jongfoster
48 * Revision 1.19 2001/09/13 20:08:06 jongfoster
49 * Adding support for LOG_LEVEL_CGI
51 * Revision 1.18 2001/09/10 11:27:24 oes
52 * Declaration of w32_socket_strerr now conditional
54 * Revision 1.17 2001/09/10 10:17:13 oes
55 * Removed unused variable; Fixed sprintf format
57 * Revision 1.16 2001/07/30 22:08:36 jongfoster
58 * Tidying up #defines:
59 * - All feature #defines are now of the form FEATURE_xxx
60 * - Permanently turned off WIN_GUI_EDIT
61 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
63 * Revision 1.15 2001/07/29 17:41:10 jongfoster
64 * Now prints thread ID for each message (pthreads only)
66 * Revision 1.14 2001/07/19 19:03:48 haroon
67 * - Added case for LOG_LEVEL_POPUPS
69 * Revision 1.13 2001/07/13 13:58:58 oes
70 * - Added case for LOG_LEVEL_DEANIMATE
71 * - Removed all #ifdef PCRS
73 * Revision 1.12 2001/06/09 10:55:28 jongfoster
74 * Changing BUFSIZ ==> BUFFER_SIZE
76 * Revision 1.11 2001/06/01 18:14:49 jongfoster
77 * Changing the calls to strerr() to check HAVE_STRERR (which is defined
78 * in config.h if appropriate) rather than the NO_STRERR macro.
80 * Revision 1.10 2001/05/29 11:52:21 oes
81 * Conditional compilation of w32_socket_error
83 * Revision 1.9 2001/05/28 16:15:17 jongfoster
84 * Improved reporting of errors under Win32.
86 * Revision 1.8 2001/05/26 17:25:14 jongfoster
87 * Added support for CLF (Common Log Format) and fixed LOG_LEVEL_LOG
89 * Revision 1.7 2001/05/26 15:21:28 jongfoster
90 * Activity animation in Win32 GUI now works even if debug==0
92 * Revision 1.6 2001/05/25 21:55:08 jongfoster
93 * Now cleans up properly on FATAL (removes taskbar icon etc)
95 * Revision 1.5 2001/05/22 18:46:04 oes
97 * - Enabled filtering banners by size rather than URL
98 * by adding patterns that replace all standard banner
99 * sizes with the "Junkbuster" gif to the re_filterfile
101 * - Enabled filtering WebBugs by providing a pattern
102 * which kills all 1x1 images
104 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
105 * which is selected by the (nonstandard and therefore
106 * capital) letter 'U' in the option string.
107 * It causes the quantifiers to be ungreedy by default.
108 * Appending a ? turns back to greedy (!).
110 * - Added a new interceptor ijb-send-banner, which
111 * sends back the "Junkbuster" gif. Without imagelist or
112 * MSIE detection support, or if tinygif = 1, or the
113 * URL isn't recognized as an imageurl, a lame HTML
114 * explanation is sent instead.
116 * - Added new feature, which permits blocking remote
117 * script redirects and firing back a local redirect
119 * The feature is conditionally compiled, i.e. it
120 * can be disabled with --disable-fast-redirects,
121 * plus it must be activated by a "fast-redirects"
122 * line in the config file, has its own log level
123 * and of course wants to be displayed by show-proxy-args
124 * Note: Boy, all the #ifdefs in 1001 locations and
125 * all the fumbling with configure.in and acconfig.h
126 * were *way* more work than the feature itself :-(
128 * - Because a generic redirect template was needed for
129 * this, tinygif = 3 now uses the same.
131 * - Moved GIFs, and other static HTTP response templates
136 * - Removed some >400 CRs again (Jon, you really worked
139 * Revision 1.4 2001/05/21 19:32:54 jongfoster
140 * Added another #ifdef _WIN_CONSOLE
142 * Revision 1.3 2001/05/20 01:11:40 jongfoster
143 * Added support for LOG_LEVEL_FATAL
144 * Renamed LOG_LEVEL_FRC to LOG_LEVEL_FORCE,
145 * and LOG_LEVEL_REF to LOG_LEVEL_RE_FILTER
147 * Revision 1.2 2001/05/17 22:42:01 oes
148 * - Cleaned CRLF's from the sources and related files
149 * - Repaired logging for REF and FRC
151 * Revision 1.1.1.1 2001/05/15 13:58:51 oes
152 * Initial import of version 2.9.3 source tree
155 *********************************************************************/
165 #if !defined(_WIN32) && !defined(__OS2__)
167 #endif /* !defined(_WIN32) && !defined(__OS2__) */
171 #ifdef FEATURE_PTHREAD
173 #endif /* def FEATURE_PTHREAD */
179 #endif /* ndef _WIN_CONSOLE */
180 #endif /* def _WIN32 */
190 const char errlog_h_rcs[] = ERRLOG_H_VERSION;
194 * LOG_LEVEL_FATAL cannot be turned off. (There are
195 * some exceptional situations where we need to get a
196 * message to the user).
198 #define LOG_LEVEL_MINIMUM LOG_LEVEL_FATAL
200 /* where to log (default: stderr) */
201 static FILE *logfp = NULL;
203 /* logging detail level. */
204 static int debug = (LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
206 /* static functions */
207 static void fatal_error(const char * error_message);
209 static char *w32_socket_strerr(int errcode, char *tmp_buf);
212 /*********************************************************************
214 * Function : fatal_error
216 * Description : Displays a fatal error to standard error (or, on
217 * a WIN32 GUI, to a dialog box), and exits
218 * JunkBuster with status code 1.
221 * 1 : error_message = The error message to display.
223 * Returns : Does not return.
225 *********************************************************************/
226 static void fatal_error(const char * error_message)
228 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
229 MessageBox(g_hwndLogFrame, error_message, "Internet JunkBuster Error",
230 MB_OK | MB_ICONERROR | MB_TASKMODAL | MB_SETFOREGROUND | MB_TOPMOST);
232 /* Cleanup - remove taskbar icon etc. */
235 #else /* if !defined(_WIN32) || defined(_WIN_CONSOLE) */
236 fputs(error_message, stderr);
237 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
243 /*********************************************************************
245 * Function : init_errlog
247 * Description : Initializes the logging module. Must call before
251 * 1 : prog_name = The program name.
252 * 2 : logfname = The logfile name, or NULL for stderr.
253 * 3 : debuglevel = The debugging level.
257 *********************************************************************/
258 void init_error_log(const char *prog_name, const char *logfname, int debuglevel)
262 /* FIXME RACE HAZARD: should start critical section error_log_use here */
264 /* set the logging detail level */
265 debug = debuglevel | LOG_LEVEL_MINIMUM;
267 if ((logfp != NULL) && (logfp != stderr))
273 /* set the designated log file */
276 if( !(fp = fopen(logfname, "a")) )
278 log_error(LOG_LEVEL_FATAL, "init_errlog(): can't open logfile: %s", logfname);
281 /* set logging to be completely unbuffered */
287 log_error(LOG_LEVEL_INFO, "Internet JunkBuster version " VERSION);
288 if (prog_name != NULL)
290 log_error(LOG_LEVEL_INFO, "Program name: %s", prog_name);
293 /* FIXME RACE HAZARD: should end critical section error_log_use here */
295 } /* init_error_log */
298 /*********************************************************************
300 * Function : log_error
302 * Description : This is the error-reporting and logging function.
305 * 1 : loglevel = the type of message to be logged
306 * 2 : fmt = the main string we want logged, printf-like
307 * 3 : ... = arguments to be inserted in fmt (printf-like).
311 *********************************************************************/
312 void log_error(int loglevel, char *fmt, ...)
316 char *outbuf_save = NULL;
319 long this_thread = 1; /* was: pthread_t this_thread;*/
325 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
327 * Irrespective of debug setting, a GET/POST/CONNECT makes
328 * the taskbar icon animate. (There is an option to disable
329 * this but checking that is handled inside LogShowActivity()).
331 if (loglevel == LOG_LEVEL_GPC)
335 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
337 /* verify if loglevel applies to current settings and bail out if negative */
338 if ((loglevel & debug) == 0)
343 /* FIXME get current thread id */
344 #ifdef FEATURE_PTHREAD
345 this_thread = (long)pthread_self();
348 ulrc = DosGetInfoBlocks(&ptib, NULL);
350 this_thread = ptib -> tib_ptib2 -> tib2_ultid;
351 #endif /* def FEATURE_PTHREAD */
353 outbuf_save = outbuf = (char*)malloc(BUFFER_SIZE);
358 * Write timestamp into tempbuf.
360 * Complex because not all OSs have tm_gmtoff or
361 * the %z field in strftime()
366 tm_now = localtime (&now);
367 strftime (outbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", tm_now);
368 outbuf += strlen( outbuf );
372 case LOG_LEVEL_ERROR:
373 outc = sprintf(outbuf, "IJB(%ld) Error: ", this_thread);
375 case LOG_LEVEL_FATAL:
376 outc = sprintf(outbuf, "IJB(%ld) Fatal error: ", this_thread);
379 outc = sprintf(outbuf, "IJB(%ld) Request: ", this_thread);
381 case LOG_LEVEL_CONNECT:
382 outc = sprintf(outbuf, "IJB(%ld) Connect: ", this_thread);
385 outc = sprintf(outbuf, "IJB(%ld) Writing: ", this_thread);
387 case LOG_LEVEL_HEADER:
388 outc = sprintf(outbuf, "IJB(%ld) Header: ", this_thread);
391 outc = sprintf(outbuf, "IJB(%ld) Info: ", this_thread);
393 case LOG_LEVEL_RE_FILTER:
394 outc = sprintf(outbuf, "IJB(%ld) Re-Filter: ", this_thread);
396 #ifdef FEATURE_FORCE_LOAD
397 case LOG_LEVEL_FORCE:
398 outc = sprintf(outbuf, "IJB(%ld) Force: ", this_thread);
400 #endif /* def FEATURE_FORCE_LOAD */
401 #ifdef FEATURE_FAST_REDIRECTS
402 case LOG_LEVEL_REDIRECTS:
403 outc = sprintf(outbuf, "IJB(%ld) Redirect: ", this_thread);
405 #endif /* def FEATURE_FAST_REDIRECTS */
406 case LOG_LEVEL_DEANIMATE:
407 outc = sprintf(outbuf, "IJB(%ld) Gif-Deanimate: ", this_thread);
410 outbuf = outbuf_save;
414 #ifdef FEATURE_KILL_POPUPS
415 case LOG_LEVEL_POPUPS:
416 outc = sprintf(outbuf, "IJB(%ld) Kill-Popups: ", this_thread);
418 #endif /* def FEATURE_KILL_POPUPS */
420 outc = sprintf(outbuf, "IJB(%ld) CGI: ", this_thread);
423 outc = sprintf(outbuf, "IJB(%ld) UNKNOWN LOG TYPE(%d): ", this_thread, loglevel);
427 /* get ready to scan var. args. */
430 /* build formatted message from fmt and var-args */
431 while ((*src) && (outc < BUFFER_SIZE-2))
433 char tempbuf[BUFFER_SIZE];
452 outbuf[outc++] = '%';
455 ival = va_arg( ap, int );
457 outc += sprintf(tempbuf, "%d", ival);
458 if (outc < BUFFER_SIZE-1)
460 strcpy(outbuf + oldoutc, tempbuf);
464 outbuf[oldoutc] = '\0';
468 uval = va_arg( ap, unsigned );
470 outc += sprintf(tempbuf, "%u", uval);
471 if (outc < BUFFER_SIZE-1)
473 strcpy(outbuf + oldoutc, tempbuf);
477 outbuf[oldoutc] = '\0';
481 /* this is a modifier that must be followed by u or d */
485 lval = va_arg( ap, long );
487 outc += sprintf(tempbuf, "%ld", lval);
491 ulval = va_arg( ap, unsigned long );
493 outc += sprintf(tempbuf, "%lu", ulval);
498 sprintf(outbuf, "IJB(%ld) Error: log_error(): Bad format string:\n"
500 "Exiting.", this_thread, fmt);
501 /* FIXME RACE HAZARD: should start critical section error_log_use here */
506 fputs(outbuf, logfp);
507 /* FIXME RACE HAZARD: should end critical section error_log_use here */
512 if (outc < BUFFER_SIZE-1)
514 strcpy(outbuf + oldoutc, tempbuf);
518 outbuf[oldoutc] = '\0';
523 * Note that char paramaters are converted to int, so we need to
524 * pass "int" to va_arg. (See K&R, 2nd ed, section A7.3.2, page 202)
526 outbuf[outc++] = (char) va_arg( ap, int );
529 sval = va_arg( ap, char * );
531 outc += strlen(sval);
532 if (outc < BUFFER_SIZE-1)
534 strcpy(outbuf + oldoutc, sval);
538 outbuf[oldoutc] = '\0';
542 /* Non-standard: Print a counted string. Takes 2 parameters:
543 * int length, const char * string
545 ival = va_arg( ap, int );
546 sval = va_arg( ap, char * );
553 if (outc < BUFFER_SIZE-1)
555 memcpy(outbuf + oldoutc, sval, ival);
559 outbuf[oldoutc] = '\0';
563 /* Non-standard: Print error code from errno */
565 ival = WSAGetLastError();
566 sval = w32_socket_strerr(ival, tempbuf);
567 #else /* ifndef _WIN32 */
570 sval = strerror(ival);
571 #else /* ifndef HAVE_STRERROR */
573 #endif /* ndef HAVE_STRERROR */
576 sprintf(tempbuf, "(errno = %d)", ival);
579 #endif /* ndef _WIN32 */
581 outc += strlen(sval);
582 if (outc < BUFFER_SIZE-1)
584 strcpy(outbuf + oldoutc, sval);
588 outbuf[oldoutc] = '\0';
592 /* Non-standard: Print a Common Log File timestamp */
595 * Write timestamp into tempbuf.
597 * Complex because not all OSs have tm_gmtoff or
598 * the %z field in strftime()
605 gmt = *gmtime (&now);
606 tm_now = localtime (&now);
607 days = tm_now->tm_yday - gmt.tm_yday;
608 hrs = ((days < -1 ? 24 : 1 < days ? -24 : days * 24) + tm_now->tm_hour - gmt.tm_hour);
609 mins = hrs * 60 + tm_now->tm_min - gmt.tm_min;
610 strftime (tempbuf, BUFFER_SIZE-6, "%d/%b/%Y:%H:%M:%S ", tm_now);
611 sprintf (tempbuf + strlen(tempbuf), "%+03d%02d", mins / 60, abs(mins) % 60);
614 outc += strlen(tempbuf);
615 if (outc < BUFFER_SIZE-1)
617 strcpy(outbuf + oldoutc, tempbuf);
621 outbuf[oldoutc] = '\0';
625 sprintf(outbuf, "IJB(%ld) Error: log_error(): Bad format string:\n"
627 "Exiting.", this_thread, fmt);
628 /* FIXME RACE HAZARD: should start critical section error_log_use here */
633 fputs(outbuf_save, logfp);
634 /* FIXME RACE HAZARD: should end critical section error_log_use here */
635 fatal_error(outbuf_save);
643 /* done with var. args */
646 if (outc >= BUFFER_SIZE-2)
648 /* insufficient room for newline and trailing null. */
650 static const char warning[] = "... [too long, truncated]\n";
652 if (outc < BUFFER_SIZE)
654 /* Need to add terminating null in this case. */
658 /* Truncate output */
659 outbuf[BUFFER_SIZE - sizeof(warning)] = '\0';
662 strcat(outbuf, warning);
666 /* Add terminating newline and null */
667 outbuf[outc++] = '\n';
671 /* FIXME RACE HAZARD: should start critical section error_log_use here */
673 /* deal with glibc stupidity - it won't let you initialize logfp */
679 fputs(outbuf_save, logfp);
681 if (loglevel == LOG_LEVEL_FATAL)
683 fatal_error(outbuf_save);
687 /* FIXME RACE HAZARD: should end critical section error_log_use here */
689 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
690 /* Write to display */
691 LogPutString(outbuf_save);
692 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
698 /*********************************************************************
700 * Function : w32_socket_strerr
702 * Description : Translate the return value from WSAGetLastError()
706 * 1 : errcode = The return value from WSAGetLastError().
707 * 2 : tmp_buf = A temporary buffer that might be used to
710 * Returns : String representing the error code. This may be
711 * a global string constant or a string stored in
714 *********************************************************************/
715 static char *w32_socket_strerr(int errcode, char *tmp_buf)
717 #define TEXT_FOR_ERROR(code,text) \
718 if (errcode == code) \
720 return #code " - " text; \
723 TEXT_FOR_ERROR(WSAEACCES, "Permission denied")
724 TEXT_FOR_ERROR(WSAEADDRINUSE, "Address already in use.")
725 TEXT_FOR_ERROR(WSAEADDRNOTAVAIL, "Cannot assign requested address.");
726 TEXT_FOR_ERROR(WSAEAFNOSUPPORT, "Address family not supported by protocol family.");
727 TEXT_FOR_ERROR(WSAEALREADY, "Operation already in progress.");
728 TEXT_FOR_ERROR(WSAECONNABORTED, "Software caused connection abort.");
729 TEXT_FOR_ERROR(WSAECONNREFUSED, "Connection refused.");
730 TEXT_FOR_ERROR(WSAECONNRESET, "Connection reset by peer.");
731 TEXT_FOR_ERROR(WSAEDESTADDRREQ, "Destination address required.");
732 TEXT_FOR_ERROR(WSAEFAULT, "Bad address.");
733 TEXT_FOR_ERROR(WSAEHOSTDOWN, "Host is down.");
734 TEXT_FOR_ERROR(WSAEHOSTUNREACH, "No route to host.");
735 TEXT_FOR_ERROR(WSAEINPROGRESS, "Operation now in progress.");
736 TEXT_FOR_ERROR(WSAEINTR, "Interrupted function call.");
737 TEXT_FOR_ERROR(WSAEINVAL, "Invalid argument.");
738 TEXT_FOR_ERROR(WSAEISCONN, "Socket is already connected.");
739 TEXT_FOR_ERROR(WSAEMFILE, "Too many open sockets.");
740 TEXT_FOR_ERROR(WSAEMSGSIZE, "Message too long.");
741 TEXT_FOR_ERROR(WSAENETDOWN, "Network is down.");
742 TEXT_FOR_ERROR(WSAENETRESET, "Network dropped connection on reset.");
743 TEXT_FOR_ERROR(WSAENETUNREACH, "Network is unreachable.");
744 TEXT_FOR_ERROR(WSAENOBUFS, "No buffer space available.");
745 TEXT_FOR_ERROR(WSAENOPROTOOPT, "Bad protocol option.");
746 TEXT_FOR_ERROR(WSAENOTCONN, "Socket is not connected.");
747 TEXT_FOR_ERROR(WSAENOTSOCK, "Socket operation on non-socket.");
748 TEXT_FOR_ERROR(WSAEOPNOTSUPP, "Operation not supported.");
749 TEXT_FOR_ERROR(WSAEPFNOSUPPORT, "Protocol family not supported.");
750 TEXT_FOR_ERROR(WSAEPROCLIM, "Too many processes.");
751 TEXT_FOR_ERROR(WSAEPROTONOSUPPORT, "Protocol not supported.");
752 TEXT_FOR_ERROR(WSAEPROTOTYPE, "Protocol wrong type for socket.");
753 TEXT_FOR_ERROR(WSAESHUTDOWN, "Cannot send after socket shutdown.");
754 TEXT_FOR_ERROR(WSAESOCKTNOSUPPORT, "Socket type not supported.");
755 TEXT_FOR_ERROR(WSAETIMEDOUT, "Connection timed out.");
756 TEXT_FOR_ERROR(WSAEWOULDBLOCK, "Resource temporarily unavailable.");
757 TEXT_FOR_ERROR(WSAHOST_NOT_FOUND, "Host not found.");
758 TEXT_FOR_ERROR(WSANOTINITIALISED, "Successful WSAStartup not yet performed.");
759 TEXT_FOR_ERROR(WSANO_DATA, "Valid name, no data record of requested type.");
760 TEXT_FOR_ERROR(WSANO_RECOVERY, "This is a non-recoverable error.");
761 TEXT_FOR_ERROR(WSASYSNOTREADY, "Network subsystem is unavailable.");
762 TEXT_FOR_ERROR(WSATRY_AGAIN, "Non-authoritative host not found.");
763 TEXT_FOR_ERROR(WSAVERNOTSUPPORTED, "WINSOCK.DLL version out of range.");
764 TEXT_FOR_ERROR(WSAEDISCON, "Graceful shutdown in progress.");
766 * The following error codes are documented in the Microsoft WinSock
767 * reference guide, but don't actually exist.
769 * TEXT_FOR_ERROR(WSA_INVALID_HANDLE, "Specified event object handle is invalid.");
770 * TEXT_FOR_ERROR(WSA_INVALID_PARAMETER, "One or more parameters are invalid.");
771 * TEXT_FOR_ERROR(WSAINVALIDPROCTABLE, "Invalid procedure table from service provider.");
772 * TEXT_FOR_ERROR(WSAINVALIDPROVIDER, "Invalid service provider version number.");
773 * TEXT_FOR_ERROR(WSA_IO_PENDING, "Overlapped operations will complete later.");
774 * TEXT_FOR_ERROR(WSA_IO_INCOMPLETE, "Overlapped I/O event object not in signaled state.");
775 * TEXT_FOR_ERROR(WSA_NOT_ENOUGH_MEMORY, "Insufficient memory available.");
776 * TEXT_FOR_ERROR(WSAPROVIDERFAILEDINIT, "Unable to initialize a service provider.");
777 * TEXT_FOR_ERROR(WSASYSCALLFAILURE, "System call failure.");
778 * TEXT_FOR_ERROR(WSA_OPERATION_ABORTED, "Overlapped operation aborted.");
781 sprintf(tmp_buf, "(error number %d)", errcode);
784 #endif /* def _WIN32 */