122e7fb62a5a562a3268f5de47ddc759ff12d410
[clogger.git] / ext / clogger_ext / clogger.c
blob122e7fb62a5a562a3268f5de47ddc759ff12d410
1 #include <ruby.h>
2 #ifdef HAVE_RUBY_IO_H
3 # include <ruby/io.h>
4 #else
5 # include <rubyio.h>
6 #endif
7 #include <assert.h>
8 #include <unistd.h>
9 #include <sys/types.h>
10 #include <sys/stat.h>
11 #include <sys/time.h>
12 #include <errno.h>
13 #ifdef HAVE_FCNTL_H
14 # include <fcntl.h>
15 #endif
16 #ifndef _POSIX_C_SOURCE
17 # define _POSIX_C_SOURCE 200112L
18 #endif
19 #include <time.h>
20 #include <stdlib.h>
21 #include <stdio.h> /* snprintf */
22 #include "ruby_1_9_compat.h"
23 #include "broken_system_compat.h"
24 #include "blocking_helpers.h"
27 * Availability of a monotonic clock needs to be detected at runtime
28 * since we could've been built on a different system than we're run
29 * under.
31 static clockid_t hopefully_CLOCK_MONOTONIC;
33 static void check_clock(void)
35 struct timespec now;
37 hopefully_CLOCK_MONOTONIC = CLOCK_MONOTONIC;
39 /* we can't check this reliably at compile time */
40 if (clock_gettime(CLOCK_MONOTONIC, &now) == 0)
41 return;
43 if (clock_gettime(CLOCK_REALTIME, &now) == 0) {
44 hopefully_CLOCK_MONOTONIC = CLOCK_REALTIME;
45 rb_warn("CLOCK_MONOTONIC not available, "
46 "falling back to CLOCK_REALTIME");
48 rb_warn("clock_gettime() totally broken, " \
49 "falling back to pure Ruby Clogger");
50 rb_raise(rb_eLoadError, "clock_gettime() broken");
53 static void clock_diff(struct timespec *a, const struct timespec *b)
55 a->tv_sec -= b->tv_sec;
56 a->tv_nsec -= b->tv_nsec;
57 if (a->tv_nsec < 0) {
58 --a->tv_sec;
59 a->tv_nsec += 1000000000;
63 /* give GCC hints for better branch prediction
64 * (we layout branches so that ASCII characters are handled faster) */
65 #if defined(__GNUC__) && (__GNUC__ >= 3)
66 # define likely(x) __builtin_expect (!!(x), 1)
67 # define unlikely(x) __builtin_expect (!!(x), 0)
68 #else
69 # define unlikely(x) (x)
70 # define likely(x) (x)
71 #endif
73 enum clogger_opcode {
74 CL_OP_LITERAL = 0,
75 CL_OP_REQUEST,
76 CL_OP_RESPONSE,
77 CL_OP_SPECIAL,
78 CL_OP_EVAL,
79 CL_OP_TIME_LOCAL,
80 CL_OP_TIME_UTC,
81 CL_OP_REQUEST_TIME,
82 CL_OP_TIME,
83 CL_OP_COOKIE
86 enum clogger_special {
87 CL_SP_body_bytes_sent = 0,
88 CL_SP_status,
89 CL_SP_request,
90 CL_SP_request_length,
91 CL_SP_response_length,
92 CL_SP_ip,
93 CL_SP_pid,
94 CL_SP_request_uri,
95 CL_SP_time_iso8601,
96 CL_SP_time_local,
97 CL_SP_time_utc
100 struct clogger {
101 VALUE app;
103 VALUE fmt_ops;
104 VALUE logger;
105 VALUE log_buf;
107 VALUE env;
108 VALUE cookies;
109 VALUE status;
110 VALUE headers;
111 VALUE body;
113 off_t body_bytes_sent;
114 struct timespec ts_start;
116 int fd;
117 int wrap_body;
118 int need_resp;
119 int reentrant; /* tri-state, -1:auto, 1/0 true/false */
122 static ID write_id;
123 static ID ltlt_id;
124 static ID call_id;
125 static ID close_id;
126 static ID to_i_id;
127 static ID to_s_id;
128 static ID size_id;
129 static ID sq_brace_id;
130 static ID new_id;
131 static ID to_path_id;
132 static ID to_io_id;
133 static ID respond_to_id;
134 static VALUE cClogger;
135 static VALUE mFormat;
136 static VALUE cHeaderHash;
138 /* common hash lookup keys */
139 static VALUE g_HTTP_X_FORWARDED_FOR;
140 static VALUE g_REMOTE_ADDR;
141 static VALUE g_REQUEST_METHOD;
142 static VALUE g_PATH_INFO;
143 static VALUE g_REQUEST_URI;
144 static VALUE g_QUERY_STRING;
145 static VALUE g_HTTP_VERSION;
146 static VALUE g_rack_errors;
147 static VALUE g_rack_input;
148 static VALUE g_rack_multithread;
149 static VALUE g_dash;
150 static VALUE g_space;
151 static VALUE g_question_mark;
152 static VALUE g_rack_request_cookie_hash;
154 #define LOG_BUF_INIT_SIZE 128
156 static void init_buffers(struct clogger *c)
158 c->log_buf = rb_str_buf_new(LOG_BUF_INIT_SIZE);
161 static inline int need_escape(unsigned c)
163 assert(c <= 0xff);
164 return !!(c == '\'' || c == '"' || c <= 0x1f || c >= 0x7f);
167 /* we are encoding-agnostic, clients can send us all sorts of junk */
168 static VALUE byte_xs(VALUE obj)
170 static const char esc[] = "0123456789ABCDEF";
171 unsigned char *new_ptr;
172 VALUE from = rb_obj_as_string(obj);
173 const unsigned char *ptr = (const unsigned char *)RSTRING_PTR(from);
174 long len = RSTRING_LEN(from);
175 long new_len = len;
176 VALUE rv;
178 for (; --len >= 0; ptr++) {
179 unsigned c = *ptr;
181 if (unlikely(need_escape(c)))
182 new_len += 3; /* { '\', 'x', 'X', 'X' } */
185 len = RSTRING_LEN(from);
186 if (new_len == len)
187 return from;
189 rv = rb_str_new(NULL, new_len);
190 new_ptr = (unsigned char *)RSTRING_PTR(rv);
191 ptr = (const unsigned char *)RSTRING_PTR(from);
192 for (; --len >= 0; ptr++) {
193 unsigned c = *ptr;
195 if (unlikely(need_escape(c))) {
196 *new_ptr++ = '\\';
197 *new_ptr++ = 'x';
198 *new_ptr++ = esc[c >> 4];
199 *new_ptr++ = esc[c & 0xf];
200 } else {
201 *new_ptr++ = c;
204 assert(RSTRING_PTR(rv)[RSTRING_LEN(rv)] == '\0');
206 RB_GC_GUARD(from);
207 return rv;
210 static void clogger_mark(void *ptr)
212 struct clogger *c = ptr;
214 rb_gc_mark(c->app);
215 rb_gc_mark(c->fmt_ops);
216 rb_gc_mark(c->logger);
217 rb_gc_mark(c->log_buf);
218 rb_gc_mark(c->env);
219 rb_gc_mark(c->cookies);
220 rb_gc_mark(c->status);
221 rb_gc_mark(c->headers);
222 rb_gc_mark(c->body);
225 static VALUE clogger_alloc(VALUE klass)
227 struct clogger *c;
229 return Data_Make_Struct(klass, struct clogger, clogger_mark, -1, c);
232 static struct clogger *clogger_get(VALUE self)
234 struct clogger *c;
236 Data_Get_Struct(self, struct clogger, c);
237 assert(c);
238 return c;
241 /* only for writing to regular files, not stupid crap like NFS */
242 static void write_full(int fd, const void *buf, size_t count)
244 ssize_t r;
245 unsigned long ubuf = (unsigned long)buf;
247 while (count > 0) {
248 r = write(fd, (void *)ubuf, count);
250 if ((size_t)r == count) { /* overwhelmingly likely */
251 return;
252 } else if (r > 0) {
253 count -= r;
254 ubuf += r;
255 } else {
256 if (errno == EINTR || errno == EAGAIN)
257 continue; /* poor souls on NFS and like: */
258 if (!errno)
259 errno = ENOSPC;
260 rb_sys_fail("write");
266 * allow us to use write_full() iff we detect a blocking file
267 * descriptor that wouldn't play nicely with Ruby threading/fibers
269 static int raw_fd(VALUE my_fd)
271 #if defined(HAVE_FCNTL) && defined(F_GETFL) && defined(O_NONBLOCK)
272 int fd;
273 int flags;
275 if (NIL_P(my_fd))
276 return -1;
277 fd = NUM2INT(my_fd);
279 flags = fcntl(fd, F_GETFL);
280 if (flags < 0)
281 rb_sys_fail("fcntl");
283 if (flags & O_NONBLOCK) {
284 struct stat sb;
286 if (fstat(fd, &sb) < 0)
287 return -1;
289 /* O_NONBLOCK is no-op for regular files: */
290 if (! S_ISREG(sb.st_mode))
291 return -1;
293 return fd;
294 #else /* platforms w/o fcntl/F_GETFL/O_NONBLOCK */
295 return -1;
296 #endif /* platforms w/o fcntl/F_GETFL/O_NONBLOCK */
299 /* :nodoc: */
300 static VALUE clogger_reentrant(VALUE self)
302 return clogger_get(self)->reentrant == 0 ? Qfalse : Qtrue;
305 /* :nodoc: */
306 static VALUE clogger_wrap_body(VALUE self)
308 return clogger_get(self)->wrap_body == 0 ? Qfalse : Qtrue;
311 static void append_status(struct clogger *c)
313 char buf[sizeof("999")];
314 int nr;
315 VALUE status = c->status;
317 if (TYPE(status) != T_FIXNUM) {
318 status = rb_funcall(status, to_i_id, 0);
319 /* no way it's a valid status code (at least not HTTP/1.1) */
320 if (TYPE(status) != T_FIXNUM) {
321 rb_str_buf_append(c->log_buf, g_dash);
322 return;
326 nr = FIX2INT(status);
327 if (nr >= 100 && nr <= 999) {
328 nr = snprintf(buf, sizeof(buf), "%03d", nr);
329 assert(nr == 3);
330 rb_str_buf_cat(c->log_buf, buf, nr);
331 } else {
332 /* raise?, swap for 500? */
333 rb_str_buf_append(c->log_buf, g_dash);
337 /* this is Rack 1.0.0-compatible, won't try to parse commas in XFF */
338 static void append_ip(struct clogger *c)
340 VALUE env = c->env;
341 VALUE tmp = rb_hash_aref(env, g_HTTP_X_FORWARDED_FOR);
343 if (NIL_P(tmp)) {
344 /* can't be faked on any real server, so no escape */
345 tmp = rb_hash_aref(env, g_REMOTE_ADDR);
346 if (NIL_P(tmp))
347 tmp = g_dash;
348 } else {
349 tmp = byte_xs(tmp);
351 rb_str_buf_append(c->log_buf, tmp);
354 static void append_body_bytes_sent(struct clogger *c)
356 char buf[(sizeof(off_t) * 8) / 3 + 1];
357 const char *fmt = sizeof(off_t) == sizeof(long) ? "%ld" : "%lld";
358 int nr = snprintf(buf, sizeof(buf), fmt, c->body_bytes_sent);
360 assert(nr > 0 && nr < (int)sizeof(buf));
361 rb_str_buf_cat(c->log_buf, buf, nr);
364 static void append_ts(struct clogger *c, VALUE op, struct timespec *ts)
366 char buf[sizeof(".000000") + ((sizeof(ts->tv_sec) * 8) / 3)];
367 int nr;
368 char *fmt = RSTRING_PTR(rb_ary_entry(op, 1));
369 int ndiv = NUM2INT(rb_ary_entry(op, 2));
370 int usec = ts->tv_nsec / 1000;
372 nr = snprintf(buf, sizeof(buf), fmt,
373 (int)ts->tv_sec, (int)(usec / ndiv));
374 assert(nr > 0 && nr < (int)sizeof(buf));
375 rb_str_buf_cat(c->log_buf, buf, nr);
378 static void append_request_time_fmt(struct clogger *c, VALUE op)
380 struct timespec now;
382 clock_gettime(hopefully_CLOCK_MONOTONIC, &now);
383 clock_diff(&now, &c->ts_start);
384 append_ts(c, op, &now);
387 static void append_time_fmt(struct clogger *c, VALUE op)
389 struct timespec now;
390 int r = clock_gettime(CLOCK_REALTIME, &now);
392 if (unlikely(r != 0))
393 rb_sys_fail("clock_gettime(CLOCK_REALTIME)");
394 append_ts(c, op, &now);
397 static void append_request_uri(struct clogger *c)
399 VALUE tmp;
401 tmp = rb_hash_aref(c->env, g_REQUEST_URI);
402 if (NIL_P(tmp)) {
403 tmp = rb_hash_aref(c->env, g_PATH_INFO);
404 if (!NIL_P(tmp))
405 rb_str_buf_append(c->log_buf, byte_xs(tmp));
406 tmp = rb_hash_aref(c->env, g_QUERY_STRING);
407 if (!NIL_P(tmp) && RSTRING_LEN(tmp) != 0) {
408 rb_str_buf_append(c->log_buf, g_question_mark);
409 rb_str_buf_append(c->log_buf, byte_xs(tmp));
411 } else {
412 rb_str_buf_append(c->log_buf, byte_xs(tmp));
416 static void append_request(struct clogger *c)
418 VALUE tmp;
420 /* REQUEST_METHOD doesn't need escaping, Rack::Lint governs it */
421 tmp = rb_hash_aref(c->env, g_REQUEST_METHOD);
422 if (!NIL_P(tmp))
423 rb_str_buf_append(c->log_buf, tmp);
425 rb_str_buf_append(c->log_buf, g_space);
427 append_request_uri(c);
429 /* HTTP_VERSION can be injected by malicious clients */
430 tmp = rb_hash_aref(c->env, g_HTTP_VERSION);
431 if (!NIL_P(tmp)) {
432 rb_str_buf_append(c->log_buf, g_space);
433 rb_str_buf_append(c->log_buf, byte_xs(tmp));
437 static void append_request_length(struct clogger *c)
439 VALUE tmp = rb_hash_aref(c->env, g_rack_input);
440 if (NIL_P(tmp)) {
441 rb_str_buf_append(c->log_buf, g_dash);
442 } else {
443 tmp = rb_funcall(tmp, size_id, 0);
444 rb_str_buf_append(c->log_buf, rb_funcall(tmp, to_s_id, 0));
448 static long local_gmtoffset(struct tm *tm)
450 time_t t = time(NULL);
452 tzset();
453 localtime_r(&t, tm);
456 * HAVE_STRUCT_TM_TM_GMTOFF may be defined in Ruby headers
457 * HAVE_ST_TM_GMTOFF is defined ourselves.
459 #if defined(HAVE_STRUCT_TM_TM_GMTOFF) || defined(HAVE_ST_TM_GMTOFF)
460 return tm->tm_gmtoff / 60;
461 #else
462 return -(tm->tm_isdst ? timezone - 3600 : timezone) / 60;
463 #endif
466 static void append_time_iso8601(struct clogger *c)
468 char buf[sizeof("1970-01-01T00:00:00+00:00")];
469 struct tm tm;
470 int nr;
471 long gmtoff = local_gmtoffset(&tm);
473 nr = snprintf(buf, sizeof(buf),
474 "%4d-%02d-%02dT%02d:%02d:%02d%c%02d:%02d",
475 tm.tm_year + 1900, tm.tm_mon + 1,
476 tm.tm_mday, tm.tm_hour,
477 tm.tm_min, tm.tm_sec,
478 gmtoff < 0 ? '-' : '+',
479 abs(gmtoff / 60), abs(gmtoff % 60));
480 assert(nr == (sizeof(buf) - 1) && "snprintf fail");
481 rb_str_buf_cat(c->log_buf, buf, sizeof(buf) - 1);
484 static const char months[] = "Jan\0Feb\0Mar\0Apr\0May\0Jun\0"
485 "Jul\0Aug\0Sep\0Oct\0Nov\0Dec";
487 static void append_time_local(struct clogger *c)
489 char buf[sizeof("01/Jan/1970:00:00:00 +0000")];
490 struct tm tm;
491 int nr;
492 long gmtoff = local_gmtoffset(&tm);
494 nr = snprintf(buf, sizeof(buf),
495 "%02d/%s/%d:%02d:%02d:%02d %c%02d%02d",
496 tm.tm_mday, months + (tm.tm_mon * sizeof("Jan")),
497 tm.tm_year + 1900, tm.tm_hour,
498 tm.tm_min, tm.tm_sec,
499 gmtoff < 0 ? '-' : '+',
500 abs(gmtoff / 60), abs(gmtoff % 60));
501 assert(nr == (sizeof(buf) - 1) && "snprintf fail");
502 rb_str_buf_cat(c->log_buf, buf, sizeof(buf) - 1);
505 static void append_time_utc(struct clogger *c)
507 char buf[sizeof("01/Jan/1970:00:00:00 +0000")];
508 struct tm tm;
509 int nr;
510 time_t t = time(NULL);
512 gmtime_r(&t, &tm);
513 nr = snprintf(buf, sizeof(buf),
514 "%02d/%s/%d:%02d:%02d:%02d +0000",
515 tm.tm_mday, months + (tm.tm_mon * sizeof("Jan")),
516 tm.tm_year + 1900, tm.tm_hour,
517 tm.tm_min, tm.tm_sec);
518 assert(nr == (sizeof(buf) - 1) && "snprintf fail");
519 rb_str_buf_cat(c->log_buf, buf, sizeof(buf) - 1);
522 static void
523 append_time(struct clogger *c, enum clogger_opcode op, VALUE fmt, VALUE buf)
525 char *buf_ptr = RSTRING_PTR(buf);
526 size_t buf_size = RSTRING_LEN(buf) + 1; /* "\0" */
527 size_t nr;
528 struct tm tmp;
529 time_t t = time(NULL);
531 if (op == CL_OP_TIME_LOCAL)
532 localtime_r(&t, &tmp);
533 else if (op == CL_OP_TIME_UTC)
534 gmtime_r(&t, &tmp);
535 else
536 assert(0 && "unknown op");
538 nr = strftime(buf_ptr, buf_size, RSTRING_PTR(fmt), &tmp);
539 assert(nr < buf_size && "time format too small!");
540 rb_str_buf_cat(c->log_buf, buf_ptr, nr);
543 static void append_pid(struct clogger *c)
545 char buf[(sizeof(pid_t) * 8) / 3 + 1];
546 int nr = snprintf(buf, sizeof(buf), "%d", (int)getpid());
548 assert(nr > 0 && nr < (int)sizeof(buf));
549 rb_str_buf_cat(c->log_buf, buf, nr);
552 static void append_eval(struct clogger *c, VALUE str)
554 int state = -1;
555 VALUE rv = rb_eval_string_protect(RSTRING_PTR(str), &state);
557 rv = state == 0 ? rb_obj_as_string(rv) : g_dash;
558 rb_str_buf_append(c->log_buf, rv);
561 static void append_cookie(struct clogger *c, VALUE key)
563 VALUE cookie;
565 if (c->cookies == Qfalse)
566 c->cookies = rb_hash_aref(c->env, g_rack_request_cookie_hash);
568 if (NIL_P(c->cookies)) {
569 cookie = g_dash;
570 } else {
571 cookie = rb_hash_aref(c->cookies, key);
572 cookie = NIL_P(cookie) ? g_dash : byte_xs(cookie);
574 rb_str_buf_append(c->log_buf, cookie);
577 static void append_request_env(struct clogger *c, VALUE key)
579 VALUE tmp = rb_hash_aref(c->env, key);
581 tmp = NIL_P(tmp) ? g_dash : byte_xs(tmp);
582 rb_str_buf_append(c->log_buf, tmp);
585 static void append_response(struct clogger *c, VALUE key)
587 VALUE v;
589 assert(rb_obj_is_kind_of(c->headers, cHeaderHash) && "not HeaderHash");
591 v = rb_funcall(c->headers, sq_brace_id, 1, key);
592 v = NIL_P(v) ? g_dash : byte_xs(v);
593 rb_str_buf_append(c->log_buf, v);
596 static void special_var(struct clogger *c, enum clogger_special var)
598 switch (var) {
599 case CL_SP_body_bytes_sent:
600 append_body_bytes_sent(c);
601 break;
602 case CL_SP_status:
603 append_status(c);
604 break;
605 case CL_SP_request:
606 append_request(c);
607 break;
608 case CL_SP_request_length:
609 append_request_length(c);
610 break;
611 case CL_SP_response_length:
612 if (c->body_bytes_sent == 0)
613 rb_str_buf_append(c->log_buf, g_dash);
614 else
615 append_body_bytes_sent(c);
616 break;
617 case CL_SP_ip:
618 append_ip(c);
619 break;
620 case CL_SP_pid:
621 append_pid(c);
622 break;
623 case CL_SP_request_uri:
624 append_request_uri(c);
625 break;
626 case CL_SP_time_iso8601:
627 append_time_iso8601(c);
628 break;
629 case CL_SP_time_local:
630 append_time_local(c);
631 break;
632 case CL_SP_time_utc:
633 append_time_utc(c);
637 static VALUE cwrite(struct clogger *c)
639 const VALUE ops = c->fmt_ops;
640 long i;
641 long len = RARRAY_LEN(ops);
642 VALUE dst = c->log_buf;
644 rb_str_set_len(dst, 0);
646 for (i = 0; i < len; i++) {
647 VALUE op = rb_ary_entry(ops, i);
648 enum clogger_opcode opcode = FIX2INT(rb_ary_entry(op, 0));
649 VALUE op1 = rb_ary_entry(op, 1);
651 switch (opcode) {
652 case CL_OP_LITERAL:
653 rb_str_buf_append(dst, op1);
654 break;
655 case CL_OP_REQUEST:
656 append_request_env(c, op1);
657 break;
658 case CL_OP_RESPONSE:
659 append_response(c, op1);
660 break;
661 case CL_OP_SPECIAL:
662 special_var(c, FIX2INT(op1));
663 break;
664 case CL_OP_EVAL:
665 append_eval(c, op1);
666 break;
667 case CL_OP_TIME_LOCAL:
668 case CL_OP_TIME_UTC: {
669 VALUE arg2 = rb_ary_entry(op, 2);
670 append_time(c, opcode, op1, arg2);
672 break;
673 case CL_OP_REQUEST_TIME:
674 append_request_time_fmt(c, op);
675 break;
676 case CL_OP_TIME:
677 append_time_fmt(c, op);
678 break;
679 case CL_OP_COOKIE:
680 append_cookie(c, op1);
681 break;
685 if (c->fd >= 0) {
686 write_full(c->fd, RSTRING_PTR(dst), RSTRING_LEN(dst));
687 } else {
688 VALUE logger = c->logger;
690 if (NIL_P(logger)) {
691 logger = rb_hash_aref(c->env, g_rack_errors);
692 rb_funcall(logger, write_id, 1, dst);
693 } else {
694 rb_funcall(logger, ltlt_id, 1, dst);
698 return Qnil;
701 static VALUE clogger_write(VALUE self)
703 return cwrite(clogger_get(self));
706 static void init_logger(struct clogger *c, VALUE path)
708 ID id;
710 if (!NIL_P(path) && !NIL_P(c->logger))
711 rb_raise(rb_eArgError, ":logger and :path are independent");
712 if (!NIL_P(path)) {
713 VALUE ab = rb_str_new2("ab");
714 id = rb_intern("open");
715 c->logger = rb_funcall(rb_cFile, id, 2, path, ab);
718 id = rb_intern("sync=");
719 if (rb_respond_to(c->logger, id))
720 rb_funcall(c->logger, id, 1, Qtrue);
722 id = rb_intern("fileno");
723 if (rb_respond_to(c->logger, id))
724 c->fd = raw_fd(rb_funcall(c->logger, id, 0));
728 * call-seq:
729 * Clogger.new(app, :logger => $stderr, :format => string) => obj
731 * Creates a new Clogger object that wraps +app+. +:logger+ may
732 * be any object that responds to the "<<" method with a string argument.
733 * Instead of +:logger+, +:path+ may be specified to be a :path of a File
734 * that will be opened in append mode.
736 static VALUE clogger_init(int argc, VALUE *argv, VALUE self)
738 struct clogger *c = clogger_get(self);
739 VALUE o = Qnil;
740 VALUE fmt = rb_const_get(mFormat, rb_intern("Common"));
742 rb_scan_args(argc, argv, "11", &c->app, &o);
743 c->fd = -1;
744 c->logger = Qnil;
745 c->reentrant = -1; /* auto-detect */
747 if (TYPE(o) == T_HASH) {
748 VALUE tmp;
750 tmp = rb_hash_aref(o, ID2SYM(rb_intern("path")));
751 c->logger = rb_hash_aref(o, ID2SYM(rb_intern("logger")));
752 init_logger(c, tmp);
754 tmp = rb_hash_aref(o, ID2SYM(rb_intern("format")));
755 if (!NIL_P(tmp))
756 fmt = tmp;
758 tmp = rb_hash_aref(o, ID2SYM(rb_intern("reentrant")));
759 switch (TYPE(tmp)) {
760 case T_TRUE:
761 c->reentrant = 1;
762 break;
763 case T_FALSE:
764 c->reentrant = 0;
765 case T_NIL:
766 break;
767 default:
768 rb_raise(rb_eArgError, ":reentrant must be boolean");
772 init_buffers(c);
773 c->fmt_ops = rb_funcall(self, rb_intern("compile_format"), 2, fmt, o);
775 if (Qtrue == rb_funcall(self, rb_intern("need_response_headers?"),
776 1, c->fmt_ops))
777 c->need_resp = 1;
778 if (Qtrue == rb_funcall(self, rb_intern("need_wrap_body?"),
779 1, c->fmt_ops))
780 c->wrap_body = 1;
782 return self;
785 static VALUE body_iter_i(VALUE str, VALUE self)
787 struct clogger *c = clogger_get(self);
789 str = rb_obj_as_string(str);
790 c->body_bytes_sent += RSTRING_LEN(str);
792 return rb_yield(str);
795 static VALUE body_close(VALUE self)
797 struct clogger *c = clogger_get(self);
799 if (rb_respond_to(c->body, close_id))
800 return rb_funcall(c->body, close_id, 0);
801 return Qnil;
805 * call-seq:
806 * clogger.each { |part| socket.write(part) }
808 * Delegates the body#each call to the underlying +body+ object
809 * while tracking the number of bytes yielded. This will log
810 * the request.
812 static VALUE clogger_each(VALUE self)
814 struct clogger *c = clogger_get(self);
816 rb_need_block();
817 c->body_bytes_sent = 0;
818 rb_iterate(rb_each, c->body, body_iter_i, self);
820 return self;
824 * call-seq:
825 * clogger.close
827 * Delegates the body#close call to the underlying +body+ object.
828 * This is only used when Clogger is wrapping the +body+ of a Rack
829 * response and should be automatically called by the web server.
831 static VALUE clogger_close(VALUE self)
834 return rb_ensure(body_close, self, clogger_write, self);
837 /* :nodoc: */
838 static VALUE clogger_fileno(VALUE self)
840 struct clogger *c = clogger_get(self);
842 return c->fd < 0 ? Qnil : INT2NUM(c->fd);
845 static VALUE ccall(struct clogger *c, VALUE env)
847 VALUE rv;
849 clock_gettime(hopefully_CLOCK_MONOTONIC, &c->ts_start);
850 c->env = env;
851 c->cookies = Qfalse;
852 rv = rb_funcall(c->app, call_id, 1, env);
853 if (TYPE(rv) == T_ARRAY && RARRAY_LEN(rv) == 3) {
854 c->status = rb_ary_entry(rv, 0);
855 c->headers = rb_ary_entry(rv, 1);
856 c->body = rb_ary_entry(rv, 2);
858 rv = rb_ary_dup(rv);
859 if (c->need_resp &&
860 ! rb_obj_is_kind_of(c->headers, cHeaderHash)) {
861 c->headers = rb_funcall(cHeaderHash, new_id, 1,
862 c->headers);
863 rb_ary_store(rv, 1, c->headers);
865 } else {
866 VALUE tmp = rb_inspect(rv);
868 c->status = INT2FIX(500);
869 c->headers = c->body = rb_ary_new();
870 cwrite(c);
871 rb_raise(rb_eTypeError,
872 "app response not a 3 element Array: %s",
873 RSTRING_PTR(tmp));
874 RB_GC_GUARD(tmp);
877 return rv;
881 * call-seq:
882 * clogger.call(env) => [ status, headers, body ]
884 * calls the wrapped Rack application with +env+, returns the
885 * [status, headers, body ] tuplet required by Rack.
887 static VALUE clogger_call(VALUE self, VALUE env)
889 struct clogger *c = clogger_get(self);
890 VALUE rv;
892 env = rb_check_convert_type(env, T_HASH, "Hash", "to_hash");
894 if (c->wrap_body) {
895 /* XXX: we assume the existence of the GVL here: */
896 if (c->reentrant < 0) {
897 VALUE tmp = rb_hash_aref(env, g_rack_multithread);
898 c->reentrant = Qfalse == tmp ? 0 : 1;
901 if (c->reentrant) {
902 self = rb_obj_dup(self);
903 c = clogger_get(self);
906 rv = ccall(c, env);
907 assert(!OBJ_FROZEN(rv) && "frozen response array");
908 rb_ary_store(rv, 2, self);
910 return rv;
913 rv = ccall(c, env);
914 cwrite(c);
916 return rv;
919 static void duplicate_buffers(VALUE ops)
921 long i;
922 long len = RARRAY_LEN(ops);
924 for (i = 0; i < len; i++) {
925 VALUE op = rb_ary_entry(ops, i);
926 enum clogger_opcode opcode = FIX2INT(rb_ary_entry(op, 0));
928 if (opcode == CL_OP_TIME_LOCAL || opcode == CL_OP_TIME_UTC) {
929 VALUE buf = rb_ary_entry(op, 2);
930 Check_Type(buf, T_STRING);
931 buf = rb_str_dup(buf);
932 rb_str_modify(buf); /* trigger copy-on-write */
933 rb_ary_store(op, 2, buf);
938 /* :nodoc: */
939 static VALUE clogger_init_copy(VALUE clone, VALUE orig)
941 struct clogger *a = clogger_get(orig);
942 struct clogger *b = clogger_get(clone);
944 memcpy(b, a, sizeof(struct clogger));
945 init_buffers(b);
946 duplicate_buffers(b->fmt_ops);
948 return clone;
951 #define CONST_GLOBAL_STR2(var, val) do { \
952 g_##var = rb_obj_freeze(rb_str_new(val, sizeof(val) - 1)); \
953 rb_global_variable(&g_##var); \
954 } while (0)
956 #define CONST_GLOBAL_STR(val) CONST_GLOBAL_STR2(val, #val)
959 * call-seq:
960 * clogger.respond_to?(:to_path) => true or false
961 * clogger.respond_to?(:close) => true
963 * used to delegate +:to_path+ checks for Rack webservers that optimize
964 * static file serving
966 static VALUE respond_to(VALUE self, VALUE method)
968 struct clogger *c = clogger_get(self);
969 ID id = rb_to_id(method);
971 if (close_id == id)
972 return Qtrue;
973 return rb_respond_to(c->body, id);
977 * call-seq:
978 * clogger.to_path
980 * used to proxy +:to_path+ method calls to the wrapped response body.
982 static VALUE to_path(VALUE self)
984 struct clogger *c = clogger_get(self);
985 struct stat sb;
986 int rv;
987 VALUE path = rb_funcall(c->body, to_path_id, 0);
989 /* try to avoid an extra path lookup */
990 if (rb_respond_to(c->body, to_io_id)) {
991 rv = fstat(my_fileno(c->body), &sb);
992 } else {
993 const char *cpath = StringValueCStr(path);
994 unsigned devfd;
996 * Rainbows! can use "/dev/fd/%u" in to_path output to avoid
997 * extra open() syscalls, too.
999 if (sscanf(cpath, "/dev/fd/%u", &devfd) == 1)
1000 rv = fstat((int)devfd, &sb);
1001 else
1002 rv = stat(cpath, &sb);
1006 * calling this method implies the web server will bypass
1007 * the each method where body_bytes_sent is calculated,
1008 * so we stat and set that value here.
1010 c->body_bytes_sent = rv == 0 ? sb.st_size : 0;
1011 return path;
1015 * call-seq:
1016 * clogger.to_io
1018 * used to proxy +:to_io+ method calls to the wrapped response body.
1020 static VALUE to_io(VALUE self)
1022 struct clogger *c = clogger_get(self);
1023 struct stat sb;
1024 VALUE io = rb_convert_type(c->body, T_FILE, "IO", "to_io");
1026 if (fstat(my_fileno(io), &sb) == 0)
1027 c->body_bytes_sent = sb.st_size;
1029 return io;
1032 /* :nodoc: */
1033 static VALUE body(VALUE self)
1035 return clogger_get(self)->body;
1038 void Init_clogger_ext(void)
1040 VALUE tmp;
1042 check_clock();
1044 write_id = rb_intern("write");
1045 ltlt_id = rb_intern("<<");
1046 call_id = rb_intern("call");
1047 close_id = rb_intern("close");
1048 to_i_id = rb_intern("to_i");
1049 to_s_id = rb_intern("to_s");
1050 size_id = rb_intern("size");
1051 sq_brace_id = rb_intern("[]");
1052 new_id = rb_intern("new");
1053 to_path_id = rb_intern("to_path");
1054 to_io_id = rb_intern("to_io");
1055 respond_to_id = rb_intern("respond_to?");
1056 cClogger = rb_define_class("Clogger", rb_cObject);
1057 mFormat = rb_define_module_under(cClogger, "Format");
1058 rb_define_alloc_func(cClogger, clogger_alloc);
1059 rb_define_method(cClogger, "initialize", clogger_init, -1);
1060 rb_define_method(cClogger, "initialize_copy", clogger_init_copy, 1);
1061 rb_define_method(cClogger, "call", clogger_call, 1);
1062 rb_define_method(cClogger, "each", clogger_each, 0);
1063 rb_define_method(cClogger, "close", clogger_close, 0);
1064 rb_define_method(cClogger, "fileno", clogger_fileno, 0);
1065 rb_define_method(cClogger, "wrap_body?", clogger_wrap_body, 0);
1066 rb_define_method(cClogger, "reentrant?", clogger_reentrant, 0);
1067 rb_define_method(cClogger, "to_path", to_path, 0);
1068 rb_define_method(cClogger, "to_io", to_io, 0);
1069 rb_define_method(cClogger, "respond_to?", respond_to, 1);
1070 rb_define_method(cClogger, "body", body, 0);
1071 CONST_GLOBAL_STR(REMOTE_ADDR);
1072 CONST_GLOBAL_STR(HTTP_X_FORWARDED_FOR);
1073 CONST_GLOBAL_STR(REQUEST_METHOD);
1074 CONST_GLOBAL_STR(PATH_INFO);
1075 CONST_GLOBAL_STR(QUERY_STRING);
1076 CONST_GLOBAL_STR(REQUEST_URI);
1077 CONST_GLOBAL_STR(HTTP_VERSION);
1078 CONST_GLOBAL_STR2(rack_errors, "rack.errors");
1079 CONST_GLOBAL_STR2(rack_input, "rack.input");
1080 CONST_GLOBAL_STR2(rack_multithread, "rack.multithread");
1081 CONST_GLOBAL_STR2(dash, "-");
1082 CONST_GLOBAL_STR2(space, " ");
1083 CONST_GLOBAL_STR2(question_mark, "?");
1084 CONST_GLOBAL_STR2(rack_request_cookie_hash, "rack.request.cookie_hash");
1086 tmp = rb_const_get(rb_cObject, rb_intern("Rack"));
1087 tmp = rb_const_get(tmp, rb_intern("Utils"));
1088 cHeaderHash = rb_const_get(tmp, rb_intern("HeaderHash"));