]> granicus.if.org Git - apache/blob - modules/loggers/mod_log_config.c
Further clarify the naming of the entity that originates the request by
[apache] / modules / loggers / mod_log_config.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  * Modified by djm@va.pubnix.com:
19  * If no TransferLog is given explicitly, decline to log.
20  *
21  * This is module implements the TransferLog directive (same as the
22  * common log module), and additional directives, LogFormat and CustomLog.
23  *
24  *
25  * Syntax:
26  *
27  *    TransferLog fn      Logs transfers to fn in standard log format, unless
28  *                        a custom format is set with LogFormat
29  *    LogFormat format    Set a log format from TransferLog files
30  *    CustomLog fn format
31  *                        Log to file fn with format given by the format
32  *                        argument
33  *
34  * There can be any number of TransferLog and CustomLog
35  * commands. Each request will be logged to _ALL_ the
36  * named files, in the appropriate format.
37  *
38  * If no TransferLog or CustomLog directive appears in a VirtualHost,
39  * the request will be logged to the log file(s) defined outside
40  * the virtual host section. If a TransferLog or CustomLog directive
41  * appears in the VirtualHost section, the log files defined outside
42  * the VirtualHost will _not_ be used. This makes this module compatable
43  * with the CLF and config log modules, where the use of TransferLog
44  * inside the VirtualHost section overrides its use outside.
45  *
46  * Examples:
47  *
48  *    TransferLog    logs/access_log
49  *    <VirtualHost>
50  *    LogFormat      "... custom format ..."
51  *    TransferLog    log/virtual_only
52  *    CustomLog      log/virtual_useragents "%t %{user-agent}i"
53  *    </VirtualHost>
54  *
55  * This will log using CLF to access_log any requests handled by the
56  * main server, while any requests to the virtual host will be logged
57  * with the "... custom format..." to virtual_only _AND_ using
58  * the custom user-agent log to virtual_useragents.
59  *
60  * Note that the NCSA referer and user-agent logs are easily added with
61  * CustomLog:
62  *   CustomLog   logs/referer  "%{referer}i -> %U"
63  *   CustomLog   logs/agent    "%{user-agent}i"
64  *
65  * RefererIgnore functionality can be obtained with conditional
66  * logging (SetEnvIf and CustomLog ... env=!VAR).
67  *
68  * But using this method allows much easier modification of the
69  * log format, e.g. to log hosts along with UA:
70  *   CustomLog   logs/referer "%{referer}i %U %h"
71  *
72  * The argument to LogFormat and CustomLog is a string, which can include
73  * literal characters copied into the log files, and '%' directives as
74  * follows:
75  *
76  * %...B:  bytes sent, excluding HTTP headers.
77  * %...b:  bytes sent, excluding HTTP headers in CLF format, i.e. a '-'
78  *         when no bytes where sent (rather than a '0'.
79  * %...{FOOBAR}C:  The contents of the HTTP cookie FOOBAR
80  * %...{FOOBAR}e:  The contents of the environment variable FOOBAR
81  * %...f:  filename
82  * %...h:  remote host
83  * %...a:  remote IP-address
84  * %...A:  local IP-address
85  * %...{Foobar}i:  The contents of Foobar: header line(s) in the request
86  *                 sent to the client.
87  * %...k:  number of keepalive requests served over this connection
88  * %...l:  remote logname (from identd, if supplied)
89  * %...{Foobar}n:  The contents of note "Foobar" from another module.
90  * %...{Foobar}o:  The contents of Foobar: header line(s) in the reply.
91  * %...p:  the canonical port for the server
92  * %...{format}p: the canonical port for the server, or the actual local
93  *                or remote port
94  * %...P:  the process ID of the child that serviced the request.
95  * %...{format}P: the process ID or thread ID of the child/thread that
96  *                serviced the request
97  * %...r:  first line of request
98  * %...s:  status.  For requests that got internally redirected, this
99  *         is status of the *original* request --- %...>s for the last.
100  * %...t:  time, in common log format time format
101  * %...{format}t:  The time, in the form given by format, which should
102  *                 be in strftime(3) format.
103  * %...T:  the time taken to serve the request, in seconds.
104  * %...D:  the time taken to serve the request, in micro seconds.
105  * %...u:  remote user (from auth; may be bogus if return status (%s) is 401)
106  * %...U:  the URL path requested.
107  * %...v:  the configured name of the server (i.e. which virtual host?)
108  * %...V:  the server name according to the UseCanonicalName setting
109  * %...m:  the request method
110  * %...H:  the request protocol
111  * %...q:  the query string prepended by "?", or empty if no query string
112  * %...X:  Status of the connection.
113  *         'X' = connection aborted before the response completed.
114  *         '+' = connection may be kept alive after the response is sent.
115  *         '-' = connection will be closed after the response is sent.
116  *         (This directive was %...c in late versions of Apache 1.3, but
117  *          this conflicted with the historical ssl %...{var}c syntax.)
118  * %...L:  Log-Id of the Request (or '-' if none)
119  * %...{c}L:  Log-Id of the Connection (or '-' if none)
120  *
121  * The '...' can be nothing at all (e.g. "%h %u %r %s %b"), or it can
122  * indicate conditions for inclusion of the item (which will cause it
123  * to be replaced with '-' if the condition is not met).  Note that
124  * there is no escaping performed on the strings from %r, %...i and
125  * %...o; some with long memories may remember that I thought this was
126  * a bad idea, once upon a time, and I'm still not comfortable with
127  * it, but it is difficult to see how to "do the right thing" with all
128  * of '%..i', unless we URL-escape everything and break with CLF.
129  *
130  * The forms of condition are a list of HTTP status codes, which may
131  * or may not be preceded by '!'.  Thus, '%400,501{User-agent}i' logs
132  * User-agent: on 400 errors and 501 errors (Bad Request, Not
133  * Implemented) only; '%!200,304,302{Referer}i' logs Referer: on all
134  * requests which did *not* return some sort of normal status.
135  *
136  * The default LogFormat reproduces CLF; see below.
137  *
138  * The way this is supposed to work with virtual hosts is as follows:
139  * a virtual host can have its own LogFormat, or its own TransferLog.
140  * If it doesn't have its own LogFormat, it inherits from the main
141  * server.  If it doesn't have its own TransferLog, it writes to the
142  * same descriptor (meaning the same process for "| ...").
143  *
144  * --- rst */
145
146 #include "apr_strings.h"
147 #include "apr_lib.h"
148 #include "apr_hash.h"
149 #include "apr_optional.h"
150 #include "apr_anylock.h"
151
152 #define APR_WANT_STRFUNC
153 #include "apr_want.h"
154
155 #include "ap_config.h"
156 #include "mod_log_config.h"
157 #include "httpd.h"
158 #include "http_config.h"
159 #include "http_core.h"          /* For REMOTE_NAME */
160 #include "http_log.h"
161 #include "http_protocol.h"
162 #include "util_time.h"
163 #include "ap_mpm.h"
164
165 #if APR_HAVE_UNISTD_H
166 #include <unistd.h>
167 #endif
168 #ifdef HAVE_LIMITS_H
169 #include <limits.h>
170 #endif
171
172 #define DEFAULT_LOG_FORMAT "%h %l %u %t \"%r\" %>s %b"
173
174 module AP_MODULE_DECLARE_DATA log_config_module;
175
176
177 static int xfer_flags = (APR_WRITE | APR_APPEND | APR_CREATE | APR_LARGEFILE);
178 static apr_fileperms_t xfer_perms = APR_OS_DEFAULT;
179 static apr_hash_t *log_hash;
180 static apr_status_t ap_default_log_writer(request_rec *r,
181                            void *handle,
182                            const char **strs,
183                            int *strl,
184                            int nelts,
185                            apr_size_t len);
186 static apr_status_t ap_buffered_log_writer(request_rec *r,
187                            void *handle,
188                            const char **strs,
189                            int *strl,
190                            int nelts,
191                            apr_size_t len);
192 static void *ap_default_log_writer_init(apr_pool_t *p, server_rec *s,
193                                         const char* name);
194 static void *ap_buffered_log_writer_init(apr_pool_t *p, server_rec *s,
195                                         const char* name);
196
197 static ap_log_writer_init* ap_log_set_writer_init(ap_log_writer_init *handle);
198 static ap_log_writer* ap_log_set_writer(ap_log_writer *handle);
199 static ap_log_writer *log_writer = ap_default_log_writer;
200 static ap_log_writer_init *log_writer_init = ap_default_log_writer_init;
201 static int buffered_logs = 0; /* default unbuffered */
202 static apr_array_header_t *all_buffered_logs = NULL;
203
204 /* POSIX.1 defines PIPE_BUF as the maximum number of bytes that is
205  * guaranteed to be atomic when writing a pipe.  And PIPE_BUF >= 512
206  * is guaranteed.  So we'll just guess 512 in the event the system
207  * doesn't have this.  Now, for file writes there is actually no limit,
208  * the entire write is atomic.  Whether all systems implement this
209  * correctly is another question entirely ... so we'll just use PIPE_BUF
210  * because it's probably a good guess as to what is implemented correctly
211  * everywhere.
212  */
213 #ifdef PIPE_BUF
214 #define LOG_BUFSIZE     PIPE_BUF
215 #else
216 #define LOG_BUFSIZE     (512)
217 #endif
218
219 /*
220  * multi_log_state is our per-(virtual)-server configuration. We store
221  * an array of the logs we are going to use, each of type config_log_state.
222  * If a default log format is given by LogFormat, store in default_format
223  * (backward compat. with mod_log_config).  We also store for each virtual
224  * server a pointer to the logs specified for the main server, so that if this
225  * vhost has no logs defined, we can use the main server's logs instead.
226  *
227  * So, for the main server, config_logs contains a list of the log files
228  * and server_config_logs is empty. For a vhost, server_config_logs
229  * points to the same array as config_logs in the main server, and
230  * config_logs points to the array of logs defined inside this vhost,
231  * which might be empty.
232  */
233
234 typedef struct {
235     const char *default_format_string;
236     apr_array_header_t *default_format;
237     apr_array_header_t *config_logs;
238     apr_array_header_t *server_config_logs;
239     apr_table_t *formats;
240 } multi_log_state;
241
242 /*
243  * config_log_state holds the status of a single log file. fname might
244  * be NULL, which means this module does no logging for this
245  * request. format might be NULL, in which case the default_format
246  * from the multi_log_state should be used, or if that is NULL as
247  * well, use the CLF.
248  * log_writer is NULL before the log file is opened and is
249  * set to a opaque structure (usually a fd) after it is opened.
250
251  */
252 typedef struct {
253     apr_file_t *handle;
254     apr_size_t outcnt;
255     char outbuf[LOG_BUFSIZE];
256     apr_anylock_t mutex;
257 } buffered_log;
258
259 typedef struct {
260     const char *fname;
261     const char *format_string;
262     apr_array_header_t *format;
263     void *log_writer;
264     char *condition_var;
265     ap_expr_info_t *condition_expr;
266 } config_log_state;
267
268 /*
269  * log_request_state holds request specific log data that is not
270  * part of the request_rec.
271  */
272 typedef struct {
273     apr_time_t request_end_time;
274 } log_request_state;
275
276 /*
277  * Format items...
278  * Note that many of these could have ap_sprintfs replaced with static buffers.
279  */
280
281 typedef struct {
282     ap_log_handler_fn_t *func;
283     char *arg;
284     int condition_sense;
285     int want_orig;
286     apr_array_header_t *conditions;
287 } log_format_item;
288
289 static char *pfmt(apr_pool_t *p, int i)
290 {
291     if (i <= 0) {
292         return "-";
293     }
294     else {
295         return apr_itoa(p, i);
296     }
297 }
298
299 static const char *constant_item(request_rec *dummy, char *stuff)
300 {
301     return stuff;
302 }
303
304 static const char *log_remote_host(request_rec *r, char *a)
305 {
306     return ap_escape_logitem(r->pool, ap_get_remote_host(r->connection,
307                                                          r->per_dir_config,
308                                                          REMOTE_NAME, NULL));
309 }
310
311 static const char *log_remote_address(request_rec *r, char *a)
312 {
313     if (a && !strcmp(a, "c")) {
314         return r->connection->peer_ip;
315     }
316     else {
317         return r->useragent_ip;
318     }
319 }
320
321 static const char *log_local_address(request_rec *r, char *a)
322 {
323     return r->connection->local_ip;
324 }
325
326 static const char *log_remote_logname(request_rec *r, char *a)
327 {
328     return ap_escape_logitem(r->pool, ap_get_remote_logname(r));
329 }
330
331 static const char *log_remote_user(request_rec *r, char *a)
332 {
333     char *rvalue = r->user;
334
335     if (rvalue == NULL) {
336         rvalue = "-";
337     }
338     else if (strlen(rvalue) == 0) {
339         rvalue = "\"\"";
340     }
341     else {
342         rvalue = ap_escape_logitem(r->pool, rvalue);
343     }
344
345     return rvalue;
346 }
347
348 static const char *log_request_line(request_rec *r, char *a)
349 {
350     /* NOTE: If the original request contained a password, we
351      * re-write the request line here to contain XXXXXX instead:
352      * (note the truncation before the protocol string for HTTP/0.9 requests)
353      * (note also that r->the_request contains the unmodified request)
354      */
355     return ap_escape_logitem(r->pool,
356                              (r->parsed_uri.password)
357                                ? apr_pstrcat(r->pool, r->method, " ",
358                                              apr_uri_unparse(r->pool,
359                                                              &r->parsed_uri, 0),
360                                              r->assbackwards ? NULL : " ",
361                                              r->protocol, NULL)
362                                : r->the_request);
363 }
364
365 static const char *log_request_file(request_rec *r, char *a)
366 {
367     return ap_escape_logitem(r->pool, r->filename);
368 }
369 static const char *log_request_uri(request_rec *r, char *a)
370 {
371     return ap_escape_logitem(r->pool, r->uri);
372 }
373 static const char *log_request_method(request_rec *r, char *a)
374 {
375     return ap_escape_logitem(r->pool, r->method);
376 }
377 static const char *log_log_id(request_rec *r, char *a)
378 {
379     if (a && !strcmp(a, "c")) {
380         return r->connection->log_id ? r->connection->log_id : "-";
381     }
382     else {
383         return r->log_id ? r->log_id : "-";
384     }
385 }
386 static const char *log_request_protocol(request_rec *r, char *a)
387 {
388     return ap_escape_logitem(r->pool, r->protocol);
389 }
390 static const char *log_request_query(request_rec *r, char *a)
391 {
392     return (r->args) ? apr_pstrcat(r->pool, "?",
393                                    ap_escape_logitem(r->pool, r->args), NULL)
394                      : "";
395 }
396 static const char *log_status(request_rec *r, char *a)
397 {
398     return pfmt(r->pool, r->status);
399 }
400
401 static const char *log_handler(request_rec *r, char *a)
402 {
403     return ap_escape_logitem(r->pool, r->handler);
404 }
405
406 static const char *clf_log_bytes_sent(request_rec *r, char *a)
407 {
408     if (!r->sent_bodyct || !r->bytes_sent) {
409         return "-";
410     }
411     else {
412         return apr_off_t_toa(r->pool, r->bytes_sent);
413     }
414 }
415
416 static const char *log_bytes_sent(request_rec *r, char *a)
417 {
418     if (!r->sent_bodyct || !r->bytes_sent) {
419         return "0";
420     }
421     else {
422         return apr_off_t_toa(r->pool, r->bytes_sent);
423     }
424 }
425
426
427 static const char *log_header_in(request_rec *r, char *a)
428 {
429     return ap_escape_logitem(r->pool, apr_table_get(r->headers_in, a));
430 }
431
432 static APR_INLINE char *find_multiple_headers(apr_pool_t *pool,
433                                               const apr_table_t *table,
434                                               const char *key)
435 {
436     const apr_array_header_t *elts;
437     const apr_table_entry_t *t_elt;
438     const apr_table_entry_t *t_end;
439     apr_size_t len;
440     struct sle {
441         struct sle *next;
442         const char *value;
443         apr_size_t len;
444     } *result_list, *rp;
445
446     elts = apr_table_elts(table);
447
448     if (!elts->nelts) {
449         return NULL;
450     }
451
452     t_elt = (const apr_table_entry_t *)elts->elts;
453     t_end = t_elt + elts->nelts;
454     len = 1; /* \0 */
455     result_list = rp = NULL;
456
457     do {
458         if (!strcasecmp(t_elt->key, key)) {
459             if (!result_list) {
460                 result_list = rp = apr_palloc(pool, sizeof(*rp));
461             }
462             else {
463                 rp = rp->next = apr_palloc(pool, sizeof(*rp));
464                 len += 2; /* ", " */
465             }
466
467             rp->next = NULL;
468             rp->value = t_elt->val;
469             rp->len = strlen(rp->value);
470
471             len += rp->len;
472         }
473         ++t_elt;
474     } while (t_elt < t_end);
475
476     if (result_list) {
477         char *result = apr_palloc(pool, len);
478         char *cp = result;
479
480         rp = result_list;
481         while (rp) {
482             if (rp != result_list) {
483                 *cp++ = ',';
484                 *cp++ = ' ';
485             }
486             memcpy(cp, rp->value, rp->len);
487             cp += rp->len;
488             rp = rp->next;
489         }
490         *cp = '\0';
491
492         return result;
493     }
494
495     return NULL;
496 }
497
498 static const char *log_header_out(request_rec *r, char *a)
499 {
500     const char *cp = NULL;
501
502     if (!strcasecmp(a, "Content-type") && r->content_type) {
503         cp = ap_field_noparam(r->pool, r->content_type);
504     }
505     else if (!strcasecmp(a, "Set-Cookie")) {
506         cp = find_multiple_headers(r->pool, r->headers_out, a);
507     }
508     else {
509         cp = apr_table_get(r->headers_out, a);
510     }
511
512     return ap_escape_logitem(r->pool, cp);
513 }
514
515 static const char *log_note(request_rec *r, char *a)
516 {
517     return ap_escape_logitem(r->pool, apr_table_get(r->notes, a));
518 }
519 static const char *log_env_var(request_rec *r, char *a)
520 {
521     return ap_escape_logitem(r->pool, apr_table_get(r->subprocess_env, a));
522 }
523
524 static const char *log_cookie(request_rec *r, char *a)
525 {
526     const char *cookies_entry;
527
528     /*
529      * This supports Netscape version 0 cookies while being tolerant to
530      * some properties of RFC2109/2965 version 1 cookies:
531      * - case-insensitive match of cookie names
532      * - white space between the tokens
533      * It does not support the following version 1 features:
534      * - quoted strings as cookie values
535      * - commas to separate cookies
536      */
537
538     if ((cookies_entry = apr_table_get(r->headers_in, "Cookie"))) {
539         char *cookie, *last1, *last2;
540         char *cookies = apr_pstrdup(r->pool, cookies_entry);
541
542         while ((cookie = apr_strtok(cookies, ";", &last1))) {
543             char *name = apr_strtok(cookie, "=", &last2);
544             char *value;
545             apr_collapse_spaces(name, name);
546
547             if (!strcasecmp(name, a) && (value = apr_strtok(NULL, "=", &last2))) {
548                 char *last;
549                 value += strspn(value, " \t");  /* Move past leading WS */
550                 last = value + strlen(value) - 1;
551                 while (last >= value && apr_isspace(*last)) {
552                    *last = '\0';
553                    --last;
554                 }
555
556                 return ap_escape_logitem(r->pool, value);
557             }
558             cookies = NULL;
559         }
560     }
561     return NULL;
562 }
563
564 static const char *log_request_time_custom(request_rec *r, char *a,
565                                            apr_time_exp_t *xt)
566 {
567     apr_size_t retcode;
568     char tstr[MAX_STRING_LEN];
569     apr_strftime(tstr, &retcode, sizeof(tstr), a, xt);
570     return apr_pstrdup(r->pool, tstr);
571 }
572
573 #define DEFAULT_REQUEST_TIME_SIZE 32
574 typedef struct {
575     unsigned t;
576     char timestr[DEFAULT_REQUEST_TIME_SIZE];
577     unsigned t_validate;
578 } cached_request_time;
579
580 #define TIME_FMT_CUSTOM          0
581 #define TIME_FMT_CLF             1
582 #define TIME_FMT_ABS_SEC         2
583 #define TIME_FMT_ABS_MSEC        3
584 #define TIME_FMT_ABS_USEC        4
585 #define TIME_FMT_ABS_MSEC_FRAC   5
586 #define TIME_FMT_ABS_USEC_FRAC   6
587
588 #define TIME_CACHE_SIZE 4
589 #define TIME_CACHE_MASK 3
590 static cached_request_time request_time_cache[TIME_CACHE_SIZE];
591
592 static apr_time_t get_request_end_time(request_rec *r)
593 {
594     log_request_state *state = (log_request_state *)ap_get_module_config(r->request_config,
595                                                                          &log_config_module);
596     if (state->request_end_time == 0) {
597         state->request_end_time = apr_time_now();
598     }
599     return state->request_end_time;
600 }
601
602
603 static const char *log_request_time(request_rec *r, char *a)
604 {
605     apr_time_exp_t xt;
606     apr_time_t request_time = r->request_time;
607     int fmt_type = TIME_FMT_CUSTOM;
608     char *fmt = a;
609
610     if (fmt && *fmt) {
611         if (!strncmp(fmt, "begin", 5)) {
612             fmt += 5;
613             if (!*fmt) {
614                 fmt_type = TIME_FMT_CLF;
615             }
616             else if (*fmt == ':') {
617                 fmt++;
618                 a = fmt;
619             }
620         }
621         else if (!strncmp(fmt, "end", 3)) {
622             fmt += 3;
623             if (!*fmt) {
624                 request_time = get_request_end_time(r);
625                 fmt_type = TIME_FMT_CLF;
626             }
627             else if (*fmt == ':') {
628                 fmt++;
629                 a = fmt;
630                 request_time = get_request_end_time(r);
631             }
632         }
633         if (!strncmp(fmt, "msec", 4)) {
634             fmt += 4;
635             if (!*fmt) {
636                 fmt_type = TIME_FMT_ABS_MSEC;
637             }
638             else if (!strcmp(fmt, "_frac")) {
639                 fmt_type = TIME_FMT_ABS_MSEC_FRAC;
640             }
641         }
642         else if (!strncmp(fmt, "usec", 4)) {
643             fmt += 4;
644             if (!*fmt) {
645                 fmt_type = TIME_FMT_ABS_USEC;
646             }
647             else if (!strcmp(fmt, "_frac")) {
648                 fmt_type = TIME_FMT_ABS_USEC_FRAC;
649             }
650         }
651         else if (!strcmp(fmt, "sec")) {
652             fmt_type = TIME_FMT_ABS_SEC;
653         }
654         else if (!*fmt) {
655             fmt_type = TIME_FMT_CLF;
656         }
657     }
658     else {
659         fmt_type = TIME_FMT_CLF;
660     }
661
662     if (fmt_type >= TIME_FMT_ABS_SEC) {      /* Absolute (micro-/milli-)second time
663                                               * or msec/usec fraction
664                                               */
665         char* buf = apr_palloc(r->pool, 20);
666         switch (fmt_type) {
667         case TIME_FMT_ABS_SEC:
668             apr_snprintf(buf, 20, "%" APR_TIME_T_FMT, apr_time_sec(request_time));
669             break;
670         case TIME_FMT_ABS_MSEC:
671             apr_snprintf(buf, 20, "%" APR_TIME_T_FMT, apr_time_as_msec(request_time));
672             break;
673         case TIME_FMT_ABS_USEC:
674             apr_snprintf(buf, 20, "%" APR_TIME_T_FMT, request_time);
675             break;
676         case TIME_FMT_ABS_MSEC_FRAC:
677             apr_snprintf(buf, 20, "%03" APR_TIME_T_FMT, apr_time_msec(request_time));
678             break;
679         case TIME_FMT_ABS_USEC_FRAC:
680             apr_snprintf(buf, 20, "%06" APR_TIME_T_FMT, apr_time_usec(request_time));
681             break;
682         default:
683             return "-";
684         }
685         return buf;
686     }
687     else if (fmt_type == TIME_FMT_CUSTOM) {  /* Custom format */
688         /* The custom time formatting uses a very large temp buffer
689          * on the stack.  To avoid using so much stack space in the
690          * common case where we're not using a custom format, the code
691          * for the custom format in a separate function.  (That's why
692          * log_request_time_custom is not inlined right here.)
693          */
694         ap_explode_recent_localtime(&xt, request_time);
695         return log_request_time_custom(r, a, &xt);
696     }
697     else {                                   /* CLF format */
698         /* This code uses the same technique as ap_explode_recent_localtime():
699          * optimistic caching with logic to detect and correct race conditions.
700          * See the comments in server/util_time.c for more information.
701          */
702         cached_request_time* cached_time = apr_palloc(r->pool,
703                                                       sizeof(*cached_time));
704         unsigned t_seconds = (unsigned)apr_time_sec(request_time);
705         unsigned i = t_seconds & TIME_CACHE_MASK;
706         *cached_time = request_time_cache[i];
707         if ((t_seconds != cached_time->t) ||
708             (t_seconds != cached_time->t_validate)) {
709
710             /* Invalid or old snapshot, so compute the proper time string
711              * and store it in the cache
712              */
713             char sign;
714             int timz;
715
716             ap_explode_recent_localtime(&xt, request_time);
717             timz = xt.tm_gmtoff;
718             if (timz < 0) {
719                 timz = -timz;
720                 sign = '-';
721             }
722             else {
723                 sign = '+';
724             }
725             cached_time->t = t_seconds;
726             apr_snprintf(cached_time->timestr, DEFAULT_REQUEST_TIME_SIZE,
727                          "[%02d/%s/%d:%02d:%02d:%02d %c%.2d%.2d]",
728                          xt.tm_mday, apr_month_snames[xt.tm_mon],
729                          xt.tm_year+1900, xt.tm_hour, xt.tm_min, xt.tm_sec,
730                          sign, timz / (60*60), (timz % (60*60)) / 60);
731             cached_time->t_validate = t_seconds;
732             request_time_cache[i] = *cached_time;
733         }
734         return cached_time->timestr;
735     }
736 }
737
738 static const char *log_request_duration(request_rec *r, char *a)
739 {
740     apr_time_t duration = get_request_end_time(r) - r->request_time;
741     return apr_psprintf(r->pool, "%" APR_TIME_T_FMT, apr_time_sec(duration));
742 }
743
744 static const char *log_request_duration_microseconds(request_rec *r, char *a)
745 {
746     return apr_psprintf(r->pool, "%" APR_TIME_T_FMT,
747                         (get_request_end_time(r) - r->request_time));
748 }
749
750 /* These next two routines use the canonical name:port so that log
751  * parsers don't need to duplicate all the vhost parsing crud.
752  */
753 static const char *log_virtual_host(request_rec *r, char *a)
754 {
755     return ap_escape_logitem(r->pool, r->server->server_hostname);
756 }
757
758 static const char *log_server_port(request_rec *r, char *a)
759 {
760     apr_port_t port;
761
762     if (*a == '\0' || !strcasecmp(a, "canonical")) {
763         port = r->server->port ? r->server->port : ap_default_port(r);
764     }
765     else if (!strcasecmp(a, "remote")) {
766         port = r->useragent_addr->port;
767     }
768     else if (!strcasecmp(a, "local")) {
769         port = r->connection->local_addr->port;
770     }
771     else {
772         /* bogus format */
773         return a;
774     }
775     return apr_itoa(r->pool, (int)port);
776 }
777
778 /* This respects the setting of UseCanonicalName so that
779  * the dynamic mass virtual hosting trick works better.
780  */
781 static const char *log_server_name(request_rec *r, char *a)
782 {
783     return ap_escape_logitem(r->pool, ap_get_server_name(r));
784 }
785
786 static const char *log_pid_tid(request_rec *r, char *a)
787 {
788     if (*a == '\0' || !strcasecmp(a, "pid")) {
789         return ap_append_pid(r->pool, "", "");
790     }
791     else if (!strcasecmp(a, "tid") || !strcasecmp(a, "hextid")) {
792 #if APR_HAS_THREADS
793         apr_os_thread_t tid = apr_os_thread_current();
794 #else
795         int tid = 0; /* APR will format "0" anyway but an arg is needed */
796 #endif
797         return apr_psprintf(r->pool,
798 #if APR_MAJOR_VERSION > 1 || (APR_MAJOR_VERSION == 1 && APR_MINOR_VERSION >= 2)
799                             /* APR can format a thread id in hex */
800                             *a == 'h' ? "%pt" : "%pT",
801 #else
802                             /* APR is missing the feature, so always use decimal */
803                             "%pT",
804 #endif
805                             &tid);
806     }
807     /* bogus format */
808     return a;
809 }
810
811 static const char *log_connection_status(request_rec *r, char *a)
812 {
813     if (r->connection->aborted)
814         return "X";
815
816     if (r->connection->keepalive == AP_CONN_KEEPALIVE &&
817         (!r->server->keep_alive_max ||
818          (r->server->keep_alive_max - r->connection->keepalives) > 0)) {
819         return "+";
820     }
821     return "-";
822 }
823
824 static const char *log_requests_on_connection(request_rec *r, char *a)
825 {
826     int num = r->connection->keepalives ? r->connection->keepalives - 1 : 0;
827     return apr_itoa(r->pool, num);
828 }
829
830 /*****************************************************************
831  *
832  * Parsing the log format string
833  */
834
835 static char *parse_log_misc_string(apr_pool_t *p, log_format_item *it,
836                                    const char **sa)
837 {
838     const char *s;
839     char *d;
840
841     it->func = constant_item;
842     it->conditions = NULL;
843
844     s = *sa;
845     while (*s && *s != '%') {
846         s++;
847     }
848     /*
849      * This might allocate a few chars extra if there's a backslash
850      * escape in the format string.
851      */
852     it->arg = apr_palloc(p, s - *sa + 1);
853
854     d = it->arg;
855     s = *sa;
856     while (*s && *s != '%') {
857         if (*s != '\\') {
858             *d++ = *s++;
859         }
860         else {
861             s++;
862             switch (*s) {
863             case '\\':
864                 *d++ = '\\';
865                 s++;
866                 break;
867             case 'r':
868                 *d++ = '\r';
869                 s++;
870                 break;
871             case 'n':
872                 *d++ = '\n';
873                 s++;
874                 break;
875             case 't':
876                 *d++ = '\t';
877                 s++;
878                 break;
879             default:
880                 /* copy verbatim */
881                 *d++ = '\\';
882                 /*
883                  * Allow the loop to deal with this *s in the normal
884                  * fashion so that it handles end of string etc.
885                  * properly.
886                  */
887                 break;
888             }
889         }
890     }
891     *d = '\0';
892
893     *sa = s;
894     return NULL;
895 }
896
897 static char *parse_log_item(apr_pool_t *p, log_format_item *it, const char **sa)
898 {
899     const char *s = *sa;
900     ap_log_handler *handler;
901
902     if (*s != '%') {
903         return parse_log_misc_string(p, it, sa);
904     }
905
906     ++s;
907     it->condition_sense = 0;
908     it->conditions = NULL;
909
910     if (*s == '%') {
911         it->arg = "%";
912         it->func = constant_item;
913         *sa = ++s;
914
915         return NULL;
916     }
917
918     it->want_orig = -1;
919     it->arg = "";               /* For safety's sake... */
920
921     while (*s) {
922         int i;
923
924         switch (*s) {
925         case '!':
926             ++s;
927             it->condition_sense = !it->condition_sense;
928             break;
929
930         case '<':
931             ++s;
932             it->want_orig = 1;
933             break;
934
935         case '>':
936             ++s;
937             it->want_orig = 0;
938             break;
939
940         case ',':
941             ++s;
942             break;
943
944         case '{':
945             ++s;
946             it->arg = ap_getword(p, &s, '}');
947             break;
948
949         case '0':
950         case '1':
951         case '2':
952         case '3':
953         case '4':
954         case '5':
955         case '6':
956         case '7':
957         case '8':
958         case '9':
959             i = *s - '0';
960             while (apr_isdigit(*++s)) {
961                 i = i * 10 + (*s) - '0';
962             }
963             if (!it->conditions) {
964                 it->conditions = apr_array_make(p, 4, sizeof(int));
965             }
966             *(int *) apr_array_push(it->conditions) = i;
967             break;
968
969         default:
970             handler = (ap_log_handler *)apr_hash_get(log_hash, s++, 1);
971             if (!handler) {
972                 char dummy[2];
973
974                 dummy[0] = s[-1];
975                 dummy[1] = '\0';
976                 return apr_pstrcat(p, "Unrecognized LogFormat directive %",
977                                dummy, NULL);
978             }
979             it->func = handler->func;
980             if (it->want_orig == -1) {
981                 it->want_orig = handler->want_orig_default;
982             }
983             *sa = s;
984             return NULL;
985         }
986     }
987
988     return "Ran off end of LogFormat parsing args to some directive";
989 }
990
991 static apr_array_header_t *parse_log_string(apr_pool_t *p, const char *s, const char **err)
992 {
993     apr_array_header_t *a = apr_array_make(p, 30, sizeof(log_format_item));
994     char *res;
995
996     while (*s) {
997         if ((res = parse_log_item(p, (log_format_item *) apr_array_push(a), &s))) {
998             *err = res;
999             return NULL;
1000         }
1001     }
1002
1003     s = APR_EOL_STR;
1004     parse_log_item(p, (log_format_item *) apr_array_push(a), &s);
1005     return a;
1006 }
1007
1008 /*****************************************************************
1009  *
1010  * Actually logging.
1011  */
1012
1013 static const char *process_item(request_rec *r, request_rec *orig,
1014                           log_format_item *item)
1015 {
1016     const char *cp;
1017
1018     /* First, see if we need to process this thing at all... */
1019
1020     if (item->conditions && item->conditions->nelts != 0) {
1021         int i;
1022         int *conds = (int *) item->conditions->elts;
1023         int in_list = 0;
1024
1025         for (i = 0; i < item->conditions->nelts; ++i) {
1026             if (r->status == conds[i]) {
1027                 in_list = 1;
1028                 break;
1029             }
1030         }
1031
1032         if ((item->condition_sense && in_list)
1033             || (!item->condition_sense && !in_list)) {
1034             return "-";
1035         }
1036     }
1037
1038     /* We do.  Do it... */
1039
1040     cp = (*item->func) (item->want_orig ? orig : r, item->arg);
1041     return cp ? cp : "-";
1042 }
1043
1044 static void flush_log(buffered_log *buf)
1045 {
1046     if (buf->outcnt && buf->handle != NULL) {
1047         apr_file_write(buf->handle, buf->outbuf, &buf->outcnt);
1048         buf->outcnt = 0;
1049     }
1050 }
1051
1052
1053 static int config_log_transaction(request_rec *r, config_log_state *cls,
1054                                   apr_array_header_t *default_format)
1055 {
1056     log_format_item *items;
1057     const char **strs;
1058     int *strl;
1059     request_rec *orig;
1060     int i;
1061     apr_size_t len = 0;
1062     apr_array_header_t *format;
1063     char *envar;
1064     apr_status_t rv;
1065
1066     if (cls->fname == NULL) {
1067         return DECLINED;
1068     }
1069
1070     /*
1071      * See if we've got any conditional envariable-controlled logging decisions
1072      * to make.
1073      */
1074     if (cls->condition_var != NULL) {
1075         envar = cls->condition_var;
1076         if (*envar != '!') {
1077             if (apr_table_get(r->subprocess_env, envar) == NULL) {
1078                 return DECLINED;
1079             }
1080         }
1081         else {
1082             if (apr_table_get(r->subprocess_env, &envar[1]) != NULL) {
1083                 return DECLINED;
1084             }
1085         }
1086     }
1087     else if (cls->condition_expr != NULL) {
1088         const char *err;
1089         int rc = ap_expr_exec(r, cls->condition_expr, &err);
1090         if (rc < 0)
1091             ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(00644)
1092                            "Error evaluating log condition: %s", err);
1093         if (rc <= 0)
1094             return DECLINED;
1095     }
1096
1097     format = cls->format ? cls->format : default_format;
1098
1099     strs = apr_palloc(r->pool, sizeof(char *) * (format->nelts));
1100     strl = apr_palloc(r->pool, sizeof(int) * (format->nelts));
1101     items = (log_format_item *) format->elts;
1102
1103     orig = r;
1104     while (orig->prev) {
1105         orig = orig->prev;
1106     }
1107     while (r->next) {
1108         r = r->next;
1109     }
1110
1111     for (i = 0; i < format->nelts; ++i) {
1112         strs[i] = process_item(r, orig, &items[i]);
1113     }
1114
1115     for (i = 0; i < format->nelts; ++i) {
1116         len += strl[i] = strlen(strs[i]);
1117     }
1118     if (!log_writer) {
1119         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00645)
1120                 "log writer isn't correctly setup");
1121          return HTTP_INTERNAL_SERVER_ERROR;
1122     }
1123     rv = log_writer(r, cls->log_writer, strs, strl, format->nelts, len);
1124     if (rv != APR_SUCCESS)
1125         ap_log_rerror(APLOG_MARK, APLOG_WARNING, rv, r, APLOGNO(00646) "Error writing to %s",
1126                       cls->fname);
1127     return OK;
1128 }
1129
1130 static int multi_log_transaction(request_rec *r)
1131 {
1132     multi_log_state *mls = ap_get_module_config(r->server->module_config,
1133                                                 &log_config_module);
1134     config_log_state *clsarray;
1135     int i;
1136
1137     /*
1138      * Initialize per request state
1139      */
1140     log_request_state *state = apr_pcalloc(r->pool, sizeof(log_request_state));
1141     ap_set_module_config(r->request_config, &log_config_module, state);
1142
1143     /*
1144      * Log this transaction..
1145      */
1146     if (mls->config_logs->nelts) {
1147         clsarray = (config_log_state *) mls->config_logs->elts;
1148         for (i = 0; i < mls->config_logs->nelts; ++i) {
1149             config_log_state *cls = &clsarray[i];
1150
1151             config_log_transaction(r, cls, mls->default_format);
1152         }
1153     }
1154     else if (mls->server_config_logs) {
1155         clsarray = (config_log_state *) mls->server_config_logs->elts;
1156         for (i = 0; i < mls->server_config_logs->nelts; ++i) {
1157             config_log_state *cls = &clsarray[i];
1158
1159             config_log_transaction(r, cls, mls->default_format);
1160         }
1161     }
1162
1163     return OK;
1164 }
1165
1166 /*****************************************************************
1167  *
1168  * Module glue...
1169  */
1170
1171 static void *make_config_log_state(apr_pool_t *p, server_rec *s)
1172 {
1173     multi_log_state *mls;
1174
1175     mls = (multi_log_state *) apr_palloc(p, sizeof(multi_log_state));
1176     mls->config_logs = apr_array_make(p, 1, sizeof(config_log_state));
1177     mls->default_format_string = NULL;
1178     mls->default_format = NULL;
1179     mls->server_config_logs = NULL;
1180     mls->formats = apr_table_make(p, 4);
1181     apr_table_setn(mls->formats, "CLF", DEFAULT_LOG_FORMAT);
1182
1183     return mls;
1184 }
1185
1186 /*
1187  * Use the merger to simply add a pointer from the vhost log state
1188  * to the log of logs specified for the non-vhost configuration.  Make sure
1189  * vhosts inherit any globally-defined format names.
1190  */
1191
1192 static void *merge_config_log_state(apr_pool_t *p, void *basev, void *addv)
1193 {
1194     multi_log_state *base = (multi_log_state *) basev;
1195     multi_log_state *add = (multi_log_state *) addv;
1196
1197     add->server_config_logs = base->config_logs;
1198     if (!add->default_format) {
1199         add->default_format_string = base->default_format_string;
1200         add->default_format = base->default_format;
1201     }
1202     add->formats = apr_table_overlay(p, base->formats, add->formats);
1203
1204     return add;
1205 }
1206
1207 /*
1208  * Set the default logfile format, or define a nickname for a format string.
1209  */
1210 static const char *log_format(cmd_parms *cmd, void *dummy, const char *fmt,
1211                               const char *name)
1212 {
1213     const char *err_string = NULL;
1214     multi_log_state *mls = ap_get_module_config(cmd->server->module_config,
1215                                                 &log_config_module);
1216
1217     /*
1218      * If we were given two arguments, the second is a name to be given to the
1219      * format.  This syntax just defines the nickname - it doesn't actually
1220      * make the format the default.
1221      */
1222     if (name != NULL) {
1223         parse_log_string(cmd->pool, fmt, &err_string);
1224         if (err_string == NULL) {
1225             apr_table_setn(mls->formats, name, fmt);
1226         }
1227     }
1228     else {
1229         mls->default_format_string = fmt;
1230         mls->default_format = parse_log_string(cmd->pool, fmt, &err_string);
1231     }
1232     return err_string;
1233 }
1234
1235
1236 static const char *add_custom_log(cmd_parms *cmd, void *dummy, const char *fn,
1237                                   const char *fmt, const char *envclause)
1238 {
1239     const char *err_string = NULL;
1240     multi_log_state *mls = ap_get_module_config(cmd->server->module_config,
1241                                                 &log_config_module);
1242     config_log_state *cls;
1243
1244     cls = (config_log_state *) apr_array_push(mls->config_logs);
1245     cls->condition_var = NULL;
1246     cls->condition_expr = NULL;
1247     if (envclause != NULL) {
1248         if (strncasecmp(envclause, "env=", 4) == 0) {
1249             if ((envclause[4] == '\0')
1250                 || ((envclause[4] == '!') && (envclause[5] == '\0'))) {
1251                 return "missing environment variable name";
1252             }
1253             cls->condition_var = apr_pstrdup(cmd->pool, &envclause[4]);
1254         }
1255         else if (strncasecmp(envclause, "expr=", 5) == 0) {
1256             const char *err;
1257             if ((envclause[5] == '\0'))
1258                 return "missing condition";
1259             cls->condition_expr = ap_expr_parse_cmd(cmd, &envclause[5],
1260                                                     AP_EXPR_FLAG_DONT_VARY,
1261                                                     &err, NULL);
1262             if (err)
1263                 return err;
1264         }
1265         else {
1266             return "error in condition clause";
1267         }
1268     }
1269
1270     cls->fname = fn;
1271     cls->format_string = fmt;
1272     if (fmt == NULL) {
1273         cls->format = NULL;
1274     }
1275     else {
1276         cls->format = parse_log_string(cmd->pool, fmt, &err_string);
1277     }
1278     cls->log_writer = NULL;
1279
1280     return err_string;
1281 }
1282
1283 static const char *set_transfer_log(cmd_parms *cmd, void *dummy,
1284                                     const char *fn)
1285 {
1286     return add_custom_log(cmd, dummy, fn, NULL, NULL);
1287 }
1288
1289 static const char *set_buffered_logs_on(cmd_parms *parms, void *dummy, int flag)
1290 {
1291     buffered_logs = flag;
1292     if (buffered_logs) {
1293         ap_log_set_writer_init(ap_buffered_log_writer_init);
1294         ap_log_set_writer(ap_buffered_log_writer);
1295     }
1296     else {
1297         ap_log_set_writer_init(ap_default_log_writer_init);
1298         ap_log_set_writer(ap_default_log_writer);
1299     }
1300     return NULL;
1301 }
1302 static const command_rec config_log_cmds[] =
1303 {
1304 AP_INIT_TAKE23("CustomLog", add_custom_log, NULL, RSRC_CONF,
1305      "a file name, a custom log format string or format name, "
1306      "and an optional \"env=\" or \"expr=\" clause (see docs)"),
1307 AP_INIT_TAKE1("TransferLog", set_transfer_log, NULL, RSRC_CONF,
1308      "the filename of the access log"),
1309 AP_INIT_TAKE12("LogFormat", log_format, NULL, RSRC_CONF,
1310      "a log format string (see docs) and an optional format name"),
1311 AP_INIT_FLAG("BufferedLogs", set_buffered_logs_on, NULL, RSRC_CONF,
1312                  "Enable Buffered Logging (experimental)"),
1313     {NULL}
1314 };
1315
1316 static config_log_state *open_config_log(server_rec *s, apr_pool_t *p,
1317                                          config_log_state *cls,
1318                                          apr_array_header_t *default_format)
1319 {
1320     if (cls->log_writer != NULL) {
1321         return cls;             /* virtual config shared w/main server */
1322     }
1323
1324     if (cls->fname == NULL) {
1325         return cls;             /* Leave it NULL to decline.  */
1326     }
1327
1328     cls->log_writer = log_writer_init(p, s, cls->fname);
1329     if (cls->log_writer == NULL)
1330         return NULL;
1331
1332     return cls;
1333 }
1334
1335 static int open_multi_logs(server_rec *s, apr_pool_t *p)
1336 {
1337     int i;
1338     multi_log_state *mls = ap_get_module_config(s->module_config,
1339                                              &log_config_module);
1340     config_log_state *clsarray;
1341     const char *dummy;
1342     const char *format;
1343
1344     if (mls->default_format_string) {
1345         format = apr_table_get(mls->formats, mls->default_format_string);
1346         if (format) {
1347             mls->default_format = parse_log_string(p, format, &dummy);
1348         }
1349     }
1350
1351     if (!mls->default_format) {
1352         mls->default_format = parse_log_string(p, DEFAULT_LOG_FORMAT, &dummy);
1353     }
1354
1355     if (mls->config_logs->nelts) {
1356         clsarray = (config_log_state *) mls->config_logs->elts;
1357         for (i = 0; i < mls->config_logs->nelts; ++i) {
1358             config_log_state *cls = &clsarray[i];
1359
1360             if (cls->format_string) {
1361                 format = apr_table_get(mls->formats, cls->format_string);
1362                 if (format) {
1363                     cls->format = parse_log_string(p, format, &dummy);
1364                 }
1365             }
1366
1367             if (!open_config_log(s, p, cls, mls->default_format)) {
1368                 /* Failure already logged by open_config_log */
1369                 return DONE;
1370             }
1371         }
1372     }
1373     else if (mls->server_config_logs) {
1374         clsarray = (config_log_state *) mls->server_config_logs->elts;
1375         for (i = 0; i < mls->server_config_logs->nelts; ++i) {
1376             config_log_state *cls = &clsarray[i];
1377
1378             if (cls->format_string) {
1379                 format = apr_table_get(mls->formats, cls->format_string);
1380                 if (format) {
1381                     cls->format = parse_log_string(p, format, &dummy);
1382                 }
1383             }
1384
1385             if (!open_config_log(s, p, cls, mls->default_format)) {
1386                 /* Failure already logged by open_config_log */
1387                 return DONE;
1388             }
1389         }
1390     }
1391
1392     return OK;
1393 }
1394
1395
1396 static apr_status_t flush_all_logs(void *data)
1397 {
1398     server_rec *s = data;
1399     multi_log_state *mls;
1400     apr_array_header_t *log_list;
1401     config_log_state *clsarray;
1402     buffered_log *buf;
1403     int i;
1404
1405     if (!buffered_logs)
1406         return APR_SUCCESS;
1407
1408     for (; s; s = s->next) {
1409         mls = ap_get_module_config(s->module_config, &log_config_module);
1410         log_list = NULL;
1411         if (mls->config_logs->nelts) {
1412             log_list = mls->config_logs;
1413         }
1414         else if (mls->server_config_logs) {
1415             log_list = mls->server_config_logs;
1416         }
1417         if (log_list) {
1418             clsarray = (config_log_state *) log_list->elts;
1419             for (i = 0; i < log_list->nelts; ++i) {
1420                 buf = clsarray[i].log_writer;
1421                 flush_log(buf);
1422             }
1423         }
1424     }
1425     return APR_SUCCESS;
1426 }
1427
1428
1429 static int init_config_log(apr_pool_t *pc, apr_pool_t *p, apr_pool_t *pt, server_rec *s)
1430 {
1431     int res;
1432
1433     /* First init the buffered logs array, which is needed when opening the logs. */
1434     if (buffered_logs) {
1435         all_buffered_logs = apr_array_make(p, 5, sizeof(buffered_log *));
1436     }
1437
1438     /* Next, do "physical" server, which gets default log fd and format
1439      * for the virtual servers, if they don't override...
1440      */
1441     res = open_multi_logs(s, p);
1442
1443     /* Then, virtual servers */
1444
1445     for (s = s->next; (res == OK) && s; s = s->next) {
1446         res = open_multi_logs(s, p);
1447     }
1448
1449     return res;
1450 }
1451
1452 static void init_child(apr_pool_t *p, server_rec *s)
1453 {
1454     int mpm_threads;
1455
1456     ap_mpm_query(AP_MPMQ_MAX_THREADS, &mpm_threads);
1457
1458     /* Now register the last buffer flush with the cleanup engine */
1459     if (buffered_logs) {
1460         int i;
1461         buffered_log **array = (buffered_log **)all_buffered_logs->elts;
1462
1463         apr_pool_cleanup_register(p, s, flush_all_logs, flush_all_logs);
1464
1465         for (i = 0; i < all_buffered_logs->nelts; i++) {
1466             buffered_log *this = array[i];
1467
1468 #if APR_HAS_THREADS
1469             if (mpm_threads > 1) {
1470                 apr_status_t rv;
1471
1472                 this->mutex.type = apr_anylock_threadmutex;
1473                 rv = apr_thread_mutex_create(&this->mutex.lock.tm,
1474                                              APR_THREAD_MUTEX_DEFAULT,
1475                                              p);
1476                 if (rv != APR_SUCCESS) {
1477                     ap_log_error(APLOG_MARK, APLOG_CRIT, rv, s, APLOGNO(00647)
1478                                  "could not initialize buffered log mutex, "
1479                                  "transfer log may become corrupted");
1480                     this->mutex.type = apr_anylock_none;
1481                 }
1482             }
1483             else
1484 #endif
1485             {
1486                 this->mutex.type = apr_anylock_none;
1487             }
1488         }
1489     }
1490 }
1491
1492 static void ap_register_log_handler(apr_pool_t *p, char *tag,
1493                                     ap_log_handler_fn_t *handler, int def)
1494 {
1495     ap_log_handler *log_struct = apr_palloc(p, sizeof(*log_struct));
1496     log_struct->func = handler;
1497     log_struct->want_orig_default = def;
1498
1499     apr_hash_set(log_hash, tag, 1, (const void *)log_struct);
1500 }
1501 static ap_log_writer_init* ap_log_set_writer_init(ap_log_writer_init *handle)
1502 {
1503     ap_log_writer_init *old = log_writer_init;
1504     log_writer_init = handle;
1505
1506     return old;
1507
1508 }
1509 static ap_log_writer *ap_log_set_writer(ap_log_writer *handle)
1510 {
1511     ap_log_writer *old = log_writer;
1512     log_writer = handle;
1513
1514     return old;
1515 }
1516
1517 static apr_status_t ap_default_log_writer( request_rec *r,
1518                            void *handle,
1519                            const char **strs,
1520                            int *strl,
1521                            int nelts,
1522                            apr_size_t len)
1523
1524 {
1525     char *str;
1526     char *s;
1527     int i;
1528     apr_status_t rv;
1529
1530     str = apr_palloc(r->pool, len + 1);
1531
1532     for (i = 0, s = str; i < nelts; ++i) {
1533         memcpy(s, strs[i], strl[i]);
1534         s += strl[i];
1535     }
1536
1537     rv = apr_file_write((apr_file_t*)handle, str, &len);
1538
1539     return rv;
1540 }
1541 static void *ap_default_log_writer_init(apr_pool_t *p, server_rec *s,
1542                                         const char* name)
1543 {
1544     if (*name == '|') {
1545         piped_log *pl;
1546
1547         pl = ap_open_piped_log(p, name + 1);
1548         if (pl == NULL) {
1549            return NULL;;
1550         }
1551         return ap_piped_log_write_fd(pl);
1552     }
1553     else {
1554         const char *fname = ap_server_root_relative(p, name);
1555         apr_file_t *fd;
1556         apr_status_t rv;
1557
1558         if (!fname) {
1559             ap_log_error(APLOG_MARK, APLOG_ERR, APR_EBADPATH, s, APLOGNO(00648)
1560                             "invalid transfer log path %s.", name);
1561             return NULL;
1562         }
1563         rv = apr_file_open(&fd, fname, xfer_flags, xfer_perms, p);
1564         if (rv != APR_SUCCESS) {
1565             ap_log_error(APLOG_MARK, APLOG_ERR, rv, s, APLOGNO(00649)
1566                             "could not open transfer log file %s.", fname);
1567             return NULL;
1568         }
1569         return fd;
1570     }
1571 }
1572 static void *ap_buffered_log_writer_init(apr_pool_t *p, server_rec *s,
1573                                         const char* name)
1574 {
1575     buffered_log *b;
1576     b = apr_pcalloc(p, sizeof(buffered_log));
1577     b->handle = ap_default_log_writer_init(p, s, name);
1578
1579     if (b->handle) {
1580         *(buffered_log **)apr_array_push(all_buffered_logs) = b;
1581         return b;
1582     }
1583     else
1584         return NULL;
1585 }
1586 static apr_status_t ap_buffered_log_writer(request_rec *r,
1587                                            void *handle,
1588                                            const char **strs,
1589                                            int *strl,
1590                                            int nelts,
1591                                            apr_size_t len)
1592
1593 {
1594     char *str;
1595     char *s;
1596     int i;
1597     apr_status_t rv;
1598     buffered_log *buf = (buffered_log*)handle;
1599
1600     if ((rv = APR_ANYLOCK_LOCK(&buf->mutex)) != APR_SUCCESS) {
1601         return rv;
1602     }
1603
1604     if (len + buf->outcnt > LOG_BUFSIZE) {
1605         flush_log(buf);
1606     }
1607     if (len >= LOG_BUFSIZE) {
1608         apr_size_t w;
1609
1610         str = apr_palloc(r->pool, len + 1);
1611         for (i = 0, s = str; i < nelts; ++i) {
1612             memcpy(s, strs[i], strl[i]);
1613             s += strl[i];
1614         }
1615         w = len;
1616         rv = apr_file_write(buf->handle, str, &w);
1617
1618     }
1619     else {
1620         for (i = 0, s = &buf->outbuf[buf->outcnt]; i < nelts; ++i) {
1621             memcpy(s, strs[i], strl[i]);
1622             s += strl[i];
1623         }
1624         buf->outcnt += len;
1625         rv = APR_SUCCESS;
1626     }
1627
1628     APR_ANYLOCK_UNLOCK(&buf->mutex);
1629     return rv;
1630 }
1631
1632 static int log_pre_config(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp)
1633 {
1634     static APR_OPTIONAL_FN_TYPE(ap_register_log_handler) *log_pfn_register;
1635
1636     log_pfn_register = APR_RETRIEVE_OPTIONAL_FN(ap_register_log_handler);
1637
1638     if (log_pfn_register) {
1639         log_pfn_register(p, "h", log_remote_host, 0);
1640         log_pfn_register(p, "a", log_remote_address, 0 );
1641         log_pfn_register(p, "A", log_local_address, 0 );
1642         log_pfn_register(p, "l", log_remote_logname, 0);
1643         log_pfn_register(p, "u", log_remote_user, 0);
1644         log_pfn_register(p, "t", log_request_time, 0);
1645         log_pfn_register(p, "f", log_request_file, 0);
1646         log_pfn_register(p, "b", clf_log_bytes_sent, 0);
1647         log_pfn_register(p, "B", log_bytes_sent, 0);
1648         log_pfn_register(p, "i", log_header_in, 0);
1649         log_pfn_register(p, "o", log_header_out, 0);
1650         log_pfn_register(p, "n", log_note, 0);
1651         log_pfn_register(p, "L", log_log_id, 1);
1652         log_pfn_register(p, "e", log_env_var, 0);
1653         log_pfn_register(p, "V", log_server_name, 0);
1654         log_pfn_register(p, "v", log_virtual_host, 0);
1655         log_pfn_register(p, "p", log_server_port, 0);
1656         log_pfn_register(p, "P", log_pid_tid, 0);
1657         log_pfn_register(p, "H", log_request_protocol, 0);
1658         log_pfn_register(p, "m", log_request_method, 0);
1659         log_pfn_register(p, "q", log_request_query, 0);
1660         log_pfn_register(p, "X", log_connection_status, 0);
1661         log_pfn_register(p, "C", log_cookie, 0);
1662         log_pfn_register(p, "k", log_requests_on_connection, 0);
1663         log_pfn_register(p, "r", log_request_line, 1);
1664         log_pfn_register(p, "D", log_request_duration_microseconds, 1);
1665         log_pfn_register(p, "T", log_request_duration, 1);
1666         log_pfn_register(p, "U", log_request_uri, 1);
1667         log_pfn_register(p, "s", log_status, 1);
1668         log_pfn_register(p, "R", log_handler, 1);
1669     }
1670
1671     /* reset to default conditions */
1672     ap_log_set_writer_init(ap_default_log_writer_init);
1673     ap_log_set_writer(ap_default_log_writer);
1674     buffered_logs = 0;
1675
1676     return OK;
1677 }
1678
1679 static void register_hooks(apr_pool_t *p)
1680 {
1681     ap_hook_pre_config(log_pre_config,NULL,NULL,APR_HOOK_REALLY_FIRST);
1682     ap_hook_child_init(init_child,NULL,NULL,APR_HOOK_MIDDLE);
1683     ap_hook_open_logs(init_config_log,NULL,NULL,APR_HOOK_MIDDLE);
1684     ap_hook_log_transaction(multi_log_transaction,NULL,NULL,APR_HOOK_MIDDLE);
1685
1686     /* Init log_hash before we register the optional function. It is
1687      * possible for the optional function, ap_register_log_handler,
1688      * to be called before any other mod_log_config hooks are called.
1689      * As a policy, we should init everything required by an optional function
1690      * before calling APR_REGISTER_OPTIONAL_FN.
1691      */
1692     log_hash = apr_hash_make(p);
1693     APR_REGISTER_OPTIONAL_FN(ap_register_log_handler);
1694     APR_REGISTER_OPTIONAL_FN(ap_log_set_writer_init);
1695     APR_REGISTER_OPTIONAL_FN(ap_log_set_writer);
1696 }
1697
1698 AP_DECLARE_MODULE(log_config) =
1699 {
1700     STANDARD20_MODULE_STUFF,
1701     NULL,                       /* create per-dir config */
1702     NULL,                       /* merge per-dir config */
1703     make_config_log_state,      /* server config */
1704     merge_config_log_state,     /* merge server config */
1705     config_log_cmds,            /* command apr_table_t */
1706     register_hooks              /* register hooks */
1707 };
1708