prevent potential premature GC in byte_xs
[clogger.git] / ext / clogger_ext / clogger.c
blob8b05c343ee44edf38c6eeddabfbd671074f43602
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 each_id;
126 static ID close_id;
127 static ID to_i_id;
128 static ID to_s_id;
129 static ID size_id;
130 static ID sq_brace_id;
131 static ID new_id;
132 static ID to_path_id;
133 static ID to_io_id;
134 static ID respond_to_id;
135 static VALUE cClogger;
136 static VALUE mFormat;
137 static VALUE cHeaderHash;
139 /* common hash lookup keys */
140 static VALUE g_HTTP_X_FORWARDED_FOR;
141 static VALUE g_REMOTE_ADDR;
142 static VALUE g_REQUEST_METHOD;
143 static VALUE g_PATH_INFO;
144 static VALUE g_REQUEST_URI;
145 static VALUE g_QUERY_STRING;
146 static VALUE g_HTTP_VERSION;
147 static VALUE g_rack_errors;
148 static VALUE g_rack_input;
149 static VALUE g_rack_multithread;
150 static VALUE g_dash;
151 static VALUE g_space;
152 static VALUE g_question_mark;
153 static VALUE g_rack_request_cookie_hash;
155 #define LOG_BUF_INIT_SIZE 128
157 static void init_buffers(struct clogger *c)
159 c->log_buf = rb_str_buf_new(LOG_BUF_INIT_SIZE);
162 static inline int need_escape(unsigned c)
164 assert(c <= 0xff);
165 return !!(c == '\'' || c == '"' || c <= 0x1f || c >= 0x7f);
168 /* we are encoding-agnostic, clients can send us all sorts of junk */
169 static VALUE byte_xs(VALUE obj)
171 static const char esc[] = "0123456789ABCDEF";
172 unsigned char *new_ptr;
173 VALUE from = rb_obj_as_string(obj);
174 const unsigned char *ptr = (const unsigned char *)RSTRING_PTR(from);
175 long len = RSTRING_LEN(from);
176 long new_len = len;
177 VALUE rv;
179 for (; --len >= 0; ptr++) {
180 unsigned c = *ptr;
182 if (unlikely(need_escape(c)))
183 new_len += 3; /* { '\', 'x', 'X', 'X' } */
186 len = RSTRING_LEN(from);
187 if (new_len == len)
188 return from;
190 rv = rb_str_new(NULL, new_len);
191 new_ptr = (unsigned char *)RSTRING_PTR(rv);
192 ptr = (const unsigned char *)RSTRING_PTR(from);
193 for (; --len >= 0; ptr++) {
194 unsigned c = *ptr;
196 if (unlikely(need_escape(c))) {
197 *new_ptr++ = '\\';
198 *new_ptr++ = 'x';
199 *new_ptr++ = esc[c >> 4];
200 *new_ptr++ = esc[c & 0xf];
201 } else {
202 *new_ptr++ = c;
205 assert(RSTRING_PTR(rv)[RSTRING_LEN(rv)] == '\0');
207 RB_GC_GUARD(from);
208 return rv;
211 static void clogger_mark(void *ptr)
213 struct clogger *c = ptr;
215 rb_gc_mark(c->app);
216 rb_gc_mark(c->fmt_ops);
217 rb_gc_mark(c->logger);
218 rb_gc_mark(c->log_buf);
219 rb_gc_mark(c->env);
220 rb_gc_mark(c->cookies);
221 rb_gc_mark(c->status);
222 rb_gc_mark(c->headers);
223 rb_gc_mark(c->body);
226 static VALUE clogger_alloc(VALUE klass)
228 struct clogger *c;
230 return Data_Make_Struct(klass, struct clogger, clogger_mark, -1, c);
233 static struct clogger *clogger_get(VALUE self)
235 struct clogger *c;
237 Data_Get_Struct(self, struct clogger, c);
238 assert(c);
239 return c;
242 /* only for writing to regular files, not stupid crap like NFS */
243 static void write_full(int fd, const void *buf, size_t count)
245 ssize_t r;
246 unsigned long ubuf = (unsigned long)buf;
248 while (count > 0) {
249 r = write(fd, (void *)ubuf, count);
251 if ((size_t)r == count) { /* overwhelmingly likely */
252 return;
253 } else if (r > 0) {
254 count -= r;
255 ubuf += r;
256 } else {
257 if (errno == EINTR || errno == EAGAIN)
258 continue; /* poor souls on NFS and like: */
259 if (!errno)
260 errno = ENOSPC;
261 rb_sys_fail("write");
267 * allow us to use write_full() iff we detect a blocking file
268 * descriptor that wouldn't play nicely with Ruby threading/fibers
270 static int raw_fd(VALUE my_fd)
272 #if defined(HAVE_FCNTL) && defined(F_GETFL) && defined(O_NONBLOCK)
273 int fd;
274 int flags;
276 if (NIL_P(my_fd))
277 return -1;
278 fd = NUM2INT(my_fd);
280 flags = fcntl(fd, F_GETFL);
281 if (flags < 0)
282 rb_sys_fail("fcntl");
284 if (flags & O_NONBLOCK) {
285 struct stat sb;
287 if (fstat(fd, &sb) < 0)
288 return -1;
290 /* O_NONBLOCK is no-op for regular files: */
291 if (! S_ISREG(sb.st_mode))
292 return -1;
294 return fd;
295 #else /* platforms w/o fcntl/F_GETFL/O_NONBLOCK */
296 return -1;
297 #endif /* platforms w/o fcntl/F_GETFL/O_NONBLOCK */
300 /* :nodoc: */
301 static VALUE clogger_reentrant(VALUE self)
303 return clogger_get(self)->reentrant == 0 ? Qfalse : Qtrue;
306 /* :nodoc: */
307 static VALUE clogger_wrap_body(VALUE self)
309 return clogger_get(self)->wrap_body == 0 ? Qfalse : Qtrue;
312 static void append_status(struct clogger *c)
314 char buf[sizeof("999")];
315 int nr;
316 VALUE status = c->status;
318 if (TYPE(status) != T_FIXNUM) {
319 status = rb_funcall(status, to_i_id, 0);
320 /* no way it's a valid status code (at least not HTTP/1.1) */
321 if (TYPE(status) != T_FIXNUM) {
322 rb_str_buf_append(c->log_buf, g_dash);
323 return;
327 nr = FIX2INT(status);
328 if (nr >= 100 && nr <= 999) {
329 nr = snprintf(buf, sizeof(buf), "%03d", nr);
330 assert(nr == 3);
331 rb_str_buf_cat(c->log_buf, buf, nr);
332 } else {
333 /* raise?, swap for 500? */
334 rb_str_buf_append(c->log_buf, g_dash);
338 /* this is Rack 1.0.0-compatible, won't try to parse commas in XFF */
339 static void append_ip(struct clogger *c)
341 VALUE env = c->env;
342 VALUE tmp = rb_hash_aref(env, g_HTTP_X_FORWARDED_FOR);
344 if (NIL_P(tmp)) {
345 /* can't be faked on any real server, so no escape */
346 tmp = rb_hash_aref(env, g_REMOTE_ADDR);
347 if (NIL_P(tmp))
348 tmp = g_dash;
349 } else {
350 tmp = byte_xs(tmp);
352 rb_str_buf_append(c->log_buf, tmp);
355 static void append_body_bytes_sent(struct clogger *c)
357 char buf[(sizeof(off_t) * 8) / 3 + 1];
358 const char *fmt = sizeof(off_t) == sizeof(long) ? "%ld" : "%lld";
359 int nr = snprintf(buf, sizeof(buf), fmt, c->body_bytes_sent);
361 assert(nr > 0 && nr < (int)sizeof(buf));
362 rb_str_buf_cat(c->log_buf, buf, nr);
365 static void append_ts(struct clogger *c, VALUE op, struct timespec *ts)
367 char buf[sizeof(".000000") + ((sizeof(ts->tv_sec) * 8) / 3)];
368 int nr;
369 char *fmt = RSTRING_PTR(rb_ary_entry(op, 1));
370 int ndiv = NUM2INT(rb_ary_entry(op, 2));
371 int usec = ts->tv_nsec / 1000;
373 nr = snprintf(buf, sizeof(buf), fmt,
374 (int)ts->tv_sec, (int)(usec / ndiv));
375 assert(nr > 0 && nr < (int)sizeof(buf));
376 rb_str_buf_cat(c->log_buf, buf, nr);
379 static void append_request_time_fmt(struct clogger *c, VALUE op)
381 struct timespec now;
383 clock_gettime(hopefully_CLOCK_MONOTONIC, &now);
384 clock_diff(&now, &c->ts_start);
385 append_ts(c, op, &now);
388 static void append_time_fmt(struct clogger *c, VALUE op)
390 struct timespec now;
391 int r = clock_gettime(CLOCK_REALTIME, &now);
393 if (unlikely(r != 0))
394 rb_sys_fail("clock_gettime(CLOCK_REALTIME)");
395 append_ts(c, op, &now);
398 static void append_request_uri(struct clogger *c)
400 VALUE tmp;
402 tmp = rb_hash_aref(c->env, g_REQUEST_URI);
403 if (NIL_P(tmp)) {
404 tmp = rb_hash_aref(c->env, g_PATH_INFO);
405 if (!NIL_P(tmp))
406 rb_str_buf_append(c->log_buf, byte_xs(tmp));
407 tmp = rb_hash_aref(c->env, g_QUERY_STRING);
408 if (!NIL_P(tmp) && RSTRING_LEN(tmp) != 0) {
409 rb_str_buf_append(c->log_buf, g_question_mark);
410 rb_str_buf_append(c->log_buf, byte_xs(tmp));
412 } else {
413 rb_str_buf_append(c->log_buf, byte_xs(tmp));
417 static void append_request(struct clogger *c)
419 VALUE tmp;
421 /* REQUEST_METHOD doesn't need escaping, Rack::Lint governs it */
422 tmp = rb_hash_aref(c->env, g_REQUEST_METHOD);
423 if (!NIL_P(tmp))
424 rb_str_buf_append(c->log_buf, tmp);
426 rb_str_buf_append(c->log_buf, g_space);
428 append_request_uri(c);
430 /* HTTP_VERSION can be injected by malicious clients */
431 tmp = rb_hash_aref(c->env, g_HTTP_VERSION);
432 if (!NIL_P(tmp)) {
433 rb_str_buf_append(c->log_buf, g_space);
434 rb_str_buf_append(c->log_buf, byte_xs(tmp));
438 static void append_request_length(struct clogger *c)
440 VALUE tmp = rb_hash_aref(c->env, g_rack_input);
441 if (NIL_P(tmp)) {
442 rb_str_buf_append(c->log_buf, g_dash);
443 } else {
444 tmp = rb_funcall(tmp, size_id, 0);
445 rb_str_buf_append(c->log_buf, rb_funcall(tmp, to_s_id, 0));
449 static long local_gmtoffset(struct tm *tm)
451 time_t t = time(NULL);
453 tzset();
454 localtime_r(&t, tm);
457 * HAVE_STRUCT_TM_TM_GMTOFF may be defined in Ruby headers
458 * HAVE_ST_TM_GMTOFF is defined ourselves.
460 #if defined(HAVE_STRUCT_TM_TM_GMTOFF) || defined(HAVE_ST_TM_GMTOFF)
461 return tm->tm_gmtoff / 60;
462 #else
463 return -(tm->tm_isdst ? timezone - 3600 : timezone) / 60;
464 #endif
467 static void append_time_iso8601(struct clogger *c)
469 char buf[sizeof("1970-01-01T00:00:00+00:00")];
470 struct tm tm;
471 int nr;
472 long gmtoff = local_gmtoffset(&tm);
474 nr = snprintf(buf, sizeof(buf),
475 "%4d-%02d-%02dT%02d:%02d:%02d%c%02d:%02d",
476 tm.tm_year + 1900, tm.tm_mon + 1,
477 tm.tm_mday, tm.tm_hour,
478 tm.tm_min, tm.tm_sec,
479 gmtoff < 0 ? '-' : '+',
480 abs(gmtoff / 60), abs(gmtoff % 60));
481 assert(nr == (sizeof(buf) - 1) && "snprintf fail");
482 rb_str_buf_cat(c->log_buf, buf, sizeof(buf) - 1);
485 static const char months[] = "Jan\0Feb\0Mar\0Apr\0May\0Jun\0"
486 "Jul\0Aug\0Sep\0Oct\0Nov\0Dec";
488 static void append_time_local(struct clogger *c)
490 char buf[sizeof("01/Jan/1970:00:00:00 +0000")];
491 struct tm tm;
492 int nr;
493 long gmtoff = local_gmtoffset(&tm);
495 nr = snprintf(buf, sizeof(buf),
496 "%02d/%s/%d:%02d:%02d:%02d %c%02d%02d",
497 tm.tm_mday, months + (tm.tm_mon * sizeof("Jan")),
498 tm.tm_year + 1900, tm.tm_hour,
499 tm.tm_min, tm.tm_sec,
500 gmtoff < 0 ? '-' : '+',
501 abs(gmtoff / 60), abs(gmtoff % 60));
502 assert(nr == (sizeof(buf) - 1) && "snprintf fail");
503 rb_str_buf_cat(c->log_buf, buf, sizeof(buf) - 1);
506 static void append_time_utc(struct clogger *c)
508 char buf[sizeof("01/Jan/1970:00:00:00 +0000")];
509 struct tm tm;
510 int nr;
511 time_t t = time(NULL);
513 gmtime_r(&t, &tm);
514 nr = snprintf(buf, sizeof(buf),
515 "%02d/%s/%d:%02d:%02d:%02d +0000",
516 tm.tm_mday, months + (tm.tm_mon * sizeof("Jan")),
517 tm.tm_year + 1900, tm.tm_hour,
518 tm.tm_min, tm.tm_sec);
519 assert(nr == (sizeof(buf) - 1) && "snprintf fail");
520 rb_str_buf_cat(c->log_buf, buf, sizeof(buf) - 1);
523 static void
524 append_time(struct clogger *c, enum clogger_opcode op, VALUE fmt, VALUE buf)
526 char *buf_ptr = RSTRING_PTR(buf);
527 size_t buf_size = RSTRING_LEN(buf) + 1; /* "\0" */
528 size_t nr;
529 struct tm tmp;
530 time_t t = time(NULL);
532 if (op == CL_OP_TIME_LOCAL)
533 localtime_r(&t, &tmp);
534 else if (op == CL_OP_TIME_UTC)
535 gmtime_r(&t, &tmp);
536 else
537 assert(0 && "unknown op");
539 nr = strftime(buf_ptr, buf_size, RSTRING_PTR(fmt), &tmp);
540 assert(nr < buf_size && "time format too small!");
541 rb_str_buf_cat(c->log_buf, buf_ptr, nr);
544 static void append_pid(struct clogger *c)
546 char buf[(sizeof(pid_t) * 8) / 3 + 1];
547 int nr = snprintf(buf, sizeof(buf), "%d", (int)getpid());
549 assert(nr > 0 && nr < (int)sizeof(buf));
550 rb_str_buf_cat(c->log_buf, buf, nr);
553 static void append_eval(struct clogger *c, VALUE str)
555 int state = -1;
556 VALUE rv = rb_eval_string_protect(RSTRING_PTR(str), &state);
558 rv = state == 0 ? rb_obj_as_string(rv) : g_dash;
559 rb_str_buf_append(c->log_buf, rv);
562 static void append_cookie(struct clogger *c, VALUE key)
564 VALUE cookie;
566 if (c->cookies == Qfalse)
567 c->cookies = rb_hash_aref(c->env, g_rack_request_cookie_hash);
569 if (NIL_P(c->cookies)) {
570 cookie = g_dash;
571 } else {
572 cookie = rb_hash_aref(c->cookies, key);
573 cookie = NIL_P(cookie) ? g_dash : byte_xs(cookie);
575 rb_str_buf_append(c->log_buf, cookie);
578 static void append_request_env(struct clogger *c, VALUE key)
580 VALUE tmp = rb_hash_aref(c->env, key);
582 tmp = NIL_P(tmp) ? g_dash : byte_xs(tmp);
583 rb_str_buf_append(c->log_buf, tmp);
586 static void append_response(struct clogger *c, VALUE key)
588 VALUE v;
590 assert(rb_obj_is_kind_of(c->headers, cHeaderHash) && "not HeaderHash");
592 v = rb_funcall(c->headers, sq_brace_id, 1, key);
593 v = NIL_P(v) ? g_dash : byte_xs(v);
594 rb_str_buf_append(c->log_buf, v);
597 static void special_var(struct clogger *c, enum clogger_special var)
599 switch (var) {
600 case CL_SP_body_bytes_sent:
601 append_body_bytes_sent(c);
602 break;
603 case CL_SP_status:
604 append_status(c);
605 break;
606 case CL_SP_request:
607 append_request(c);
608 break;
609 case CL_SP_request_length:
610 append_request_length(c);
611 break;
612 case CL_SP_response_length:
613 if (c->body_bytes_sent == 0)
614 rb_str_buf_append(c->log_buf, g_dash);
615 else
616 append_body_bytes_sent(c);
617 break;
618 case CL_SP_ip:
619 append_ip(c);
620 break;
621 case CL_SP_pid:
622 append_pid(c);
623 break;
624 case CL_SP_request_uri:
625 append_request_uri(c);
626 break;
627 case CL_SP_time_iso8601:
628 append_time_iso8601(c);
629 break;
630 case CL_SP_time_local:
631 append_time_local(c);
632 break;
633 case CL_SP_time_utc:
634 append_time_utc(c);
638 static VALUE cwrite(struct clogger *c)
640 const VALUE ops = c->fmt_ops;
641 long i;
642 long len = RARRAY_LEN(ops);
643 VALUE dst = c->log_buf;
645 rb_str_set_len(dst, 0);
647 for (i = 0; i < len; i++) {
648 VALUE op = rb_ary_entry(ops, i);
649 enum clogger_opcode opcode = FIX2INT(rb_ary_entry(op, 0));
650 VALUE op1 = rb_ary_entry(op, 1);
652 switch (opcode) {
653 case CL_OP_LITERAL:
654 rb_str_buf_append(dst, op1);
655 break;
656 case CL_OP_REQUEST:
657 append_request_env(c, op1);
658 break;
659 case CL_OP_RESPONSE:
660 append_response(c, op1);
661 break;
662 case CL_OP_SPECIAL:
663 special_var(c, FIX2INT(op1));
664 break;
665 case CL_OP_EVAL:
666 append_eval(c, op1);
667 break;
668 case CL_OP_TIME_LOCAL:
669 case CL_OP_TIME_UTC: {
670 VALUE arg2 = rb_ary_entry(op, 2);
671 append_time(c, opcode, op1, arg2);
673 break;
674 case CL_OP_REQUEST_TIME:
675 append_request_time_fmt(c, op);
676 break;
677 case CL_OP_TIME:
678 append_time_fmt(c, op);
679 break;
680 case CL_OP_COOKIE:
681 append_cookie(c, op1);
682 break;
686 if (c->fd >= 0) {
687 write_full(c->fd, RSTRING_PTR(dst), RSTRING_LEN(dst));
688 } else {
689 VALUE logger = c->logger;
691 if (NIL_P(logger)) {
692 logger = rb_hash_aref(c->env, g_rack_errors);
693 rb_funcall(logger, write_id, 1, dst);
694 } else {
695 rb_funcall(logger, ltlt_id, 1, dst);
699 return Qnil;
702 static VALUE clogger_write(VALUE self)
704 return cwrite(clogger_get(self));
707 static void init_logger(struct clogger *c, VALUE path)
709 ID id;
711 if (!NIL_P(path) && !NIL_P(c->logger))
712 rb_raise(rb_eArgError, ":logger and :path are independent");
713 if (!NIL_P(path)) {
714 VALUE ab = rb_str_new2("ab");
715 id = rb_intern("open");
716 c->logger = rb_funcall(rb_cFile, id, 2, path, ab);
719 id = rb_intern("sync=");
720 if (rb_respond_to(c->logger, id))
721 rb_funcall(c->logger, id, 1, Qtrue);
723 id = rb_intern("fileno");
724 if (rb_respond_to(c->logger, id))
725 c->fd = raw_fd(rb_funcall(c->logger, id, 0));
729 * call-seq:
730 * Clogger.new(app, :logger => $stderr, :format => string) => obj
732 * Creates a new Clogger object that wraps +app+. +:logger+ may
733 * be any object that responds to the "<<" method with a string argument.
734 * Instead of +:logger+, +:path+ may be specified to be a :path of a File
735 * that will be opened in append mode.
737 static VALUE clogger_init(int argc, VALUE *argv, VALUE self)
739 struct clogger *c = clogger_get(self);
740 VALUE o = Qnil;
741 VALUE fmt = rb_const_get(mFormat, rb_intern("Common"));
743 rb_scan_args(argc, argv, "11", &c->app, &o);
744 c->fd = -1;
745 c->logger = Qnil;
746 c->reentrant = -1; /* auto-detect */
748 if (TYPE(o) == T_HASH) {
749 VALUE tmp;
751 tmp = rb_hash_aref(o, ID2SYM(rb_intern("path")));
752 c->logger = rb_hash_aref(o, ID2SYM(rb_intern("logger")));
753 init_logger(c, tmp);
755 tmp = rb_hash_aref(o, ID2SYM(rb_intern("format")));
756 if (!NIL_P(tmp))
757 fmt = tmp;
759 tmp = rb_hash_aref(o, ID2SYM(rb_intern("reentrant")));
760 switch (TYPE(tmp)) {
761 case T_TRUE:
762 c->reentrant = 1;
763 break;
764 case T_FALSE:
765 c->reentrant = 0;
766 case T_NIL:
767 break;
768 default:
769 rb_raise(rb_eArgError, ":reentrant must be boolean");
773 init_buffers(c);
774 c->fmt_ops = rb_funcall(self, rb_intern("compile_format"), 2, fmt, o);
776 if (Qtrue == rb_funcall(self, rb_intern("need_response_headers?"),
777 1, c->fmt_ops))
778 c->need_resp = 1;
779 if (Qtrue == rb_funcall(self, rb_intern("need_wrap_body?"),
780 1, c->fmt_ops))
781 c->wrap_body = 1;
783 return self;
786 static VALUE body_iter_i(VALUE str, VALUE self)
788 struct clogger *c = clogger_get(self);
790 str = rb_obj_as_string(str);
791 c->body_bytes_sent += RSTRING_LEN(str);
793 return rb_yield(str);
796 static VALUE body_close(VALUE self)
798 struct clogger *c = clogger_get(self);
800 if (rb_respond_to(c->body, close_id))
801 return rb_funcall(c->body, close_id, 0);
802 return Qnil;
806 * call-seq:
807 * clogger.each { |part| socket.write(part) }
809 * Delegates the body#each call to the underlying +body+ object
810 * while tracking the number of bytes yielded. This will log
811 * the request.
813 static VALUE clogger_each(VALUE self)
815 struct clogger *c = clogger_get(self);
817 rb_need_block();
818 c->body_bytes_sent = 0;
819 rb_iterate(rb_each, c->body, body_iter_i, self);
821 return self;
825 * call-seq:
826 * clogger.close
828 * Delegates the body#close call to the underlying +body+ object.
829 * This is only used when Clogger is wrapping the +body+ of a Rack
830 * response and should be automatically called by the web server.
832 static VALUE clogger_close(VALUE self)
835 return rb_ensure(body_close, self, clogger_write, self);
838 /* :nodoc: */
839 static VALUE clogger_fileno(VALUE self)
841 struct clogger *c = clogger_get(self);
843 return c->fd < 0 ? Qnil : INT2NUM(c->fd);
846 static VALUE ccall(struct clogger *c, VALUE env)
848 VALUE rv;
850 clock_gettime(hopefully_CLOCK_MONOTONIC, &c->ts_start);
851 c->env = env;
852 c->cookies = Qfalse;
853 rv = rb_funcall(c->app, call_id, 1, env);
854 if (TYPE(rv) == T_ARRAY && RARRAY_LEN(rv) == 3) {
855 c->status = rb_ary_entry(rv, 0);
856 c->headers = rb_ary_entry(rv, 1);
857 c->body = rb_ary_entry(rv, 2);
859 rv = rb_ary_dup(rv);
860 if (c->need_resp &&
861 ! rb_obj_is_kind_of(c->headers, cHeaderHash)) {
862 c->headers = rb_funcall(cHeaderHash, new_id, 1,
863 c->headers);
864 rb_ary_store(rv, 1, c->headers);
866 } else {
867 VALUE tmp = rb_inspect(rv);
869 c->status = INT2FIX(500);
870 c->headers = c->body = rb_ary_new();
871 cwrite(c);
872 rb_raise(rb_eTypeError,
873 "app response not a 3 element Array: %s",
874 RSTRING_PTR(tmp));
875 RB_GC_GUARD(tmp);
878 return rv;
882 * call-seq:
883 * clogger.call(env) => [ status, headers, body ]
885 * calls the wrapped Rack application with +env+, returns the
886 * [status, headers, body ] tuplet required by Rack.
888 static VALUE clogger_call(VALUE self, VALUE env)
890 struct clogger *c = clogger_get(self);
891 VALUE rv;
893 env = rb_check_convert_type(env, T_HASH, "Hash", "to_hash");
895 if (c->wrap_body) {
896 /* XXX: we assume the existence of the GVL here: */
897 if (c->reentrant < 0) {
898 VALUE tmp = rb_hash_aref(env, g_rack_multithread);
899 c->reentrant = Qfalse == tmp ? 0 : 1;
902 if (c->reentrant) {
903 self = rb_obj_dup(self);
904 c = clogger_get(self);
907 rv = ccall(c, env);
908 assert(!OBJ_FROZEN(rv) && "frozen response array");
909 rb_ary_store(rv, 2, self);
911 return rv;
914 rv = ccall(c, env);
915 cwrite(c);
917 return rv;
920 static void duplicate_buffers(VALUE ops)
922 long i;
923 long len = RARRAY_LEN(ops);
925 for (i = 0; i < len; i++) {
926 VALUE op = rb_ary_entry(ops, i);
927 enum clogger_opcode opcode = FIX2INT(rb_ary_entry(op, 0));
929 if (opcode == CL_OP_TIME_LOCAL || opcode == CL_OP_TIME_UTC) {
930 VALUE buf = rb_ary_entry(op, 2);
931 Check_Type(buf, T_STRING);
932 buf = rb_str_dup(buf);
933 rb_str_modify(buf); /* trigger copy-on-write */
934 rb_ary_store(op, 2, buf);
939 /* :nodoc: */
940 static VALUE clogger_init_copy(VALUE clone, VALUE orig)
942 struct clogger *a = clogger_get(orig);
943 struct clogger *b = clogger_get(clone);
945 memcpy(b, a, sizeof(struct clogger));
946 init_buffers(b);
947 duplicate_buffers(b->fmt_ops);
949 return clone;
952 #define CONST_GLOBAL_STR2(var, val) do { \
953 g_##var = rb_obj_freeze(rb_str_new(val, sizeof(val) - 1)); \
954 rb_global_variable(&g_##var); \
955 } while (0)
957 #define CONST_GLOBAL_STR(val) CONST_GLOBAL_STR2(val, #val)
960 * call-seq:
961 * clogger.respond_to?(:to_path) => true or false
962 * clogger.respond_to?(:close) => true
964 * used to delegate +:to_path+ checks for Rack webservers that optimize
965 * static file serving
967 static VALUE respond_to(VALUE self, VALUE method)
969 struct clogger *c = clogger_get(self);
970 ID id = rb_to_id(method);
972 if (close_id == id)
973 return Qtrue;
974 return rb_respond_to(c->body, id);
978 * call-seq:
979 * clogger.to_path
981 * used to proxy +:to_path+ method calls to the wrapped response body.
983 static VALUE to_path(VALUE self)
985 struct clogger *c = clogger_get(self);
986 struct stat sb;
987 int rv;
988 VALUE path = rb_funcall(c->body, to_path_id, 0);
990 /* try to avoid an extra path lookup */
991 if (rb_respond_to(c->body, to_io_id)) {
992 rv = fstat(my_fileno(c->body), &sb);
993 } else {
994 const char *cpath = StringValueCStr(path);
995 unsigned devfd;
997 * Rainbows! can use "/dev/fd/%u" in to_path output to avoid
998 * extra open() syscalls, too.
1000 if (sscanf(cpath, "/dev/fd/%u", &devfd) == 1)
1001 rv = fstat((int)devfd, &sb);
1002 else
1003 rv = stat(cpath, &sb);
1007 * calling this method implies the web server will bypass
1008 * the each method where body_bytes_sent is calculated,
1009 * so we stat and set that value here.
1011 c->body_bytes_sent = rv == 0 ? sb.st_size : 0;
1012 return path;
1016 * call-seq:
1017 * clogger.to_io
1019 * used to proxy +:to_io+ method calls to the wrapped response body.
1021 static VALUE to_io(VALUE self)
1023 struct clogger *c = clogger_get(self);
1024 struct stat sb;
1025 VALUE io = rb_convert_type(c->body, T_FILE, "IO", "to_io");
1027 if (fstat(my_fileno(io), &sb) == 0)
1028 c->body_bytes_sent = sb.st_size;
1030 return io;
1033 /* :nodoc: */
1034 static VALUE body(VALUE self)
1036 return clogger_get(self)->body;
1039 void Init_clogger_ext(void)
1041 VALUE tmp;
1043 check_clock();
1045 write_id = rb_intern("write");
1046 ltlt_id = rb_intern("<<");
1047 call_id = rb_intern("call");
1048 each_id = rb_intern("each");
1049 close_id = rb_intern("close");
1050 to_i_id = rb_intern("to_i");
1051 to_s_id = rb_intern("to_s");
1052 size_id = rb_intern("size");
1053 sq_brace_id = rb_intern("[]");
1054 new_id = rb_intern("new");
1055 to_path_id = rb_intern("to_path");
1056 to_io_id = rb_intern("to_io");
1057 respond_to_id = rb_intern("respond_to?");
1058 cClogger = rb_define_class("Clogger", rb_cObject);
1059 mFormat = rb_define_module_under(cClogger, "Format");
1060 rb_define_alloc_func(cClogger, clogger_alloc);
1061 rb_define_method(cClogger, "initialize", clogger_init, -1);
1062 rb_define_method(cClogger, "initialize_copy", clogger_init_copy, 1);
1063 rb_define_method(cClogger, "call", clogger_call, 1);
1064 rb_define_method(cClogger, "each", clogger_each, 0);
1065 rb_define_method(cClogger, "close", clogger_close, 0);
1066 rb_define_method(cClogger, "fileno", clogger_fileno, 0);
1067 rb_define_method(cClogger, "wrap_body?", clogger_wrap_body, 0);
1068 rb_define_method(cClogger, "reentrant?", clogger_reentrant, 0);
1069 rb_define_method(cClogger, "to_path", to_path, 0);
1070 rb_define_method(cClogger, "to_io", to_io, 0);
1071 rb_define_method(cClogger, "respond_to?", respond_to, 1);
1072 rb_define_method(cClogger, "body", body, 0);
1073 CONST_GLOBAL_STR(REMOTE_ADDR);
1074 CONST_GLOBAL_STR(HTTP_X_FORWARDED_FOR);
1075 CONST_GLOBAL_STR(REQUEST_METHOD);
1076 CONST_GLOBAL_STR(PATH_INFO);
1077 CONST_GLOBAL_STR(QUERY_STRING);
1078 CONST_GLOBAL_STR(REQUEST_URI);
1079 CONST_GLOBAL_STR(HTTP_VERSION);
1080 CONST_GLOBAL_STR2(rack_errors, "rack.errors");
1081 CONST_GLOBAL_STR2(rack_input, "rack.input");
1082 CONST_GLOBAL_STR2(rack_multithread, "rack.multithread");
1083 CONST_GLOBAL_STR2(dash, "-");
1084 CONST_GLOBAL_STR2(space, " ");
1085 CONST_GLOBAL_STR2(question_mark, "?");
1086 CONST_GLOBAL_STR2(rack_request_cookie_hash, "rack.request.cookie_hash");
1088 tmp = rb_const_get(rb_cObject, rb_intern("Rack"));
1089 tmp = rb_const_get(tmp, rb_intern("Utils"));
1090 cHeaderHash = rb_const_get(tmp, rb_intern("HeaderHash"));