1 const char errlog_rcs[] = "$Id: errlog.c,v 1.21 2001/10/25 03:40:47 david__schmidt 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.21 2001/10/25 03:40:47 david__schmidt
37 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
38 * threads to call select() simultaneously. So, it's time to do a real, live,
39 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
40 * (native). Both versions will work, but using __OS2__ offers multi-threading.
42 * Revision 1.20 2001/09/16 23:04:34 jongfoster
45 * Revision 1.19 2001/09/13 20:08:06 jongfoster
46 * Adding support for LOG_LEVEL_CGI
48 * Revision 1.18 2001/09/10 11:27:24 oes
49 * Declaration of w32_socket_strerr now conditional
51 * Revision 1.17 2001/09/10 10:17:13 oes
52 * Removed unused variable; Fixed sprintf format
54 * Revision 1.16 2001/07/30 22:08:36 jongfoster
55 * Tidying up #defines:
56 * - All feature #defines are now of the form FEATURE_xxx
57 * - Permanently turned off WIN_GUI_EDIT
58 * - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
60 * Revision 1.15 2001/07/29 17:41:10 jongfoster
61 * Now prints thread ID for each message (pthreads only)
63 * Revision 1.14 2001/07/19 19:03:48 haroon
64 * - Added case for LOG_LEVEL_POPUPS
66 * Revision 1.13 2001/07/13 13:58:58 oes
67 * - Added case for LOG_LEVEL_DEANIMATE
68 * - Removed all #ifdef PCRS
70 * Revision 1.12 2001/06/09 10:55:28 jongfoster
71 * Changing BUFSIZ ==> BUFFER_SIZE
73 * Revision 1.11 2001/06/01 18:14:49 jongfoster
74 * Changing the calls to strerr() to check HAVE_STRERR (which is defined
75 * in config.h if appropriate) rather than the NO_STRERR macro.
77 * Revision 1.10 2001/05/29 11:52:21 oes
78 * Conditional compilation of w32_socket_error
80 * Revision 1.9 2001/05/28 16:15:17 jongfoster
81 * Improved reporting of errors under Win32.
83 * Revision 1.8 2001/05/26 17:25:14 jongfoster
84 * Added support for CLF (Common Log Format) and fixed LOG_LEVEL_LOG
86 * Revision 1.7 2001/05/26 15:21:28 jongfoster
87 * Activity animation in Win32 GUI now works even if debug==0
89 * Revision 1.6 2001/05/25 21:55:08 jongfoster
90 * Now cleans up properly on FATAL (removes taskbar icon etc)
92 * Revision 1.5 2001/05/22 18:46:04 oes
94 * - Enabled filtering banners by size rather than URL
95 * by adding patterns that replace all standard banner
96 * sizes with the "Junkbuster" gif to the re_filterfile
98 * - Enabled filtering WebBugs by providing a pattern
99 * which kills all 1x1 images
101 * - Added support for PCRE_UNGREEDY behaviour to pcrs,
102 * which is selected by the (nonstandard and therefore
103 * capital) letter 'U' in the option string.
104 * It causes the quantifiers to be ungreedy by default.
105 * Appending a ? turns back to greedy (!).
107 * - Added a new interceptor ijb-send-banner, which
108 * sends back the "Junkbuster" gif. Without imagelist or
109 * MSIE detection support, or if tinygif = 1, or the
110 * URL isn't recognized as an imageurl, a lame HTML
111 * explanation is sent instead.
113 * - Added new feature, which permits blocking remote
114 * script redirects and firing back a local redirect
116 * The feature is conditionally compiled, i.e. it
117 * can be disabled with --disable-fast-redirects,
118 * plus it must be activated by a "fast-redirects"
119 * line in the config file, has its own log level
120 * and of course wants to be displayed by show-proxy-args
121 * Note: Boy, all the #ifdefs in 1001 locations and
122 * all the fumbling with configure.in and acconfig.h
123 * were *way* more work than the feature itself :-(
125 * - Because a generic redirect template was needed for
126 * this, tinygif = 3 now uses the same.
128 * - Moved GIFs, and other static HTTP response templates
133 * - Removed some >400 CRs again (Jon, you really worked
136 * Revision 1.4 2001/05/21 19:32:54 jongfoster
137 * Added another #ifdef _WIN_CONSOLE
139 * Revision 1.3 2001/05/20 01:11:40 jongfoster
140 * Added support for LOG_LEVEL_FATAL
141 * Renamed LOG_LEVEL_FRC to LOG_LEVEL_FORCE,
142 * and LOG_LEVEL_REF to LOG_LEVEL_RE_FILTER
144 * Revision 1.2 2001/05/17 22:42:01 oes
145 * - Cleaned CRLF's from the sources and related files
146 * - Repaired logging for REF and FRC
148 * Revision 1.1.1.1 2001/05/15 13:58:51 oes
149 * Initial import of version 2.9.3 source tree
152 *********************************************************************/
162 #if !defined(_WIN32) && !defined(__OS2__)
164 #endif /* !defined(_WIN32) && !defined(__OS2__) */
168 #ifdef FEATURE_PTHREAD
170 #endif /* def FEATURE_PTHREAD */
176 #endif /* ndef _WIN_CONSOLE */
177 #endif /* def _WIN32 */
187 const char errlog_h_rcs[] = ERRLOG_H_VERSION;
191 * LOG_LEVEL_FATAL cannot be turned off. (There are
192 * some exceptional situations where we need to get a
193 * message to the user).
195 #define LOG_LEVEL_MINIMUM LOG_LEVEL_FATAL
197 /* where to log (default: stderr) */
198 static FILE *logfp = NULL;
200 /* logging detail level. */
201 static int debug = (LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
203 /* static functions */
204 static void fatal_error(const char * error_message);
206 static char *w32_socket_strerr(int errcode, char *tmp_buf);
209 /*********************************************************************
211 * Function : fatal_error
213 * Description : Displays a fatal error to standard error (or, on
214 * a WIN32 GUI, to a dialog box), and exits
215 * JunkBuster with status code 1.
218 * 1 : error_message = The error message to display.
220 * Returns : Does not return.
222 *********************************************************************/
223 static void fatal_error(const char * error_message)
225 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
226 MessageBox(g_hwndLogFrame, error_message, "Internet JunkBuster Error",
227 MB_OK | MB_ICONERROR | MB_TASKMODAL | MB_SETFOREGROUND | MB_TOPMOST);
229 /* Cleanup - remove taskbar icon etc. */
232 #else /* if !defined(_WIN32) || defined(_WIN_CONSOLE) */
233 fputs(error_message, stderr);
234 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
240 /*********************************************************************
242 * Function : init_errlog
244 * Description : Initializes the logging module. Must call before
248 * 1 : prog_name = The program name.
249 * 2 : logfname = The logfile name, or NULL for stderr.
250 * 3 : debuglevel = The debugging level.
254 *********************************************************************/
255 void init_error_log(const char *prog_name, const char *logfname, int debuglevel)
259 /* FIXME RACE HAZARD: should start critical section error_log_use here */
261 /* set the logging detail level */
262 debug = debuglevel | LOG_LEVEL_MINIMUM;
264 if ((logfp != NULL) && (logfp != stderr))
270 /* set the designated log file */
273 if( !(fp = fopen(logfname, "a")) )
275 log_error(LOG_LEVEL_FATAL, "init_errlog(): can't open logfile: %s", logfname);
278 /* set logging to be completely unbuffered */
284 log_error(LOG_LEVEL_INFO, "Internet JunkBuster version " VERSION);
285 if (prog_name != NULL)
287 log_error(LOG_LEVEL_INFO, "Program name: %s", prog_name);
290 /* FIXME RACE HAZARD: should end critical section error_log_use here */
292 } /* init_error_log */
295 /*********************************************************************
297 * Function : log_error
299 * Description : This is the error-reporting and logging function.
302 * 1 : loglevel = the type of message to be logged
303 * 2 : fmt = the main string we want logged, printf-like
304 * 3 : ... = arguments to be inserted in fmt (printf-like).
308 *********************************************************************/
309 void log_error(int loglevel, char *fmt, ...)
313 char *outbuf_save = NULL;
316 long this_thread = 1; /* was: pthread_t this_thread;*/
322 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
324 * Irrespective of debug setting, a GET/POST/CONNECT makes
325 * the taskbar icon animate. (There is an option to disable
326 * this but checking that is handled inside LogShowActivity()).
328 if (loglevel == LOG_LEVEL_GPC)
332 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
334 /* verify if loglevel applies to current settings and bail out if negative */
335 if ((loglevel & debug) == 0)
340 /* FIXME get current thread id */
341 #ifdef FEATURE_PTHREAD
342 this_thread = (long)pthread_self();
345 ulrc = DosGetInfoBlocks(&ptib, NULL);
347 this_thread = ptib -> tib_ptib2 -> tib2_ultid;
348 #endif /* def FEATURE_PTHREAD */
350 outbuf_save = outbuf = (char*)malloc(BUFFER_SIZE);
355 * Write timestamp into tempbuf.
357 * Complex because not all OSs have tm_gmtoff or
358 * the %z field in strftime()
363 tm_now = localtime (&now);
364 strftime (outbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", tm_now);
365 outbuf += strlen( outbuf );
369 case LOG_LEVEL_ERROR:
370 outc = sprintf(outbuf, "IJB(%ld) Error: ", this_thread);
372 case LOG_LEVEL_FATAL:
373 outc = sprintf(outbuf, "IJB(%ld) Fatal error: ", this_thread);
376 outc = sprintf(outbuf, "IJB(%ld) Request: ", this_thread);
378 case LOG_LEVEL_CONNECT:
379 outc = sprintf(outbuf, "IJB(%ld) Connect: ", this_thread);
382 outc = sprintf(outbuf, "IJB(%ld) Writing: ", this_thread);
384 case LOG_LEVEL_HEADER:
385 outc = sprintf(outbuf, "IJB(%ld) Header: ", this_thread);
388 outc = sprintf(outbuf, "IJB(%ld) Info: ", this_thread);
390 case LOG_LEVEL_RE_FILTER:
391 outc = sprintf(outbuf, "IJB(%ld) Re-Filter: ", this_thread);
393 #ifdef FEATURE_FORCE_LOAD
394 case LOG_LEVEL_FORCE:
395 outc = sprintf(outbuf, "IJB(%ld) Force: ", this_thread);
397 #endif /* def FEATURE_FORCE_LOAD */
398 #ifdef FEATURE_FAST_REDIRECTS
399 case LOG_LEVEL_REDIRECTS:
400 outc = sprintf(outbuf, "IJB(%ld) Redirect: ", this_thread);
402 #endif /* def FEATURE_FAST_REDIRECTS */
403 case LOG_LEVEL_DEANIMATE:
404 outc = sprintf(outbuf, "IJB(%ld) Gif-Deanimate: ", this_thread);
410 #ifdef FEATURE_KILL_POPUPS
411 case LOG_LEVEL_POPUPS:
412 outc = sprintf(outbuf, "IJB(%ld) Kill-Popups: ", this_thread);
414 #endif /* def FEATURE_KILL_POPUPS */
416 outc = sprintf(outbuf, "IJB(%ld) CGI: ", this_thread);
419 outc = sprintf(outbuf, "IJB(%ld) UNKNOWN LOG TYPE(%d): ", this_thread, loglevel);
423 /* get ready to scan var. args. */
426 /* build formatted message from fmt and var-args */
427 while ((*src) && (outc < BUFFER_SIZE-2))
429 char tempbuf[BUFFER_SIZE];
448 outbuf[outc++] = '%';
451 ival = va_arg( ap, int );
453 outc += sprintf(tempbuf, "%d", ival);
454 if (outc < BUFFER_SIZE-1)
456 strcpy(outbuf + oldoutc, tempbuf);
460 outbuf[oldoutc] = '\0';
464 uval = va_arg( ap, unsigned );
466 outc += sprintf(tempbuf, "%u", uval);
467 if (outc < BUFFER_SIZE-1)
469 strcpy(outbuf + oldoutc, tempbuf);
473 outbuf[oldoutc] = '\0';
477 /* this is a modifier that must be followed by u or d */
481 lval = va_arg( ap, long );
483 outc += sprintf(tempbuf, "%ld", lval);
487 ulval = va_arg( ap, unsigned long );
489 outc += sprintf(tempbuf, "%lu", ulval);
494 sprintf(outbuf, "IJB(%ld) Error: log_error(): Bad format string:\n"
496 "Exiting.", this_thread, fmt);
497 /* FIXME RACE HAZARD: should start critical section error_log_use here */
502 fputs(outbuf, logfp);
503 /* FIXME RACE HAZARD: should end critical section error_log_use here */
508 if (outc < BUFFER_SIZE-1)
510 strcpy(outbuf + oldoutc, tempbuf);
514 outbuf[oldoutc] = '\0';
519 * Note that char paramaters are converted to int, so we need to
520 * pass "int" to va_arg. (See K&R, 2nd ed, section A7.3.2, page 202)
522 outbuf[outc++] = (char) va_arg( ap, int );
525 sval = va_arg( ap, char * );
527 outc += strlen(sval);
528 if (outc < BUFFER_SIZE-1)
530 strcpy(outbuf + oldoutc, sval);
534 outbuf[oldoutc] = '\0';
538 /* Non-standard: Print a counted string. Takes 2 parameters:
539 * int length, const char * string
541 ival = va_arg( ap, int );
542 sval = va_arg( ap, char * );
549 if (outc < BUFFER_SIZE-1)
551 memcpy(outbuf + oldoutc, sval, ival);
555 outbuf[oldoutc] = '\0';
559 /* Non-standard: Print error code from errno */
561 ival = WSAGetLastError();
562 sval = w32_socket_strerr(ival, tempbuf);
563 #else /* ifndef _WIN32 */
566 sval = strerror(ival);
567 #else /* ifndef HAVE_STRERROR */
569 #endif /* ndef HAVE_STRERROR */
572 sprintf(tempbuf, "(errno = %d)", ival);
575 #endif /* ndef _WIN32 */
577 outc += strlen(sval);
578 if (outc < BUFFER_SIZE-1)
580 strcpy(outbuf + oldoutc, sval);
584 outbuf[oldoutc] = '\0';
588 /* Non-standard: Print a Common Log File timestamp */
591 * Write timestamp into tempbuf.
593 * Complex because not all OSs have tm_gmtoff or
594 * the %z field in strftime()
601 gmt = *gmtime (&now);
602 tm_now = localtime (&now);
603 days = tm_now->tm_yday - gmt.tm_yday;
604 hrs = ((days < -1 ? 24 : 1 < days ? -24 : days * 24) + tm_now->tm_hour - gmt.tm_hour);
605 mins = hrs * 60 + tm_now->tm_min - gmt.tm_min;
606 strftime (tempbuf, BUFFER_SIZE-6, "%d/%b/%Y:%H:%M:%S ", tm_now);
607 sprintf (tempbuf + strlen(tempbuf), "%+03d%02d", mins / 60, abs(mins) % 60);
610 outc += strlen(tempbuf);
611 if (outc < BUFFER_SIZE-1)
613 strcpy(outbuf + oldoutc, tempbuf);
617 outbuf[oldoutc] = '\0';
621 sprintf(outbuf, "IJB(%ld) Error: log_error(): Bad format string:\n"
623 "Exiting.", this_thread, fmt);
624 /* FIXME RACE HAZARD: should start critical section error_log_use here */
629 fputs(outbuf_save, logfp);
630 /* FIXME RACE HAZARD: should end critical section error_log_use here */
631 fatal_error(outbuf_save);
639 /* done with var. args */
642 if (outc >= BUFFER_SIZE-2)
644 /* insufficient room for newline and trailing null. */
646 static const char warning[] = "... [too long, truncated]\n";
648 if (outc < BUFFER_SIZE)
650 /* Need to add terminating null in this case. */
654 /* Truncate output */
655 outbuf[BUFFER_SIZE - sizeof(warning)] = '\0';
658 strcat(outbuf, warning);
662 /* Add terminating newline and null */
663 outbuf[outc++] = '\n';
667 /* FIXME RACE HAZARD: should start critical section error_log_use here */
669 /* deal with glibc stupidity - it won't let you initialize logfp */
675 fputs(outbuf_save, logfp);
677 if (loglevel == LOG_LEVEL_FATAL)
679 fatal_error(outbuf_save);
683 /* FIXME RACE HAZARD: should end critical section error_log_use here */
685 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
686 /* Write to display */
687 LogPutString(outbuf_save);
688 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
694 /*********************************************************************
696 * Function : w32_socket_strerr
698 * Description : Translate the return value from WSAGetLastError()
702 * 1 : errcode = The return value from WSAGetLastError().
703 * 2 : tmp_buf = A temporary buffer that might be used to
706 * Returns : String representing the error code. This may be
707 * a global string constant or a string stored in
710 *********************************************************************/
711 static char *w32_socket_strerr(int errcode, char *tmp_buf)
713 #define TEXT_FOR_ERROR(code,text) \
714 if (errcode == code) \
716 return #code " - " text; \
719 TEXT_FOR_ERROR(WSAEACCES, "Permission denied")
720 TEXT_FOR_ERROR(WSAEADDRINUSE, "Address already in use.")
721 TEXT_FOR_ERROR(WSAEADDRNOTAVAIL, "Cannot assign requested address.");
722 TEXT_FOR_ERROR(WSAEAFNOSUPPORT, "Address family not supported by protocol family.");
723 TEXT_FOR_ERROR(WSAEALREADY, "Operation already in progress.");
724 TEXT_FOR_ERROR(WSAECONNABORTED, "Software caused connection abort.");
725 TEXT_FOR_ERROR(WSAECONNREFUSED, "Connection refused.");
726 TEXT_FOR_ERROR(WSAECONNRESET, "Connection reset by peer.");
727 TEXT_FOR_ERROR(WSAEDESTADDRREQ, "Destination address required.");
728 TEXT_FOR_ERROR(WSAEFAULT, "Bad address.");
729 TEXT_FOR_ERROR(WSAEHOSTDOWN, "Host is down.");
730 TEXT_FOR_ERROR(WSAEHOSTUNREACH, "No route to host.");
731 TEXT_FOR_ERROR(WSAEINPROGRESS, "Operation now in progress.");
732 TEXT_FOR_ERROR(WSAEINTR, "Interrupted function call.");
733 TEXT_FOR_ERROR(WSAEINVAL, "Invalid argument.");
734 TEXT_FOR_ERROR(WSAEISCONN, "Socket is already connected.");
735 TEXT_FOR_ERROR(WSAEMFILE, "Too many open sockets.");
736 TEXT_FOR_ERROR(WSAEMSGSIZE, "Message too long.");
737 TEXT_FOR_ERROR(WSAENETDOWN, "Network is down.");
738 TEXT_FOR_ERROR(WSAENETRESET, "Network dropped connection on reset.");
739 TEXT_FOR_ERROR(WSAENETUNREACH, "Network is unreachable.");
740 TEXT_FOR_ERROR(WSAENOBUFS, "No buffer space available.");
741 TEXT_FOR_ERROR(WSAENOPROTOOPT, "Bad protocol option.");
742 TEXT_FOR_ERROR(WSAENOTCONN, "Socket is not connected.");
743 TEXT_FOR_ERROR(WSAENOTSOCK, "Socket operation on non-socket.");
744 TEXT_FOR_ERROR(WSAEOPNOTSUPP, "Operation not supported.");
745 TEXT_FOR_ERROR(WSAEPFNOSUPPORT, "Protocol family not supported.");
746 TEXT_FOR_ERROR(WSAEPROCLIM, "Too many processes.");
747 TEXT_FOR_ERROR(WSAEPROTONOSUPPORT, "Protocol not supported.");
748 TEXT_FOR_ERROR(WSAEPROTOTYPE, "Protocol wrong type for socket.");
749 TEXT_FOR_ERROR(WSAESHUTDOWN, "Cannot send after socket shutdown.");
750 TEXT_FOR_ERROR(WSAESOCKTNOSUPPORT, "Socket type not supported.");
751 TEXT_FOR_ERROR(WSAETIMEDOUT, "Connection timed out.");
752 TEXT_FOR_ERROR(WSAEWOULDBLOCK, "Resource temporarily unavailable.");
753 TEXT_FOR_ERROR(WSAHOST_NOT_FOUND, "Host not found.");
754 TEXT_FOR_ERROR(WSANOTINITIALISED, "Successful WSAStartup not yet performed.");
755 TEXT_FOR_ERROR(WSANO_DATA, "Valid name, no data record of requested type.");
756 TEXT_FOR_ERROR(WSANO_RECOVERY, "This is a non-recoverable error.");
757 TEXT_FOR_ERROR(WSASYSNOTREADY, "Network subsystem is unavailable.");
758 TEXT_FOR_ERROR(WSATRY_AGAIN, "Non-authoritative host not found.");
759 TEXT_FOR_ERROR(WSAVERNOTSUPPORTED, "WINSOCK.DLL version out of range.");
760 TEXT_FOR_ERROR(WSAEDISCON, "Graceful shutdown in progress.");
762 * The following error codes are documented in the Microsoft WinSock
763 * reference guide, but don't actually exist.
765 * TEXT_FOR_ERROR(WSA_INVALID_HANDLE, "Specified event object handle is invalid.");
766 * TEXT_FOR_ERROR(WSA_INVALID_PARAMETER, "One or more parameters are invalid.");
767 * TEXT_FOR_ERROR(WSAINVALIDPROCTABLE, "Invalid procedure table from service provider.");
768 * TEXT_FOR_ERROR(WSAINVALIDPROVIDER, "Invalid service provider version number.");
769 * TEXT_FOR_ERROR(WSA_IO_PENDING, "Overlapped operations will complete later.");
770 * TEXT_FOR_ERROR(WSA_IO_INCOMPLETE, "Overlapped I/O event object not in signaled state.");
771 * TEXT_FOR_ERROR(WSA_NOT_ENOUGH_MEMORY, "Insufficient memory available.");
772 * TEXT_FOR_ERROR(WSAPROVIDERFAILEDINIT, "Unable to initialize a service provider.");
773 * TEXT_FOR_ERROR(WSASYSCALLFAILURE, "System call failure.");
774 * TEXT_FOR_ERROR(WSA_OPERATION_ABORTED, "Overlapped operation aborted.");
777 sprintf(tmp_buf, "(error number %d)", errcode);
780 #endif /* def _WIN32 */