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