16 #ifndef _POSIX_C_SOURCE
17 # define _POSIX_C_SOURCE 200112L
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
31 static clockid_t hopefully_CLOCK_MONOTONIC
;
33 static void check_clock(void)
37 hopefully_CLOCK_MONOTONIC
= CLOCK_MONOTONIC
;
39 /* we can't check this reliably at compile time */
40 if (clock_gettime(CLOCK_MONOTONIC
, &now
) == 0)
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
;
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)
69 # define unlikely(x) (x)
70 # define likely(x) (x)
86 enum clogger_special
{
87 CL_SP_body_bytes_sent
= 0,
91 CL_SP_response_length
,
113 off_t body_bytes_sent
;
114 struct timespec ts_start
;
119 int reentrant
; /* tri-state, -1:auto, 1/0 true/false */
129 static ID sq_brace_id
;
131 static ID to_path_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
;
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
)
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
);
178 for (; --len
>= 0; ptr
++) {
181 if (unlikely(need_escape(c
)))
182 new_len
+= 3; /* { '\', 'x', 'X', 'X' } */
185 len
= RSTRING_LEN(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
++) {
195 if (unlikely(need_escape(c
))) {
198 *new_ptr
++ = esc
[c
>> 4];
199 *new_ptr
++ = esc
[c
& 0xf];
204 assert(RSTRING_PTR(rv
)[RSTRING_LEN(rv
)] == '\0');
210 static void clogger_mark(void *ptr
)
212 struct clogger
*c
= ptr
;
215 rb_gc_mark(c
->fmt_ops
);
216 rb_gc_mark(c
->logger
);
217 rb_gc_mark(c
->log_buf
);
219 rb_gc_mark(c
->cookies
);
220 rb_gc_mark(c
->status
);
221 rb_gc_mark(c
->headers
);
225 static VALUE
clogger_alloc(VALUE klass
)
229 return Data_Make_Struct(klass
, struct clogger
, clogger_mark
, -1, c
);
232 static struct clogger
*clogger_get(VALUE self
)
236 Data_Get_Struct(self
, struct clogger
, 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
)
245 unsigned long ubuf
= (unsigned long)buf
;
248 r
= write(fd
, (void *)ubuf
, count
);
250 if ((size_t)r
== count
) { /* overwhelmingly likely */
256 if (errno
== EINTR
|| errno
== EAGAIN
)
257 continue; /* poor souls on NFS and like: */
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)
279 flags
= fcntl(fd
, F_GETFL
);
281 rb_sys_fail("fcntl");
283 if (flags
& O_NONBLOCK
) {
286 if (fstat(fd
, &sb
) < 0)
289 /* O_NONBLOCK is no-op for regular files: */
290 if (! S_ISREG(sb
.st_mode
))
294 #else /* platforms w/o fcntl/F_GETFL/O_NONBLOCK */
296 #endif /* platforms w/o fcntl/F_GETFL/O_NONBLOCK */
300 static VALUE
clogger_reentrant(VALUE self
)
302 return clogger_get(self
)->reentrant
== 0 ? Qfalse
: Qtrue
;
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")];
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
);
326 nr
= FIX2INT(status
);
327 if (nr
>= 100 && nr
<= 999) {
328 nr
= snprintf(buf
, sizeof(buf
), "%03d", nr
);
330 rb_str_buf_cat(c
->log_buf
, buf
, nr
);
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
)
341 VALUE tmp
= rb_hash_aref(env
, g_HTTP_X_FORWARDED_FOR
);
344 /* can't be faked on any real server, so no escape */
345 tmp
= rb_hash_aref(env
, g_REMOTE_ADDR
);
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)];
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
)
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
)
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
)
401 tmp
= rb_hash_aref(c
->env
, g_REQUEST_URI
);
403 tmp
= rb_hash_aref(c
->env
, g_PATH_INFO
);
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
));
412 rb_str_buf_append(c
->log_buf
, byte_xs(tmp
));
416 static void append_request(struct clogger
*c
)
420 /* REQUEST_METHOD doesn't need escaping, Rack::Lint governs it */
421 tmp
= rb_hash_aref(c
->env
, g_REQUEST_METHOD
);
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
);
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
);
441 rb_str_buf_append(c
->log_buf
, g_dash
);
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
);
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;
462 return -(tm
->tm_isdst
? timezone
- 3600 : timezone
) / 60;
466 static void append_time_iso8601(struct clogger
*c
)
468 char buf
[sizeof("1970-01-01T00:00:00+00:00")];
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")];
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")];
510 time_t t
= time(NULL
);
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);
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" */
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
)
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
)
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
)
565 if (c
->cookies
== Qfalse
)
566 c
->cookies
= rb_hash_aref(c
->env
, g_rack_request_cookie_hash
);
568 if (NIL_P(c
->cookies
)) {
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
)
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
)
599 case CL_SP_body_bytes_sent
:
600 append_body_bytes_sent(c
);
608 case CL_SP_request_length
:
609 append_request_length(c
);
611 case CL_SP_response_length
:
612 if (c
->body_bytes_sent
== 0)
613 rb_str_buf_append(c
->log_buf
, g_dash
);
615 append_body_bytes_sent(c
);
623 case CL_SP_request_uri
:
624 append_request_uri(c
);
626 case CL_SP_time_iso8601
:
627 append_time_iso8601(c
);
629 case CL_SP_time_local
:
630 append_time_local(c
);
637 static VALUE
cwrite(struct clogger
*c
)
639 const VALUE ops
= c
->fmt_ops
;
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);
653 rb_str_buf_append(dst
, op1
);
656 append_request_env(c
, op1
);
659 append_response(c
, op1
);
662 special_var(c
, FIX2INT(op1
));
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
);
673 case CL_OP_REQUEST_TIME
:
674 append_request_time_fmt(c
, op
);
677 append_time_fmt(c
, op
);
680 append_cookie(c
, op1
);
686 write_full(c
->fd
, RSTRING_PTR(dst
), RSTRING_LEN(dst
));
688 VALUE logger
= c
->logger
;
691 logger
= rb_hash_aref(c
->env
, g_rack_errors
);
692 rb_funcall(logger
, write_id
, 1, dst
);
694 rb_funcall(logger
, ltlt_id
, 1, dst
);
701 static VALUE
clogger_write(VALUE self
)
703 return cwrite(clogger_get(self
));
706 static void init_logger(struct clogger
*c
, VALUE path
)
710 if (!NIL_P(path
) && !NIL_P(c
->logger
))
711 rb_raise(rb_eArgError
, ":logger and :path are independent");
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));
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
);
740 VALUE fmt
= rb_const_get(mFormat
, rb_intern("Common"));
742 rb_scan_args(argc
, argv
, "11", &c
->app
, &o
);
745 c
->reentrant
= -1; /* auto-detect */
747 if (TYPE(o
) == T_HASH
) {
750 tmp
= rb_hash_aref(o
, ID2SYM(rb_intern("path")));
751 c
->logger
= rb_hash_aref(o
, ID2SYM(rb_intern("logger")));
754 tmp
= rb_hash_aref(o
, ID2SYM(rb_intern("format")));
758 tmp
= rb_hash_aref(o
, ID2SYM(rb_intern("reentrant")));
768 rb_raise(rb_eArgError
, ":reentrant must be boolean");
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?"),
778 if (Qtrue
== rb_funcall(self
, rb_intern("need_wrap_body?"),
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);
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
812 static VALUE
clogger_each(VALUE self
)
814 struct clogger
*c
= clogger_get(self
);
817 c
->body_bytes_sent
= 0;
818 rb_iterate(rb_each
, c
->body
, body_iter_i
, self
);
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
);
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
)
849 clock_gettime(hopefully_CLOCK_MONOTONIC
, &c
->ts_start
);
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);
860 ! rb_obj_is_kind_of(c
->headers
, cHeaderHash
)) {
861 c
->headers
= rb_funcall(cHeaderHash
, new_id
, 1,
863 rb_ary_store(rv
, 1, c
->headers
);
866 VALUE tmp
= rb_inspect(rv
);
868 c
->status
= INT2FIX(500);
869 c
->headers
= c
->body
= rb_ary_new();
871 rb_raise(rb_eTypeError
,
872 "app response not a 3 element Array: %s",
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
);
892 env
= rb_check_convert_type(env
, T_HASH
, "Hash", "to_hash");
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;
902 self
= rb_obj_dup(self
);
903 c
= clogger_get(self
);
907 assert(!OBJ_FROZEN(rv
) && "frozen response array");
908 rb_ary_store(rv
, 2, self
);
919 static void duplicate_buffers(VALUE ops
)
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
);
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
));
946 duplicate_buffers(b
->fmt_ops
);
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); \
956 #define CONST_GLOBAL_STR(val) CONST_GLOBAL_STR2(val, #val)
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
);
973 return rb_respond_to(c
->body
, id
);
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
);
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
);
993 const char *cpath
= StringValueCStr(path
);
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
);
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;
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
);
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
;
1033 static VALUE
body(VALUE self
)
1035 return clogger_get(self
)->body
;
1038 void Init_clogger_ext(void)
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"));