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