]> granicus.if.org Git - apache/blob - server/log.c
05d99ad6150f8314c9904c3bfa1150f4b5d9b6ad
[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 #include "apr_base64.h"
33
34 #define APR_WANT_STDIO
35 #define APR_WANT_STRFUNC
36 #include "apr_want.h"
37
38 #if APR_HAVE_STDARG_H
39 #include <stdarg.h>
40 #endif
41 #if APR_HAVE_UNISTD_H
42 #include <unistd.h>
43 #endif
44 #if APR_HAVE_PROCESS_H
45 #include <process.h>            /* for getpid() on Win32 */
46 #endif
47
48 #include "ap_config.h"
49 #include "httpd.h"
50 #include "http_config.h"
51 #include "http_core.h"
52 #include "http_log.h"
53 #include "http_main.h"
54 #include "util_time.h"
55 #include "ap_mpm.h"
56
57 #if HAVE_GETTID
58 #include <sys/syscall.h>
59 #include <sys/types.h>
60 #endif
61
62 /* we know core's module_index is 0 */
63 #undef APLOG_MODULE_INDEX
64 #define APLOG_MODULE_INDEX AP_CORE_MODULE_INDEX
65
66 typedef struct {
67     const char *t_name;
68     int t_val;
69 } TRANS;
70
71 APR_HOOK_STRUCT(
72     APR_HOOK_LINK(error_log)
73     APR_HOOK_LINK(generate_log_id)
74 )
75
76 int AP_DECLARE_DATA ap_default_loglevel = DEFAULT_LOGLEVEL;
77
78 #ifdef HAVE_SYSLOG
79
80 static const TRANS facilities[] = {
81     {"auth",    LOG_AUTH},
82 #ifdef LOG_AUTHPRIV
83     {"authpriv",LOG_AUTHPRIV},
84 #endif
85 #ifdef LOG_CRON
86     {"cron",    LOG_CRON},
87 #endif
88 #ifdef LOG_DAEMON
89     {"daemon",  LOG_DAEMON},
90 #endif
91 #ifdef LOG_FTP
92     {"ftp", LOG_FTP},
93 #endif
94 #ifdef LOG_KERN
95     {"kern",    LOG_KERN},
96 #endif
97 #ifdef LOG_LPR
98     {"lpr", LOG_LPR},
99 #endif
100 #ifdef LOG_MAIL
101     {"mail",    LOG_MAIL},
102 #endif
103 #ifdef LOG_NEWS
104     {"news",    LOG_NEWS},
105 #endif
106 #ifdef LOG_SYSLOG
107     {"syslog",  LOG_SYSLOG},
108 #endif
109 #ifdef LOG_USER
110     {"user",    LOG_USER},
111 #endif
112 #ifdef LOG_UUCP
113     {"uucp",    LOG_UUCP},
114 #endif
115 #ifdef LOG_LOCAL0
116     {"local0",  LOG_LOCAL0},
117 #endif
118 #ifdef LOG_LOCAL1
119     {"local1",  LOG_LOCAL1},
120 #endif
121 #ifdef LOG_LOCAL2
122     {"local2",  LOG_LOCAL2},
123 #endif
124 #ifdef LOG_LOCAL3
125     {"local3",  LOG_LOCAL3},
126 #endif
127 #ifdef LOG_LOCAL4
128     {"local4",  LOG_LOCAL4},
129 #endif
130 #ifdef LOG_LOCAL5
131     {"local5",  LOG_LOCAL5},
132 #endif
133 #ifdef LOG_LOCAL6
134     {"local6",  LOG_LOCAL6},
135 #endif
136 #ifdef LOG_LOCAL7
137     {"local7",  LOG_LOCAL7},
138 #endif
139     {NULL,      -1},
140 };
141 #endif
142
143 static const TRANS priorities[] = {
144     {"emerg",   APLOG_EMERG},
145     {"alert",   APLOG_ALERT},
146     {"crit",    APLOG_CRIT},
147     {"error",   APLOG_ERR},
148     {"warn",    APLOG_WARNING},
149     {"notice",  APLOG_NOTICE},
150     {"info",    APLOG_INFO},
151     {"debug",   APLOG_DEBUG},
152     {"trace1",  APLOG_TRACE1},
153     {"trace2",  APLOG_TRACE2},
154     {"trace3",  APLOG_TRACE3},
155     {"trace4",  APLOG_TRACE4},
156     {"trace5",  APLOG_TRACE5},
157     {"trace6",  APLOG_TRACE6},
158     {"trace7",  APLOG_TRACE7},
159     {"trace8",  APLOG_TRACE8},
160     {NULL,      -1},
161 };
162
163 static apr_pool_t *stderr_pool = NULL;
164
165 static apr_file_t *stderr_log = NULL;
166
167 /* track pipe handles to close in child process */
168 typedef struct read_handle_t {
169     struct read_handle_t *next;
170     apr_file_t *handle;
171 } read_handle_t;
172
173 static read_handle_t *read_handles;
174
175 /**
176  * @brief The piped logging structure.
177  *
178  * Piped logs are used to move functionality out of the main server.
179  * For example, log rotation is done with piped logs.
180  */
181 struct piped_log {
182     /** The pool to use for the piped log */
183     apr_pool_t *p;
184     /** The pipe between the server and the logging process */
185     apr_file_t *read_fd, *write_fd;
186 #ifdef AP_HAVE_RELIABLE_PIPED_LOGS
187     /** The name of the program the logging process is running */
188     char *program;
189     /** The pid of the logging process */
190     apr_proc_t *pid;
191     /** How to reinvoke program when it must be replaced */
192     apr_cmdtype_e cmdtype;
193 #endif
194 };
195
196 AP_DECLARE(apr_file_t *) ap_piped_log_read_fd(piped_log *pl)
197 {
198     return pl->read_fd;
199 }
200
201 AP_DECLARE(apr_file_t *) ap_piped_log_write_fd(piped_log *pl)
202 {
203     return pl->write_fd;
204 }
205
206 /* remember to close this handle in the child process
207  *
208  * On Win32 this makes zero sense, because we don't
209  * take the parent process's child procs.
210  * If the win32 parent instead passed each and every
211  * logger write handle from itself down to the child,
212  * and the parent manages all aspects of keeping the
213  * reliable pipe log children alive, this would still
214  * make no sense :)  Cripple it on Win32.
215  */
216 static void close_handle_in_child(apr_pool_t *p, apr_file_t *f)
217 {
218 #ifndef WIN32
219     read_handle_t *new_handle;
220
221     new_handle = apr_pcalloc(p, sizeof(read_handle_t));
222     new_handle->next = read_handles;
223     new_handle->handle = f;
224     read_handles = new_handle;
225 #endif
226 }
227
228 void ap_logs_child_init(apr_pool_t *p, server_rec *s)
229 {
230     read_handle_t *cur = read_handles;
231
232     while (cur) {
233         apr_file_close(cur->handle);
234         cur = cur->next;
235     }
236 }
237
238 AP_DECLARE(void) ap_open_stderr_log(apr_pool_t *p)
239 {
240     apr_file_open_stderr(&stderr_log, p);
241 }
242
243 AP_DECLARE(apr_status_t) ap_replace_stderr_log(apr_pool_t *p,
244                                                const char *fname)
245 {
246     apr_file_t *stderr_file;
247     apr_status_t rc;
248     char *filename = ap_server_root_relative(p, fname);
249     if (!filename) {
250         ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_CRIT,
251                      APR_EBADPATH, NULL, APLOGNO(00085) "Invalid -E error log file %s",
252                      fname);
253         return APR_EBADPATH;
254     }
255     if ((rc = apr_file_open(&stderr_file, filename,
256                             APR_APPEND | APR_WRITE | APR_CREATE | APR_LARGEFILE,
257                             APR_OS_DEFAULT, p)) != APR_SUCCESS) {
258         ap_log_error(APLOG_MARK, APLOG_STARTUP, rc, NULL, APLOGNO(00086)
259                      "%s: could not open error log file %s.",
260                      ap_server_argv0, fname);
261         return rc;
262     }
263     if (!stderr_pool) {
264         /* This is safe provided we revert it when we are finished.
265          * We don't manager the callers pool!
266          */
267         stderr_pool = p;
268     }
269     if ((rc = apr_file_open_stderr(&stderr_log, stderr_pool))
270             == APR_SUCCESS) {
271         apr_file_flush(stderr_log);
272         if ((rc = apr_file_dup2(stderr_log, stderr_file, stderr_pool))
273                 == APR_SUCCESS) {
274             apr_file_close(stderr_file);
275             /*
276              * You might ponder why stderr_pool should survive?
277              * The trouble is, stderr_pool may have s_main->error_log,
278              * so we aren't in a position to destory stderr_pool until
279              * the next recycle.  There's also an apparent bug which
280              * is not; if some folk decided to call this function before
281              * the core open error logs hook, this pool won't survive.
282              * Neither does the stderr logger, so this isn't a problem.
283              */
284         }
285     }
286     /* Revert, see above */
287     if (stderr_pool == p)
288         stderr_pool = NULL;
289
290     if (rc != APR_SUCCESS) {
291         ap_log_error(APLOG_MARK, APLOG_CRIT, rc, NULL, APLOGNO(00087)
292                      "unable to replace stderr with error log file");
293     }
294     return rc;
295 }
296
297 static void log_child_errfn(apr_pool_t *pool, apr_status_t err,
298                             const char *description)
299 {
300     ap_log_error(APLOG_MARK, APLOG_ERR, err, NULL, APLOGNO(00088)
301                  "%s", description);
302 }
303
304 /* Create a child process running PROGNAME with a pipe connected to
305  * the childs stdin.  The write-end of the pipe will be placed in
306  * *FPIN on successful return.  If dummy_stderr is non-zero, the
307  * stderr for the child will be the same as the stdout of the parent.
308  * Otherwise the child will inherit the stderr from the parent. */
309 static int log_child(apr_pool_t *p, const char *progname,
310                      apr_file_t **fpin, apr_cmdtype_e cmdtype,
311                      int dummy_stderr)
312 {
313     /* Child process code for 'ErrorLog "|..."';
314      * may want a common framework for this, since I expect it will
315      * be common for other foo-loggers to want this sort of thing...
316      */
317     apr_status_t rc;
318     apr_procattr_t *procattr;
319     apr_proc_t *procnew;
320     apr_file_t *errfile;
321
322     if (((rc = apr_procattr_create(&procattr, p)) == APR_SUCCESS)
323         && ((rc = apr_procattr_dir_set(procattr,
324                                        ap_server_root)) == APR_SUCCESS)
325         && ((rc = apr_procattr_cmdtype_set(procattr, cmdtype)) == APR_SUCCESS)
326         && ((rc = apr_procattr_io_set(procattr,
327                                       APR_FULL_BLOCK,
328                                       APR_NO_PIPE,
329                                       APR_NO_PIPE)) == APR_SUCCESS)
330         && ((rc = apr_procattr_error_check_set(procattr, 1)) == APR_SUCCESS)
331         && ((rc = apr_procattr_child_errfn_set(procattr, log_child_errfn))
332                 == APR_SUCCESS)) {
333         char **args;
334         const char *pname;
335
336         apr_tokenize_to_argv(progname, &args, p);
337         pname = apr_pstrdup(p, args[0]);
338         procnew = (apr_proc_t *)apr_pcalloc(p, sizeof(*procnew));
339
340         if (dummy_stderr) {
341             if ((rc = apr_file_open_stdout(&errfile, p)) == APR_SUCCESS)
342                 rc = apr_procattr_child_err_set(procattr, errfile, NULL);
343         }
344
345         rc = apr_proc_create(procnew, pname, (const char * const *)args,
346                              NULL, procattr, p);
347
348         if (rc == APR_SUCCESS) {
349             apr_pool_note_subprocess(p, procnew, APR_KILL_AFTER_TIMEOUT);
350             (*fpin) = procnew->in;
351             /* read handle to pipe not kept open, so no need to call
352              * close_handle_in_child()
353              */
354         }
355     }
356
357     return rc;
358 }
359
360 /* Open the error log for the given server_rec.  If IS_MAIN is
361  * non-zero, s is the main server. */
362 static int open_error_log(server_rec *s, int is_main, apr_pool_t *p)
363 {
364     const char *fname;
365     int rc;
366
367     if (*s->error_fname == '|') {
368         apr_file_t *dummy = NULL;
369         apr_cmdtype_e cmdtype = APR_PROGRAM_ENV;
370         fname = s->error_fname + 1;
371
372         /* In 2.4 favor PROGRAM_ENV, accept "||prog" syntax for compatibility
373          * and "|$cmd" to override the default.
374          * Any 2.2 backport would continue to favor SHELLCMD_ENV so there
375          * accept "||prog" to override, and "|$cmd" to ease conversion.
376          */
377         if (*fname == '|')
378             ++fname;
379         if (*fname == '$') {
380             cmdtype = APR_SHELLCMD_ENV;
381             ++fname;
382         }
383
384         /* Spawn a new child logger.  If this is the main server_rec,
385          * the new child must use a dummy stderr since the current
386          * stderr might be a pipe to the old logger.  Otherwise, the
387          * child inherits the parents stderr. */
388         rc = log_child(p, fname, &dummy, cmdtype, is_main);
389         if (rc != APR_SUCCESS) {
390             ap_log_error(APLOG_MARK, APLOG_STARTUP, rc, NULL, APLOGNO(00089)
391                          "Couldn't start ErrorLog process '%s'.",
392                          s->error_fname + 1);
393             return DONE;
394         }
395
396         s->error_log = dummy;
397     }
398
399 #ifdef HAVE_SYSLOG
400     else if (!strncasecmp(s->error_fname, "syslog", 6)) {
401         if ((fname = strchr(s->error_fname, ':'))) {
402             const TRANS *fac;
403
404             fname++;
405             for (fac = facilities; fac->t_name; fac++) {
406                 if (!strcasecmp(fname, fac->t_name)) {
407                     openlog(ap_server_argv0, LOG_NDELAY|LOG_CONS|LOG_PID,
408                             fac->t_val);
409                     s->error_log = NULL;
410                     return OK;
411                 }
412             }
413         }
414         else {
415             openlog(ap_server_argv0, LOG_NDELAY|LOG_CONS|LOG_PID, LOG_LOCAL7);
416         }
417
418         s->error_log = NULL;
419     }
420 #endif
421     else {
422         fname = ap_server_root_relative(p, s->error_fname);
423         if (!fname) {
424             ap_log_error(APLOG_MARK, APLOG_STARTUP, APR_EBADPATH, NULL, APLOGNO(00090)
425                          "%s: Invalid error log path %s.",
426                          ap_server_argv0, s->error_fname);
427             return DONE;
428         }
429         if ((rc = apr_file_open(&s->error_log, fname,
430                                APR_APPEND | APR_WRITE | APR_CREATE | APR_LARGEFILE,
431                                APR_OS_DEFAULT, p)) != APR_SUCCESS) {
432             ap_log_error(APLOG_MARK, APLOG_STARTUP, rc, NULL, APLOGNO(00091)
433                          "%s: could not open error log file %s.",
434                          ap_server_argv0, fname);
435             return DONE;
436         }
437     }
438
439     return OK;
440 }
441
442 int ap_open_logs(apr_pool_t *pconf, apr_pool_t *p /* plog */,
443                  apr_pool_t *ptemp, server_rec *s_main)
444 {
445     apr_pool_t *stderr_p;
446     server_rec *virt, *q;
447     int replace_stderr;
448
449
450     /* Register to throw away the read_handles list when we
451      * cleanup plog.  Upon fork() for the apache children,
452      * this read_handles list is closed so only the parent
453      * can relaunch a lost log child.  These read handles
454      * are always closed on exec.
455      * We won't care what happens to our stderr log child
456      * between log phases, so we don't mind losing stderr's
457      * read_handle a little bit early.
458      */
459     apr_pool_cleanup_register(p, &read_handles, ap_pool_cleanup_set_null,
460                               apr_pool_cleanup_null);
461
462     /* HERE we need a stdout log that outlives plog.
463      * We *presume* the parent of plog is a process
464      * or global pool which spans server restarts.
465      * Create our stderr_pool as a child of the plog's
466      * parent pool.
467      */
468     apr_pool_create(&stderr_p, apr_pool_parent_get(p));
469     apr_pool_tag(stderr_p, "stderr_pool");
470
471     if (open_error_log(s_main, 1, stderr_p) != OK) {
472         return DONE;
473     }
474
475     replace_stderr = 1;
476     if (s_main->error_log) {
477         apr_status_t rv;
478
479         /* Replace existing stderr with new log. */
480         apr_file_flush(s_main->error_log);
481         rv = apr_file_dup2(stderr_log, s_main->error_log, stderr_p);
482         if (rv != APR_SUCCESS) {
483             ap_log_error(APLOG_MARK, APLOG_CRIT, rv, s_main, APLOGNO(00092)
484                          "unable to replace stderr with error_log");
485         }
486         else {
487             /* We are done with stderr_pool, close it, killing
488              * the previous generation's stderr logger
489              */
490             if (stderr_pool)
491                 apr_pool_destroy(stderr_pool);
492             stderr_pool = stderr_p;
493             replace_stderr = 0;
494             /*
495              * Now that we have dup'ed s_main->error_log to stderr_log
496              * close it and set s_main->error_log to stderr_log. This avoids
497              * this fd being inherited by the next piped logger who would
498              * keep open the writing end of the pipe that this one uses
499              * as stdin. This in turn would prevent the piped logger from
500              * exiting.
501              */
502              apr_file_close(s_main->error_log);
503              s_main->error_log = stderr_log;
504         }
505     }
506     /* note that stderr may still need to be replaced with something
507      * because it points to the old error log, or back to the tty
508      * of the submitter.
509      * XXX: This is BS - /dev/null is non-portable
510      *      errno-as-apr_status_t is also non-portable
511      */
512     if (replace_stderr && freopen("/dev/null", "w", stderr) == NULL) {
513         ap_log_error(APLOG_MARK, APLOG_CRIT, errno, s_main, APLOGNO(00093)
514                      "unable to replace stderr with /dev/null");
515     }
516
517     for (virt = s_main->next; virt; virt = virt->next) {
518         if (virt->error_fname) {
519             for (q=s_main; q != virt; q = q->next) {
520                 if (q->error_fname != NULL
521                     && strcmp(q->error_fname, virt->error_fname) == 0) {
522                     break;
523                 }
524             }
525
526             if (q == virt) {
527                 if (open_error_log(virt, 0, p) != OK) {
528                     return DONE;
529                 }
530             }
531             else {
532                 virt->error_log = q->error_log;
533             }
534         }
535         else {
536             virt->error_log = s_main->error_log;
537         }
538     }
539     return OK;
540 }
541
542 AP_DECLARE(void) ap_error_log2stderr(server_rec *s) {
543     apr_file_t *errfile = NULL;
544
545     apr_file_open_stderr(&errfile, s->process->pool);
546     if (s->error_log != NULL) {
547         apr_file_dup2(s->error_log, errfile, s->process->pool);
548     }
549 }
550
551 static int cpystrn(char *buf, const char *arg, int buflen)
552 {
553     char *end;
554     if (!arg)
555         return 0;
556     end = apr_cpystrn(buf, arg, buflen);
557     return end - buf;
558 }
559
560
561 static int log_remote_address(const ap_errorlog_info *info, const char *arg,
562                               char *buf, int buflen)
563 {
564     if (info->r && !(arg && *arg == 'c'))
565         return apr_snprintf(buf, buflen, "%s:%d", info->r->useragent_ip,
566                             info->r->useragent_addr ? info->r->useragent_addr->port : 0);
567     else if (info->c)
568         return apr_snprintf(buf, buflen, "%s:%d", info->c->client_ip,
569                             info->c->client_addr ? info->c->client_addr->port : 0);
570     else
571         return 0;
572 }
573
574 static int log_local_address(const ap_errorlog_info *info, const char *arg,
575                              char *buf, int buflen)
576 {
577     if (info->c)
578         return apr_snprintf(buf, buflen, "%s:%d", info->c->local_ip,
579                             info->c->local_addr->port);
580     else
581         return 0;
582 }
583
584 static int log_pid(const ap_errorlog_info *info, const char *arg,
585                    char *buf, int buflen)
586 {
587     pid_t pid = getpid();
588     return apr_snprintf(buf, buflen, "%" APR_PID_T_FMT, pid);
589 }
590
591 static int log_tid(const ap_errorlog_info *info, const char *arg,
592                    char *buf, int buflen)
593 {
594 #if APR_HAS_THREADS
595     int result;
596 #endif
597 #if HAVE_GETTID
598     if (arg && *arg == 'g') {
599         pid_t tid = syscall(SYS_gettid);
600         if (tid == -1)
601             return 0;
602         return apr_snprintf(buf, buflen, "%"APR_PID_T_FMT, tid);
603     }
604 #endif
605 #if APR_HAS_THREADS
606     if (ap_mpm_query(AP_MPMQ_IS_THREADED, &result) == APR_SUCCESS
607         && result != AP_MPMQ_NOT_SUPPORTED)
608     {
609         apr_os_thread_t tid = apr_os_thread_current();
610         return apr_snprintf(buf, buflen, "%pT", &tid);
611     }
612 #endif
613     return 0;
614 }
615
616 static int log_ctime(const ap_errorlog_info *info, const char *arg,
617                      char *buf, int buflen)
618 {
619     int time_len = buflen;
620     int option = AP_CTIME_OPTION_NONE;
621
622     while(arg && *arg) {
623         switch (*arg) {
624             case 'u':   option |= AP_CTIME_OPTION_USEC;
625                         break;
626             case 'c':   option |= AP_CTIME_OPTION_COMPACT;
627                         break;
628         }
629         arg++;
630     }
631
632     ap_recent_ctime_ex(buf, apr_time_now(), option, &time_len);
633
634     /* ap_recent_ctime_ex includes the trailing \0 in time_len */
635     return time_len - 1;
636 }
637
638 static int log_loglevel(const ap_errorlog_info *info, const char *arg,
639                         char *buf, int buflen)
640 {
641     if (info->level < 0)
642         return 0;
643     else
644         return cpystrn(buf, priorities[info->level].t_name, buflen);
645 }
646
647 static int log_log_id(const ap_errorlog_info *info, const char *arg,
648                       char *buf, int buflen)
649 {
650     /*
651      * C: log conn log_id if available,
652      * c: log conn log id if available and not a once-per-request log line
653      * else: log request log id if available
654      */
655     if (arg && !strcasecmp(arg, "c")) {
656         if (info->c && (*arg != 'C' || !info->r)) {
657             return cpystrn(buf, info->c->log_id, buflen);
658         }
659     }
660     else if (info->rmain) {
661         return cpystrn(buf, info->rmain->log_id, buflen);
662     }
663     return 0;
664 }
665
666 static int log_keepalives(const ap_errorlog_info *info, const char *arg,
667                           char *buf, int buflen)
668 {
669     if (!info->c)
670         return 0;
671
672     return apr_snprintf(buf, buflen, "%d", info->c->keepalives);
673 }
674
675 static int log_module_name(const ap_errorlog_info *info, const char *arg,
676                            char *buf, int buflen)
677 {
678     return cpystrn(buf, ap_find_module_short_name(info->module_index), buflen);
679 }
680
681 static int log_file_line(const ap_errorlog_info *info, const char *arg,
682                          char *buf, int buflen)
683 {
684     if (info->file == NULL) {
685         return 0;
686     }
687     else {
688         const char *file = info->file;
689 #if defined(_OSD_POSIX) || defined(WIN32) || defined(__MVS__)
690         char tmp[256];
691         char *e = strrchr(file, '/');
692 #ifdef WIN32
693         if (!e) {
694             e = strrchr(file, '\\');
695         }
696 #endif
697
698         /* In OSD/POSIX, the compiler returns for __FILE__
699          * a string like: __FILE__="*POSIX(/usr/include/stdio.h)"
700          * (it even returns an absolute path for sources in
701          * the current directory). Here we try to strip this
702          * down to the basename.
703          */
704         if (e != NULL && e[1] != '\0') {
705             apr_snprintf(tmp, sizeof(tmp), "%s", &e[1]);
706             e = &tmp[strlen(tmp)-1];
707             if (*e == ')') {
708                 *e = '\0';
709             }
710             file = tmp;
711         }
712 #else /* _OSD_POSIX || WIN32 */
713         const char *p;
714         /* On Unix, __FILE__ may be an absolute path in a
715          * VPATH build. */
716         if (file[0] == '/' && (p = ap_strrchr_c(file, '/')) != NULL) {
717             file = p + 1;
718         }
719 #endif /*_OSD_POSIX || WIN32 */
720         return apr_snprintf(buf, buflen, "%s(%d)", file, info->line);
721     }
722 }
723
724 static int log_apr_status(const ap_errorlog_info *info, const char *arg,
725                           char *buf, int buflen)
726 {
727     apr_status_t status = info->status;
728     int len;
729     if (!status)
730         return 0;
731
732     if (status < APR_OS_START_EAIERR) {
733         len = apr_snprintf(buf, buflen, "(%d)", status);
734     }
735     else if (status < APR_OS_START_SYSERR) {
736         len = apr_snprintf(buf, buflen, "(EAI %d)",
737                            status - APR_OS_START_EAIERR);
738     }
739     else if (status < 100000 + APR_OS_START_SYSERR) {
740         len = apr_snprintf(buf, buflen, "(OS %d)",
741                            status - APR_OS_START_SYSERR);
742     }
743     else {
744         len = apr_snprintf(buf, buflen, "(os 0x%08x)",
745                            status - APR_OS_START_SYSERR);
746     }
747     apr_strerror(status, buf + len, buflen - len);
748     len += strlen(buf + len);
749     return len;
750 }
751
752 static int log_server_name(const ap_errorlog_info *info, const char *arg,
753                            char *buf, int buflen)
754 {
755     if (info->r)
756         return cpystrn(buf, ap_get_server_name((request_rec *)info->r), buflen);
757
758     return 0;
759 }
760
761 static int log_virtual_host(const ap_errorlog_info *info, const char *arg,
762                             char *buf, int buflen)
763 {
764     if (info->s)
765         return cpystrn(buf, info->s->server_hostname, buflen);
766
767     return 0;
768 }
769
770
771 static int log_table_entry(const apr_table_t *table, const char *name,
772                            char *buf, int buflen)
773 {
774 #ifndef AP_UNSAFE_ERROR_LOG_UNESCAPED
775     const char *value;
776     char scratch[MAX_STRING_LEN];
777
778     if ((value = apr_table_get(table, name)) != NULL) {
779         ap_escape_errorlog_item(scratch, value, MAX_STRING_LEN);
780         return cpystrn(buf, scratch, buflen);
781     }
782
783     return 0;
784 #else
785     return cpystrn(buf, apr_table_get(table, name), buflen);
786 #endif
787 }
788
789 static int log_header(const ap_errorlog_info *info, const char *arg,
790                       char *buf, int buflen)
791 {
792     if (info->r)
793         return log_table_entry(info->r->headers_in, arg, buf, buflen);
794
795     return 0;
796 }
797
798 static int log_note(const ap_errorlog_info *info, const char *arg,
799                       char *buf, int buflen)
800 {
801     /* XXX: maybe escaping the entry is not necessary for notes? */
802     if (info->r)
803         return log_table_entry(info->r->notes, arg, buf, buflen);
804
805     return 0;
806 }
807
808 static int log_env_var(const ap_errorlog_info *info, const char *arg,
809                       char *buf, int buflen)
810 {
811     if (info->r)
812         return log_table_entry(info->r->subprocess_env, arg, buf, buflen);
813
814     return 0;
815 }
816
817 static int core_generate_log_id(const conn_rec *c, const request_rec *r,
818                                  const char **idstring)
819 {
820     apr_uint64_t id, tmp;
821     pid_t pid;
822     int len;
823     char *encoded;
824
825     if (r && r->request_time) {
826         id = (apr_uint64_t)r->request_time;
827     }
828     else {
829         id = (apr_uint64_t)apr_time_now();
830     }
831
832     pid = getpid();
833     if (sizeof(pid_t) > 2) {
834         tmp = pid;
835         tmp = tmp << 40;
836         id ^= tmp;
837         pid = pid >> 24;
838         tmp = pid;
839         tmp = tmp << 56;
840         id ^= tmp;
841     }
842     else {
843         tmp = pid;
844         tmp = tmp << 40;
845         id ^= tmp;
846     }
847 #if APR_HAS_THREADS
848     {
849         apr_uintptr_t tmp2 = (apr_uintptr_t)c->current_thread;
850         tmp = tmp2;
851         tmp = tmp << 32;
852         id ^= tmp;
853     }
854 #endif
855
856     len = apr_base64_encode_len(sizeof(id)); /* includes trailing \0 */
857     encoded = apr_palloc(r ? r->pool : c->pool, len);
858     apr_base64_encode(encoded, (char *)&id, sizeof(id));
859
860     /* Skip the last char, it is always '=' */
861     encoded[len - 2] = '\0';
862
863     *idstring = encoded;
864
865     return OK;
866 }
867
868 static void add_log_id(const conn_rec *c, const request_rec *r)
869 {
870     const char **id;
871     /* need to cast const away */
872     if (r) {
873         id = &((request_rec *)r)->log_id;
874     }
875     else {
876         id = &((conn_rec *)c)->log_id;
877     }
878
879     ap_run_generate_log_id(c, r, id);
880 }
881
882 AP_DECLARE(void) ap_register_log_hooks(apr_pool_t *p)
883 {
884     ap_hook_generate_log_id(core_generate_log_id, NULL, NULL,
885                             APR_HOOK_REALLY_LAST);
886
887     ap_register_errorlog_handler(p, "a", log_remote_address, 0);
888     ap_register_errorlog_handler(p, "A", log_local_address, 0);
889     ap_register_errorlog_handler(p, "e", log_env_var, 0);
890     ap_register_errorlog_handler(p, "E", log_apr_status, 0);
891     ap_register_errorlog_handler(p, "F", log_file_line, 0);
892     ap_register_errorlog_handler(p, "i", log_header, 0);
893     ap_register_errorlog_handler(p, "k", log_keepalives, 0);
894     ap_register_errorlog_handler(p, "l", log_loglevel, 0);
895     ap_register_errorlog_handler(p, "L", log_log_id, 0);
896     ap_register_errorlog_handler(p, "m", log_module_name, 0);
897     ap_register_errorlog_handler(p, "n", log_note, 0);
898     ap_register_errorlog_handler(p, "P", log_pid, 0);
899     ap_register_errorlog_handler(p, "t", log_ctime, 0);
900     ap_register_errorlog_handler(p, "T", log_tid, 0);
901     ap_register_errorlog_handler(p, "v", log_virtual_host, 0);
902     ap_register_errorlog_handler(p, "V", log_server_name, 0);
903 }
904
905 /*
906  * This is used if no error log format is defined and during startup.
907  * It automatically omits the timestamp if logging to syslog.
908  */
909 static int do_errorlog_default(const ap_errorlog_info *info, char *buf,
910                                int buflen, int *errstr_start, int *errstr_end,
911                                const char *errstr_fmt, va_list args)
912 {
913     int len = 0;
914     int field_start = 0;
915     int item_len;
916 #ifndef AP_UNSAFE_ERROR_LOG_UNESCAPED
917     char scratch[MAX_STRING_LEN];
918 #endif
919
920     if (!info->using_syslog && !info->startup) {
921         buf[len++] = '[';
922         len += log_ctime(info, "u", buf + len, buflen - len);
923         buf[len++] = ']';
924         buf[len++] = ' ';
925     }
926
927     if (!info->startup) {
928         buf[len++] = '[';
929         len += log_module_name(info, NULL, buf + len, buflen - len);
930         buf[len++] = ':';
931         len += log_loglevel(info, NULL, buf + len, buflen - len);
932         len += cpystrn(buf + len, "] [pid ", buflen - len);
933
934         len += log_pid(info, NULL, buf + len, buflen - len);
935 #if APR_HAS_THREADS
936         field_start = len;
937         len += cpystrn(buf + len, ":tid ", buflen - len);
938         item_len = log_tid(info, NULL, buf + len, buflen - len);
939         if (!item_len)
940             len = field_start;
941         else
942             len += item_len;
943 #endif
944         buf[len++] = ']';
945         buf[len++] = ' ';
946     }
947
948     if (info->level >= APLOG_DEBUG) {
949         item_len = log_file_line(info, NULL, buf + len, buflen - len);
950         if (item_len) {
951             len += item_len;
952             len += cpystrn(buf + len, ": ", buflen - len);
953         }
954     }
955
956     if (info->status) {
957         item_len = log_apr_status(info, NULL, buf + len, buflen - len);
958         if (item_len) {
959             len += item_len;
960             len += cpystrn(buf + len, ": ", buflen - len);
961         }
962     }
963
964     /*
965      * useragent_ip/client_ip can be client or backend server. If we have
966      * a scoreboard handle, it is likely a client.
967      */
968     if (info->r) {
969         len += apr_snprintf(buf + len, buflen - len,
970                             info->r->connection->sbh ? "[client %s:%d] " : "[remote %s:%d] ",
971                             info->r->useragent_ip,
972                             info->r->useragent_addr ? info->r->useragent_addr->port : 0);
973     }
974     else if (info->c) {
975         len += apr_snprintf(buf + len, buflen - len,
976                             info->c->sbh ? "[client %s:%d] " : "[remote %s:%d] ",
977                             info->c->client_ip,
978                             info->c->client_addr ? info->c->client_addr->port : 0);
979     }
980
981     /* the actual error message */
982     *errstr_start = len;
983 #ifndef AP_UNSAFE_ERROR_LOG_UNESCAPED
984     if (apr_vsnprintf(scratch, MAX_STRING_LEN, errstr_fmt, args)) {
985         len += ap_escape_errorlog_item(buf + len, scratch,
986                                        buflen - len);
987
988     }
989 #else
990     len += apr_vsnprintf(buf + len, buflen - len, errstr_fmt, args);
991 #endif
992     *errstr_end = len;
993
994     field_start = len;
995     len += cpystrn(buf + len, ", referer: ", buflen - len);
996     item_len = log_header(info, "Referer", buf + len, buflen - len);
997     if (item_len)
998         len += item_len;
999     else
1000         len = field_start;
1001
1002     return len;
1003 }
1004
1005 static int do_errorlog_format(apr_array_header_t *fmt, ap_errorlog_info *info,
1006                               char *buf, int buflen, int *errstr_start,
1007                               int *errstr_end, const char *err_fmt, va_list args)
1008 {
1009 #ifndef AP_UNSAFE_ERROR_LOG_UNESCAPED
1010     char scratch[MAX_STRING_LEN];
1011 #endif
1012     int i;
1013     int len = 0;
1014     int field_start = 0;
1015     int skipping = 0;
1016     ap_errorlog_format_item *items = (ap_errorlog_format_item *)fmt->elts;
1017
1018     AP_DEBUG_ASSERT(fmt->nelts > 0);
1019     for (i = 0; i < fmt->nelts; ++i) {
1020         ap_errorlog_format_item *item = &items[i];
1021         if (item->flags & AP_ERRORLOG_FLAG_FIELD_SEP) {
1022             if (skipping) {
1023                 skipping = 0;
1024             }
1025             else {
1026                 field_start = len;
1027             }
1028         }
1029
1030         if (item->flags & AP_ERRORLOG_FLAG_MESSAGE) {
1031             /* the actual error message */
1032             *errstr_start = len;
1033 #ifndef AP_UNSAFE_ERROR_LOG_UNESCAPED
1034             if (apr_vsnprintf(scratch, MAX_STRING_LEN, err_fmt, args)) {
1035                 len += ap_escape_errorlog_item(buf + len, scratch,
1036                                                buflen - len);
1037
1038             }
1039 #else
1040             len += apr_vsnprintf(buf + len, buflen - len, err_fmt, args);
1041 #endif
1042             *errstr_end = len;
1043         }
1044         else if (skipping) {
1045             continue;
1046         }
1047         else if (info->level != -1 && (int)item->min_loglevel > info->level) {
1048             len = field_start;
1049             skipping = 1;
1050         }
1051         else {
1052             int item_len = (*item->func)(info, item->arg, buf + len,
1053                                          buflen - len);
1054             if (!item_len) {
1055                 if (item->flags & AP_ERRORLOG_FLAG_REQUIRED) {
1056                     /* required item is empty. skip whole line */
1057                     buf[0] = '\0';
1058                     return 0;
1059                 }
1060                 else if (item->flags & AP_ERRORLOG_FLAG_NULL_AS_HYPHEN) {
1061                     buf[len++] = '-';
1062                 }
1063                 else {
1064                     len = field_start;
1065                     skipping = 1;
1066                 }
1067             }
1068             else {
1069                 len += item_len;
1070             }
1071         }
1072     }
1073     return len;
1074 }
1075
1076 static void write_logline(char *errstr, apr_size_t len, apr_file_t *logf,
1077                           int level)
1078 {
1079     /* NULL if we are logging to syslog */
1080     if (logf) {
1081         /* Truncate for the terminator (as apr_snprintf does) */
1082         if (len > MAX_STRING_LEN - sizeof(APR_EOL_STR)) {
1083             len = MAX_STRING_LEN - sizeof(APR_EOL_STR);
1084         }
1085         strcpy(errstr + len, APR_EOL_STR);
1086         apr_file_puts(errstr, logf);
1087         apr_file_flush(logf);
1088     }
1089 #ifdef HAVE_SYSLOG
1090     else {
1091         syslog(level < LOG_PRIMASK ? level : APLOG_DEBUG, "%.*s",
1092                (int)len, errstr);
1093     }
1094 #endif
1095 }
1096
1097 static void log_error_core(const char *file, int line, int module_index,
1098                            int level,
1099                            apr_status_t status, const server_rec *s,
1100                            const conn_rec *c,
1101                            const request_rec *r, apr_pool_t *pool,
1102                            const char *fmt, va_list args)
1103 {
1104     char errstr[MAX_STRING_LEN];
1105     apr_file_t *logf = NULL;
1106     int level_and_mask = level & APLOG_LEVELMASK;
1107     const request_rec *rmain = NULL;
1108     core_server_config *sconf = NULL;
1109     ap_errorlog_info info;
1110
1111     /* do we need to log once-per-req or once-per-conn info? */
1112     int log_conn_info = 0, log_req_info = 0;
1113     apr_array_header_t **lines = NULL;
1114     int done = 0;
1115     int line_number = 0;
1116
1117     if (r) {
1118         AP_DEBUG_ASSERT(r->connection != NULL);
1119         c = r->connection;
1120     }
1121
1122     if (s == NULL) {
1123         /*
1124          * If we are doing stderr logging (startup), don't log messages that are
1125          * above the default server log level unless it is a startup/shutdown
1126          * notice
1127          */
1128 #ifndef DEBUG
1129         if ((level_and_mask != APLOG_NOTICE)
1130             && (level_and_mask > ap_default_loglevel)) {
1131             return;
1132         }
1133 #endif
1134
1135         logf = stderr_log;
1136     }
1137     else {
1138         int configured_level = r ? ap_get_request_module_loglevel(r, module_index)        :
1139                                c ? ap_get_conn_server_module_loglevel(c, s, module_index) :
1140                                    ap_get_server_module_loglevel(s, module_index);
1141         if (s->error_log) {
1142             /*
1143              * If we are doing normal logging, don't log messages that are
1144              * above the module's log level unless it is a startup/shutdown notice
1145              */
1146             if ((level_and_mask != APLOG_NOTICE)
1147                 && (level_and_mask > configured_level)) {
1148                 return;
1149             }
1150
1151             logf = s->error_log;
1152         }
1153         else {
1154             /*
1155              * If we are doing syslog logging, don't log messages that are
1156              * above the module's log level (including a startup/shutdown notice)
1157              */
1158             if (level_and_mask > configured_level) {
1159                 return;
1160             }
1161         }
1162
1163         /* the faked server_rec from mod_cgid does not have s->module_config */
1164         if (s->module_config) {
1165             sconf = ap_get_core_module_config(s->module_config);
1166             if (c && !c->log_id) {
1167                 add_log_id(c, NULL);
1168                 if (sconf->error_log_conn && sconf->error_log_conn->nelts > 0)
1169                     log_conn_info = 1;
1170             }
1171             if (r) {
1172                 if (r->main)
1173                     rmain = r->main;
1174                 else
1175                     rmain = r;
1176
1177                 if (!rmain->log_id) {
1178                     /* XXX: do we need separate log ids for subrequests? */
1179                     if (sconf->error_log_req && sconf->error_log_req->nelts > 0)
1180                         log_req_info = 1;
1181                     /*
1182                      * XXX: potential optimization: only create log id if %L is
1183                      * XXX: actually used
1184                      */
1185                     add_log_id(c, rmain);
1186                 }
1187             }
1188         }
1189     }
1190
1191     info.s             = s;
1192     info.c             = c;
1193     info.pool          = pool;
1194     info.file          = NULL;
1195     info.line          = 0;
1196     info.status        = 0;
1197     info.using_syslog  = (logf == NULL);
1198     info.startup       = ((level & APLOG_STARTUP) == APLOG_STARTUP);
1199     info.format        = fmt;
1200
1201     while (!done) {
1202         apr_array_header_t *log_format;
1203         int len = 0, errstr_start = 0, errstr_end = 0;
1204         /* XXX: potential optimization: format common prefixes only once */
1205         if (log_conn_info) {
1206             /* once-per-connection info */
1207             if (line_number == 0) {
1208                 lines = (apr_array_header_t **)sconf->error_log_conn->elts;
1209                 info.r = NULL;
1210                 info.rmain = NULL;
1211                 info.level = -1;
1212                 info.module_index = APLOG_NO_MODULE;
1213             }
1214
1215             log_format = lines[line_number++];
1216
1217             if (line_number == sconf->error_log_conn->nelts) {
1218                 /* this is the last line of once-per-connection info */
1219                 line_number = 0;
1220                 log_conn_info = 0;
1221             }
1222         }
1223         else if (log_req_info) {
1224             /* once-per-request info */
1225             if (line_number == 0) {
1226                 lines = (apr_array_header_t **)sconf->error_log_req->elts;
1227                 info.r = rmain;
1228                 info.rmain = rmain;
1229                 info.level = -1;
1230                 info.module_index = APLOG_NO_MODULE;
1231             }
1232
1233             log_format = lines[line_number++];
1234
1235             if (line_number == sconf->error_log_req->nelts) {
1236                 /* this is the last line of once-per-request info */
1237                 line_number = 0;
1238                 log_req_info = 0;
1239             }
1240         }
1241         else {
1242             /* the actual error message */
1243             info.r            = r;
1244             info.rmain        = rmain;
1245             info.level        = level_and_mask;
1246             info.module_index = module_index;
1247             info.file         = file;
1248             info.line         = line;
1249             info.status       = status;
1250             log_format = sconf ? sconf->error_log_format : NULL;
1251             done = 1;
1252         }
1253
1254         /*
1255          * prepare and log one line
1256          */
1257
1258         if (log_format) {
1259             len += do_errorlog_format(log_format, &info, errstr + len,
1260                                       MAX_STRING_LEN - len,
1261                                       &errstr_start, &errstr_end, fmt, args);
1262         }
1263         else {
1264             len += do_errorlog_default(&info, errstr + len, MAX_STRING_LEN - len,
1265                                        &errstr_start, &errstr_end, fmt, args);
1266         }
1267
1268         if (!*errstr) {
1269             /*
1270              * Don't log empty lines. This can happen with once-per-conn/req
1271              * info if an item with AP_ERRORLOG_FLAG_REQUIRED is NULL.
1272              */
1273             continue;
1274         }
1275         write_logline(errstr, len, logf, level_and_mask);
1276
1277         if (done) {
1278             /*
1279              * We don't call the error_log hook for per-request/per-conn
1280              * lines, and we only pass the actual log message, not the
1281              * prefix and suffix.
1282              */
1283             errstr[errstr_end] = '\0';
1284             ap_run_error_log(&info, errstr + errstr_start);
1285         }
1286
1287         *errstr = '\0';
1288     }
1289 }
1290
1291 AP_DECLARE(void) ap_log_error_(const char *file, int line, int module_index,
1292                                int level, apr_status_t status,
1293                                const server_rec *s, const char *fmt, ...)
1294 {
1295     va_list args;
1296
1297     va_start(args, fmt);
1298     log_error_core(file, line, module_index, level, status, s, NULL, NULL,
1299                    NULL, fmt, args);
1300     va_end(args);
1301 }
1302
1303 AP_DECLARE(void) ap_log_perror_(const char *file, int line, int module_index,
1304                                 int level, apr_status_t status, apr_pool_t *p,
1305                                 const char *fmt, ...)
1306 {
1307     va_list args;
1308
1309     va_start(args, fmt);
1310     log_error_core(file, line, module_index, level, status, NULL, NULL, NULL,
1311                    p, fmt, args);
1312     va_end(args);
1313 }
1314
1315 AP_DECLARE(void) ap_log_rerror_(const char *file, int line, int module_index,
1316                                 int level, apr_status_t status,
1317                                 const request_rec *r, const char *fmt, ...)
1318 {
1319     va_list args;
1320
1321     va_start(args, fmt);
1322     log_error_core(file, line, module_index, level, status, r->server, NULL, r,
1323                    NULL, fmt, args);
1324
1325     /*
1326      * IF APLOG_TOCLIENT is set,
1327      * AND the error level is 'warning' or more severe,
1328      * AND there isn't already error text associated with this request,
1329      * THEN make the message text available to ErrorDocument and
1330      * other error processors.
1331      */
1332     va_end(args);
1333     va_start(args,fmt);
1334     if ((level & APLOG_TOCLIENT)
1335         && ((level & APLOG_LEVELMASK) <= APLOG_WARNING)
1336         && (apr_table_get(r->notes, "error-notes") == NULL)) {
1337         apr_table_setn(r->notes, "error-notes",
1338                        ap_escape_html(r->pool, apr_pvsprintf(r->pool, fmt,
1339                                                              args)));
1340     }
1341     va_end(args);
1342 }
1343
1344 AP_DECLARE(void) ap_log_cserror_(const char *file, int line, int module_index,
1345                                  int level, apr_status_t status,
1346                                  const conn_rec *c, const server_rec *s,
1347                                  const char *fmt, ...)
1348 {
1349     va_list args;
1350
1351     va_start(args, fmt);
1352     log_error_core(file, line, module_index, level, status, s, c,
1353                    NULL, NULL, fmt, args);
1354     va_end(args);
1355 }
1356
1357 AP_DECLARE(void) ap_log_cerror_(const char *file, int line, int module_index,
1358                                 int level, apr_status_t status,
1359                                 const conn_rec *c, const char *fmt, ...)
1360 {
1361     va_list args;
1362
1363     va_start(args, fmt);
1364     log_error_core(file, line, module_index, level, status, c->base_server, c,
1365                    NULL, NULL, fmt, args);
1366     va_end(args);
1367 }
1368
1369 AP_DECLARE(void) ap_log_command_line(apr_pool_t *plog, server_rec *s)
1370 {
1371     int i;
1372     process_rec *process = s->process;
1373     char *result;
1374     int len_needed = 0;
1375
1376     /* Piece together the command line from the pieces
1377      * in process->argv, with spaces in between.
1378      */
1379     for (i = 0; i < process->argc; i++) {
1380         len_needed += strlen(process->argv[i]) + 1;
1381     }
1382
1383     result = (char *) apr_palloc(plog, len_needed);
1384     *result = '\0';
1385
1386     for (i = 0; i < process->argc; i++) {
1387         strcat(result, process->argv[i]);
1388         if ((i+1)< process->argc) {
1389             strcat(result, " ");
1390         }
1391     }
1392     ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, s, APLOGNO(00094)
1393                  "Command line: '%s'", result);
1394 }
1395
1396 AP_DECLARE(void) ap_remove_pid(apr_pool_t *p, const char *rel_fname)
1397 {
1398     apr_status_t rv;
1399     const char *fname = ap_server_root_relative(p, rel_fname);
1400
1401     if (fname != NULL) {
1402         rv = apr_file_remove(fname, p);
1403         if (rv != APR_SUCCESS) {
1404             ap_log_error(APLOG_MARK, APLOG_ERR, rv, ap_server_conf, APLOGNO(00095)
1405                          "failed to remove PID file %s", fname);
1406         }
1407         else {
1408             ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf, APLOGNO(00096)
1409                          "removed PID file %s (pid=%" APR_PID_T_FMT ")",
1410                          fname, getpid());
1411         }
1412     }
1413 }
1414
1415 AP_DECLARE(void) ap_log_pid(apr_pool_t *p, const char *filename)
1416 {
1417     apr_file_t *pid_file = NULL;
1418     apr_finfo_t finfo;
1419     static pid_t saved_pid = -1;
1420     pid_t mypid;
1421     apr_status_t rv;
1422     const char *fname;
1423
1424     if (!filename) {
1425         return;
1426     }
1427
1428     fname = ap_server_root_relative(p, filename);
1429     if (!fname) {
1430         ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_CRIT, APR_EBADPATH,
1431                      NULL, APLOGNO(00097) "Invalid PID file path %s, ignoring.", filename);
1432         return;
1433     }
1434
1435     mypid = getpid();
1436     if (mypid != saved_pid
1437         && apr_stat(&finfo, fname, APR_FINFO_MTIME, p) == APR_SUCCESS) {
1438         /* AP_SIG_GRACEFUL and HUP call this on each restart.
1439          * Only warn on first time through for this pid.
1440          *
1441          * XXX: Could just write first time through too, although
1442          *      that may screw up scripts written to do something
1443          *      based on the last modification time of the pid file.
1444          */
1445         ap_log_perror(APLOG_MARK, APLOG_WARNING, 0, p, APLOGNO(00098)
1446                       "pid file %s overwritten -- Unclean "
1447                       "shutdown of previous Apache run?",
1448                       fname);
1449     }
1450
1451     if ((rv = apr_file_open(&pid_file, fname,
1452                             APR_WRITE | APR_CREATE | APR_TRUNCATE,
1453                             APR_UREAD | APR_UWRITE | APR_GREAD | APR_WREAD, p))
1454         != APR_SUCCESS) {
1455         ap_log_error(APLOG_MARK, APLOG_ERR, rv, NULL, APLOGNO(00099)
1456                      "could not create %s", fname);
1457         ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL, APLOGNO(00100)
1458                      "%s: could not log pid to file %s",
1459                      ap_server_argv0, fname);
1460         exit(1);
1461     }
1462     apr_file_printf(pid_file, "%" APR_PID_T_FMT APR_EOL_STR, mypid);
1463     apr_file_close(pid_file);
1464     saved_pid = mypid;
1465 }
1466
1467 AP_DECLARE(apr_status_t) ap_read_pid(apr_pool_t *p, const char *filename,
1468                                      pid_t *mypid)
1469 {
1470     const apr_size_t BUFFER_SIZE = sizeof(long) * 3 + 2; /* see apr_ltoa */
1471     apr_file_t *pid_file = NULL;
1472     apr_status_t rv;
1473     const char *fname;
1474     char *buf, *endptr;
1475     apr_size_t bytes_read;
1476
1477     if (!filename) {
1478         return APR_EGENERAL;
1479     }
1480
1481     fname = ap_server_root_relative(p, filename);
1482     if (!fname) {
1483         ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_CRIT, APR_EBADPATH,
1484                      NULL, APLOGNO(00101) "Invalid PID file path %s, ignoring.", filename);
1485         return APR_EGENERAL;
1486     }
1487
1488     rv = apr_file_open(&pid_file, fname, APR_READ, APR_OS_DEFAULT, p);
1489     if (rv != APR_SUCCESS) {
1490         return rv;
1491     }
1492
1493     buf = apr_palloc(p, BUFFER_SIZE);
1494
1495     rv = apr_file_read_full(pid_file, buf, BUFFER_SIZE - 1, &bytes_read);
1496     if (rv != APR_SUCCESS && rv != APR_EOF) {
1497         return rv;
1498     }
1499
1500     /* If we fill the buffer, we're probably reading a corrupt pid file.
1501      * To be nice, let's also ensure the first char is a digit. */
1502     if (bytes_read == 0 || bytes_read == BUFFER_SIZE - 1 || !apr_isdigit(*buf)) {
1503         return APR_EGENERAL;
1504     }
1505
1506     buf[bytes_read] = '\0';
1507     *mypid = strtol(buf, &endptr, 10);
1508
1509     apr_file_close(pid_file);
1510     return APR_SUCCESS;
1511 }
1512
1513 AP_DECLARE(void) ap_log_assert(const char *szExp, const char *szFile,
1514                                int nLine)
1515 {
1516     char time_str[APR_CTIME_LEN];
1517
1518     apr_ctime(time_str, apr_time_now());
1519     ap_log_error(APLOG_MARK, APLOG_CRIT, 0, NULL, APLOGNO(00102)
1520                  "[%s] file %s, line %d, assertion \"%s\" failed",
1521                  time_str, szFile, nLine, szExp);
1522 #if defined(WIN32)
1523     DebugBreak();
1524 #else
1525     /* unix assert does an abort leading to a core dump */
1526     abort();
1527 #endif
1528 }
1529
1530 /* piped log support */
1531
1532 #ifdef AP_HAVE_RELIABLE_PIPED_LOGS
1533 /* forward declaration */
1534 static void piped_log_maintenance(int reason, void *data, apr_wait_t status);
1535
1536 /* Spawn the piped logger process pl->program. */
1537 static apr_status_t piped_log_spawn(piped_log *pl)
1538 {
1539     apr_procattr_t *procattr;
1540     apr_proc_t *procnew = NULL;
1541     apr_status_t status;
1542
1543     if (((status = apr_procattr_create(&procattr, pl->p)) != APR_SUCCESS) ||
1544         ((status = apr_procattr_dir_set(procattr, ap_server_root))
1545          != APR_SUCCESS) ||
1546         ((status = apr_procattr_cmdtype_set(procattr, pl->cmdtype))
1547          != APR_SUCCESS) ||
1548         ((status = apr_procattr_child_in_set(procattr,
1549                                              pl->read_fd,
1550                                              pl->write_fd))
1551          != APR_SUCCESS) ||
1552         ((status = apr_procattr_child_errfn_set(procattr, log_child_errfn))
1553          != APR_SUCCESS) ||
1554         ((status = apr_procattr_error_check_set(procattr, 1)) != APR_SUCCESS)) {
1555         char buf[120];
1556         /* Something bad happened, give up and go away. */
1557         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, APLOGNO(00103)
1558                      "piped_log_spawn: unable to setup child process '%s': %s",
1559                      pl->program, apr_strerror(status, buf, sizeof(buf)));
1560     }
1561     else {
1562         char **args;
1563         const char *pname;
1564
1565         apr_tokenize_to_argv(pl->program, &args, pl->p);
1566         pname = apr_pstrdup(pl->p, args[0]);
1567         procnew = apr_pcalloc(pl->p, sizeof(apr_proc_t));
1568         status = apr_proc_create(procnew, pname, (const char * const *) args,
1569                                  NULL, procattr, pl->p);
1570
1571         if (status == APR_SUCCESS) {
1572             pl->pid = procnew;
1573             /* procnew->in was dup2'd from pl->write_fd;
1574              * since the original fd is still valid, close the copy to
1575              * avoid a leak. */
1576             apr_file_close(procnew->in);
1577             procnew->in = NULL;
1578             apr_proc_other_child_register(procnew, piped_log_maintenance, pl,
1579                                           pl->write_fd, pl->p);
1580             close_handle_in_child(pl->p, pl->read_fd);
1581         }
1582         else {
1583             char buf[120];
1584             /* Something bad happened, give up and go away. */
1585             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, APLOGNO(00104)
1586                          "unable to start piped log program '%s': %s",
1587                          pl->program, apr_strerror(status, buf, sizeof(buf)));
1588         }
1589     }
1590
1591     return status;
1592 }
1593
1594
1595 static void piped_log_maintenance(int reason, void *data, apr_wait_t status)
1596 {
1597     piped_log *pl = data;
1598     apr_status_t stats;
1599     int mpm_state;
1600
1601     switch (reason) {
1602     case APR_OC_REASON_DEATH:
1603     case APR_OC_REASON_LOST:
1604         pl->pid = NULL; /* in case we don't get it going again, this
1605                          * tells other logic not to try to kill it
1606                          */
1607         apr_proc_other_child_unregister(pl);
1608         stats = ap_mpm_query(AP_MPMQ_MPM_STATE, &mpm_state);
1609         if (stats != APR_SUCCESS) {
1610             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, APLOGNO(00105)
1611                          "can't query MPM state; not restarting "
1612                          "piped log program '%s'",
1613                          pl->program);
1614         }
1615         else if (mpm_state != AP_MPMQ_STOPPING) {
1616             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, APLOGNO(00106)
1617                          "piped log program '%s' failed unexpectedly",
1618                          pl->program);
1619             if ((stats = piped_log_spawn(pl)) != APR_SUCCESS) {
1620                 /* what can we do?  This could be the error log we're having
1621                  * problems opening up... */
1622                 char buf[120];
1623                 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, APLOGNO(00107)
1624                              "piped_log_maintenance: unable to respawn '%s': %s",
1625                              pl->program, apr_strerror(stats, buf, sizeof(buf)));
1626             }
1627         }
1628         break;
1629
1630     case APR_OC_REASON_UNWRITABLE:
1631         /* We should not kill off the pipe here, since it may only be full.
1632          * If it really is locked, we should kill it off manually. */
1633     break;
1634
1635     case APR_OC_REASON_RESTART:
1636         if (pl->pid != NULL) {
1637             apr_proc_kill(pl->pid, SIGTERM);
1638             pl->pid = NULL;
1639         }
1640         break;
1641
1642     case APR_OC_REASON_UNREGISTER:
1643         break;
1644     }
1645 }
1646
1647
1648 static apr_status_t piped_log_cleanup_for_exec(void *data)
1649 {
1650     piped_log *pl = data;
1651
1652     apr_file_close(pl->read_fd);
1653     apr_file_close(pl->write_fd);
1654     return APR_SUCCESS;
1655 }
1656
1657
1658 static apr_status_t piped_log_cleanup(void *data)
1659 {
1660     piped_log *pl = data;
1661
1662     if (pl->pid != NULL) {
1663         apr_proc_kill(pl->pid, SIGTERM);
1664     }
1665     return piped_log_cleanup_for_exec(data);
1666 }
1667
1668
1669 AP_DECLARE(piped_log *) ap_open_piped_log_ex(apr_pool_t *p,
1670                                              const char *program,
1671                                              apr_cmdtype_e cmdtype)
1672 {
1673     piped_log *pl;
1674
1675     pl = apr_palloc(p, sizeof (*pl));
1676     pl->p = p;
1677     pl->program = apr_pstrdup(p, program);
1678     pl->pid = NULL;
1679     pl->cmdtype = cmdtype;
1680     if (apr_file_pipe_create_ex(&pl->read_fd,
1681                                 &pl->write_fd,
1682                                 APR_FULL_BLOCK, p) != APR_SUCCESS) {
1683         return NULL;
1684     }
1685     apr_pool_cleanup_register(p, pl, piped_log_cleanup,
1686                               piped_log_cleanup_for_exec);
1687     if (piped_log_spawn(pl) != APR_SUCCESS) {
1688         apr_pool_cleanup_kill(p, pl, piped_log_cleanup);
1689         apr_file_close(pl->read_fd);
1690         apr_file_close(pl->write_fd);
1691         return NULL;
1692     }
1693     return pl;
1694 }
1695
1696 #else /* !AP_HAVE_RELIABLE_PIPED_LOGS */
1697
1698 static apr_status_t piped_log_cleanup(void *data)
1699 {
1700     piped_log *pl = data;
1701
1702     apr_file_close(pl->write_fd);
1703     return APR_SUCCESS;
1704 }
1705
1706 AP_DECLARE(piped_log *) ap_open_piped_log_ex(apr_pool_t *p,
1707                                              const char *program,
1708                                              apr_cmdtype_e cmdtype)
1709 {
1710     piped_log *pl;
1711     apr_file_t *dummy = NULL;
1712     int rc;
1713
1714     rc = log_child(p, program, &dummy, cmdtype, 0);
1715     if (rc != APR_SUCCESS) {
1716         ap_log_error(APLOG_MARK, APLOG_STARTUP, rc, NULL, APLOGNO(00108)
1717                      "Couldn't start piped log process '%s'.",
1718                      (program == NULL) ? "NULL" : program);
1719         return NULL;
1720     }
1721
1722     pl = apr_palloc(p, sizeof (*pl));
1723     pl->p = p;
1724     pl->read_fd = NULL;
1725     pl->write_fd = dummy;
1726     apr_pool_cleanup_register(p, pl, piped_log_cleanup, piped_log_cleanup);
1727
1728     return pl;
1729 }
1730
1731 #endif
1732
1733 AP_DECLARE(piped_log *) ap_open_piped_log(apr_pool_t *p,
1734                                           const char *program)
1735 {
1736     apr_cmdtype_e cmdtype = APR_PROGRAM_ENV;
1737
1738     /* In 2.4 favor PROGRAM_ENV, accept "||prog" syntax for compatibility
1739      * and "|$cmd" to override the default.
1740      * Any 2.2 backport would continue to favor SHELLCMD_ENV so there
1741      * accept "||prog" to override, and "|$cmd" to ease conversion.
1742      */
1743     if (*program == '|')
1744         ++program;
1745     if (*program == '$') {
1746         cmdtype = APR_SHELLCMD_ENV;
1747         ++program;
1748     }
1749
1750     return ap_open_piped_log_ex(p, program, cmdtype);
1751 }
1752
1753 AP_DECLARE(void) ap_close_piped_log(piped_log *pl)
1754 {
1755     apr_pool_cleanup_run(pl->p, pl, piped_log_cleanup);
1756 }
1757
1758 AP_DECLARE(const char *) ap_parse_log_level(const char *str, int *val)
1759 {
1760     char *err = "Log level keyword must be one of emerg/alert/crit/error/warn/"
1761                 "notice/info/debug/trace1/.../trace8";
1762     int i = 0;
1763
1764     if (str == NULL)
1765         return err;
1766
1767     while (priorities[i].t_name != NULL) {
1768         if (!strcasecmp(str, priorities[i].t_name)) {
1769             *val = priorities[i].t_val;
1770             return NULL;
1771         }
1772         i++;
1773     }
1774     return err;
1775 }
1776
1777 AP_IMPLEMENT_HOOK_VOID(error_log,
1778                        (const ap_errorlog_info *info, const char *errstr),
1779                        (info, errstr))
1780
1781 AP_IMPLEMENT_HOOK_RUN_FIRST(int, generate_log_id,
1782                             (const conn_rec *c, const request_rec *r,
1783                              const char **id),
1784                             (c, r, id), DECLINED)