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