Fix entry count.
[privoxy.git] / errlog.c
1 const char errlog_rcs[] = "$Id: errlog.c,v 1.77 2008/09/07 12:43:44 fabiankeil 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-2007 the SourceForge
10  *                Privoxy team. http://www.privoxy.org/
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.77  2008/09/07 12:43:44  fabiankeil
37  *    Move the LogPutString() call in log_error() into the locked
38  *    region so the Windows GUI log is consistent with the logfile.
39  *
40  *    Revision 1.76  2008/09/07 12:35:05  fabiankeil
41  *    Add mutex lock support for _WIN32.
42  *
43  *    Revision 1.75  2008/09/04 08:13:58  fabiankeil
44  *    Prepare for critical sections on Windows by adding a
45  *    layer of indirection before the pthread mutex functions.
46  *
47  *    Revision 1.74  2008/08/06 18:33:36  fabiankeil
48  *    If the "close fd first" workaround doesn't work,
49  *    the fatal error message will be lost, so we better
50  *    explain the consequences while we still can.
51  *
52  *    Revision 1.73  2008/08/04 19:06:55  fabiankeil
53  *    Add a lame workaround for the "can't open an already open
54  *    logfile on OS/2" problem reported by Maynard in #2028842
55  *    and describe what a real solution would look like.
56  *
57  *    Revision 1.72  2008/07/27 12:04:28  fabiankeil
58  *    Fix a comment typo.
59  *
60  *    Revision 1.71  2008/06/28 17:17:15  fabiankeil
61  *    Remove another stray semicolon.
62  *
63  *    Revision 1.70  2008/06/28 17:10:29  fabiankeil
64  *    Remove stray semicolon in get_log_timestamp().
65  *    Reported by Jochen Voss in #2005221.
66  *
67  *    Revision 1.69  2008/05/30 15:55:25  fabiankeil
68  *    Declare variable "debug" static and complain about its name.
69  *
70  *    Revision 1.68  2008/04/27 16:50:46  fabiankeil
71  *    Remove an incorrect assertion. The value of debug may change if
72  *    the configuration is reloaded in another thread. While we could
73  *    cache the initial value, the assertion doesn't seem worth it.
74  *
75  *    Revision 1.67  2008/03/27 18:27:23  fabiankeil
76  *    Remove kill-popups action.
77  *
78  *    Revision 1.66  2008/01/31 15:38:14  fabiankeil
79  *    - Make the logfp assertion more strict. As of 1.63, the "||" could
80  *      have been an "&&", which means we can use two separate assertions
81  *      and skip on of them on Windows.
82  *    - Break a long commit message line in two.
83  *
84  *    Revision 1.65  2008/01/31 14:44:33  fabiankeil
85  *    Use (a != b) instead of !(a == b) so the sanity check looks less insane.
86  *
87  *    Revision 1.64  2008/01/21 18:56:46  david__schmidt
88  *    Swap #def from negative to positive, re-joined it so it didn't
89  *    span an assertion (compilation failure on OS/2)
90  *
91  *    Revision 1.63  2007/12/15 19:49:32  fabiankeil
92  *    Stop overloading logfile to control the mingw32 log window as well.
93  *    It's no longer necessary now that we disable all debug lines by default
94  *    and at least one user perceived it as a regression (added in 1.55).
95  *
96  *    Revision 1.62  2007/11/30 15:33:46  fabiankeil
97  *    Unbreak LOG_LEVEL_FATAL. It wasn't fatal with logging disabled
98  *    and on mingw32 fatal log messages didn't end up in the log file.
99  *
100  *    Revision 1.61  2007/11/04 19:03:01  fabiankeil
101  *    Fix another deadlock Hal spotted and that mysteriously didn't affect FreeBSD.
102  *
103  *    Revision 1.60  2007/11/03 19:03:31  fabiankeil
104  *    - Prevent the Windows GUI from showing the version two times in a row.
105  *    - Stop using the imperative in the "(Re-)Open logfile" message.
106  *    - Ditch the "Switching to daemon mode" message as the detection
107  *      whether or not we're already in daemon mode doesn't actually work.
108  *
109  *    Revision 1.59  2007/11/01 12:50:56  fabiankeil
110  *    Here's looking at you, deadlock.
111  *
112  *    Revision 1.58  2007/10/28 19:04:21  fabiankeil
113  *    Don't mention daemon mode in "Logging disabled" message. Some
114  *    platforms call it differently and it's not really relevant anyway.
115  *
116  *    Revision 1.57  2007/10/27 13:02:26  fabiankeil
117  *    Relocate daemon-mode-related log messages to make sure
118  *    they aren't shown again in case of configuration reloads.
119  *
120  *    Revision 1.56  2007/10/14 14:26:56  fabiankeil
121  *    Remove the old log_error() version.
122  *
123  *    Revision 1.55  2007/10/14 14:12:41  fabiankeil
124  *    When in daemon mode, close stderr after the configuration file has been
125  *    parsed the first time. If logfile isn't set, stop logging. Fixes BR#897436.
126  *
127  *    Revision 1.54  2007/09/22 16:15:34  fabiankeil
128  *    - Let it compile with pcc.
129  *    - Move our includes below system includes to prevent macro conflicts.
130  *
131  *    Revision 1.53  2007/08/05 13:53:14  fabiankeil
132  *    #1763173 from Stefan Huehner: declare some more functions
133  *    static and use void instead of empty parameter lists.
134  *
135  *    Revision 1.52  2007/07/14 07:28:47  fabiankeil
136  *    Add translation function for JB_ERR_FOO codes.
137  *
138  *    Revision 1.51  2007/05/11 11:51:34  fabiankeil
139  *    Fix a type mismatch warning.
140  *
141  *    Revision 1.50  2007/04/11 10:55:44  fabiankeil
142  *    Enforce some assertions that could be triggered
143  *    on mingw32 and other systems where we use threads
144  *    but no locks.
145  *
146  *    Revision 1.49  2007/04/08 16:44:15  fabiankeil
147  *    We need <sys/time.h> for gettimeofday(), not <time.h>.
148  *
149  *    Revision 1.48  2007/03/31 13:33:28  fabiankeil
150  *    Add alternative log_error() with timestamps
151  *    that contain milliseconds and without using
152  *    strcpy(), strcat() or sprintf().
153  *
154  *    Revision 1.47  2006/11/28 15:25:15  fabiankeil
155  *    Only unlink the pidfile if it's actually used.
156  *
157  *    Revision 1.46  2006/11/13 19:05:51  fabiankeil
158  *    Make pthread mutex locking more generic. Instead of
159  *    checking for OSX and OpenBSD, check for FEATURE_PTHREAD
160  *    and use mutex locking unless there is an _r function
161  *    available. Better safe than sorry.
162  *
163  *    Fixes "./configure --disable-pthread" and should result
164  *    in less threading-related problems on pthread-using platforms,
165  *    but it still doesn't fix BR#1122404.
166  *
167  *    Revision 1.45  2006/08/21 11:15:54  david__schmidt
168  *    MS Visual C++ build updates
169  *
170  *    Revision 1.44  2006/08/18 16:03:16  david__schmidt
171  *    Tweak for OS/2 build happiness.
172  *
173  *    Revision 1.43  2006/08/03 02:46:41  david__schmidt
174  *    Incorporate Fabian Keil's patch work:
175  *    http://www.fabiankeil.de/sourcecode/privoxy/
176  *
177  *    Revision 1.42  2006/07/18 14:48:46  david__schmidt
178  *    Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
179  *    with what was really the latest development (the v_3_0_branch branch)
180  *
181  *    Revision 1.40.2.4  2005/04/03 20:10:50  david__schmidt
182  *    Thanks to Jindrich Makovicka for a race condition fix for the log
183  *    file.  The race condition remains for non-pthread implementations.
184  *    Reference patch #1175720.
185  *
186  *    Revision 1.40.2.3  2003/03/07 03:41:04  david__schmidt
187  *    Wrapping all *_r functions (the non-_r versions of them) with mutex 
188  *    semaphores for OSX.  Hopefully this will take care of all of those pesky
189  *    crash reports.
190  *
191  *    Revision 1.40.2.2  2002/09/28 00:30:57  david__schmidt
192  *    Update error logging to give sane values for thread IDs on Mach kernels.
193  *    It's still a hack, but at least it looks farily normal.  We print the
194  *    absolute value of the first 4 bytes of the pthread_t modded with 1000.
195  *
196  *    Revision 1.40.2.1  2002/09/25 12:47:42  oes
197  *    Make log_error safe against NULL string arguments
198  *
199  *    Revision 1.40  2002/05/22 01:27:27  david__schmidt
200  *
201  *    Add os2_socket_strerr mirroring w32_socket_strerr.
202  *
203  *    Revision 1.39  2002/04/03 17:15:27  gliptak
204  *    zero padding thread ids in log
205  *
206  *    Revision 1.38  2002/03/31 17:18:59  jongfoster
207  *    Win32 only: Enabling STRICT to fix a VC++ compile warning.
208  *
209  *    Revision 1.37  2002/03/27 14:32:43  david__schmidt
210  *    More compiler warning message maintenance
211  *
212  *    Revision 1.36  2002/03/26 22:29:54  swa
213  *    we have a new homepage!
214  *
215  *    Revision 1.35  2002/03/24 15:23:33  jongfoster
216  *    Name changes
217  *
218  *    Revision 1.34  2002/03/24 13:25:43  swa
219  *    name change related issues
220  *
221  *    Revision 1.33  2002/03/13 00:27:04  jongfoster
222  *    Killing warnings
223  *
224  *    Revision 1.32  2002/03/07 03:46:17  oes
225  *    Fixed compiler warnings
226  *
227  *    Revision 1.31  2002/03/06 23:02:57  jongfoster
228  *    Removing tabs
229  *
230  *    Revision 1.30  2002/03/05 22:43:45  david__schmidt
231  *    - Better error reporting on OS/2
232  *    - Fix double-slash comment (oops)
233  *
234  *    Revision 1.29  2002/03/04 23:45:13  jongfoster
235  *    Printing thread ID if using Win32 native threads
236  *
237  *    Revision 1.28  2002/03/04 17:59:59  oes
238  *    Deleted deletePidFile(), cosmetics
239  *
240  *    Revision 1.27  2002/03/04 02:08:01  david__schmidt
241  *    Enable web editing of actions file on OS/2 (it had been broken all this time!)
242  *
243  *    Revision 1.26  2002/01/09 19:05:45  steudten
244  *    Fix big memory leak.
245  *
246  *    Revision 1.25  2002/01/09 14:32:08  oes
247  *    Added support for gmtime_r and localtime_r.
248  *
249  *    Revision 1.24  2001/12/30 14:07:32  steudten
250  *    - Add signal handling (unix)
251  *    - Add SIGHUP handler (unix)
252  *    - Add creation of pidfile (unix)
253  *    - Add action 'top' in rc file (RH)
254  *    - Add entry 'SIGNALS' to manpage
255  *    - Add exit message to logfile (unix)
256  *
257  *    Revision 1.23  2001/11/07 00:02:13  steudten
258  *    Add line number in error output for lineparsing for
259  *    actionsfile and configfile.
260  *    Special handling for CLF added.
261  *
262  *    Revision 1.22  2001/11/05 23:43:05  steudten
263  *    Add time+date to log files.
264  *
265  *    Revision 1.21  2001/10/25 03:40:47  david__schmidt
266  *    Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
267  *    threads to call select() simultaneously.  So, it's time to do a real, live,
268  *    native OS/2 port.  See defines for __EMX__ (the porting layer) vs. __OS2__
269  *    (native). Both versions will work, but using __OS2__ offers multi-threading.
270  *
271  *    Revision 1.20  2001/09/16 23:04:34  jongfoster
272  *    Fixing a warning
273  *
274  *    Revision 1.19  2001/09/13 20:08:06  jongfoster
275  *    Adding support for LOG_LEVEL_CGI
276  *
277  *    Revision 1.18  2001/09/10 11:27:24  oes
278  *    Declaration of w32_socket_strerr now conditional
279  *
280  *    Revision 1.17  2001/09/10 10:17:13  oes
281  *    Removed unused variable; Fixed sprintf format
282  *
283  *    Revision 1.16  2001/07/30 22:08:36  jongfoster
284  *    Tidying up #defines:
285  *    - All feature #defines are now of the form FEATURE_xxx
286  *    - Permanently turned off WIN_GUI_EDIT
287  *    - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
288  *
289  *    Revision 1.15  2001/07/29 17:41:10  jongfoster
290  *    Now prints thread ID for each message (pthreads only)
291  *
292  *    Revision 1.14  2001/07/19 19:03:48  haroon
293  *    - Added case for LOG_LEVEL_POPUPS
294  *
295  *    Revision 1.13  2001/07/13 13:58:58  oes
296  *     - Added case for LOG_LEVEL_DEANIMATE
297  *     - Removed all #ifdef PCRS
298  *
299  *    Revision 1.12  2001/06/09 10:55:28  jongfoster
300  *    Changing BUFSIZ ==> BUFFER_SIZE
301  *
302  *    Revision 1.11  2001/06/01 18:14:49  jongfoster
303  *    Changing the calls to strerr() to check HAVE_STRERR (which is defined
304  *    in config.h if appropriate) rather than the NO_STRERR macro.
305  *
306  *    Revision 1.10  2001/05/29 11:52:21  oes
307  *    Conditional compilation of w32_socket_error
308  *
309  *    Revision 1.9  2001/05/28 16:15:17  jongfoster
310  *    Improved reporting of errors under Win32.
311  *
312  *    Revision 1.8  2001/05/26 17:25:14  jongfoster
313  *    Added support for CLF (Common Log Format) and fixed LOG_LEVEL_LOG
314  *
315  *    Revision 1.7  2001/05/26 15:21:28  jongfoster
316  *    Activity animation in Win32 GUI now works even if debug==0
317  *
318  *    Revision 1.6  2001/05/25 21:55:08  jongfoster
319  *    Now cleans up properly on FATAL (removes taskbar icon etc)
320  *
321  *    Revision 1.5  2001/05/22 18:46:04  oes
322  *
323  *    - Enabled filtering banners by size rather than URL
324  *      by adding patterns that replace all standard banner
325  *      sizes with the "Junkbuster" gif to the re_filterfile
326  *
327  *    - Enabled filtering WebBugs by providing a pattern
328  *      which kills all 1x1 images
329  *
330  *    - Added support for PCRE_UNGREEDY behaviour to pcrs,
331  *      which is selected by the (nonstandard and therefore
332  *      capital) letter 'U' in the option string.
333  *      It causes the quantifiers to be ungreedy by default.
334  *      Appending a ? turns back to greedy (!).
335  *
336  *    - Added a new interceptor ijb-send-banner, which
337  *      sends back the "Junkbuster" gif. Without imagelist or
338  *      MSIE detection support, or if tinygif = 1, or the
339  *      URL isn't recognized as an imageurl, a lame HTML
340  *      explanation is sent instead.
341  *
342  *    - Added new feature, which permits blocking remote
343  *      script redirects and firing back a local redirect
344  *      to the browser.
345  *      The feature is conditionally compiled, i.e. it
346  *      can be disabled with --disable-fast-redirects,
347  *      plus it must be activated by a "fast-redirects"
348  *      line in the config file, has its own log level
349  *      and of course wants to be displayed by show-proxy-args
350  *      Note: Boy, all the #ifdefs in 1001 locations and
351  *      all the fumbling with configure.in and acconfig.h
352  *      were *way* more work than the feature itself :-(
353  *
354  *    - Because a generic redirect template was needed for
355  *      this, tinygif = 3 now uses the same.
356  *
357  *    - Moved GIFs, and other static HTTP response templates
358  *      to project.h
359  *
360  *    - Some minor fixes
361  *
362  *    - Removed some >400 CRs again (Jon, you really worked
363  *      a lot! ;-)
364  *
365  *    Revision 1.4  2001/05/21 19:32:54  jongfoster
366  *    Added another #ifdef _WIN_CONSOLE
367  *
368  *    Revision 1.3  2001/05/20 01:11:40  jongfoster
369  *    Added support for LOG_LEVEL_FATAL
370  *    Renamed LOG_LEVEL_FRC to LOG_LEVEL_FORCE,
371  *    and LOG_LEVEL_REF to LOG_LEVEL_RE_FILTER
372  *
373  *    Revision 1.2  2001/05/17 22:42:01  oes
374  *     - Cleaned CRLF's from the sources and related files
375  *     - Repaired logging for REF and FRC
376  *
377  *    Revision 1.1.1.1  2001/05/15 13:58:51  oes
378  *    Initial import of version 2.9.3 source tree
379  *
380  *
381  *********************************************************************/
382 \f
383
384 #include <stdlib.h>
385 #include <stdio.h>
386 #include <stdarg.h>
387 #include <string.h>
388
389 #include "config.h"
390 #include "miscutil.h"
391
392 /* For gettimeofday() */
393 #include <sys/time.h>
394
395 #if !defined(_WIN32) && !defined(__OS2__)
396 #include <unistd.h>
397 #endif /* !defined(_WIN32) && !defined(__OS2__) */
398
399 #include <errno.h>
400 #include <assert.h>
401
402 #ifdef _WIN32
403 #ifndef STRICT
404 #define STRICT
405 #endif
406 #include <windows.h>
407 #ifndef _WIN_CONSOLE
408 #include "w32log.h"
409 #endif /* ndef _WIN_CONSOLE */
410 #endif /* def _WIN32 */
411 #ifdef _MSC_VER
412 #define inline __inline
413 #endif /* def _MSC_VER */
414
415 #ifdef __OS2__
416 #include <sys/socket.h> /* For sock_errno */
417 #define INCL_DOS
418 #include <os2.h>
419 #endif
420
421 #include "errlog.h"
422 #include "project.h"
423 #include "jcc.h"
424
425 const char errlog_h_rcs[] = ERRLOG_H_VERSION;
426
427
428 /*
429  * LOG_LEVEL_FATAL cannot be turned off.  (There are
430  * some exceptional situations where we need to get a
431  * message to the user).
432  */
433 #define LOG_LEVEL_MINIMUM  LOG_LEVEL_FATAL
434
435 /* where to log (default: stderr) */
436 static FILE *logfp = NULL;
437
438 /* logging detail level. XXX: stupid name. */
439 static int debug = (LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);  
440
441 /* static functions */
442 static void fatal_error(const char * error_message);
443 #ifdef _WIN32
444 static char *w32_socket_strerr(int errcode, char *tmp_buf);
445 #endif
446 #ifdef __OS2__
447 static char *os2_socket_strerr(int errcode, char *tmp_buf);
448 #endif
449
450 #ifdef MUTEX_LOCKS_AVAILABLE
451 static inline void lock_logfile(void)
452 {
453    privoxy_mutex_lock(&log_mutex);
454 }
455 static inline void unlock_logfile(void)
456 {
457    privoxy_mutex_unlock(&log_mutex);
458 }
459 static inline void lock_loginit(void)
460 {
461    privoxy_mutex_lock(&log_init_mutex);
462 }
463 static inline void unlock_loginit(void)
464 {
465    privoxy_mutex_unlock(&log_init_mutex);
466 }
467 #else /* ! MUTEX_LOCKS_AVAILABLE */
468 /*
469  * FIXME we need a cross-platform locking mechanism.
470  * The locking/unlocking functions below should be 
471  * fleshed out for non-pthread implementations.
472  */ 
473 static inline void lock_logfile() {}
474 static inline void unlock_logfile() {}
475 static inline void lock_loginit() {}
476 static inline void unlock_loginit() {}
477 #endif
478
479 /*********************************************************************
480  *
481  * Function    :  fatal_error
482  *
483  * Description :  Displays a fatal error to standard error (or, on 
484  *                a WIN32 GUI, to a dialog box), and exits
485  *                JunkBuster with status code 1.
486  *
487  * Parameters  :
488  *          1  :  error_message = The error message to display.
489  *
490  * Returns     :  Does not return.
491  *
492  *********************************************************************/
493 static void fatal_error(const char * error_message)
494 {
495 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
496    MessageBox(g_hwndLogFrame, error_message, "Privoxy Error", 
497       MB_OK | MB_ICONERROR | MB_TASKMODAL | MB_SETFOREGROUND | MB_TOPMOST);  
498
499    /* Cleanup - remove taskbar icon etc. */
500    TermLogWindow();
501 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
502
503    if (logfp != NULL)
504    {
505       fputs(error_message, logfp);
506    }
507
508 #if defined(unix)
509    if (pidfile)
510    {
511       unlink(pidfile);
512    }
513 #endif /* unix */
514
515    exit(1);
516 }
517
518
519 /*********************************************************************
520  *
521  * Function    :  show_version
522  *
523  * Description :  Logs the Privoxy version and the program name.
524  *
525  * Parameters  :
526  *          1  :  prog_name = The program name.
527  *
528  * Returns     :  Nothing.
529  *
530  *********************************************************************/
531 static void show_version(const char *prog_name)
532 {
533    log_error(LOG_LEVEL_INFO, "Privoxy version " VERSION);
534    if (prog_name != NULL)
535    {
536       log_error(LOG_LEVEL_INFO, "Program name: %s", prog_name);
537    }
538 }
539
540
541 /*********************************************************************
542  *
543  * Function    :  init_log_module
544  *
545  * Description :  Initializes the logging module to log to stderr.
546  *                Can only be called while stderr hasn't been closed
547  *                yet and is only supposed to be called once.
548  *
549  * Parameters  :
550  *          1  :  prog_name = The program name.
551  *
552  * Returns     :  Nothing.
553  *
554  *********************************************************************/
555 void init_log_module(const char *prog_name)
556 {
557    lock_logfile();
558    logfp = stderr;
559    unlock_logfile();
560    set_debug_level(debug);
561    show_version(prog_name);
562 }
563
564
565 /*********************************************************************
566  *
567  * Function    :  set_debug_level
568  *
569  * Description :  Sets the debug level to the provided value
570  *                plus LOG_LEVEL_MINIMUM.
571  *
572  *                XXX: we should only use the LOG_LEVEL_MINIMUM
573  *                until the first time the configuration file has
574  *                been parsed.
575  *                
576  * Parameters  :  1: debug_level = The debug level to set.
577  *
578  * Returns     :  Nothing.
579  *
580  *********************************************************************/
581 void set_debug_level(int debug_level)
582 {
583    debug = debug_level | LOG_LEVEL_MINIMUM;
584 }
585
586
587 /*********************************************************************
588  *
589  * Function    :  disable_logging
590  *
591  * Description :  Disables logging.
592  *                
593  * Parameters  :  None.
594  *
595  * Returns     :  Nothing.
596  *
597  *********************************************************************/
598 void disable_logging(void)
599 {
600    if (logfp != NULL)
601    {
602       log_error(LOG_LEVEL_INFO,
603          "No logfile configured. Please enable it before reporting any problems.");
604       lock_logfile();
605       fclose(logfp);
606       logfp = NULL;
607       unlock_logfile();
608    }
609 }
610
611
612 /*********************************************************************
613  *
614  * Function    :  init_error_log
615  *
616  * Description :  Initializes the logging module to log to a file.
617  *
618  *                XXX: should be renamed.
619  *
620  * Parameters  :
621  *          1  :  prog_name  = The program name.
622  *          2  :  logfname   = The logfile name, or NULL for stderr.
623  *          3  :  debuglevel = The debugging level.
624  *
625  * Returns     :  N/A
626  *
627  *********************************************************************/
628 void init_error_log(const char *prog_name, const char *logfname)
629 {
630    FILE *fp;
631
632    assert(NULL != logfname);
633
634    lock_loginit();
635
636    if (logfp != NULL)
637    {
638       log_error(LOG_LEVEL_INFO, "(Re-)Opening logfile \'%s\'", logfname);
639    }
640
641    /* set the designated log file */
642    fp = fopen(logfname, "a");
643    if ((NULL == fp) && (logfp != NULL))
644    {
645       /*
646        * Some platforms (like OS/2) don't allow us to open
647        * the same file twice, therefore we give it another
648        * shot after closing the old file descriptor first.
649        *
650        * We don't do it right away because it prevents us
651        * from logging the "can't open logfile" message to
652        * the old logfile.
653        *
654        * XXX: this is a lame workaround and once the next
655        * release is out we should stop bothering reopening
656        * the logfile unless we have to.
657        *
658        * Currently we reopen it every time the config file
659        * has been reloaded, but actually we only have to
660        * reopen it if the file name changed or if the
661        * configuration reloas was caused by a SIGHUP.
662        */
663       log_error(LOG_LEVEL_INFO, "Failed to reopen logfile: \'%s\'. "
664          "Retrying after closing the old file descriptor first. If that "
665          "doesn't work, Privoxy will exit without being able to log a message.",
666          logfname);
667       lock_logfile();
668       fclose(logfp);
669       logfp = NULL;
670       unlock_logfile();
671       fp = fopen(logfname, "a");
672    }
673
674    if (NULL == fp)
675    {
676       log_error(LOG_LEVEL_FATAL, "init_error_log(): can't open logfile: \'%s\'", logfname);
677    }
678
679    /* set logging to be completely unbuffered */
680    setbuf(fp, NULL);
681
682    lock_logfile();
683    if (logfp != NULL)
684    {
685       fclose(logfp);
686    }
687    logfp = fp;
688    unlock_logfile();
689
690 #if !defined(_WIN32)
691    /*
692     * Prevent the Windows GUI from showing the version two
693     * times in a row on startup. It already displayed the show_version()
694     * call from init_log_module() that other systems write to stderr.
695     *
696     * This means mingw32 users will never see the version in their
697     * log file, but I assume they wouldn't look for it there anyway
698     * and simply use the "Help/About Privoxy" menu.
699     */
700    show_version(prog_name);
701 #endif /* def unix */
702
703    unlock_loginit();
704
705 } /* init_error_log */
706
707
708 /*********************************************************************
709  *
710  * Function    :  get_thread_id
711  *
712  * Description :  Returns a number that is different for each thread.
713  *
714  *                XXX: Should be moved elsewhere (miscutil.c?)
715  *                
716  * Parameters  :  None
717  *
718  * Returns     :  thread_id
719  *
720  *********************************************************************/
721 static long get_thread_id(void)
722 {
723    long this_thread = 1;  /* was: pthread_t this_thread;*/
724
725 #ifdef __OS2__
726    PTIB     ptib;
727    APIRET   ulrc; /* XXX: I have no clue what this does */
728 #endif /* __OS2__ */
729
730    /* FIXME get current thread id */
731 #ifdef FEATURE_PTHREAD
732    this_thread = (long)pthread_self();
733 #ifdef __MACH__
734    /*
735     * Mac OSX (and perhaps other Mach instances) doesn't have a debuggable
736     * value at the first 4 bytes of pthread_self()'s return value, a pthread_t.
737     * pthread_t is supposed to be opaque... but it's fairly random, though, so
738     * we make it mostly presentable.
739     */
740    this_thread = abs(this_thread % 1000);
741 #endif /* def __MACH__ */
742 #elif defined(_WIN32)
743    this_thread = GetCurrentThreadId();
744 #elif defined(__OS2__)
745    ulrc = DosGetInfoBlocks(&ptib, NULL);
746    if (ulrc == 0)
747      this_thread = ptib -> tib_ptib2 -> tib2_ultid;
748 #endif /* def FEATURE_PTHREAD */
749
750    return this_thread;
751 }
752
753
754 /*********************************************************************
755  *
756  * Function    :  get_log_timestamp
757  *
758  * Description :  Generates the time stamp for the log message prefix.
759  *
760  * Parameters  :
761  *          1  :  buffer = Storage buffer
762  *          2  :  buffer_size = Size of storage buffer
763  *
764  * Returns     :  Number of written characters or 0 for error.
765  *
766  *********************************************************************/
767 static inline size_t get_log_timestamp(char *buffer, size_t buffer_size)
768 {
769    size_t length;
770    time_t now; 
771    struct tm tm_now;
772    struct timeval tv_now; /* XXX: stupid name */
773    long msecs;
774    int msecs_length = 0;
775
776    gettimeofday(&tv_now, NULL);
777    msecs = tv_now.tv_usec / 1000;
778
779    time(&now);
780
781 #ifdef HAVE_LOCALTIME_R
782    tm_now = *localtime_r(&now, &tm_now);
783 #elif FEATURE_PTHREAD
784    privoxy_mutex_lock(&localtime_mutex);
785    tm_now = *localtime(&now); 
786    privoxy_mutex_unlock(&localtime_mutex);
787 #else
788    tm_now = *localtime(&now); 
789 #endif
790
791    length = strftime(buffer, buffer_size, "%b %d %H:%M:%S", &tm_now);
792    if (length > 0)
793    {
794       msecs_length = snprintf(buffer+length, buffer_size - length, ".%.3ld", msecs);               
795    }
796    if (msecs_length > 0)
797    {
798       length += (size_t)msecs_length;
799    }
800    else
801    {
802       length = 0;
803    }
804
805    return length;
806 }
807
808
809 /*********************************************************************
810  *
811  * Function    :  get_clf_timestamp
812  *
813  * Description :  Generates a Common Log Format time string.
814  *
815  * Parameters  :
816  *          1  :  buffer = Storage buffer
817  *          2  :  buffer_size = Size of storage buffer
818  *
819  * Returns     :  Number of written characters or 0 for error.
820  *
821  *********************************************************************/
822 static inline size_t get_clf_timestamp(char *buffer, size_t buffer_size)
823 {
824    /*
825     * Complex because not all OSs have tm_gmtoff or
826     * the %z field in strftime()
827     */
828    time_t now;
829    struct tm *tm_now; 
830    struct tm gmt;
831 #ifdef HAVE_LOCALTIME_R
832    struct tm dummy;
833 #endif
834    int days, hrs, mins;
835    size_t length;
836    int tz_length = 0;
837
838    time (&now); 
839 #ifdef HAVE_GMTIME_R
840    gmt = *gmtime_r(&now, &gmt);
841 #elif FEATURE_PTHREAD
842    privoxy_mutex_lock(&gmtime_mutex);
843    gmt = *gmtime(&now);
844    privoxy_mutex_unlock(&gmtime_mutex);
845 #else
846    gmt = *gmtime(&now);
847 #endif
848 #ifdef HAVE_LOCALTIME_R
849    tm_now = localtime_r(&now, &dummy);
850 #elif FEATURE_PTHREAD
851    privoxy_mutex_lock(&localtime_mutex);
852    tm_now = localtime(&now); 
853    privoxy_mutex_unlock(&localtime_mutex);
854 #else
855    tm_now = localtime(&now); 
856 #endif
857    days = tm_now->tm_yday - gmt.tm_yday; 
858    hrs = ((days < -1 ? 24 : 1 < days ? -24 : days * 24) + tm_now->tm_hour - gmt.tm_hour); 
859    mins = hrs * 60 + tm_now->tm_min - gmt.tm_min; 
860
861    length = strftime(buffer, buffer_size, "%d/%b/%Y:%H:%M:%S ", tm_now);
862
863    if (length > 0)
864    {
865       tz_length = snprintf(buffer+length, buffer_size-length,
866                      "%+03d%02d", mins / 60, abs(mins) % 60);
867    }
868    if (tz_length > 0)
869    {
870       length += (size_t)tz_length;
871    }
872    else
873    {
874       length = 0;
875    }
876
877    return length;
878 }
879
880
881 /*********************************************************************
882  *
883  * Function    :  get_log_level_string
884  *
885  * Description :  Translates a numerical loglevel into a string.
886  *
887  * Parameters  :  
888  *          1  :  loglevel = LOG_LEVEL_FOO
889  *
890  * Returns     :  Log level string.
891  *
892  *********************************************************************/
893 static inline const char *get_log_level_string(int loglevel)
894 {
895    char *log_level_string = NULL;
896
897    assert(0 < loglevel);
898
899    switch (loglevel)
900    {
901       case LOG_LEVEL_ERROR:
902          log_level_string = "Error";
903          break;
904       case LOG_LEVEL_FATAL:
905          log_level_string = "Fatal error";
906          break;
907       case LOG_LEVEL_GPC:
908          log_level_string = "Request";
909          break;
910       case LOG_LEVEL_CONNECT:
911          log_level_string = "Connect";
912          break;
913       case LOG_LEVEL_LOG:
914          log_level_string = "Writing";
915          break;
916       case LOG_LEVEL_HEADER:
917          log_level_string = "Header";
918          break;
919       case LOG_LEVEL_INFO:
920          log_level_string = "Info";
921          break;
922       case LOG_LEVEL_RE_FILTER:
923          log_level_string = "Re-Filter";
924          break;
925 #ifdef FEATURE_FORCE_LOAD
926       case LOG_LEVEL_FORCE:
927          log_level_string = "Force";
928          break;
929 #endif /* def FEATURE_FORCE_LOAD */
930 #ifdef FEATURE_FAST_REDIRECTS
931       case LOG_LEVEL_REDIRECTS:
932          log_level_string = "Redirect";
933          break;
934 #endif /* def FEATURE_FAST_REDIRECTS */
935       case LOG_LEVEL_DEANIMATE:
936          log_level_string = "Gif-Deanimate";
937          break;
938       case LOG_LEVEL_CGI:
939          log_level_string = "CGI";
940          break;
941       default:
942          log_level_string = "Unknown log level";
943          break;
944    }
945    assert(NULL != log_level_string);
946
947    return log_level_string;
948 }
949
950
951 /*********************************************************************
952  *
953  * Function    :  log_error
954  *
955  * Description :  This is the error-reporting and logging function.
956  *
957  * Parameters  :
958  *          1  :  loglevel  = the type of message to be logged
959  *          2  :  fmt       = the main string we want logged, printf-like
960  *          3  :  ...       = arguments to be inserted in fmt (printf-like).
961  *
962  * Returns     :  N/A
963  *
964  *********************************************************************/
965 void log_error(int loglevel, const char *fmt, ...)
966 {
967    va_list ap;
968    char *outbuf = NULL;
969    static char *outbuf_save = NULL;
970    char tempbuf[BUFFER_SIZE];
971    size_t length = 0;
972    const char * src = fmt;
973    long thread_id;
974    char timestamp[30];
975    /*
976     * XXX: Make this a config option,
977     * why else do we allocate instead of using
978     * an array?
979     */
980    size_t log_buffer_size = BUFFER_SIZE;
981
982 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
983    /*
984     * Irrespective of debug setting, a GET/POST/CONNECT makes
985     * the taskbar icon animate.  (There is an option to disable
986     * this but checking that is handled inside LogShowActivity()).
987     */
988    if (loglevel == LOG_LEVEL_GPC)
989    {
990       LogShowActivity();
991    }
992 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
993
994    /*
995     * verify that the loglevel applies to current
996     * settings and that logging is enabled.
997     * Bail out otherwise.
998     */
999    if ((0 == (loglevel & debug))
1000 #ifndef _WIN32
1001       || (logfp == NULL)
1002 #endif
1003       )
1004    {
1005       return;
1006    }
1007
1008    thread_id = get_thread_id();
1009    get_log_timestamp(timestamp, sizeof(timestamp));
1010
1011    /* protect the whole function because of the static buffer (outbuf) */
1012    lock_logfile();
1013
1014    if (NULL == outbuf_save) 
1015    {
1016       outbuf_save = (char*)zalloc(log_buffer_size + 1); /* +1 for paranoia */
1017       if (NULL == outbuf_save)
1018       {
1019          snprintf(tempbuf, sizeof(tempbuf),
1020             "%s Privoxy(%08lx) Fatal error: log_error() failed to allocate buffer memory.\n"
1021             "\nExiting.", timestamp, thread_id);
1022          fatal_error(tempbuf); /* Exit */
1023       }
1024    }
1025    outbuf = outbuf_save;
1026
1027    /*
1028     * Memsetting the whole buffer to zero (in theory)
1029     * makes things easier later on.
1030     */
1031    memset(outbuf, 0, log_buffer_size);
1032
1033    /* Add prefix for everything but Common Log Format messages */
1034    if (loglevel != LOG_LEVEL_CLF)
1035    {
1036       length = (size_t)snprintf(outbuf, log_buffer_size, "%s Privoxy(%08lx) %s: ",
1037                                 timestamp, thread_id, get_log_level_string(loglevel));
1038    }
1039
1040    /* get ready to scan var. args. */
1041    va_start(ap, fmt);
1042
1043    /* build formatted message from fmt and var-args */
1044    while ((*src) && (length < log_buffer_size-2))
1045    {
1046       const char *sval = NULL; /* %N string  */
1047       int ival;                /* %N string length or an error code */
1048       unsigned uval;           /* %u value */
1049       long lval;               /* %l value */
1050       unsigned long ulval;     /* %ul value */
1051       char ch;
1052       const char *format_string = tempbuf;
1053
1054       ch = *src++;
1055       if (ch != '%')
1056       {
1057          outbuf[length++] = ch;
1058          /*
1059           * XXX: Only necessary on platforms where multiple threads
1060           * can write to the buffer at the same time because we
1061           * don't support mutexes (OS/2 for example).
1062           */
1063          outbuf[length] = '\0';
1064          continue;
1065       }
1066       outbuf[length] = '\0';
1067       ch = *src++;
1068       switch (ch) {
1069          case '%':
1070             tempbuf[0] = '%';
1071             tempbuf[1] = '\0';
1072             break;
1073          case 'd':
1074             ival = va_arg( ap, int );
1075             snprintf(tempbuf, sizeof(tempbuf), "%d", ival);
1076             break;
1077          case 'u':
1078             uval = va_arg( ap, unsigned );
1079             snprintf(tempbuf, sizeof(tempbuf), "%u", uval);
1080             break;
1081          case 'l':
1082             /* this is a modifier that must be followed by u or d */
1083             ch = *src++;
1084             if (ch == 'd')
1085             {
1086                lval = va_arg( ap, long );
1087                snprintf(tempbuf, sizeof(tempbuf), "%ld", lval);
1088             }
1089             else if (ch == 'u')
1090             {
1091                ulval = va_arg( ap, unsigned long );
1092                snprintf(tempbuf, sizeof(tempbuf), "%lu", ulval);
1093             }
1094             else
1095             {
1096                snprintf(tempbuf, sizeof(tempbuf), "Bad format string: \"%s\"", fmt);
1097                loglevel = LOG_LEVEL_FATAL;
1098             }
1099             break;
1100          case 'c':
1101             /*
1102              * Note that char paramaters are converted to int, so we need to
1103              * pass "int" to va_arg.  (See K&R, 2nd ed, section A7.3.2, page 202)
1104              */
1105             tempbuf[0] = (char) va_arg(ap, int);
1106             tempbuf[1] = '\0';
1107             break;
1108          case 's':
1109             format_string = va_arg(ap, char *);
1110             if (format_string == NULL)
1111             {
1112                format_string = "[null]";
1113             }
1114             break;
1115          case 'N':
1116             /*
1117              * Non-standard: Print a counted unterminated string.
1118              * Takes 2 parameters: int length, const char * string.
1119              */
1120             ival = va_arg(ap, int);
1121             sval = va_arg(ap, char *);
1122             if (sval == NULL)
1123             {
1124                format_string = "[null]";
1125             }
1126             else if (ival <= 0)
1127             {
1128                if (0 == ival)
1129                {
1130                   /* That's ok (but stupid) */
1131                   tempbuf[0] = '\0';
1132                }
1133                else
1134                {
1135                   /*
1136                    * That's not ok (and even more stupid)
1137                    */
1138                   assert(ival >= 0);
1139                   format_string = "[counted string lenght < 0]";
1140                }
1141             }
1142             else if (ival >= sizeof(tempbuf))
1143             {
1144                /*
1145                 * String is too long, copy as much as possible.
1146                 * It will be further truncated later.
1147                 */
1148                memcpy(tempbuf, sval, sizeof(tempbuf)-1);
1149                tempbuf[sizeof(tempbuf)-1] = '\0';
1150             }
1151             else
1152             {
1153                memcpy(tempbuf, sval, (size_t) ival);
1154                tempbuf[ival] = '\0';
1155             }
1156             break;
1157          case 'E':
1158             /* Non-standard: Print error code from errno */
1159 #ifdef _WIN32
1160             ival = WSAGetLastError();
1161             format_string = w32_socket_strerr(ival, tempbuf);
1162 #elif __OS2__
1163             ival = sock_errno();
1164             if (ival != 0)
1165             {
1166                format_string = os2_socket_strerr(ival, tempbuf);
1167             }
1168             else
1169             {
1170                ival = errno;
1171                format_string = strerror(ival);
1172             }
1173 #else /* ifndef _WIN32 */
1174             ival = errno; 
1175 #ifdef HAVE_STRERROR
1176             format_string = strerror(ival);
1177 #else /* ifndef HAVE_STRERROR */
1178             format_string = NULL;
1179 #endif /* ndef HAVE_STRERROR */
1180             if (sval == NULL)
1181             {
1182                snprintf(tempbuf, sizeof(tempbuf), "(errno = %d)", ival);
1183             }
1184 #endif /* ndef _WIN32 */
1185             break;
1186          case 'T':
1187             /* Non-standard: Print a Common Log File timestamp */
1188             get_clf_timestamp(tempbuf, sizeof(tempbuf));
1189             break;
1190          default:
1191             snprintf(tempbuf, sizeof(tempbuf), "Bad format string: \"%s\"", fmt);
1192             loglevel = LOG_LEVEL_FATAL;
1193             break;
1194       } /* switch( p ) */
1195
1196       assert(length < log_buffer_size);
1197       length += strlcpy(outbuf + length, format_string, log_buffer_size - length);
1198
1199       if (length >= log_buffer_size-2)
1200       {
1201          static char warning[] = "... [too long, truncated]";
1202
1203          length = log_buffer_size - sizeof(warning) - 1;
1204          length += strlcpy(outbuf + length, warning, log_buffer_size - length);
1205          assert(length < log_buffer_size);
1206
1207          break;
1208       }
1209    } /* for( p ... ) */
1210
1211    /* done with var. args */
1212    va_end(ap);
1213
1214    assert(length < log_buffer_size);
1215    length += strlcpy(outbuf + length, "\n", log_buffer_size - length);
1216
1217    /* Some sanity checks */
1218    if ((length >= log_buffer_size)
1219     || (outbuf[log_buffer_size-1] != '\0')
1220     || (outbuf[log_buffer_size] != '\0')
1221       )
1222    {
1223       /* Repeat as assertions */
1224       assert(length < log_buffer_size);
1225       assert(outbuf[log_buffer_size-1] == '\0');
1226       /*
1227        * outbuf's real size is log_buffer_size+1,
1228        * so while this looks like an off-by-one,
1229        * we're only checking our paranoia byte.
1230        */
1231       assert(outbuf[log_buffer_size] == '\0');
1232
1233       snprintf(outbuf, log_buffer_size,
1234          "%s Privoxy(%08lx) Fatal error: log_error()'s sanity checks failed. length: %d\n"
1235          "Exiting.", timestamp, thread_id, (int)length);
1236       loglevel = LOG_LEVEL_FATAL;
1237    }
1238
1239 #ifndef _WIN32
1240    /*
1241     * On Windows this is acceptable in case
1242     * we are logging to the GUI window only.
1243     */
1244    assert(NULL != logfp);
1245 #endif
1246
1247    if (loglevel == LOG_LEVEL_FATAL)
1248    {
1249       fatal_error(outbuf_save);
1250       /* Never get here */
1251    }
1252    if (logfp != NULL)
1253    {
1254       fputs(outbuf_save, logfp);
1255    }
1256
1257 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
1258    /* Write to display */
1259    LogPutString(outbuf_save);
1260 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
1261
1262    unlock_logfile();
1263
1264 }
1265
1266
1267 /*********************************************************************
1268  *
1269  * Function    :  jb_err_to_string
1270  *
1271  * Description :  Translates JB_ERR_FOO codes into strings.
1272  *
1273  *                XXX: the type of error codes is jb_err
1274  *                but the typedef'inition is currently not
1275  *                visible to all files that include errlog.h.
1276  *
1277  * Parameters  :
1278  *          1  :  error = a valid jb_err code
1279  *
1280  * Returns     :  A string with the jb_err translation
1281  *
1282  *********************************************************************/
1283 const char *jb_err_to_string(int error)
1284 {
1285    switch (error)
1286    {
1287       case JB_ERR_OK:
1288          return "Success, no error";
1289       case JB_ERR_MEMORY:
1290          return "Out of memory";
1291       case JB_ERR_CGI_PARAMS:
1292          return "Missing or corrupt CGI parameters";
1293       case JB_ERR_FILE:
1294          return "Error opening, reading or writing a file";
1295       case JB_ERR_PARSE:
1296          return "Parse error";
1297       case JB_ERR_MODIFIED:
1298          return "File has been modified outside of the CGI actions editor.";
1299       case JB_ERR_COMPRESS:
1300          return "(De)compression failure";
1301       default:
1302          assert(0);
1303          return "Unknown error";
1304    }
1305    assert(0);
1306    return "Internal error";
1307 }
1308
1309 #ifdef _WIN32
1310 /*********************************************************************
1311  *
1312  * Function    :  w32_socket_strerr
1313  *
1314  * Description :  Translate the return value from WSAGetLastError()
1315  *                into a string.
1316  *
1317  * Parameters  :
1318  *          1  :  errcode = The return value from WSAGetLastError().
1319  *          2  :  tmp_buf = A temporary buffer that might be used to
1320  *                          store the string.
1321  *
1322  * Returns     :  String representing the error code.  This may be
1323  *                a global string constant or a string stored in
1324  *                tmp_buf.
1325  *
1326  *********************************************************************/
1327 static char *w32_socket_strerr(int errcode, char *tmp_buf)
1328 {
1329 #define TEXT_FOR_ERROR(code,text) \
1330    if (errcode == code)           \
1331    {                              \
1332       return #code " - " text;    \
1333    }
1334
1335    TEXT_FOR_ERROR(WSAEACCES, "Permission denied")
1336    TEXT_FOR_ERROR(WSAEADDRINUSE, "Address already in use.")
1337    TEXT_FOR_ERROR(WSAEADDRNOTAVAIL, "Cannot assign requested address.");
1338    TEXT_FOR_ERROR(WSAEAFNOSUPPORT, "Address family not supported by protocol family.");
1339    TEXT_FOR_ERROR(WSAEALREADY, "Operation already in progress.");
1340    TEXT_FOR_ERROR(WSAECONNABORTED, "Software caused connection abort.");
1341    TEXT_FOR_ERROR(WSAECONNREFUSED, "Connection refused.");
1342    TEXT_FOR_ERROR(WSAECONNRESET, "Connection reset by peer.");
1343    TEXT_FOR_ERROR(WSAEDESTADDRREQ, "Destination address required.");
1344    TEXT_FOR_ERROR(WSAEFAULT, "Bad address.");
1345    TEXT_FOR_ERROR(WSAEHOSTDOWN, "Host is down.");
1346    TEXT_FOR_ERROR(WSAEHOSTUNREACH, "No route to host.");
1347    TEXT_FOR_ERROR(WSAEINPROGRESS, "Operation now in progress.");
1348    TEXT_FOR_ERROR(WSAEINTR, "Interrupted function call.");
1349    TEXT_FOR_ERROR(WSAEINVAL, "Invalid argument.");
1350    TEXT_FOR_ERROR(WSAEISCONN, "Socket is already connected.");
1351    TEXT_FOR_ERROR(WSAEMFILE, "Too many open sockets.");
1352    TEXT_FOR_ERROR(WSAEMSGSIZE, "Message too long.");
1353    TEXT_FOR_ERROR(WSAENETDOWN, "Network is down.");
1354    TEXT_FOR_ERROR(WSAENETRESET, "Network dropped connection on reset.");
1355    TEXT_FOR_ERROR(WSAENETUNREACH, "Network is unreachable.");
1356    TEXT_FOR_ERROR(WSAENOBUFS, "No buffer space available.");
1357    TEXT_FOR_ERROR(WSAENOPROTOOPT, "Bad protocol option.");
1358    TEXT_FOR_ERROR(WSAENOTCONN, "Socket is not connected.");
1359    TEXT_FOR_ERROR(WSAENOTSOCK, "Socket operation on non-socket.");
1360    TEXT_FOR_ERROR(WSAEOPNOTSUPP, "Operation not supported.");
1361    TEXT_FOR_ERROR(WSAEPFNOSUPPORT, "Protocol family not supported.");
1362    TEXT_FOR_ERROR(WSAEPROCLIM, "Too many processes.");
1363    TEXT_FOR_ERROR(WSAEPROTONOSUPPORT, "Protocol not supported.");
1364    TEXT_FOR_ERROR(WSAEPROTOTYPE, "Protocol wrong type for socket.");
1365    TEXT_FOR_ERROR(WSAESHUTDOWN, "Cannot send after socket shutdown.");
1366    TEXT_FOR_ERROR(WSAESOCKTNOSUPPORT, "Socket type not supported.");
1367    TEXT_FOR_ERROR(WSAETIMEDOUT, "Connection timed out.");
1368    TEXT_FOR_ERROR(WSAEWOULDBLOCK, "Resource temporarily unavailable.");
1369    TEXT_FOR_ERROR(WSAHOST_NOT_FOUND, "Host not found.");
1370    TEXT_FOR_ERROR(WSANOTINITIALISED, "Successful WSAStartup not yet performed.");
1371    TEXT_FOR_ERROR(WSANO_DATA, "Valid name, no data record of requested type.");
1372    TEXT_FOR_ERROR(WSANO_RECOVERY, "This is a non-recoverable error.");
1373    TEXT_FOR_ERROR(WSASYSNOTREADY, "Network subsystem is unavailable.");
1374    TEXT_FOR_ERROR(WSATRY_AGAIN, "Non-authoritative host not found.");
1375    TEXT_FOR_ERROR(WSAVERNOTSUPPORTED, "WINSOCK.DLL version out of range.");
1376    TEXT_FOR_ERROR(WSAEDISCON, "Graceful shutdown in progress.");
1377    /*
1378     * The following error codes are documented in the Microsoft WinSock
1379     * reference guide, but don't actually exist.
1380     *
1381     * TEXT_FOR_ERROR(WSA_INVALID_HANDLE, "Specified event object handle is invalid.");
1382     * TEXT_FOR_ERROR(WSA_INVALID_PARAMETER, "One or more parameters are invalid.");
1383     * TEXT_FOR_ERROR(WSAINVALIDPROCTABLE, "Invalid procedure table from service provider.");
1384     * TEXT_FOR_ERROR(WSAINVALIDPROVIDER, "Invalid service provider version number.");
1385     * TEXT_FOR_ERROR(WSA_IO_PENDING, "Overlapped operations will complete later.");
1386     * TEXT_FOR_ERROR(WSA_IO_INCOMPLETE, "Overlapped I/O event object not in signaled state.");
1387     * TEXT_FOR_ERROR(WSA_NOT_ENOUGH_MEMORY, "Insufficient memory available.");
1388     * TEXT_FOR_ERROR(WSAPROVIDERFAILEDINIT, "Unable to initialize a service provider.");
1389     * TEXT_FOR_ERROR(WSASYSCALLFAILURE, "System call failure.");
1390     * TEXT_FOR_ERROR(WSA_OPERATION_ABORTED, "Overlapped operation aborted.");
1391     */
1392
1393    sprintf(tmp_buf, "(error number %d)", errcode);
1394    return tmp_buf;
1395 }
1396 #endif /* def _WIN32 */
1397
1398
1399 #ifdef __OS2__
1400 /*********************************************************************
1401  *
1402  * Function    :  os2_socket_strerr
1403  *
1404  * Description :  Translate the return value from sock_errno()
1405  *                into a string.
1406  *
1407  * Parameters  :
1408  *          1  :  errcode = The return value from sock_errno().
1409  *          2  :  tmp_buf = A temporary buffer that might be used to
1410  *                          store the string.
1411  *
1412  * Returns     :  String representing the error code.  This may be
1413  *                a global string constant or a string stored in
1414  *                tmp_buf.
1415  *
1416  *********************************************************************/
1417 static char *os2_socket_strerr(int errcode, char *tmp_buf)
1418 {
1419 #define TEXT_FOR_ERROR(code,text) \
1420    if (errcode == code)           \
1421    {                              \
1422       return #code " - " text;    \
1423    }
1424
1425    TEXT_FOR_ERROR(SOCEPERM          , "Not owner.")
1426    TEXT_FOR_ERROR(SOCESRCH          , "No such process.")
1427    TEXT_FOR_ERROR(SOCEINTR          , "Interrupted system call.")
1428    TEXT_FOR_ERROR(SOCENXIO          , "No such device or address.")
1429    TEXT_FOR_ERROR(SOCEBADF          , "Bad file number.")
1430    TEXT_FOR_ERROR(SOCEACCES         , "Permission denied.")
1431    TEXT_FOR_ERROR(SOCEFAULT         , "Bad address.")
1432    TEXT_FOR_ERROR(SOCEINVAL         , "Invalid argument.")
1433    TEXT_FOR_ERROR(SOCEMFILE         , "Too many open files.")
1434    TEXT_FOR_ERROR(SOCEPIPE          , "Broken pipe.")
1435    TEXT_FOR_ERROR(SOCEWOULDBLOCK    , "Operation would block.")
1436    TEXT_FOR_ERROR(SOCEINPROGRESS    , "Operation now in progress.")
1437    TEXT_FOR_ERROR(SOCEALREADY       , "Operation already in progress.")
1438    TEXT_FOR_ERROR(SOCENOTSOCK       , "Socket operation on non-socket.")
1439    TEXT_FOR_ERROR(SOCEDESTADDRREQ   , "Destination address required.")
1440    TEXT_FOR_ERROR(SOCEMSGSIZE       , "Message too long.")
1441    TEXT_FOR_ERROR(SOCEPROTOTYPE     , "Protocol wrong type for socket.")
1442    TEXT_FOR_ERROR(SOCENOPROTOOPT    , "Protocol not available.")
1443    TEXT_FOR_ERROR(SOCEPROTONOSUPPORT, "Protocol not supported.")
1444    TEXT_FOR_ERROR(SOCESOCKTNOSUPPORT, "Socket type not supported.")
1445    TEXT_FOR_ERROR(SOCEOPNOTSUPP     , "Operation not supported.")
1446    TEXT_FOR_ERROR(SOCEPFNOSUPPORT   , "Protocol family not supported.")
1447    TEXT_FOR_ERROR(SOCEAFNOSUPPORT   , "Address family not supported by protocol family.")
1448    TEXT_FOR_ERROR(SOCEADDRINUSE     , "Address already in use.")
1449    TEXT_FOR_ERROR(SOCEADDRNOTAVAIL  , "Can't assign requested address.")
1450    TEXT_FOR_ERROR(SOCENETDOWN       , "Network is down.")
1451    TEXT_FOR_ERROR(SOCENETUNREACH    , "Network is unreachable.")
1452    TEXT_FOR_ERROR(SOCENETRESET      , "Network dropped connection on reset.")
1453    TEXT_FOR_ERROR(SOCECONNABORTED   , "Software caused connection abort.")
1454    TEXT_FOR_ERROR(SOCECONNRESET     , "Connection reset by peer.")
1455    TEXT_FOR_ERROR(SOCENOBUFS        , "No buffer space available.")
1456    TEXT_FOR_ERROR(SOCEISCONN        , "Socket is already connected.")
1457    TEXT_FOR_ERROR(SOCENOTCONN       , "Socket is not connected.")
1458    TEXT_FOR_ERROR(SOCESHUTDOWN      , "Can't send after socket shutdown.")
1459    TEXT_FOR_ERROR(SOCETOOMANYREFS   , "Too many references: can't splice.")
1460    TEXT_FOR_ERROR(SOCETIMEDOUT      , "Operation timed out.")
1461    TEXT_FOR_ERROR(SOCECONNREFUSED   , "Connection refused.")
1462    TEXT_FOR_ERROR(SOCELOOP          , "Too many levels of symbolic links.")
1463    TEXT_FOR_ERROR(SOCENAMETOOLONG   , "File name too long.")
1464    TEXT_FOR_ERROR(SOCEHOSTDOWN      , "Host is down.")
1465    TEXT_FOR_ERROR(SOCEHOSTUNREACH   , "No route to host.")
1466    TEXT_FOR_ERROR(SOCENOTEMPTY      , "Directory not empty.")
1467    TEXT_FOR_ERROR(SOCEOS2ERR        , "OS/2 Error.")
1468
1469    sprintf(tmp_buf, "(error number %d)", errcode);
1470    return tmp_buf;
1471 }
1472 #endif /* def __OS2__ */
1473
1474
1475 /*
1476   Local Variables:
1477   tab-width: 3
1478   end:
1479 */