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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * Modified by djm@va.pubnix.com:
19 * If no TransferLog is given explicitly, decline to log.
21 * This is module implements the TransferLog directive (same as the
22 * common log module), and additional directives, LogFormat and CustomLog.
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
31 * Log to file fn with format given by the format
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.
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.
48 * TransferLog logs/access_log
50 * LogFormat "... custom format ..."
51 * TransferLog log/virtual_only
52 * CustomLog log/virtual_useragents "%t %{user-agent}i"
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.
60 * Note that the NCSA referer and user-agent logs are easily added with
62 * CustomLog logs/referer "%{referer}i -> %U"
63 * CustomLog logs/agent "%{user-agent}i"
65 * RefererIgnore functionality can be obtained with conditional
66 * logging (SetEnvIf and CustomLog ... env=!VAR).
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"
72 * The argument to LogFormat and CustomLog is a string, which can include
73 * literal characters copied into the log files, and '%' directives as
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
83 * %...a: remote IP-address
84 * %...A: local IP-address
85 * %...{Foobar}i: The contents of Foobar: header line(s) in the request
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
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)
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.
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.
136 * The default LogFormat reproduces CLF; see below.
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 "| ...").
146 #include "apr_strings.h"
148 #include "apr_hash.h"
149 #include "apr_optional.h"
150 #include "apr_anylock.h"
152 #define APR_WANT_STRFUNC
153 #include "apr_want.h"
155 #include "ap_config.h"
156 #include "mod_log_config.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"
165 #if APR_HAVE_UNISTD_H
172 #define DEFAULT_LOG_FORMAT "%h %l %u %t \"%r\" %>s %b"
174 module AP_MODULE_DECLARE_DATA log_config_module;
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,
186 static apr_status_t ap_buffered_log_writer(request_rec *r,
192 static void *ap_default_log_writer_init(apr_pool_t *p, server_rec *s,
194 static void *ap_buffered_log_writer_init(apr_pool_t *p, server_rec *s,
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;
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
214 #define LOG_BUFSIZE PIPE_BUF
216 #define LOG_BUFSIZE (512)
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.
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.
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;
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
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.
255 char outbuf[LOG_BUFSIZE];
261 const char *format_string;
262 apr_array_header_t *format;
265 ap_expr_info_t *condition_expr;
269 * log_request_state holds request specific log data that is not
270 * part of the request_rec.
273 apr_time_t request_end_time;
278 * Note that many of these could have ap_sprintfs replaced with static buffers.
282 ap_log_handler_fn_t *func;
286 apr_array_header_t *conditions;
289 static char *pfmt(apr_pool_t *p, int i)
295 return apr_itoa(p, i);
299 static const char *constant_item(request_rec *dummy, char *stuff)
304 static const char *log_remote_host(request_rec *r, char *a)
306 return ap_escape_logitem(r->pool, ap_get_remote_host(r->connection,
311 static const char *log_remote_address(request_rec *r, char *a)
313 if (a && !strcmp(a, "c")) {
314 return r->connection->client_ip;
317 return r->useragent_ip;
321 static const char *log_local_address(request_rec *r, char *a)
323 return r->connection->local_ip;
326 static const char *log_remote_logname(request_rec *r, char *a)
328 return ap_escape_logitem(r->pool, ap_get_remote_logname(r));
331 static const char *log_remote_user(request_rec *r, char *a)
333 char *rvalue = r->user;
335 if (rvalue == NULL) {
338 else if (strlen(rvalue) == 0) {
342 rvalue = ap_escape_logitem(r->pool, rvalue);
348 static const char *log_request_line(request_rec *r, char *a)
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)
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,
360 r->assbackwards ? NULL : " ",
365 static const char *log_request_file(request_rec *r, char *a)
367 return ap_escape_logitem(r->pool, r->filename);
369 static const char *log_request_uri(request_rec *r, char *a)
371 return ap_escape_logitem(r->pool, r->uri);
373 static const char *log_request_method(request_rec *r, char *a)
375 return ap_escape_logitem(r->pool, r->method);
377 static const char *log_log_id(request_rec *r, char *a)
379 if (a && !strcmp(a, "c")) {
380 return r->connection->log_id ? r->connection->log_id : "-";
383 return r->log_id ? r->log_id : "-";
386 static const char *log_request_protocol(request_rec *r, char *a)
388 return ap_escape_logitem(r->pool, r->protocol);
390 static const char *log_request_query(request_rec *r, char *a)
392 return (r->args) ? apr_pstrcat(r->pool, "?",
393 ap_escape_logitem(r->pool, r->args), NULL)
396 static const char *log_status(request_rec *r, char *a)
398 return pfmt(r->pool, r->status);
401 static const char *log_handler(request_rec *r, char *a)
403 return ap_escape_logitem(r->pool, r->handler);
406 static const char *clf_log_bytes_sent(request_rec *r, char *a)
408 if (!r->sent_bodyct || !r->bytes_sent) {
412 return apr_off_t_toa(r->pool, r->bytes_sent);
416 static const char *log_bytes_sent(request_rec *r, char *a)
418 if (!r->sent_bodyct || !r->bytes_sent) {
422 return apr_off_t_toa(r->pool, r->bytes_sent);
427 static const char *log_header_in(request_rec *r, char *a)
429 return ap_escape_logitem(r->pool, apr_table_get(r->headers_in, a));
432 static APR_INLINE char *find_multiple_headers(apr_pool_t *pool,
433 const apr_table_t *table,
436 const apr_array_header_t *elts;
437 const apr_table_entry_t *t_elt;
438 const apr_table_entry_t *t_end;
446 elts = apr_table_elts(table);
452 t_elt = (const apr_table_entry_t *)elts->elts;
453 t_end = t_elt + elts->nelts;
455 result_list = rp = NULL;
458 if (!strcasecmp(t_elt->key, key)) {
460 result_list = rp = apr_palloc(pool, sizeof(*rp));
463 rp = rp->next = apr_palloc(pool, sizeof(*rp));
468 rp->value = t_elt->val;
469 rp->len = strlen(rp->value);
474 } while (t_elt < t_end);
477 char *result = apr_palloc(pool, len);
482 if (rp != result_list) {
486 memcpy(cp, rp->value, rp->len);
498 static const char *log_header_out(request_rec *r, char *a)
500 const char *cp = NULL;
502 if (!strcasecmp(a, "Content-type") && r->content_type) {
503 cp = ap_field_noparam(r->pool, r->content_type);
505 else if (!strcasecmp(a, "Set-Cookie")) {
506 cp = find_multiple_headers(r->pool, r->headers_out, a);
509 cp = apr_table_get(r->headers_out, a);
512 return ap_escape_logitem(r->pool, cp);
515 static const char *log_note(request_rec *r, char *a)
517 return ap_escape_logitem(r->pool, apr_table_get(r->notes, a));
519 static const char *log_env_var(request_rec *r, char *a)
521 return ap_escape_logitem(r->pool, apr_table_get(r->subprocess_env, a));
524 static const char *log_cookie(request_rec *r, char *a)
526 const char *cookies_entry;
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
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);
542 while ((cookie = apr_strtok(cookies, ";", &last1))) {
543 char *name = apr_strtok(cookie, "=", &last2);
545 apr_collapse_spaces(name, name);
547 if (!strcasecmp(name, a) && (value = apr_strtok(NULL, "=", &last2))) {
549 value += strspn(value, " \t"); /* Move past leading WS */
550 last = value + strlen(value) - 1;
551 while (last >= value && apr_isspace(*last)) {
556 return ap_escape_logitem(r->pool, value);
564 static const char *log_request_time_custom(request_rec *r, char *a,
568 char tstr[MAX_STRING_LEN];
569 apr_strftime(tstr, &retcode, sizeof(tstr), a, xt);
570 return apr_pstrdup(r->pool, tstr);
573 #define DEFAULT_REQUEST_TIME_SIZE 32
576 char timestr[DEFAULT_REQUEST_TIME_SIZE];
578 } cached_request_time;
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
588 #define TIME_CACHE_SIZE 4
589 #define TIME_CACHE_MASK 3
590 static cached_request_time request_time_cache[TIME_CACHE_SIZE];
592 static apr_time_t get_request_end_time(request_rec *r)
594 log_request_state *state = (log_request_state *)ap_get_module_config(r->request_config,
596 if (state->request_end_time == 0) {
597 state->request_end_time = apr_time_now();
599 return state->request_end_time;
603 static const char *log_request_time(request_rec *r, char *a)
606 apr_time_t request_time = r->request_time;
607 int fmt_type = TIME_FMT_CUSTOM;
611 if (!strncmp(fmt, "begin", 5)) {
614 fmt_type = TIME_FMT_CLF;
616 else if (*fmt == ':') {
621 else if (!strncmp(fmt, "end", 3)) {
624 request_time = get_request_end_time(r);
625 fmt_type = TIME_FMT_CLF;
627 else if (*fmt == ':') {
630 request_time = get_request_end_time(r);
633 if (!strncmp(fmt, "msec", 4)) {
636 fmt_type = TIME_FMT_ABS_MSEC;
638 else if (!strcmp(fmt, "_frac")) {
639 fmt_type = TIME_FMT_ABS_MSEC_FRAC;
642 else if (!strncmp(fmt, "usec", 4)) {
645 fmt_type = TIME_FMT_ABS_USEC;
647 else if (!strcmp(fmt, "_frac")) {
648 fmt_type = TIME_FMT_ABS_USEC_FRAC;
651 else if (!strcmp(fmt, "sec")) {
652 fmt_type = TIME_FMT_ABS_SEC;
655 fmt_type = TIME_FMT_CLF;
659 fmt_type = TIME_FMT_CLF;
662 if (fmt_type >= TIME_FMT_ABS_SEC) { /* Absolute (micro-/milli-)second time
663 * or msec/usec fraction
665 char* buf = apr_palloc(r->pool, 20);
667 case TIME_FMT_ABS_SEC:
668 apr_snprintf(buf, 20, "%" APR_TIME_T_FMT, apr_time_sec(request_time));
670 case TIME_FMT_ABS_MSEC:
671 apr_snprintf(buf, 20, "%" APR_TIME_T_FMT, apr_time_as_msec(request_time));
673 case TIME_FMT_ABS_USEC:
674 apr_snprintf(buf, 20, "%" APR_TIME_T_FMT, request_time);
676 case TIME_FMT_ABS_MSEC_FRAC:
677 apr_snprintf(buf, 20, "%03" APR_TIME_T_FMT, apr_time_msec(request_time));
679 case TIME_FMT_ABS_USEC_FRAC:
680 apr_snprintf(buf, 20, "%06" APR_TIME_T_FMT, apr_time_usec(request_time));
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.)
694 ap_explode_recent_localtime(&xt, request_time);
695 return log_request_time_custom(r, a, &xt);
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.
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)) {
710 /* Invalid or old snapshot, so compute the proper time string
711 * and store it in the cache
716 ap_explode_recent_localtime(&xt, request_time);
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;
734 return cached_time->timestr;
738 static const char *log_request_duration(request_rec *r, char *a)
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));
744 static const char *log_request_duration_microseconds(request_rec *r, char *a)
746 return apr_psprintf(r->pool, "%" APR_TIME_T_FMT,
747 (get_request_end_time(r) - r->request_time));
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.
753 static const char *log_virtual_host(request_rec *r, char *a)
755 return ap_escape_logitem(r->pool, r->server->server_hostname);
758 static const char *log_server_port(request_rec *r, char *a)
762 if (*a == '\0' || !strcasecmp(a, "canonical")) {
763 port = r->server->port ? r->server->port : ap_default_port(r);
765 else if (!strcasecmp(a, "remote")) {
766 port = r->useragent_addr->port;
768 else if (!strcasecmp(a, "local")) {
769 port = r->connection->local_addr->port;
775 return apr_itoa(r->pool, (int)port);
778 /* This respects the setting of UseCanonicalName so that
779 * the dynamic mass virtual hosting trick works better.
781 static const char *log_server_name(request_rec *r, char *a)
783 return ap_escape_logitem(r->pool, ap_get_server_name(r));
786 static const char *log_pid_tid(request_rec *r, char *a)
788 if (*a == '\0' || !strcasecmp(a, "pid")) {
789 return ap_append_pid(r->pool, "", "");
791 else if (!strcasecmp(a, "tid") || !strcasecmp(a, "hextid")) {
793 apr_os_thread_t tid = apr_os_thread_current();
795 int tid = 0; /* APR will format "0" anyway but an arg is needed */
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",
802 /* APR is missing the feature, so always use decimal */
811 static const char *log_connection_status(request_rec *r, char *a)
813 if (r->connection->aborted)
816 if (r->connection->keepalive == AP_CONN_KEEPALIVE &&
817 (!r->server->keep_alive_max ||
818 (r->server->keep_alive_max - r->connection->keepalives) > 0)) {
824 static const char *log_requests_on_connection(request_rec *r, char *a)
826 int num = r->connection->keepalives ? r->connection->keepalives - 1 : 0;
827 return apr_itoa(r->pool, num);
830 /*****************************************************************
832 * Parsing the log format string
835 static char *parse_log_misc_string(apr_pool_t *p, log_format_item *it,
841 it->func = constant_item;
842 it->conditions = NULL;
845 while (*s && *s != '%') {
849 * This might allocate a few chars extra if there's a backslash
850 * escape in the format string.
852 it->arg = apr_palloc(p, s - *sa + 1);
856 while (*s && *s != '%') {
883 * Allow the loop to deal with this *s in the normal
884 * fashion so that it handles end of string etc.
897 static char *parse_log_item(apr_pool_t *p, log_format_item *it, const char **sa)
900 ap_log_handler *handler;
903 return parse_log_misc_string(p, it, sa);
907 it->condition_sense = 0;
908 it->conditions = NULL;
912 it->func = constant_item;
919 it->arg = ""; /* For safety's sake... */
927 it->condition_sense = !it->condition_sense;
946 it->arg = ap_getword(p, &s, '}');
960 while (apr_isdigit(*++s)) {
961 i = i * 10 + (*s) - '0';
963 if (!it->conditions) {
964 it->conditions = apr_array_make(p, 4, sizeof(int));
966 *(int *) apr_array_push(it->conditions) = i;
970 handler = (ap_log_handler *)apr_hash_get(log_hash, s++, 1);
976 return apr_pstrcat(p, "Unrecognized LogFormat directive %",
979 it->func = handler->func;
980 if (it->want_orig == -1) {
981 it->want_orig = handler->want_orig_default;
988 return "Ran off end of LogFormat parsing args to some directive";
991 static apr_array_header_t *parse_log_string(apr_pool_t *p, const char *s, const char **err)
993 apr_array_header_t *a = apr_array_make(p, 30, sizeof(log_format_item));
997 if ((res = parse_log_item(p, (log_format_item *) apr_array_push(a), &s))) {
1004 parse_log_item(p, (log_format_item *) apr_array_push(a), &s);
1008 /*****************************************************************
1013 static const char *process_item(request_rec *r, request_rec *orig,
1014 log_format_item *item)
1018 /* First, see if we need to process this thing at all... */
1020 if (item->conditions && item->conditions->nelts != 0) {
1022 int *conds = (int *) item->conditions->elts;
1025 for (i = 0; i < item->conditions->nelts; ++i) {
1026 if (r->status == conds[i]) {
1032 if ((item->condition_sense && in_list)
1033 || (!item->condition_sense && !in_list)) {
1038 /* We do. Do it... */
1040 cp = (*item->func) (item->want_orig ? orig : r, item->arg);
1041 return cp ? cp : "-";
1044 static void flush_log(buffered_log *buf)
1046 if (buf->outcnt && buf->handle != NULL) {
1047 apr_file_write(buf->handle, buf->outbuf, &buf->outcnt);
1053 static int config_log_transaction(request_rec *r, config_log_state *cls,
1054 apr_array_header_t *default_format)
1056 log_format_item *items;
1062 apr_array_header_t *format;
1066 if (cls->fname == NULL) {
1071 * See if we've got any conditional envariable-controlled logging decisions
1074 if (cls->condition_var != NULL) {
1075 envar = cls->condition_var;
1076 if (*envar != '!') {
1077 if (apr_table_get(r->subprocess_env, envar) == NULL) {
1082 if (apr_table_get(r->subprocess_env, &envar[1]) != NULL) {
1087 else if (cls->condition_expr != NULL) {
1089 int rc = ap_expr_exec(r, cls->condition_expr, &err);
1091 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(00644)
1092 "Error evaluating log condition: %s", err);
1097 format = cls->format ? cls->format : default_format;
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;
1104 while (orig->prev) {
1111 for (i = 0; i < format->nelts; ++i) {
1112 strs[i] = process_item(r, orig, &items[i]);
1115 for (i = 0; i < format->nelts; ++i) {
1116 len += strl[i] = strlen(strs[i]);
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;
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",
1130 static int multi_log_transaction(request_rec *r)
1132 multi_log_state *mls = ap_get_module_config(r->server->module_config,
1133 &log_config_module);
1134 config_log_state *clsarray;
1138 * Initialize per request state
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);
1144 * Log this transaction..
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];
1151 config_log_transaction(r, cls, mls->default_format);
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];
1159 config_log_transaction(r, cls, mls->default_format);
1166 /*****************************************************************
1171 static void *make_config_log_state(apr_pool_t *p, server_rec *s)
1173 multi_log_state *mls;
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);
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.
1192 static void *merge_config_log_state(apr_pool_t *p, void *basev, void *addv)
1194 multi_log_state *base = (multi_log_state *) basev;
1195 multi_log_state *add = (multi_log_state *) addv;
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;
1202 add->formats = apr_table_overlay(p, base->formats, add->formats);
1208 * Set the default logfile format, or define a nickname for a format string.
1210 static const char *log_format(cmd_parms *cmd, void *dummy, const char *fmt,
1213 const char *err_string = NULL;
1214 multi_log_state *mls = ap_get_module_config(cmd->server->module_config,
1215 &log_config_module);
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.
1223 parse_log_string(cmd->pool, fmt, &err_string);
1224 if (err_string == NULL) {
1225 apr_table_setn(mls->formats, name, fmt);
1229 mls->default_format_string = fmt;
1230 mls->default_format = parse_log_string(cmd->pool, fmt, &err_string);
1236 static const char *add_custom_log(cmd_parms *cmd, void *dummy, const char *fn,
1237 const char *fmt, const char *envclause)
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;
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";
1253 cls->condition_var = apr_pstrdup(cmd->pool, &envclause[4]);
1255 else if (strncasecmp(envclause, "expr=", 5) == 0) {
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,
1266 return "error in condition clause";
1271 cls->format_string = fmt;
1276 cls->format = parse_log_string(cmd->pool, fmt, &err_string);
1278 cls->log_writer = NULL;
1283 static const char *set_transfer_log(cmd_parms *cmd, void *dummy,
1286 return add_custom_log(cmd, dummy, fn, NULL, NULL);
1289 static const char *set_buffered_logs_on(cmd_parms *parms, void *dummy, int flag)
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);
1297 ap_log_set_writer_init(ap_default_log_writer_init);
1298 ap_log_set_writer(ap_default_log_writer);
1302 static const command_rec config_log_cmds[] =
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)"),
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)
1320 if (cls->log_writer != NULL) {
1321 return cls; /* virtual config shared w/main server */
1324 if (cls->fname == NULL) {
1325 return cls; /* Leave it NULL to decline. */
1328 cls->log_writer = log_writer_init(p, s, cls->fname);
1329 if (cls->log_writer == NULL)
1335 static int open_multi_logs(server_rec *s, apr_pool_t *p)
1338 multi_log_state *mls = ap_get_module_config(s->module_config,
1339 &log_config_module);
1340 config_log_state *clsarray;
1344 if (mls->default_format_string) {
1345 format = apr_table_get(mls->formats, mls->default_format_string);
1347 mls->default_format = parse_log_string(p, format, &dummy);
1351 if (!mls->default_format) {
1352 mls->default_format = parse_log_string(p, DEFAULT_LOG_FORMAT, &dummy);
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];
1360 if (cls->format_string) {
1361 format = apr_table_get(mls->formats, cls->format_string);
1363 cls->format = parse_log_string(p, format, &dummy);
1367 if (!open_config_log(s, p, cls, mls->default_format)) {
1368 /* Failure already logged by open_config_log */
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];
1378 if (cls->format_string) {
1379 format = apr_table_get(mls->formats, cls->format_string);
1381 cls->format = parse_log_string(p, format, &dummy);
1385 if (!open_config_log(s, p, cls, mls->default_format)) {
1386 /* Failure already logged by open_config_log */
1396 static apr_status_t flush_all_logs(void *data)
1398 server_rec *s = data;
1399 multi_log_state *mls;
1400 apr_array_header_t *log_list;
1401 config_log_state *clsarray;
1408 for (; s; s = s->next) {
1409 mls = ap_get_module_config(s->module_config, &log_config_module);
1411 if (mls->config_logs->nelts) {
1412 log_list = mls->config_logs;
1414 else if (mls->server_config_logs) {
1415 log_list = mls->server_config_logs;
1418 clsarray = (config_log_state *) log_list->elts;
1419 for (i = 0; i < log_list->nelts; ++i) {
1420 buf = clsarray[i].log_writer;
1429 static int init_config_log(apr_pool_t *pc, apr_pool_t *p, apr_pool_t *pt, server_rec *s)
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 *));
1438 /* Next, do "physical" server, which gets default log fd and format
1439 * for the virtual servers, if they don't override...
1441 res = open_multi_logs(s, p);
1443 /* Then, virtual servers */
1445 for (s = s->next; (res == OK) && s; s = s->next) {
1446 res = open_multi_logs(s, p);
1452 static void init_child(apr_pool_t *p, server_rec *s)
1456 ap_mpm_query(AP_MPMQ_MAX_THREADS, &mpm_threads);
1458 /* Now register the last buffer flush with the cleanup engine */
1459 if (buffered_logs) {
1461 buffered_log **array = (buffered_log **)all_buffered_logs->elts;
1463 apr_pool_cleanup_register(p, s, flush_all_logs, flush_all_logs);
1465 for (i = 0; i < all_buffered_logs->nelts; i++) {
1466 buffered_log *this = array[i];
1469 if (mpm_threads > 1) {
1472 this->mutex.type = apr_anylock_threadmutex;
1473 rv = apr_thread_mutex_create(&this->mutex.lock.tm,
1474 APR_THREAD_MUTEX_DEFAULT,
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;
1486 this->mutex.type = apr_anylock_none;
1492 static void ap_register_log_handler(apr_pool_t *p, char *tag,
1493 ap_log_handler_fn_t *handler, int def)
1495 ap_log_handler *log_struct = apr_palloc(p, sizeof(*log_struct));
1496 log_struct->func = handler;
1497 log_struct->want_orig_default = def;
1499 apr_hash_set(log_hash, tag, 1, (const void *)log_struct);
1501 static ap_log_writer_init* ap_log_set_writer_init(ap_log_writer_init *handle)
1503 ap_log_writer_init *old = log_writer_init;
1504 log_writer_init = handle;
1509 static ap_log_writer *ap_log_set_writer(ap_log_writer *handle)
1511 ap_log_writer *old = log_writer;
1512 log_writer = handle;
1517 static apr_status_t ap_default_log_writer( request_rec *r,
1530 str = apr_palloc(r->pool, len + 1);
1532 for (i = 0, s = str; i < nelts; ++i) {
1533 memcpy(s, strs[i], strl[i]);
1537 rv = apr_file_write((apr_file_t*)handle, str, &len);
1541 static void *ap_default_log_writer_init(apr_pool_t *p, server_rec *s,
1547 pl = ap_open_piped_log(p, name + 1);
1551 return ap_piped_log_write_fd(pl);
1554 const char *fname = ap_server_root_relative(p, name);
1559 ap_log_error(APLOG_MARK, APLOG_ERR, APR_EBADPATH, s, APLOGNO(00648)
1560 "invalid transfer log path %s.", name);
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);
1572 static void *ap_buffered_log_writer_init(apr_pool_t *p, server_rec *s,
1576 b = apr_pcalloc(p, sizeof(buffered_log));
1577 b->handle = ap_default_log_writer_init(p, s, name);
1580 *(buffered_log **)apr_array_push(all_buffered_logs) = b;
1586 static apr_status_t ap_buffered_log_writer(request_rec *r,
1598 buffered_log *buf = (buffered_log*)handle;
1600 if ((rv = APR_ANYLOCK_LOCK(&buf->mutex)) != APR_SUCCESS) {
1604 if (len + buf->outcnt > LOG_BUFSIZE) {
1607 if (len >= LOG_BUFSIZE) {
1610 str = apr_palloc(r->pool, len + 1);
1611 for (i = 0, s = str; i < nelts; ++i) {
1612 memcpy(s, strs[i], strl[i]);
1616 rv = apr_file_write(buf->handle, str, &w);
1620 for (i = 0, s = &buf->outbuf[buf->outcnt]; i < nelts; ++i) {
1621 memcpy(s, strs[i], strl[i]);
1628 APR_ANYLOCK_UNLOCK(&buf->mutex);
1632 static int log_pre_config(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp)
1634 static APR_OPTIONAL_FN_TYPE(ap_register_log_handler) *log_pfn_register;
1636 log_pfn_register = APR_RETRIEVE_OPTIONAL_FN(ap_register_log_handler);
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);
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);
1679 static void register_hooks(apr_pool_t *p)
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);
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.
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);
1698 AP_DECLARE_MODULE(log_config) =
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 */