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