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