moonbridge

view moonbridge.c @ 37:c89d8d442987

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

Impressum / About Us