-
Notifications
You must be signed in to change notification settings - Fork 0
/
access_log.c
371 lines (331 loc) · 12.1 KB
/
access_log.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
/*
* Copyright (c) 2014 DeNA Co., Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include "h2o.h"
#define LOG_ALLOCA_SIZE 4096
enum {
ELEMENT_TYPE_EMPTY, /* empty element (with suffix only) */
ELEMENT_TYPE_REMOTE_ADDR, /* %h */
ELEMENT_TYPE_LOGNAME, /* %l */
ELEMENT_TYPE_REMOTE_USER, /* %u */
ELEMENT_TYPE_TIMESTAMP, /* %t */
ELEMENT_TYPE_REQUEST_LINE, /* %r */
ELEMENT_TYPE_STATUS, /* %s */
ELEMENT_TYPE_BYTES_SENT, /* %b */
NUM_ELEMENT_TYPES
};
struct log_element_t {
unsigned type;
h2o_buf_t suffix;
};
struct st_h2o_access_logger_t {
h2o_logger_t super;
struct log_element_t *elements;
size_t num_elements;
int fd;
};
static struct log_element_t *compile_log_format(const char *fmt, size_t *_num_elements)
{
struct log_element_t *elements = NULL;
size_t fmt_len = strlen(fmt), num_elements = 0;
const char *pt = fmt;
/* suffix buffer is always guaranteed to be larger than the fmt + (sizeof('\n') - 1) (so that they would be no buffer overruns) */
#define NEW_ELEMENT(ty) \
do { \
elements = h2o_realloc(elements, sizeof(*elements) * (num_elements + 1)); \
elements[num_elements].type = ty; \
elements[num_elements].suffix = h2o_buf_init(h2o_malloc(fmt_len + 1), 0); \
++num_elements; \
} while (0)
while (*pt != '\0') {
if (*pt == '%') {
++pt;
if (*pt != '%') {
unsigned type = NUM_ELEMENT_TYPES;
switch (*pt++) {
#define TYPE_MAP(ch, ty) case ch: type = ty; break
TYPE_MAP('h', ELEMENT_TYPE_REMOTE_ADDR);
TYPE_MAP('l', ELEMENT_TYPE_LOGNAME);
TYPE_MAP('u', ELEMENT_TYPE_REMOTE_USER);
TYPE_MAP('t', ELEMENT_TYPE_TIMESTAMP);
TYPE_MAP('r', ELEMENT_TYPE_REQUEST_LINE);
TYPE_MAP('s', ELEMENT_TYPE_STATUS);
TYPE_MAP('b', ELEMENT_TYPE_BYTES_SENT);
#undef TYPE_MAP
default:
goto SyntaxError;
}
NEW_ELEMENT(type);
continue;
}
}
/* emit current char */
if (elements == NULL)
NEW_ELEMENT(ELEMENT_TYPE_EMPTY);
elements[num_elements - 1].suffix.base[elements[num_elements - 1].suffix.len++] = *pt++;
}
/* emit end-of-line */
if (elements == NULL)
NEW_ELEMENT(ELEMENT_TYPE_EMPTY);
elements[num_elements - 1].suffix.base[elements[num_elements - 1].suffix.len++] = '\n';
#undef NEW_ELEMENT
*_num_elements = num_elements;
return elements;
SyntaxError:
fprintf(stderr, "failed to compile log format: unknown escape sequence: %%%c\n", pt[-1]);
free(elements);
return NULL;
}
static inline char *append_safe_string(char *pos, const char *src, size_t len)
{
memcpy(pos, src, len);
return pos + len;
}
static char *append_unsafe_string(char *pos, const char *src, size_t len)
{
const char *src_end = src + len;
for (; src != src_end; ++src) {
if (' ' <= *src && *src < 0x7d && *src != '"') {
*pos++ = *src;
} else {
*pos++ = '\\';
*pos++ = 'x';
*pos++ = ("0123456789abcdef")[(*src >> 4) & 0xf];
*pos++ = ("0123456789abcdef")[*src & 0xf];
}
}
return pos;
}
static char *expand_line_buf(char *line, size_t cur_size, size_t required)
{
size_t new_size = cur_size;
/* determine the new size */
do {
new_size *= 2;
} while (new_size < required);
/* reallocate */
if (cur_size == LOG_ALLOCA_SIZE) {
char *newpt = h2o_malloc(new_size);
memcpy(newpt, line, cur_size);
line = newpt;
} else {
line = h2o_realloc(line, new_size);
}
return line;
}
static void log_access(h2o_logger_t *_self, h2o_req_t *req)
{
struct st_h2o_access_logger_t *self = (struct st_h2o_access_logger_t*)_self;
char *line, *pos, *line_end;
size_t element_index;
line = alloca(LOG_ALLOCA_SIZE);
pos = line;
line_end = line + LOG_ALLOCA_SIZE;
for (element_index = 0; element_index != self->num_elements; ++element_index) {
struct log_element_t *element = self->elements + element_index;
/* reserve capacity + suffix.len */
#define RESERVE(capacity) \
do { \
if ((capacity) + element->suffix.len > line_end - pos) { \
size_t off = pos - line; \
line = expand_line_buf(line, line_end - line, off + (capacity) + element->suffix.len); \
pos = line + off; \
} \
} while (0)
switch (element->type) {
case ELEMENT_TYPE_EMPTY:
RESERVE(0);
break;
case ELEMENT_TYPE_REMOTE_ADDR:
{
char hostname[NI_MAXHOST];
if (req->conn->peername.addr != NULL && req->conn->peername.addr->sa_family == AF_INET) {
struct sockaddr_in *sin = (void*)req->conn->peername.addr;
uint32_t addr;
RESERVE(sizeof("255.255.255.255") - 1);
addr = htonl(sin->sin_addr.s_addr);
pos += sprintf(pos, "%d.%d.%d.%d", addr >> 24, (addr >> 16) & 255, (addr >> 8) & 255, addr & 255);
} else if (req->conn->peername.addr != NULL
&& getnameinfo(req->conn->peername.addr, req->conn->peername.len, hostname, sizeof(hostname), NULL, 0, NI_NUMERICHOST)
== 0) {
size_t len = strlen(hostname);
RESERVE(len);
pos = append_safe_string(pos, hostname, len);
} else {
RESERVE(1);
*pos++ = '-';
}
}
break;
case ELEMENT_TYPE_LOGNAME:
case ELEMENT_TYPE_REMOTE_USER:
RESERVE(1);
*pos++ = '-';
break;
case ELEMENT_TYPE_TIMESTAMP:
RESERVE(H2O_TIMESTR_LOG_LEN + 2);
*pos++ = '[';
pos = append_safe_string(pos, req->processed_at.str->log, H2O_TIMESTR_LOG_LEN);
*pos++ = ']';
break;
case ELEMENT_TYPE_REQUEST_LINE:
RESERVE((req->method.len + req->path.len) * 4 + sizeof(" HTTP/1.2147483647") - 1);
pos = append_unsafe_string(pos, req->method.base, req->method.len);
*pos++ = ' ';
pos = append_unsafe_string(pos, req->path.base, req->path.len);
*pos++ = ' ';
if (req->version < 0x200) {
pos = append_safe_string(pos, H2O_STRLIT("HTTP/1."));
if ((req->version & 0xff) <= 9) {
*pos++ = '0' + (req->version & 0xff);
} else {
pos += sprintf(pos, "%d", req->version);
}
} else {
pos = append_safe_string(pos, H2O_STRLIT("HTTP/2"));
}
break;
case ELEMENT_TYPE_STATUS:
RESERVE(sizeof("2147483647") - 1);
pos += sprintf(pos, "%d", req->res.status);
break;
case ELEMENT_TYPE_BYTES_SENT:
RESERVE(sizeof("18446744073709551615") - 1);
pos += sprintf(pos, "%llu", (unsigned long long)req->bytes_sent);
break;
default:
assert(!"unknown type");
break;
}
#undef RESERVE
pos = append_safe_string(pos, element->suffix.base, element->suffix.len);
}
write(self->fd, line, pos - line);
if (line_end - line != LOG_ALLOCA_SIZE)
free(line);
}
static void dispose(h2o_logger_t *_self)
{
struct st_h2o_access_logger_t *self = (void*)_self;
size_t i;
for (i = 0; i != self->num_elements; ++i)
free(self->elements[i].suffix.base);
free(self->elements);
if (self->fd != -1)
close(self->fd);
}
h2o_logger_t *h2o_access_log_register(h2o_hostconf_t *host_config, const char *path, const char *fmt)
{
struct log_element_t *elements;
size_t num_elements;
int fd;
struct st_h2o_access_logger_t *self;
/* default to common log format */
if (fmt == NULL)
fmt = "%h %l %u %t \"%r\" %s %b";
if ((elements = compile_log_format(fmt, &num_elements)) == NULL)
return NULL;
/* open log file */
if (path[0] == '|') {
FILE *fp;
if ((fp = popen(path + 1, "w")) == NULL) {
fprintf(stderr, "failed to open log pipe to command:%s\n", path + 1);
return NULL;
}
fd = dup(fileno(fp));
fclose(fp);
if (fd == -1) {
fprintf(stderr, "failed to dup pipe fd:%s\n", strerror(errno));
return NULL;
}
} else {
if ((fd = open(path, O_CREAT | O_WRONLY | O_APPEND, 0644)) == -1) {
fprintf(stderr, "failed to open log file:%s:%s\n", path, strerror(errno));
return NULL;
}
}
/* register */
self = (void*)h2o_create_logger(host_config, sizeof(*self));
self->super.dispose = dispose;
self->super.log_access = log_access;
self->elements = elements;
self->num_elements = num_elements;
self->fd = fd;
return &self->super;
}
static int on_config(h2o_configurator_command_t *cmd, h2o_configurator_context_t *ctx, const char *file, yoml_t *node)
{
const char *path, *fmt = NULL;
switch (node->type) {
case YOML_TYPE_SCALAR:
path = node->data.scalar;
break;
case YOML_TYPE_MAPPING:
{
yoml_t *t;
/* get path */
if ((t = yoml_get(node, "path")) == NULL) {
h2o_config_print_error(cmd, file, node, "could not find mandatory key `path`");
return -1;
}
if (t->type != YOML_TYPE_SCALAR) {
h2o_config_print_error(cmd, file, t, "`path` must be scalar");
return -1;
}
path = t->data.scalar;
/* get format */
if ((t = yoml_get(node, "format")) != NULL) {
if (t->type != YOML_TYPE_SCALAR) {
h2o_config_print_error(cmd, file, t, "`format` must be a scalar");
return -1;
}
fmt = t->data.scalar;
}
}
break;
default:
h2o_config_print_error(cmd, file, node, "node must be a scalar or a mapping");
return -1;
}
h2o_access_log_register(ctx->hostconf, path, fmt);
return 0;
}
void h2o_access_log_register_configurator(h2o_globalconf_t *conf)
{
h2o_configurator_t *c = h2o_config_create_configurator(conf, sizeof(*c));
h2o_config_define_command(c, "access-log", H2O_CONFIGURATOR_FLAG_HOST,
on_config,
"path (and optionally the format) of the access log (default: none)",
" - if the value is a scalar, it is treated as the path of the log file",
" - if the value is a mapping, its `path` property is treated as the path",
" and `format` property is treated as the format",
" - if the path starts with `|`, the rest of the path is considered as a ",
" command pipe to which the logs should be emitted"
);
}