bottleneck testcase based on rubbos
[bottlenecks.git] / rubbos / app / httpd-2.0.64 / server / log.c
1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2  * contributor license agreements.  See the NOTICE file distributed with
3  * this work for additional information regarding copyright ownership.
4  * The ASF licenses this file to You under the Apache License, Version 2.0
5  * (the "License"); you may not use this file except in compliance with
6  * the License.  You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /*
18  * http_log.c: Dealing with the logs and errors
19  *
20  * Rob McCool
21  *
22  */
23
24 #include "apr.h"
25 #include "apr_general.h"        /* for signal stuff */
26 #include "apr_strings.h"
27 #include "apr_errno.h"
28 #include "apr_thread_proc.h"
29 #include "apr_lib.h"
30 #include "apr_signal.h"
31
32 #define APR_WANT_STDIO
33 #define APR_WANT_STRFUNC
34 #include "apr_want.h"
35
36 #if APR_HAVE_STDARG_H
37 #include <stdarg.h>
38 #endif
39 #if APR_HAVE_UNISTD_H
40 #include <unistd.h>
41 #endif
42
43 #define CORE_PRIVATE
44
45 #include "ap_config.h"
46 #include "httpd.h"
47 #include "http_config.h"
48 #include "http_core.h"
49 #include "http_log.h"
50 #include "http_main.h"
51 #include "util_time.h"
52 #include "ap_mpm.h"
53
54 #ifndef APR_LARGEFILE
55 #define APR_LARGEFILE 0
56 #endif
57
58 typedef struct {
59     char    *t_name;
60     int      t_val;
61 } TRANS;
62
63 APR_HOOK_STRUCT(
64     APR_HOOK_LINK(error_log)
65 )
66
67 int AP_DECLARE_DATA ap_default_loglevel = DEFAULT_LOGLEVEL;
68
69 #ifdef HAVE_SYSLOG
70
71 static const TRANS facilities[] = {
72     {"auth",    LOG_AUTH},
73 #ifdef LOG_AUTHPRIV
74     {"authpriv",LOG_AUTHPRIV},
75 #endif
76 #ifdef LOG_CRON
77     {"cron",    LOG_CRON},
78 #endif
79 #ifdef LOG_DAEMON
80     {"daemon",  LOG_DAEMON},
81 #endif
82 #ifdef LOG_FTP
83     {"ftp", LOG_FTP},
84 #endif
85 #ifdef LOG_KERN
86     {"kern",    LOG_KERN},
87 #endif
88 #ifdef LOG_LPR
89     {"lpr", LOG_LPR},
90 #endif
91 #ifdef LOG_MAIL
92     {"mail",    LOG_MAIL},
93 #endif
94 #ifdef LOG_NEWS
95     {"news",    LOG_NEWS},
96 #endif
97 #ifdef LOG_SYSLOG
98     {"syslog",  LOG_SYSLOG},
99 #endif
100 #ifdef LOG_USER
101     {"user",    LOG_USER},
102 #endif
103 #ifdef LOG_UUCP
104     {"uucp",    LOG_UUCP},
105 #endif
106 #ifdef LOG_LOCAL0
107     {"local0",  LOG_LOCAL0},
108 #endif
109 #ifdef LOG_LOCAL1
110     {"local1",  LOG_LOCAL1},
111 #endif
112 #ifdef LOG_LOCAL2
113     {"local2",  LOG_LOCAL2},
114 #endif
115 #ifdef LOG_LOCAL3
116     {"local3",  LOG_LOCAL3},
117 #endif
118 #ifdef LOG_LOCAL4
119     {"local4",  LOG_LOCAL4},
120 #endif
121 #ifdef LOG_LOCAL5
122     {"local5",  LOG_LOCAL5},
123 #endif
124 #ifdef LOG_LOCAL6
125     {"local6",  LOG_LOCAL6},
126 #endif
127 #ifdef LOG_LOCAL7
128     {"local7",  LOG_LOCAL7},
129 #endif
130     {NULL,      -1},
131 };
132 #endif
133
134 static const TRANS priorities[] = {
135     {"emerg",   APLOG_EMERG},
136     {"alert",   APLOG_ALERT},
137     {"crit",    APLOG_CRIT},
138     {"error",   APLOG_ERR},
139     {"warn",    APLOG_WARNING},
140     {"notice",  APLOG_NOTICE},
141     {"info",    APLOG_INFO},
142     {"debug",   APLOG_DEBUG},
143     {NULL,      -1},
144 };
145
146 static apr_pool_t *stderr_pool = NULL;
147
148 static apr_file_t *stderr_log = NULL;
149
150 /* track pipe handles to close in child process */
151 typedef struct read_handle_t {
152     struct read_handle_t *next;
153     apr_file_t *handle;
154 } read_handle_t;
155
156 static read_handle_t *read_handles;
157
158 /* clear_handle_list() is called when plog is cleared; at that
159  * point we need to forget about our old list of pipe read
160  * handles.  We let the plog cleanups close the actual pipes.
161  */
162 static apr_status_t clear_handle_list(void *v)
163 {
164     read_handles = NULL;
165     return APR_SUCCESS;
166 }
167
168 /* remember to close this handle in the child process
169  *
170  * On Win32 this makes zero sense, because we don't
171  * take the parent process's child procs.
172  * If the win32 parent instead passed each and every
173  * logger write handle from itself down to the child,
174  * and the parent manages all aspects of keeping the 
175  * reliable pipe log children alive, this would still
176  * make no sense :)  Cripple it on Win32.
177  */
178 static void close_handle_in_child(apr_pool_t *p, apr_file_t *f)
179 {
180 #ifndef WIN32
181     read_handle_t *new_handle;
182
183     new_handle = apr_pcalloc(p, sizeof(read_handle_t));
184     new_handle->next = read_handles;
185     new_handle->handle = f;
186     read_handles = new_handle;
187 #endif
188 }
189
190 void ap_logs_child_init(apr_pool_t *p, server_rec *s)
191 {
192     read_handle_t *cur = read_handles;
193
194     while (cur) {
195         apr_file_close(cur->handle);
196         cur = cur->next;
197     }
198 }
199
200 AP_DECLARE(void) ap_open_stderr_log(apr_pool_t *p)
201 {
202     apr_file_open_stderr(&stderr_log, p);
203 }
204
205 AP_DECLARE(apr_status_t) ap_replace_stderr_log(apr_pool_t *p, 
206                                                const char *fname)
207 {
208     apr_file_t *stderr_file;
209     apr_status_t rc;
210     char *filename = ap_server_root_relative(p, fname);
211     if (!filename) {
212         ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_CRIT,
213                      APR_EBADPATH, NULL, "Invalid -E error log file %s",
214                      fname);
215         return APR_EBADPATH;
216     }
217     if ((rc = apr_file_open(&stderr_file, filename,
218                             APR_APPEND | APR_WRITE | APR_CREATE | APR_LARGEFILE,
219                             APR_OS_DEFAULT, p)) != APR_SUCCESS) {
220         ap_log_error(APLOG_MARK, APLOG_STARTUP, rc, NULL,
221                      "%s: could not open error log file %s.",
222                      ap_server_argv0, fname);
223         return rc;
224     }
225     if (!stderr_pool) {
226         /* This is safe provided we revert it when we are finished.
227          * We don't manager the callers pool!
228          */
229         stderr_pool = p;
230     }
231     if ((rc = apr_file_open_stderr(&stderr_log, stderr_pool)) 
232             == APR_SUCCESS) {
233         apr_file_flush(stderr_log);
234         if ((rc = apr_file_dup2(stderr_log, stderr_file, stderr_pool)) 
235                 == APR_SUCCESS) {
236             apr_file_close(stderr_file);
237             /*
238              * You might ponder why stderr_pool should survive?
239              * The trouble is, stderr_pool may have s_main->error_log,
240              * so we aren't in a position to destory stderr_pool until
241              * the next recycle.  There's also an apparent bug which 
242              * is not; if some folk decided to call this function before 
243              * the core open error logs hook, this pool won't survive.
244              * Neither does the stderr logger, so this isn't a problem.
245              */
246         }
247     }
248     /* Revert, see above */
249     if (stderr_pool == p)
250         stderr_pool = NULL;
251
252     if (rc != APR_SUCCESS) {
253         ap_log_error(APLOG_MARK, APLOG_CRIT, rc, NULL,
254                      "unable to replace stderr with error log file");
255     }
256     return rc;
257 }
258
259 static void log_child_errfn(apr_pool_t *pool, apr_status_t err,
260                             const char *description)
261 {
262     ap_log_error(APLOG_MARK, APLOG_ERR, err, NULL,
263                  "%s", description);
264 }
265
266 /* Create a child process running PROGNAME with a pipe connected to
267  * the childs stdin.  The write-end of the pipe will be placed in
268  * *FPIN on successful return.  If dummy_stderr is non-zero, the
269  * stderr for the child will be the same as the stdout of the parent.
270  * Otherwise the child will inherit the stderr from the parent. */
271 static int log_child(apr_pool_t *p, const char *progname,
272                      apr_file_t **fpin, int dummy_stderr)
273 {
274     /* Child process code for 'ErrorLog "|..."';
275      * may want a common framework for this, since I expect it will
276      * be common for other foo-loggers to want this sort of thing...
277      */
278     apr_status_t rc;
279     apr_procattr_t *procattr;
280     apr_proc_t *procnew;
281     apr_file_t *outfile, *errfile;
282
283     if (((rc = apr_procattr_create(&procattr, p)) == APR_SUCCESS)
284         && ((rc = apr_procattr_io_set(procattr,
285                                       APR_FULL_BLOCK,
286                                       APR_NO_PIPE,
287                                       APR_NO_PIPE)) == APR_SUCCESS)
288         && ((rc = apr_procattr_error_check_set(procattr, 1)) == APR_SUCCESS)
289         && ((rc = apr_procattr_child_errfn_set(procattr, log_child_errfn))
290                 == APR_SUCCESS)) {
291         char **args;
292         const char *pname;
293
294         apr_tokenize_to_argv(progname, &args, p);
295         pname = apr_pstrdup(p, args[0]);
296         procnew = (apr_proc_t *)apr_pcalloc(p, sizeof(*procnew));
297
298         if ((rc = apr_file_open_stdout(&outfile, p)) == APR_SUCCESS) {
299             rc = apr_procattr_child_out_set(procattr, outfile, NULL);
300             if (dummy_stderr)
301                 rc = apr_procattr_child_err_set(procattr, outfile, NULL);
302             else if ((rc = apr_file_open_stderr(&errfile, p)) == APR_SUCCESS)
303                 rc = apr_procattr_child_err_set(procattr, errfile, NULL);
304         }
305
306         rc = apr_proc_create(procnew, pname, (const char * const *)args,
307                              NULL, procattr, p);
308
309         if (rc == APR_SUCCESS) {
310             apr_pool_note_subprocess(p, procnew, APR_KILL_AFTER_TIMEOUT);
311             (*fpin) = procnew->in;
312             /* read handle to pipe not kept open, so no need to call
313              * close_handle_in_child()
314              */
315         }
316     }
317
318     return rc;
319 }
320
321 /* Open the error log for the given server_rec.  If IS_MAIN is
322  * non-zero, s is the main server. */
323 static int open_error_log(server_rec *s, int is_main, apr_pool_t *p)
324 {
325     const char *fname;
326     int rc;
327
328     if (*s->error_fname == '|') {
329         apr_file_t *dummy = NULL;
330
331         /* Spawn a new child logger.  If this is the main server_rec,
332          * the new child must use a dummy stderr since the current
333          * stderr might be a pipe to the old logger.  Otherwise, the
334          * child inherits the parents stderr. */
335         rc = log_child(p, s->error_fname + 1, &dummy, is_main);
336         if (rc != APR_SUCCESS) {
337             ap_log_error(APLOG_MARK, APLOG_STARTUP, rc, NULL,
338                          "Couldn't start ErrorLog process");
339             return DONE;
340         }
341
342         s->error_log = dummy;
343     }
344
345 #ifdef HAVE_SYSLOG
346     else if (!strncasecmp(s->error_fname, "syslog", 6)) {
347         if ((fname = strchr(s->error_fname, ':'))) {
348             const TRANS *fac;
349
350             fname++;
351             for (fac = facilities; fac->t_name; fac++) {
352                 if (!strcasecmp(fname, fac->t_name)) {
353                     openlog(ap_server_argv0, LOG_NDELAY|LOG_CONS|LOG_PID,
354                             fac->t_val);
355                     s->error_log = NULL;
356                     return OK;
357                 }
358             }
359         }
360         else {
361             openlog(ap_server_argv0, LOG_NDELAY|LOG_CONS|LOG_PID, LOG_LOCAL7);
362         }
363
364         s->error_log = NULL;
365     }
366 #endif
367     else {
368         fname = ap_server_root_relative(p, s->error_fname);
369         if (!fname) {
370             ap_log_error(APLOG_MARK, APLOG_STARTUP, APR_EBADPATH, NULL,
371                          "%s: Invalid error log path %s.",
372                          ap_server_argv0, s->error_fname);
373             return DONE;
374         }
375         if ((rc = apr_file_open(&s->error_log, fname,
376                                APR_APPEND | APR_WRITE | APR_CREATE | APR_LARGEFILE,
377                                APR_OS_DEFAULT, p)) != APR_SUCCESS) {
378             ap_log_error(APLOG_MARK, APLOG_STARTUP, rc, NULL,
379                          "%s: could not open error log file %s.",
380                          ap_server_argv0, fname);
381             return DONE;
382         }
383     }
384
385     return OK;
386 }
387
388 int ap_open_logs(apr_pool_t *pconf, apr_pool_t *p /* plog */, 
389                  apr_pool_t *ptemp, server_rec *s_main)
390 {
391     apr_pool_t *stderr_p;
392     server_rec *virt, *q;
393     int replace_stderr;
394
395
396     /* Register to throw away the read_handles list when we
397      * cleanup plog.  Upon fork() for the apache children,
398      * this read_handles list is closed so only the parent
399      * can relaunch a lost log child.  These read handles 
400      * are always closed on exec.
401      * We won't care what happens to our stderr log child 
402      * between log phases, so we don't mind losing stderr's 
403      * read_handle a little bit early.
404      */
405     apr_pool_cleanup_register(p, NULL, clear_handle_list,
406                               apr_pool_cleanup_null);
407
408     /* HERE we need a stdout log that outlives plog.
409      * We *presume* the parent of plog is a process 
410      * or global pool which spans server restarts.
411      * Create our stderr_pool as a child of the plog's
412      * parent pool.
413      */
414     apr_pool_create(&stderr_p, apr_pool_parent_get(p));
415     apr_pool_tag(stderr_p, "stderr_pool");
416     
417     if (open_error_log(s_main, 1, stderr_p) != OK) {
418         return DONE;
419     }
420
421     replace_stderr = 1;
422     if (s_main->error_log) {
423         apr_status_t rv;
424         
425         /* Replace existing stderr with new log. */
426         apr_file_flush(s_main->error_log);
427         rv = apr_file_dup2(stderr_log, s_main->error_log, stderr_p);
428         if (rv != APR_SUCCESS) {
429             ap_log_error(APLOG_MARK, APLOG_CRIT, rv, s_main,
430                          "unable to replace stderr with error_log");
431         }
432         else {
433             /* We are done with stderr_pool, close it, killing
434              * the previous generation's stderr logger
435              */
436             if (stderr_pool)
437                 apr_pool_destroy(stderr_pool);
438             stderr_pool = stderr_p;
439             replace_stderr = 0;
440             /*
441              * Now that we have dup'ed s_main->error_log to stderr_log
442              * close it and set s_main->error_log to stderr_log. This avoids
443              * this fd being inherited by the next piped logger who would
444              * keep open the writing end of the pipe that this one uses
445              * as stdin. This in turn would prevent the piped logger from
446              * exiting.
447              */
448              apr_file_close(s_main->error_log);
449              s_main->error_log = stderr_log;
450         }
451     }
452     /* note that stderr may still need to be replaced with something
453      * because it points to the old error log, or back to the tty
454      * of the submitter.
455      * XXX: This is BS - /dev/null is non-portable
456      */
457     if (replace_stderr && freopen("/dev/null", "w", stderr) == NULL) {
458         ap_log_error(APLOG_MARK, APLOG_CRIT, errno, s_main,
459                      "unable to replace stderr with /dev/null");
460     }
461
462     for (virt = s_main->next; virt; virt = virt->next) {
463         if (virt->error_fname) {
464             for (q=s_main; q != virt; q = q->next) {
465                 if (q->error_fname != NULL
466                     && strcmp(q->error_fname, virt->error_fname) == 0) {
467                     break;
468                 }
469             }
470
471             if (q == virt) {
472                 if (open_error_log(virt, 0, p) != OK) {
473                     return DONE;
474                 }
475             }
476             else {
477                 virt->error_log = q->error_log;
478             }
479         }
480         else {
481             virt->error_log = s_main->error_log;
482         }
483     }
484     return OK;
485 }
486
487 AP_DECLARE(void) ap_error_log2stderr(server_rec *s) {
488     apr_file_t *errfile = NULL;
489
490     apr_file_open_stderr(&errfile, s->process->pool);
491     if (s->error_log != NULL) {
492         apr_file_dup2(s->error_log, errfile, s->process->pool);
493     }
494 }
495
496 static void log_error_core(const char *file, int line, int level,
497                            apr_status_t status, const server_rec *s,
498                            const conn_rec *c,
499                            const request_rec *r, apr_pool_t *pool,
500                            const char *fmt, va_list args)
501 {
502     char errstr[MAX_STRING_LEN];
503 #ifndef AP_UNSAFE_ERROR_LOG_UNESCAPED
504     char scratch[MAX_STRING_LEN];
505 #endif
506     apr_size_t len, errstrlen;
507     apr_file_t *logf = NULL;
508     const char *referer;
509     int level_and_mask = level & APLOG_LEVELMASK;
510
511     if (r && r->connection) {
512         c = r->connection;
513     }
514
515     if (s == NULL) {
516         /*
517          * If we are doing stderr logging (startup), don't log messages that are
518          * above the default server log level unless it is a startup/shutdown
519          * notice
520          */
521         if ((level_and_mask != APLOG_NOTICE)
522             && (level_and_mask > ap_default_loglevel)) {
523             return;
524         }
525
526         logf = stderr_log;
527     }
528     else if (s->error_log) {
529         /*
530          * If we are doing normal logging, don't log messages that are
531          * above the server log level unless it is a startup/shutdown notice
532          */
533         if ((level_and_mask != APLOG_NOTICE)
534             && (level_and_mask > s->loglevel)) {
535             return;
536         }
537
538         logf = s->error_log;
539     }
540 #ifdef TPF
541     else if (tpf_child) {
542         /*
543          * If we are doing normal logging, don't log messages that are
544          * above the server log level unless it is a startup/shutdown notice
545          */
546         if ((level_and_mask != APLOG_NOTICE)
547             && (level_and_mask > s->loglevel)) {
548             return;
549         }
550
551         logf = stderr;
552     }
553 #endif /* TPF */
554     else {
555         /*
556          * If we are doing syslog logging, don't log messages that are
557          * above the server log level (including a startup/shutdown notice)
558          */
559         if (level_and_mask > s->loglevel) {
560             return;
561         }
562     }
563
564     if (logf && ((level & APLOG_STARTUP) != APLOG_STARTUP)) {
565         errstr[0] = '[';
566         ap_recent_ctime(errstr + 1, apr_time_now());
567         errstr[1 + APR_CTIME_LEN - 1] = ']';
568         errstr[1 + APR_CTIME_LEN    ] = ' ';
569         len = 1 + APR_CTIME_LEN + 1;
570     } else {
571         len = 0;
572     }
573
574     if ((level & APLOG_STARTUP) != APLOG_STARTUP) {
575         len += apr_snprintf(errstr + len, MAX_STRING_LEN - len,
576                             "[%s] ", priorities[level_and_mask].t_name);
577     }
578
579 #ifndef TPF
580     if (file && level_and_mask == APLOG_DEBUG) {
581 #if defined(_OSD_POSIX) || defined(WIN32) || defined(__MVS__)
582         char tmp[256];
583         char *e = strrchr(file, '/');
584 #ifdef WIN32
585         if (!e) {
586             e = strrchr(file, '\\');
587         }
588 #endif
589
590         /* In OSD/POSIX, the compiler returns for __FILE__
591          * a string like: __FILE__="*POSIX(/usr/include/stdio.h)"
592          * (it even returns an absolute path for sources in
593          * the current directory). Here we try to strip this
594          * down to the basename.
595          */
596         if (e != NULL && e[1] != '\0') {
597             apr_snprintf(tmp, sizeof(tmp), "%s", &e[1]);
598             e = &tmp[strlen(tmp)-1];
599             if (*e == ')') {
600                 *e = '\0';
601             }
602             file = tmp;
603         }
604 #else /* _OSD_POSIX || WIN32 */
605         const char *p;
606         /* On Unix, __FILE__ may be an absolute path in a
607          * VPATH build. */
608         if (file[0] == '/' && (p = ap_strrchr_c(file, '/')) != NULL) {
609             file = p + 1;
610         }
611 #endif /*_OSD_POSIX || WIN32 */
612         len += apr_snprintf(errstr + len, MAX_STRING_LEN - len,
613                             "%s(%d): ", file, line);
614     }
615 #endif /* TPF */
616
617     if (c) {
618         /* XXX: TODO: add a method of selecting whether logged client
619          * addresses are in dotted quad or resolved form... dotted
620          * quad is the most secure, which is why I'm implementing it
621          * first. -djg
622          */
623         len += apr_snprintf(errstr + len, MAX_STRING_LEN - len,
624                             "[client %s] ", c->remote_ip);
625     }
626     if (status != 0) {
627         if (status < APR_OS_START_EAIERR) {
628             len += apr_snprintf(errstr + len, MAX_STRING_LEN - len,
629                                 "(%d)", status);
630         }
631         else if (status < APR_OS_START_SYSERR) {
632             len += apr_snprintf(errstr + len, MAX_STRING_LEN - len,
633                                 "(EAI %d)", status - APR_OS_START_EAIERR);
634         }
635         else if (status < 100000 + APR_OS_START_SYSERR) {
636             len += apr_snprintf(errstr + len, MAX_STRING_LEN - len,
637                                 "(OS %d)", status - APR_OS_START_SYSERR);
638         }
639         else {
640             len += apr_snprintf(errstr + len, MAX_STRING_LEN - len,
641                                 "(os 0x%08x)", status - APR_OS_START_SYSERR);
642         }
643         apr_strerror(status, errstr + len, MAX_STRING_LEN - len);
644         len += strlen(errstr + len);
645         if (MAX_STRING_LEN - len > 2) {
646             errstr[len++] = ':';
647             errstr[len++] = ' ';
648             errstr[len] = '\0';
649         }
650     }
651
652     errstrlen = len;
653 #ifndef AP_UNSAFE_ERROR_LOG_UNESCAPED
654     if (apr_vsnprintf(scratch, MAX_STRING_LEN - len, fmt, args)) {
655         len += ap_escape_errorlog_item(errstr + len, scratch,
656                                        MAX_STRING_LEN - len);
657     }
658 #else
659     len += apr_vsnprintf(errstr + len, MAX_STRING_LEN - len, fmt, args);
660 #endif
661
662     if (   r && (referer = apr_table_get(r->headers_in, "Referer"))
663 #ifndef AP_UNSAFE_ERROR_LOG_UNESCAPED
664         && ap_escape_errorlog_item(scratch, referer, MAX_STRING_LEN - len)
665 #endif
666         ) {
667         len += apr_snprintf(errstr + len, MAX_STRING_LEN - len,
668                             ", referer: %s",
669 #ifndef AP_UNSAFE_ERROR_LOG_UNESCAPED
670                             scratch
671 #else
672                             referer
673 #endif
674                             );
675     }
676
677     /* NULL if we are logging to syslog */
678     if (logf) {
679         /* Truncate for the terminator (as apr_snprintf does) */
680         if (len > MAX_STRING_LEN - sizeof(APR_EOL_STR)) {
681             len = MAX_STRING_LEN - sizeof(APR_EOL_STR);
682         }
683         strcpy(errstr + len, APR_EOL_STR);
684         apr_file_puts(errstr, logf);
685         apr_file_flush(logf);
686     }
687 #ifdef HAVE_SYSLOG
688     else {
689         syslog(level_and_mask, "%s", errstr);
690     }
691 #endif
692
693     ap_run_error_log(file, line, level, status, s, r, pool, errstr + errstrlen);
694 }
695
696 AP_DECLARE(void) ap_log_error(const char *file, int line, int level,
697                               apr_status_t status, const server_rec *s,
698                               const char *fmt, ...)
699 {
700     va_list args;
701
702     va_start(args, fmt);
703     log_error_core(file, line, level, status, s, NULL, NULL, NULL, fmt, args);
704     va_end(args);
705 }
706
707 AP_DECLARE(void) ap_log_perror(const char *file, int line, int level,
708                                apr_status_t status, apr_pool_t *p,
709                                const char *fmt, ...)
710 {
711     va_list args;
712
713     va_start(args, fmt);
714     log_error_core(file, line, level, status, NULL, NULL, NULL, p, fmt, args);
715     va_end(args);
716 }
717
718 AP_DECLARE(void) ap_log_rerror(const char *file, int line, int level,
719                                apr_status_t status, const request_rec *r,
720                                const char *fmt, ...)
721 {
722     va_list args;
723
724     va_start(args, fmt);
725     log_error_core(file, line, level, status, r->server, NULL, r, NULL, fmt,
726                    args);
727
728     /*
729      * IF APLOG_TOCLIENT is set,
730      * AND the error level is 'warning' or more severe,
731      * AND there isn't already error text associated with this request,
732      * THEN make the message text available to ErrorDocument and
733      * other error processors.
734      */
735     va_end(args);
736     va_start(args,fmt);
737     if ((level & APLOG_TOCLIENT)
738         && ((level & APLOG_LEVELMASK) <= APLOG_WARNING)
739         && (apr_table_get(r->notes, "error-notes") == NULL)) {
740         apr_table_setn(r->notes, "error-notes",
741                        ap_escape_html(r->pool, apr_pvsprintf(r->pool, fmt,
742                                                              args)));
743     }
744     va_end(args);
745 }
746
747 AP_DECLARE(void) ap_log_cerror(const char *file, int line, int level,
748                                apr_status_t status, const conn_rec *c,
749                                const char *fmt, ...)
750 {
751     va_list args;
752
753     va_start(args, fmt);
754     log_error_core(file, line, level, status, c->base_server, c, NULL, NULL,
755                    fmt, args);
756     va_end(args);
757 }
758
759 AP_DECLARE(void) ap_log_pid(apr_pool_t *p, const char *filename)
760 {
761     apr_file_t *pid_file = NULL;
762     apr_finfo_t finfo;
763     static pid_t saved_pid = -1;
764     pid_t mypid;
765     apr_status_t rv;
766     const char *fname;
767
768     if (!filename) {
769         return;
770     }
771
772     fname = ap_server_root_relative(p, filename);
773     if (!fname) {
774         ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_CRIT, APR_EBADPATH, 
775                      NULL, "Invalid PID file path %s, ignoring.", filename);
776         return;
777     }
778
779     mypid = getpid();
780     if (mypid != saved_pid
781         && apr_stat(&finfo, fname, APR_FINFO_MTIME, p) == APR_SUCCESS) {
782         /* AP_SIG_GRACEFUL and HUP call this on each restart.
783          * Only warn on first time through for this pid.
784          *
785          * XXX: Could just write first time through too, although
786          *      that may screw up scripts written to do something
787          *      based on the last modification time of the pid file.
788          */
789         ap_log_perror(APLOG_MARK, APLOG_WARNING, 0, p,
790                       apr_psprintf(p, "pid file %s overwritten -- Unclean "
791                                    "shutdown of previous Apache run?",
792                                    fname));
793     }
794
795     if ((rv = apr_file_open(&pid_file, fname,
796                             APR_WRITE | APR_CREATE | APR_TRUNCATE,
797                             APR_UREAD | APR_UWRITE | APR_GREAD | APR_WREAD, p))
798         != APR_SUCCESS) {
799         ap_log_error(APLOG_MARK, APLOG_ERR, rv, NULL,
800                      "could not create %s", fname);
801         ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL,
802                      "%s: could not log pid to file %s",
803                      ap_server_argv0, fname);
804         exit(1);
805     }
806     apr_file_printf(pid_file, "%ld" APR_EOL_STR, (long)mypid);
807     apr_file_close(pid_file);
808     saved_pid = mypid;
809 }
810
811 AP_DECLARE(apr_status_t) ap_read_pid(apr_pool_t *p, const char *filename,
812                                      pid_t *mypid)
813 {
814     const apr_size_t BUFFER_SIZE = sizeof(long) * 3 + 2; /* see apr_ltoa */
815     apr_file_t *pid_file = NULL;
816     apr_status_t rv;
817     const char *fname;
818     char *buf, *endptr;
819     apr_size_t bytes_read;
820
821     if (!filename) {
822         return APR_EGENERAL;
823     }
824
825     fname = ap_server_root_relative(p, filename);
826     if (!fname) {
827         ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_CRIT, APR_EBADPATH, 
828                      NULL, "Invalid PID file path %s, ignoring.", filename);
829         return APR_EGENERAL;
830     }
831
832     rv = apr_file_open(&pid_file, fname, APR_READ, APR_OS_DEFAULT, p);
833     if (rv != APR_SUCCESS) {
834         return rv;
835     }
836
837     /* Ensure null-termination, so that strtol doesn't go crazy. */
838     buf = apr_palloc(p, BUFFER_SIZE);
839     buf[BUFFER_SIZE - 1] = '\0';
840
841     rv = apr_file_read_full(pid_file, buf, BUFFER_SIZE - 1, &bytes_read);
842     if (rv != APR_SUCCESS && rv != APR_EOF) {
843         return rv;
844     }
845
846     /* If we fill the buffer, we're probably reading a corrupt pid file.
847      * To be nice, let's also ensure the first char is a digit. */
848     if (bytes_read == BUFFER_SIZE - 1 || !apr_isdigit(*buf)) {
849         return APR_EGENERAL;
850     }
851
852     *mypid = strtol(buf, &endptr, 10);
853
854     apr_file_close(pid_file);
855     return APR_SUCCESS;
856 }
857
858 AP_DECLARE(void) ap_log_assert(const char *szExp, const char *szFile,
859                                int nLine)
860 {
861     char time_str[APR_CTIME_LEN];
862
863     apr_ctime(time_str, apr_time_now());
864     ap_log_error(APLOG_MARK, APLOG_CRIT, 0, NULL,
865                  "[%s] file %s, line %d, assertion \"%s\" failed",
866                  time_str, szFile, nLine, szExp);
867 #if defined(WIN32)
868     DebugBreak();
869 #else
870     /* unix assert does an abort leading to a core dump */
871     abort();
872 #endif
873 }
874
875 /* piped log support */
876
877 #ifdef AP_HAVE_RELIABLE_PIPED_LOGS
878 /* forward declaration */
879 static void piped_log_maintenance(int reason, void *data, apr_wait_t status);
880
881 /* Spawn the piped logger process pl->program. */
882 static apr_status_t piped_log_spawn(piped_log *pl)
883 {
884     apr_procattr_t *procattr;
885     apr_proc_t *procnew = NULL;
886     apr_status_t status;
887
888     if (((status = apr_procattr_create(&procattr, pl->p)) != APR_SUCCESS) ||
889         ((status = apr_procattr_child_in_set(procattr,
890                                              ap_piped_log_read_fd(pl),
891                                              ap_piped_log_write_fd(pl)))
892         != APR_SUCCESS) ||
893         ((status = apr_procattr_child_errfn_set(procattr, log_child_errfn))
894          != APR_SUCCESS) ||
895         ((status = apr_procattr_error_check_set(procattr, 1)) != APR_SUCCESS)) {
896         char buf[120];
897         /* Something bad happened, give up and go away. */
898         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
899                      "piped_log_spawn: unable to setup child process '%s': %s",
900                      pl->program, apr_strerror(status, buf, sizeof(buf)));
901     }
902     else {
903         char **args;
904         const char *pname;
905         apr_file_t *outfile, *errfile;
906
907         if ((status = apr_file_open_stdout(&outfile, pl->p)) == APR_SUCCESS)
908             status = apr_procattr_child_out_set(procattr, outfile, NULL);
909         if ((status = apr_file_open_stderr(&errfile, pl->p)) == APR_SUCCESS)
910             status = apr_procattr_child_err_set(procattr, errfile, NULL);
911
912         apr_tokenize_to_argv(pl->program, &args, pl->p);
913         pname = apr_pstrdup(pl->p, args[0]);
914         procnew = apr_pcalloc(pl->p, sizeof(apr_proc_t));
915         status = apr_proc_create(procnew, pname, (const char * const *) args,
916                                  NULL, procattr, pl->p);
917
918         if (status == APR_SUCCESS) {
919             pl->pid = procnew;
920             /* procnew->in was dup2'd from ap_piped_log_write_fd(pl);
921              * since the original fd is still valid, close the copy to
922              * avoid a leak. */
923             apr_file_close(procnew->in);
924             procnew->in = NULL;
925             apr_proc_other_child_register(procnew, piped_log_maintenance, pl,
926                                           ap_piped_log_write_fd(pl), pl->p);
927             close_handle_in_child(pl->p, ap_piped_log_read_fd(pl));
928         }
929         else {
930             char buf[120];
931             /* Something bad happened, give up and go away. */
932             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
933                          "unable to start piped log program '%s': %s",
934                          pl->program, apr_strerror(status, buf, sizeof(buf)));
935         }
936     }
937
938     return status;
939 }
940
941
942 static void piped_log_maintenance(int reason, void *data, apr_wait_t status)
943 {
944     piped_log *pl = data;
945     apr_status_t stats;
946     int mpm_state;
947
948     switch (reason) {
949     case APR_OC_REASON_DEATH:
950     case APR_OC_REASON_LOST:
951         pl->pid = NULL; /* in case we don't get it going again, this
952                          * tells other logic not to try to kill it
953                          */
954         apr_proc_other_child_unregister(pl);
955         stats = ap_mpm_query(AP_MPMQ_MPM_STATE, &mpm_state);
956         if (stats != APR_SUCCESS) {
957             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
958                          "can't query MPM state; not restarting "
959                          "piped log program '%s'",
960                          pl->program);
961         }
962         else if (mpm_state != AP_MPMQ_STOPPING) {
963             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
964                          "piped log program '%s' failed unexpectedly",
965                          pl->program);
966             if ((stats = piped_log_spawn(pl)) != APR_SUCCESS) {
967                 /* what can we do?  This could be the error log we're having
968                  * problems opening up... */
969                 char buf[120];
970                 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
971                              "piped_log_maintenance: unable to respawn '%s': %s",
972                              pl->program, apr_strerror(stats, buf, sizeof(buf)));
973             }
974         }
975         break;
976
977     case APR_OC_REASON_UNWRITABLE:
978         /* We should not kill off the pipe here, since it may only be full.
979          * If it really is locked, we should kill it off manually. */
980     break;
981
982     case APR_OC_REASON_RESTART:
983         if (pl->pid != NULL) {
984             apr_proc_kill(pl->pid, SIGTERM);
985             pl->pid = NULL;
986         }
987         break;
988
989     case APR_OC_REASON_UNREGISTER:
990         break;
991     }
992 }
993
994
995 static apr_status_t piped_log_cleanup_for_exec(void *data)
996 {
997     piped_log *pl = data;
998
999     apr_file_close(ap_piped_log_read_fd(pl));
1000     apr_file_close(ap_piped_log_write_fd(pl));
1001     return APR_SUCCESS;
1002 }
1003
1004
1005 static apr_status_t piped_log_cleanup(void *data)
1006 {
1007     piped_log *pl = data;
1008
1009     if (pl->pid != NULL) {
1010         apr_proc_kill(pl->pid, SIGTERM);
1011     }
1012     return piped_log_cleanup_for_exec(data);
1013 }
1014
1015
1016 AP_DECLARE(piped_log *) ap_open_piped_log(apr_pool_t *p, const char *program)
1017 {
1018     piped_log *pl;
1019
1020     pl = apr_palloc(p, sizeof (*pl));
1021     pl->p = p;
1022     pl->program = apr_pstrdup(p, program);
1023     pl->pid = NULL;
1024     if (apr_file_pipe_create(&ap_piped_log_read_fd(pl),
1025                              &ap_piped_log_write_fd(pl), p) != APR_SUCCESS) {
1026         return NULL;
1027     }
1028     apr_pool_cleanup_register(p, pl, piped_log_cleanup,
1029                               piped_log_cleanup_for_exec);
1030     if (piped_log_spawn(pl) != APR_SUCCESS) {
1031         apr_pool_cleanup_kill(p, pl, piped_log_cleanup);
1032         apr_file_close(ap_piped_log_read_fd(pl));
1033         apr_file_close(ap_piped_log_write_fd(pl));
1034         return NULL;
1035     }
1036     return pl;
1037 }
1038
1039 #else /* !AP_HAVE_RELIABLE_PIPED_LOGS */
1040
1041 static apr_status_t piped_log_cleanup(void *data)
1042 {
1043     piped_log *pl = data;
1044
1045     apr_file_close(ap_piped_log_write_fd(pl));
1046     return APR_SUCCESS;
1047 }
1048
1049 AP_DECLARE(piped_log *) ap_open_piped_log(apr_pool_t *p, const char *program)
1050 {
1051     piped_log *pl;
1052     apr_file_t *dummy = NULL;
1053     int rc;
1054
1055     rc = log_child(p, program, &dummy, 0);
1056     if (rc != APR_SUCCESS) {
1057         ap_log_error(APLOG_MARK, APLOG_STARTUP, rc, NULL,
1058                      "Couldn't start piped log process");
1059         return NULL;
1060     }
1061
1062     pl = apr_palloc(p, sizeof (*pl));
1063     pl->p = p;
1064     ap_piped_log_read_fd(pl) = NULL;
1065     ap_piped_log_write_fd(pl) = dummy;
1066     apr_pool_cleanup_register(p, pl, piped_log_cleanup, piped_log_cleanup);
1067
1068     return pl;
1069 }
1070
1071 #endif
1072
1073 AP_DECLARE(void) ap_close_piped_log(piped_log *pl)
1074 {
1075     apr_pool_cleanup_run(pl->p, pl, piped_log_cleanup);
1076 }
1077
1078 AP_IMPLEMENT_HOOK_VOID(error_log,
1079                        (const char *file, int line, int level,
1080                         apr_status_t status, const server_rec *s,
1081                         const request_rec *r, apr_pool_t *pool,
1082                         const char *errstr), (file, line, level,
1083                         status, s, r, pool, errstr))
1084