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