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