moonbridge

view moonbridge.c @ 20:133a609958c4

Backed out previous changeset: Avoid "unused-result" compiler warning by storing return values in dummy variables
author jbe
date Thu Jan 29 21:54:34 2015 +0100 (2015-01-29)
parents be880e7c1e56
children 891ceefb0876
line source
2 /*** Compile-time configuration ***/
4 #define MOONBR_LUA_PANIC_BUG_WORKAROUND 1
7 /*** C preprocessor macros for portability support ***/
9 #ifndef __has_include
10 #define __has_include(x) 0
11 #endif
14 /*** Include directives for used system libraries ***/
16 #if defined(__linux__)
17 #define _GNU_SOURCE
18 #endif
19 #include <stdlib.h>
20 #include <unistd.h>
21 #include <stdint.h>
22 #include <errno.h>
23 #include <getopt.h>
24 #include <syslog.h>
25 #include <string.h>
26 #include <stdio.h>
27 #include <time.h>
28 #include <sys/time.h>
29 #include <sys/socket.h>
30 #include <sys/un.h>
31 #include <netinet/in.h>
32 #include <poll.h>
33 #include <signal.h>
34 #include <sys/wait.h>
35 #include <sys/resource.h>
36 #include <sys/file.h>
37 #if defined(__FreeBSD__) || __has_include(<libutil.h>)
38 #include <libutil.h>
39 #endif
40 #if defined(__linux__) || __has_include(<bsd/libutil.h>)
41 #include <bsd/libutil.h>
42 #endif
43 #if defined(__linux__) || __has_include(<bsd/unistd.h>)
44 #include <bsd/unistd.h>
45 #endif
48 /*** Fallback definitions for missing constants on some platforms ***/
50 /* INFTIM is used as timeout parameter for poll() */
51 #ifndef INFTIM
52 #define INFTIM -1
53 #endif
56 /*** Include directives for Lua ***/
58 #include <lua.h>
59 #include <lauxlib.h>
60 #include <lualib.h>
63 /*** Constants ***/
65 /* Backlog option for listen() call */
66 #define MOONBR_LISTEN_BACKLOG 1024
68 /* Maximum length of a timestamp used for strftime() */
69 #define MOONBR_LOG_MAXTIMELEN 40
71 /* Maximum length of a log message */
72 #define MOONBR_LOG_MAXMSGLEN 4095
74 /* Exitcodes passed to exit() call */
75 #define MOONBR_EXITCODE_GRACEFUL 0
76 #define MOONBR_EXITCODE_CMDLINEERROR 1
77 #define MOONBR_EXITCODE_ALREADYRUNNING 2
78 #define MOONBR_EXITCODE_STARTUPERROR 3
79 #define MOONBR_EXITCODE_RUNTIMEERROR 4
81 /* Maximum length of a line sent to stderr by child processes */
82 #define MOONBR_MAXERRORLINELEN 1024
84 /* Maximum length of an error string returned by strerror() */
85 #define MOONBR_MAXSTRERRORLEN 80
87 /* Status bytes exchanged between master and child processes */
88 #define MOONBR_SOCKETTYPE_INTERVAL 'I'
89 #define MOONBR_SOCKETTYPE_LOCAL 'L'
90 #define MOONBR_SOCKETTYPE_NETWORK 'N'
91 #define MOONBR_STATUS_IDLE '1'
92 #define MOONBR_COMMAND_TERMINATE '2'
93 #define MOONBR_STATUS_GOODBYE '3'
95 /* Constant file descriptors */
96 #define MOONBR_FD_STDERR 2
97 #define MOONBR_FD_CONTROL 3
98 #define MOONBR_FD_END 4
100 /* Return values of moonbr_try_destroy_worker() */
101 #define MOONBR_DESTROY_NONE 0
102 #define MOONBR_DESTROY_PREPARE 1
103 #define MOONBR_DESTROY_IDLE_OR_ASSIGNED 2
106 /*** Types ***/
108 /* Enum for 'moonbr_pstate' */
109 #define MOONBR_PSTATE_STARTUP 0
110 #define MOONBR_PSTATE_RUNNING 1
111 #define MOONBR_PSTATE_FORKED 2
113 /* Enum for 'proto' field of struct moonbr_listener */
114 #define MOONBR_PROTO_INTERVAL 1
115 #define MOONBR_PROTO_LOCAL 2
116 #define MOONBR_PROTO_TCP6 3
117 #define MOONBR_PROTO_TCP4 4
119 /* Data structure for a pool's listener that can accept incoming connections */
120 struct moonbr_listener {
121 struct moonbr_pool *pool;
122 struct moonbr_listener *prev_listener; /* previous idle or(!) connected listener */
123 struct moonbr_listener *next_listener; /* next idle or(!) connected listener */
124 int proto;
125 union {
126 struct {
127 char *name; /* name of interval passed to 'connect' function as 'interval' field in table */
128 int strict; /* nonzero = runtime of 'connect' function does not delay interval */
129 struct timeval delay; /* interval between invocations of 'connect' function */
130 struct timeval wakeup; /* point in time of next invocation */
131 } interval;
132 struct {
133 char *path; /* full path name (i.e. filename with path) of UNIX domain socket */
134 } local;
135 struct {
136 int port; /* port number to listen on (in host endianess) */
137 int localhost_only; /* nonzero = listen on localhost only */
138 } tcp;
139 } proto_specific;
140 int listenfd; /* -1 = none */
141 int pollidx; /* -1 = none */
142 };
144 /* Data structure for a child process that is handling incoming connections */
145 struct moonbr_worker {
146 struct moonbr_pool *pool;
147 struct moonbr_worker *prev_worker;
148 struct moonbr_worker *next_worker;
149 struct moonbr_worker *prev_idle_worker;
150 struct moonbr_worker *next_idle_worker;
151 int idle; /* nonzero = waiting for command from parent process */
152 int assigned; /* nonzero = currently handling a connection */
153 pid_t pid;
154 int controlfd; /* socket to send/receive control message to/from child process */
155 int errorfd; /* socket to receive error output from child process' stderr */
156 char *errorlinebuf; /* optional buffer for collecting stderr data from child process */
157 int errorlinelen; /* number of bytes stored in 'errorlinebuf' */
158 int errorlineovf; /* nonzero = line length overflow */
159 struct timeval idle_expiration; /* point in time until child process may stay in idle state */
160 struct moonbr_listener *restart_interval_listener; /* set while interval listener is assigned */
161 };
163 /* Data structure for a pool of workers and listeners */
164 struct moonbr_pool {
165 int poolnum; /* number of pool for log output */
166 struct moonbr_pool *next_pool; /* next entry in linked list starting with 'moonbr_first_pool' */
167 struct moonbr_worker *first_worker; /* first worker of pool */
168 struct moonbr_worker *last_worker; /* last worker of pool */
169 struct moonbr_worker *first_idle_worker; /* first idle worker of pool */
170 struct moonbr_worker *last_idle_worker; /* last idle worker of pool */
171 int idle_worker_count;
172 int unassigned_worker_count;
173 int total_worker_count;
174 int worker_count_stat; /* only needed for statistics */
175 int pre_fork; /* desired minimum number of unassigned workers */
176 int min_fork; /* desired minimum number of workers in total */
177 int max_fork; /* maximum number of workers */
178 struct timeval fork_delay; /* delay after each fork() until a fork may happen again */
179 struct timeval fork_wakeup; /* point in time when a fork may happen again (unless a worker terminates before) */
180 struct timeval fork_error_delay; /* delay between fork()s when an error during fork or preparation occurred */
181 struct timeval fork_error_wakeup; /* point in time when fork may happen again if an error in preparation occurred */
182 int use_fork_error_wakeup; /* nonzero = error in preparation occured; gets reset on next fork */
183 struct timeval exit_delay; /* delay for terminating excessive workers (unassigned_worker_count > pre_fork) */
184 struct timeval exit_wakeup; /* point in time when terminating an excessive worker */
185 struct timeval idle_timeout; /* delay before an idle worker is terminated */
186 size_t memory_limit; /* maximum bytes of memory that the Lua machine may allocate */
187 int listener_count; /* total number of listeners of pool (and size of 'listener' array at end of this struct) */
188 struct moonbr_listener *first_idle_listener; /* first listener that is idle (i.e. has no waiting connection) */
189 struct moonbr_listener *last_idle_listener; /* last listener that is idle (i.e. has no waiting connection) */
190 struct moonbr_listener *first_connected_listener; /* first listener that has a pending connection */
191 struct moonbr_listener *last_connected_listener; /* last listener that has a pending connection */
192 struct moonbr_listener listener[1]; /* static array of variable(!) size to contain 'listener' structures */
193 };
195 /* Enum for 'channel' field of struct moonbr_poll_worker */
196 #define MOONBR_POLL_WORKER_CONTROLCHANNEL 1
197 #define MOONBR_POLL_WORKER_ERRORCHANNEL 2
199 /* Structure to refer from 'moonbr_poll_worker_fds' entry to worker structure */
200 struct moonbr_poll_worker {
201 struct moonbr_worker *worker;
202 int channel; /* field indicating whether file descriptor is 'controlfd' or 'errorfd' */
203 };
205 /* Variable indicating that clean shutdown was requested */
206 static int moonbr_shutdown_in_progress = 0;
209 /*** Macros for Lua registry ***/
211 /* Lightuserdata keys for Lua registry to store 'prepare', 'connect', and 'finish' functions */
212 #define moonbr_luakey_prepare_func(pool) ((void *)(intptr_t)(pool) + 0)
213 #define moonbr_luakey_connect_func(pool) ((void *)(intptr_t)(pool) + 1)
214 #define moonbr_luakey_finish_func(pool) ((void *)(intptr_t)(pool) + 2)
217 /*** Global variables ***/
219 /* State of process execution */
220 static int moonbr_pstate = MOONBR_PSTATE_STARTUP;
222 /* Process ID of the main process */
223 static pid_t moonbr_masterpid;
225 /* Condition variables set by the signal handler */
226 static volatile sig_atomic_t moonbr_cond_poll = 0;
227 static volatile sig_atomic_t moonbr_cond_terminate = 0;
228 static volatile sig_atomic_t moonbr_cond_interrupt = 0;
229 static volatile sig_atomic_t moonbr_cond_child = 0;
231 /* Socket pair to denote signal delivery when signal handler was called just before poll() */
232 static int moonbr_poll_signalfds[2];
233 #define moonbr_poll_signalfd_read moonbr_poll_signalfds[0]
234 #define moonbr_poll_signalfd_write moonbr_poll_signalfds[1]
236 /* Global variables for pidfile and logging */
237 static struct pidfh *moonbr_pidfh = NULL;
238 static FILE *moonbr_logfile = NULL;
239 static int moonbr_use_syslog = 0;
241 /* First and last entry of linked list of all created pools during initialization */
242 static struct moonbr_pool *moonbr_first_pool = NULL;
243 static struct moonbr_pool *moonbr_last_pool = NULL;
245 /* Total count of pools */
246 static int moonbr_pool_count = 0;
248 /* Set to a nonzero value if dynamic part of 'moonbr_poll_fds' ('moonbr_poll_worker_fds') needs an update */
249 static int moonbr_poll_refresh_needed = 0;
251 /* Array passed to poll(), consisting of static part and dynamic part ('moonbr_poll_worker_fds') */
252 static struct pollfd *moonbr_poll_fds = NULL; /* the array */
253 static int moonbr_poll_fds_bufsize = 0; /* memory allocated for this number of elements */
254 static int moonbr_poll_fds_count = 0; /* total number of elements */
255 static int moonbr_poll_fds_static_count; /* number of elements in static part */
257 /* Dynamic part of 'moonbr_poll_fds' array */
258 #define moonbr_poll_worker_fds (moonbr_poll_fds+moonbr_poll_fds_static_count)
260 /* Additional information for dynamic part of 'moonbr_poll_fds' array */
261 struct moonbr_poll_worker *moonbr_poll_workers; /* the array */
262 static int moonbr_poll_workers_bufsize = 0; /* memory allocated for this number of elements */
263 static int moonbr_poll_worker_count = 0; /* number of elements in array */
265 /* Variable set to nonzero value to disallow further calls of 'listen' function */
266 static int moonbr_booted = 0;
268 /* Global variables to store information on connection socket in child process */
269 static int moonbr_child_peersocket_type; /* type of socket by MOONBR_SOCKETTYPE constant */
270 static int moonbr_child_peersocket_fd; /* Original file descriptor of peer socket */
271 static luaL_Stream *moonbr_child_peersocket_inputstream; /* Lua input stream of socket */
272 static luaL_Stream *moonbr_child_peersocket_outputstream; /* Lua output stream of socket */
274 /* Verbosity settings */
275 static int moonbr_debug = 0;
276 static int moonbr_stat = 0;
278 /* Memory consumption by Lua machine */
279 static size_t moonbr_memory_usage = 0;
280 static size_t moonbr_memory_limit = 0;
283 /*** Functions for signal handling ***/
285 /* Signal handler for master and child processes */
286 static void moonbr_signal(int sig) {
287 if (getpid() == moonbr_masterpid) {
288 /* master process */
289 switch (sig) {
290 case SIGHUP:
291 case SIGINT:
292 /* fast shutdown requested */
293 moonbr_cond_interrupt = 1;
294 break;
295 case SIGTERM:
296 /* clean shutdown requested */
297 moonbr_cond_terminate = 1;
298 break;
299 case SIGCHLD:
300 /* child process terminated */
301 moonbr_cond_child = 1;
302 break;
303 }
304 if (moonbr_cond_poll) {
305 /* avoid race condition if signal handler is invoked right before poll() */
306 char buf[1] = {0};
307 write(moonbr_poll_signalfd_write, buf, 1);
308 }
309 } else {
310 /* child process forwards certain signals to parent process */
311 switch (sig) {
312 case SIGHUP:
313 case SIGINT:
314 case SIGTERM:
315 kill(moonbr_masterpid, sig);
316 }
317 }
318 }
320 /* Initialize signal handling */
321 static void moonbr_signal_init(){
322 moonbr_masterpid = getpid();
323 signal(SIGHUP, moonbr_signal);
324 signal(SIGINT, moonbr_signal);
325 signal(SIGTERM, moonbr_signal);
326 signal(SIGCHLD, moonbr_signal);
327 }
330 /*** Functions for logging in master process ***/
332 /* Logs a pre-formatted message with given syslog() priority */
333 static void moonbr_log_msg(int priority, const char *msg) {
334 if (moonbr_logfile) {
335 /* logging to logfile desired (timestamp is prepended in that case) */
336 time_t now_time = 0;
337 struct tm now_tmstruct;
338 char timestr[MOONBR_LOG_MAXTIMELEN+1];
339 time(&now_time);
340 localtime_r(&now_time, &now_tmstruct);
341 if (!strftime(
342 timestr, MOONBR_LOG_MAXTIMELEN+1, "%Y-%m-%d %H:%M:%S %Z: ", &now_tmstruct
343 )) timestr[0] = 0;
344 fprintf(moonbr_logfile, "%s%s\n", timestr, msg);
345 }
346 if (moonbr_use_syslog) {
347 /* logging through syslog desired */
348 syslog(priority, "%s", msg);
349 }
350 }
352 /* Formats a message via vsnprintf() and logs it with given syslog() priority */
353 static void moonbr_log(int priority, const char *message, ...) {
354 char msgbuf[MOONBR_LOG_MAXMSGLEN+1]; /* buffer of static size to store formatted message */
355 int msglen; /* length of full message (may exceed MOONBR_LOG_MAXMSGLEN) */
356 {
357 /* pass variable arguments to vsnprintf() to format message */
358 va_list ap;
359 va_start(ap, message);
360 msglen = vsnprintf(msgbuf, MOONBR_LOG_MAXMSGLEN+1, message, ap);
361 va_end(ap);
362 }
363 {
364 /* split and log message line by line */
365 char *line = msgbuf;
366 while (1) {
367 char *endptr = strchr(line, '\n');
368 if (endptr) {
369 /* terminate string where newline character is found */
370 *endptr = 0;
371 } else if (line != msgbuf && msglen > MOONBR_LOG_MAXMSGLEN) {
372 /* break if line is incomplete and not the first line */
373 break;
374 }
375 moonbr_log_msg(priority, line);
376 if (!endptr) break; /* break if end of formatted message is reached */
377 line = endptr+1; /* otherwise continue with remaining message */
378 }
379 }
380 if (msglen > MOONBR_LOG_MAXMSGLEN) {
381 /* print warning if message was truncated */
382 moonbr_log_msg(priority, "Previous log message has been truncated due to excessive length");
383 }
384 }
387 /*** Termination function ***/
389 /* Kill all child processes, remove PID file (if existent), and exit master process with given exitcode */
390 static void moonbr_terminate(int exitcode) {
391 {
392 struct moonbr_pool *pool;
393 for (pool=moonbr_first_pool; pool; pool=pool->next_pool) {
394 {
395 struct moonbr_worker *worker;
396 for (worker=pool->first_worker; worker; worker=worker->next_worker) {
397 moonbr_log(LOG_INFO, "Sending SIGKILL to child with PID %i", (int)worker->pid);
398 if (kill(worker->pid, SIGKILL)) {
399 moonbr_log(LOG_ERR, "Error while killing child process: %s", strerror(errno));
400 }
401 }
402 }
403 {
404 int i;
405 for (i=0; i<pool->listener_count; i++) {
406 struct moonbr_listener *listener = &pool->listener[i];
407 if (listener->proto == MOONBR_PROTO_LOCAL) {
408 moonbr_log(LOG_INFO, "Unlinking local socket \"%s\"", listener->proto_specific.local.path);
409 if (unlink(listener->proto_specific.local.path)) {
410 moonbr_log(LOG_ERR, "Error while unlinking local socket: %s", strerror(errno));
411 }
412 }
413 }
414 }
415 }
416 }
417 moonbr_log(exitcode ? LOG_ERR : LOG_NOTICE, "Terminating with exit code %i", exitcode);
418 if (moonbr_pidfh && pidfile_remove(moonbr_pidfh)) {
419 moonbr_log(LOG_ERR, "Error while removing PID file: %s", strerror(errno));
420 }
421 exit(exitcode);
422 }
424 /* Terminate with either MOONBR_EXITCODE_STARTUPERROR or MOONBR_EXITCODE_RUNTIMEERROR */
425 #define moonbr_terminate_error() \
426 moonbr_terminate( \
427 moonbr_pstate == MOONBR_PSTATE_STARTUP ? \
428 MOONBR_EXITCODE_STARTUPERROR : \
429 MOONBR_EXITCODE_RUNTIMEERROR \
430 )
433 /*** Helper functions ***/
435 /* Fills a 'struct timeval' structure with the current time (using CLOCK_MONOTONIC) */
436 static void moonbr_now(struct timeval *now) {
437 struct timespec ts = {0, };
438 if (clock_gettime(CLOCK_MONOTONIC, &ts)) {
439 moonbr_log(LOG_CRIT, "Error in clock_gettime() call: %s", strerror(errno));
440 moonbr_terminate_error();
441 }
442 *now = (struct timeval){ .tv_sec = ts.tv_sec, .tv_usec = ts.tv_nsec / 1000 };
443 }
445 /* Formats a 'struct timeval' value (not thread-safe) */
446 static char *moonbr_format_timeval(struct timeval *t) {
447 static char buf[32];
448 snprintf(buf, 32, "%ji.%06ji seconds", (intmax_t)t->tv_sec, (intmax_t)t->tv_usec);
449 return buf;
450 }
453 /*** Functions for pool creation and startup ***/
455 /* Creates a 'struct moonbr_pool' structure with a given number of listeners */
456 static struct moonbr_pool *moonbr_create_pool(int listener_count) {
457 struct moonbr_pool *pool;
458 pool = calloc(1,
459 sizeof(struct moonbr_pool) + /* size of 'struct moonbr_pool' with one listener */
460 (listener_count-1) * sizeof(struct moonbr_listener) /* size of extra listeners */
461 );
462 if (!pool) {
463 moonbr_log(LOG_CRIT, "Memory allocation error");
464 moonbr_terminate_error();
465 }
466 pool->listener_count = listener_count;
467 {
468 /* initialization of listeners */
469 int i;
470 for (i=0; i<listener_count; i++) {
471 struct moonbr_listener *listener = &pool->listener[i];
472 listener->pool = pool;
473 listener->listenfd = -1;
474 listener->pollidx = -1;
475 }
476 }
477 return pool;
478 }
480 /* Destroys a 'struct moonbr_pool' structure before it has been started */
481 static void moonbr_destroy_pool(struct moonbr_pool *pool) {
482 int i;
483 for (i=0; i<pool->listener_count; i++) {
484 struct moonbr_listener *listener = &pool->listener[i];
485 if (
486 listener->proto == MOONBR_PROTO_INTERVAL &&
487 listener->proto_specific.interval.name
488 ) {
489 free(listener->proto_specific.interval.name);
490 }
491 if (
492 listener->proto == MOONBR_PROTO_LOCAL &&
493 listener->proto_specific.local.path
494 ) {
495 free(listener->proto_specific.local.path);
496 }
497 }
498 free(pool);
499 }
501 /* Starts a all listeners in a pool */
502 static int moonbr_start_pool(struct moonbr_pool *pool) {
503 moonbr_log(LOG_INFO, "Creating pool", pool->poolnum);
504 {
505 int i;
506 for (i=0; i<pool->listener_count; i++) {
507 struct moonbr_listener *listener = &pool->listener[i];
508 switch (listener->proto) {
509 case MOONBR_PROTO_INTERVAL:
510 /* nothing to do here: starting intervals is performed in moonbr_run() function */
511 if (!listener->proto_specific.interval.name) {
512 moonbr_log(LOG_INFO, "Adding unnamed interval listener");
513 } else {
514 moonbr_log(LOG_INFO, "Adding interval listener \"%s\"", listener->proto_specific.interval.name);
515 }
516 break;
517 case MOONBR_PROTO_LOCAL:
518 moonbr_log(LOG_INFO, "Adding local socket listener for path \"%s\"", listener->proto_specific.local.path);
519 {
520 struct sockaddr_un servaddr = { .sun_family = AF_UNIX };
521 const int path_maxlen = sizeof(struct sockaddr_un) - (
522 (void *)&servaddr.sun_path - (void *)&servaddr
523 );
524 if (
525 snprintf(
526 servaddr.sun_path,
527 path_maxlen,
528 "%s",
529 listener->proto_specific.local.path
530 ) >= path_maxlen
531 ) {
532 errno = ENAMETOOLONG;
533 };
534 listener->listenfd = socket(PF_LOCAL, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
535 if (listener->listenfd == -1) goto moonbr_start_pool_error;
536 if (!unlink(listener->proto_specific.local.path)) {
537 moonbr_log(LOG_WARNING, "Unlinked named socket \"%s\" prior to listening", listener->proto_specific.local.path);
538 } else {
539 if (errno != ENOENT) {
540 moonbr_log(LOG_ERR, "Could not unlink named socket \"%s\" prior to listening: %s", listener->proto_specific.local.path, strerror(errno));
541 }
542 }
543 if (
544 bind(listener->listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr))
545 ) goto moonbr_start_pool_error;
546 if (listen(listener->listenfd, MOONBR_LISTEN_BACKLOG)) goto moonbr_start_pool_error;
547 }
548 break;
549 case MOONBR_PROTO_TCP6:
550 if (listener->proto_specific.tcp.localhost_only) {
551 moonbr_log(LOG_INFO, "Adding localhost TCP/IPv6 listener on port %i", listener->proto_specific.tcp.port);
552 } else {
553 moonbr_log(LOG_INFO, "Adding public TCP/IPv6 listener on port %i", listener->proto_specific.tcp.port);
554 }
555 {
556 struct sockaddr_in6 servaddr = {
557 .sin6_family = AF_INET6,
558 .sin6_port = htons(listener->proto_specific.tcp.port)
559 };
560 listener->listenfd = socket(PF_INET6, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
561 if (listener->listenfd == -1) goto moonbr_start_pool_error;
562 {
563 /* avoid "Address already in use" error when restarting service */
564 static const int reuseval = 1;
565 if (setsockopt(
566 listener->listenfd, SOL_SOCKET, SO_REUSEADDR, &reuseval, sizeof(reuseval)
567 )) goto moonbr_start_pool_error;
568 }
569 {
570 /* default to send TCP RST when process terminates unexpectedly */
571 static const struct linger lingerval = {
572 .l_onoff = 1,
573 .l_linger = 0
574 };
575 if (setsockopt(
576 listener->listenfd, SOL_SOCKET, SO_LINGER, &lingerval, sizeof(lingerval)
577 )) goto moonbr_start_pool_error;
578 }
579 if (listener->proto_specific.tcp.localhost_only) {
580 servaddr.sin6_addr.s6_addr[15] = 1;
581 }
582 if (
583 bind(listener->listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr))
584 ) goto moonbr_start_pool_error;
585 if (listen(listener->listenfd, MOONBR_LISTEN_BACKLOG)) goto moonbr_start_pool_error;
586 }
587 break;
588 case MOONBR_PROTO_TCP4:
589 if (listener->proto_specific.tcp.localhost_only) {
590 moonbr_log(LOG_INFO, "Adding localhost TCP/IPv4 listener on port %i", listener->proto_specific.tcp.port);
591 } else {
592 moonbr_log(LOG_INFO, "Adding public TCP/IPv4 listener on port %i", listener->proto_specific.tcp.port);
593 }
594 {
595 struct sockaddr_in servaddr = {
596 .sin_family = AF_INET,
597 .sin_port = htons(listener->proto_specific.tcp.port)
598 };
599 listener->listenfd = socket(PF_INET, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
600 if (listener->listenfd == -1) goto moonbr_start_pool_error;
601 {
602 /* avoid "Address already in use" error when restarting service */
603 static const int reuseval = 1;
604 if (setsockopt(
605 listener->listenfd, SOL_SOCKET, SO_REUSEADDR, &reuseval, sizeof(reuseval)
606 )) goto moonbr_start_pool_error;
607 }
608 {
609 /* default to send TCP RST when process terminates unexpectedly */
610 static const struct linger lingerval = {
611 .l_onoff = 1,
612 .l_linger = 0
613 };
614 if (setsockopt(
615 listener->listenfd, SOL_SOCKET, SO_LINGER, &lingerval, sizeof(lingerval)
616 )) goto moonbr_start_pool_error;
617 }
618 if (listener->proto_specific.tcp.localhost_only) {
619 ((uint8_t *)&servaddr.sin_addr.s_addr)[0] = 127;
620 ((uint8_t *)&servaddr.sin_addr.s_addr)[3] = 1;
621 }
622 if (
623 bind(listener->listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr))
624 ) goto moonbr_start_pool_error;
625 if (listen(listener->listenfd, MOONBR_LISTEN_BACKLOG)) goto moonbr_start_pool_error;
626 }
627 break;
628 default:
629 moonbr_log(LOG_CRIT, "Internal error (should not happen): Unexpected value in listener.proto field");
630 moonbr_terminate_error();
631 }
632 }
633 goto moonbr_start_pool_ok;
634 moonbr_start_pool_error:
635 {
636 int j = i;
637 int errno2 = errno;
638 for (; i>=0; i--) {
639 struct moonbr_listener *listener = &pool->listener[i];
640 if (listener->listenfd != -1) close(listener->listenfd);
641 }
642 errno = errno2;
643 return j;
644 }
645 }
646 moonbr_start_pool_ok:
647 pool->poolnum = ++moonbr_pool_count;
648 moonbr_log(LOG_INFO, "Pool #%i created", pool->poolnum);
649 if (moonbr_last_pool) moonbr_last_pool->next_pool = pool;
650 else moonbr_first_pool = pool;
651 moonbr_last_pool = pool;
652 return -1;
653 }
656 /*** Function to send data and a file descriptor to child process */
658 /* Sends control message of one bye plus optional file descriptor plus optional pointer to child process */
659 static void moonbr_send_control_message(struct moonbr_worker *worker, char status, int fd, void *ptr) {
660 {
661 struct iovec iovector = { .iov_base = &status, .iov_len = 1 }; /* carrying status byte */
662 char control_message_buffer[CMSG_SPACE(sizeof(int))] = {0, }; /* used to transfer file descriptor */
663 struct msghdr message = { .msg_iov = &iovector, .msg_iovlen = 1 }; /* data structure passed to sendmsg() call */
664 if (moonbr_debug) {
665 if (fd == -1) {
666 moonbr_log(LOG_DEBUG, "Sending control message \"%c\" to child process in pool #%i (PID %i)", (int)status, worker->pool->poolnum, (int)worker->pid);
667 } else {
668 moonbr_log(LOG_DEBUG, "Sending control message \"%c\" with file descriptor #%i to child process in pool #%i (PID %i)", (int)status, fd, worker->pool->poolnum, (int)worker->pid);
669 }
670 }
671 if (fd != -1) {
672 /* attach control message with file descriptor */
673 message.msg_control = control_message_buffer;
674 message.msg_controllen = CMSG_SPACE(sizeof(int));
675 {
676 struct cmsghdr *control_message = CMSG_FIRSTHDR(&message);
677 control_message->cmsg_level = SOL_SOCKET;
678 control_message->cmsg_type = SCM_RIGHTS;
679 control_message->cmsg_len = CMSG_LEN(sizeof(int));
680 memcpy(CMSG_DATA(control_message), &fd, sizeof(int));
681 }
682 }
683 while (sendmsg(worker->controlfd, &message, MSG_NOSIGNAL) < 0) {
684 if (errno == EPIPE) {
685 moonbr_log(LOG_ERR, "Error while communicating with idle child process in pool #%i (PID %i): %s", worker->pool->poolnum, (int)worker->pid, strerror(errno));
686 return; /* do not close socket; socket is closed when reading from it */
687 }
688 if (errno != EINTR) {
689 moonbr_log(LOG_CRIT, "Unexpected error while communicating with idle child process in pool #%i (PID %i): %s", worker->pool->poolnum, (int)worker->pid, strerror(errno));
690 moonbr_terminate_error();
691 }
692 }
693 }
694 if (ptr) {
695 char buf[sizeof(void *)];
696 char *pos = buf;
697 int len = sizeof(void *);
698 ssize_t written;
699 if (moonbr_debug) {
700 moonbr_log(LOG_DEBUG, "Sending memory pointer to child process in pool #%i (PID %i)", (int)status, worker->pool->poolnum, (int)worker->pid);
701 }
702 memcpy(buf, &ptr, sizeof(void *));
703 while (len) {
704 written = send(worker->controlfd, pos, len, MSG_NOSIGNAL);
705 if (written > 0) {
706 pos += written;
707 len -= written;
708 } else if (errno == EPIPE) {
709 moonbr_log(LOG_ERR, "Error while communicating with idle child process in pool #%i (PID %i): %s", worker->pool->poolnum, (int)worker->pid, strerror(errno));
710 return; /* do not close socket; socket is closed when reading from it */
711 } else if (errno != EINTR) {
712 moonbr_log(LOG_CRIT, "Unexpected error while communicating with idle child process in pool #%i (PID %i): %s", worker->pool->poolnum, (int)worker->pid, strerror(errno));
713 moonbr_terminate_error();
714 }
715 }
716 }
717 }
720 /*** Functions running in child process ***/
722 /* Logs an error in child process */
723 static void moonbr_child_log(const char *message) {
724 fprintf(stderr, "%s\n", message);
725 }
727 /* Logs a fatal error in child process and terminates process with error status */
728 static void moonbr_child_log_fatal(const char *message) {
729 moonbr_child_log(message);
730 exit(1);
731 }
733 /* Logs an error in child process while appending error string for global errno variable */
734 static void moonbr_child_log_errno(const char *message) {
735 char errmsg[MOONBR_MAXSTRERRORLEN];
736 strerror_r(errno, errmsg, MOONBR_MAXSTRERRORLEN); /* use thread-safe call in case child created threads */
737 fprintf(stderr, "%s: %s\n", message, errmsg);
738 }
740 /* Logs a fatal error in child process while appending error string for errno and terminating process */
741 static void moonbr_child_log_errno_fatal(const char *message) {
742 moonbr_child_log_errno(message);
743 exit(1);
744 }
746 /* Receives a control message consisting of one character plus an optional file descriptor from parent process */
747 static void moonbr_child_receive_control_message(int socketfd, char *status, int *fd) {
748 struct iovec iovector = { .iov_base = status, .iov_len = 1 }; /* reference to status byte variable */
749 char control_message_buffer[CMSG_SPACE(sizeof(int))] = {0, }; /* used to receive file descriptor */
750 struct msghdr message = { /* data structure passed to recvmsg() call */
751 .msg_iov = &iovector,
752 .msg_iovlen = 1,
753 .msg_control = control_message_buffer,
754 .msg_controllen = CMSG_SPACE(sizeof(int))
755 };
756 {
757 int received;
758 while ((received = recvmsg(socketfd, &message, MSG_CMSG_CLOEXEC)) < 0) {
759 if (errno != EINTR) {
760 moonbr_child_log_errno_fatal("Error while trying to receive connection socket from parent process");
761 }
762 }
763 if (!received) {
764 moonbr_child_log_fatal("Unexpected EOF while trying to receive connection socket from parent process");
765 }
766 }
767 {
768 struct cmsghdr *control_message = CMSG_FIRSTHDR(&message);
769 if (control_message) {
770 if (control_message->cmsg_level != SOL_SOCKET) {
771 moonbr_child_log_fatal("Received control message with cmsg_level not equal to SOL_SOCKET");
772 }
773 if (control_message->cmsg_type != SCM_RIGHTS) {
774 moonbr_child_log_fatal("Received control message with cmsg_type not equal to SCM_RIGHTS");
775 }
776 memcpy(fd, CMSG_DATA(control_message), sizeof(int));
777 } else {
778 *fd = -1;
779 }
780 }
781 }
783 /* Receives a pointer from parent process */
784 static void *moonbr_child_receive_pointer(int socketfd) {
785 char buf[sizeof(void *)];
786 char *pos = buf;
787 int len = sizeof(void *);
788 ssize_t bytes_read;
789 while (len) {
790 bytes_read = recv(socketfd, pos, len, 0);
791 if (bytes_read > 0) {
792 pos += bytes_read;
793 len -= bytes_read;
794 } else if (!bytes_read) {
795 moonbr_child_log_fatal("Unexpected EOF while trying to receive memory pointer from parent process");
796 } else if (errno != EINTR) {
797 moonbr_child_log_errno_fatal("Error while trying to receive memory pointer from parent process");
798 }
799 }
800 {
801 void *ptr; /* avoid breaking strict-aliasing rules */
802 memcpy(&ptr, buf, sizeof(void *));
803 return ptr;
804 }
805 }
807 /* Throws a Lua error message with an error string for errno appended to it */
808 static void moonbr_child_lua_errno_error(lua_State *L, char *message) {
809 char errmsg[MOONBR_MAXSTRERRORLEN];
810 strerror_r(errno, errmsg, MOONBR_MAXSTRERRORLEN); /* use thread-safe call in case child created threads */
811 luaL_error(L, "%s: %s", message, errmsg);
812 }
814 /* Closes the input stream from peer unless it has already been closed */
815 static int moonbr_child_close_peersocket_inputstream(
816 int cleanshut, /* nonzero = use shutdown() if applicable */
817 int mark /* nonzero = mark the stream as closed for Lua */
818 ) {
819 int err = 0; /* nonzero = error occurred */
820 int errno2; /* stores previous errno values that take precedence */
821 if (moonbr_child_peersocket_inputstream->f) {
822 if (cleanshut && moonbr_child_peersocket_type == MOONBR_SOCKETTYPE_NETWORK) {
823 if (shutdown(moonbr_child_peersocket_fd, SHUT_RD)) {
824 errno2 = errno;
825 err = -1;
826 }
827 }
828 if (fclose(moonbr_child_peersocket_inputstream->f)) {
829 if (!err) errno2 = errno;
830 err = -1;
831 }
832 moonbr_child_peersocket_inputstream->f = NULL;
833 }
834 if (mark) moonbr_child_peersocket_inputstream->closef = NULL;
835 if (err) errno = errno2;
836 return err;
837 }
839 /* Closes the output stream to peer unless it has already been closed */
840 static int moonbr_child_close_peersocket_outputstream(
841 int cleanshut, /* nonzero = use fflush() and shutdown() if applicable */
842 int mark /* nonzero = mark the stream as closed for Lua */
843 ) {
844 int err = 0; /* nonzero = error occurred */
845 int errno2; /* stores previous errno values that take precedence */
846 if (moonbr_child_peersocket_outputstream->f) {
847 if (moonbr_child_peersocket_type == MOONBR_SOCKETTYPE_NETWORK) {
848 if (cleanshut) {
849 if (fflush(moonbr_child_peersocket_outputstream->f)) {
850 errno2 = errno;
851 err = -1;
852 } else {
853 if (shutdown(moonbr_child_peersocket_fd, SHUT_WR)) {
854 errno2 = errno;
855 err = -1;
856 }
857 }
858 } else {
859 fpurge(moonbr_child_peersocket_outputstream->f);
860 }
861 }
862 if (fclose(moonbr_child_peersocket_outputstream->f)) {
863 if (!err) errno2 = errno;
864 err = -1;
865 }
866 moonbr_child_peersocket_outputstream->f = NULL;
867 }
868 if (mark) moonbr_child_peersocket_outputstream->closef = NULL;
869 if (err) errno = errno2;
870 return err;
871 }
873 /* Perform a clean shutdown of input and output stream (may be called multiple times) */
874 static int moonbr_child_close_peersocket(int timeout) {
875 int errprio = 0;
876 int errno2;
877 if (moonbr_child_peersocket_fd == -1) return 0;
878 if (moonbr_child_close_peersocket_inputstream(1, 1)) {
879 errprio = 1;
880 errno2 = errno;
881 }
882 if (moonbr_child_close_peersocket_outputstream(1, 1)) {
883 errprio = 4;
884 errno2 = errno;
885 }
886 if (moonbr_child_peersocket_type == MOONBR_SOCKETTYPE_NETWORK) {
887 struct linger lingerval = { 0, };
888 if (timeout && !errprio) {
889 lingerval.l_onoff = 1;
890 lingerval.l_linger = timeout;
891 }
892 if (setsockopt(moonbr_child_peersocket_fd, SOL_SOCKET, SO_LINGER, &lingerval, sizeof(lingerval))) {
893 if (errprio < 2) {
894 errprio = 2;
895 errno2 = errno;
896 }
897 }
898 }
899 if (close(moonbr_child_peersocket_fd)) {
900 if (errprio < 3) {
901 errprio = 3;
902 errno2 = errno;
903 }
904 }
905 moonbr_child_peersocket_fd = -1;
906 if (errprio) {
907 errno = errno2;
908 return -1;
909 }
910 return 0;
911 }
913 /* Close socket and cause reset of TCP connection (TCP RST aka "Connection reset by peer") if possible */
914 static int moonbr_child_cancel_peersocket() {
915 int err = 0;
916 if (moonbr_child_close_peersocket_inputstream(0, 1)) err = -1;
917 if (moonbr_child_close_peersocket_outputstream(0, 1)) err = -1;
918 if (close(moonbr_child_peersocket_fd)) err = -1;
919 moonbr_child_peersocket_fd = -1;
920 return err;
921 }
923 /* Lua method for socket object to read from input stream */
924 static int moonbr_child_lua_read_stream(lua_State *L) {
925 lua_getfield(L, 1, "input");
926 lua_getfield(L, -1, "read");
927 lua_insert(L, 1);
928 lua_replace(L, 2);
929 lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
930 return lua_gettop(L);
931 }
933 /* Lua method for socket object to read from input stream until terminator */
934 static int moonbr_child_lua_readuntil_stream(lua_State *L) {
935 lua_getfield(L, 1, "input");
936 lua_getfield(L, -1, "readuntil");
937 lua_insert(L, 1);
938 lua_replace(L, 2);
939 lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
940 return lua_gettop(L);
941 }
943 /* Lua method for socket object to iterate over input stream */
944 static int moonbr_child_lua_lines_stream(lua_State *L) {
945 lua_getfield(L, 1, "input");
946 lua_getfield(L, -1, "lines");
947 lua_insert(L, 1);
948 lua_replace(L, 2);
949 lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
950 return lua_gettop(L);
951 }
953 /* Lua method for socket object to write to output stream */
954 static int moonbr_child_lua_write_stream(lua_State *L) {
955 lua_getfield(L, 1, "output");
956 lua_getfield(L, -1, "write");
957 lua_insert(L, 1);
958 lua_replace(L, 2);
959 lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
960 return lua_gettop(L);
961 }
963 /* Lua method for socket object to flush the output stream */
964 static int moonbr_child_lua_flush_stream(lua_State *L) {
965 lua_getfield(L, 1, "output");
966 lua_getfield(L, -1, "flush");
967 lua_insert(L, 1);
968 lua_replace(L, 2);
969 lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
970 return lua_gettop(L);
971 }
973 /* Lua function to close a single stream (input or output) from/to peer */
974 static int moonbr_child_lua_close_stream(lua_State *L) {
975 luaL_Stream *stream = lua_touserdata(L, 1);
976 if (stream == moonbr_child_peersocket_inputstream) {
977 if (moonbr_child_close_peersocket_inputstream(1, 0)) { /* don't mark as closed as it's done by Lua */
978 moonbr_child_lua_errno_error(L, "Could not close input stream");
979 }
980 } else if (stream == moonbr_child_peersocket_outputstream) {
981 if (moonbr_child_close_peersocket_outputstream(1, 0)) { /* don't mark as closed as it's done by Lua */
982 moonbr_child_lua_errno_error(L, "Could not close output stream");
983 }
984 } else {
985 luaL_argerror(L, 1, "Not a connection socket");
986 }
987 return 0;
988 }
990 /* Lua function to close both input and output stream from/to peer */
991 static int moonbr_child_lua_close_both_streams(lua_State *L) {
992 int timeout = 0;
993 if (!lua_isnoneornil(L, 2)) {
994 lua_Integer n = luaL_checkinteger(L, 2);
995 luaL_argcheck(L, n >= 0 && n <= INT_MAX, 2, "out of range");
996 timeout = n;
997 }
998 if (moonbr_child_peersocket_fd == -1) {
999 luaL_error(L, "Connection with peer has already been explicitly closed");
1001 if (moonbr_child_close_peersocket(timeout)) {
1002 moonbr_child_lua_errno_error(L, "Could not close socket connection with peer");
1004 return 0;
1007 /* Lua function to close both input and output stream from/to peer */
1008 static int moonbr_child_lua_cancel_both_streams(lua_State *L) {
1009 if (moonbr_child_peersocket_fd == -1) {
1010 luaL_error(L, "Connection with peer has already been explicitly closed");
1012 if (moonbr_child_cancel_peersocket()) {
1013 moonbr_child_lua_errno_error(L, "Could not cancel socket connection with peer");
1015 return 0;
1018 /* Methods of (bidirectional) socket object passed to handler */
1019 static luaL_Reg moonbr_child_lua_socket_functions[] = {
1020 {"read", moonbr_child_lua_read_stream},
1021 {"readuntil", moonbr_child_lua_readuntil_stream},
1022 {"lines", moonbr_child_lua_lines_stream},
1023 {"write", moonbr_child_lua_write_stream},
1024 {"flush", moonbr_child_lua_flush_stream},
1025 {"close", moonbr_child_lua_close_both_streams},
1026 {"cancel", moonbr_child_lua_cancel_both_streams},
1027 {NULL, NULL}
1028 };
1030 /* Main function of child process to be called after fork() and file descriptor rearrangement */
1031 void moonbr_child_run(struct moonbr_pool *pool, lua_State *L) {
1032 char controlmsg;
1033 struct itimerval notimer = { { 0, }, { 0, } };
1034 lua_rawgetp(L, LUA_REGISTRYINDEX, moonbr_luakey_prepare_func(pool));
1035 if (lua_isnil(L, -1)) lua_pop(L, 1);
1036 else if (lua_pcall(L, 0, 0, 1)) {
1037 fprintf(stderr, "Error in \"prepare\" function: %s\n", lua_tostring(L, -1));
1038 exit(1);
1040 while (1) {
1041 struct moonbr_listener *listener;
1042 if (setitimer(ITIMER_REAL, &notimer, NULL)) {
1043 moonbr_child_log_errno_fatal("Could not reset ITIMER_REAL via setitimer()");
1045 controlmsg = MOONBR_STATUS_IDLE;
1046 if (write(MOONBR_FD_CONTROL, &controlmsg, 1) <= 0) {
1047 moonbr_child_log_errno_fatal("Error while sending ready message to parent process");
1049 moonbr_child_receive_control_message(
1050 MOONBR_FD_CONTROL,
1051 &controlmsg,
1052 &moonbr_child_peersocket_fd
1053 );
1054 if (!(
1055 (controlmsg == MOONBR_COMMAND_TERMINATE && moonbr_child_peersocket_fd == -1) ||
1056 (controlmsg == MOONBR_SOCKETTYPE_INTERVAL && moonbr_child_peersocket_fd == -1) ||
1057 (controlmsg == MOONBR_SOCKETTYPE_LOCAL && moonbr_child_peersocket_fd != -1) ||
1058 (controlmsg == MOONBR_SOCKETTYPE_NETWORK && moonbr_child_peersocket_fd != -1)
1059 )) {
1060 moonbr_child_log_fatal("Received illegal control message from parent process");
1062 if (controlmsg == MOONBR_COMMAND_TERMINATE) break;
1063 listener = moonbr_child_receive_pointer(MOONBR_FD_CONTROL);
1064 moonbr_child_peersocket_type = controlmsg;
1065 if (moonbr_child_peersocket_fd != -1) {
1067 int clonedfd;
1068 clonedfd = dup(moonbr_child_peersocket_fd);
1069 if (!clonedfd) {
1070 moonbr_child_log_errno_fatal("Could not duplicate file descriptor for input stream");
1072 moonbr_child_peersocket_inputstream = lua_newuserdata(L, sizeof(luaL_Stream));
1073 if (!moonbr_child_peersocket_inputstream) {
1074 moonbr_child_log_fatal("Memory allocation error");
1076 moonbr_child_peersocket_inputstream->f = fdopen(clonedfd, "rb");
1077 if (!moonbr_child_peersocket_inputstream->f) {
1078 moonbr_child_log_errno_fatal("Could not open input stream for remote connection");
1080 moonbr_child_peersocket_inputstream->closef = moonbr_child_lua_close_stream;
1081 if (luaL_newmetatable(L, LUA_FILEHANDLE)) {
1082 moonbr_child_log_fatal("Lua metatable LUA_FILEHANDLE does not exist");
1084 lua_setmetatable(L, -2);
1087 int clonedfd;
1088 clonedfd = dup(moonbr_child_peersocket_fd);
1089 if (!clonedfd) {
1090 moonbr_child_log_errno_fatal("Could not duplicate file descriptor for output stream");
1092 moonbr_child_peersocket_outputstream = lua_newuserdata(L, sizeof(luaL_Stream));
1093 if (!moonbr_child_peersocket_outputstream) {
1094 moonbr_child_log_fatal("Memory allocation error");
1096 moonbr_child_peersocket_outputstream->f = fdopen(clonedfd, "wb");
1097 if (!moonbr_child_peersocket_outputstream->f) {
1098 moonbr_child_log_errno_fatal("Could not open output stream for remote connection");
1100 moonbr_child_peersocket_outputstream->closef = moonbr_child_lua_close_stream;
1101 if (luaL_newmetatable(L, LUA_FILEHANDLE)) {
1102 moonbr_child_log_fatal("Lua metatable LUA_FILEHANDLE does not exist");
1104 lua_setmetatable(L, -2);
1107 lua_rawgetp(L, LUA_REGISTRYINDEX, moonbr_luakey_connect_func(pool));
1108 if (listener->proto == MOONBR_PROTO_INTERVAL) {
1109 lua_newtable(L);
1110 lua_pushstring(L,
1111 listener->proto_specific.interval.name ?
1112 listener->proto_specific.interval.name : ""
1113 );
1114 lua_setfield(L, -2, "interval");
1115 } else {
1116 lua_newtable(L);
1117 lua_pushvalue(L, -4);
1118 lua_setfield(L, -2, "input");
1119 lua_pushvalue(L, -3);
1120 lua_setfield(L, -2, "output");
1121 luaL_setfuncs(L, moonbr_child_lua_socket_functions, 0);
1122 if (listener->proto == MOONBR_PROTO_TCP6) {
1123 struct sockaddr_in6 addr;
1124 socklen_t addr_len = sizeof(struct sockaddr_in6);
1125 if (getsockname(moonbr_child_peersocket_fd, (struct sockaddr *)&addr, &addr_len)) {
1126 moonbr_child_log_errno("Could not get local IP address/port");
1127 } else {
1128 lua_pushlstring(L, (char *)addr.sin6_addr.s6_addr, 16);
1129 lua_setfield(L, -2, "local_ip6");
1130 lua_pushinteger(L, ntohs(addr.sin6_port));
1131 lua_setfield(L, -2, "local_tcpport");
1133 if (getpeername(moonbr_child_peersocket_fd, (struct sockaddr *)&addr, &addr_len)) {
1134 moonbr_child_log_errno("Could not get remote IP address/port");
1135 } else {
1136 lua_pushlstring(L, (char *)addr.sin6_addr.s6_addr, 16);
1137 lua_setfield(L, -2, "remote_ip6");
1138 lua_pushinteger(L, ntohs(addr.sin6_port));
1139 lua_setfield(L, -2, "remote_tcpport");
1141 } else if (listener->proto == MOONBR_PROTO_TCP4) {
1142 struct sockaddr_in addr;
1143 socklen_t addr_len = sizeof(struct sockaddr_in);
1144 if (getsockname(moonbr_child_peersocket_fd, (struct sockaddr *)&addr, &addr_len)) {
1145 moonbr_child_log_errno("Could not get local IP address/port");
1146 } else {
1147 lua_pushlstring(L, (char *)&addr.sin_addr.s_addr, 4);
1148 lua_setfield(L, -2, "local_ip4");
1149 lua_pushinteger(L, ntohs(addr.sin_port));
1150 lua_setfield(L, -2, "local_tcpport");
1152 if (getpeername(moonbr_child_peersocket_fd, (struct sockaddr *)&addr, &addr_len)) {
1153 moonbr_child_log_errno("Could not get remote IP address/port");
1154 } else {
1155 lua_pushlstring(L, (char *)&addr.sin_addr.s_addr, 4);
1156 lua_setfield(L, -2, "remote_ip4");
1157 lua_pushinteger(L, ntohs(addr.sin_port));
1158 lua_setfield(L, -2, "remote_tcpport");
1162 if (lua_pcall(L, 1, 1, 1)) {
1163 fprintf(stderr, "Error in \"connect\" function: %s\n", lua_tostring(L, -1));
1164 exit(1);
1166 if (moonbr_child_close_peersocket(0)) {
1167 moonbr_child_log_errno("Could not close socket connection with peer");
1169 if (lua_type(L, -1) != LUA_TBOOLEAN || !lua_toboolean(L, -1)) break;
1170 #ifdef MOONBR_LUA_PANIC_BUG_WORKAROUND
1171 lua_settop(L, 2);
1172 #else
1173 lua_settop(L, 1);
1174 #endif
1176 controlmsg = MOONBR_STATUS_GOODBYE;
1177 if (write(MOONBR_FD_CONTROL, &controlmsg, 1) <= 0) {
1178 moonbr_child_log_errno_fatal("Error while sending goodbye message to parent process");
1180 if (close(MOONBR_FD_CONTROL) && errno != EINTR) {
1181 moonbr_child_log_errno("Error while closing control socket");
1183 lua_rawgetp(L, LUA_REGISTRYINDEX, moonbr_luakey_finish_func(pool));
1184 if (lua_isnil(L, -1)) lua_pop(L, 1);
1185 else if (lua_pcall(L, 0, 0, 1)) {
1186 fprintf(stderr, "Error in \"finish\" function: %s\n", lua_tostring(L, -1));
1187 exit(1);
1189 lua_close(L);
1190 exit(0);
1194 /*** Functions to spawn child process ***/
1196 /* Helper function to send an error message to a file descriptor (not needing a file stream) */
1197 static void moonbr_child_emergency_print(int fd, char *message) {
1198 size_t len = strlen(message);
1199 ssize_t written;
1200 while (len) {
1201 written = write(fd, message, len);
1202 if (written > 0) {
1203 message += written;
1204 len -= written;
1205 } else {
1206 if (written != -1 || errno != EINTR) break;
1211 /* Helper function to send an error message plus a text for errno to a file descriptor and terminate the process */
1212 static void moonbr_child_emergency_error(int fd, char *message) {
1213 int errno2 = errno;
1214 moonbr_child_emergency_print(fd, message);
1215 moonbr_child_emergency_print(fd, ": ");
1216 moonbr_child_emergency_print(fd, strerror(errno2));
1217 moonbr_child_emergency_print(fd, "\n");
1218 exit(1);
1221 /* Creates a child process and (in case of success) registers it in the 'struct moonbr_pool' structure */
1222 static int moonbr_create_worker(struct moonbr_pool *pool, lua_State *L) {
1223 struct moonbr_worker *worker;
1224 worker = calloc(1, sizeof(struct moonbr_worker));
1225 if (!worker) {
1226 moonbr_log(LOG_CRIT, "Memory allocation error");
1227 return -1;
1229 worker->pool = pool;
1231 int controlfds[2];
1232 int errorfds[2];
1233 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, controlfds)) {
1234 moonbr_log(LOG_ERR, "Could not create control socket pair for communcation with child process: %s", strerror(errno));
1235 free(worker);
1236 return -1;
1238 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, errorfds)) {
1239 moonbr_log(LOG_ERR, "Could not create socket pair to redirect stderr of child process: %s", strerror(errno));
1240 close(controlfds[0]);
1241 close(controlfds[1]);
1242 free(worker);
1243 return -1;
1245 if (moonbr_logfile && fflush(moonbr_logfile)) {
1246 moonbr_log(LOG_CRIT, "Could not flush log file prior to forking: %s", strerror(errno));
1247 moonbr_terminate_error();
1249 worker->pid = fork();
1250 if (worker->pid == -1) {
1251 moonbr_log(LOG_ERR, "Could not fork: %s", strerror(errno));
1252 close(controlfds[0]);
1253 close(controlfds[1]);
1254 close(errorfds[0]);
1255 close(errorfds[1]);
1256 free(worker);
1257 return -1;
1258 } else if (!worker->pid) {
1259 moonbr_pstate = MOONBR_PSTATE_FORKED;
1260 #ifdef MOONBR_LUA_PANIC_BUG_WORKAROUND
1261 lua_pushliteral(L, "Failed to pass error message due to bug in Lua panic handler (hint: not enough memory?)");
1262 #endif
1263 moonbr_memory_limit = pool->memory_limit;
1264 if (moonbr_pidfh && pidfile_close(moonbr_pidfh)) {
1265 moonbr_child_emergency_error(errorfds[1], "Could not close PID file in forked child process");
1267 if (moonbr_logfile && moonbr_logfile != stderr && fclose(moonbr_logfile)) {
1268 moonbr_child_emergency_error(errorfds[1], "Could not close log file in forked child process");
1270 if (dup2(errorfds[1], MOONBR_FD_STDERR) == -1) {
1271 moonbr_child_emergency_error(errorfds[1], "Could not duplicate socket to stderr file descriptor");
1273 if (dup2(controlfds[1], MOONBR_FD_CONTROL) == -1) {
1274 moonbr_child_emergency_error(errorfds[1], "Could not duplicate control socket");
1276 closefrom(MOONBR_FD_END);
1277 moonbr_child_run(pool, L);
1279 if (moonbr_stat) {
1280 moonbr_log(LOG_INFO, "Created new worker in pool #%i with PID %i", worker->pool->poolnum, (int)worker->pid);
1282 worker->controlfd = controlfds[0];
1283 worker->errorfd = errorfds[0];
1284 if (close(controlfds[1]) && errno != EINTR) {
1285 moonbr_log(LOG_CRIT, "Could not close opposite end of control file descriptor after forking");
1286 moonbr_terminate_error();
1288 if (close(errorfds[1]) && errno != EINTR) {
1289 moonbr_log(LOG_CRIT, "Could not close opposite end of control file descriptor after forking");
1290 moonbr_terminate_error();
1293 worker->prev_worker = pool->last_worker;
1294 if (worker->prev_worker) worker->prev_worker->next_worker = worker;
1295 else pool->first_worker = worker;
1296 pool->last_worker = worker;
1297 pool->unassigned_worker_count++;
1298 pool->total_worker_count++;
1299 pool->worker_count_stat = 1;
1300 moonbr_poll_refresh_needed = 1;
1301 return 0; /* return zero only in case of success */
1305 /*** Functions to handle previously created 'struct moonbr_worker' structures ***/
1307 #define moonbr_try_destroy_worker_stat(str, field) \
1308 moonbr_log(LOG_INFO, "Resource usage in pool #%i for PID %i: " str " %li", worker->pool->poolnum, (int)worker->pid, (long)childusage.field);
1310 /* Destroys a worker structure if socket connections have been closed and child process has terminated */
1311 static int moonbr_try_destroy_worker(struct moonbr_worker *worker) {
1312 if (worker->controlfd != -1 || worker->errorfd != -1) return MOONBR_DESTROY_NONE;
1314 int childstatus;
1315 struct rusage childusage;
1317 pid_t waitedpid;
1318 while (
1319 (waitedpid = wait4(worker->pid, &childstatus, WNOHANG, &childusage)) == -1
1320 ) {
1321 if (errno != EINTR) {
1322 moonbr_log(LOG_CRIT, "Error in wait4() call: %s", strerror(errno));
1323 moonbr_terminate_error();
1326 if (!waitedpid) return 0; /* return 0 if worker couldn't be destroyed */
1327 if (waitedpid != worker->pid) {
1328 moonbr_log(LOG_CRIT, "Wrong PID returned by wait4() call");
1329 moonbr_terminate_error();
1332 if (WIFEXITED(childstatus)) {
1333 if (WEXITSTATUS(childstatus) || moonbr_stat) {
1334 moonbr_log(
1335 WEXITSTATUS(childstatus) ? LOG_WARNING : LOG_INFO,
1336 "Child process in pool #%i with PID %i returned with exit code %i", worker->pool->poolnum, (int)worker->pid, WEXITSTATUS(childstatus)
1337 );
1339 } else if (WIFSIGNALED(childstatus)) {
1340 if (WCOREDUMP(childstatus)) {
1341 moonbr_log(LOG_ERR, "Child process in pool #%i with PID %i died from signal %i (core dump was created)", worker->pool->poolnum, (int)worker->pid, WTERMSIG(childstatus));
1342 } else if (WTERMSIG(childstatus) == SIGALRM) {
1343 moonbr_log(LOG_WARNING, "Child process in pool #%i with PID %i exited prematurely due to timeout", worker->pool->poolnum, (int)worker->pid);
1344 } else {
1345 moonbr_log(LOG_ERR, "Child process in pool #%i with PID %i died from signal %i", worker->pool->poolnum, (int)worker->pid, WTERMSIG(childstatus));
1347 } else {
1348 moonbr_log(LOG_CRIT, "Illegal exit status from child process in pool #%i with PID %i", worker->pool->poolnum, (int)worker->pid);
1349 moonbr_terminate_error();
1351 if (moonbr_stat) {
1352 moonbr_log(LOG_INFO, "Resource usage in pool #%i for PID %i: user time %s", worker->pool->poolnum, (int)worker->pid, moonbr_format_timeval(&childusage.ru_utime));
1353 moonbr_log(LOG_INFO, "Resource usage in pool #%i for PID %i: system time %s", worker->pool->poolnum, (int)worker->pid, moonbr_format_timeval(&childusage.ru_stime));
1354 moonbr_try_destroy_worker_stat("max resident set size", ru_maxrss);
1355 moonbr_try_destroy_worker_stat("integral shared memory size", ru_ixrss);
1356 moonbr_try_destroy_worker_stat("integral unshared data", ru_idrss);
1357 moonbr_try_destroy_worker_stat("integral unshared stack", ru_isrss);
1358 moonbr_try_destroy_worker_stat("page replaims", ru_minflt);
1359 moonbr_try_destroy_worker_stat("page faults", ru_majflt);
1360 moonbr_try_destroy_worker_stat("swaps", ru_nswap);
1361 moonbr_try_destroy_worker_stat("block input operations", ru_inblock);
1362 moonbr_try_destroy_worker_stat("block output operations", ru_oublock);
1363 moonbr_try_destroy_worker_stat("messages sent", ru_msgsnd);
1364 moonbr_try_destroy_worker_stat("messages received", ru_msgrcv);
1365 moonbr_try_destroy_worker_stat("signals received", ru_nsignals);
1366 moonbr_try_destroy_worker_stat("voluntary context switches", ru_nvcsw);
1367 moonbr_try_destroy_worker_stat("involuntary context switches", ru_nivcsw);
1371 int retval = (
1372 (worker->idle || worker->assigned) ?
1373 MOONBR_DESTROY_IDLE_OR_ASSIGNED :
1374 MOONBR_DESTROY_PREPARE
1375 );
1376 if (worker->prev_worker) worker->prev_worker->next_worker = worker->next_worker;
1377 else worker->pool->first_worker = worker->next_worker;
1378 if (worker->next_worker) worker->next_worker->prev_worker = worker->prev_worker;
1379 else worker->pool->last_worker = worker->prev_worker;
1380 if (worker->idle) {
1381 if (worker->prev_idle_worker) worker->prev_idle_worker->next_idle_worker = worker->next_idle_worker;
1382 else worker->pool->first_idle_worker = worker->next_idle_worker;
1383 if (worker->next_idle_worker) worker->next_idle_worker->prev_idle_worker = worker->prev_idle_worker;
1384 else worker->pool->last_idle_worker = worker->prev_idle_worker;
1385 worker->pool->idle_worker_count--;
1387 if (!worker->assigned) worker->pool->unassigned_worker_count--;
1388 worker->pool->total_worker_count--;
1389 worker->pool->worker_count_stat = 1;
1390 if (worker->errorlinebuf) free(worker->errorlinebuf);
1391 free(worker);
1392 return retval;
1396 /* Marks a worker as idle and stores it in a queue, optionally setting 'idle_expiration' value */
1397 static void moonbr_add_idle_worker(struct moonbr_worker *worker) {
1398 worker->prev_idle_worker = worker->pool->last_idle_worker;
1399 if (worker->prev_idle_worker) worker->prev_idle_worker->next_idle_worker = worker;
1400 else worker->pool->first_idle_worker = worker;
1401 worker->pool->last_idle_worker = worker;
1402 worker->idle = 1;
1403 worker->pool->idle_worker_count++;
1404 if (worker->assigned) {
1405 worker->assigned = 0;
1406 worker->pool->unassigned_worker_count++;
1408 worker->pool->worker_count_stat = 1;
1409 if (timerisset(&worker->pool->idle_timeout)) {
1410 struct timeval now;
1411 moonbr_now(&now);
1412 timeradd(&now, &worker->pool->idle_timeout, &worker->idle_expiration);
1416 /* Pops a worker from the queue of idle workers (idle queue must not be empty) */
1417 static struct moonbr_worker *moonbr_pop_idle_worker(struct moonbr_pool *pool) {
1418 struct moonbr_worker *worker;
1419 worker = pool->first_idle_worker;
1420 pool->first_idle_worker = worker->next_idle_worker;
1421 if (pool->first_idle_worker) pool->first_idle_worker->prev_idle_worker = NULL;
1422 else pool->last_idle_worker = NULL;
1423 worker->next_idle_worker = NULL;
1424 worker->idle = 0;
1425 worker->pool->idle_worker_count--;
1426 worker->assigned = 1;
1427 worker->pool->unassigned_worker_count--;
1428 worker->pool->worker_count_stat = 1;
1429 return worker;
1433 /*** Functions for queues of 'struct moonbr_listener' ***/
1435 /* Appends a 'struct moonbr_listener' to the queue of idle listeners and registers it for poll() */
1436 static void moonbr_add_idle_listener(struct moonbr_listener *listener) {
1437 listener->prev_listener = listener->pool->last_idle_listener;
1438 if (listener->prev_listener) listener->prev_listener->next_listener = listener;
1439 else listener->pool->first_idle_listener = listener;
1440 listener->pool->last_idle_listener = listener;
1441 if (listener->pollidx != -1) moonbr_poll_fds[listener->pollidx].events |= POLLIN;
1444 /* Removes a 'struct moonbr_listener' from the queue of idle listeners and unregisters it from poll() */
1445 static void moonbr_remove_idle_listener(struct moonbr_listener *listener) {
1446 if (listener->prev_listener) listener->prev_listener->next_listener = listener->next_listener;
1447 else listener->pool->first_idle_listener = listener->next_listener;
1448 if (listener->next_listener) listener->next_listener->prev_listener = listener->prev_listener;
1449 else listener->pool->last_idle_listener = listener->prev_listener;
1450 listener->prev_listener = NULL;
1451 listener->next_listener = NULL;
1452 if (listener->pollidx != -1) moonbr_poll_fds[listener->pollidx].events &= ~POLLIN;
1455 /* Adds a listener to the queue of connected listeners (i.e. waiting to have their incoming connection accepted) */
1456 static void moonbr_add_connected_listener(struct moonbr_listener *listener) {
1457 listener->prev_listener = listener->pool->last_connected_listener;
1458 if (listener->prev_listener) listener->prev_listener->next_listener = listener;
1459 else listener->pool->first_connected_listener = listener;
1460 listener->pool->last_connected_listener = listener;
1463 /* Removes and returns the first connected listener in the queue */
1464 static struct moonbr_listener *moonbr_pop_connected_listener(struct moonbr_pool *pool) {
1465 struct moonbr_listener *listener = pool->first_connected_listener;
1466 listener->pool->first_connected_listener = listener->next_listener;
1467 if (listener->pool->first_connected_listener) listener->pool->first_connected_listener->prev_listener = NULL;
1468 else listener->pool->last_connected_listener = NULL;
1469 listener->next_listener = NULL;
1470 return listener;
1474 /*** Functions to handle polling ***/
1476 /* Returns an index to a new initialized entry in moonbr_poll_fds[] */
1477 int moonbr_poll_fds_nextindex() {
1478 if (moonbr_poll_fds_count >= moonbr_poll_fds_bufsize) {
1479 if (moonbr_poll_fds_bufsize) moonbr_poll_fds_bufsize *= 2;
1480 else moonbr_poll_fds_bufsize = 1;
1481 moonbr_poll_fds = realloc(
1482 moonbr_poll_fds, moonbr_poll_fds_bufsize * sizeof(struct pollfd)
1483 );
1484 if (!moonbr_poll_fds) {
1485 moonbr_log(LOG_CRIT, "Memory allocation error");
1486 moonbr_terminate_error();
1489 moonbr_poll_fds[moonbr_poll_fds_count] = (struct pollfd){0, };
1490 return moonbr_poll_fds_count++;
1493 /* Returns an index to a new initialized entry in moonbr_poll_workers[] */
1494 int moonbr_poll_workers_nextindex() {
1495 if (moonbr_poll_worker_count >= moonbr_poll_workers_bufsize) {
1496 if (moonbr_poll_workers_bufsize) moonbr_poll_workers_bufsize *= 2;
1497 else moonbr_poll_workers_bufsize = 1;
1498 moonbr_poll_workers = realloc(
1499 moonbr_poll_workers, moonbr_poll_workers_bufsize * sizeof(struct moonbr_poll_worker)
1500 );
1501 if (!moonbr_poll_workers) {
1502 moonbr_log(LOG_CRIT, "Memory allocation error");
1503 moonbr_terminate_error();
1506 moonbr_poll_workers[moonbr_poll_worker_count] = (struct moonbr_poll_worker){0, };
1507 return moonbr_poll_worker_count++;
1510 /* Queues all listeners as idle, and initializes static part of moonbr_poll_fds[], which is passed to poll() */
1511 static void moonbr_poll_init() {
1512 if (socketpair(
1513 PF_LOCAL,
1514 SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
1515 0,
1516 moonbr_poll_signalfds
1517 )) {
1518 moonbr_log(LOG_CRIT, "Could not create socket pair for signal delivery during polling: %s", strerror(errno));
1519 moonbr_terminate_error();
1522 int j = moonbr_poll_fds_nextindex();
1523 struct pollfd *pollfd = &moonbr_poll_fds[j];
1524 pollfd->fd = moonbr_poll_signalfd_read;
1525 pollfd->events = POLLIN;
1528 struct moonbr_pool *pool;
1529 for (pool=moonbr_first_pool; pool; pool=pool->next_pool) {
1530 int i;
1531 for (i=0; i<pool->listener_count; i++) {
1532 struct moonbr_listener *listener = &pool->listener[i];
1533 if (listener->listenfd != -1) {
1534 int j = moonbr_poll_fds_nextindex();
1535 listener->pollidx = j;
1536 moonbr_poll_fds[j].fd = listener->listenfd;
1538 moonbr_add_idle_listener(listener);
1542 moonbr_poll_fds_static_count = moonbr_poll_fds_count; /* remember size of static part of array */
1545 /* Disables polling of all listeners (required for clean shutdown) */
1546 static void moonbr_poll_shutdown() {
1547 int i;
1548 for (i=1; i<moonbr_poll_fds_static_count; i++) {
1549 moonbr_poll_fds[i].fd = -1;
1553 /* (Re)builds dynamic part of moonbr_poll_fds[] array, and (re)builds moonbr_poll_workers[] array */
1554 static void moonbr_poll_refresh() {
1555 moonbr_poll_refresh_needed = 0;
1556 moonbr_poll_fds_count = moonbr_poll_fds_static_count;
1557 moonbr_poll_worker_count = 0;
1559 struct moonbr_pool *pool;
1560 for (pool=moonbr_first_pool; pool; pool=pool->next_pool) {
1561 struct moonbr_worker *worker;
1562 for (worker=pool->first_worker; worker; worker=worker->next_worker) {
1563 if (worker->controlfd != -1) {
1564 int j = moonbr_poll_fds_nextindex();
1565 int k = moonbr_poll_workers_nextindex();
1566 struct pollfd *pollfd = &moonbr_poll_fds[j];
1567 struct moonbr_poll_worker *poll_worker = &moonbr_poll_workers[k];
1568 pollfd->fd = worker->controlfd;
1569 pollfd->events = POLLIN;
1570 poll_worker->channel = MOONBR_POLL_WORKER_CONTROLCHANNEL;
1571 poll_worker->worker = worker;
1573 if (worker->errorfd != -1) {
1574 int j = moonbr_poll_fds_nextindex();
1575 int k = moonbr_poll_workers_nextindex();
1576 struct pollfd *pollfd = &moonbr_poll_fds[j];
1577 struct moonbr_poll_worker *poll_worker = &moonbr_poll_workers[k];
1578 pollfd->fd = worker->errorfd;
1579 pollfd->events = POLLIN;
1580 poll_worker->channel = MOONBR_POLL_WORKER_ERRORCHANNEL;
1581 poll_worker->worker = worker;
1588 /* resets socket and 'revents' field of moonbr_poll_fds[] for signal delivery just before poll() is called */
1589 static void moonbr_poll_reset_signal() {
1590 ssize_t readcount;
1591 char buf[1];
1592 moonbr_poll_fds[0].revents = 0;
1593 while ((readcount = read(moonbr_poll_signalfd_read, buf, 1)) < 0) {
1594 if (errno == EAGAIN) break;
1595 if (errno != EINTR) {
1596 moonbr_log(LOG_CRIT, "Error while reading from signal delivery socket: %s", strerror(errno));
1597 moonbr_terminate_error();
1600 if (!readcount) {
1601 moonbr_log(LOG_CRIT, "Unexpected EOF when reading from signal delivery socket: %s", strerror(errno));
1602 moonbr_terminate_error();
1607 /*** Shutdown initiation ***/
1609 /* Sets global variable 'moonbr_shutdown_in_progress', closes listeners, and demands worker termination */
1610 static void moonbr_initiate_shutdown() {
1611 struct moonbr_pool *pool;
1612 int i;
1613 if (moonbr_shutdown_in_progress) {
1614 moonbr_log(LOG_NOTICE, "Shutdown already in progress");
1615 return;
1617 moonbr_shutdown_in_progress = 1;
1618 moonbr_log(LOG_NOTICE, "Initiate shutdown");
1619 for (pool = moonbr_first_pool; pool; pool = pool->next_pool) {
1620 for (i=0; i<pool->listener_count; i++) {
1621 struct moonbr_listener *listener = &pool->listener[i];
1622 if (listener->listenfd != -1) {
1623 if (close(listener->listenfd) && errno != EINTR) {
1624 moonbr_log(LOG_CRIT, "Could not close listening socket: %s", strerror(errno));
1625 moonbr_terminate_error();
1629 pool->pre_fork = 0;
1630 pool->min_fork = 0;
1631 pool->max_fork = 0;
1632 timerclear(&pool->exit_delay);
1634 moonbr_poll_shutdown(); /* avoids loops due to error condition when polling closed listeners */
1638 /*** Functions to communicate with child processes ***/
1640 /* Tells child process to terminate */
1641 static void moonbr_terminate_idle_worker(struct moonbr_worker *worker) {
1642 moonbr_send_control_message(worker, MOONBR_COMMAND_TERMINATE, -1, NULL);
1645 /* Handles status messages from child process */
1646 static void moonbr_read_controlchannel(struct moonbr_worker *worker) {
1647 char controlmsg;
1649 ssize_t bytes_read;
1650 while ((bytes_read = read(worker->controlfd, &controlmsg, 1)) <= 0) {
1651 if (bytes_read == 0 || errno == ECONNRESET) {
1652 moonbr_log(LOG_WARNING, "Child process in pool #%i with PID %i unexpectedly closed control socket", worker->pool->poolnum, (int)worker->pid);
1653 if (close(worker->controlfd) && errno != EINTR) {
1654 moonbr_log(LOG_CRIT, "Error while closing control socket to child process in pool #%i with PID %i: %s", worker->pool->poolnum, (int)worker->pid, strerror(errno));
1655 moonbr_terminate_error();
1657 worker->controlfd = -1;
1658 moonbr_poll_refresh_needed = 1;
1659 return;
1661 if (errno != EINTR) {
1662 moonbr_log(LOG_CRIT, "Unexpected error while reading control socket from child process in pool #%i with PID %i: %s", worker->pool->poolnum, (int)worker->pid, strerror(errno));
1663 moonbr_terminate_error();
1667 if (worker->idle) {
1668 moonbr_log(LOG_CRIT, "Unexpected data from supposedly idle child process in pool #%i with PID %i", worker->pool->poolnum, (int)worker->pid);
1669 moonbr_terminate_error();
1671 if (moonbr_debug) {
1672 moonbr_log(LOG_DEBUG, "Received control message from child in pool #%i with PID %i: \"%c\"", worker->pool->poolnum, (int)worker->pid, (int)controlmsg);
1674 switch (controlmsg) {
1675 case MOONBR_STATUS_IDLE:
1676 if (moonbr_stat) {
1677 moonbr_log(LOG_INFO, "Child process in pool #%i with PID %i reports as idle", worker->pool->poolnum, (int)worker->pid);
1679 moonbr_add_idle_worker(worker);
1680 break;
1681 case MOONBR_STATUS_GOODBYE:
1682 if (moonbr_stat) {
1683 moonbr_log(LOG_INFO, "Child process in pool #%i with PID %i announced termination", worker->pool->poolnum, (int)worker->pid);
1685 if (close(worker->controlfd) && errno != EINTR) {
1686 moonbr_log(LOG_CRIT, "Error while closing control socket to child process in pool #%i with PID %i: %s", worker->pool->poolnum, (int)worker->pid, strerror(errno));
1687 moonbr_terminate_error();
1689 worker->controlfd = -1;
1690 moonbr_poll_refresh_needed = 1;
1691 break;
1692 default:
1693 moonbr_log(LOG_CRIT, "Received illegal data (\"%c\") while reading control socket from child process in pool #%i with PID %i", (int)controlmsg, worker->pool->poolnum, (int)worker->pid);
1694 moonbr_terminate_error();
1698 /* Handles stderr stream from child process */
1699 static void moonbr_read_errorchannel(struct moonbr_worker *worker) {
1700 char staticbuf[MOONBR_MAXERRORLINELEN+1];
1701 char *buf = worker->errorlinebuf;
1702 if (!buf) buf = staticbuf;
1704 ssize_t bytes_read;
1705 while (
1706 (bytes_read = read(
1707 worker->errorfd,
1708 buf + worker->errorlinelen,
1709 MOONBR_MAXERRORLINELEN+1 - worker->errorlinelen
1710 )) <= 0
1711 ) {
1712 if (bytes_read == 0 || errno == ECONNRESET) {
1713 if (moonbr_debug) {
1714 moonbr_log(LOG_DEBUG, "Child process in pool #%i with PID %i closed stderr socket", worker->pool->poolnum, (int)worker->pid);
1716 if (close(worker->errorfd) && errno != EINTR) {
1717 moonbr_log(LOG_CRIT, "Error while closing stderr socket to child process in pool #%i with PID %i: %s", worker->pool->poolnum, (int)worker->pid, strerror(errno));
1718 moonbr_terminate_error();
1720 worker->errorfd = -1;
1721 moonbr_poll_refresh_needed = 1;
1722 break;
1724 if (errno != EINTR) {
1725 moonbr_log(LOG_CRIT, "Unexpected error while reading stderr from child process in pool #%i with PID %i: %s", worker->pool->poolnum, (int)worker->pid, strerror(errno));
1726 moonbr_terminate_error();
1729 worker->errorlinelen += bytes_read;
1732 int i;
1733 for (i=0; i<worker->errorlinelen; i++) {
1734 if (buf[i] == '\n') buf[i] = 0;
1735 if (!buf[i]) {
1736 if (worker->errorlineovf) {
1737 worker->errorlineovf = 0;
1738 } else {
1739 moonbr_log(LOG_WARNING, "Error log from process in pool #%i with PID %i: %s", worker->pool->poolnum, (int)worker->pid, buf);
1741 worker->errorlinelen -= i+1;
1742 memmove(buf, buf+i+1, worker->errorlinelen);
1743 i = -1;
1746 if (i > MOONBR_MAXERRORLINELEN) {
1747 buf[MOONBR_MAXERRORLINELEN] = 0;
1748 if (!worker->errorlineovf) {
1749 moonbr_log(LOG_WARNING, "Error log from process in pool #%i with PID %i (line has been truncated): %s", worker->pool->poolnum, (int)worker->pid, buf);
1751 worker->errorlinelen = 0;
1752 worker->errorlineovf = 1;
1755 if (!worker->errorlinebuf && worker->errorlinelen) { /* allocate buffer on heap only if necessary */
1756 worker->errorlinebuf = malloc((MOONBR_MAXERRORLINELEN+1) * sizeof(char));
1757 if (!worker->errorlinebuf) {
1758 moonbr_log(LOG_CRIT, "Memory allocation error");
1759 moonbr_terminate_error();
1761 memcpy(worker->errorlinebuf, staticbuf, worker->errorlinelen);
1766 /*** Handler for incoming connections ***/
1768 /* Accepts one or more incoming connections on listener socket and passes it to worker(s) popped from idle queue */
1769 static void moonbr_connect(struct moonbr_pool *pool) {
1770 struct moonbr_listener *listener = moonbr_pop_connected_listener(pool);
1771 struct moonbr_worker *worker;
1772 switch (listener->proto) {
1773 case MOONBR_PROTO_INTERVAL:
1774 worker = moonbr_pop_idle_worker(pool);
1775 if (moonbr_stat) {
1776 moonbr_log(LOG_INFO, "Dispatching interval timer \"%s\" of pool #%i to PID %i", listener->proto_specific.interval.name, listener->pool->poolnum, (int)worker->pid);
1778 worker->restart_interval_listener = listener;
1779 moonbr_send_control_message(worker, MOONBR_SOCKETTYPE_INTERVAL, -1, listener);
1780 /* do not push listener to queue of idle listeners yet */
1781 break;
1782 case MOONBR_PROTO_LOCAL:
1783 do {
1784 int peerfd;
1785 struct sockaddr_un peeraddr;
1786 socklen_t peeraddr_len = sizeof(struct sockaddr_un);
1787 peerfd = accept4(
1788 listener->listenfd,
1789 (struct sockaddr *)&peeraddr,
1790 &peeraddr_len,
1791 SOCK_CLOEXEC
1792 );
1793 if (peerfd == -1) {
1794 if (errno == EWOULDBLOCK) {
1795 break;
1796 } else if (errno == ECONNABORTED) {
1797 moonbr_log(LOG_WARNING, "Connection aborted before accepting it (proto=\"local\", path=\"%s\")", listener->proto_specific.local.path);
1798 break;
1799 } else if (errno != EINTR) {
1800 moonbr_log(LOG_ERR, "Could not accept socket connection: %s", strerror(errno));
1801 moonbr_terminate_error();
1803 } else {
1804 worker = moonbr_pop_idle_worker(pool);
1805 if (moonbr_stat) {
1806 moonbr_log(LOG_INFO, "Dispatching local socket connection on path \"%s\" for pool #%i to PID %i", listener->proto_specific.local.path, listener->pool->poolnum, (int)worker->pid);
1808 moonbr_send_control_message(worker, MOONBR_SOCKETTYPE_LOCAL, peerfd, listener);
1809 if (close(peerfd) && errno != EINTR) {
1810 moonbr_log(LOG_ERR, "Could not close incoming socket connection in parent process: %s", strerror(errno));
1811 moonbr_terminate_error();
1814 } while (pool->first_idle_worker);
1815 moonbr_add_idle_listener(listener);
1816 break;
1817 case MOONBR_PROTO_TCP6:
1818 do {
1819 int peerfd;
1820 struct sockaddr_in6 peeraddr;
1821 socklen_t peeraddr_len = sizeof(struct sockaddr_in6);
1822 peerfd = accept4(
1823 listener->listenfd,
1824 (struct sockaddr *)&peeraddr,
1825 &peeraddr_len,
1826 SOCK_CLOEXEC
1827 );
1828 if (peerfd == -1) {
1829 if (errno == EWOULDBLOCK) {
1830 break;
1831 } else if (errno == ECONNABORTED) {
1832 moonbr_log(LOG_WARNING, "Connection aborted before accepting it (proto=\"tcp6\", port=%i)", listener->proto_specific.tcp.port);
1833 break;
1834 } else if (errno != EINTR) {
1835 moonbr_log(LOG_ERR, "Could not accept socket connection: %s", strerror(errno));
1836 moonbr_terminate_error();
1838 } else {
1839 worker = moonbr_pop_idle_worker(pool);
1840 if (moonbr_stat) {
1841 moonbr_log(LOG_INFO, "Dispatching TCP/IPv6 connection for pool #%i on port %i to PID %i", listener->pool->poolnum, listener->proto_specific.tcp.port, (int)worker->pid);
1843 moonbr_send_control_message(worker, MOONBR_SOCKETTYPE_NETWORK, peerfd, listener);
1844 if (close(peerfd) && errno != EINTR) {
1845 moonbr_log(LOG_ERR, "Could not close incoming socket connection in parent process: %s", strerror(errno));
1846 moonbr_terminate_error();
1849 } while (pool->first_idle_worker);
1850 moonbr_add_idle_listener(listener);
1851 break;
1852 case MOONBR_PROTO_TCP4:
1853 do {
1854 int peerfd;
1855 struct sockaddr_in peeraddr;
1856 socklen_t peeraddr_len = sizeof(struct sockaddr_in);
1857 peerfd = accept4(
1858 listener->listenfd,
1859 (struct sockaddr *)&peeraddr,
1860 &peeraddr_len,
1861 SOCK_CLOEXEC
1862 );
1863 if (peerfd == -1) {
1864 if (errno == EWOULDBLOCK) {
1865 break;
1866 } else if (errno == ECONNABORTED) {
1867 moonbr_log(LOG_WARNING, "Connection aborted before accepting it (proto=\"tcp4\", port=%i)", listener->proto_specific.tcp.port);
1868 break;
1869 } else if (errno != EINTR) {
1870 moonbr_log(LOG_ERR, "Could not accept socket connection: %s", strerror(errno));
1871 moonbr_terminate_error();
1873 } else {
1874 worker = moonbr_pop_idle_worker(pool);
1875 if (moonbr_stat) {
1876 moonbr_log(LOG_INFO, "Dispatching TCP/IPv4 connection for pool #%i on port %i to PID %i", listener->pool->poolnum, listener->proto_specific.tcp.port, (int)worker->pid);
1878 moonbr_send_control_message(worker, MOONBR_SOCKETTYPE_NETWORK, peerfd, listener);
1879 if (close(peerfd) && errno != EINTR) {
1880 moonbr_log(LOG_ERR, "Could not close incoming socket connection in parent process: %s", strerror(errno));
1881 moonbr_terminate_error();
1884 } while (pool->first_idle_worker);
1885 moonbr_add_idle_listener(listener);
1886 break;
1887 default:
1888 moonbr_log(LOG_ERR, "Internal error (should not happen): Unexpected value in listener.proto field");
1889 moonbr_terminate_error();
1894 /*** Functions to initialize and restart interval timers ***/
1896 /* Initializes all interval timers */
1897 static void moonbr_interval_initialize() {
1898 struct timeval now;
1899 struct moonbr_pool *pool;
1900 moonbr_now(&now);
1901 for (pool=moonbr_first_pool; pool; pool=pool->next_pool) {
1902 int i;
1903 for (i=0; i<pool->listener_count; i++) {
1904 struct moonbr_listener *listener = &pool->listener[i];
1905 if (listener->proto == MOONBR_PROTO_INTERVAL) {
1906 timeradd(
1907 &now,
1908 &listener->proto_specific.interval.delay,
1909 &listener->proto_specific.interval.wakeup
1910 );
1916 /* If necessary, restarts interval timers and queues interval listener as idle after a worker changed status */
1917 static void moonbr_interval_restart(
1918 struct moonbr_worker *worker,
1919 struct timeval *now /* passed to synchronize with moonbr_run() function */
1920 ) {
1921 struct moonbr_listener *listener = worker->restart_interval_listener;
1922 if (listener) {
1923 moonbr_add_idle_listener(listener);
1924 worker->restart_interval_listener = NULL;
1925 if (listener->proto_specific.interval.strict) {
1926 timeradd(
1927 &listener->proto_specific.interval.wakeup,
1928 &listener->proto_specific.interval.delay,
1929 &listener->proto_specific.interval.wakeup
1930 );
1931 if (timercmp(&listener->proto_specific.interval.wakeup, now, <)) {
1932 listener->proto_specific.interval.wakeup = *now;
1934 } else {
1935 timeradd(
1936 now,
1937 &listener->proto_specific.interval.delay,
1938 &listener->proto_specific.interval.wakeup
1939 );
1945 /*** Main loop and helper functions ***/
1947 /* Stores the earliest required wakeup time in 'wait' variable */
1948 static void moonbr_calc_wait(struct timeval *wait, struct timeval *wakeup) {
1949 if (!timerisset(wait) || timercmp(wakeup, wait, <)) *wait = *wakeup;
1952 /* Main loop of Moonbridge system (including initialization of signal handlers and polling structures) */
1953 static void moonbr_run(lua_State *L) {
1954 struct timeval now;
1955 struct moonbr_pool *pool;
1956 struct moonbr_worker *worker;
1957 struct moonbr_worker *next_worker; /* needed when worker is removed during iteration of workers */
1958 struct moonbr_listener *listener;
1959 struct moonbr_listener *next_listener; /* needed when listener is removed during iteration of listeners */
1960 int i;
1961 moonbr_poll_init(); /* must be executed before moonbr_signal_init() */
1962 moonbr_signal_init();
1963 moonbr_interval_initialize();
1964 moonbr_pstate = MOONBR_PSTATE_RUNNING;
1965 while (1) {
1966 struct timeval wait = {0, }; /* point in time when premature wakeup of poll() is required */
1967 if (moonbr_cond_interrupt) {
1968 moonbr_log(LOG_WARNING, "Fast shutdown requested");
1969 moonbr_terminate(MOONBR_EXITCODE_GRACEFUL);
1971 if (moonbr_cond_terminate) {
1972 moonbr_initiate_shutdown();
1973 moonbr_cond_terminate = 0;
1975 moonbr_cond_child = 0; /* must not be reset between moonbr_try_destroy_worker() and poll() */
1976 moonbr_now(&now);
1977 for (pool=moonbr_first_pool; pool; pool=pool->next_pool) {
1978 int terminated_worker_count = 0; /* allows shortcut for new worker creation */
1979 /* terminate idle workers when expired */
1980 if (timerisset(&pool->idle_timeout)) {
1981 while ((worker = pool->first_idle_worker) != NULL) {
1982 if (timercmp(&worker->idle_expiration, &now, >)) break;
1983 moonbr_pop_idle_worker(pool);
1984 moonbr_terminate_idle_worker(worker);
1987 /* mark listeners as connected when incoming connection is pending */
1988 for (listener=pool->first_idle_listener; listener; listener=next_listener) {
1989 next_listener = listener->next_listener; /* extra variable necessary due to changing list */
1990 if (listener->pollidx != -1) {
1991 if (moonbr_poll_fds[listener->pollidx].revents) {
1992 moonbr_poll_fds[listener->pollidx].revents = 0;
1993 moonbr_remove_idle_listener(listener);
1994 moonbr_add_connected_listener(listener);
1996 } else if (listener->proto == MOONBR_PROTO_INTERVAL) {
1997 if (!timercmp(&listener->proto_specific.interval.wakeup, &now, >)) {
1998 moonbr_remove_idle_listener(listener);
1999 moonbr_add_connected_listener(listener);
2001 } else {
2002 moonbr_log(LOG_CRIT, "Internal error (should not happen): Listener is neither an interval timer nor has the 'pollidx' value set");
2003 moonbr_terminate_error();
2006 /* process input from child processes */
2007 for (i=0; i<moonbr_poll_worker_count; i++) {
2008 if (moonbr_poll_worker_fds[i].revents) {
2009 moonbr_poll_worker_fds[i].revents = 0;
2010 struct moonbr_poll_worker *poll_worker = &moonbr_poll_workers[i];
2011 switch (poll_worker->channel) {
2012 case MOONBR_POLL_WORKER_CONTROLCHANNEL:
2013 moonbr_read_controlchannel(poll_worker->worker);
2014 moonbr_interval_restart(poll_worker->worker, &now);
2015 break;
2016 case MOONBR_POLL_WORKER_ERRORCHANNEL:
2017 moonbr_read_errorchannel(poll_worker->worker);
2018 break;
2022 /* collect dead child processes */
2023 for (worker=pool->first_worker; worker; worker=next_worker) {
2024 next_worker = worker->next_worker; /* extra variable necessary due to changing list */
2025 switch (moonbr_try_destroy_worker(worker)) {
2026 case MOONBR_DESTROY_PREPARE:
2027 pool->use_fork_error_wakeup = 1;
2028 break;
2029 case MOONBR_DESTROY_IDLE_OR_ASSIGNED:
2030 terminated_worker_count++;
2031 break;
2034 /* connect listeners with idle workers */
2035 if (!moonbr_shutdown_in_progress) {
2036 while (pool->first_connected_listener && pool->first_idle_worker) {
2037 moonbr_connect(pool);
2040 /* create new worker processes */
2041 while (
2042 pool->total_worker_count < pool->max_fork && (
2043 pool->unassigned_worker_count < pool->pre_fork ||
2044 pool->total_worker_count < pool->min_fork
2046 ) {
2047 if (pool->use_fork_error_wakeup) {
2048 if (timercmp(&pool->fork_error_wakeup, &now, >)) {
2049 moonbr_calc_wait(&wait, &pool->fork_error_wakeup);
2050 break;
2052 } else {
2053 if (terminated_worker_count) {
2054 terminated_worker_count--;
2055 } else if (timercmp(&pool->fork_wakeup, &now, >)) {
2056 moonbr_calc_wait(&wait, &pool->fork_wakeup);
2057 break;
2060 if (moonbr_create_worker(pool, L)) {
2061 /* on error, enforce error delay */
2062 timeradd(&now, &pool->fork_error_delay, &pool->fork_error_wakeup);
2063 pool->use_fork_error_wakeup = 1;
2064 moonbr_calc_wait(&wait, &pool->fork_error_wakeup);
2065 break;
2066 } else {
2067 /* normal fork delay on success */
2068 timeradd(&now, &pool->fork_delay, &pool->fork_wakeup);
2069 timeradd(&now, &pool->fork_error_delay, &pool->fork_error_wakeup);
2070 pool->use_fork_error_wakeup = 0; /* gets set later if error occures during preparation */
2073 /* terminate excessive worker processes */
2074 while (
2075 pool->total_worker_count > pool->min_fork &&
2076 pool->idle_worker_count > pool->pre_fork
2077 ) {
2078 if (timerisset(&pool->exit_wakeup)) {
2079 if (timercmp(&pool->exit_wakeup, &now, >)) {
2080 moonbr_calc_wait(&wait, &pool->exit_wakeup);
2081 break;
2083 moonbr_terminate_idle_worker(moonbr_pop_idle_worker(pool));
2084 timeradd(&now, &pool->exit_delay, &pool->exit_wakeup);
2085 } else {
2086 timeradd(&now, &pool->exit_delay, &pool->exit_wakeup);
2087 break;
2090 if (!(
2091 pool->total_worker_count > pool->min_fork &&
2092 pool->idle_worker_count > pool->pre_fork
2093 )) {
2094 timerclear(&pool->exit_wakeup); /* timer gets restarted later when there are excessive workers */
2096 /* optionally output worker count stats */
2097 if (moonbr_stat && pool->worker_count_stat) {
2098 pool->worker_count_stat = 0;
2099 moonbr_log(
2100 LOG_INFO,
2101 "Worker count for pool #%i: %i idle, %i assigned, %i total",
2102 pool->poolnum, pool->idle_worker_count,
2103 pool->total_worker_count - pool->unassigned_worker_count,
2104 pool->total_worker_count);
2106 /* calculate wakeup time for interval listeners */
2107 for (listener=pool->first_idle_listener; listener; listener=listener->next_listener) {
2108 if (listener->proto == MOONBR_PROTO_INTERVAL) {
2109 moonbr_calc_wait(&wait, &listener->proto_specific.interval.wakeup);
2112 /* calculate wakeup time for idle workers (only first idle worker is significant) */
2113 if (timerisset(&pool->idle_timeout) && pool->first_idle_worker) {
2114 moonbr_calc_wait(&wait, &pool->first_idle_worker->idle_expiration);
2117 /* check if shutdown is complete */
2118 if (moonbr_shutdown_in_progress) {
2119 for (pool=moonbr_first_pool; pool; pool=pool->next_pool) {
2120 if (pool->first_worker) break;
2122 if (!pool) {
2123 moonbr_log(LOG_INFO, "All worker threads have terminated");
2124 moonbr_terminate(MOONBR_EXITCODE_GRACEFUL);
2127 if (moonbr_poll_refresh_needed) moonbr_poll_refresh();
2128 moonbr_cond_poll = 1;
2129 if (!moonbr_cond_child && !moonbr_cond_terminate && !moonbr_cond_interrupt) {
2130 int timeout;
2131 if (timerisset(&wait)) {
2132 if (timercmp(&wait, &now, <)) {
2133 moonbr_log(LOG_CRIT, "Internal error (should not happen): Future is in the past");
2134 moonbr_terminate_error();
2136 timersub(&wait, &now, &wait);
2137 timeout = wait.tv_sec * 1000 + wait.tv_usec / 1000;
2138 } else {
2139 timeout = INFTIM;
2141 if (moonbr_debug) {
2142 moonbr_log(LOG_DEBUG, "Waiting for I/O");
2144 poll(moonbr_poll_fds, moonbr_poll_fds_count, timeout);
2145 } else {
2146 if (moonbr_debug) {
2147 moonbr_log(LOG_DEBUG, "Do not wait for I/O");
2150 moonbr_cond_poll = 0;
2151 moonbr_poll_reset_signal();
2156 /*** Lua interface ***/
2158 static int moonbr_lua_panic(lua_State *L) {
2159 const char *errmsg;
2160 errmsg = lua_tostring(L, -1);
2161 if (!errmsg) {
2162 if (lua_isnoneornil(L, -1)) errmsg = "(error message is nil)";
2163 else errmsg = "(error message is not a string)";
2165 if (moonbr_pstate == MOONBR_PSTATE_FORKED) {
2166 fprintf(stderr, "Uncaught Lua error: %s\n", errmsg);
2167 exit(1);
2168 } else {
2169 moonbr_log(LOG_CRIT, "Uncaught Lua error: %s", errmsg);
2170 moonbr_terminate_error();
2172 return 0;
2175 static int moonbr_addtraceback(lua_State *L) {
2176 luaL_traceback(L, L, luaL_tolstring(L, 1, NULL), 1);
2177 return 1;
2180 /* Memory allocator that allows limiting memory consumption */
2181 static void *moonbr_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
2182 (void)ud; /* not used */
2183 if (nsize == 0) {
2184 if (ptr) {
2185 moonbr_memory_usage -= osize;
2186 free(ptr);
2188 return NULL;
2189 } else if (ptr) {
2190 if (
2191 moonbr_memory_limit &&
2192 nsize > osize &&
2193 moonbr_memory_usage + (nsize - osize) > moonbr_memory_limit
2194 ) {
2195 return NULL;
2196 } else {
2197 ptr = realloc(ptr, nsize);
2198 if (ptr) moonbr_memory_usage += nsize - osize;
2200 } else {
2201 if (
2202 moonbr_memory_limit &&
2203 moonbr_memory_usage + nsize > moonbr_memory_limit
2204 ) {
2205 return NULL;
2206 } else {
2207 ptr = realloc(ptr, nsize);
2208 if (ptr) moonbr_memory_usage += nsize;
2211 return ptr;
2214 /* New method for Lua file objects: read until terminator or length exceeded */
2215 static int moonbr_readuntil(lua_State *L) {
2216 luaL_Stream *stream;
2217 FILE *file;
2218 const char *terminatorstr;
2219 size_t terminatorlen;
2220 luaL_Buffer buf;
2221 lua_Integer maxlen;
2222 char terminator;
2223 int byte;
2224 stream = luaL_checkudata(L, 1, LUA_FILEHANDLE);
2225 terminatorstr = luaL_checklstring(L, 2, &terminatorlen);
2226 luaL_argcheck(L, terminatorlen == 1, 2, "single byte expected");
2227 maxlen = luaL_optinteger(L, 3, 0);
2228 if (!stream->closef) luaL_error(L, "attempt to use a closed file");
2229 file = stream->f;
2230 luaL_buffinit(L, &buf);
2231 if (!maxlen) maxlen = -1;
2232 terminator = terminatorstr[0];
2233 while (maxlen > 0 ? maxlen-- : maxlen) {
2234 byte = fgetc(file);
2235 if (byte == EOF) {
2236 if (ferror(file)) {
2237 char errmsg[MOONBR_MAXSTRERRORLEN];
2238 strerror_r(errno, errmsg, MOONBR_MAXSTRERRORLEN); /* use thread-safe call in case child created threads */
2239 luaL_error(L, "%s", errmsg);
2240 } else {
2241 break;
2244 luaL_addchar(&buf, byte);
2245 if (byte == terminator) break;
2247 luaL_pushresult(&buf);
2248 if (!lua_rawlen(L, -1)) lua_pushnil(L);
2249 return 1;
2252 static int moonbr_lua_tonatural(lua_State *L, int idx) {
2253 int isnum;
2254 lua_Number n;
2255 n = lua_tonumberx(L, idx, &isnum);
2256 if (isnum && n>=0 && n<INT_MAX && (lua_Number)(int)n == n) return n;
2257 else return -1;
2260 static int moonbr_lua_totimeval(lua_State *L, int idx, struct timeval *value) {
2261 int isnum;
2262 lua_Number n;
2263 n = lua_tonumberx(L, idx, &isnum);
2264 if (isnum && n>=0 && n<=100000000) {
2265 value->tv_sec = n;
2266 value->tv_usec = 1e6 * (n - value->tv_sec);
2267 return 1;
2268 } else {
2269 return 0;
2273 static int moonbr_timeout(lua_State *L) {
2274 struct itimerval oldval;
2275 if (lua_isnoneornil(L, 1) && lua_isnoneornil(L, 2)) {
2276 getitimer(ITIMER_REAL, &oldval);
2277 } else {
2278 struct itimerval newval = {};
2279 if (lua_toboolean(L, 1)) {
2280 luaL_argcheck(
2281 L, moonbr_lua_totimeval(L, 1, &newval.it_value), 1,
2282 "interval in seconds expected"
2283 );
2285 if (lua_isnoneornil(L, 2)) {
2286 if (setitimer(ITIMER_REAL, &newval, &oldval)) {
2287 moonbr_log(LOG_CRIT, "Could not set ITIMER_REAL via setitimer()");
2288 moonbr_terminate_error();
2290 } else {
2291 getitimer(ITIMER_REAL, &oldval);
2292 if (timercmp(&newval.it_value, &oldval.it_value, <)) {
2293 struct itimerval remval;
2294 if (setitimer(ITIMER_REAL, &newval, NULL)) {
2295 moonbr_log(LOG_CRIT, "Could not set ITIMER_REAL via setitimer()");
2296 moonbr_terminate_error();
2298 lua_call(L, lua_gettop(L) - 2, LUA_MULTRET);
2299 getitimer(ITIMER_REAL, &remval);
2300 timersub(&oldval.it_value, &newval.it_value, &newval.it_value);
2301 timeradd(&newval.it_value, &remval.it_value, &newval.it_value);
2302 if (setitimer(ITIMER_REAL, &newval, NULL)) {
2303 moonbr_log(LOG_CRIT, "Could not set ITIMER_REAL via setitimer()");
2304 moonbr_terminate_error();
2306 } else {
2307 lua_call(L, lua_gettop(L) - 2, LUA_MULTRET);
2309 return lua_gettop(L) - 1;
2312 lua_pushnumber(L, oldval.it_value.tv_sec + 1e-6 * oldval.it_value.tv_usec);
2313 return 1;
2316 #define moonbr_listen_init_pool_forkoption(luaname, cname, defval) { \
2317 lua_getfield(L, 2, luaname); \
2318 pool->cname = lua_isnil(L, -1) ? (defval) : moonbr_lua_tonatural(L, -1); \
2319 } while(0)
2321 #define moonbr_listen_init_pool_timeoption(luaname, cname, defval, defvalu) ( \
2322 lua_getfield(L, 2, luaname), \
2323 lua_isnil(L, -1) ? ( \
2324 pool->cname.tv_sec = (defval), pool->cname.tv_usec = (defvalu), \
2325 1 \
2326 ) : ( \
2327 (lua_isboolean(L, -1) && !lua_toboolean(L, -1)) ? ( \
2328 pool->cname.tv_sec = 0, pool->cname.tv_usec = 0, \
2329 1 \
2330 ) : ( \
2331 moonbr_lua_totimeval(L, -1, &pool->cname) \
2332 ) \
2333 ) \
2336 static int moonbr_listen_init_pool(lua_State *L) {
2337 struct moonbr_pool *pool;
2338 const char *proto;
2339 int i;
2340 pool = lua_touserdata(L, 1);
2341 for (i=0; i<pool->listener_count; i++) {
2342 struct moonbr_listener *listener = &pool->listener[i];
2343 lua_settop(L, 2);
2344 #if LUA_VERSION_NUM >= 503
2345 lua_geti(L, 2, i+1);
2346 #else
2347 lua_pushinteger(L, i+1);
2348 lua_gettable(L, 2);
2349 #endif
2350 lua_getfield(L, 3, "proto");
2351 proto = lua_tostring(L, -1);
2352 if (proto && !strcmp(proto, "interval")) {
2353 listener->proto = MOONBR_PROTO_INTERVAL;
2354 lua_getfield(L, 3, "name");
2356 const char *name = lua_tostring(L, -1);
2357 if (name) {
2358 if (asprintf(&listener->proto_specific.interval.name, "%s", name) < 0) {
2359 moonbr_log(LOG_CRIT, "Memory allocation_error");
2360 moonbr_terminate_error();
2364 lua_getfield(L, 3, "delay");
2365 if (
2366 !moonbr_lua_totimeval(L, -1, &listener->proto_specific.interval.delay) ||
2367 !timerisset(&listener->proto_specific.interval.delay)
2368 ) {
2369 luaL_error(L, "No valid interval delay specified; use listen{{proto=\"interval\", delay=...}, ...}");
2371 lua_getfield(L, 3, "strict");
2372 if (!lua_isnil(L, -1)) {
2373 if (lua_isboolean(L, -1)) {
2374 if (lua_toboolean(L, -1)) listener->proto_specific.interval.strict = 1;
2375 } else {
2376 luaL_error(L, "Option \"strict\" must be a boolean if set; use listen{{proto=\"interval\", strict=true, ...}, ...}");
2379 } else if (proto && !strcmp(proto, "local")) {
2380 listener->proto = MOONBR_PROTO_LOCAL;
2381 lua_getfield(L, 3, "path");
2383 const char *path = lua_tostring(L, -1);
2384 if (!path) {
2385 luaL_error(L, "No valid path specified for local socket; use listen{{proto=\"local\", path=...}, ...}");
2387 if (asprintf(&listener->proto_specific.local.path, "%s", path) < 0) {
2388 moonbr_log(LOG_CRIT, "Memory allocation_error");
2389 moonbr_terminate_error();
2392 } else if (proto && !strcmp(proto, "tcp6")) {
2393 listener->proto = MOONBR_PROTO_TCP6;
2394 lua_getfield(L, 3, "port");
2395 listener->proto_specific.tcp.port = lua_tointeger(L, -1);
2396 if (
2397 listener->proto_specific.tcp.port < 1 ||
2398 listener->proto_specific.tcp.port > 65535
2399 ) {
2400 luaL_error(L, "No valid port number specified; use listen{{proto=\"tcp6\", port=...}, ...}");
2402 lua_getfield(L, 3, "localhost");
2403 if (!lua_isnil(L, -1)) {
2404 if (lua_isboolean(L, -1)) {
2405 if (lua_toboolean(L, -1)) listener->proto_specific.tcp.localhost_only = 1;
2406 } else {
2407 luaL_error(L, "Option \"localhost\" must be a boolean if set; use listen{{proto=\"tcp6\", localhost=true, ...}, ...}");
2410 } else if (proto && !strcmp(proto, "tcp4")) {
2411 listener->proto = MOONBR_PROTO_TCP4;
2412 lua_getfield(L, 3, "port");
2413 listener->proto_specific.tcp.port = lua_tointeger(L, -1);
2414 if (
2415 listener->proto_specific.tcp.port < 1 ||
2416 listener->proto_specific.tcp.port > 65535
2417 ) {
2418 luaL_error(L, "No valid port number specified; use listen{{proto=\"tcp4\", port=...}, ...}");
2420 lua_getfield(L, 3, "localhost");
2421 if (!lua_isnil(L, -1)) {
2422 if (lua_isboolean(L, -1)) {
2423 if (lua_toboolean(L, -1)) listener->proto_specific.tcp.localhost_only = 1;
2424 } else {
2425 luaL_error(L, "Option \"localhost\" must be a boolean if set; use listen{{proto=\"tcp4\", localhost=true, ...}, ...}");
2430 lua_settop(L, 2);
2431 moonbr_listen_init_pool_forkoption("pre_fork", pre_fork, 1);
2432 moonbr_listen_init_pool_forkoption("min_fork", min_fork, pool->pre_fork > 2 ? pool->pre_fork : 2);
2433 moonbr_listen_init_pool_forkoption("max_fork", max_fork, pool->min_fork > 16 ? pool->min_fork : 16);
2434 if (!moonbr_listen_init_pool_timeoption("fork_delay", fork_delay, 1, 0)) {
2435 luaL_error(L, "Option \"fork_delay\" is expected to be a non-negative number");
2437 if (!moonbr_listen_init_pool_timeoption("fork_error_delay", fork_error_delay, 2, 0)) {
2438 luaL_error(L, "Option \"fork_error_delay\" is expected to be a non-negative number");
2440 if (!moonbr_listen_init_pool_timeoption("exit_delay", exit_delay, 60, 0)) {
2441 luaL_error(L, "Option \"exit_delay\" is expected to be a non-negative number");
2443 if (timercmp(&pool->fork_error_delay, &pool->fork_delay, <)) {
2444 pool->fork_error_delay = pool->fork_delay;
2446 if (!moonbr_listen_init_pool_timeoption("idle_timeout", idle_timeout, 0, 0)) {
2447 luaL_error(L, "Option \"idle_timeout\" is expected to be a non-negative number");
2449 lua_getfield(L, 2, "memory_limit");
2450 if (!lua_isnil(L, -1)) {
2451 int isnum;
2452 lua_Number n;
2453 n = lua_tonumberx(L, -1, &isnum);
2454 if (n < 0 || !isnum) {
2455 luaL_error(L, "Option \"memory_limit\" is expected to be a non-negative number");
2457 pool->memory_limit = n;
2459 lua_settop(L, 2);
2460 lua_getfield(L, 2, "prepare");
2461 if (!lua_isnil(L, -1) && !lua_isfunction(L, -1)) {
2462 luaL_error(L, "Option \"prepare\" must be nil or a function");
2464 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_prepare_func(pool));
2465 lua_getfield(L, 2, "connect");
2466 if (!lua_isfunction(L, -1)) {
2467 luaL_error(L, "Option \"connect\" must be a function; use listen{{...}, {...}, connect=function(socket) ... end, ...}");
2469 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_connect_func(pool));
2470 lua_getfield(L, 2, "finish");
2471 if (!lua_isnil(L, -1) && !lua_isfunction(L, -1)) {
2472 luaL_error(L, "Option \"finish\" must be nil or a function");
2474 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_finish_func(pool));
2475 return 0;
2478 static int moonbr_listen(lua_State *L) {
2479 struct moonbr_pool *pool;
2480 lua_Integer listener_count;
2481 if (moonbr_booted) luaL_error(L, "Moonbridge bootup is already complete");
2482 luaL_checktype(L, 1, LUA_TTABLE);
2483 listener_count = luaL_len(L, 1);
2484 if (!listener_count) luaL_error(L, "No listen ports specified; use listen{{proto=..., port=...},...}");
2485 if (listener_count > 100) luaL_error(L, "Too many listeners");
2486 pool = moonbr_create_pool(listener_count);
2487 lua_pushcfunction(L, moonbr_listen_init_pool);
2488 lua_pushlightuserdata(L, pool);
2489 lua_pushvalue(L, 1);
2490 if (lua_pcall(L, 2, 0, 0)) goto moonbr_listen_error;
2492 int i;
2493 i = moonbr_start_pool(pool);
2494 if (i >= 0) {
2495 struct moonbr_listener *listener = &pool->listener[i];
2496 switch (listener->proto) {
2497 case MOONBR_PROTO_INTERVAL:
2498 lua_pushfstring(L, "Could not initialize listener #%d (proto=\"interval\"): %s", i+1, strerror(errno));
2499 break;
2500 case MOONBR_PROTO_LOCAL:
2501 lua_pushfstring(L, "Could not initialize listener #%d (proto=\"local\", path=\"%s\"): %s", i+1, listener->proto_specific.local.path, strerror(errno));
2502 break;
2503 case MOONBR_PROTO_TCP6:
2504 lua_pushfstring(L, "Could not initialize listener #%d (proto=\"tcp6\", port=%d): %s", i+1, listener->proto_specific.tcp.port, strerror(errno));
2505 break;
2506 case MOONBR_PROTO_TCP4:
2507 lua_pushfstring(L, "Could not initialize listener #%d (proto=\"tcp4\", port=%d): %s", i+1, listener->proto_specific.tcp.port, strerror(errno));
2508 break;
2509 default:
2510 moonbr_log(LOG_ERR, "Internal error (should not happen): Unexpected value in listener.proto field");
2511 moonbr_terminate_error();
2513 goto moonbr_listen_error;
2516 return 0;
2517 moonbr_listen_error:
2518 moonbr_destroy_pool(pool);
2519 lua_pushnil(L);
2520 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_prepare_func(pool));
2521 lua_pushnil(L);
2522 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_connect_func(pool));
2523 lua_pushnil(L);
2524 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_finish_func(pool));
2525 lua_error(L);
2526 return 0; /* avoid compiler warning */
2530 /*** Function to modify Lua's library path and/or cpath ***/
2532 #if defined(MOONBR_LUA_PATH) || defined(MOONBR_LUA_CPATH)
2533 static void moonbr_modify_path(lua_State *L, char *key, char *value) {
2534 int stackbase;
2535 stackbase = lua_gettop(L);
2536 lua_getglobal(L, "package");
2537 lua_getfield(L, stackbase+1, key);
2539 const char *current_str;
2540 size_t current_strlen;
2541 luaL_Buffer buf;
2542 current_str = lua_tolstring(L, stackbase+2, &current_strlen);
2543 luaL_buffinit(L, &buf);
2544 if (current_str) {
2545 lua_pushvalue(L, stackbase+2);
2546 luaL_addvalue(&buf);
2547 if (current_strlen && current_str[current_strlen-1] != ';') {
2548 luaL_addchar(&buf, ';');
2551 luaL_addstring(&buf, value);
2552 luaL_pushresult(&buf);
2554 lua_setfield(L, stackbase+1, key);
2555 lua_settop(L, stackbase);
2557 #endif
2560 /*** Main function and command line invokation ***/
2562 static void moonbr_usage(int err, const char *cmd) {
2563 FILE *out;
2564 out = err ? stderr : stdout;
2565 if (!cmd) cmd = "moonbridge";
2566 fprintf(out, "Get this help message: %s {-h|--help}\n", cmd);
2567 fprintf(out, "Usage: %s \\\n", cmd);
2568 fprintf(out, " [-b|--background] \\\n");
2569 fprintf(out, " [-d|--debug] \\\n");
2570 fprintf(out, " [-f|--logfacility {DAEMON|USER|0|1|...|7}] \\\n");
2571 fprintf(out, " [-i|--logident <syslog ident> \\\n");
2572 fprintf(out, " [-l|--logfile <logfile>] \\\n");
2573 fprintf(out, " [-p|--pidfile <pidfile>] \\\n");
2574 fprintf(out, " [-s|--stats] \\\n");
2575 fprintf(out, " -- <Lua script> [<cmdline options for Lua script>]\n");
2576 exit(err);
2579 #define moonbr_usage_error() moonbr_usage(MOONBR_EXITCODE_CMDLINEERROR, argc ? argv[0] : NULL)
2581 int main(int argc, char **argv) {
2583 int daemonize = 0;
2584 int log_facility = LOG_USER;
2585 const char *log_ident = "moonbridge";
2586 const char *log_filename = NULL;
2587 const char *pid_filename = NULL;
2588 int option;
2589 struct option longopts[] = {
2590 { "background", no_argument, NULL, 'b' },
2591 { "debug", no_argument, NULL, 'd' },
2592 { "logfacility", required_argument, NULL, 'f' },
2593 { "help", no_argument, NULL, 'h' },
2594 { "logident", required_argument, NULL, 'i' },
2595 { "logfile", required_argument, NULL, 'l' },
2596 { "pidfile", required_argument, NULL, 'p' },
2597 { "stats", no_argument, NULL, 's' }
2598 };
2599 while ((option = getopt_long(argc, argv, "bdf:hi:l:p:s", longopts, NULL)) != -1) {
2600 switch (option) {
2601 case 'b':
2602 daemonize = 1;
2603 break;
2604 case 'd':
2605 moonbr_debug = 1;
2606 moonbr_stat = 1;
2607 break;
2608 case 'f':
2609 if (!strcmp(optarg, "DAEMON")) {
2610 log_facility = LOG_DAEMON;
2611 } else if (!strcmp(optarg, "USER")) {
2612 log_facility = LOG_USER;
2613 } else if (!strcmp(optarg, "0")) {
2614 log_facility = LOG_LOCAL0;
2615 } else if (!strcmp(optarg, "1")) {
2616 log_facility = LOG_LOCAL1;
2617 } else if (!strcmp(optarg, "2")) {
2618 log_facility = LOG_LOCAL2;
2619 } else if (!strcmp(optarg, "3")) {
2620 log_facility = LOG_LOCAL3;
2621 } else if (!strcmp(optarg, "4")) {
2622 log_facility = LOG_LOCAL4;
2623 } else if (!strcmp(optarg, "5")) {
2624 log_facility = LOG_LOCAL5;
2625 } else if (!strcmp(optarg, "6")) {
2626 log_facility = LOG_LOCAL6;
2627 } else if (!strcmp(optarg, "7")) {
2628 log_facility = LOG_LOCAL7;
2629 } else {
2630 moonbr_usage_error();
2632 moonbr_use_syslog = 1;
2633 break;
2634 case 'h':
2635 moonbr_usage(MOONBR_EXITCODE_GRACEFUL, argv[0]);
2636 break;
2637 case 'i':
2638 log_ident = optarg;
2639 moonbr_use_syslog = 1;
2640 break;
2641 case 'l':
2642 log_filename = optarg;
2643 break;
2644 case 'p':
2645 pid_filename = optarg;
2646 break;
2647 case 's':
2648 moonbr_stat = 1;
2649 break;
2650 default:
2651 moonbr_usage_error();
2654 if (argc - optind < 1) moonbr_usage_error();
2655 if (pid_filename) {
2656 pid_t otherpid;
2657 while ((moonbr_pidfh = pidfile_open(pid_filename, 0644, &otherpid)) == NULL) {
2658 if (errno == EEXIST) {
2659 if (otherpid == -1) {
2660 fprintf(stderr, "PID file \"%s\" is already locked\n", pid_filename);
2661 } else {
2662 fprintf(stderr, "PID file \"%s\" is already locked by process with PID: %i\n", pid_filename, (int)otherpid);
2664 exit(MOONBR_EXITCODE_ALREADYRUNNING);
2665 } else if (errno != EINTR) {
2666 fprintf(stderr, "Could not write PID file \"%s\": %s\n", pid_filename, strerror(errno));
2667 exit(MOONBR_EXITCODE_STARTUPERROR);
2671 if (log_filename) {
2672 int logfd;
2673 while (
2674 ( logfd = flopen(
2675 log_filename,
2676 O_WRONLY|O_NONBLOCK|O_CREAT|O_APPEND|O_CLOEXEC,
2677 0640
2679 ) < 0
2680 ) {
2681 if (errno == EWOULDBLOCK) {
2682 fprintf(stderr, "Logfile \"%s\" is locked\n", log_filename);
2683 exit(MOONBR_EXITCODE_ALREADYRUNNING);
2684 } else if (errno != EINTR) {
2685 fprintf(stderr, "Could not open logfile \"%s\": %s\n", log_filename, strerror(errno));
2686 exit(MOONBR_EXITCODE_STARTUPERROR);
2689 moonbr_logfile = fdopen(logfd, "a");
2690 if (!moonbr_logfile) {
2691 fprintf(stderr, "Could not open write stream to logfile \"%s\": %s\n", log_filename, strerror(errno));
2692 exit(MOONBR_EXITCODE_STARTUPERROR);
2695 if (daemonize == 0 && !moonbr_logfile) moonbr_logfile = stderr;
2696 if (moonbr_logfile) setlinebuf(moonbr_logfile);
2697 else moonbr_use_syslog = 1;
2698 if (moonbr_use_syslog) openlog(log_ident, LOG_NDELAY | LOG_PID, log_facility);
2699 if (daemonize) {
2700 if (daemon(1, 0)) {
2701 moonbr_log(LOG_ERR, "Could not daemonize moonbridge process");
2702 moonbr_terminate_error();
2706 moonbr_log(LOG_NOTICE, "Starting moonbridge server");
2707 if (moonbr_pidfh && pidfile_write(moonbr_pidfh)) {
2708 moonbr_log(LOG_ERR, "Could not write pidfile (after locking)");
2711 lua_State *L;
2712 L = lua_newstate(moonbr_alloc, NULL);
2713 if (!L) {
2714 moonbr_log(LOG_CRIT, "Could not initialize Lua state");
2715 moonbr_terminate_error();
2717 lua_atpanic(L, moonbr_lua_panic);
2718 luaL_openlibs(L);
2719 #ifdef MOONBR_LUA_PATH
2720 moonbr_modify_path(L, "path", MOONBR_LUA_PATH);
2721 #endif
2722 #ifdef MOONBR_LUA_CPATH
2723 moonbr_modify_path(L, "cpath", MOONBR_LUA_CPATH);
2724 #endif
2725 if (luaL_newmetatable(L, LUA_FILEHANDLE)) {
2726 moonbr_log(LOG_CRIT, "Lua metatable LUA_FILEHANDLE does not exist");
2727 moonbr_terminate_error();
2729 lua_getfield(L, -1, "__index");
2730 lua_pushcfunction(L, moonbr_readuntil);
2731 lua_setfield(L, -2, "readuntil");
2732 lua_pop(L, 2);
2733 lua_pushcfunction(L, moonbr_timeout);
2734 lua_setglobal(L, "timeout");
2735 lua_pushcfunction(L, moonbr_listen);
2736 lua_setglobal(L, "listen");
2737 lua_pushcfunction(L, moonbr_addtraceback); /* on stack position 1 */
2738 moonbr_log(LOG_INFO, "Loading \"%s\"", argv[optind]);
2739 if (luaL_loadfile(L, argv[optind])) {
2740 moonbr_log(LOG_ERR, "Error while loading \"%s\": %s", argv[optind], lua_tostring(L, -1));
2741 moonbr_terminate_error();
2743 { int i; for (i=optind+1; i<argc; i++) lua_pushstring(L, argv[i]); }
2744 if (lua_pcall(L, argc-(optind+1), 0, 1)) {
2745 moonbr_log(LOG_ERR, "Error while executing \"%s\": %s", argv[optind], lua_tostring(L, -1));
2746 moonbr_terminate_error();
2748 if (!moonbr_first_pool) {
2749 moonbr_log(LOG_WARNING, "No listener initialized.");
2750 moonbr_terminate_error();
2752 lua_getglobal(L, "listen");
2753 lua_pushcfunction(L, moonbr_listen);
2754 if (lua_compare(L, -2, -1, LUA_OPEQ)) {
2755 lua_pushnil(L);
2756 lua_setglobal(L, "listen");
2758 lua_settop(L, 1);
2759 moonbr_run(L);
2761 return 0;

Impressum / About Us