test case to simulate Rack::BodyProxy usage pattern
[clogger.git] / ext / clogger_ext / clogger.c
blob857ed9aea2271c8ff19fd83c0084f0a85646cf14
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 ltlt_id;
123 static ID call_id;
124 static ID each_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_str(VALUE from)
170 static const char esc[] = "0123456789ABCDEF";
171 unsigned char *new_ptr;
172 unsigned char *ptr = (unsigned char *)RSTRING_PTR(from);
173 long len = RSTRING_LEN(from);
174 long new_len = len;
175 VALUE rv;
177 for (; --len >= 0; ptr++) {
178 unsigned c = *ptr;
180 if (unlikely(need_escape(c)))
181 new_len += 3; /* { '\', 'x', 'X', 'X' } */
184 len = RSTRING_LEN(from);
185 if (new_len == len)
186 return from;
188 rv = rb_str_new(NULL, new_len);
189 new_ptr = (unsigned char *)RSTRING_PTR(rv);
190 ptr = (unsigned char *)RSTRING_PTR(from);
191 for (; --len >= 0; ptr++) {
192 unsigned c = *ptr;
194 if (unlikely(need_escape(c))) {
195 *new_ptr++ = '\\';
196 *new_ptr++ = 'x';
197 *new_ptr++ = esc[c >> 4];
198 *new_ptr++ = esc[c & 0xf];
199 } else {
200 *new_ptr++ = c;
203 assert(RSTRING_PTR(rv)[RSTRING_LEN(rv)] == '\0');
205 return rv;
208 static VALUE byte_xs(VALUE from)
210 return byte_xs_str(rb_obj_as_string(from));
213 static void clogger_mark(void *ptr)
215 struct clogger *c = ptr;
217 rb_gc_mark(c->app);
218 rb_gc_mark(c->fmt_ops);
219 rb_gc_mark(c->logger);
220 rb_gc_mark(c->log_buf);
221 rb_gc_mark(c->env);
222 rb_gc_mark(c->cookies);
223 rb_gc_mark(c->status);
224 rb_gc_mark(c->headers);
225 rb_gc_mark(c->body);
228 static VALUE clogger_alloc(VALUE klass)
230 struct clogger *c;
232 return Data_Make_Struct(klass, struct clogger, clogger_mark, -1, c);
235 static struct clogger *clogger_get(VALUE self)
237 struct clogger *c;
239 Data_Get_Struct(self, struct clogger, c);
240 assert(c);
241 return c;
244 /* only for writing to regular files, not stupid crap like NFS */
245 static void write_full(int fd, const void *buf, size_t count)
247 ssize_t r;
248 unsigned long ubuf = (unsigned long)buf;
250 while (count > 0) {
251 r = write(fd, (void *)ubuf, count);
253 if ((size_t)r == count) { /* overwhelmingly likely */
254 return;
255 } else if (r > 0) {
256 count -= r;
257 ubuf += r;
258 } else {
259 if (errno == EINTR || errno == EAGAIN)
260 continue; /* poor souls on NFS and like: */
261 if (!errno)
262 errno = ENOSPC;
263 rb_sys_fail("write");
269 * allow us to use write_full() iff we detect a blocking file
270 * descriptor that wouldn't play nicely with Ruby threading/fibers
272 static int raw_fd(VALUE my_fd)
274 #if defined(HAVE_FCNTL) && defined(F_GETFL) && defined(O_NONBLOCK)
275 int fd;
276 int flags;
278 if (NIL_P(my_fd))
279 return -1;
280 fd = NUM2INT(my_fd);
282 flags = fcntl(fd, F_GETFL);
283 if (flags < 0)
284 rb_sys_fail("fcntl");
286 if (flags & O_NONBLOCK) {
287 struct stat sb;
289 if (fstat(fd, &sb) < 0)
290 return -1;
292 /* O_NONBLOCK is no-op for regular files: */
293 if (! S_ISREG(sb.st_mode))
294 return -1;
296 return fd;
297 #else /* platforms w/o fcntl/F_GETFL/O_NONBLOCK */
298 return -1;
299 #endif /* platforms w/o fcntl/F_GETFL/O_NONBLOCK */
302 /* :nodoc: */
303 static VALUE clogger_reentrant(VALUE self)
305 return clogger_get(self)->reentrant == 0 ? Qfalse : Qtrue;
308 /* :nodoc: */
309 static VALUE clogger_wrap_body(VALUE self)
311 return clogger_get(self)->wrap_body == 0 ? Qfalse : Qtrue;
314 static void append_status(struct clogger *c)
316 char buf[sizeof("999")];
317 int nr;
318 VALUE status = c->status;
320 if (TYPE(status) != T_FIXNUM) {
321 status = rb_funcall(status, to_i_id, 0);
322 /* no way it's a valid status code (at least not HTTP/1.1) */
323 if (TYPE(status) != T_FIXNUM) {
324 rb_str_buf_append(c->log_buf, g_dash);
325 return;
329 nr = FIX2INT(status);
330 if (nr >= 100 && nr <= 999) {
331 nr = snprintf(buf, sizeof(buf), "%03d", nr);
332 assert(nr == 3);
333 rb_str_buf_cat(c->log_buf, buf, nr);
334 } else {
335 /* raise?, swap for 500? */
336 rb_str_buf_append(c->log_buf, g_dash);
340 /* this is Rack 1.0.0-compatible, won't try to parse commas in XFF */
341 static void append_ip(struct clogger *c)
343 VALUE env = c->env;
344 VALUE tmp = rb_hash_aref(env, g_HTTP_X_FORWARDED_FOR);
346 if (NIL_P(tmp)) {
347 /* can't be faked on any real server, so no escape */
348 tmp = rb_hash_aref(env, g_REMOTE_ADDR);
349 if (NIL_P(tmp))
350 tmp = g_dash;
351 } else {
352 tmp = byte_xs(tmp);
354 rb_str_buf_append(c->log_buf, tmp);
357 static void append_body_bytes_sent(struct clogger *c)
359 char buf[(sizeof(off_t) * 8) / 3 + 1];
360 const char *fmt = sizeof(off_t) == sizeof(long) ? "%ld" : "%lld";
361 int nr = snprintf(buf, sizeof(buf), fmt, c->body_bytes_sent);
363 assert(nr > 0 && nr < (int)sizeof(buf));
364 rb_str_buf_cat(c->log_buf, buf, nr);
367 static void append_ts(struct clogger *c, const VALUE *op, struct timespec *ts)
369 char buf[sizeof(".000000") + ((sizeof(ts->tv_sec) * 8) / 3)];
370 int nr;
371 char *fmt = RSTRING_PTR(op[1]);
372 int ndiv = NUM2INT(op[2]);
373 int usec = ts->tv_nsec / 1000;
375 nr = snprintf(buf, sizeof(buf), fmt,
376 (int)ts->tv_sec, (int)(usec / ndiv));
377 assert(nr > 0 && nr < (int)sizeof(buf));
378 rb_str_buf_cat(c->log_buf, buf, nr);
381 static void append_request_time_fmt(struct clogger *c, const VALUE *op)
383 struct timespec now;
385 clock_gettime(hopefully_CLOCK_MONOTONIC, &now);
386 clock_diff(&now, &c->ts_start);
387 append_ts(c, op, &now);
390 static void append_time_fmt(struct clogger *c, const VALUE *op)
392 struct timespec now;
393 int r = clock_gettime(CLOCK_REALTIME, &now);
395 if (unlikely(r != 0))
396 rb_sys_fail("clock_gettime(CLOCK_REALTIME)");
397 append_ts(c, op, &now);
400 static void append_request_uri(struct clogger *c)
402 VALUE tmp;
404 tmp = rb_hash_aref(c->env, g_REQUEST_URI);
405 if (NIL_P(tmp)) {
406 tmp = rb_hash_aref(c->env, g_PATH_INFO);
407 if (!NIL_P(tmp))
408 rb_str_buf_append(c->log_buf, byte_xs(tmp));
409 tmp = rb_hash_aref(c->env, g_QUERY_STRING);
410 if (!NIL_P(tmp) && RSTRING_LEN(tmp) != 0) {
411 rb_str_buf_append(c->log_buf, g_question_mark);
412 rb_str_buf_append(c->log_buf, byte_xs(tmp));
414 } else {
415 rb_str_buf_append(c->log_buf, byte_xs(tmp));
419 static void append_request(struct clogger *c)
421 VALUE tmp;
423 /* REQUEST_METHOD doesn't need escaping, Rack::Lint governs it */
424 tmp = rb_hash_aref(c->env, g_REQUEST_METHOD);
425 if (!NIL_P(tmp))
426 rb_str_buf_append(c->log_buf, tmp);
428 rb_str_buf_append(c->log_buf, g_space);
430 append_request_uri(c);
432 /* HTTP_VERSION can be injected by malicious clients */
433 tmp = rb_hash_aref(c->env, g_HTTP_VERSION);
434 if (!NIL_P(tmp)) {
435 rb_str_buf_append(c->log_buf, g_space);
436 rb_str_buf_append(c->log_buf, byte_xs(tmp));
440 static void append_request_length(struct clogger *c)
442 VALUE tmp = rb_hash_aref(c->env, g_rack_input);
443 if (NIL_P(tmp)) {
444 rb_str_buf_append(c->log_buf, g_dash);
445 } else {
446 tmp = rb_funcall(tmp, size_id, 0);
447 rb_str_buf_append(c->log_buf, rb_funcall(tmp, to_s_id, 0));
451 static long local_gmtoffset(struct tm *tm)
453 time_t t = time(NULL);
455 tzset();
456 localtime_r(&t, tm);
459 * HAVE_STRUCT_TM_TM_GMTOFF may be defined in Ruby headers
460 * HAVE_ST_TM_GMTOFF is defined ourselves.
462 #if defined(HAVE_STRUCT_TM_TM_GMTOFF) || defined(HAVE_ST_TM_GMTOFF)
463 return tm->tm_gmtoff / 60;
464 #else
465 return -(tm->tm_isdst ? timezone - 3600 : timezone) / 60;
466 #endif
469 static void append_time_iso8601(struct clogger *c)
471 char buf[sizeof("1970-01-01T00:00:00+00:00")];
472 struct tm tm;
473 int nr;
474 long gmtoff = local_gmtoffset(&tm);
476 nr = snprintf(buf, sizeof(buf),
477 "%4d-%02d-%02dT%02d:%02d:%02d%c%02d:%02d",
478 tm.tm_year + 1900, tm.tm_mon + 1,
479 tm.tm_mday, tm.tm_hour,
480 tm.tm_min, tm.tm_sec,
481 gmtoff < 0 ? '-' : '+',
482 abs(gmtoff / 60), abs(gmtoff % 60));
483 assert(nr == (sizeof(buf) - 1) && "snprintf fail");
484 rb_str_buf_cat(c->log_buf, buf, sizeof(buf) - 1);
487 static const char months[] = "Jan\0Feb\0Mar\0Apr\0May\0Jun\0"
488 "Jul\0Aug\0Sep\0Oct\0Nov\0Dec";
490 static void append_time_local(struct clogger *c)
492 char buf[sizeof("01/Jan/1970:00:00:00 +0000")];
493 struct tm tm;
494 int nr;
495 long gmtoff = local_gmtoffset(&tm);
497 nr = snprintf(buf, sizeof(buf),
498 "%02d/%s/%d:%02d:%02d:%02d %c%02d%02d",
499 tm.tm_mday, months + (tm.tm_mon * sizeof("Jan")),
500 tm.tm_year + 1900, tm.tm_hour,
501 tm.tm_min, tm.tm_sec,
502 gmtoff < 0 ? '-' : '+',
503 abs(gmtoff / 60), abs(gmtoff % 60));
504 assert(nr == (sizeof(buf) - 1) && "snprintf fail");
505 rb_str_buf_cat(c->log_buf, buf, sizeof(buf) - 1);
508 static void append_time_utc(struct clogger *c)
510 char buf[sizeof("01/Jan/1970:00:00:00 +0000")];
511 struct tm tm;
512 int nr;
513 time_t t = time(NULL);
515 gmtime_r(&t, &tm);
516 nr = snprintf(buf, sizeof(buf),
517 "%02d/%s/%d:%02d:%02d:%02d +0000",
518 tm.tm_mday, months + (tm.tm_mon * sizeof("Jan")),
519 tm.tm_year + 1900, tm.tm_hour,
520 tm.tm_min, tm.tm_sec);
521 assert(nr == (sizeof(buf) - 1) && "snprintf fail");
522 rb_str_buf_cat(c->log_buf, buf, sizeof(buf) - 1);
525 static void
526 append_time(struct clogger *c, enum clogger_opcode op, VALUE fmt, VALUE buf)
528 char *buf_ptr = RSTRING_PTR(buf);
529 size_t buf_size = RSTRING_LEN(buf) + 1; /* "\0" */
530 size_t nr;
531 struct tm tmp;
532 time_t t = time(NULL);
534 if (op == CL_OP_TIME_LOCAL)
535 localtime_r(&t, &tmp);
536 else if (op == CL_OP_TIME_UTC)
537 gmtime_r(&t, &tmp);
538 else
539 assert(0 && "unknown op");
541 nr = strftime(buf_ptr, buf_size, RSTRING_PTR(fmt), &tmp);
542 assert(nr < buf_size && "time format too small!");
543 rb_str_buf_cat(c->log_buf, buf_ptr, nr);
546 static void append_pid(struct clogger *c)
548 char buf[(sizeof(pid_t) * 8) / 3 + 1];
549 int nr = snprintf(buf, sizeof(buf), "%d", (int)getpid());
551 assert(nr > 0 && nr < (int)sizeof(buf));
552 rb_str_buf_cat(c->log_buf, buf, nr);
555 static void append_eval(struct clogger *c, VALUE str)
557 int state = -1;
558 VALUE rv = rb_eval_string_protect(RSTRING_PTR(str), &state);
560 rv = state == 0 ? rb_obj_as_string(rv) : g_dash;
561 rb_str_buf_append(c->log_buf, rv);
564 static void append_cookie(struct clogger *c, VALUE key)
566 VALUE cookie;
568 if (c->cookies == Qfalse)
569 c->cookies = rb_hash_aref(c->env, g_rack_request_cookie_hash);
571 if (NIL_P(c->cookies)) {
572 cookie = g_dash;
573 } else {
574 cookie = rb_hash_aref(c->cookies, key);
575 cookie = NIL_P(cookie) ? g_dash : byte_xs(cookie);
577 rb_str_buf_append(c->log_buf, cookie);
580 static void append_request_env(struct clogger *c, VALUE key)
582 VALUE tmp = rb_hash_aref(c->env, key);
584 tmp = NIL_P(tmp) ? g_dash : byte_xs(tmp);
585 rb_str_buf_append(c->log_buf, tmp);
588 static void append_response(struct clogger *c, VALUE key)
590 VALUE v;
592 assert(rb_obj_is_kind_of(c->headers, cHeaderHash) && "not HeaderHash");
594 v = rb_funcall(c->headers, sq_brace_id, 1, key);
595 v = NIL_P(v) ? g_dash : byte_xs(v);
596 rb_str_buf_append(c->log_buf, v);
599 static void special_var(struct clogger *c, enum clogger_special var)
601 switch (var) {
602 case CL_SP_body_bytes_sent:
603 append_body_bytes_sent(c);
604 break;
605 case CL_SP_status:
606 append_status(c);
607 break;
608 case CL_SP_request:
609 append_request(c);
610 break;
611 case CL_SP_request_length:
612 append_request_length(c);
613 break;
614 case CL_SP_response_length:
615 if (c->body_bytes_sent == 0)
616 rb_str_buf_append(c->log_buf, g_dash);
617 else
618 append_body_bytes_sent(c);
619 break;
620 case CL_SP_ip:
621 append_ip(c);
622 break;
623 case CL_SP_pid:
624 append_pid(c);
625 break;
626 case CL_SP_request_uri:
627 append_request_uri(c);
628 break;
629 case CL_SP_time_iso8601:
630 append_time_iso8601(c);
631 break;
632 case CL_SP_time_local:
633 append_time_local(c);
634 break;
635 case CL_SP_time_utc:
636 append_time_utc(c);
640 static VALUE cwrite(struct clogger *c)
642 const VALUE ops = c->fmt_ops;
643 const VALUE *ary = RARRAY_PTR(ops);
644 long i = RARRAY_LEN(ops);
645 VALUE dst = c->log_buf;
647 rb_str_set_len(dst, 0);
649 for (; --i >= 0; ary++) {
650 const VALUE *op = RARRAY_PTR(*ary);
651 enum clogger_opcode opcode = FIX2INT(op[0]);
653 switch (opcode) {
654 case CL_OP_LITERAL:
655 rb_str_buf_append(dst, op[1]);
656 break;
657 case CL_OP_REQUEST:
658 append_request_env(c, op[1]);
659 break;
660 case CL_OP_RESPONSE:
661 append_response(c, op[1]);
662 break;
663 case CL_OP_SPECIAL:
664 special_var(c, FIX2INT(op[1]));
665 break;
666 case CL_OP_EVAL:
667 append_eval(c, op[1]);
668 break;
669 case CL_OP_TIME_LOCAL:
670 case CL_OP_TIME_UTC:
671 append_time(c, opcode, op[1], op[2]);
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, op[1]);
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, ltlt_id, 1, dst);
695 return Qnil;
698 static VALUE clogger_write(VALUE self)
700 return cwrite(clogger_get(self));
703 static void init_logger(struct clogger *c, VALUE path)
705 ID id;
707 if (!NIL_P(path) && !NIL_P(c->logger))
708 rb_raise(rb_eArgError, ":logger and :path are independent");
709 if (!NIL_P(path)) {
710 VALUE ab = rb_str_new2("ab");
711 id = rb_intern("open");
712 c->logger = rb_funcall(rb_cFile, id, 2, path, ab);
715 id = rb_intern("sync=");
716 if (rb_respond_to(c->logger, id))
717 rb_funcall(c->logger, id, 1, Qtrue);
719 id = rb_intern("fileno");
720 if (rb_respond_to(c->logger, id))
721 c->fd = raw_fd(rb_funcall(c->logger, id, 0));
725 * call-seq:
726 * Clogger.new(app, :logger => $stderr, :format => string) => obj
728 * Creates a new Clogger object that wraps +app+. +:logger+ may
729 * be any object that responds to the "<<" method with a string argument.
730 * Instead of +:logger+, +:path+ may be specified to be a :path of a File
731 * that will be opened in append mode.
733 static VALUE clogger_init(int argc, VALUE *argv, VALUE self)
735 struct clogger *c = clogger_get(self);
736 VALUE o = Qnil;
737 VALUE fmt = rb_const_get(mFormat, rb_intern("Common"));
739 rb_scan_args(argc, argv, "11", &c->app, &o);
740 c->fd = -1;
741 c->logger = Qnil;
742 c->reentrant = -1; /* auto-detect */
744 if (TYPE(o) == T_HASH) {
745 VALUE tmp;
747 tmp = rb_hash_aref(o, ID2SYM(rb_intern("path")));
748 c->logger = rb_hash_aref(o, ID2SYM(rb_intern("logger")));
749 init_logger(c, tmp);
751 tmp = rb_hash_aref(o, ID2SYM(rb_intern("format")));
752 if (!NIL_P(tmp))
753 fmt = tmp;
755 tmp = rb_hash_aref(o, ID2SYM(rb_intern("reentrant")));
756 switch (TYPE(tmp)) {
757 case T_TRUE:
758 c->reentrant = 1;
759 break;
760 case T_FALSE:
761 c->reentrant = 0;
762 case T_NIL:
763 break;
764 default:
765 rb_raise(rb_eArgError, ":reentrant must be boolean");
769 init_buffers(c);
770 c->fmt_ops = rb_funcall(self, rb_intern("compile_format"), 2, fmt, o);
772 if (Qtrue == rb_funcall(self, rb_intern("need_response_headers?"),
773 1, c->fmt_ops))
774 c->need_resp = 1;
775 if (Qtrue == rb_funcall(self, rb_intern("need_wrap_body?"),
776 1, c->fmt_ops))
777 c->wrap_body = 1;
779 return self;
782 static VALUE body_iter_i(VALUE str, VALUE self)
784 struct clogger *c = clogger_get(self);
786 str = rb_obj_as_string(str);
787 c->body_bytes_sent += RSTRING_LEN(str);
789 return rb_yield(str);
792 static VALUE body_close(VALUE self)
794 struct clogger *c = clogger_get(self);
796 if (rb_respond_to(c->body, close_id))
797 return rb_funcall(c->body, close_id, 0);
798 return Qnil;
802 * call-seq:
803 * clogger.each { |part| socket.write(part) }
805 * Delegates the body#each call to the underlying +body+ object
806 * while tracking the number of bytes yielded. This will log
807 * the request.
809 static VALUE clogger_each(VALUE self)
811 struct clogger *c = clogger_get(self);
813 rb_need_block();
814 c->body_bytes_sent = 0;
815 rb_iterate(rb_each, c->body, body_iter_i, self);
817 return self;
821 * call-seq:
822 * clogger.close
824 * Delegates the body#close call to the underlying +body+ object.
825 * This is only used when Clogger is wrapping the +body+ of a Rack
826 * response and should be automatically called by the web server.
828 static VALUE clogger_close(VALUE self)
831 return rb_ensure(body_close, self, clogger_write, self);
834 /* :nodoc: */
835 static VALUE clogger_fileno(VALUE self)
837 struct clogger *c = clogger_get(self);
839 return c->fd < 0 ? Qnil : INT2NUM(c->fd);
842 static VALUE ccall(struct clogger *c, VALUE env)
844 VALUE rv;
846 clock_gettime(hopefully_CLOCK_MONOTONIC, &c->ts_start);
847 c->env = env;
848 c->cookies = Qfalse;
849 rv = rb_funcall(c->app, call_id, 1, env);
850 if (TYPE(rv) == T_ARRAY && RARRAY_LEN(rv) == 3) {
851 VALUE *tmp = RARRAY_PTR(rv);
853 c->status = tmp[0];
854 c->headers = tmp[1];
855 c->body = tmp[2];
857 rv = rb_ary_new4(3, tmp);
858 if (c->need_resp &&
859 ! rb_obj_is_kind_of(tmp[1], cHeaderHash)) {
860 c->headers = rb_funcall(cHeaderHash, new_id, 1, tmp[1]);
861 rb_ary_store(rv, 1, c->headers);
863 } else {
864 volatile VALUE tmp = rb_inspect(rv);
866 c->status = INT2FIX(500);
867 c->headers = c->body = rb_ary_new();
868 cwrite(c);
869 rb_raise(rb_eTypeError,
870 "app response not a 3 element Array: %s",
871 RSTRING_PTR(tmp));
874 return rv;
878 * call-seq:
879 * clogger.call(env) => [ status, headers, body ]
881 * calls the wrapped Rack application with +env+, returns the
882 * [status, headers, body ] tuplet required by Rack.
884 static VALUE clogger_call(VALUE self, VALUE env)
886 struct clogger *c = clogger_get(self);
887 VALUE rv;
889 env = rb_check_convert_type(env, T_HASH, "Hash", "to_hash");
891 if (c->wrap_body) {
892 /* XXX: we assume the existence of the GVL here: */
893 if (c->reentrant < 0) {
894 VALUE tmp = rb_hash_aref(env, g_rack_multithread);
895 c->reentrant = Qfalse == tmp ? 0 : 1;
898 if (c->reentrant) {
899 self = rb_obj_dup(self);
900 c = clogger_get(self);
903 rv = ccall(c, env);
904 assert(!OBJ_FROZEN(rv) && "frozen response array");
905 rb_ary_store(rv, 2, self);
907 return rv;
910 rv = ccall(c, env);
911 cwrite(c);
913 return rv;
916 static void duplicate_buffers(VALUE ops)
918 long i = RARRAY_LEN(ops);
919 VALUE *ary = RARRAY_PTR(ops);
921 for ( ; --i >= 0; ary++) {
922 VALUE *op = RARRAY_PTR(*ary);
923 enum clogger_opcode opcode = FIX2INT(op[0]);
925 if (opcode == CL_OP_TIME_LOCAL || opcode == CL_OP_TIME_UTC) {
926 Check_Type(op[2], T_STRING);
927 op[2] = rb_str_dup(op[2]);
928 rb_str_modify(op[2]); /* trigger copy-on-write */
933 /* :nodoc: */
934 static VALUE clogger_init_copy(VALUE clone, VALUE orig)
936 struct clogger *a = clogger_get(orig);
937 struct clogger *b = clogger_get(clone);
939 memcpy(b, a, sizeof(struct clogger));
940 init_buffers(b);
941 duplicate_buffers(b->fmt_ops);
943 return clone;
946 #define CONST_GLOBAL_STR2(var, val) do { \
947 g_##var = rb_obj_freeze(rb_str_new(val, sizeof(val) - 1)); \
948 rb_global_variable(&g_##var); \
949 } while (0)
951 #define CONST_GLOBAL_STR(val) CONST_GLOBAL_STR2(val, #val)
954 * call-seq:
955 * clogger.respond_to?(:to_path) => true or false
956 * clogger.respond_to?(:close) => true
958 * used to delegate +:to_path+ checks for Rack webservers that optimize
959 * static file serving
961 static VALUE respond_to(VALUE self, VALUE method)
963 struct clogger *c = clogger_get(self);
964 ID id = rb_to_id(method);
966 if (close_id == id)
967 return Qtrue;
968 return rb_respond_to(c->body, id);
972 * call-seq:
973 * clogger.to_path
975 * used to proxy +:to_path+ method calls to the wrapped response body.
977 static VALUE to_path(VALUE self)
979 struct clogger *c = clogger_get(self);
980 struct stat sb;
981 int rv;
982 VALUE path = rb_funcall(c->body, to_path_id, 0);
984 /* try to avoid an extra path lookup */
985 if (rb_respond_to(c->body, to_io_id)) {
986 rv = fstat(my_fileno(c->body), &sb);
987 } else {
988 const char *cpath = StringValueCStr(path);
989 unsigned devfd;
991 * Rainbows! can use "/dev/fd/%u" in to_path output to avoid
992 * extra open() syscalls, too.
994 if (sscanf(cpath, "/dev/fd/%u", &devfd) == 1)
995 rv = fstat((int)devfd, &sb);
996 else
997 rv = stat(cpath, &sb);
1001 * calling this method implies the web server will bypass
1002 * the each method where body_bytes_sent is calculated,
1003 * so we stat and set that value here.
1005 c->body_bytes_sent = rv == 0 ? sb.st_size : 0;
1006 return path;
1010 * call-seq:
1011 * clogger.to_io
1013 * used to proxy +:to_io+ method calls to the wrapped response body.
1015 static VALUE to_io(VALUE self)
1017 struct clogger *c = clogger_get(self);
1018 struct stat sb;
1019 VALUE io = rb_convert_type(c->body, T_FILE, "IO", "to_io");
1021 if (fstat(my_fileno(io), &sb) == 0)
1022 c->body_bytes_sent = sb.st_size;
1024 return io;
1027 /* :nodoc: */
1028 static VALUE body(VALUE self)
1030 return clogger_get(self)->body;
1033 void Init_clogger_ext(void)
1035 VALUE tmp;
1037 check_clock();
1039 ltlt_id = rb_intern("<<");
1040 call_id = rb_intern("call");
1041 each_id = rb_intern("each");
1042 close_id = rb_intern("close");
1043 to_i_id = rb_intern("to_i");
1044 to_s_id = rb_intern("to_s");
1045 size_id = rb_intern("size");
1046 sq_brace_id = rb_intern("[]");
1047 new_id = rb_intern("new");
1048 to_path_id = rb_intern("to_path");
1049 to_io_id = rb_intern("to_io");
1050 respond_to_id = rb_intern("respond_to?");
1051 cClogger = rb_define_class("Clogger", rb_cObject);
1052 mFormat = rb_define_module_under(cClogger, "Format");
1053 rb_define_alloc_func(cClogger, clogger_alloc);
1054 rb_define_method(cClogger, "initialize", clogger_init, -1);
1055 rb_define_method(cClogger, "initialize_copy", clogger_init_copy, 1);
1056 rb_define_method(cClogger, "call", clogger_call, 1);
1057 rb_define_method(cClogger, "each", clogger_each, 0);
1058 rb_define_method(cClogger, "close", clogger_close, 0);
1059 rb_define_method(cClogger, "fileno", clogger_fileno, 0);
1060 rb_define_method(cClogger, "wrap_body?", clogger_wrap_body, 0);
1061 rb_define_method(cClogger, "reentrant?", clogger_reentrant, 0);
1062 rb_define_method(cClogger, "to_path", to_path, 0);
1063 rb_define_method(cClogger, "to_io", to_io, 0);
1064 rb_define_method(cClogger, "respond_to?", respond_to, 1);
1065 rb_define_method(cClogger, "body", body, 0);
1066 CONST_GLOBAL_STR(REMOTE_ADDR);
1067 CONST_GLOBAL_STR(HTTP_X_FORWARDED_FOR);
1068 CONST_GLOBAL_STR(REQUEST_METHOD);
1069 CONST_GLOBAL_STR(PATH_INFO);
1070 CONST_GLOBAL_STR(QUERY_STRING);
1071 CONST_GLOBAL_STR(REQUEST_URI);
1072 CONST_GLOBAL_STR(HTTP_VERSION);
1073 CONST_GLOBAL_STR2(rack_errors, "rack.errors");
1074 CONST_GLOBAL_STR2(rack_input, "rack.input");
1075 CONST_GLOBAL_STR2(rack_multithread, "rack.multithread");
1076 CONST_GLOBAL_STR2(dash, "-");
1077 CONST_GLOBAL_STR2(space, " ");
1078 CONST_GLOBAL_STR2(question_mark, "?");
1079 CONST_GLOBAL_STR2(rack_request_cookie_hash, "rack.request.cookie_hash");
1081 tmp = rb_const_get(rb_cObject, rb_intern("Rack"));
1082 tmp = rb_const_get(tmp, rb_intern("Utils"));
1083 cHeaderHash = rb_const_get(tmp, rb_intern("HeaderHash"));