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