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