moonbridge

view moonbridge.c @ 40:46e45cd8548e

Disabling SHUT_RD due to problems with Linux
author jbe
date Sun Mar 08 00:08:22 2015 +0100 (2015-03-08)
parents 5e73b75bd2dc
children b6619de6f494
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 /* NOTE: shutdown() with SHUT_RD shows different behavior on different
826 * operating systems and particularly causes problems with Linux. Hence it
827 * is disabled here. */
828 /*
829 if (cleanshut && moonbr_child_peersocket_type == MOONBR_SOCKETTYPE_NETWORK) {
830 if (shutdown(moonbr_child_peersocket_fd, SHUT_RD)) {
831 errno2 = errno;
832 err = -1;
833 }
834 }
835 */
836 if (fclose(moonbr_child_peersocket_inputstream->f)) {
837 if (!err) errno2 = errno;
838 err = -1;
839 }
840 moonbr_child_peersocket_inputstream->f = NULL;
841 }
842 if (mark) moonbr_child_peersocket_inputstream->closef = NULL;
843 if (err) errno = errno2;
844 return err;
845 }
847 /* Closes the output stream to peer unless it has already been closed */
848 static int moonbr_child_close_peersocket_outputstream(
849 int cleanshut, /* nonzero = use fflush() and shutdown() if applicable */
850 int mark /* nonzero = mark the stream as closed for Lua */
851 ) {
852 int err = 0; /* nonzero = error occurred */
853 int errno2; /* stores previous errno values that take precedence */
854 if (moonbr_child_peersocket_outputstream->f) {
855 if (moonbr_child_peersocket_type == MOONBR_SOCKETTYPE_NETWORK) {
856 if (cleanshut) {
857 if (fflush(moonbr_child_peersocket_outputstream->f)) {
858 errno2 = errno;
859 err = -1;
860 } else {
861 if (shutdown(moonbr_child_peersocket_fd, SHUT_WR)) {
862 errno2 = errno;
863 err = -1;
864 }
865 }
866 } else {
867 fpurge(moonbr_child_peersocket_outputstream->f);
868 }
869 }
870 if (fclose(moonbr_child_peersocket_outputstream->f)) {
871 if (!err) errno2 = errno;
872 err = -1;
873 }
874 moonbr_child_peersocket_outputstream->f = NULL;
875 }
876 if (mark) moonbr_child_peersocket_outputstream->closef = NULL;
877 if (err) errno = errno2;
878 return err;
879 }
881 /* Perform a clean shutdown of input and output stream (may be called multiple times) */
882 static int moonbr_child_close_peersocket(int timeout) {
883 int errprio = 0;
884 int errno2;
885 if (moonbr_child_peersocket_fd == -1) return 0;
886 if (moonbr_child_close_peersocket_inputstream(1, 1)) {
887 errprio = 1;
888 errno2 = errno;
889 }
890 if (moonbr_child_close_peersocket_outputstream(1, 1)) {
891 errprio = 4;
892 errno2 = errno;
893 }
894 if (moonbr_child_peersocket_type == MOONBR_SOCKETTYPE_NETWORK) {
895 struct linger lingerval = { 0, };
896 if (timeout && !errprio) {
897 lingerval.l_onoff = 1;
898 lingerval.l_linger = timeout;
899 }
900 if (setsockopt(moonbr_child_peersocket_fd, SOL_SOCKET, SO_LINGER, &lingerval, sizeof(lingerval))) {
901 if (errprio < 2) {
902 errprio = 2;
903 errno2 = errno;
904 }
905 }
906 }
907 if (close(moonbr_child_peersocket_fd)) {
908 if (errprio < 3) {
909 errprio = 3;
910 errno2 = errno;
911 }
912 }
913 moonbr_child_peersocket_fd = -1;
914 if (errprio) {
915 errno = errno2;
916 return -1;
917 }
918 return 0;
919 }
921 /* Close socket and cause reset of TCP connection (TCP RST aka "Connection reset by peer") if possible */
922 static int moonbr_child_cancel_peersocket() {
923 int err = 0;
924 if (moonbr_child_close_peersocket_inputstream(0, 1)) err = -1;
925 if (moonbr_child_close_peersocket_outputstream(0, 1)) err = -1;
926 if (close(moonbr_child_peersocket_fd)) err = -1;
927 moonbr_child_peersocket_fd = -1;
928 return err;
929 }
931 /* Lua method for socket object to read from input stream */
932 static int moonbr_child_lua_read_stream(lua_State *L) {
933 lua_getfield(L, 1, "input");
934 lua_getfield(L, -1, "read");
935 lua_insert(L, 1);
936 lua_replace(L, 2);
937 lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
938 return lua_gettop(L);
939 }
941 /* Lua method for socket object to read from input stream until terminator */
942 static int moonbr_child_lua_readuntil_stream(lua_State *L) {
943 lua_getfield(L, 1, "input");
944 lua_getfield(L, -1, "readuntil");
945 lua_insert(L, 1);
946 lua_replace(L, 2);
947 lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
948 return lua_gettop(L);
949 }
951 /* Lua method for socket object to iterate over input stream */
952 static int moonbr_child_lua_lines_stream(lua_State *L) {
953 lua_getfield(L, 1, "input");
954 lua_getfield(L, -1, "lines");
955 lua_insert(L, 1);
956 lua_replace(L, 2);
957 lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
958 return lua_gettop(L);
959 }
961 /* Lua method for socket object to write to output stream */
962 static int moonbr_child_lua_write_stream(lua_State *L) {
963 lua_getfield(L, 1, "output");
964 lua_getfield(L, -1, "write");
965 lua_insert(L, 1);
966 lua_replace(L, 2);
967 lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
968 return lua_gettop(L);
969 }
971 /* Lua method for socket object to flush the output stream */
972 static int moonbr_child_lua_flush_stream(lua_State *L) {
973 lua_getfield(L, 1, "output");
974 lua_getfield(L, -1, "flush");
975 lua_insert(L, 1);
976 lua_replace(L, 2);
977 lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
978 return lua_gettop(L);
979 }
981 /* Lua function to close a single stream (input or output) from/to peer */
982 static int moonbr_child_lua_close_stream(lua_State *L) {
983 luaL_Stream *stream = lua_touserdata(L, 1);
984 if (stream == moonbr_child_peersocket_inputstream) {
985 if (moonbr_child_close_peersocket_inputstream(1, 0)) { /* don't mark as closed as it's done by Lua */
986 moonbr_child_lua_errno_error(L, "Could not close input stream");
987 }
988 } else if (stream == moonbr_child_peersocket_outputstream) {
989 if (moonbr_child_close_peersocket_outputstream(1, 0)) { /* don't mark as closed as it's done by Lua */
990 moonbr_child_lua_errno_error(L, "Could not close output stream");
991 }
992 } else {
993 luaL_argerror(L, 1, "Not a connection socket");
994 }
995 return 0;
996 }
998 /* Lua function to close both input and output stream from/to peer */
999 static int moonbr_child_lua_close_both_streams(lua_State *L) {
1000 int timeout = 0;
1001 if (!lua_isnoneornil(L, 2)) {
1002 lua_Integer n = luaL_checkinteger(L, 2);
1003 luaL_argcheck(L, n >= 0 && n <= INT_MAX, 2, "out of range");
1004 timeout = n;
1006 if (moonbr_child_peersocket_fd == -1) {
1007 luaL_error(L, "Connection with peer has already been explicitly closed");
1009 if (moonbr_child_close_peersocket(timeout)) {
1010 moonbr_child_lua_errno_error(L, "Could not close socket connection with peer");
1012 return 0;
1015 /* Lua function to close both input and output stream from/to peer */
1016 static int moonbr_child_lua_cancel_both_streams(lua_State *L) {
1017 if (moonbr_child_peersocket_fd == -1) {
1018 luaL_error(L, "Connection with peer has already been explicitly closed");
1020 if (moonbr_child_cancel_peersocket()) {
1021 moonbr_child_lua_errno_error(L, "Could not cancel socket connection with peer");
1023 return 0;
1026 /* Methods of (bidirectional) socket object passed to handler */
1027 static luaL_Reg moonbr_child_lua_socket_functions[] = {
1028 {"read", moonbr_child_lua_read_stream},
1029 {"readuntil", moonbr_child_lua_readuntil_stream},
1030 {"lines", moonbr_child_lua_lines_stream},
1031 {"write", moonbr_child_lua_write_stream},
1032 {"flush", moonbr_child_lua_flush_stream},
1033 {"close", moonbr_child_lua_close_both_streams},
1034 {"cancel", moonbr_child_lua_cancel_both_streams},
1035 {NULL, NULL}
1036 };
1038 /* Main function of child process to be called after fork() and file descriptor rearrangement */
1039 void moonbr_child_run(struct moonbr_pool *pool, lua_State *L) {
1040 char controlmsg;
1041 struct itimerval notimer = { { 0, }, { 0, } };
1042 lua_rawgetp(L, LUA_REGISTRYINDEX, moonbr_luakey_prepare_func(pool));
1043 if (lua_isnil(L, -1)) lua_pop(L, 1);
1044 else if (lua_pcall(L, 0, 0, 1)) {
1045 fprintf(stderr, "Error in \"prepare\" function: %s\n", lua_tostring(L, -1));
1046 exit(1);
1048 while (1) {
1049 struct moonbr_listener *listener;
1050 if (setitimer(ITIMER_REAL, &notimer, NULL)) {
1051 moonbr_child_log_errno_fatal("Could not reset ITIMER_REAL via setitimer()");
1053 controlmsg = MOONBR_STATUS_IDLE;
1054 if (write(MOONBR_FD_CONTROL, &controlmsg, 1) <= 0) {
1055 moonbr_child_log_errno_fatal("Error while sending ready message to parent process");
1057 moonbr_child_receive_control_message(
1058 MOONBR_FD_CONTROL,
1059 &controlmsg,
1060 &moonbr_child_peersocket_fd
1061 );
1062 if (!(
1063 (controlmsg == MOONBR_COMMAND_TERMINATE && moonbr_child_peersocket_fd == -1) ||
1064 (controlmsg == MOONBR_SOCKETTYPE_INTERVAL && moonbr_child_peersocket_fd == -1) ||
1065 (controlmsg == MOONBR_SOCKETTYPE_LOCAL && moonbr_child_peersocket_fd != -1) ||
1066 (controlmsg == MOONBR_SOCKETTYPE_NETWORK && moonbr_child_peersocket_fd != -1)
1067 )) {
1068 moonbr_child_log_fatal("Received illegal control message from parent process");
1070 if (controlmsg == MOONBR_COMMAND_TERMINATE) break;
1071 listener = moonbr_child_receive_pointer(MOONBR_FD_CONTROL);
1072 moonbr_child_peersocket_type = controlmsg;
1073 if (moonbr_child_peersocket_fd != -1) {
1075 int clonedfd;
1076 clonedfd = dup(moonbr_child_peersocket_fd);
1077 if (!clonedfd) {
1078 moonbr_child_log_errno_fatal("Could not duplicate file descriptor for input stream");
1080 moonbr_child_peersocket_inputstream = lua_newuserdata(L, sizeof(luaL_Stream));
1081 if (!moonbr_child_peersocket_inputstream) {
1082 moonbr_child_log_fatal("Memory allocation error");
1084 moonbr_child_peersocket_inputstream->f = fdopen(clonedfd, "rb");
1085 if (!moonbr_child_peersocket_inputstream->f) {
1086 moonbr_child_log_errno_fatal("Could not open input stream for remote connection");
1088 moonbr_child_peersocket_inputstream->closef = moonbr_child_lua_close_stream;
1089 if (luaL_newmetatable(L, LUA_FILEHANDLE)) {
1090 moonbr_child_log_fatal("Lua metatable LUA_FILEHANDLE does not exist");
1092 lua_setmetatable(L, -2);
1095 int clonedfd;
1096 clonedfd = dup(moonbr_child_peersocket_fd);
1097 if (!clonedfd) {
1098 moonbr_child_log_errno_fatal("Could not duplicate file descriptor for output stream");
1100 moonbr_child_peersocket_outputstream = lua_newuserdata(L, sizeof(luaL_Stream));
1101 if (!moonbr_child_peersocket_outputstream) {
1102 moonbr_child_log_fatal("Memory allocation error");
1104 moonbr_child_peersocket_outputstream->f = fdopen(clonedfd, "wb");
1105 if (!moonbr_child_peersocket_outputstream->f) {
1106 moonbr_child_log_errno_fatal("Could not open output stream for remote connection");
1108 moonbr_child_peersocket_outputstream->closef = moonbr_child_lua_close_stream;
1109 if (luaL_newmetatable(L, LUA_FILEHANDLE)) {
1110 moonbr_child_log_fatal("Lua metatable LUA_FILEHANDLE does not exist");
1112 lua_setmetatable(L, -2);
1115 lua_rawgetp(L, LUA_REGISTRYINDEX, moonbr_luakey_connect_func(pool));
1116 if (listener->proto == MOONBR_PROTO_INTERVAL) {
1117 lua_newtable(L);
1118 lua_pushstring(L,
1119 listener->proto_specific.interval.name ?
1120 listener->proto_specific.interval.name : ""
1121 );
1122 lua_setfield(L, -2, "interval");
1123 } else {
1124 lua_newtable(L);
1125 lua_pushvalue(L, -4);
1126 lua_setfield(L, -2, "input");
1127 lua_pushvalue(L, -3);
1128 lua_setfield(L, -2, "output");
1129 luaL_setfuncs(L, moonbr_child_lua_socket_functions, 0);
1130 if (listener->proto == MOONBR_PROTO_TCP6) {
1131 struct sockaddr_in6 addr;
1132 socklen_t addr_len = sizeof(struct sockaddr_in6);
1133 if (getsockname(moonbr_child_peersocket_fd, (struct sockaddr *)&addr, &addr_len)) {
1134 moonbr_child_log_errno("Could not get local IP address/port");
1135 } else {
1136 lua_pushlstring(L, (char *)addr.sin6_addr.s6_addr, 16);
1137 lua_setfield(L, -2, "local_ip6");
1138 lua_pushinteger(L, ntohs(addr.sin6_port));
1139 lua_setfield(L, -2, "local_tcpport");
1141 if (getpeername(moonbr_child_peersocket_fd, (struct sockaddr *)&addr, &addr_len)) {
1142 moonbr_child_log_errno("Could not get remote IP address/port");
1143 } else {
1144 lua_pushlstring(L, (char *)addr.sin6_addr.s6_addr, 16);
1145 lua_setfield(L, -2, "remote_ip6");
1146 lua_pushinteger(L, ntohs(addr.sin6_port));
1147 lua_setfield(L, -2, "remote_tcpport");
1149 } else if (listener->proto == MOONBR_PROTO_TCP4) {
1150 struct sockaddr_in addr;
1151 socklen_t addr_len = sizeof(struct sockaddr_in);
1152 if (getsockname(moonbr_child_peersocket_fd, (struct sockaddr *)&addr, &addr_len)) {
1153 moonbr_child_log_errno("Could not get local IP address/port");
1154 } else {
1155 lua_pushlstring(L, (char *)&addr.sin_addr.s_addr, 4);
1156 lua_setfield(L, -2, "local_ip4");
1157 lua_pushinteger(L, ntohs(addr.sin_port));
1158 lua_setfield(L, -2, "local_tcpport");
1160 if (getpeername(moonbr_child_peersocket_fd, (struct sockaddr *)&addr, &addr_len)) {
1161 moonbr_child_log_errno("Could not get remote IP address/port");
1162 } else {
1163 lua_pushlstring(L, (char *)&addr.sin_addr.s_addr, 4);
1164 lua_setfield(L, -2, "remote_ip4");
1165 lua_pushinteger(L, ntohs(addr.sin_port));
1166 lua_setfield(L, -2, "remote_tcpport");
1170 if (lua_pcall(L, 1, 1, 1)) {
1171 fprintf(stderr, "Error in \"connect\" function: %s\n", lua_tostring(L, -1));
1172 exit(1);
1174 if (moonbr_child_close_peersocket(0)) {
1175 moonbr_child_log_errno("Could not close socket connection with peer");
1177 if (lua_type(L, -1) != LUA_TBOOLEAN || !lua_toboolean(L, -1)) break;
1178 #ifdef MOONBR_LUA_PANIC_BUG_WORKAROUND
1179 lua_settop(L, 2);
1180 #else
1181 lua_settop(L, 1);
1182 #endif
1184 controlmsg = MOONBR_STATUS_GOODBYE;
1185 if (write(MOONBR_FD_CONTROL, &controlmsg, 1) <= 0) {
1186 moonbr_child_log_errno_fatal("Error while sending goodbye message to parent process");
1188 if (close(MOONBR_FD_CONTROL) && errno != EINTR) {
1189 moonbr_child_log_errno("Error while closing control socket");
1191 lua_rawgetp(L, LUA_REGISTRYINDEX, moonbr_luakey_finish_func(pool));
1192 if (lua_isnil(L, -1)) lua_pop(L, 1);
1193 else if (lua_pcall(L, 0, 0, 1)) {
1194 fprintf(stderr, "Error in \"finish\" function: %s\n", lua_tostring(L, -1));
1195 exit(1);
1197 lua_close(L);
1198 exit(0);
1202 /*** Functions to spawn child process ***/
1204 /* Helper function to send an error message to a file descriptor (not needing a file stream) */
1205 static void moonbr_child_emergency_print(int fd, char *message) {
1206 size_t len = strlen(message);
1207 ssize_t written;
1208 while (len) {
1209 written = write(fd, message, len);
1210 if (written > 0) {
1211 message += written;
1212 len -= written;
1213 } else {
1214 if (written != -1 || errno != EINTR) break;
1219 /* Helper function to send an error message plus a text for errno to a file descriptor and terminate the process */
1220 static void moonbr_child_emergency_error(int fd, char *message) {
1221 int errno2 = errno;
1222 moonbr_child_emergency_print(fd, message);
1223 moonbr_child_emergency_print(fd, ": ");
1224 moonbr_child_emergency_print(fd, strerror(errno2));
1225 moonbr_child_emergency_print(fd, "\n");
1226 exit(1);
1229 /* Creates a child process and (in case of success) registers it in the 'struct moonbr_pool' structure */
1230 static int moonbr_create_worker(struct moonbr_pool *pool, lua_State *L) {
1231 struct moonbr_worker *worker;
1232 worker = calloc(1, sizeof(struct moonbr_worker));
1233 if (!worker) {
1234 moonbr_log(LOG_CRIT, "Memory allocation error");
1235 return -1;
1237 worker->pool = pool;
1239 int controlfds[2];
1240 int errorfds[2];
1241 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, controlfds)) {
1242 moonbr_log(LOG_ERR, "Could not create control socket pair for communcation with child process: %s", strerror(errno));
1243 free(worker);
1244 return -1;
1246 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, errorfds)) {
1247 moonbr_log(LOG_ERR, "Could not create socket pair to redirect stderr of child process: %s", strerror(errno));
1248 close(controlfds[0]);
1249 close(controlfds[1]);
1250 free(worker);
1251 return -1;
1253 if (moonbr_logfile && fflush(moonbr_logfile)) {
1254 moonbr_log(LOG_CRIT, "Could not flush log file prior to forking: %s", strerror(errno));
1255 moonbr_terminate_error();
1257 worker->pid = fork();
1258 if (worker->pid == -1) {
1259 moonbr_log(LOG_ERR, "Could not fork: %s", strerror(errno));
1260 close(controlfds[0]);
1261 close(controlfds[1]);
1262 close(errorfds[0]);
1263 close(errorfds[1]);
1264 free(worker);
1265 return -1;
1266 } else if (!worker->pid) {
1267 moonbr_pstate = MOONBR_PSTATE_FORKED;
1268 #ifdef MOONBR_LUA_PANIC_BUG_WORKAROUND
1269 lua_pushliteral(L, "Failed to pass error message due to bug in Lua panic handler (hint: not enough memory?)");
1270 #endif
1271 moonbr_memory_limit = pool->memory_limit;
1272 if (moonbr_pidfh && pidfile_close(moonbr_pidfh)) {
1273 moonbr_child_emergency_error(errorfds[1], "Could not close PID file in forked child process");
1275 if (moonbr_logfile && moonbr_logfile != stderr && fclose(moonbr_logfile)) {
1276 moonbr_child_emergency_error(errorfds[1], "Could not close log file in forked child process");
1278 if (dup2(errorfds[1], MOONBR_FD_STDERR) == -1) {
1279 moonbr_child_emergency_error(errorfds[1], "Could not duplicate socket to stderr file descriptor");
1281 if (dup2(controlfds[1], MOONBR_FD_CONTROL) == -1) {
1282 moonbr_child_emergency_error(errorfds[1], "Could not duplicate control socket");
1284 closefrom(MOONBR_FD_END);
1285 moonbr_child_run(pool, L);
1287 if (moonbr_stat) {
1288 moonbr_log(LOG_INFO, "Created new worker in pool #%i with PID %i", worker->pool->poolnum, (int)worker->pid);
1290 worker->controlfd = controlfds[0];
1291 worker->errorfd = errorfds[0];
1292 if (close(controlfds[1]) && errno != EINTR) {
1293 moonbr_log(LOG_CRIT, "Could not close opposite end of control file descriptor after forking");
1294 moonbr_terminate_error();
1296 if (close(errorfds[1]) && errno != EINTR) {
1297 moonbr_log(LOG_CRIT, "Could not close opposite end of control file descriptor after forking");
1298 moonbr_terminate_error();
1301 worker->prev_worker = pool->last_worker;
1302 if (worker->prev_worker) worker->prev_worker->next_worker = worker;
1303 else pool->first_worker = worker;
1304 pool->last_worker = worker;
1305 pool->unassigned_worker_count++;
1306 pool->total_worker_count++;
1307 pool->worker_count_stat = 1;
1308 moonbr_poll_refresh_needed = 1;
1309 return 0; /* return zero only in case of success */
1313 /*** Functions to handle previously created 'struct moonbr_worker' structures ***/
1315 #define moonbr_try_destroy_worker_stat(str, field) \
1316 moonbr_log(LOG_INFO, "Resource usage in pool #%i for PID %i: " str " %li", worker->pool->poolnum, (int)worker->pid, (long)childusage.field);
1318 /* Destroys a worker structure if socket connections have been closed and child process has terminated */
1319 static int moonbr_try_destroy_worker(struct moonbr_worker *worker) {
1320 if (worker->controlfd != -1 || worker->errorfd != -1) return MOONBR_DESTROY_NONE;
1322 int childstatus;
1323 struct rusage childusage;
1325 pid_t waitedpid;
1326 while (
1327 (waitedpid = wait4(worker->pid, &childstatus, WNOHANG, &childusage)) == -1
1328 ) {
1329 if (errno != EINTR) {
1330 moonbr_log(LOG_CRIT, "Error in wait4() call: %s", strerror(errno));
1331 moonbr_terminate_error();
1334 if (!waitedpid) return 0; /* return 0 if worker couldn't be destroyed */
1335 if (waitedpid != worker->pid) {
1336 moonbr_log(LOG_CRIT, "Wrong PID returned by wait4() call");
1337 moonbr_terminate_error();
1340 if (WIFEXITED(childstatus)) {
1341 if (WEXITSTATUS(childstatus) || moonbr_stat) {
1342 moonbr_log(
1343 WEXITSTATUS(childstatus) ? LOG_WARNING : LOG_INFO,
1344 "Child process in pool #%i with PID %i returned with exit code %i", worker->pool->poolnum, (int)worker->pid, WEXITSTATUS(childstatus)
1345 );
1347 } else if (WIFSIGNALED(childstatus)) {
1348 if (WCOREDUMP(childstatus)) {
1349 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));
1350 } else if (WTERMSIG(childstatus) == SIGALRM) {
1351 moonbr_log(LOG_WARNING, "Child process in pool #%i with PID %i exited prematurely due to timeout", worker->pool->poolnum, (int)worker->pid);
1352 } else {
1353 moonbr_log(LOG_ERR, "Child process in pool #%i with PID %i died from signal %i", worker->pool->poolnum, (int)worker->pid, WTERMSIG(childstatus));
1355 } else {
1356 moonbr_log(LOG_CRIT, "Illegal exit status from child process in pool #%i with PID %i", worker->pool->poolnum, (int)worker->pid);
1357 moonbr_terminate_error();
1359 if (moonbr_stat) {
1360 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));
1361 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));
1362 moonbr_try_destroy_worker_stat("max resident set size", ru_maxrss);
1363 moonbr_try_destroy_worker_stat("integral shared memory size", ru_ixrss);
1364 moonbr_try_destroy_worker_stat("integral unshared data", ru_idrss);
1365 moonbr_try_destroy_worker_stat("integral unshared stack", ru_isrss);
1366 moonbr_try_destroy_worker_stat("page replaims", ru_minflt);
1367 moonbr_try_destroy_worker_stat("page faults", ru_majflt);
1368 moonbr_try_destroy_worker_stat("swaps", ru_nswap);
1369 moonbr_try_destroy_worker_stat("block input operations", ru_inblock);
1370 moonbr_try_destroy_worker_stat("block output operations", ru_oublock);
1371 moonbr_try_destroy_worker_stat("messages sent", ru_msgsnd);
1372 moonbr_try_destroy_worker_stat("messages received", ru_msgrcv);
1373 moonbr_try_destroy_worker_stat("signals received", ru_nsignals);
1374 moonbr_try_destroy_worker_stat("voluntary context switches", ru_nvcsw);
1375 moonbr_try_destroy_worker_stat("involuntary context switches", ru_nivcsw);
1379 int retval = (
1380 (worker->idle || worker->assigned) ?
1381 MOONBR_DESTROY_IDLE_OR_ASSIGNED :
1382 MOONBR_DESTROY_PREPARE
1383 );
1384 if (worker->prev_worker) worker->prev_worker->next_worker = worker->next_worker;
1385 else worker->pool->first_worker = worker->next_worker;
1386 if (worker->next_worker) worker->next_worker->prev_worker = worker->prev_worker;
1387 else worker->pool->last_worker = worker->prev_worker;
1388 if (worker->idle) {
1389 if (worker->prev_idle_worker) worker->prev_idle_worker->next_idle_worker = worker->next_idle_worker;
1390 else worker->pool->first_idle_worker = worker->next_idle_worker;
1391 if (worker->next_idle_worker) worker->next_idle_worker->prev_idle_worker = worker->prev_idle_worker;
1392 else worker->pool->last_idle_worker = worker->prev_idle_worker;
1393 worker->pool->idle_worker_count--;
1395 if (!worker->assigned) worker->pool->unassigned_worker_count--;
1396 worker->pool->total_worker_count--;
1397 worker->pool->worker_count_stat = 1;
1398 if (worker->errorlinebuf) free(worker->errorlinebuf);
1399 free(worker);
1400 return retval;
1404 /* Marks a worker as idle and stores it in a queue, optionally setting 'idle_expiration' value */
1405 static void moonbr_add_idle_worker(struct moonbr_worker *worker) {
1406 worker->prev_idle_worker = worker->pool->last_idle_worker;
1407 if (worker->prev_idle_worker) worker->prev_idle_worker->next_idle_worker = worker;
1408 else worker->pool->first_idle_worker = worker;
1409 worker->pool->last_idle_worker = worker;
1410 worker->idle = 1;
1411 worker->pool->idle_worker_count++;
1412 if (worker->assigned) {
1413 worker->assigned = 0;
1414 worker->pool->unassigned_worker_count++;
1416 worker->pool->worker_count_stat = 1;
1417 if (timerisset(&worker->pool->idle_timeout)) {
1418 struct timeval now;
1419 moonbr_now(&now);
1420 timeradd(&now, &worker->pool->idle_timeout, &worker->idle_expiration);
1424 /* Pops a worker from the queue of idle workers (idle queue must not be empty) */
1425 static struct moonbr_worker *moonbr_pop_idle_worker(struct moonbr_pool *pool) {
1426 struct moonbr_worker *worker;
1427 worker = pool->first_idle_worker;
1428 pool->first_idle_worker = worker->next_idle_worker;
1429 if (pool->first_idle_worker) pool->first_idle_worker->prev_idle_worker = NULL;
1430 else pool->last_idle_worker = NULL;
1431 worker->next_idle_worker = NULL;
1432 worker->idle = 0;
1433 worker->pool->idle_worker_count--;
1434 worker->assigned = 1;
1435 worker->pool->unassigned_worker_count--;
1436 worker->pool->worker_count_stat = 1;
1437 return worker;
1441 /*** Functions for queues of 'struct moonbr_listener' ***/
1443 /* Appends a 'struct moonbr_listener' to the queue of idle listeners and registers it for poll() */
1444 static void moonbr_add_idle_listener(struct moonbr_listener *listener) {
1445 listener->prev_listener = listener->pool->last_idle_listener;
1446 if (listener->prev_listener) listener->prev_listener->next_listener = listener;
1447 else listener->pool->first_idle_listener = listener;
1448 listener->pool->last_idle_listener = listener;
1449 if (listener->pollidx != -1) moonbr_poll_fds[listener->pollidx].events |= POLLIN;
1452 /* Removes a 'struct moonbr_listener' from the queue of idle listeners and unregisters it from poll() */
1453 static void moonbr_remove_idle_listener(struct moonbr_listener *listener) {
1454 if (listener->prev_listener) listener->prev_listener->next_listener = listener->next_listener;
1455 else listener->pool->first_idle_listener = listener->next_listener;
1456 if (listener->next_listener) listener->next_listener->prev_listener = listener->prev_listener;
1457 else listener->pool->last_idle_listener = listener->prev_listener;
1458 listener->prev_listener = NULL;
1459 listener->next_listener = NULL;
1460 if (listener->pollidx != -1) moonbr_poll_fds[listener->pollidx].events &= ~POLLIN;
1463 /* Adds a listener to the queue of connected listeners (i.e. waiting to have their incoming connection accepted) */
1464 static void moonbr_add_connected_listener(struct moonbr_listener *listener) {
1465 listener->prev_listener = listener->pool->last_connected_listener;
1466 if (listener->prev_listener) listener->prev_listener->next_listener = listener;
1467 else listener->pool->first_connected_listener = listener;
1468 listener->pool->last_connected_listener = listener;
1471 /* Removes and returns the first connected listener in the queue */
1472 static struct moonbr_listener *moonbr_pop_connected_listener(struct moonbr_pool *pool) {
1473 struct moonbr_listener *listener = pool->first_connected_listener;
1474 listener->pool->first_connected_listener = listener->next_listener;
1475 if (listener->pool->first_connected_listener) listener->pool->first_connected_listener->prev_listener = NULL;
1476 else listener->pool->last_connected_listener = NULL;
1477 listener->next_listener = NULL;
1478 return listener;
1482 /*** Functions to handle polling ***/
1484 /* Returns an index to a new initialized entry in moonbr_poll_fds[] */
1485 int moonbr_poll_fds_nextindex() {
1486 if (moonbr_poll_fds_count >= moonbr_poll_fds_bufsize) {
1487 if (moonbr_poll_fds_bufsize) moonbr_poll_fds_bufsize *= 2;
1488 else moonbr_poll_fds_bufsize = 1;
1489 moonbr_poll_fds = realloc(
1490 moonbr_poll_fds, moonbr_poll_fds_bufsize * sizeof(struct pollfd)
1491 );
1492 if (!moonbr_poll_fds) {
1493 moonbr_log(LOG_CRIT, "Memory allocation error");
1494 moonbr_terminate_error();
1497 moonbr_poll_fds[moonbr_poll_fds_count] = (struct pollfd){0, };
1498 return moonbr_poll_fds_count++;
1501 /* Returns an index to a new initialized entry in moonbr_poll_workers[] */
1502 int moonbr_poll_workers_nextindex() {
1503 if (moonbr_poll_worker_count >= moonbr_poll_workers_bufsize) {
1504 if (moonbr_poll_workers_bufsize) moonbr_poll_workers_bufsize *= 2;
1505 else moonbr_poll_workers_bufsize = 1;
1506 moonbr_poll_workers = realloc(
1507 moonbr_poll_workers, moonbr_poll_workers_bufsize * sizeof(struct moonbr_poll_worker)
1508 );
1509 if (!moonbr_poll_workers) {
1510 moonbr_log(LOG_CRIT, "Memory allocation error");
1511 moonbr_terminate_error();
1514 moonbr_poll_workers[moonbr_poll_worker_count] = (struct moonbr_poll_worker){0, };
1515 return moonbr_poll_worker_count++;
1518 /* Queues all listeners as idle, and initializes static part of moonbr_poll_fds[], which is passed to poll() */
1519 static void moonbr_poll_init() {
1520 if (socketpair(
1521 PF_LOCAL,
1522 SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
1523 0,
1524 moonbr_poll_signalfds
1525 )) {
1526 moonbr_log(LOG_CRIT, "Could not create socket pair for signal delivery during polling: %s", strerror(errno));
1527 moonbr_terminate_error();
1530 int j = moonbr_poll_fds_nextindex();
1531 struct pollfd *pollfd = &moonbr_poll_fds[j];
1532 pollfd->fd = moonbr_poll_signalfd_read;
1533 pollfd->events = POLLIN;
1536 struct moonbr_pool *pool;
1537 for (pool=moonbr_first_pool; pool; pool=pool->next_pool) {
1538 int i;
1539 for (i=0; i<pool->listener_count; i++) {
1540 struct moonbr_listener *listener = &pool->listener[i];
1541 if (listener->listenfd != -1) {
1542 int j = moonbr_poll_fds_nextindex();
1543 listener->pollidx = j;
1544 moonbr_poll_fds[j].fd = listener->listenfd;
1546 moonbr_add_idle_listener(listener);
1550 moonbr_poll_fds_static_count = moonbr_poll_fds_count; /* remember size of static part of array */
1553 /* Disables polling of all listeners (required for clean shutdown) */
1554 static void moonbr_poll_shutdown() {
1555 int i;
1556 for (i=1; i<moonbr_poll_fds_static_count; i++) {
1557 moonbr_poll_fds[i].fd = -1;
1561 /* (Re)builds dynamic part of moonbr_poll_fds[] array, and (re)builds moonbr_poll_workers[] array */
1562 static void moonbr_poll_refresh() {
1563 moonbr_poll_refresh_needed = 0;
1564 moonbr_poll_fds_count = moonbr_poll_fds_static_count;
1565 moonbr_poll_worker_count = 0;
1567 struct moonbr_pool *pool;
1568 for (pool=moonbr_first_pool; pool; pool=pool->next_pool) {
1569 struct moonbr_worker *worker;
1570 for (worker=pool->first_worker; worker; worker=worker->next_worker) {
1571 if (worker->controlfd != -1) {
1572 int j = moonbr_poll_fds_nextindex();
1573 int k = moonbr_poll_workers_nextindex();
1574 struct pollfd *pollfd = &moonbr_poll_fds[j];
1575 struct moonbr_poll_worker *poll_worker = &moonbr_poll_workers[k];
1576 pollfd->fd = worker->controlfd;
1577 pollfd->events = POLLIN;
1578 poll_worker->channel = MOONBR_POLL_WORKER_CONTROLCHANNEL;
1579 poll_worker->worker = worker;
1581 if (worker->errorfd != -1) {
1582 int j = moonbr_poll_fds_nextindex();
1583 int k = moonbr_poll_workers_nextindex();
1584 struct pollfd *pollfd = &moonbr_poll_fds[j];
1585 struct moonbr_poll_worker *poll_worker = &moonbr_poll_workers[k];
1586 pollfd->fd = worker->errorfd;
1587 pollfd->events = POLLIN;
1588 poll_worker->channel = MOONBR_POLL_WORKER_ERRORCHANNEL;
1589 poll_worker->worker = worker;
1596 /* resets socket and 'revents' field of moonbr_poll_fds[] for signal delivery just before poll() is called */
1597 static void moonbr_poll_reset_signal() {
1598 ssize_t readcount;
1599 char buf[1];
1600 moonbr_poll_fds[0].revents = 0;
1601 while ((readcount = read(moonbr_poll_signalfd_read, buf, 1)) < 0) {
1602 if (errno == EAGAIN) break;
1603 if (errno != EINTR) {
1604 moonbr_log(LOG_CRIT, "Error while reading from signal delivery socket: %s", strerror(errno));
1605 moonbr_terminate_error();
1608 if (!readcount) {
1609 moonbr_log(LOG_CRIT, "Unexpected EOF when reading from signal delivery socket: %s", strerror(errno));
1610 moonbr_terminate_error();
1615 /*** Shutdown initiation ***/
1617 /* Sets global variable 'moonbr_shutdown_in_progress', closes listeners, and demands worker termination */
1618 static void moonbr_initiate_shutdown() {
1619 struct moonbr_pool *pool;
1620 int i;
1621 if (moonbr_shutdown_in_progress) {
1622 moonbr_log(LOG_NOTICE, "Shutdown already in progress");
1623 return;
1625 moonbr_shutdown_in_progress = 1;
1626 moonbr_log(LOG_NOTICE, "Initiate shutdown");
1627 for (pool = moonbr_first_pool; pool; pool = pool->next_pool) {
1628 for (i=0; i<pool->listener_count; i++) {
1629 struct moonbr_listener *listener = &pool->listener[i];
1630 if (listener->listenfd != -1) {
1631 if (close(listener->listenfd) && errno != EINTR) {
1632 moonbr_log(LOG_CRIT, "Could not close listening socket: %s", strerror(errno));
1633 moonbr_terminate_error();
1637 pool->pre_fork = 0;
1638 pool->min_fork = 0;
1639 pool->max_fork = 0;
1640 timerclear(&pool->exit_delay);
1642 moonbr_poll_shutdown(); /* avoids loops due to error condition when polling closed listeners */
1646 /*** Functions to communicate with child processes ***/
1648 /* Tells child process to terminate */
1649 static void moonbr_terminate_idle_worker(struct moonbr_worker *worker) {
1650 moonbr_send_control_message(worker, MOONBR_COMMAND_TERMINATE, -1, NULL);
1653 /* Handles status messages from child process */
1654 static void moonbr_read_controlchannel(struct moonbr_worker *worker) {
1655 char controlmsg;
1657 ssize_t bytes_read;
1658 while ((bytes_read = read(worker->controlfd, &controlmsg, 1)) <= 0) {
1659 if (bytes_read == 0 || errno == ECONNRESET) {
1660 moonbr_log(LOG_WARNING, "Child process in pool #%i with PID %i unexpectedly closed control socket", worker->pool->poolnum, (int)worker->pid);
1661 if (close(worker->controlfd) && errno != EINTR) {
1662 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));
1663 moonbr_terminate_error();
1665 worker->controlfd = -1;
1666 moonbr_poll_refresh_needed = 1;
1667 return;
1669 if (errno != EINTR) {
1670 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));
1671 moonbr_terminate_error();
1675 if (worker->idle) {
1676 moonbr_log(LOG_CRIT, "Unexpected data from supposedly idle child process in pool #%i with PID %i", worker->pool->poolnum, (int)worker->pid);
1677 moonbr_terminate_error();
1679 if (moonbr_debug) {
1680 moonbr_log(LOG_DEBUG, "Received control message from child in pool #%i with PID %i: \"%c\"", worker->pool->poolnum, (int)worker->pid, (int)controlmsg);
1682 switch (controlmsg) {
1683 case MOONBR_STATUS_IDLE:
1684 if (moonbr_stat) {
1685 moonbr_log(LOG_INFO, "Child process in pool #%i with PID %i reports as idle", worker->pool->poolnum, (int)worker->pid);
1687 moonbr_add_idle_worker(worker);
1688 break;
1689 case MOONBR_STATUS_GOODBYE:
1690 if (moonbr_stat) {
1691 moonbr_log(LOG_INFO, "Child process in pool #%i with PID %i announced termination", worker->pool->poolnum, (int)worker->pid);
1693 if (close(worker->controlfd) && errno != EINTR) {
1694 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));
1695 moonbr_terminate_error();
1697 worker->controlfd = -1;
1698 moonbr_poll_refresh_needed = 1;
1699 break;
1700 default:
1701 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);
1702 moonbr_terminate_error();
1706 /* Handles stderr stream from child process */
1707 static void moonbr_read_errorchannel(struct moonbr_worker *worker) {
1708 char staticbuf[MOONBR_MAXERRORLINELEN+1];
1709 char *buf = worker->errorlinebuf;
1710 if (!buf) buf = staticbuf;
1712 ssize_t bytes_read;
1713 while (
1714 (bytes_read = read(
1715 worker->errorfd,
1716 buf + worker->errorlinelen,
1717 MOONBR_MAXERRORLINELEN+1 - worker->errorlinelen
1718 )) <= 0
1719 ) {
1720 if (bytes_read == 0 || errno == ECONNRESET) {
1721 if (moonbr_debug) {
1722 moonbr_log(LOG_DEBUG, "Child process in pool #%i with PID %i closed stderr socket", worker->pool->poolnum, (int)worker->pid);
1724 if (close(worker->errorfd) && errno != EINTR) {
1725 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));
1726 moonbr_terminate_error();
1728 worker->errorfd = -1;
1729 moonbr_poll_refresh_needed = 1;
1730 break;
1732 if (errno != EINTR) {
1733 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));
1734 moonbr_terminate_error();
1737 worker->errorlinelen += bytes_read;
1740 int i;
1741 for (i=0; i<worker->errorlinelen; i++) {
1742 if (buf[i] == '\n') buf[i] = 0;
1743 if (!buf[i]) {
1744 if (worker->errorlineovf) {
1745 worker->errorlineovf = 0;
1746 } else {
1747 moonbr_log(LOG_WARNING, "Error log from process in pool #%i with PID %i: %s", worker->pool->poolnum, (int)worker->pid, buf);
1749 worker->errorlinelen -= i+1;
1750 memmove(buf, buf+i+1, worker->errorlinelen);
1751 i = -1;
1754 if (i > MOONBR_MAXERRORLINELEN) {
1755 buf[MOONBR_MAXERRORLINELEN] = 0;
1756 if (!worker->errorlineovf) {
1757 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);
1759 worker->errorlinelen = 0;
1760 worker->errorlineovf = 1;
1763 if (!worker->errorlinebuf && worker->errorlinelen) { /* allocate buffer on heap only if necessary */
1764 worker->errorlinebuf = malloc((MOONBR_MAXERRORLINELEN+1) * sizeof(char));
1765 if (!worker->errorlinebuf) {
1766 moonbr_log(LOG_CRIT, "Memory allocation error");
1767 moonbr_terminate_error();
1769 memcpy(worker->errorlinebuf, staticbuf, worker->errorlinelen);
1774 /*** Handler for incoming connections ***/
1776 /* Accepts one or more incoming connections on listener socket and passes it to worker(s) popped from idle queue */
1777 static void moonbr_connect(struct moonbr_pool *pool) {
1778 struct moonbr_listener *listener = moonbr_pop_connected_listener(pool);
1779 struct moonbr_worker *worker;
1780 switch (listener->proto) {
1781 case MOONBR_PROTO_INTERVAL:
1782 worker = moonbr_pop_idle_worker(pool);
1783 if (moonbr_stat) {
1784 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);
1786 worker->restart_interval_listener = listener;
1787 moonbr_send_control_message(worker, MOONBR_SOCKETTYPE_INTERVAL, -1, listener);
1788 /* do not push listener to queue of idle listeners yet */
1789 break;
1790 case MOONBR_PROTO_LOCAL:
1791 do {
1792 int peerfd;
1793 struct sockaddr_un peeraddr;
1794 socklen_t peeraddr_len = sizeof(struct sockaddr_un);
1795 peerfd = accept4(
1796 listener->listenfd,
1797 (struct sockaddr *)&peeraddr,
1798 &peeraddr_len,
1799 SOCK_CLOEXEC
1800 );
1801 if (peerfd == -1) {
1802 if (errno == EWOULDBLOCK) {
1803 break;
1804 } else if (errno == ECONNABORTED) {
1805 moonbr_log(LOG_WARNING, "Connection aborted before accepting it (proto=\"local\", path=\"%s\")", listener->proto_specific.local.path);
1806 break;
1807 } else if (errno != EINTR) {
1808 moonbr_log(LOG_ERR, "Could not accept socket connection: %s", strerror(errno));
1809 moonbr_terminate_error();
1811 } else {
1812 worker = moonbr_pop_idle_worker(pool);
1813 if (moonbr_stat) {
1814 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);
1816 moonbr_send_control_message(worker, MOONBR_SOCKETTYPE_LOCAL, peerfd, listener);
1817 if (close(peerfd) && errno != EINTR) {
1818 moonbr_log(LOG_ERR, "Could not close incoming socket connection in parent process: %s", strerror(errno));
1819 moonbr_terminate_error();
1822 } while (pool->first_idle_worker);
1823 moonbr_add_idle_listener(listener);
1824 break;
1825 case MOONBR_PROTO_TCP6:
1826 do {
1827 int peerfd;
1828 struct sockaddr_in6 peeraddr;
1829 socklen_t peeraddr_len = sizeof(struct sockaddr_in6);
1830 peerfd = accept4(
1831 listener->listenfd,
1832 (struct sockaddr *)&peeraddr,
1833 &peeraddr_len,
1834 SOCK_CLOEXEC
1835 );
1836 if (peerfd == -1) {
1837 if (errno == EWOULDBLOCK) {
1838 break;
1839 } else if (errno == ECONNABORTED) {
1840 moonbr_log(LOG_WARNING, "Connection aborted before accepting it (proto=\"tcp6\", port=%i)", listener->proto_specific.tcp.port);
1841 break;
1842 } else if (errno != EINTR) {
1843 moonbr_log(LOG_ERR, "Could not accept socket connection: %s", strerror(errno));
1844 moonbr_terminate_error();
1846 } else {
1847 worker = moonbr_pop_idle_worker(pool);
1848 if (moonbr_stat) {
1849 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);
1851 moonbr_send_control_message(worker, MOONBR_SOCKETTYPE_NETWORK, peerfd, listener);
1852 if (close(peerfd) && errno != EINTR) {
1853 moonbr_log(LOG_ERR, "Could not close incoming socket connection in parent process: %s", strerror(errno));
1854 moonbr_terminate_error();
1857 } while (pool->first_idle_worker);
1858 moonbr_add_idle_listener(listener);
1859 break;
1860 case MOONBR_PROTO_TCP4:
1861 do {
1862 int peerfd;
1863 struct sockaddr_in peeraddr;
1864 socklen_t peeraddr_len = sizeof(struct sockaddr_in);
1865 peerfd = accept4(
1866 listener->listenfd,
1867 (struct sockaddr *)&peeraddr,
1868 &peeraddr_len,
1869 SOCK_CLOEXEC
1870 );
1871 if (peerfd == -1) {
1872 if (errno == EWOULDBLOCK) {
1873 break;
1874 } else if (errno == ECONNABORTED) {
1875 moonbr_log(LOG_WARNING, "Connection aborted before accepting it (proto=\"tcp4\", port=%i)", listener->proto_specific.tcp.port);
1876 break;
1877 } else if (errno != EINTR) {
1878 moonbr_log(LOG_ERR, "Could not accept socket connection: %s", strerror(errno));
1879 moonbr_terminate_error();
1881 } else {
1882 worker = moonbr_pop_idle_worker(pool);
1883 if (moonbr_stat) {
1884 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);
1886 moonbr_send_control_message(worker, MOONBR_SOCKETTYPE_NETWORK, peerfd, listener);
1887 if (close(peerfd) && errno != EINTR) {
1888 moonbr_log(LOG_ERR, "Could not close incoming socket connection in parent process: %s", strerror(errno));
1889 moonbr_terminate_error();
1892 } while (pool->first_idle_worker);
1893 moonbr_add_idle_listener(listener);
1894 break;
1895 default:
1896 moonbr_log(LOG_ERR, "Internal error (should not happen): Unexpected value in listener.proto field");
1897 moonbr_terminate_error();
1902 /*** Functions to initialize and restart interval timers ***/
1904 /* Initializes all interval timers */
1905 static void moonbr_interval_initialize() {
1906 struct timeval now;
1907 struct moonbr_pool *pool;
1908 moonbr_now(&now);
1909 for (pool=moonbr_first_pool; pool; pool=pool->next_pool) {
1910 int i;
1911 for (i=0; i<pool->listener_count; i++) {
1912 struct moonbr_listener *listener = &pool->listener[i];
1913 if (listener->proto == MOONBR_PROTO_INTERVAL) {
1914 timeradd(
1915 &now,
1916 &listener->proto_specific.interval.delay,
1917 &listener->proto_specific.interval.wakeup
1918 );
1924 /* If necessary, restarts interval timers and queues interval listener as idle after a worker changed status */
1925 static void moonbr_interval_restart(
1926 struct moonbr_worker *worker,
1927 struct timeval *now /* passed to synchronize with moonbr_run() function */
1928 ) {
1929 struct moonbr_listener *listener = worker->restart_interval_listener;
1930 if (listener) {
1931 moonbr_add_idle_listener(listener);
1932 worker->restart_interval_listener = NULL;
1933 if (listener->proto_specific.interval.strict) {
1934 timeradd(
1935 &listener->proto_specific.interval.wakeup,
1936 &listener->proto_specific.interval.delay,
1937 &listener->proto_specific.interval.wakeup
1938 );
1939 if (timercmp(&listener->proto_specific.interval.wakeup, now, <)) {
1940 listener->proto_specific.interval.wakeup = *now;
1942 } else {
1943 timeradd(
1944 now,
1945 &listener->proto_specific.interval.delay,
1946 &listener->proto_specific.interval.wakeup
1947 );
1953 /*** Main loop and helper functions ***/
1955 /* Stores the earliest required wakeup time in 'wait' variable */
1956 static void moonbr_calc_wait(struct timeval *wait, struct timeval *wakeup) {
1957 if (!timerisset(wait) || timercmp(wakeup, wait, <)) *wait = *wakeup;
1960 /* Main loop of Moonbridge system (including initialization of signal handlers and polling structures) */
1961 static void moonbr_run(lua_State *L) {
1962 struct timeval now;
1963 struct moonbr_pool *pool;
1964 struct moonbr_worker *worker;
1965 struct moonbr_worker *next_worker; /* needed when worker is removed during iteration of workers */
1966 struct moonbr_listener *listener;
1967 struct moonbr_listener *next_listener; /* needed when listener is removed during iteration of listeners */
1968 int i;
1969 moonbr_poll_init(); /* must be executed before moonbr_signal_init() */
1970 moonbr_signal_init();
1971 moonbr_interval_initialize();
1972 moonbr_pstate = MOONBR_PSTATE_RUNNING;
1973 while (1) {
1974 struct timeval wait = {0, }; /* point in time when premature wakeup of poll() is required */
1975 if (moonbr_cond_interrupt) {
1976 moonbr_log(LOG_WARNING, "Fast shutdown requested");
1977 moonbr_terminate(MOONBR_EXITCODE_GRACEFUL);
1979 if (moonbr_cond_terminate) {
1980 moonbr_initiate_shutdown();
1981 moonbr_cond_terminate = 0;
1983 moonbr_cond_child = 0; /* must not be reset between moonbr_try_destroy_worker() and poll() */
1984 moonbr_now(&now);
1985 for (pool=moonbr_first_pool; pool; pool=pool->next_pool) {
1986 int terminated_worker_count = 0; /* allows shortcut for new worker creation */
1987 /* terminate idle workers when expired */
1988 if (timerisset(&pool->idle_timeout)) {
1989 while ((worker = pool->first_idle_worker) != NULL) {
1990 if (timercmp(&worker->idle_expiration, &now, >)) break;
1991 moonbr_pop_idle_worker(pool);
1992 moonbr_terminate_idle_worker(worker);
1995 /* mark listeners as connected when incoming connection is pending */
1996 for (listener=pool->first_idle_listener; listener; listener=next_listener) {
1997 next_listener = listener->next_listener; /* extra variable necessary due to changing list */
1998 if (listener->pollidx != -1) {
1999 if (moonbr_poll_fds[listener->pollidx].revents) {
2000 moonbr_poll_fds[listener->pollidx].revents = 0;
2001 moonbr_remove_idle_listener(listener);
2002 moonbr_add_connected_listener(listener);
2004 } else if (listener->proto == MOONBR_PROTO_INTERVAL) {
2005 if (!timercmp(&listener->proto_specific.interval.wakeup, &now, >)) {
2006 moonbr_remove_idle_listener(listener);
2007 moonbr_add_connected_listener(listener);
2009 } else {
2010 moonbr_log(LOG_CRIT, "Internal error (should not happen): Listener is neither an interval timer nor has the 'pollidx' value set");
2011 moonbr_terminate_error();
2014 /* process input from child processes */
2015 for (i=0; i<moonbr_poll_worker_count; i++) {
2016 if (moonbr_poll_worker_fds[i].revents) {
2017 moonbr_poll_worker_fds[i].revents = 0;
2018 struct moonbr_poll_worker *poll_worker = &moonbr_poll_workers[i];
2019 switch (poll_worker->channel) {
2020 case MOONBR_POLL_WORKER_CONTROLCHANNEL:
2021 moonbr_read_controlchannel(poll_worker->worker);
2022 moonbr_interval_restart(poll_worker->worker, &now);
2023 break;
2024 case MOONBR_POLL_WORKER_ERRORCHANNEL:
2025 moonbr_read_errorchannel(poll_worker->worker);
2026 break;
2030 /* collect dead child processes */
2031 for (worker=pool->first_worker; worker; worker=next_worker) {
2032 next_worker = worker->next_worker; /* extra variable necessary due to changing list */
2033 switch (moonbr_try_destroy_worker(worker)) {
2034 case MOONBR_DESTROY_PREPARE:
2035 pool->use_fork_error_wakeup = 1;
2036 break;
2037 case MOONBR_DESTROY_IDLE_OR_ASSIGNED:
2038 terminated_worker_count++;
2039 break;
2042 /* connect listeners with idle workers */
2043 if (!moonbr_shutdown_in_progress) {
2044 while (pool->first_connected_listener && pool->first_idle_worker) {
2045 moonbr_connect(pool);
2048 /* create new worker processes */
2049 while (
2050 pool->total_worker_count < pool->max_fork && (
2051 pool->unassigned_worker_count < pool->pre_fork ||
2052 pool->total_worker_count < pool->min_fork
2054 ) {
2055 if (pool->use_fork_error_wakeup) {
2056 if (timercmp(&pool->fork_error_wakeup, &now, >)) {
2057 moonbr_calc_wait(&wait, &pool->fork_error_wakeup);
2058 break;
2060 } else {
2061 if (terminated_worker_count) {
2062 terminated_worker_count--;
2063 } else if (timercmp(&pool->fork_wakeup, &now, >)) {
2064 moonbr_calc_wait(&wait, &pool->fork_wakeup);
2065 break;
2068 if (moonbr_create_worker(pool, L)) {
2069 /* on error, enforce error delay */
2070 timeradd(&now, &pool->fork_error_delay, &pool->fork_error_wakeup);
2071 pool->use_fork_error_wakeup = 1;
2072 moonbr_calc_wait(&wait, &pool->fork_error_wakeup);
2073 break;
2074 } else {
2075 /* normal fork delay on success */
2076 timeradd(&now, &pool->fork_delay, &pool->fork_wakeup);
2077 timeradd(&now, &pool->fork_error_delay, &pool->fork_error_wakeup);
2078 pool->use_fork_error_wakeup = 0; /* gets set later if error occures during preparation */
2081 /* terminate excessive worker processes */
2082 while (
2083 pool->total_worker_count > pool->min_fork &&
2084 pool->idle_worker_count > pool->pre_fork
2085 ) {
2086 if (timerisset(&pool->exit_wakeup)) {
2087 if (timercmp(&pool->exit_wakeup, &now, >)) {
2088 moonbr_calc_wait(&wait, &pool->exit_wakeup);
2089 break;
2091 moonbr_terminate_idle_worker(moonbr_pop_idle_worker(pool));
2092 timeradd(&now, &pool->exit_delay, &pool->exit_wakeup);
2093 } else {
2094 timeradd(&now, &pool->exit_delay, &pool->exit_wakeup);
2095 break;
2098 if (!(
2099 pool->total_worker_count > pool->min_fork &&
2100 pool->idle_worker_count > pool->pre_fork
2101 )) {
2102 timerclear(&pool->exit_wakeup); /* timer gets restarted later when there are excessive workers */
2104 /* optionally output worker count stats */
2105 if (moonbr_stat && pool->worker_count_stat) {
2106 pool->worker_count_stat = 0;
2107 moonbr_log(
2108 LOG_INFO,
2109 "Worker count for pool #%i: %i idle, %i assigned, %i total",
2110 pool->poolnum, pool->idle_worker_count,
2111 pool->total_worker_count - pool->unassigned_worker_count,
2112 pool->total_worker_count);
2114 /* calculate wakeup time for interval listeners */
2115 for (listener=pool->first_idle_listener; listener; listener=listener->next_listener) {
2116 if (listener->proto == MOONBR_PROTO_INTERVAL) {
2117 moonbr_calc_wait(&wait, &listener->proto_specific.interval.wakeup);
2120 /* calculate wakeup time for idle workers (only first idle worker is significant) */
2121 if (timerisset(&pool->idle_timeout) && pool->first_idle_worker) {
2122 moonbr_calc_wait(&wait, &pool->first_idle_worker->idle_expiration);
2125 /* check if shutdown is complete */
2126 if (moonbr_shutdown_in_progress) {
2127 for (pool=moonbr_first_pool; pool; pool=pool->next_pool) {
2128 if (pool->first_worker) break;
2130 if (!pool) {
2131 moonbr_log(LOG_INFO, "All worker threads have terminated");
2132 moonbr_terminate(MOONBR_EXITCODE_GRACEFUL);
2135 if (moonbr_poll_refresh_needed) moonbr_poll_refresh();
2136 moonbr_cond_poll = 1;
2137 if (!moonbr_cond_child && !moonbr_cond_terminate && !moonbr_cond_interrupt) {
2138 int timeout;
2139 if (timerisset(&wait)) {
2140 if (timercmp(&wait, &now, <)) {
2141 moonbr_log(LOG_CRIT, "Internal error (should not happen): Future is in the past");
2142 moonbr_terminate_error();
2144 timersub(&wait, &now, &wait);
2145 timeout = wait.tv_sec * 1000 + wait.tv_usec / 1000;
2146 } else {
2147 timeout = INFTIM;
2149 if (moonbr_debug) {
2150 moonbr_log(LOG_DEBUG, "Waiting for I/O");
2152 poll(moonbr_poll_fds, moonbr_poll_fds_count, timeout);
2153 } else {
2154 if (moonbr_debug) {
2155 moonbr_log(LOG_DEBUG, "Do not wait for I/O");
2158 moonbr_cond_poll = 0;
2159 moonbr_poll_reset_signal();
2164 /*** Lua interface ***/
2166 static int moonbr_lua_panic(lua_State *L) {
2167 const char *errmsg;
2168 errmsg = lua_tostring(L, -1);
2169 if (!errmsg) {
2170 if (lua_isnoneornil(L, -1)) errmsg = "(error message is nil)";
2171 else errmsg = "(error message is not a string)";
2173 if (moonbr_pstate == MOONBR_PSTATE_FORKED) {
2174 fprintf(stderr, "Uncaught Lua error: %s\n", errmsg);
2175 exit(1);
2176 } else {
2177 moonbr_log(LOG_CRIT, "Uncaught Lua error: %s", errmsg);
2178 moonbr_terminate_error();
2180 return 0;
2183 static int moonbr_addtraceback(lua_State *L) {
2184 luaL_traceback(L, L, luaL_tolstring(L, 1, NULL), 1);
2185 return 1;
2188 /* Memory allocator that allows limiting memory consumption */
2189 static void *moonbr_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
2190 (void)ud; /* not used */
2191 if (nsize == 0) {
2192 if (ptr) {
2193 moonbr_memory_usage -= osize;
2194 free(ptr);
2196 return NULL;
2197 } else if (ptr) {
2198 if (
2199 moonbr_memory_limit &&
2200 nsize > osize &&
2201 moonbr_memory_usage + (nsize - osize) > moonbr_memory_limit
2202 ) {
2203 return NULL;
2204 } else {
2205 ptr = realloc(ptr, nsize);
2206 if (ptr) moonbr_memory_usage += nsize - osize;
2208 } else {
2209 if (
2210 moonbr_memory_limit &&
2211 moonbr_memory_usage + nsize > moonbr_memory_limit
2212 ) {
2213 return NULL;
2214 } else {
2215 ptr = realloc(ptr, nsize);
2216 if (ptr) moonbr_memory_usage += nsize;
2219 return ptr;
2222 /* New method for Lua file objects: read until terminator or length exceeded */
2223 static int moonbr_readuntil(lua_State *L) {
2224 luaL_Stream *stream;
2225 FILE *file;
2226 const char *terminatorstr;
2227 size_t terminatorlen;
2228 luaL_Buffer buf;
2229 lua_Integer maxlen;
2230 char terminator;
2231 int byte;
2232 stream = luaL_checkudata(L, 1, LUA_FILEHANDLE);
2233 terminatorstr = luaL_checklstring(L, 2, &terminatorlen);
2234 luaL_argcheck(L, terminatorlen == 1, 2, "single byte expected");
2235 maxlen = luaL_optinteger(L, 3, 0);
2236 if (!stream->closef) luaL_error(L, "attempt to use a closed file");
2237 file = stream->f;
2238 luaL_buffinit(L, &buf);
2239 if (!maxlen) maxlen = -1;
2240 terminator = terminatorstr[0];
2241 while (maxlen > 0 ? maxlen-- : maxlen) {
2242 byte = fgetc(file);
2243 if (byte == EOF) {
2244 if (ferror(file)) {
2245 char errmsg[MOONBR_MAXSTRERRORLEN];
2246 strerror_r(errno, errmsg, MOONBR_MAXSTRERRORLEN); /* use thread-safe call in case child created threads */
2247 luaL_error(L, "%s", errmsg);
2248 } else {
2249 break;
2252 luaL_addchar(&buf, byte);
2253 if (byte == terminator) break;
2255 luaL_pushresult(&buf);
2256 if (!lua_rawlen(L, -1)) lua_pushnil(L);
2257 return 1;
2260 static int moonbr_lua_tonatural(lua_State *L, int idx) {
2261 int isnum;
2262 lua_Number n;
2263 n = lua_tonumberx(L, idx, &isnum);
2264 if (isnum && n>=0 && n<INT_MAX && (lua_Number)(int)n == n) return n;
2265 else return -1;
2268 static int moonbr_lua_totimeval(lua_State *L, int idx, struct timeval *value) {
2269 int isnum;
2270 lua_Number n;
2271 n = lua_tonumberx(L, idx, &isnum);
2272 if (isnum && n>=0 && n<=100000000) {
2273 value->tv_sec = n;
2274 value->tv_usec = 1e6 * (n - value->tv_sec);
2275 return 1;
2276 } else {
2277 return 0;
2281 static int moonbr_timeout(lua_State *L) {
2282 struct itimerval oldval;
2283 if (lua_isnoneornil(L, 1) && lua_isnoneornil(L, 2)) {
2284 getitimer(ITIMER_REAL, &oldval);
2285 } else {
2286 struct itimerval newval = {};
2287 timerclear(&newval.it_interval);
2288 timerclear(&newval.it_value);
2289 if (lua_toboolean(L, 1)) {
2290 luaL_argcheck(
2291 L, moonbr_lua_totimeval(L, 1, &newval.it_value), 1,
2292 "interval in seconds expected"
2293 );
2295 if (lua_isnoneornil(L, 2)) {
2296 if (setitimer(ITIMER_REAL, &newval, &oldval)) {
2297 moonbr_log(LOG_CRIT, "Could not set ITIMER_REAL via setitimer()");
2298 moonbr_terminate_error();
2300 } else {
2301 getitimer(ITIMER_REAL, &oldval);
2302 if (!timerisset(&oldval.it_value)) {
2303 if (setitimer(ITIMER_REAL, &newval, NULL)) {
2304 moonbr_log(LOG_CRIT, "Could not set ITIMER_REAL via setitimer()");
2305 moonbr_terminate_error();
2307 lua_call(L, lua_gettop(L) - 2, LUA_MULTRET);
2308 timerclear(&newval.it_value);
2309 if (setitimer(ITIMER_REAL, &newval, NULL)) {
2310 moonbr_log(LOG_CRIT, "Could not set ITIMER_REAL via setitimer()");
2311 moonbr_terminate_error();
2313 } else if (timercmp(&newval.it_value, &oldval.it_value, <)) {
2314 struct itimerval remval;
2315 if (setitimer(ITIMER_REAL, &newval, NULL)) {
2316 moonbr_log(LOG_CRIT, "Could not set ITIMER_REAL via setitimer()");
2317 moonbr_terminate_error();
2319 lua_call(L, lua_gettop(L) - 2, LUA_MULTRET);
2320 getitimer(ITIMER_REAL, &remval);
2321 timersub(&oldval.it_value, &newval.it_value, &newval.it_value);
2322 timeradd(&newval.it_value, &remval.it_value, &newval.it_value);
2323 if (setitimer(ITIMER_REAL, &newval, NULL)) {
2324 moonbr_log(LOG_CRIT, "Could not set ITIMER_REAL via setitimer()");
2325 moonbr_terminate_error();
2327 } else {
2328 lua_call(L, lua_gettop(L) - 2, LUA_MULTRET);
2330 return lua_gettop(L) - 1;
2333 lua_pushnumber(L, oldval.it_value.tv_sec + 1e-6 * oldval.it_value.tv_usec);
2334 return 1;
2337 #define moonbr_listen_init_pool_forkoption(luaname, cname, defval) { \
2338 lua_getfield(L, 2, luaname); \
2339 pool->cname = lua_isnil(L, -1) ? (defval) : moonbr_lua_tonatural(L, -1); \
2340 } while(0)
2342 #define moonbr_listen_init_pool_timeoption(luaname, cname, defval, defvalu) ( \
2343 lua_getfield(L, 2, luaname), \
2344 lua_isnil(L, -1) ? ( \
2345 pool->cname.tv_sec = (defval), pool->cname.tv_usec = (defvalu), \
2346 1 \
2347 ) : ( \
2348 (lua_isboolean(L, -1) && !lua_toboolean(L, -1)) ? ( \
2349 pool->cname.tv_sec = 0, pool->cname.tv_usec = 0, \
2350 1 \
2351 ) : ( \
2352 moonbr_lua_totimeval(L, -1, &pool->cname) \
2353 ) \
2354 ) \
2357 static int moonbr_listen_init_pool(lua_State *L) {
2358 struct moonbr_pool *pool;
2359 const char *proto;
2360 int i;
2361 pool = lua_touserdata(L, 1);
2362 for (i=0; i<pool->listener_count; i++) {
2363 struct moonbr_listener *listener = &pool->listener[i];
2364 lua_settop(L, 2);
2365 #if LUA_VERSION_NUM >= 503
2366 lua_geti(L, 2, i+1);
2367 #else
2368 lua_pushinteger(L, i+1);
2369 lua_gettable(L, 2);
2370 #endif
2371 lua_getfield(L, 3, "proto");
2372 proto = lua_tostring(L, -1);
2373 if (proto && !strcmp(proto, "interval")) {
2374 listener->proto = MOONBR_PROTO_INTERVAL;
2375 lua_getfield(L, 3, "name");
2377 const char *name = lua_tostring(L, -1);
2378 if (name) {
2379 if (asprintf(&listener->proto_specific.interval.name, "%s", name) < 0) {
2380 moonbr_log(LOG_CRIT, "Memory allocation_error");
2381 moonbr_terminate_error();
2385 lua_getfield(L, 3, "delay");
2386 if (
2387 !moonbr_lua_totimeval(L, -1, &listener->proto_specific.interval.delay) ||
2388 !timerisset(&listener->proto_specific.interval.delay)
2389 ) {
2390 luaL_error(L, "No valid interval delay specified; use listen{{proto=\"interval\", delay=...}, ...}");
2392 lua_getfield(L, 3, "strict");
2393 if (!lua_isnil(L, -1)) {
2394 if (lua_isboolean(L, -1)) {
2395 if (lua_toboolean(L, -1)) listener->proto_specific.interval.strict = 1;
2396 } else {
2397 luaL_error(L, "Option \"strict\" must be a boolean if set; use listen{{proto=\"interval\", strict=true, ...}, ...}");
2400 } else if (proto && !strcmp(proto, "local")) {
2401 listener->proto = MOONBR_PROTO_LOCAL;
2402 lua_getfield(L, 3, "path");
2404 const char *path = lua_tostring(L, -1);
2405 if (!path) {
2406 luaL_error(L, "No valid path specified for local socket; use listen{{proto=\"local\", path=...}, ...}");
2408 if (asprintf(&listener->proto_specific.local.path, "%s", path) < 0) {
2409 moonbr_log(LOG_CRIT, "Memory allocation_error");
2410 moonbr_terminate_error();
2413 } else if (proto && !strcmp(proto, "tcp6")) {
2414 listener->proto = MOONBR_PROTO_TCP6;
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=\"tcp6\", 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=\"tcp6\", localhost=true, ...}, ...}");
2431 } else if (proto && !strcmp(proto, "tcp4")) {
2432 listener->proto = MOONBR_PROTO_TCP4;
2433 lua_getfield(L, 3, "port");
2434 listener->proto_specific.tcp.port = lua_tointeger(L, -1);
2435 if (
2436 listener->proto_specific.tcp.port < 1 ||
2437 listener->proto_specific.tcp.port > 65535
2438 ) {
2439 luaL_error(L, "No valid port number specified; use listen{{proto=\"tcp4\", port=...}, ...}");
2441 lua_getfield(L, 3, "localhost");
2442 if (!lua_isnil(L, -1)) {
2443 if (lua_isboolean(L, -1)) {
2444 if (lua_toboolean(L, -1)) listener->proto_specific.tcp.localhost_only = 1;
2445 } else {
2446 luaL_error(L, "Option \"localhost\" must be a boolean if set; use listen{{proto=\"tcp4\", localhost=true, ...}, ...}");
2451 lua_settop(L, 2);
2452 moonbr_listen_init_pool_forkoption("pre_fork", pre_fork, 1);
2453 moonbr_listen_init_pool_forkoption("min_fork", min_fork, pool->pre_fork > 2 ? pool->pre_fork : 2);
2454 moonbr_listen_init_pool_forkoption("max_fork", max_fork, pool->min_fork > 16 ? pool->min_fork : 16);
2455 if (!moonbr_listen_init_pool_timeoption("fork_delay", fork_delay, 1, 0)) {
2456 luaL_error(L, "Option \"fork_delay\" is expected to be a non-negative number");
2458 if (!moonbr_listen_init_pool_timeoption("fork_error_delay", fork_error_delay, 2, 0)) {
2459 luaL_error(L, "Option \"fork_error_delay\" is expected to be a non-negative number");
2461 if (!moonbr_listen_init_pool_timeoption("exit_delay", exit_delay, 60, 0)) {
2462 luaL_error(L, "Option \"exit_delay\" is expected to be a non-negative number");
2464 if (timercmp(&pool->fork_error_delay, &pool->fork_delay, <)) {
2465 pool->fork_error_delay = pool->fork_delay;
2467 if (!moonbr_listen_init_pool_timeoption("idle_timeout", idle_timeout, 0, 0)) {
2468 luaL_error(L, "Option \"idle_timeout\" is expected to be a non-negative number");
2470 lua_getfield(L, 2, "memory_limit");
2471 if (!lua_isnil(L, -1)) {
2472 int isnum;
2473 lua_Number n;
2474 n = lua_tonumberx(L, -1, &isnum);
2475 if (n < 0 || !isnum) {
2476 luaL_error(L, "Option \"memory_limit\" is expected to be a non-negative number");
2478 pool->memory_limit = n;
2480 lua_settop(L, 2);
2481 lua_getfield(L, 2, "prepare");
2482 if (!lua_isnil(L, -1) && !lua_isfunction(L, -1)) {
2483 luaL_error(L, "Option \"prepare\" must be nil or a function");
2485 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_prepare_func(pool));
2486 lua_getfield(L, 2, "connect");
2487 if (!lua_isfunction(L, -1)) {
2488 luaL_error(L, "Option \"connect\" must be a function; use listen{{...}, {...}, connect=function(socket) ... end, ...}");
2490 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_connect_func(pool));
2491 lua_getfield(L, 2, "finish");
2492 if (!lua_isnil(L, -1) && !lua_isfunction(L, -1)) {
2493 luaL_error(L, "Option \"finish\" must be nil or a function");
2495 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_finish_func(pool));
2496 return 0;
2499 static int moonbr_listen(lua_State *L) {
2500 struct moonbr_pool *pool;
2501 lua_Integer listener_count;
2502 if (moonbr_booted) luaL_error(L, "Moonbridge bootup is already complete");
2503 luaL_checktype(L, 1, LUA_TTABLE);
2504 listener_count = luaL_len(L, 1);
2505 if (!listener_count) luaL_error(L, "No listen ports specified; use listen{{proto=..., port=...},...}");
2506 if (listener_count > 100) luaL_error(L, "Too many listeners");
2507 pool = moonbr_create_pool(listener_count);
2508 lua_pushcfunction(L, moonbr_listen_init_pool);
2509 lua_pushlightuserdata(L, pool);
2510 lua_pushvalue(L, 1);
2511 if (lua_pcall(L, 2, 0, 0)) goto moonbr_listen_error;
2513 int i;
2514 i = moonbr_start_pool(pool);
2515 if (i >= 0) {
2516 struct moonbr_listener *listener = &pool->listener[i];
2517 switch (listener->proto) {
2518 case MOONBR_PROTO_INTERVAL:
2519 lua_pushfstring(L, "Could not initialize listener #%d (proto=\"interval\"): %s", i+1, strerror(errno));
2520 break;
2521 case MOONBR_PROTO_LOCAL:
2522 lua_pushfstring(L, "Could not initialize listener #%d (proto=\"local\", path=\"%s\"): %s", i+1, listener->proto_specific.local.path, strerror(errno));
2523 break;
2524 case MOONBR_PROTO_TCP6:
2525 lua_pushfstring(L, "Could not initialize listener #%d (proto=\"tcp6\", port=%d): %s", i+1, listener->proto_specific.tcp.port, strerror(errno));
2526 break;
2527 case MOONBR_PROTO_TCP4:
2528 lua_pushfstring(L, "Could not initialize listener #%d (proto=\"tcp4\", port=%d): %s", i+1, listener->proto_specific.tcp.port, strerror(errno));
2529 break;
2530 default:
2531 moonbr_log(LOG_ERR, "Internal error (should not happen): Unexpected value in listener.proto field");
2532 moonbr_terminate_error();
2534 goto moonbr_listen_error;
2537 return 0;
2538 moonbr_listen_error:
2539 moonbr_destroy_pool(pool);
2540 lua_pushnil(L);
2541 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_prepare_func(pool));
2542 lua_pushnil(L);
2543 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_connect_func(pool));
2544 lua_pushnil(L);
2545 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_finish_func(pool));
2546 lua_error(L);
2547 return 0; /* avoid compiler warning */
2551 /*** Function to modify Lua's library path and/or cpath ***/
2553 #if defined(MOONBR_LUA_PATH) || defined(MOONBR_LUA_CPATH)
2554 static void moonbr_modify_path(lua_State *L, char *key, char *value) {
2555 int stackbase;
2556 stackbase = lua_gettop(L);
2557 lua_getglobal(L, "package");
2558 lua_getfield(L, stackbase+1, key);
2560 const char *current_str;
2561 size_t current_strlen;
2562 luaL_Buffer buf;
2563 current_str = lua_tolstring(L, stackbase+2, &current_strlen);
2564 luaL_buffinit(L, &buf);
2565 if (current_str) {
2566 lua_pushvalue(L, stackbase+2);
2567 luaL_addvalue(&buf);
2568 if (current_strlen && current_str[current_strlen-1] != ';') {
2569 luaL_addchar(&buf, ';');
2572 luaL_addstring(&buf, value);
2573 luaL_pushresult(&buf);
2575 lua_setfield(L, stackbase+1, key);
2576 lua_settop(L, stackbase);
2578 #endif
2581 /*** Main function and command line invokation ***/
2583 static void moonbr_usage(int err, const char *cmd) {
2584 FILE *out;
2585 out = err ? stderr : stdout;
2586 if (!cmd) cmd = "moonbridge";
2587 fprintf(out, "Get this help message: %s {-h|--help}\n", cmd);
2588 fprintf(out, "Usage: %s \\\n", cmd);
2589 fprintf(out, " [-b|--background] \\\n");
2590 fprintf(out, " [-d|--debug] \\\n");
2591 fprintf(out, " [-f|--logfacility {DAEMON|USER|0|1|...|7}] \\\n");
2592 fprintf(out, " [-i|--logident <syslog ident> \\\n");
2593 fprintf(out, " [-l|--logfile <logfile>] \\\n");
2594 fprintf(out, " [-p|--pidfile <pidfile>] \\\n");
2595 fprintf(out, " [-s|--stats] \\\n");
2596 fprintf(out, " -- <Lua script> [<cmdline options for Lua script>]\n");
2597 exit(err);
2600 #define moonbr_usage_error() moonbr_usage(MOONBR_EXITCODE_CMDLINEERROR, argc ? argv[0] : NULL)
2602 int main(int argc, char **argv) {
2604 int daemonize = 0;
2605 int log_facility = LOG_USER;
2606 const char *log_ident = "moonbridge";
2607 const char *log_filename = NULL;
2608 const char *pid_filename = NULL;
2609 int option;
2610 struct option longopts[] = {
2611 { "background", no_argument, NULL, 'b' },
2612 { "debug", no_argument, NULL, 'd' },
2613 { "logfacility", required_argument, NULL, 'f' },
2614 { "help", no_argument, NULL, 'h' },
2615 { "logident", required_argument, NULL, 'i' },
2616 { "logfile", required_argument, NULL, 'l' },
2617 { "pidfile", required_argument, NULL, 'p' },
2618 { "stats", no_argument, NULL, 's' }
2619 };
2620 while ((option = getopt_long(argc, argv, "bdf:hi:l:p:s", longopts, NULL)) != -1) {
2621 switch (option) {
2622 case 'b':
2623 daemonize = 1;
2624 break;
2625 case 'd':
2626 moonbr_debug = 1;
2627 moonbr_stat = 1;
2628 break;
2629 case 'f':
2630 if (!strcmp(optarg, "DAEMON")) {
2631 log_facility = LOG_DAEMON;
2632 } else if (!strcmp(optarg, "USER")) {
2633 log_facility = LOG_USER;
2634 } else if (!strcmp(optarg, "0")) {
2635 log_facility = LOG_LOCAL0;
2636 } else if (!strcmp(optarg, "1")) {
2637 log_facility = LOG_LOCAL1;
2638 } else if (!strcmp(optarg, "2")) {
2639 log_facility = LOG_LOCAL2;
2640 } else if (!strcmp(optarg, "3")) {
2641 log_facility = LOG_LOCAL3;
2642 } else if (!strcmp(optarg, "4")) {
2643 log_facility = LOG_LOCAL4;
2644 } else if (!strcmp(optarg, "5")) {
2645 log_facility = LOG_LOCAL5;
2646 } else if (!strcmp(optarg, "6")) {
2647 log_facility = LOG_LOCAL6;
2648 } else if (!strcmp(optarg, "7")) {
2649 log_facility = LOG_LOCAL7;
2650 } else {
2651 moonbr_usage_error();
2653 moonbr_use_syslog = 1;
2654 break;
2655 case 'h':
2656 moonbr_usage(MOONBR_EXITCODE_GRACEFUL, argv[0]);
2657 break;
2658 case 'i':
2659 log_ident = optarg;
2660 moonbr_use_syslog = 1;
2661 break;
2662 case 'l':
2663 log_filename = optarg;
2664 break;
2665 case 'p':
2666 pid_filename = optarg;
2667 break;
2668 case 's':
2669 moonbr_stat = 1;
2670 break;
2671 default:
2672 moonbr_usage_error();
2675 if (argc - optind < 1) moonbr_usage_error();
2676 if (pid_filename) {
2677 pid_t otherpid;
2678 while ((moonbr_pidfh = pidfile_open(pid_filename, 0644, &otherpid)) == NULL) {
2679 if (errno == EEXIST) {
2680 if (otherpid == -1) {
2681 fprintf(stderr, "PID file \"%s\" is already locked\n", pid_filename);
2682 } else {
2683 fprintf(stderr, "PID file \"%s\" is already locked by process with PID: %i\n", pid_filename, (int)otherpid);
2685 exit(MOONBR_EXITCODE_ALREADYRUNNING);
2686 } else if (errno != EINTR) {
2687 fprintf(stderr, "Could not write PID file \"%s\": %s\n", pid_filename, strerror(errno));
2688 exit(MOONBR_EXITCODE_STARTUPERROR);
2692 if (log_filename) {
2693 int logfd;
2694 while (
2695 ( logfd = flopen(
2696 log_filename,
2697 O_WRONLY|O_NONBLOCK|O_CREAT|O_APPEND|O_CLOEXEC,
2698 0640
2700 ) < 0
2701 ) {
2702 if (errno == EWOULDBLOCK) {
2703 fprintf(stderr, "Logfile \"%s\" is locked\n", log_filename);
2704 exit(MOONBR_EXITCODE_ALREADYRUNNING);
2705 } else if (errno != EINTR) {
2706 fprintf(stderr, "Could not open logfile \"%s\": %s\n", log_filename, strerror(errno));
2707 exit(MOONBR_EXITCODE_STARTUPERROR);
2710 moonbr_logfile = fdopen(logfd, "a");
2711 if (!moonbr_logfile) {
2712 fprintf(stderr, "Could not open write stream to logfile \"%s\": %s\n", log_filename, strerror(errno));
2713 exit(MOONBR_EXITCODE_STARTUPERROR);
2716 if (daemonize == 0 && !moonbr_logfile) moonbr_logfile = stderr;
2717 if (moonbr_logfile) setlinebuf(moonbr_logfile);
2718 else moonbr_use_syslog = 1;
2719 if (moonbr_use_syslog) openlog(log_ident, LOG_NDELAY | LOG_PID, log_facility);
2720 if (daemonize) {
2721 if (daemon(1, 0)) {
2722 moonbr_log(LOG_ERR, "Could not daemonize moonbridge process");
2723 moonbr_terminate_error();
2727 moonbr_log(LOG_NOTICE, "Starting moonbridge server");
2728 if (moonbr_pidfh && pidfile_write(moonbr_pidfh)) {
2729 moonbr_log(LOG_ERR, "Could not write pidfile (after locking)");
2732 lua_State *L;
2733 L = lua_newstate(moonbr_alloc, NULL);
2734 if (!L) {
2735 moonbr_log(LOG_CRIT, "Could not initialize Lua state");
2736 moonbr_terminate_error();
2738 lua_atpanic(L, moonbr_lua_panic);
2739 luaL_openlibs(L);
2740 #ifdef MOONBR_LUA_PATH
2741 moonbr_modify_path(L, "path", MOONBR_LUA_PATH);
2742 #endif
2743 #ifdef MOONBR_LUA_CPATH
2744 moonbr_modify_path(L, "cpath", MOONBR_LUA_CPATH);
2745 #endif
2746 if (luaL_newmetatable(L, LUA_FILEHANDLE)) {
2747 moonbr_log(LOG_CRIT, "Lua metatable LUA_FILEHANDLE does not exist");
2748 moonbr_terminate_error();
2750 lua_getfield(L, -1, "__index");
2751 lua_pushcfunction(L, moonbr_readuntil);
2752 lua_setfield(L, -2, "readuntil");
2753 lua_pop(L, 2);
2754 lua_pushcfunction(L, moonbr_timeout);
2755 lua_setglobal(L, "timeout");
2756 lua_pushcfunction(L, moonbr_listen);
2757 lua_setglobal(L, "listen");
2758 lua_pushcfunction(L, moonbr_addtraceback); /* on stack position 1 */
2759 moonbr_log(LOG_INFO, "Loading \"%s\"", argv[optind]);
2760 if (luaL_loadfile(L, argv[optind])) {
2761 moonbr_log(LOG_ERR, "Error while loading \"%s\": %s", argv[optind], lua_tostring(L, -1));
2762 moonbr_terminate_error();
2764 { int i; for (i=optind+1; i<argc; i++) lua_pushstring(L, argv[i]); }
2765 if (lua_pcall(L, argc-(optind+1), 0, 1)) {
2766 moonbr_log(LOG_ERR, "Error while executing \"%s\": %s", argv[optind], lua_tostring(L, -1));
2767 moonbr_terminate_error();
2769 if (!moonbr_first_pool) {
2770 moonbr_log(LOG_WARNING, "No listener initialized.");
2771 moonbr_terminate_error();
2773 lua_getglobal(L, "listen");
2774 lua_pushcfunction(L, moonbr_listen);
2775 if (lua_compare(L, -2, -1, LUA_OPEQ)) {
2776 lua_pushnil(L);
2777 lua_setglobal(L, "listen");
2779 lua_settop(L, 1);
2780 moonbr_run(L);
2782 return 0;

Impressum / About Us