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