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