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