will test.
[privoxy.git] / errlog.c
1 const char errlog_rcs[] = "$Id: errlog.c,v 1.32 2002/03/07 03:46:17 oes Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/errlog.c,v $
5  *
6  * Purpose     :  Log errors to a designated destination in an elegant,
7  *                printf-like fashion.
8  *
9  * Copyright   :  Written by and Copyright (C) 2001 the SourceForge
10  *                IJBSWA team.  http://ijbswa.sourceforge.net
11  *
12  *                Based on the Internet Junkbuster originally written
13  *                by and Copyright (C) 1997 Anonymous Coders and 
14  *                Junkbusters Corporation.  http://www.junkbusters.com
15  *
16  *                This program is free software; you can redistribute it 
17  *                and/or modify it under the terms of the GNU General
18  *                Public License as published by the Free Software
19  *                Foundation; either version 2 of the License, or (at
20  *                your option) any later version.
21  *
22  *                This program is distributed in the hope that it will
23  *                be useful, but WITHOUT ANY WARRANTY; without even the
24  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
25  *                PARTICULAR PURPOSE.  See the GNU General Public
26  *                License for more details.
27  *
28  *                The GNU General Public License should be included with
29  *                this file.  If not, you can view it at
30  *                http://www.gnu.org/copyleft/gpl.html
31  *                or write to the Free Software Foundation, Inc., 59
32  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
33  *
34  * Revisions   :
35  *    $Log: errlog.c,v $
36  *    Revision 1.32  2002/03/07 03:46:17  oes
37  *    Fixed compiler warnings
38  *
39  *    Revision 1.31  2002/03/06 23:02:57  jongfoster
40  *    Removing tabs
41  *
42  *    Revision 1.30  2002/03/05 22:43:45  david__schmidt
43  *    - Better error reporting on OS/2
44  *    - Fix double-slash comment (oops)
45  *
46  *    Revision 1.29  2002/03/04 23:45:13  jongfoster
47  *    Printing thread ID if using Win32 native threads
48  *
49  *    Revision 1.28  2002/03/04 17:59:59  oes
50  *    Deleted deletePidFile(), cosmetics
51  *
52  *    Revision 1.27  2002/03/04 02:08:01  david__schmidt
53  *    Enable web editing of actions file on OS/2 (it had been broken all this time!)
54  *
55  *    Revision 1.26  2002/01/09 19:05:45  steudten
56  *    Fix big memory leak.
57  *
58  *    Revision 1.25  2002/01/09 14:32:08  oes
59  *    Added support for gmtime_r and localtime_r.
60  *
61  *    Revision 1.24  2001/12/30 14:07:32  steudten
62  *    - Add signal handling (unix)
63  *    - Add SIGHUP handler (unix)
64  *    - Add creation of pidfile (unix)
65  *    - Add action 'top' in rc file (RH)
66  *    - Add entry 'SIGNALS' to manpage
67  *    - Add exit message to logfile (unix)
68  *
69  *    Revision 1.23  2001/11/07 00:02:13  steudten
70  *    Add line number in error output for lineparsing for
71  *    actionsfile and configfile.
72  *    Special handling for CLF added.
73  *
74  *    Revision 1.22  2001/11/05 23:43:05  steudten
75  *    Add time+date to log files.
76  *
77  *    Revision 1.21  2001/10/25 03:40:47  david__schmidt
78  *    Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
79  *    threads to call select() simultaneously.  So, it's time to do a real, live,
80  *    native OS/2 port.  See defines for __EMX__ (the porting layer) vs. __OS2__
81  *    (native). Both versions will work, but using __OS2__ offers multi-threading.
82  *
83  *    Revision 1.20  2001/09/16 23:04:34  jongfoster
84  *    Fixing a warning
85  *
86  *    Revision 1.19  2001/09/13 20:08:06  jongfoster
87  *    Adding support for LOG_LEVEL_CGI
88  *
89  *    Revision 1.18  2001/09/10 11:27:24  oes
90  *    Declaration of w32_socket_strerr now conditional
91  *
92  *    Revision 1.17  2001/09/10 10:17:13  oes
93  *    Removed unused variable; Fixed sprintf format
94  *
95  *    Revision 1.16  2001/07/30 22:08:36  jongfoster
96  *    Tidying up #defines:
97  *    - All feature #defines are now of the form FEATURE_xxx
98  *    - Permanently turned off WIN_GUI_EDIT
99  *    - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
100  *
101  *    Revision 1.15  2001/07/29 17:41:10  jongfoster
102  *    Now prints thread ID for each message (pthreads only)
103  *
104  *    Revision 1.14  2001/07/19 19:03:48  haroon
105  *    - Added case for LOG_LEVEL_POPUPS
106  *
107  *    Revision 1.13  2001/07/13 13:58:58  oes
108  *     - Added case for LOG_LEVEL_DEANIMATE
109  *     - Removed all #ifdef PCRS
110  *
111  *    Revision 1.12  2001/06/09 10:55:28  jongfoster
112  *    Changing BUFSIZ ==> BUFFER_SIZE
113  *
114  *    Revision 1.11  2001/06/01 18:14:49  jongfoster
115  *    Changing the calls to strerr() to check HAVE_STRERR (which is defined
116  *    in config.h if appropriate) rather than the NO_STRERR macro.
117  *
118  *    Revision 1.10  2001/05/29 11:52:21  oes
119  *    Conditional compilation of w32_socket_error
120  *
121  *    Revision 1.9  2001/05/28 16:15:17  jongfoster
122  *    Improved reporting of errors under Win32.
123  *
124  *    Revision 1.8  2001/05/26 17:25:14  jongfoster
125  *    Added support for CLF (Common Log Format) and fixed LOG_LEVEL_LOG
126  *
127  *    Revision 1.7  2001/05/26 15:21:28  jongfoster
128  *    Activity animation in Win32 GUI now works even if debug==0
129  *
130  *    Revision 1.6  2001/05/25 21:55:08  jongfoster
131  *    Now cleans up properly on FATAL (removes taskbar icon etc)
132  *
133  *    Revision 1.5  2001/05/22 18:46:04  oes
134  *
135  *    - Enabled filtering banners by size rather than URL
136  *      by adding patterns that replace all standard banner
137  *      sizes with the "Junkbuster" gif to the re_filterfile
138  *
139  *    - Enabled filtering WebBugs by providing a pattern
140  *      which kills all 1x1 images
141  *
142  *    - Added support for PCRE_UNGREEDY behaviour to pcrs,
143  *      which is selected by the (nonstandard and therefore
144  *      capital) letter 'U' in the option string.
145  *      It causes the quantifiers to be ungreedy by default.
146  *      Appending a ? turns back to greedy (!).
147  *
148  *    - Added a new interceptor ijb-send-banner, which
149  *      sends back the "Junkbuster" gif. Without imagelist or
150  *      MSIE detection support, or if tinygif = 1, or the
151  *      URL isn't recognized as an imageurl, a lame HTML
152  *      explanation is sent instead.
153  *
154  *    - Added new feature, which permits blocking remote
155  *      script redirects and firing back a local redirect
156  *      to the browser.
157  *      The feature is conditionally compiled, i.e. it
158  *      can be disabled with --disable-fast-redirects,
159  *      plus it must be activated by a "fast-redirects"
160  *      line in the config file, has its own log level
161  *      and of course wants to be displayed by show-proxy-args
162  *      Note: Boy, all the #ifdefs in 1001 locations and
163  *      all the fumbling with configure.in and acconfig.h
164  *      were *way* more work than the feature itself :-(
165  *
166  *    - Because a generic redirect template was needed for
167  *      this, tinygif = 3 now uses the same.
168  *
169  *    - Moved GIFs, and other static HTTP response templates
170  *      to project.h
171  *
172  *    - Some minor fixes
173  *
174  *    - Removed some >400 CRs again (Jon, you really worked
175  *      a lot! ;-)
176  *
177  *    Revision 1.4  2001/05/21 19:32:54  jongfoster
178  *    Added another #ifdef _WIN_CONSOLE
179  *
180  *    Revision 1.3  2001/05/20 01:11:40  jongfoster
181  *    Added support for LOG_LEVEL_FATAL
182  *    Renamed LOG_LEVEL_FRC to LOG_LEVEL_FORCE,
183  *    and LOG_LEVEL_REF to LOG_LEVEL_RE_FILTER
184  *
185  *    Revision 1.2  2001/05/17 22:42:01  oes
186  *     - Cleaned CRLF's from the sources and related files
187  *     - Repaired logging for REF and FRC
188  *
189  *    Revision 1.1.1.1  2001/05/15 13:58:51  oes
190  *    Initial import of version 2.9.3 source tree
191  *
192  *
193  *********************************************************************/
194 \f
195
196 #include "config.h"
197 #include "miscutil.h"
198
199 #include <stdlib.h>
200 #include <stdio.h>
201 #include <stdarg.h>
202 #include <string.h>
203
204 #if !defined(_WIN32) && !defined(__OS2__)
205 #include <unistd.h>
206 #endif /* !defined(_WIN32) && !defined(__OS2__) */
207
208 #include <errno.h>
209 #include <assert.h>
210 #ifdef FEATURE_PTHREAD
211 #include <pthread.h>
212 #endif /* def FEATURE_PTHREAD */
213
214 #ifdef _WIN32
215 #include <windows.h>
216 #ifndef _WIN_CONSOLE
217 #include "w32log.h"
218 #endif /* ndef _WIN_CONSOLE */
219 #endif /* def _WIN32 */
220
221 #ifdef __OS2__
222 #define INCL_DOS
223 #include <os2.h>
224 #endif
225
226 #include "errlog.h"
227 #include "project.h"
228 #include "jcc.h"
229
230 const char errlog_h_rcs[] = ERRLOG_H_VERSION;
231
232
233 /*
234  * LOG_LEVEL_FATAL cannot be turned off.  (There are
235  * some exceptional situations where we need to get a
236  * message to the user).
237  */
238 #define LOG_LEVEL_MINIMUM  LOG_LEVEL_FATAL
239
240 /* where to log (default: stderr) */
241 static FILE *logfp = NULL;
242
243 /* logging detail level.  */
244 static int debug = (LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);  
245
246 /* static functions */
247 static void fatal_error(const char * error_message);
248 #ifdef _WIN32
249 static char *w32_socket_strerr(int errcode, char *tmp_buf);
250 #endif
251
252 /*********************************************************************
253  *
254  * Function    :  fatal_error
255  *
256  * Description :  Displays a fatal error to standard error (or, on 
257  *                a WIN32 GUI, to a dialog box), and exits
258  *                JunkBuster with status code 1.
259  *
260  * Parameters  :
261  *          1  :  error_message = The error message to display.
262  *
263  * Returns     :  Does not return.
264  *
265  *********************************************************************/
266 static void fatal_error(const char * error_message)
267 {
268 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
269    MessageBox(g_hwndLogFrame, error_message, "Internet JunkBuster Error", 
270       MB_OK | MB_ICONERROR | MB_TASKMODAL | MB_SETFOREGROUND | MB_TOPMOST);  
271
272    /* Cleanup - remove taskbar icon etc. */
273    TermLogWindow();
274
275 #else /* if !defined(_WIN32) || defined(_WIN_CONSOLE) */
276    fputs(error_message, stderr);
277 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
278
279 #if defined(unix)
280    unlink(pidfile);
281 #endif /* unix */
282
283    exit(1);
284 }
285
286
287 /*********************************************************************
288  *
289  * Function    :  init_error_log
290  *
291  * Description :  Initializes the logging module.  Must call before
292  *                calling log_error.
293  *
294  * Parameters  :
295  *          1  :  prog_name  = The program name.
296  *          2  :  logfname   = The logfile name, or NULL for stderr.
297  *          3  :  debuglevel = The debugging level.
298  *
299  * Returns     :  N/A
300  *
301  *********************************************************************/
302 void init_error_log(const char *prog_name, const char *logfname, int debuglevel)
303 {
304    FILE *fp;
305
306    /* FIXME RACE HAZARD: should start critical section error_log_use here */
307
308    /* set the logging detail level */
309    debug = debuglevel | LOG_LEVEL_MINIMUM;
310
311    if ((logfp != NULL) && (logfp != stderr))
312    {
313       log_error(LOG_LEVEL_INFO, "(Re-)Open logfile %s", logfname ? logfname : "none");
314       fclose(logfp);
315    }
316    logfp = stderr;
317
318    /* set the designated log file */
319    if( logfname )
320    {
321       if( NULL == (fp = fopen(logfname, "a")) )
322       {
323          log_error(LOG_LEVEL_FATAL, "init_error_log(): can't open logfile: %s", logfname);
324       }
325
326       /* set logging to be completely unbuffered */
327       setbuf(fp, NULL);
328
329       logfp = fp;
330    }
331
332    log_error(LOG_LEVEL_INFO, "Internet JunkBuster version " VERSION);
333    if (prog_name != NULL)
334    {
335       log_error(LOG_LEVEL_INFO, "Program name: %s", prog_name);
336    }
337
338    /* FIXME RACE HAZARD: should end critical section error_log_use here */
339
340 } /* init_error_log */
341
342
343 /*********************************************************************
344  *
345  * Function    :  log_error
346  *
347  * Description :  This is the error-reporting and logging function.
348  *
349  * Parameters  :
350  *          1  :  loglevel  = the type of message to be logged
351  *          2  :  fmt       = the main string we want logged, printf-like
352  *          3  :  ...       = arguments to be inserted in fmt (printf-like).
353  *
354  * Returns     :  N/A
355  *
356  *********************************************************************/
357 void log_error(int loglevel, char *fmt, ...)
358 {
359    va_list ap;
360    char *outbuf= NULL;
361    static char *outbuf_save = NULL;
362    char * src = fmt;
363    int outc = 0;
364    long this_thread = 1;  /* was: pthread_t this_thread;*/
365 #ifdef __OS2__
366    PTIB     ptib;
367    APIRET   ulrc;
368 #endif /* __OS2__ */
369
370 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
371    /*
372     * Irrespective of debug setting, a GET/POST/CONNECT makes
373     * the taskbar icon animate.  (There is an option to disable
374     * this but checking that is handled inside LogShowActivity()).
375     */
376    if (loglevel == LOG_LEVEL_GPC)
377    {
378       LogShowActivity();
379    }
380 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
381
382    /* verify if loglevel applies to current settings and bail out if negative */
383    if ((loglevel & debug) == 0)
384    {
385       return;
386    }
387
388    /* FIXME get current thread id */
389 #ifdef FEATURE_PTHREAD
390    this_thread = (long)pthread_self();
391 #elif defined(_WIN32)
392    this_thread = GetCurrentThreadId();
393 #elif defined(__OS2__)
394    ulrc = DosGetInfoBlocks(&ptib, NULL);
395    if (ulrc == 0)
396      this_thread = ptib -> tib_ptib2 -> tib2_ultid;
397 #endif /* def FEATURE_PTHREAD */
398
399    if ( !outbuf_save ) 
400    {
401       outbuf_save = outbuf = (char*)malloc(BUFFER_SIZE);
402       assert(outbuf);
403    }
404    outbuf = outbuf_save;
405
406     {
407        /*
408         * Write timestamp into tempbuf.
409         *
410         * Complex because not all OSs have tm_gmtoff or
411         * the %z field in strftime()
412         */
413        time_t now; 
414        struct tm tm_now; 
415        time (&now);
416 #ifdef HAVE_LOCALTIME_R
417        tm_now = *localtime_r(&now, &tm_now);
418 #else
419        tm_now = *localtime (&now); 
420 #endif
421        strftime(outbuf, BUFFER_SIZE-6, "%b %d %H:%M:%S ", &tm_now); 
422        outbuf += strlen( outbuf );
423     }
424    switch (loglevel)
425    {
426       case LOG_LEVEL_ERROR:
427          outc = sprintf(outbuf, "IJB(%ld) Error: ", this_thread);
428          break;
429       case LOG_LEVEL_FATAL:
430          outc = sprintf(outbuf, "IJB(%ld) Fatal error: ", this_thread);
431          break;
432       case LOG_LEVEL_GPC:
433          outc = sprintf(outbuf, "IJB(%ld) Request: ", this_thread);
434          break;
435       case LOG_LEVEL_CONNECT:
436          outc = sprintf(outbuf, "IJB(%ld) Connect: ", this_thread);
437          break;
438       case LOG_LEVEL_LOG:
439          outc = sprintf(outbuf, "IJB(%ld) Writing: ", this_thread);
440          break;
441       case LOG_LEVEL_HEADER:
442          outc = sprintf(outbuf, "IJB(%ld) Header: ", this_thread);
443          break;
444       case LOG_LEVEL_INFO:
445          outc = sprintf(outbuf, "IJB(%ld) Info: ", this_thread);
446          break;
447       case LOG_LEVEL_RE_FILTER:
448          outc = sprintf(outbuf, "IJB(%ld) Re-Filter: ", this_thread);
449          break;
450 #ifdef FEATURE_FORCE_LOAD
451       case LOG_LEVEL_FORCE:
452          outc = sprintf(outbuf, "IJB(%ld) Force: ", this_thread);
453          break;
454 #endif /* def FEATURE_FORCE_LOAD */
455 #ifdef FEATURE_FAST_REDIRECTS
456       case LOG_LEVEL_REDIRECTS:
457          outc = sprintf(outbuf, "IJB(%ld) Redirect: ", this_thread);
458          break;
459 #endif /* def FEATURE_FAST_REDIRECTS */
460       case LOG_LEVEL_DEANIMATE:
461          outc = sprintf(outbuf, "IJB(%ld) Gif-Deanimate: ", this_thread);
462          break;
463       case LOG_LEVEL_CLF:
464          outbuf = outbuf_save;
465          outc = 0;
466          outbuf[0] = '\0';
467          break;
468 #ifdef FEATURE_KILL_POPUPS
469       case LOG_LEVEL_POPUPS:
470          outc = sprintf(outbuf, "IJB(%ld) Kill-Popups: ", this_thread);
471          break;
472 #endif /* def FEATURE_KILL_POPUPS */
473       case LOG_LEVEL_CGI:
474          outc = sprintf(outbuf, "IJB(%ld) CGI: ", this_thread);
475          break;
476       default:
477          outc = sprintf(outbuf, "IJB(%ld) UNKNOWN LOG TYPE(%d): ", this_thread, loglevel);
478          break;
479    }
480    
481    /* get ready to scan var. args. */
482    va_start( ap, fmt );
483
484    /* build formatted message from fmt and var-args */
485    while ((*src) && (outc < BUFFER_SIZE-2))
486    {
487       char tempbuf[BUFFER_SIZE];
488       char *sval = NULL;
489       int ival;
490       unsigned uval;
491       long lval;
492       unsigned long ulval;
493       int oldoutc;
494       char ch;
495       
496       ch = *src++;
497       if( ch != '%' )
498       {
499          outbuf[outc++] = ch;
500          continue;
501       }
502
503       ch = *src++;
504       switch (ch) {
505          case '%':
506             outbuf[outc++] = '%';
507             break;
508          case 'd':
509             ival = va_arg( ap, int );
510             oldoutc = outc;
511             outc += sprintf(tempbuf, "%d", ival);
512             if (outc < BUFFER_SIZE-1) 
513             {
514                strcpy(outbuf + oldoutc, tempbuf);
515             }
516             else
517             {
518                outbuf[oldoutc] = '\0';
519             }
520             break;
521          case 'u':
522             uval = va_arg( ap, unsigned );
523             oldoutc = outc;
524             outc += sprintf(tempbuf, "%u", uval);
525             if (outc < BUFFER_SIZE-1) 
526             {
527                strcpy(outbuf + oldoutc, tempbuf);
528             }
529             else
530             {
531                outbuf[oldoutc] = '\0';
532             }
533             break;
534          case 'l':
535             /* this is a modifier that must be followed by u or d */
536             ch = *src++;
537             if (ch == 'd')
538             {
539                lval = va_arg( ap, long );
540                oldoutc = outc;
541                outc += sprintf(tempbuf, "%ld", lval);
542             }
543             else if (ch == 'u')
544             {
545                ulval = va_arg( ap, unsigned long );
546                oldoutc = outc;
547                outc += sprintf(tempbuf, "%lu", ulval);
548             }
549             else
550             {
551                /* Error */
552                sprintf(outbuf, "IJB(%ld) Error: log_error(): Bad format string:\n"
553                                "Format = \"%s\"\n"
554                                "Exiting.", this_thread, fmt);
555                /* FIXME RACE HAZARD: should start critical section error_log_use here */
556                if( !logfp )
557                {
558                   logfp = stderr;
559                }
560                fputs(outbuf, logfp);
561                /* FIXME RACE HAZARD: should end critical section error_log_use here */
562                fatal_error(outbuf);
563                /* Never get here */
564                break;
565             }
566             if (outc < BUFFER_SIZE-1) 
567             {
568                strcpy(outbuf + oldoutc, tempbuf);
569             }
570             else
571             {
572                outbuf[oldoutc] = '\0';
573             }
574             break;
575          case 'c':
576             /*
577              * Note that char paramaters are converted to int, so we need to
578              * pass "int" to va_arg.  (See K&R, 2nd ed, section A7.3.2, page 202)
579              */
580             outbuf[outc++] = (char) va_arg( ap, int );
581             break;
582          case 's':
583             sval = va_arg( ap, char * );
584             oldoutc = outc;
585             outc += strlen(sval);
586             if (outc < BUFFER_SIZE-1) 
587             {
588                strcpy(outbuf + oldoutc, sval);
589             }
590             else
591             {
592                outbuf[oldoutc] = '\0';
593             }
594             break;
595          case 'N':
596             /* Non-standard: Print a counted string.  Takes 2 parameters:
597              * int length, const char * string
598              */
599             ival = va_arg( ap, int );
600             sval = va_arg( ap, char * );
601             if (ival < 0)
602             {
603                ival = 0;
604             }
605             oldoutc = outc;
606             outc += ival;
607             if (outc < BUFFER_SIZE-1)
608             {
609                memcpy(outbuf + oldoutc, sval, (size_t) ival);
610             }
611             else
612             {
613                outbuf[oldoutc] = '\0';
614             }
615             break;
616          case 'E':
617             /* Non-standard: Print error code from errno */
618 #ifdef _WIN32
619             ival = WSAGetLastError();
620             sval = w32_socket_strerr(ival, tempbuf);
621 #elif __OS2__
622             ival = sock_errno();
623             if (ival == 0)
624               ival = errno;
625             sval = strerror(ival);
626 #else /* ifndef _WIN32 */
627             ival = errno; 
628 #ifdef HAVE_STRERROR
629             sval = strerror(ival);
630 #else /* ifndef HAVE_STRERROR */
631             sval = NULL;
632 #endif /* ndef HAVE_STRERROR */
633             if (sval == NULL)
634             {
635                sprintf(tempbuf, "(errno = %d)", ival);
636                sval = tempbuf;
637             }
638 #endif /* ndef _WIN32 */
639             oldoutc = outc;
640             outc += strlen(sval);
641             if (outc < BUFFER_SIZE-1) 
642             {
643                strcpy(outbuf + oldoutc, sval);
644             }
645             else
646             {
647                outbuf[oldoutc] = '\0';
648             }
649             break;
650          case 'T':
651             /* Non-standard: Print a Common Log File timestamp */
652             {
653                /*
654                 * Write timestamp into tempbuf.
655                 *
656                 * Complex because not all OSs have tm_gmtoff or
657                 * the %z field in strftime()
658                 */
659                time_t now; 
660                struct tm *tm_now; 
661                struct tm gmt;
662 #ifdef HAVE_LOCALTIME_R
663                struct tm dummy;
664 #endif
665                int days, hrs, mins; 
666                time (&now); 
667 #ifdef HAVE_GMTIME_R
668                gmt = *gmtime_r(&now, &gmt);
669 #else
670                gmt = *gmtime(&now);
671 #endif
672 #ifdef HAVE_LOCALTIME_R
673                tm_now = localtime_r(&now, &dummy);
674 #else
675                tm_now = localtime (&now); 
676 #endif
677                days = tm_now->tm_yday - gmt.tm_yday; 
678                hrs = ((days < -1 ? 24 : 1 < days ? -24 : days * 24) + tm_now->tm_hour - gmt.tm_hour); 
679                mins = hrs * 60 + tm_now->tm_min - gmt.tm_min; 
680                strftime (tempbuf, BUFFER_SIZE-6, "%d/%b/%Y:%H:%M:%S ", tm_now); 
681                sprintf (tempbuf + strlen(tempbuf), "%+03d%02d", mins / 60, abs(mins) % 60); 
682             }
683             oldoutc = outc;
684             outc += strlen(tempbuf);
685             if (outc < BUFFER_SIZE-1) 
686             {
687                strcpy(outbuf + oldoutc, tempbuf);
688             }
689             else
690             {
691                outbuf[oldoutc] = '\0';
692             }
693             break;
694          default:
695             sprintf(outbuf, "IJB(%ld) Error: log_error(): Bad format string:\n"
696                             "Format = \"%s\"\n"
697                             "Exiting.", this_thread, fmt);
698             /* FIXME RACE HAZARD: should start critical section error_log_use here */
699             if( !logfp )
700             {
701                logfp = stderr;
702             }
703             fputs(outbuf_save, logfp);
704             /* FIXME RACE HAZARD: should end critical section error_log_use here */
705             fatal_error(outbuf_save);
706             /* Never get here */
707             break;
708
709       } /* switch( p ) */
710
711    } /* for( p ... ) */
712    
713    /* done with var. args */
714    va_end( ap );
715    
716    if (outc >= BUFFER_SIZE-2)
717    {
718       /* insufficient room for newline and trailing null. */
719
720       static const char warning[] = "... [too long, truncated]\n";
721
722       if (outc < BUFFER_SIZE)
723       {
724          /* Need to add terminating null in this case. */
725          outbuf[outc] = '\0';
726       }
727
728       /* Truncate output */
729       outbuf[BUFFER_SIZE - sizeof(warning)] = '\0';
730
731       /* Append warning */
732       strcat(outbuf, warning);
733    }
734    else
735    {
736       /* Add terminating newline and null */
737       outbuf[outc++] = '\n';
738       outbuf[outc] = '\0';
739    }
740
741    /* FIXME RACE HAZARD: should start critical section error_log_use here */
742
743    /* deal with glibc stupidity - it won't let you initialize logfp */
744    if( !logfp )
745    {
746       logfp = stderr;
747    }
748
749    fputs(outbuf_save, logfp);
750
751    if (loglevel == LOG_LEVEL_FATAL)
752    {
753       fatal_error(outbuf_save);
754       /* Never get here */
755    }
756
757    /* FIXME RACE HAZARD: should end critical section error_log_use here */
758
759 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
760    /* Write to display */
761    LogPutString(outbuf_save);
762 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
763
764 }
765
766
767 #ifdef _WIN32
768 /*********************************************************************
769  *
770  * Function    :  w32_socket_strerr
771  *
772  * Description :  Translate the return value from WSAGetLastError()
773  *                into a string.
774  *
775  * Parameters  :
776  *          1  :  errcode = The return value from WSAGetLastError().
777  *          2  :  tmp_buf = A temporary buffer that might be used to
778  *                          store the string.
779  *
780  * Returns     :  String representing the error code.  This may be
781  *                a global string constant or a string stored in
782  *                tmp_buf.
783  *
784  *********************************************************************/
785 static char *w32_socket_strerr(int errcode, char *tmp_buf)
786 {
787 #define TEXT_FOR_ERROR(code,text) \
788    if (errcode == code)           \
789    {                              \
790       return #code " - " text;    \
791    }
792
793    TEXT_FOR_ERROR(WSAEACCES, "Permission denied")
794    TEXT_FOR_ERROR(WSAEADDRINUSE, "Address already in use.")
795    TEXT_FOR_ERROR(WSAEADDRNOTAVAIL, "Cannot assign requested address.");
796    TEXT_FOR_ERROR(WSAEAFNOSUPPORT, "Address family not supported by protocol family.");
797    TEXT_FOR_ERROR(WSAEALREADY, "Operation already in progress.");
798    TEXT_FOR_ERROR(WSAECONNABORTED, "Software caused connection abort.");
799    TEXT_FOR_ERROR(WSAECONNREFUSED, "Connection refused.");
800    TEXT_FOR_ERROR(WSAECONNRESET, "Connection reset by peer.");
801    TEXT_FOR_ERROR(WSAEDESTADDRREQ, "Destination address required.");
802    TEXT_FOR_ERROR(WSAEFAULT, "Bad address.");
803    TEXT_FOR_ERROR(WSAEHOSTDOWN, "Host is down.");
804    TEXT_FOR_ERROR(WSAEHOSTUNREACH, "No route to host.");
805    TEXT_FOR_ERROR(WSAEINPROGRESS, "Operation now in progress.");
806    TEXT_FOR_ERROR(WSAEINTR, "Interrupted function call.");
807    TEXT_FOR_ERROR(WSAEINVAL, "Invalid argument.");
808    TEXT_FOR_ERROR(WSAEISCONN, "Socket is already connected.");
809    TEXT_FOR_ERROR(WSAEMFILE, "Too many open sockets.");
810    TEXT_FOR_ERROR(WSAEMSGSIZE, "Message too long.");
811    TEXT_FOR_ERROR(WSAENETDOWN, "Network is down.");
812    TEXT_FOR_ERROR(WSAENETRESET, "Network dropped connection on reset.");
813    TEXT_FOR_ERROR(WSAENETUNREACH, "Network is unreachable.");
814    TEXT_FOR_ERROR(WSAENOBUFS, "No buffer space available.");
815    TEXT_FOR_ERROR(WSAENOPROTOOPT, "Bad protocol option.");
816    TEXT_FOR_ERROR(WSAENOTCONN, "Socket is not connected.");
817    TEXT_FOR_ERROR(WSAENOTSOCK, "Socket operation on non-socket.");
818    TEXT_FOR_ERROR(WSAEOPNOTSUPP, "Operation not supported.");
819    TEXT_FOR_ERROR(WSAEPFNOSUPPORT, "Protocol family not supported.");
820    TEXT_FOR_ERROR(WSAEPROCLIM, "Too many processes.");
821    TEXT_FOR_ERROR(WSAEPROTONOSUPPORT, "Protocol not supported.");
822    TEXT_FOR_ERROR(WSAEPROTOTYPE, "Protocol wrong type for socket.");
823    TEXT_FOR_ERROR(WSAESHUTDOWN, "Cannot send after socket shutdown.");
824    TEXT_FOR_ERROR(WSAESOCKTNOSUPPORT, "Socket type not supported.");
825    TEXT_FOR_ERROR(WSAETIMEDOUT, "Connection timed out.");
826    TEXT_FOR_ERROR(WSAEWOULDBLOCK, "Resource temporarily unavailable.");
827    TEXT_FOR_ERROR(WSAHOST_NOT_FOUND, "Host not found.");
828    TEXT_FOR_ERROR(WSANOTINITIALISED, "Successful WSAStartup not yet performed.");
829    TEXT_FOR_ERROR(WSANO_DATA, "Valid name, no data record of requested type.");
830    TEXT_FOR_ERROR(WSANO_RECOVERY, "This is a non-recoverable error.");
831    TEXT_FOR_ERROR(WSASYSNOTREADY, "Network subsystem is unavailable.");
832    TEXT_FOR_ERROR(WSATRY_AGAIN, "Non-authoritative host not found.");
833    TEXT_FOR_ERROR(WSAVERNOTSUPPORTED, "WINSOCK.DLL version out of range.");
834    TEXT_FOR_ERROR(WSAEDISCON, "Graceful shutdown in progress.");
835    /*
836     * The following error codes are documented in the Microsoft WinSock
837     * reference guide, but don't actually exist.
838     *
839     * TEXT_FOR_ERROR(WSA_INVALID_HANDLE, "Specified event object handle is invalid.");
840     * TEXT_FOR_ERROR(WSA_INVALID_PARAMETER, "One or more parameters are invalid.");
841     * TEXT_FOR_ERROR(WSAINVALIDPROCTABLE, "Invalid procedure table from service provider.");
842     * TEXT_FOR_ERROR(WSAINVALIDPROVIDER, "Invalid service provider version number.");
843     * TEXT_FOR_ERROR(WSA_IO_PENDING, "Overlapped operations will complete later.");
844     * TEXT_FOR_ERROR(WSA_IO_INCOMPLETE, "Overlapped I/O event object not in signaled state.");
845     * TEXT_FOR_ERROR(WSA_NOT_ENOUGH_MEMORY, "Insufficient memory available.");
846     * TEXT_FOR_ERROR(WSAPROVIDERFAILEDINIT, "Unable to initialize a service provider.");
847     * TEXT_FOR_ERROR(WSASYSCALLFAILURE, "System call failure.");
848     * TEXT_FOR_ERROR(WSA_OPERATION_ABORTED, "Overlapped operation aborted.");
849     */
850
851    sprintf(tmp_buf, "(error number %d)", errcode);
852    return tmp_buf;
853 }
854 #endif /* def _WIN32 */
855
856
857 /*
858   Local Variables:
859   tab-width: 3
860   end:
861 */