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