xref: /unit/src/nodejs/unit-http/unit.cpp (revision 1021:8884d891d4c7)
1 
2 /*
3  * Copyright (C) NGINX, Inc.
4  */
5 
6 #include "unit.h"
7 
8 #include <unistd.h>
9 #include <fcntl.h>
10 
11 #include <uv.h>
12 
13 
14 napi_ref Unit::constructor_;
15 
16 
17 struct nxt_nodejs_ctx_t {
18     nxt_unit_port_id_t  port_id;
19     uv_poll_t           poll;
20 };
21 
22 
23 Unit::Unit(napi_env env, napi_value jsthis):
24     nxt_napi(env),
25     wrapper_(wrap(jsthis, this, destroy)),
26     unit_ctx_(nullptr)
27 {
28 }
29 
30 
31 Unit::~Unit()
32 {
33     delete_reference(wrapper_);
34 }
35 
36 
37 napi_value
38 Unit::init(napi_env env, napi_value exports)
39 {
40     nxt_napi    napi(env);
41     napi_value  cons;
42 
43     napi_property_descriptor  properties[] = {
44         { "createServer", 0, create_server, 0, 0, 0, napi_default, 0 },
45         { "listen", 0, listen, 0, 0, 0, napi_default, 0 },
46         { "_read", 0, _read, 0, 0, 0, napi_default, 0 }
47     };
48 
49     try {
50         cons = napi.define_class("Unit", create, 3, properties);
51         constructor_ = napi.create_reference(cons);
52 
53         napi.set_named_property(exports, "Unit", cons);
54         napi.set_named_property(exports, "unit_response_headers",
55                                 response_send_headers);
56         napi.set_named_property(exports, "unit_response_write", response_write);
57         napi.set_named_property(exports, "unit_response_end", response_end);
58 
59     } catch (exception &e) {
60         napi.throw_error(e);
61         return nullptr;
62     }
63 
64     return exports;
65 }
66 
67 
68 void
69 Unit::destroy(napi_env env, void *nativeObject, void *finalize_hint)
70 {
71     Unit  *obj = reinterpret_cast<Unit *>(nativeObject);
72 
73     delete obj;
74 }
75 
76 
77 napi_value
78 Unit::create(napi_env env, napi_callback_info info)
79 {
80     Unit        *obj;
81     nxt_napi    napi(env);
82     napi_ref    ref;
83     napi_value  target, cons, instance, jsthis;
84 
85     try {
86         target = napi.get_new_target(info);
87 
88         if (target != nullptr) {
89             /* Invoked as constructor: `new Unit(...)`. */
90             jsthis = napi.get_cb_info(info);
91 
92             obj = new Unit(env, jsthis);
93 
94             ref = napi.create_reference(jsthis);
95 
96             return jsthis;
97         }
98 
99         /* Invoked as plain function `Unit(...)`, turn into construct call. */
100         cons = napi.get_reference_value(constructor_);
101         instance = napi.new_instance(cons);
102         ref = napi.create_reference(instance);
103 
104     } catch (exception &e) {
105         napi.throw_error(e);
106         return nullptr;
107     }
108 
109     return instance;
110 }
111 
112 
113 napi_value
114 Unit::create_server(napi_env env, napi_callback_info info)
115 {
116     Unit             *obj;
117     size_t           argc;
118     nxt_napi         napi(env);
119     napi_value       jsthis, argv;
120     nxt_unit_init_t  unit_init;
121 
122     argc = 1;
123 
124     try {
125         jsthis = napi.get_cb_info(info, argc, &argv);
126         obj = (Unit *) napi.unwrap(jsthis);
127 
128     } catch (exception &e) {
129         napi.throw_error(e);
130         return nullptr;
131     }
132 
133     memset(&unit_init, 0, sizeof(nxt_unit_init_t));
134 
135     unit_init.data = obj;
136     unit_init.callbacks.request_handler = request_handler;
137     unit_init.callbacks.add_port        = add_port;
138     unit_init.callbacks.remove_port     = remove_port;
139     unit_init.callbacks.quit            = quit;
140 
141     obj->unit_ctx_ = nxt_unit_init(&unit_init);
142     if (obj->unit_ctx_ == NULL) {
143         goto failed;
144     }
145 
146     return nullptr;
147 
148 failed:
149 
150     napi_throw_error(env, NULL, "Failed to create Unit object");
151 
152     return nullptr;
153 }
154 
155 
156 napi_value
157 Unit::listen(napi_env env, napi_callback_info info)
158 {
159     return nullptr;
160 }
161 
162 
163 napi_value
164 Unit::_read(napi_env env, napi_callback_info info)
165 {
166     void                     *data;
167     size_t                   argc;
168     nxt_napi                 napi(env);
169     napi_value               jsthis, buffer, argv;
170     nxt_unit_request_info_t  *req;
171 
172     argc = 1;
173 
174     try {
175         jsthis = napi.get_cb_info(info, argc, &argv);
176 
177         req = napi.get_request_info(argv);
178         buffer = napi.create_buffer((size_t) req->content_length, &data);
179 
180     } catch (exception &e) {
181         napi.throw_error(e);
182         return nullptr;
183     }
184 
185     nxt_unit_request_read(req, data, req->content_length);
186 
187     return buffer;
188 }
189 
190 
191 void
192 Unit::request_handler(nxt_unit_request_info_t *req)
193 {
194     Unit         *obj;
195     napi_value   socket, request, response, server_obj;
196     napi_value   emit_events;
197     napi_value   events_args[3];
198 
199     obj = reinterpret_cast<Unit *>(req->unit->data);
200 
201     try {
202         nxt_handle_scope  scope(obj->env());
203 
204         server_obj = obj->get_server_object();
205 
206         socket = obj->create_socket(server_obj, req);
207         request = obj->create_request(server_obj, socket);
208         response = obj->create_response(server_obj, socket, request, req);
209 
210         obj->create_headers(req, request);
211 
212         emit_events = obj->get_named_property(server_obj, "emit_events");
213 
214         events_args[0] = server_obj;
215         events_args[1] = request;
216         events_args[2] = response;
217 
218         nxt_async_context   async_context(obj->env(), "unit_request_handler");
219         nxt_callback_scope  async_scope(async_context);
220 
221         obj->make_callback(async_context, server_obj, emit_events,
222                            3, events_args);
223 
224     } catch (exception &e) {
225         obj->throw_error(e);
226     }
227 }
228 
229 
230 void
231 nxt_uv_read_callback(uv_poll_t *handle, int status, int events)
232 {
233     nxt_unit_run_once((nxt_unit_ctx_t *) handle->data);
234 }
235 
236 
237 int
238 Unit::add_port(nxt_unit_ctx_t *ctx, nxt_unit_port_t *port)
239 {
240     int               err;
241     Unit              *obj;
242     uv_loop_t         *loop;
243     napi_status       status;
244     nxt_nodejs_ctx_t  *node_ctx;
245 
246     if (port->in_fd != -1) {
247         obj = reinterpret_cast<Unit *>(ctx->unit->data);
248 
249         if (fcntl(port->in_fd, F_SETFL, O_NONBLOCK) == -1) {
250             obj->throw_error("Failed to upgrade read"
251                              " file descriptor to O_NONBLOCK");
252             return -1;
253         }
254 
255         status = napi_get_uv_event_loop(obj->env(), &loop);
256         if (status != napi_ok) {
257             obj->throw_error("Failed to get uv.loop");
258             return NXT_UNIT_ERROR;
259         }
260 
261         node_ctx = new nxt_nodejs_ctx_t;
262 
263         err = uv_poll_init(loop, &node_ctx->poll, port->in_fd);
264         if (err < 0) {
265             obj->throw_error("Failed to init uv.poll");
266             return NXT_UNIT_ERROR;
267         }
268 
269         err = uv_poll_start(&node_ctx->poll, UV_READABLE, nxt_uv_read_callback);
270         if (err < 0) {
271             obj->throw_error("Failed to start uv.poll");
272             return NXT_UNIT_ERROR;
273         }
274 
275         ctx->data = node_ctx;
276 
277         node_ctx->port_id = port->id;
278         node_ctx->poll.data = ctx;
279     }
280 
281     return nxt_unit_add_port(ctx, port);
282 }
283 
284 
285 inline bool
286 operator == (const nxt_unit_port_id_t &p1, const nxt_unit_port_id_t &p2)
287 {
288     return p1.pid == p2.pid && p1.id == p2.id;
289 }
290 
291 
292 void
293 Unit::remove_port(nxt_unit_ctx_t *ctx, nxt_unit_port_id_t *port_id)
294 {
295     nxt_nodejs_ctx_t  *node_ctx;
296 
297     if (ctx->data != NULL) {
298         node_ctx = (nxt_nodejs_ctx_t *) ctx->data;
299 
300         if (node_ctx->port_id == *port_id) {
301             uv_poll_stop(&node_ctx->poll);
302 
303             delete node_ctx;
304 
305             ctx->data = NULL;
306         }
307     }
308 
309     nxt_unit_remove_port(ctx, port_id);
310 }
311 
312 
313 void
314 Unit::quit(nxt_unit_ctx_t *ctx)
315 {
316     Unit        *obj;
317     napi_value  server_obj, emit_close;
318 
319     obj = reinterpret_cast<Unit *>(ctx->unit->data);
320 
321     try {
322         nxt_handle_scope  scope(obj->env());
323 
324         server_obj = obj->get_server_object();
325 
326         emit_close = obj->get_named_property(server_obj, "emit_close");
327 
328         nxt_async_context   async_context(obj->env(), "unit_quit");
329         nxt_callback_scope  async_scope(async_context);
330 
331         obj->make_callback(async_context, server_obj, emit_close, 0, NULL);
332 
333     } catch (exception &e) {
334         obj->throw_error(e);
335     }
336 
337     nxt_unit_done(ctx);
338 }
339 
340 
341 napi_value
342 Unit::get_server_object()
343 {
344     napi_value  unit_obj;
345 
346     unit_obj = get_reference_value(wrapper_);
347 
348     return get_named_property(unit_obj, "server");
349 }
350 
351 
352 void
353 Unit::create_headers(nxt_unit_request_info_t *req, napi_value request)
354 {
355     uint32_t            i;
356     napi_value          headers, raw_headers;
357     napi_status         status;
358     nxt_unit_request_t  *r;
359 
360     r = req->request;
361 
362     headers = create_object();
363 
364     status = napi_create_array_with_length(env(), r->fields_count * 2,
365                                            &raw_headers);
366     if (status != napi_ok) {
367         throw exception("Failed to create array");
368     }
369 
370     for (i = 0; i < r->fields_count; i++) {
371         append_header(r->fields + i, headers, raw_headers, i);
372     }
373 
374     set_named_property(request, "headers", headers);
375     set_named_property(request, "rawHeaders", raw_headers);
376     set_named_property(request, "httpVersion", r->version, r->version_length);
377     set_named_property(request, "method", r->method, r->method_length);
378     set_named_property(request, "url", r->target, r->target_length);
379 }
380 
381 
382 inline void
383 Unit::append_header(nxt_unit_field_t *f, napi_value headers,
384     napi_value raw_headers, uint32_t idx)
385 {
386     const char   *name;
387     napi_value   str, vstr;
388 
389     name = (const char *) nxt_unit_sptr_get(&f->name);
390 
391     vstr = set_named_property(headers, name, f->value, f->value_length);
392     str = create_string_latin1(name, f->name_length);
393 
394     set_element(raw_headers, idx * 2, str);
395     set_element(raw_headers, idx * 2 + 1, vstr);
396 }
397 
398 
399 napi_value
400 Unit::create_socket(napi_value server_obj, nxt_unit_request_info_t *req)
401 {
402     napi_value  constructor, return_val;
403 
404     constructor = get_named_property(server_obj, "socket");
405 
406     return_val = new_instance(constructor);
407 
408     set_named_property(return_val, "req_pointer", (intptr_t) req);
409 
410     return return_val;
411 }
412 
413 
414 napi_value
415 Unit::create_request(napi_value server_obj, napi_value socket)
416 {
417     napi_value  constructor, return_val;
418 
419     constructor = get_named_property(server_obj, "request");
420 
421     return_val = new_instance(constructor, server_obj);
422 
423     set_named_property(return_val, "socket", socket);
424 
425     return return_val;
426 }
427 
428 
429 napi_value
430 Unit::create_response(napi_value server_obj, napi_value socket,
431     napi_value request, nxt_unit_request_info_t *req)
432 {
433     napi_value  constructor, return_val;
434 
435     constructor = get_named_property(server_obj, "response");
436 
437     return_val = new_instance(constructor, request);
438 
439     set_named_property(return_val, "socket", socket);
440     set_named_property(return_val, "_req_point", (intptr_t) req);
441 
442     return return_val;
443 }
444 
445 
446 napi_value
447 Unit::response_send_headers(napi_env env, napi_callback_info info)
448 {
449     int                      ret;
450     char                     *ptr, *name_ptr;
451     bool                     is_array;
452     size_t                   argc, name_len, value_len;
453     uint32_t                 status_code, header_len, keys_len, array_len;
454     uint32_t                 keys_count, i, j;
455     uint16_t                 hash;
456     nxt_napi                 napi(env);
457     napi_value               this_arg, headers, keys, name, value, array_val;
458     napi_value               req_num, array_entry;
459     napi_valuetype           val_type;
460     nxt_unit_field_t         *f;
461     nxt_unit_request_info_t  *req;
462     napi_value               argv[5];
463 
464     argc = 5;
465 
466     try {
467         this_arg = napi.get_cb_info(info, argc, argv);
468         if (argc != 5) {
469             napi.throw_error("Wrong args count. Expected: "
470                              "statusCode, headers, headers count, "
471                              "headers length");
472             return nullptr;
473         }
474 
475         req_num = napi.get_named_property(argv[0], "_req_point");
476 
477         req = napi.get_request_info(req_num);
478 
479         status_code = napi.get_value_uint32(argv[1]);
480         keys_count = napi.get_value_uint32(argv[3]);
481         header_len = napi.get_value_uint32(argv[4]);
482 
483         /* Need to reserve extra byte for C-string 0-termination. */
484         header_len++;
485 
486         headers = argv[2];
487 
488         ret = nxt_unit_response_init(req, status_code, keys_count, header_len);
489         if (ret != NXT_UNIT_OK) {
490             napi.throw_error("Failed to create response");
491             return nullptr;
492         }
493 
494         keys = napi.get_property_names(headers);
495         keys_len = napi.get_array_length(keys);
496 
497         ptr = req->response_buf->free;
498 
499         for (i = 0; i < keys_len; i++) {
500             name = napi.get_element(keys, i);
501 
502             array_entry = napi.get_property(headers, name);
503 
504             name = napi.get_element(array_entry, 0);
505             value = napi.get_element(array_entry, 1);
506 
507             name_len = napi.get_value_string_latin1(name, ptr, header_len);
508             name_ptr = ptr;
509 
510             ptr += name_len;
511             header_len -= name_len;
512 
513             hash = nxt_unit_field_hash(name_ptr, name_len);
514 
515             is_array = napi.is_array(value);
516 
517             if (is_array) {
518                 array_len = napi.get_array_length(value);
519 
520                 for (j = 0; j < array_len; j++) {
521                     array_val = napi.get_element(value, j);
522 
523                     val_type = napi.type_of(array_val);
524 
525                     if (val_type != napi_string) {
526                         array_val = napi.coerce_to_string(array_val);
527                     }
528 
529                     value_len = napi.get_value_string_latin1(array_val, ptr,
530                                                              header_len);
531 
532                     f = req->response->fields + req->response->fields_count;
533                     f->skip = 0;
534 
535                     nxt_unit_sptr_set(&f->name, name_ptr);
536 
537                     f->name_length = name_len;
538                     f->hash = hash;
539 
540                     nxt_unit_sptr_set(&f->value, ptr);
541                     f->value_length = (uint32_t) value_len;
542 
543                     ptr += value_len;
544                     header_len -= value_len;
545 
546                     req->response->fields_count++;
547                 }
548 
549             } else {
550                 val_type = napi.type_of(value);
551 
552                 if (val_type != napi_string) {
553                     value = napi.coerce_to_string(value);
554                 }
555 
556                 value_len = napi.get_value_string_latin1(value, ptr, header_len);
557 
558                 f = req->response->fields + req->response->fields_count;
559                 f->skip = 0;
560 
561                 nxt_unit_sptr_set(&f->name, name_ptr);
562 
563                 f->name_length = name_len;
564                 f->hash = hash;
565 
566                 nxt_unit_sptr_set(&f->value, ptr);
567                 f->value_length = (uint32_t) value_len;
568 
569                 ptr += value_len;
570                 header_len -= value_len;
571 
572                 req->response->fields_count++;
573             }
574         }
575 
576     } catch (exception &e) {
577         napi.throw_error(e);
578         return nullptr;
579     }
580 
581     req->response_buf->free = ptr;
582 
583     ret = nxt_unit_response_send(req);
584     if (ret != NXT_UNIT_OK) {
585         napi.throw_error("Failed to send response");
586         return nullptr;
587     }
588 
589     return this_arg;
590 }
591 
592 
593 napi_value
594 Unit::response_write(napi_env env, napi_callback_info info)
595 {
596     int                      ret;
597     char                     *ptr;
598     size_t                   argc, have_buf_len;
599     uint32_t                 buf_len;
600     nxt_napi                 napi(env);
601     napi_value               this_arg, req_num;
602     napi_status              status;
603     nxt_unit_buf_t           *buf;
604     napi_valuetype           buf_type;
605     nxt_unit_request_info_t  *req;
606     napi_value               argv[3];
607 
608     argc = 3;
609 
610     try {
611         this_arg = napi.get_cb_info(info, argc, argv);
612         if (argc != 3) {
613             throw exception("Wrong args count. Expected: "
614                             "chunk, chunk length");
615         }
616 
617         req_num = napi.get_named_property(argv[0], "_req_point");
618         req = napi.get_request_info(req_num);
619 
620         buf_len = napi.get_value_uint32(argv[2]);
621 
622         buf_type = napi.type_of(argv[1]);
623 
624     } catch (exception &e) {
625         napi.throw_error(e);
626         return nullptr;
627     }
628 
629     buf_len++;
630 
631     buf = nxt_unit_response_buf_alloc(req, buf_len);
632     if (buf == NULL) {
633         goto failed;
634     }
635 
636     if (buf_type == napi_string) {
637         /* TODO: will work only for utf8 content-type */
638 
639         status = napi_get_value_string_utf8(env, argv[1], buf->free,
640                                             buf_len, &have_buf_len);
641 
642     } else {
643         status = napi_get_buffer_info(env, argv[1], (void **) &ptr,
644                                       &have_buf_len);
645 
646         memcpy(buf->free, ptr, have_buf_len);
647     }
648 
649     if (status != napi_ok) {
650         goto failed;
651     }
652 
653     buf->free += have_buf_len;
654 
655     ret = nxt_unit_buf_send(buf);
656     if (ret != NXT_UNIT_OK) {
657         goto failed;
658     }
659 
660     return this_arg;
661 
662 failed:
663 
664     napi.throw_error("Failed to write body");
665 
666     return nullptr;
667 }
668 
669 
670 napi_value
671 Unit::response_end(napi_env env, napi_callback_info info)
672 {
673     size_t                   argc;
674     nxt_napi                 napi(env);
675     napi_value               resp, this_arg, req_num;
676     nxt_unit_request_info_t  *req;
677 
678     argc = 1;
679 
680     try {
681         this_arg = napi.get_cb_info(info, argc, &resp);
682 
683         req_num = napi.get_named_property(resp, "_req_point");
684         req = napi.get_request_info(req_num);
685 
686     } catch (exception &e) {
687         napi.throw_error(e);
688         return nullptr;
689     }
690 
691     nxt_unit_request_done(req, NXT_UNIT_OK);
692 
693     return this_arg;
694 }
695