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