clogger.c: comment to explain the lack of GC guard
[clogger.git] / ext / clogger_ext / clogger.c
blob83ce76a991141ec22549fc927acfb1ffce092da1
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 respond_to_id;
133 static VALUE cClogger;
134 static VALUE mFormat;
135 static VALUE cHeaderHash;
137 /* common hash lookup keys */
138 static VALUE g_HTTP_X_FORWARDED_FOR;
139 static VALUE g_REMOTE_ADDR;
140 static VALUE g_REQUEST_METHOD;
141 static VALUE g_PATH_INFO;
142 static VALUE g_REQUEST_URI;
143 static VALUE g_QUERY_STRING;
144 static VALUE g_HTTP_VERSION;
145 static VALUE g_rack_errors;
146 static VALUE g_rack_input;
147 static VALUE g_rack_multithread;
148 static VALUE g_dash;
149 static VALUE g_space;
150 static VALUE g_question_mark;
151 static VALUE g_rack_request_cookie_hash;
153 #define LOG_BUF_INIT_SIZE 128
155 static void init_buffers(struct clogger *c)
157 c->log_buf = rb_str_buf_new(LOG_BUF_INIT_SIZE);
160 static inline int need_escape(unsigned c)
162 assert(c <= 0xff);
163 return !!(c == '\'' || c == '"' || c <= 0x1f || c >= 0x7f);
166 /* we are encoding-agnostic, clients can send us all sorts of junk */
167 static VALUE byte_xs(VALUE obj)
169 static const char esc[] = "0123456789ABCDEF";
170 unsigned char *new_ptr;
171 VALUE from = rb_obj_as_string(obj);
172 const unsigned char *ptr = (const 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 = (const 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 RB_GC_GUARD(from);
206 return rv;
209 static void clogger_mark(void *ptr)
211 struct clogger *c = ptr;
213 rb_gc_mark(c->app);
214 rb_gc_mark(c->fmt_ops);
215 rb_gc_mark(c->logger);
216 rb_gc_mark(c->log_buf);
217 rb_gc_mark(c->env);
218 rb_gc_mark(c->cookies);
219 rb_gc_mark(c->status);
220 rb_gc_mark(c->headers);
221 rb_gc_mark(c->body);
224 static VALUE clogger_alloc(VALUE klass)
226 struct clogger *c;
228 return Data_Make_Struct(klass, struct clogger, clogger_mark, -1, c);
231 static struct clogger *clogger_get(VALUE self)
233 struct clogger *c;
235 Data_Get_Struct(self, struct clogger, c);
236 assert(c);
237 return c;
240 /* only for writing to regular files, not stupid crap like NFS */
241 static void write_full(int fd, const char *buf, size_t count)
243 ssize_t r;
245 while (count > 0) {
246 r = nogvl_write(fd, buf, count);
248 if ((size_t)r == count) { /* overwhelmingly likely */
249 return;
250 } else if (r > 0) {
251 count -= r;
252 buf += r;
253 } else {
254 if (errno == EINTR || errno == EAGAIN)
255 continue; /* poor souls on NFS and like: */
256 if (!errno)
257 errno = ENOSPC;
258 rb_sys_fail("write");
264 * allow us to use write_full() iff we detect a blocking file
265 * descriptor that wouldn't play nicely with Ruby threading/fibers
267 static int raw_fd(VALUE my_fd)
269 #if defined(HAVE_FCNTL) && defined(F_GETFL) && defined(O_NONBLOCK)
270 int fd;
271 int flags;
273 if (NIL_P(my_fd))
274 return -1;
275 fd = NUM2INT(my_fd);
277 flags = fcntl(fd, F_GETFL);
278 if (flags < 0)
279 rb_sys_fail("fcntl");
281 if (flags & O_NONBLOCK) {
282 struct stat sb;
284 if (fstat(fd, &sb) < 0)
285 return -1;
287 /* O_NONBLOCK is no-op for regular files: */
288 if (! S_ISREG(sb.st_mode))
289 return -1;
291 return fd;
292 #else /* platforms w/o fcntl/F_GETFL/O_NONBLOCK */
293 return -1;
294 #endif /* platforms w/o fcntl/F_GETFL/O_NONBLOCK */
297 /* :nodoc: */
298 static VALUE clogger_reentrant(VALUE self)
300 return clogger_get(self)->reentrant == 0 ? Qfalse : Qtrue;
303 /* :nodoc: */
304 static VALUE clogger_wrap_body(VALUE self)
306 return clogger_get(self)->wrap_body == 0 ? Qfalse : Qtrue;
309 static void append_status(struct clogger *c)
311 char buf[sizeof("999")];
312 int nr;
313 VALUE status = c->status;
315 if (TYPE(status) != T_FIXNUM) {
316 status = rb_funcall(status, to_i_id, 0);
317 /* no way it's a valid status code (at least not HTTP/1.1) */
318 if (TYPE(status) != T_FIXNUM) {
319 rb_str_buf_append(c->log_buf, g_dash);
320 return;
324 nr = FIX2INT(status);
325 if (nr >= 100 && nr <= 999) {
326 nr = snprintf(buf, sizeof(buf), "%03d", nr);
327 assert(nr == 3);
328 rb_str_buf_cat(c->log_buf, buf, nr);
329 } else {
330 /* raise?, swap for 500? */
331 rb_str_buf_append(c->log_buf, g_dash);
335 /* this is Rack 1.0.0-compatible, won't try to parse commas in XFF */
336 static void append_ip(struct clogger *c)
338 VALUE env = c->env;
339 VALUE tmp = rb_hash_aref(env, g_HTTP_X_FORWARDED_FOR);
341 if (NIL_P(tmp)) {
342 /* can't be faked on any real server, so no escape */
343 tmp = rb_hash_aref(env, g_REMOTE_ADDR);
344 if (NIL_P(tmp))
345 tmp = g_dash;
346 } else {
347 tmp = byte_xs(tmp);
349 rb_str_buf_append(c->log_buf, tmp);
352 static void append_body_bytes_sent(struct clogger *c)
354 char buf[(sizeof(off_t) * 8) / 3 + 1];
355 const char *fmt = sizeof(off_t) == sizeof(long) ? "%ld" : "%lld";
356 int nr = snprintf(buf, sizeof(buf), fmt, c->body_bytes_sent);
358 assert(nr > 0 && nr < (int)sizeof(buf));
359 rb_str_buf_cat(c->log_buf, buf, nr);
362 static void append_ts(struct clogger *c, VALUE op, struct timespec *ts)
364 char buf[sizeof(".000000") + ((sizeof(ts->tv_sec) * 8) / 3)];
365 int nr;
366 char *fmt = RSTRING_PTR(rb_ary_entry(op, 1));
367 int ndiv = NUM2INT(rb_ary_entry(op, 2));
368 int usec = ts->tv_nsec / 1000;
370 nr = snprintf(buf, sizeof(buf), fmt,
371 (int)ts->tv_sec, (int)(usec / ndiv));
372 assert(nr > 0 && nr < (int)sizeof(buf));
373 rb_str_buf_cat(c->log_buf, buf, nr);
376 static void append_request_time_fmt(struct clogger *c, VALUE op)
378 struct timespec now;
380 clock_gettime(hopefully_CLOCK_MONOTONIC, &now);
381 clock_diff(&now, &c->ts_start);
382 append_ts(c, op, &now);
385 static void append_time_fmt(struct clogger *c, VALUE op)
387 struct timespec now;
388 int r = clock_gettime(CLOCK_REALTIME, &now);
390 if (unlikely(r != 0))
391 rb_sys_fail("clock_gettime(CLOCK_REALTIME)");
392 append_ts(c, op, &now);
395 static void append_request_uri(struct clogger *c)
397 VALUE tmp;
399 tmp = rb_hash_aref(c->env, g_REQUEST_URI);
400 if (NIL_P(tmp)) {
401 tmp = rb_hash_aref(c->env, g_PATH_INFO);
402 if (!NIL_P(tmp))
403 rb_str_buf_append(c->log_buf, byte_xs(tmp));
404 tmp = rb_hash_aref(c->env, g_QUERY_STRING);
405 if (!NIL_P(tmp) && RSTRING_LEN(tmp) != 0) {
406 rb_str_buf_append(c->log_buf, g_question_mark);
407 rb_str_buf_append(c->log_buf, byte_xs(tmp));
409 } else {
410 rb_str_buf_append(c->log_buf, byte_xs(tmp));
414 static void append_request(struct clogger *c)
416 VALUE tmp;
418 /* REQUEST_METHOD doesn't need escaping, Rack::Lint governs it */
419 tmp = rb_hash_aref(c->env, g_REQUEST_METHOD);
420 if (!NIL_P(tmp))
421 rb_str_buf_append(c->log_buf, tmp);
423 rb_str_buf_append(c->log_buf, g_space);
425 append_request_uri(c);
427 /* HTTP_VERSION can be injected by malicious clients */
428 tmp = rb_hash_aref(c->env, g_HTTP_VERSION);
429 if (!NIL_P(tmp)) {
430 rb_str_buf_append(c->log_buf, g_space);
431 rb_str_buf_append(c->log_buf, byte_xs(tmp));
435 static void append_request_length(struct clogger *c)
437 VALUE tmp = rb_hash_aref(c->env, g_rack_input);
438 if (NIL_P(tmp)) {
439 rb_str_buf_append(c->log_buf, g_dash);
440 } else {
441 tmp = rb_funcall(tmp, size_id, 0);
442 rb_str_buf_append(c->log_buf, rb_funcall(tmp, to_s_id, 0));
446 static long local_gmtoffset(struct tm *tm)
448 time_t t = time(NULL);
450 tzset();
451 localtime_r(&t, tm);
454 * HAVE_STRUCT_TM_TM_GMTOFF may be defined in Ruby headers
455 * HAVE_ST_TM_GMTOFF is defined ourselves.
457 #if defined(HAVE_STRUCT_TM_TM_GMTOFF) || defined(HAVE_ST_TM_GMTOFF)
458 return tm->tm_gmtoff / 60;
459 #else
460 return -(tm->tm_isdst ? timezone - 3600 : timezone) / 60;
461 #endif
464 static void append_time_iso8601(struct clogger *c)
466 char buf[sizeof("1970-01-01T00:00:00+00:00")];
467 struct tm tm;
468 int nr;
469 long gmtoff = local_gmtoffset(&tm);
471 nr = snprintf(buf, sizeof(buf),
472 "%4d-%02d-%02dT%02d:%02d:%02d%c%02d:%02d",
473 tm.tm_year + 1900, tm.tm_mon + 1,
474 tm.tm_mday, tm.tm_hour,
475 tm.tm_min, tm.tm_sec,
476 gmtoff < 0 ? '-' : '+',
477 abs(gmtoff / 60), abs(gmtoff % 60));
478 assert(nr == (sizeof(buf) - 1) && "snprintf fail");
479 rb_str_buf_cat(c->log_buf, buf, sizeof(buf) - 1);
482 static const char months[] = "Jan\0Feb\0Mar\0Apr\0May\0Jun\0"
483 "Jul\0Aug\0Sep\0Oct\0Nov\0Dec";
485 static void append_time_local(struct clogger *c)
487 char buf[sizeof("01/Jan/1970:00:00:00 +0000")];
488 struct tm tm;
489 int nr;
490 long gmtoff = local_gmtoffset(&tm);
492 nr = snprintf(buf, sizeof(buf),
493 "%02d/%s/%d:%02d:%02d:%02d %c%02d%02d",
494 tm.tm_mday, months + (tm.tm_mon * sizeof("Jan")),
495 tm.tm_year + 1900, tm.tm_hour,
496 tm.tm_min, tm.tm_sec,
497 gmtoff < 0 ? '-' : '+',
498 abs(gmtoff / 60), abs(gmtoff % 60));
499 assert(nr == (sizeof(buf) - 1) && "snprintf fail");
500 rb_str_buf_cat(c->log_buf, buf, sizeof(buf) - 1);
503 static void append_time_utc(struct clogger *c)
505 char buf[sizeof("01/Jan/1970:00:00:00 +0000")];
506 struct tm tm;
507 int nr;
508 time_t t = time(NULL);
510 gmtime_r(&t, &tm);
511 nr = snprintf(buf, sizeof(buf),
512 "%02d/%s/%d:%02d:%02d:%02d +0000",
513 tm.tm_mday, months + (tm.tm_mon * sizeof("Jan")),
514 tm.tm_year + 1900, tm.tm_hour,
515 tm.tm_min, tm.tm_sec);
516 assert(nr == (sizeof(buf) - 1) && "snprintf fail");
517 rb_str_buf_cat(c->log_buf, buf, sizeof(buf) - 1);
520 static void
521 append_time(struct clogger *c, enum clogger_opcode op, VALUE fmt, VALUE buf)
523 char *buf_ptr = RSTRING_PTR(buf);
524 size_t buf_size = RSTRING_LEN(buf) + 1; /* "\0" */
525 size_t nr;
526 struct tm tmp;
527 time_t t = time(NULL);
529 if (op == CL_OP_TIME_LOCAL)
530 localtime_r(&t, &tmp);
531 else if (op == CL_OP_TIME_UTC)
532 gmtime_r(&t, &tmp);
533 else
534 assert(0 && "unknown op");
536 nr = strftime(buf_ptr, buf_size, RSTRING_PTR(fmt), &tmp);
537 assert(nr < buf_size && "time format too small!");
538 rb_str_buf_cat(c->log_buf, buf_ptr, nr);
541 static void append_pid(struct clogger *c)
543 char buf[(sizeof(pid_t) * 8) / 3 + 1];
544 int nr = snprintf(buf, sizeof(buf), "%d", (int)getpid());
546 assert(nr > 0 && nr < (int)sizeof(buf));
547 rb_str_buf_cat(c->log_buf, buf, nr);
550 static void append_eval(struct clogger *c, VALUE str)
552 int state = -1;
553 VALUE rv = rb_eval_string_protect(RSTRING_PTR(str), &state);
555 rv = state == 0 ? rb_obj_as_string(rv) : g_dash;
556 rb_str_buf_append(c->log_buf, rv);
559 static void append_cookie(struct clogger *c, VALUE key)
561 VALUE cookie;
563 if (c->cookies == Qfalse)
564 c->cookies = rb_hash_aref(c->env, g_rack_request_cookie_hash);
566 if (NIL_P(c->cookies)) {
567 cookie = g_dash;
568 } else {
569 cookie = rb_hash_aref(c->cookies, key);
570 cookie = NIL_P(cookie) ? g_dash : byte_xs(cookie);
572 rb_str_buf_append(c->log_buf, cookie);
575 static void append_request_env(struct clogger *c, VALUE key)
577 VALUE tmp = rb_hash_aref(c->env, key);
579 tmp = NIL_P(tmp) ? g_dash : byte_xs(tmp);
580 rb_str_buf_append(c->log_buf, tmp);
583 static void append_response(struct clogger *c, VALUE key)
585 VALUE v;
587 assert(rb_obj_is_kind_of(c->headers, cHeaderHash) && "not HeaderHash");
589 v = rb_funcall(c->headers, sq_brace_id, 1, key);
590 v = NIL_P(v) ? g_dash : byte_xs(v);
591 rb_str_buf_append(c->log_buf, v);
594 static void special_var(struct clogger *c, enum clogger_special var)
596 switch (var) {
597 case CL_SP_body_bytes_sent:
598 append_body_bytes_sent(c);
599 break;
600 case CL_SP_status:
601 append_status(c);
602 break;
603 case CL_SP_request:
604 append_request(c);
605 break;
606 case CL_SP_request_length:
607 append_request_length(c);
608 break;
609 case CL_SP_response_length:
610 if (c->body_bytes_sent == 0)
611 rb_str_buf_append(c->log_buf, g_dash);
612 else
613 append_body_bytes_sent(c);
614 break;
615 case CL_SP_ip:
616 append_ip(c);
617 break;
618 case CL_SP_pid:
619 append_pid(c);
620 break;
621 case CL_SP_request_uri:
622 append_request_uri(c);
623 break;
624 case CL_SP_time_iso8601:
625 append_time_iso8601(c);
626 break;
627 case CL_SP_time_local:
628 append_time_local(c);
629 break;
630 case CL_SP_time_utc:
631 append_time_utc(c);
635 static VALUE cwrite(struct clogger *c)
637 const VALUE ops = c->fmt_ops;
638 long i;
639 long len = RARRAY_LEN(ops);
640 VALUE dst = c->log_buf;
642 rb_str_set_len(dst, 0);
644 for (i = 0; i < len; i++) {
645 VALUE op = rb_ary_entry(ops, i);
646 enum clogger_opcode opcode = FIX2INT(rb_ary_entry(op, 0));
647 VALUE op1 = rb_ary_entry(op, 1);
649 switch (opcode) {
650 case CL_OP_LITERAL:
651 rb_str_buf_append(dst, op1);
652 break;
653 case CL_OP_REQUEST:
654 append_request_env(c, op1);
655 break;
656 case CL_OP_RESPONSE:
657 append_response(c, op1);
658 break;
659 case CL_OP_SPECIAL:
660 special_var(c, FIX2INT(op1));
661 break;
662 case CL_OP_EVAL:
663 append_eval(c, op1);
664 break;
665 case CL_OP_TIME_LOCAL:
666 case CL_OP_TIME_UTC: {
667 VALUE arg2 = rb_ary_entry(op, 2);
668 append_time(c, opcode, op1, arg2);
670 break;
671 case CL_OP_REQUEST_TIME:
672 append_request_time_fmt(c, op);
673 break;
674 case CL_OP_TIME:
675 append_time_fmt(c, op);
676 break;
677 case CL_OP_COOKIE:
678 append_cookie(c, op1);
679 break;
683 if (c->fd >= 0) {
684 write_full(c->fd, RSTRING_PTR(dst), RSTRING_LEN(dst));
685 /* no need for RB_GC_GUARD(dst) here, marked as c->log_buf */
686 } else {
687 VALUE logger = c->logger;
689 if (NIL_P(logger)) {
690 logger = rb_hash_aref(c->env, g_rack_errors);
691 rb_funcall(logger, write_id, 1, dst);
692 } else {
693 rb_funcall(logger, ltlt_id, 1, dst);
697 return Qnil;
700 static VALUE clogger_write(VALUE self)
702 return cwrite(clogger_get(self));
705 static void init_logger(struct clogger *c, VALUE path)
707 ID id;
709 if (!NIL_P(path) && !NIL_P(c->logger))
710 rb_raise(rb_eArgError, ":logger and :path are independent");
711 if (!NIL_P(path)) {
712 VALUE ab = rb_str_new2("ab");
713 id = rb_intern("open");
714 c->logger = rb_funcall(rb_cFile, id, 2, path, ab);
717 id = rb_intern("sync=");
718 if (rb_respond_to(c->logger, id))
719 rb_funcall(c->logger, id, 1, Qtrue);
721 id = rb_intern("fileno");
722 if (rb_respond_to(c->logger, id))
723 c->fd = raw_fd(rb_funcall(c->logger, id, 0));
727 * call-seq:
728 * Clogger.new(app, :logger => $stderr, :format => string) => obj
730 * Creates a new Clogger object that wraps +app+. +:logger+ may
731 * be any object that responds to the "<<" method with a string argument.
732 * Instead of +:logger+, +:path+ may be specified to be a :path of a File
733 * that will be opened in append mode.
735 static VALUE clogger_init(int argc, VALUE *argv, VALUE self)
737 struct clogger *c = clogger_get(self);
738 VALUE o = Qnil;
739 VALUE fmt = rb_const_get(mFormat, rb_intern("Common"));
741 rb_scan_args(argc, argv, "11", &c->app, &o);
742 c->fd = -1;
743 c->logger = Qnil;
744 c->reentrant = -1; /* auto-detect */
746 if (TYPE(o) == T_HASH) {
747 VALUE tmp;
749 tmp = rb_hash_aref(o, ID2SYM(rb_intern("path")));
750 c->logger = rb_hash_aref(o, ID2SYM(rb_intern("logger")));
751 init_logger(c, tmp);
753 tmp = rb_hash_aref(o, ID2SYM(rb_intern("format")));
754 if (!NIL_P(tmp))
755 fmt = tmp;
757 tmp = rb_hash_aref(o, ID2SYM(rb_intern("reentrant")));
758 switch (TYPE(tmp)) {
759 case T_TRUE:
760 c->reentrant = 1;
761 break;
762 case T_FALSE:
763 c->reentrant = 0;
764 case T_NIL:
765 break;
766 default:
767 rb_raise(rb_eArgError, ":reentrant must be boolean");
771 init_buffers(c);
772 c->fmt_ops = rb_funcall(self, rb_intern("compile_format"), 2, fmt, o);
774 if (Qtrue == rb_funcall(self, rb_intern("need_response_headers?"),
775 1, c->fmt_ops))
776 c->need_resp = 1;
777 if (Qtrue == rb_funcall(self, rb_intern("need_wrap_body?"),
778 1, c->fmt_ops))
779 c->wrap_body = 1;
781 return self;
784 static VALUE body_iter_i(VALUE str, VALUE self)
786 struct clogger *c = clogger_get(self);
788 str = rb_obj_as_string(str);
789 c->body_bytes_sent += RSTRING_LEN(str);
791 return rb_yield(str);
794 static VALUE body_close(VALUE self)
796 struct clogger *c = clogger_get(self);
798 if (rb_respond_to(c->body, close_id))
799 return rb_funcall(c->body, close_id, 0);
800 return Qnil;
804 * call-seq:
805 * clogger.each { |part| socket.write(part) }
807 * Delegates the body#each call to the underlying +body+ object
808 * while tracking the number of bytes yielded. This will log
809 * the request.
811 static VALUE clogger_each(VALUE self)
813 struct clogger *c = clogger_get(self);
815 rb_need_block();
816 c->body_bytes_sent = 0;
817 rb_iterate(rb_each, c->body, body_iter_i, self);
819 return self;
823 * call-seq:
824 * clogger.close
826 * Delegates the body#close call to the underlying +body+ object.
827 * This is only used when Clogger is wrapping the +body+ of a Rack
828 * response and should be automatically called by the web server.
830 static VALUE clogger_close(VALUE self)
833 return rb_ensure(body_close, self, clogger_write, self);
836 /* :nodoc: */
837 static VALUE clogger_fileno(VALUE self)
839 struct clogger *c = clogger_get(self);
841 return c->fd < 0 ? Qnil : INT2NUM(c->fd);
844 static VALUE ccall(struct clogger *c, VALUE env)
846 VALUE rv;
848 clock_gettime(hopefully_CLOCK_MONOTONIC, &c->ts_start);
849 c->env = env;
850 c->cookies = Qfalse;
851 rv = rb_funcall(c->app, call_id, 1, env);
852 if (TYPE(rv) == T_ARRAY && RARRAY_LEN(rv) == 3) {
853 c->status = rb_ary_entry(rv, 0);
854 c->headers = rb_ary_entry(rv, 1);
855 c->body = rb_ary_entry(rv, 2);
857 rv = rb_ary_dup(rv);
858 if (c->need_resp &&
859 ! rb_obj_is_kind_of(c->headers, cHeaderHash)) {
860 c->headers = rb_funcall(cHeaderHash, new_id, 1,
861 c->headers);
862 rb_ary_store(rv, 1, c->headers);
864 } else {
865 VALUE tmp = rb_inspect(rv);
867 c->status = INT2FIX(500);
868 c->headers = c->body = rb_ary_new();
869 cwrite(c);
870 rb_raise(rb_eTypeError,
871 "app response not a 3 element Array: %s",
872 RSTRING_PTR(tmp));
873 RB_GC_GUARD(tmp);
876 return rv;
880 * call-seq:
881 * clogger.call(env) => [ status, headers, body ]
883 * calls the wrapped Rack application with +env+, returns the
884 * [status, headers, body ] tuplet required by Rack.
886 static VALUE clogger_call(VALUE self, VALUE env)
888 struct clogger *c = clogger_get(self);
889 VALUE rv;
891 env = rb_check_convert_type(env, T_HASH, "Hash", "to_hash");
893 if (c->wrap_body) {
894 /* XXX: we assume the existence of the GVL here: */
895 if (c->reentrant < 0) {
896 VALUE tmp = rb_hash_aref(env, g_rack_multithread);
897 c->reentrant = Qfalse == tmp ? 0 : 1;
900 if (c->reentrant) {
901 self = rb_obj_dup(self);
902 c = clogger_get(self);
905 rv = ccall(c, env);
906 assert(!OBJ_FROZEN(rv) && "frozen response array");
907 rb_ary_store(rv, 2, self);
909 return rv;
912 rv = ccall(c, env);
913 cwrite(c);
915 return rv;
918 static void duplicate_buffers(VALUE ops)
920 long i;
921 long len = RARRAY_LEN(ops);
923 for (i = 0; i < len; i++) {
924 VALUE op = rb_ary_entry(ops, i);
925 enum clogger_opcode opcode = FIX2INT(rb_ary_entry(op, 0));
927 if (opcode == CL_OP_TIME_LOCAL || opcode == CL_OP_TIME_UTC) {
928 VALUE buf = rb_ary_entry(op, 2);
929 Check_Type(buf, T_STRING);
930 buf = rb_str_dup(buf);
931 rb_str_modify(buf); /* trigger copy-on-write */
932 rb_ary_store(op, 2, buf);
937 /* :nodoc: */
938 static VALUE clogger_init_copy(VALUE clone, VALUE orig)
940 struct clogger *a = clogger_get(orig);
941 struct clogger *b = clogger_get(clone);
943 memcpy(b, a, sizeof(struct clogger));
944 init_buffers(b);
945 duplicate_buffers(b->fmt_ops);
947 return clone;
950 #define CONST_GLOBAL_STR2(var, val) do { \
951 g_##var = rb_obj_freeze(rb_str_new(val, sizeof(val) - 1)); \
952 rb_global_variable(&g_##var); \
953 } while (0)
955 #define CONST_GLOBAL_STR(val) CONST_GLOBAL_STR2(val, #val)
958 * call-seq:
959 * clogger.respond_to?(:to_path) => true or false
960 * clogger.respond_to?(:close) => true
962 * used to delegate +:to_path+ checks for Rack webservers that optimize
963 * static file serving
965 static VALUE respond_to(VALUE self, VALUE method)
967 struct clogger *c = clogger_get(self);
968 ID id = rb_to_id(method);
970 if (close_id == id)
971 return Qtrue;
972 return rb_respond_to(c->body, id);
976 * call-seq:
977 * clogger.to_path
979 * used to proxy +:to_path+ method calls to the wrapped response body.
981 static VALUE to_path(VALUE self)
983 struct clogger *c = clogger_get(self);
984 struct stat sb;
985 int rv;
986 VALUE path = rb_funcall(c->body, to_path_id, 0);
987 const char *cpath = StringValueCStr(path);
988 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 = nogvl_stat(cpath, &sb);
1000 * calling this method implies the web server will bypass
1001 * the each method where body_bytes_sent is calculated,
1002 * so we stat and set that value here.
1004 c->body_bytes_sent = rv == 0 ? sb.st_size : 0;
1005 return path;
1008 /* :nodoc: */
1009 static VALUE body(VALUE self)
1011 return clogger_get(self)->body;
1014 void Init_clogger_ext(void)
1016 VALUE tmp;
1018 check_clock();
1020 write_id = rb_intern("write");
1021 ltlt_id = rb_intern("<<");
1022 call_id = rb_intern("call");
1023 close_id = rb_intern("close");
1024 to_i_id = rb_intern("to_i");
1025 to_s_id = rb_intern("to_s");
1026 size_id = rb_intern("size");
1027 sq_brace_id = rb_intern("[]");
1028 new_id = rb_intern("new");
1029 to_path_id = rb_intern("to_path");
1030 respond_to_id = rb_intern("respond_to?");
1031 cClogger = rb_define_class("Clogger", rb_cObject);
1032 mFormat = rb_define_module_under(cClogger, "Format");
1033 rb_define_alloc_func(cClogger, clogger_alloc);
1034 rb_define_method(cClogger, "initialize", clogger_init, -1);
1035 rb_define_method(cClogger, "initialize_copy", clogger_init_copy, 1);
1036 rb_define_method(cClogger, "call", clogger_call, 1);
1037 rb_define_method(cClogger, "each", clogger_each, 0);
1038 rb_define_method(cClogger, "close", clogger_close, 0);
1039 rb_define_method(cClogger, "fileno", clogger_fileno, 0);
1040 rb_define_method(cClogger, "wrap_body?", clogger_wrap_body, 0);
1041 rb_define_method(cClogger, "reentrant?", clogger_reentrant, 0);
1042 rb_define_method(cClogger, "to_path", to_path, 0);
1043 rb_define_method(cClogger, "respond_to?", respond_to, 1);
1044 rb_define_method(cClogger, "body", body, 0);
1045 CONST_GLOBAL_STR(REMOTE_ADDR);
1046 CONST_GLOBAL_STR(HTTP_X_FORWARDED_FOR);
1047 CONST_GLOBAL_STR(REQUEST_METHOD);
1048 CONST_GLOBAL_STR(PATH_INFO);
1049 CONST_GLOBAL_STR(QUERY_STRING);
1050 CONST_GLOBAL_STR(REQUEST_URI);
1051 CONST_GLOBAL_STR(HTTP_VERSION);
1052 CONST_GLOBAL_STR2(rack_errors, "rack.errors");
1053 CONST_GLOBAL_STR2(rack_input, "rack.input");
1054 CONST_GLOBAL_STR2(rack_multithread, "rack.multithread");
1055 CONST_GLOBAL_STR2(dash, "-");
1056 CONST_GLOBAL_STR2(space, " ");
1057 CONST_GLOBAL_STR2(question_mark, "?");
1058 CONST_GLOBAL_STR2(rack_request_cookie_hash, "rack.request.cookie_hash");
1060 tmp = rb_const_get(rb_cObject, rb_intern("Rack"));
1061 tmp = rb_const_get(tmp, rb_intern("Utils"));
1062 cHeaderHash = rb_const_get(tmp, rb_intern("HeaderHash"));