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