1 #include <inttypes.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include <uv.h>
6
7 uv_loop_t *loop;
8 uv_process_t child_req;
9 uv_process_options_t options;
10
cleanup_handles(uv_process_t * req,int64_t exit_status,int term_signal)11 void cleanup_handles(uv_process_t *req, int64_t exit_status, int term_signal) {
12 fprintf(stderr, "Process exited with status %" PRId64 ", signal %d\n", exit_status, term_signal);
13 uv_close((uv_handle_t*) req->data, NULL);
14 uv_close((uv_handle_t*) req, NULL);
15 }
16
invoke_cgi_script(uv_tcp_t * client)17 void invoke_cgi_script(uv_tcp_t *client) {
18 char path[500];
19 size_t size = sizeof(path);
20 uv_exepath(path, &size);
21 strcpy(path + (strlen(path) - strlen("cgi")), "tick");
22
23 char* args[2];
24 args[0] = path;
25 args[1] = NULL;
26
27 /* ... finding the executable path and setting up arguments ... */
28
29 options.stdio_count = 3;
30 uv_stdio_container_t child_stdio[3];
31 child_stdio[0].flags = UV_IGNORE;
32 child_stdio[1].flags = UV_INHERIT_STREAM;
33 child_stdio[1].data.stream = (uv_stream_t*) client;
34 child_stdio[2].flags = UV_IGNORE;
35 options.stdio = child_stdio;
36
37 options.exit_cb = cleanup_handles;
38 options.file = args[0];
39 options.args = args;
40
41 // Set this so we can close the socket after the child process exits.
42 child_req.data = (void*) client;
43 int r;
44 if ((r = uv_spawn(loop, &child_req, &options))) {
45 fprintf(stderr, "%s\n", uv_strerror(r));
46 return;
47 }
48 }
49
on_new_connection(uv_stream_t * server,int status)50 void on_new_connection(uv_stream_t *server, int status) {
51 if (status == -1) {
52 // error!
53 return;
54 }
55
56 uv_tcp_t *client = (uv_tcp_t*) malloc(sizeof(uv_tcp_t));
57 uv_tcp_init(loop, client);
58 if (uv_accept(server, (uv_stream_t*) client) == 0) {
59 invoke_cgi_script(client);
60 }
61 else {
62 uv_close((uv_handle_t*) client, NULL);
63 }
64 }
65
main()66 int main() {
67 loop = uv_default_loop();
68
69 uv_tcp_t server;
70 uv_tcp_init(loop, &server);
71
72 struct sockaddr_in bind_addr;
73 uv_ip4_addr("0.0.0.0", 7000, &bind_addr);
74 uv_tcp_bind(&server, (const struct sockaddr *)&bind_addr, 0);
75 int r = uv_listen((uv_stream_t*) &server, 128, on_new_connection);
76 if (r) {
77 fprintf(stderr, "Listen error %s\n", uv_err_name(r));
78 return 1;
79 }
80 return uv_run(loop, UV_RUN_DEFAULT);
81 }
82