xref: /unit/src/ruby/nxt_ruby.c (revision 743:e0f0cd7d244a)
1 /*
2  * Copyright (C) Alexander Borisov
3  * Copyright (C) NGINX, Inc.
4  */
5 
6 #include <ruby/nxt_ruby.h>
7 
8 #include <nxt_unit.h>
9 #include <nxt_unit_request.h>
10 
11 
12 #define NXT_RUBY_RACK_API_VERSION_MAJOR  1
13 #define NXT_RUBY_RACK_API_VERSION_MINOR  3
14 
15 #define NXT_RUBY_STRINGIZE_HELPER(x)     #x
16 #define NXT_RUBY_STRINGIZE(x)            NXT_RUBY_STRINGIZE_HELPER(x)
17 
18 #define NXT_RUBY_LIB_VERSION                                                   \
19     NXT_RUBY_STRINGIZE(RUBY_API_VERSION_MAJOR)                                 \
20     "." NXT_RUBY_STRINGIZE(RUBY_API_VERSION_MINOR)                             \
21     "." NXT_RUBY_STRINGIZE(RUBY_API_VERSION_TEENY)
22 
23 
24 typedef struct {
25     nxt_task_t  *task;
26     nxt_str_t   *script;
27     VALUE       builder;
28 } nxt_ruby_rack_init_t;
29 
30 
31 static nxt_int_t nxt_ruby_init(nxt_task_t *task, nxt_common_app_conf_t *conf);
32 static VALUE nxt_ruby_init_basic(VALUE arg);
33 static nxt_int_t nxt_ruby_init_io(nxt_task_t *task);
34 static VALUE nxt_ruby_rack_init(nxt_ruby_rack_init_t *rack_init);
35 
36 static VALUE nxt_ruby_require_rubygems(VALUE arg);
37 static VALUE nxt_ruby_bundler_setup(VALUE arg);
38 static VALUE nxt_ruby_require_rack(VALUE arg);
39 static VALUE nxt_ruby_rack_parse_script(VALUE ctx);
40 static VALUE nxt_ruby_rack_env_create(VALUE arg);
41 static void nxt_ruby_request_handler(nxt_unit_request_info_t *req);
42 
43 static VALUE nxt_ruby_rack_app_run(VALUE arg);
44 static int nxt_ruby_read_request(VALUE hash_env);
45 nxt_inline void nxt_ruby_add_sptr(VALUE hash_env,
46     const char *name, uint32_t name_len, nxt_unit_sptr_t *sptr, uint32_t len);
47 nxt_inline void nxt_ruby_add_str(VALUE hash_env,
48     const char *name, uint32_t name_len, char *str, uint32_t len);
49 static nxt_int_t nxt_ruby_rack_result_status(VALUE result);
50 static int nxt_ruby_rack_result_headers(VALUE result, nxt_int_t status);
51 static int nxt_ruby_hash_info(VALUE r_key, VALUE r_value, VALUE arg);
52 static int nxt_ruby_hash_add(VALUE r_key, VALUE r_value, VALUE arg);
53 static int nxt_ruby_rack_result_body(VALUE result);
54 static int nxt_ruby_rack_result_body_file_write(VALUE filepath);
55 static VALUE nxt_ruby_rack_result_body_each(VALUE body);
56 
57 static void nxt_ruby_exception_log(nxt_task_t *task, uint32_t level,
58     const char *desc);
59 
60 static void nxt_ruby_atexit(void);
61 
62 
63 static uint32_t  compat[] = {
64     NXT_VERNUM, NXT_DEBUG,
65 };
66 
67 static VALUE               nxt_ruby_rackup;
68 static VALUE               nxt_ruby_call;
69 static VALUE               nxt_ruby_env;
70 static VALUE               nxt_ruby_io_input;
71 static VALUE               nxt_ruby_io_error;
72 static nxt_ruby_run_ctx_t  nxt_ruby_run_ctx;
73 
74 NXT_EXPORT nxt_app_module_t  nxt_app_module = {
75     sizeof(compat),
76     compat,
77     nxt_string("ruby"),
78     ruby_version,
79     nxt_ruby_init,
80 };
81 
82 
83 static nxt_int_t
84 nxt_ruby_init(nxt_task_t *task, nxt_common_app_conf_t *conf)
85 {
86     int                   state, rc;
87     VALUE                 dummy, res;
88     nxt_unit_ctx_t        *unit_ctx;
89     nxt_unit_init_t       ruby_unit_init;
90     nxt_ruby_rack_init_t  rack_init;
91 
92     ruby_init();
93     Init_stack(&dummy);
94     ruby_init_loadpath();
95     ruby_script("NGINX_Unit");
96 
97     rack_init.task = task;
98     rack_init.script = &conf->u.ruby.script;
99 
100     res = rb_protect(nxt_ruby_init_basic,
101                      (VALUE) (uintptr_t) &rack_init, &state);
102     if (nxt_slow_path(res == Qnil || state != 0)) {
103         nxt_ruby_exception_log(task, NXT_LOG_ALERT,
104                                "Failed to init basic variables");
105         return NXT_ERROR;
106     }
107 
108     nxt_ruby_rackup = nxt_ruby_rack_init(&rack_init);
109     if (nxt_slow_path(nxt_ruby_rackup == Qnil)) {
110         return NXT_ERROR;
111     }
112 
113     nxt_ruby_call = rb_intern("call");
114     if (nxt_slow_path(nxt_ruby_call == Qnil)) {
115         nxt_alert(task, "Ruby: Unable to find rack entry point");
116 
117         return NXT_ERROR;
118     }
119 
120     nxt_ruby_env = rb_protect(nxt_ruby_rack_env_create, Qnil, &state);
121     if (nxt_slow_path(state != 0)) {
122         nxt_ruby_exception_log(task, NXT_LOG_ALERT,
123                                "Failed to create 'environ' variable");
124         return NXT_ERROR;
125     }
126 
127     rb_gc_register_address(&nxt_ruby_rackup);
128     rb_gc_register_address(&nxt_ruby_call);
129     rb_gc_register_address(&nxt_ruby_env);
130 
131     nxt_unit_default_init(task, &ruby_unit_init);
132 
133     ruby_unit_init.callbacks.request_handler = nxt_ruby_request_handler;
134 
135     unit_ctx = nxt_unit_init(&ruby_unit_init);
136     if (nxt_slow_path(unit_ctx == NULL)) {
137         return NXT_ERROR;
138     }
139 
140     nxt_ruby_run_ctx.unit_ctx = unit_ctx;
141 
142     rc = nxt_unit_run(unit_ctx);
143 
144     nxt_ruby_atexit();
145 
146     nxt_ruby_run_ctx.unit_ctx = NULL;
147 
148     nxt_unit_done(unit_ctx);
149 
150     exit(rc);
151 
152     return NXT_OK;
153 }
154 
155 
156 static VALUE
157 nxt_ruby_init_basic(VALUE arg)
158 {
159     int                   state;
160     nxt_int_t             rc;
161     nxt_ruby_rack_init_t  *rack_init;
162 
163     rack_init = (nxt_ruby_rack_init_t *) (uintptr_t) arg;
164 
165     state = rb_enc_find_index("encdb");
166     if (nxt_slow_path(state == 0)) {
167         nxt_alert(rack_init->task,
168                   "Ruby: Failed to find encoding index 'encdb'");
169 
170         return Qnil;
171     }
172 
173     rb_funcall(rb_cObject, rb_intern("require"), 1,
174                rb_str_new2("enc/trans/transdb"));
175 
176     rc = nxt_ruby_init_io(rack_init->task);
177     if (nxt_slow_path(rc != NXT_OK)) {
178         return Qnil;
179     }
180 
181     return arg;
182 }
183 
184 
185 static nxt_int_t
186 nxt_ruby_init_io(nxt_task_t *task)
187 {
188     VALUE  rb, io_input, io_error;
189 
190     io_input = nxt_ruby_stream_io_input_init();
191     rb = Data_Wrap_Struct(io_input, 0, 0, &nxt_ruby_run_ctx);
192 
193     nxt_ruby_io_input = rb_funcall(io_input, rb_intern("new"), 1, rb);
194     if (nxt_slow_path(nxt_ruby_io_input == Qnil)) {
195         nxt_alert(task, "Ruby: Failed to create environment 'rack.input' var");
196 
197         return NXT_ERROR;
198     }
199 
200     io_error = nxt_ruby_stream_io_error_init();
201     rb = Data_Wrap_Struct(io_error, 0, 0, &nxt_ruby_run_ctx);
202 
203     nxt_ruby_io_error = rb_funcall(io_error, rb_intern("new"), 1, rb);
204     if (nxt_slow_path(nxt_ruby_io_error == Qnil)) {
205         nxt_alert(task, "Ruby: Failed to create environment 'rack.error' var");
206 
207         return NXT_ERROR;
208     }
209 
210     rb_gc_register_address(&nxt_ruby_io_input);
211     rb_gc_register_address(&nxt_ruby_io_error);
212 
213     return NXT_OK;
214 }
215 
216 
217 static VALUE
218 nxt_ruby_rack_init(nxt_ruby_rack_init_t *rack_init)
219 {
220     int    state;
221     VALUE  rack, rackup, err;
222 
223     rb_protect(nxt_ruby_require_rubygems, Qnil, &state);
224     if (nxt_slow_path(state != 0)) {
225         nxt_ruby_exception_log(rack_init->task, NXT_LOG_ALERT,
226                                "Failed to require 'rubygems' package");
227         return Qnil;
228     }
229 
230     rb_protect(nxt_ruby_bundler_setup, Qnil, &state);
231     if (state != 0) {
232         err = rb_errinfo();
233 
234         if (rb_obj_is_kind_of(err, rb_eLoadError) == Qfalse) {
235             nxt_ruby_exception_log(rack_init->task, NXT_LOG_ALERT,
236                                    "Failed to require 'bundler/setup' package");
237             return Qnil;
238         }
239 
240         rb_set_errinfo(Qnil);
241     }
242 
243     rb_protect(nxt_ruby_require_rack, Qnil, &state);
244     if (nxt_slow_path(state != 0)) {
245         nxt_ruby_exception_log(rack_init->task, NXT_LOG_ALERT,
246                                "Failed to require 'rack' package");
247         return Qnil;
248     }
249 
250     rack = rb_const_get(rb_cObject, rb_intern("Rack"));
251     rack_init->builder = rb_const_get(rack, rb_intern("Builder"));
252 
253     rackup = rb_protect(nxt_ruby_rack_parse_script,
254                         (VALUE) (uintptr_t) rack_init, &state);
255     if (nxt_slow_path(TYPE(rackup) != T_ARRAY || state != 0)) {
256         nxt_ruby_exception_log(rack_init->task, NXT_LOG_ALERT,
257                                "Failed to parse rack script");
258         return Qnil;
259     }
260 
261     if (nxt_slow_path(RARRAY_LEN(rackup) < 1)) {
262         nxt_alert(rack_init->task, "Ruby: Invalid rack config file");
263         return Qnil;
264     }
265 
266     return RARRAY_PTR(rackup)[0];
267 }
268 
269 
270 static VALUE
271 nxt_ruby_require_rubygems(VALUE arg)
272 {
273     return rb_funcall(rb_cObject, rb_intern("require"), 1,
274                       rb_str_new2("rubygems"));
275 }
276 
277 
278 static VALUE
279 nxt_ruby_bundler_setup(VALUE arg)
280 {
281     return rb_funcall(rb_cObject, rb_intern("require"), 1,
282                       rb_str_new2("bundler/setup"));
283 }
284 
285 
286 static VALUE
287 nxt_ruby_require_rack(VALUE arg)
288 {
289     return rb_funcall(rb_cObject, rb_intern("require"), 1, rb_str_new2("rack"));
290 }
291 
292 
293 static VALUE
294 nxt_ruby_rack_parse_script(VALUE ctx)
295 {
296     VALUE                 script, res;
297     nxt_ruby_rack_init_t  *rack_init;
298 
299     rack_init = (nxt_ruby_rack_init_t *) (uintptr_t) ctx;
300 
301     script = rb_str_new((const char *) rack_init->script->start,
302                         (long) rack_init->script->length);
303 
304     res = rb_funcall(rack_init->builder, rb_intern("parse_file"), 1, script);
305 
306     rb_str_free(script);
307 
308     return res;
309 }
310 
311 
312 static VALUE
313 nxt_ruby_rack_env_create(VALUE arg)
314 {
315     VALUE  hash_env, version;
316 
317     hash_env = rb_hash_new();
318 
319     rb_hash_aset(hash_env, rb_str_new2("SERVER_SOFTWARE"),
320                  rb_str_new((const char *) nxt_server.start,
321                             (long) nxt_server.length));
322 
323     version = rb_ary_new();
324 
325     rb_ary_push(version, UINT2NUM(NXT_RUBY_RACK_API_VERSION_MAJOR));
326     rb_ary_push(version, UINT2NUM(NXT_RUBY_RACK_API_VERSION_MINOR));
327 
328     rb_hash_aset(hash_env, rb_str_new2("rack.version"), version);
329     rb_hash_aset(hash_env, rb_str_new2("rack.url_scheme"), rb_str_new2("http"));
330     rb_hash_aset(hash_env, rb_str_new2("rack.input"), nxt_ruby_io_input);
331     rb_hash_aset(hash_env, rb_str_new2("rack.errors"), nxt_ruby_io_error);
332     rb_hash_aset(hash_env, rb_str_new2("rack.multithread"), Qfalse);
333     rb_hash_aset(hash_env, rb_str_new2("rack.multiprocess"), Qtrue);
334     rb_hash_aset(hash_env, rb_str_new2("rack.run_once"), Qfalse);
335     rb_hash_aset(hash_env, rb_str_new2("rack.hijack?"), Qfalse);
336     rb_hash_aset(hash_env, rb_str_new2("rack.hijack"), Qnil);
337     rb_hash_aset(hash_env, rb_str_new2("rack.hijack_io"), Qnil);
338 
339     return hash_env;
340 }
341 
342 
343 static void
344 nxt_ruby_request_handler(nxt_unit_request_info_t *req)
345 {
346     int    state;
347     VALUE  res;
348 
349     nxt_ruby_run_ctx.req = req;
350 
351     res = rb_protect(nxt_ruby_rack_app_run, Qnil, &state);
352     if (nxt_slow_path(res == Qnil || state != 0)) {
353         nxt_ruby_exception_log(NULL, NXT_LOG_ERR,
354                                "Failed to run ruby script");
355     }
356 }
357 
358 
359 static VALUE
360 nxt_ruby_rack_app_run(VALUE arg)
361 {
362     int        rc;
363     VALUE      env, result;
364     nxt_int_t  status;
365 
366     env = rb_hash_dup(nxt_ruby_env);
367 
368     rc = nxt_ruby_read_request(env);
369     if (nxt_slow_path(rc != NXT_UNIT_OK)) {
370         nxt_unit_req_alert(nxt_ruby_run_ctx.req,
371                            "Ruby: Failed to process incoming request");
372 
373         goto fail;
374     }
375 
376     result = rb_funcall(nxt_ruby_rackup, nxt_ruby_call, 1, env);
377     if (nxt_slow_path(TYPE(result) != T_ARRAY)) {
378         nxt_unit_req_error(nxt_ruby_run_ctx.req,
379                            "Ruby: Invalid response format from application");
380 
381         goto fail;
382     }
383 
384     if (nxt_slow_path(RARRAY_LEN(result) != 3)) {
385         nxt_unit_req_error(nxt_ruby_run_ctx.req,
386                            "Ruby: Invalid response format from application. "
387                            "Need 3 entries [Status, Headers, Body]");
388 
389         goto fail;
390     }
391 
392     status = nxt_ruby_rack_result_status(result);
393     if (nxt_slow_path(status < 0)) {
394         nxt_unit_req_error(nxt_ruby_run_ctx.req,
395                            "Ruby: Invalid response status from application.");
396 
397         goto fail;
398     }
399 
400     rc = nxt_ruby_rack_result_headers(result, status);
401     if (nxt_slow_path(rc != NXT_UNIT_OK)) {
402         goto fail;
403     }
404 
405     rc = nxt_ruby_rack_result_body(result);
406     if (nxt_slow_path(rc != NXT_UNIT_OK)) {
407         goto fail;
408     }
409 
410     nxt_unit_request_done(nxt_ruby_run_ctx.req, rc);
411     nxt_ruby_run_ctx.req = NULL;
412 
413     rb_hash_delete(env, rb_obj_id(env));
414 
415     return result;
416 
417 fail:
418 
419     nxt_unit_request_done(nxt_ruby_run_ctx.req, NXT_UNIT_ERROR);
420     nxt_ruby_run_ctx.req = NULL;
421 
422     rb_hash_delete(env, rb_obj_id(env));
423 
424     return Qnil;
425 }
426 
427 
428 static int
429 nxt_ruby_read_request(VALUE hash_env)
430 {
431     char                *host_start, *port_start;
432     uint32_t            i, host_length, port_length;
433     nxt_unit_field_t    *f;
434     nxt_unit_request_t  *r;
435 
436     r = nxt_ruby_run_ctx.req->request;
437 
438 #define NL(S) (S), sizeof(S)-1
439 
440     nxt_ruby_add_sptr(hash_env, NL("REQUEST_METHOD"), &r->method,
441                       r->method_length);
442     nxt_ruby_add_sptr(hash_env, NL("REQUEST_URI"), &r->target,
443                       r->target_length);
444     nxt_ruby_add_sptr(hash_env, NL("PATH_INFO"), &r->path, r->path_length);
445     if (r->query.offset) {
446         nxt_ruby_add_sptr(hash_env, NL("QUERY_STRING"), &r->query,
447                           r->query_length);
448     }
449     nxt_ruby_add_sptr(hash_env, NL("SERVER_PROTOCOL"), &r->version,
450                       r->version_length);
451     nxt_ruby_add_sptr(hash_env, NL("REMOTE_ADDR"), &r->remote,
452                       r->remote_length);
453     nxt_ruby_add_sptr(hash_env, NL("SERVER_ADDR"), &r->local, r->local_length);
454 
455     for (i = 0; i < r->fields_count; i++) {
456         f = r->fields + i;
457 
458         nxt_ruby_add_sptr(hash_env, nxt_unit_sptr_get(&f->name), f->name_length,
459                           &f->value, f->value_length);
460     }
461 
462     if (r->content_length_field != NXT_UNIT_NONE_FIELD) {
463         f = r->fields + r->content_length_field;
464 
465         nxt_ruby_add_sptr(hash_env, NL("CONTENT_LENGTH"),
466                           &f->value, f->value_length);
467     }
468 
469     if (r->content_type_field != NXT_UNIT_NONE_FIELD) {
470         f = r->fields + r->content_type_field;
471 
472         nxt_ruby_add_sptr(hash_env, NL("CONTENT_TYPE"),
473                           &f->value, f->value_length);
474     }
475 
476     if (r->host_field != NXT_UNIT_NONE_FIELD) {
477         f = r->fields + r->host_field;
478 
479         host_start = nxt_unit_sptr_get(&f->value);
480         host_length = f->value_length;
481 
482     } else {
483         host_start = NULL;
484         host_length = 0;
485     }
486 
487     nxt_unit_split_host(host_start, host_length, &host_start, &host_length,
488                         &port_start, &port_length);
489 
490     nxt_ruby_add_str(hash_env, NL("SERVER_NAME"), host_start, host_length);
491     nxt_ruby_add_str(hash_env, NL("SERVER_PORT"), port_start, port_length);
492 
493 #undef NL
494 
495     return NXT_UNIT_OK;
496 }
497 
498 
499 nxt_inline void
500 nxt_ruby_add_sptr(VALUE hash_env,
501     const char *name, uint32_t name_len, nxt_unit_sptr_t *sptr, uint32_t len)
502 {
503     char  *str;
504 
505     str = nxt_unit_sptr_get(sptr);
506 
507     rb_hash_aset(hash_env, rb_str_new(name, name_len), rb_str_new(str, len));
508 }
509 
510 
511 nxt_inline void
512 nxt_ruby_add_str(VALUE hash_env,
513     const char *name, uint32_t name_len, char *str, uint32_t len)
514 {
515     rb_hash_aset(hash_env, rb_str_new(name, name_len), rb_str_new(str, len));
516 }
517 
518 
519 static nxt_int_t
520 nxt_ruby_rack_result_status(VALUE result)
521 {
522     VALUE   status;
523 
524     status = rb_ary_entry(result, 0);
525 
526     if (TYPE(status) == T_FIXNUM) {
527         return FIX2INT(status);
528     }
529 
530     if (TYPE(status) == T_STRING) {
531         return nxt_int_parse((u_char *) RSTRING_PTR(status),
532                              RSTRING_LEN(status));
533     }
534 
535     nxt_unit_req_error(nxt_ruby_run_ctx.req, "Ruby: Invalid response 'status' "
536                        "format from application");
537 
538     return -2;
539 }
540 
541 
542 typedef struct {
543     int       rc;
544     uint32_t  fields;
545     uint32_t  size;
546 } nxt_ruby_headers_info_t;
547 
548 
549 static int
550 nxt_ruby_rack_result_headers(VALUE result, nxt_int_t status)
551 {
552     int                      rc;
553     VALUE                    headers;
554     nxt_ruby_headers_info_t  headers_info;
555 
556     headers = rb_ary_entry(result, 1);
557     if (nxt_slow_path(TYPE(headers) != T_HASH)) {
558         nxt_unit_req_error(nxt_ruby_run_ctx.req,
559                            "Ruby: Invalid response 'headers' format from "
560                            "application");
561 
562         return NXT_UNIT_ERROR;
563     }
564 
565     rc = NXT_UNIT_OK;
566 
567     headers_info.rc = NXT_UNIT_OK;
568     headers_info.fields = 0;
569     headers_info.size = 0;
570 
571     rb_hash_foreach(headers, nxt_ruby_hash_info,
572                     (VALUE) (uintptr_t) &headers_info);
573     if (nxt_slow_path(headers_info.rc != NXT_UNIT_OK)) {
574         return headers_info.rc;
575     }
576 
577     rc = nxt_unit_response_init(nxt_ruby_run_ctx.req, status,
578                                 headers_info.fields, headers_info.size);
579     if (nxt_slow_path(rc != NXT_UNIT_OK)) {
580         return rc;
581     }
582 
583     rb_hash_foreach(headers, nxt_ruby_hash_add, (VALUE) (uintptr_t) &rc);
584 
585     return rc;
586 }
587 
588 
589 static int
590 nxt_ruby_hash_info(VALUE r_key, VALUE r_value, VALUE arg)
591 {
592     const char               *value, *value_end, *pos;
593     nxt_ruby_headers_info_t  *headers_info;
594 
595     headers_info = (void *) (uintptr_t) arg;
596 
597     if (nxt_slow_path(TYPE(r_key) != T_STRING)) {
598         nxt_unit_req_error(nxt_ruby_run_ctx.req,
599                            "Ruby: Wrong header entry 'key' from application");
600 
601         goto fail;
602     }
603 
604     if (nxt_slow_path(TYPE(r_value) != T_STRING)) {
605         nxt_unit_req_error(nxt_ruby_run_ctx.req,
606                            "Ruby: Wrong header entry 'value' from application");
607 
608         goto fail;
609     }
610 
611     value = RSTRING_PTR(r_value);
612     value_end = value + RSTRING_LEN(r_value);
613 
614     pos = value;
615 
616     for ( ;; ) {
617         pos = strchr(pos, '\n');
618 
619         if (pos == NULL) {
620             break;
621         }
622 
623         headers_info->fields++;
624         headers_info->size += RSTRING_LEN(r_key) + (pos - value);
625 
626         pos++;
627         value = pos;
628     }
629 
630     if (value <= value_end) {
631         headers_info->fields++;
632         headers_info->size += RSTRING_LEN(r_key) + (value_end - value);
633     }
634 
635     return ST_CONTINUE;
636 
637 fail:
638 
639     headers_info->rc = NXT_UNIT_ERROR;
640 
641     return ST_STOP;
642 }
643 
644 
645 static int
646 nxt_ruby_hash_add(VALUE r_key, VALUE r_value, VALUE arg)
647 {
648     int         *rc;
649     uint32_t    key_len;
650     const char  *value, *value_end, *pos;
651 
652     rc = (int *) (uintptr_t) arg;
653 
654     value = RSTRING_PTR(r_value);
655     value_end = value + RSTRING_LEN(r_value);
656 
657     key_len = RSTRING_LEN(r_key);
658 
659     pos = value;
660 
661     for ( ;; ) {
662         pos = strchr(pos, '\n');
663 
664         if (pos == NULL) {
665             break;
666         }
667 
668         *rc = nxt_unit_response_add_field(nxt_ruby_run_ctx.req,
669                                           RSTRING_PTR(r_key), key_len,
670                                           value, pos - value);
671         if (nxt_slow_path(*rc != NXT_UNIT_OK)) {
672             goto fail;
673         }
674 
675         pos++;
676         value = pos;
677     }
678 
679     if (value <= value_end) {
680         *rc = nxt_unit_response_add_field(nxt_ruby_run_ctx.req,
681                                           RSTRING_PTR(r_key), key_len,
682                                           value, value_end - value);
683         if (nxt_slow_path(*rc != NXT_UNIT_OK)) {
684             goto fail;
685         }
686     }
687 
688     return ST_CONTINUE;
689 
690 fail:
691 
692     *rc = NXT_UNIT_ERROR;
693 
694     return ST_STOP;
695 }
696 
697 
698 static int
699 nxt_ruby_rack_result_body(VALUE result)
700 {
701     int    rc;
702     VALUE  fn, body;
703 
704     body = rb_ary_entry(result, 2);
705 
706     if (rb_respond_to(body, rb_intern("to_path"))) {
707 
708         fn = rb_funcall(body, rb_intern("to_path"), 0);
709         if (nxt_slow_path(TYPE(fn) != T_STRING)) {
710             nxt_unit_req_error(nxt_ruby_run_ctx.req,
711                                "Ruby: Failed to get 'body' file path from "
712                                "application");
713 
714             return NXT_UNIT_ERROR;
715         }
716 
717         rc = nxt_ruby_rack_result_body_file_write(fn);
718         if (nxt_slow_path(rc != NXT_UNIT_OK)) {
719             return rc;
720         }
721 
722     } else if (rb_respond_to(body, rb_intern("each"))) {
723         rb_iterate(rb_each, body, nxt_ruby_rack_result_body_each, 0);
724 
725     } else {
726         nxt_unit_req_error(nxt_ruby_run_ctx.req,
727                            "Ruby: Invalid response 'body' format "
728                            "from application");
729 
730         return NXT_UNIT_ERROR;
731     }
732 
733     if (rb_respond_to(body, rb_intern("close"))) {
734         rb_funcall(body, rb_intern("close"), 0);
735     }
736 
737     return NXT_UNIT_OK;
738 }
739 
740 
741 typedef struct {
742     int    fd;
743     off_t  pos;
744     off_t  rest;
745 } nxt_ruby_rack_file_t;
746 
747 
748 static ssize_t
749 nxt_ruby_rack_file_read(nxt_unit_read_info_t *read_info, void *dst, size_t size)
750 {
751     ssize_t               res;
752     nxt_ruby_rack_file_t  *file;
753 
754     file = read_info->data;
755 
756     size = nxt_min(size, (size_t) file->rest);
757 
758     res = pread(file->fd, dst, size, file->pos);
759 
760     if (res >= 0) {
761         file->pos += res;
762         file->rest -= res;
763 
764         if (size > (size_t) res) {
765             file->rest = 0;
766         }
767     }
768 
769     read_info->eof = file->rest == 0;
770 
771     return res;
772 }
773 
774 
775 static int
776 nxt_ruby_rack_result_body_file_write(VALUE filepath)
777 {
778     int                   fd, rc;
779     struct stat           finfo;
780     nxt_ruby_rack_file_t  ruby_file;
781     nxt_unit_read_info_t  read_info;
782 
783     fd = open(RSTRING_PTR(filepath), O_RDONLY, 0);
784     if (nxt_slow_path(fd == -1)) {
785         nxt_unit_req_error(nxt_ruby_run_ctx.req,
786                            "Ruby: Failed to open content file \"%s\": %s (%d)",
787                            RSTRING_PTR(filepath), strerror(errno), errno);
788 
789         return NXT_UNIT_ERROR;
790     }
791 
792     rc = fstat(fd, &finfo);
793     if (nxt_slow_path(rc == -1)) {
794         nxt_unit_req_error(nxt_ruby_run_ctx.req,
795                            "Ruby: Content file fstat(\"%s\") failed: %s (%d)",
796                            RSTRING_PTR(filepath), strerror(errno), errno);
797 
798         close(fd);
799 
800         return NXT_UNIT_ERROR;
801     }
802 
803     ruby_file.fd = fd;
804     ruby_file.pos = 0;
805     ruby_file.rest = finfo.st_size;
806 
807     read_info.read = nxt_ruby_rack_file_read;
808     read_info.eof = ruby_file.rest == 0;
809     read_info.buf_size = ruby_file.rest;
810     read_info.data = &ruby_file;
811 
812     rc = nxt_unit_response_write_cb(nxt_ruby_run_ctx.req, &read_info);
813     if (nxt_slow_path(rc != NXT_UNIT_OK)) {
814         nxt_unit_req_error(nxt_ruby_run_ctx.req,
815                            "Ruby: Failed to write content file.");
816     }
817 
818     close(fd);
819 
820     return rc;
821 }
822 
823 
824 static VALUE
825 nxt_ruby_rack_result_body_each(VALUE body)
826 {
827     int  rc;
828 
829     if (TYPE(body) != T_STRING) {
830         return Qnil;
831     }
832 
833     rc = nxt_unit_response_write(nxt_ruby_run_ctx.req, RSTRING_PTR(body),
834                                  RSTRING_LEN(body));
835     if (nxt_slow_path(rc != NXT_UNIT_OK)) {
836         nxt_unit_req_error(nxt_ruby_run_ctx.req,
837                            "Ruby: Failed to write 'body' from application");
838     }
839 
840     return Qnil;
841 }
842 
843 
844 static void
845 nxt_ruby_exception_log(nxt_task_t *task, uint32_t level, const char *desc)
846 {
847     int    i;
848     VALUE  err, ary, eclass, msg;
849 
850     if (task != NULL) {
851         nxt_log(task, level, "Ruby: %s", desc);
852 
853     } else {
854         nxt_unit_log(nxt_ruby_run_ctx.unit_ctx, level, "Ruby: %s", desc);
855     }
856 
857     err = rb_errinfo();
858     if (nxt_slow_path(err == Qnil)) {
859         return;
860     }
861 
862     ary = rb_funcall(err, rb_intern("backtrace"), 0);
863     if (nxt_slow_path(RARRAY_LEN(ary) == 0)) {
864         return;
865     }
866 
867     eclass = rb_class_name(rb_class_of(err));
868     msg = rb_funcall(err, rb_intern("message"), 0);
869 
870     if (task != NULL) {
871         nxt_log(task, level, "Ruby: %s: %s (%s)",
872                 RSTRING_PTR(RARRAY_PTR(ary)[0]),
873                 RSTRING_PTR(msg), RSTRING_PTR(eclass));
874 
875     } else {
876         nxt_unit_log(nxt_ruby_run_ctx.unit_ctx, level, "Ruby: %s: %s (%s)",
877                      RSTRING_PTR(RARRAY_PTR(ary)[0]),
878                      RSTRING_PTR(msg), RSTRING_PTR(eclass));
879     }
880 
881     for (i = 1; i < RARRAY_LEN(ary); i++) {
882         if (task != NULL) {
883             nxt_log(task, level, "from %s", RSTRING_PTR(RARRAY_PTR(ary)[i]));
884 
885         } else {
886             nxt_unit_log(nxt_ruby_run_ctx.unit_ctx, level, "from %s",
887                          RSTRING_PTR(RARRAY_PTR(ary)[i]));
888         }
889     }
890 }
891 
892 
893 static void
894 nxt_ruby_atexit(void)
895 {
896     rb_gc_unregister_address(&nxt_ruby_io_input);
897     rb_gc_unregister_address(&nxt_ruby_io_error);
898 
899     rb_gc_unregister_address(&nxt_ruby_rackup);
900     rb_gc_unregister_address(&nxt_ruby_call);
901     rb_gc_unregister_address(&nxt_ruby_env);
902 
903     ruby_cleanup(0);
904 }
905