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