moonbridge

view moonbridge.c @ 57:439eece506ac

Removed explicit garbage collection while waiting for next request
author jbe
date Sun Mar 22 23:42:36 2015 +0100 (2015-03-22)
parents b3d04d528c83
children 16af76ba40a8
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 signal(SIGPIPE, SIG_IGN); /* generate I/O errors instead of signal 13 */
331 }
334 /*** Functions for logging in master process ***/
336 /* Logs a pre-formatted message with given syslog() priority */
337 static void moonbr_log_msg(int priority, const char *msg) {
338 if (moonbr_logfile) {
339 /* logging to logfile desired (timestamp is prepended in that case) */
340 time_t now_time = 0;
341 struct tm now_tmstruct;
342 char timestr[MOONBR_LOG_MAXTIMELEN+1];
343 time(&now_time);
344 localtime_r(&now_time, &now_tmstruct);
345 if (!strftime(
346 timestr, MOONBR_LOG_MAXTIMELEN+1, "%Y-%m-%d %H:%M:%S %Z: ", &now_tmstruct
347 )) timestr[0] = 0;
348 fprintf(moonbr_logfile, "%s%s\n", timestr, msg);
349 }
350 if (moonbr_use_syslog) {
351 /* logging through syslog desired */
352 syslog(priority, "%s", msg);
353 }
354 }
356 /* Formats a message via vsnprintf() and logs it with given syslog() priority */
357 static void moonbr_log(int priority, const char *message, ...) {
358 char msgbuf[MOONBR_LOG_MAXMSGLEN+1]; /* buffer of static size to store formatted message */
359 int msglen; /* length of full message (may exceed MOONBR_LOG_MAXMSGLEN) */
360 {
361 /* pass variable arguments to vsnprintf() to format message */
362 va_list ap;
363 va_start(ap, message);
364 msglen = vsnprintf(msgbuf, MOONBR_LOG_MAXMSGLEN+1, message, ap);
365 va_end(ap);
366 }
367 {
368 /* split and log message line by line */
369 char *line = msgbuf;
370 while (1) {
371 char *endptr = strchr(line, '\n');
372 if (endptr) {
373 /* terminate string where newline character is found */
374 *endptr = 0;
375 } else if (line != msgbuf && msglen > MOONBR_LOG_MAXMSGLEN) {
376 /* break if line is incomplete and not the first line */
377 break;
378 }
379 moonbr_log_msg(priority, line);
380 if (!endptr) break; /* break if end of formatted message is reached */
381 line = endptr+1; /* otherwise continue with remaining message */
382 }
383 }
384 if (msglen > MOONBR_LOG_MAXMSGLEN) {
385 /* print warning if message was truncated */
386 moonbr_log_msg(priority, "Previous log message has been truncated due to excessive length");
387 }
388 }
391 /*** Termination function ***/
393 /* Kill all child processes, remove PID file (if existent), and exit master process with given exitcode */
394 static void moonbr_terminate(int exitcode) {
395 {
396 struct moonbr_pool *pool;
397 for (pool=moonbr_first_pool; pool; pool=pool->next_pool) {
398 {
399 struct moonbr_worker *worker;
400 for (worker=pool->first_worker; worker; worker=worker->next_worker) {
401 moonbr_log(LOG_INFO, "Sending SIGKILL to child with PID %i", (int)worker->pid);
402 if (kill(worker->pid, SIGKILL)) {
403 moonbr_log(LOG_ERR, "Error while killing child process: %s", strerror(errno));
404 }
405 }
406 }
407 {
408 int i;
409 for (i=0; i<pool->listener_count; i++) {
410 struct moonbr_listener *listener = &pool->listener[i];
411 if (listener->proto == MOONBR_PROTO_LOCAL) {
412 moonbr_log(LOG_INFO, "Unlinking local socket \"%s\"", listener->proto_specific.local.path);
413 if (unlink(listener->proto_specific.local.path)) {
414 moonbr_log(LOG_ERR, "Error while unlinking local socket: %s", strerror(errno));
415 }
416 }
417 }
418 }
419 }
420 }
421 moonbr_log(exitcode ? LOG_ERR : LOG_NOTICE, "Terminating with exit code %i", exitcode);
422 if (moonbr_pidfh && pidfile_remove(moonbr_pidfh)) {
423 moonbr_log(LOG_ERR, "Error while removing PID file: %s", strerror(errno));
424 }
425 exit(exitcode);
426 }
428 /* Terminate with either MOONBR_EXITCODE_STARTUPERROR or MOONBR_EXITCODE_RUNTIMEERROR */
429 #define moonbr_terminate_error() \
430 moonbr_terminate( \
431 moonbr_pstate == MOONBR_PSTATE_STARTUP ? \
432 MOONBR_EXITCODE_STARTUPERROR : \
433 MOONBR_EXITCODE_RUNTIMEERROR \
434 )
437 /*** Helper functions ***/
439 /* Fills a 'struct timeval' structure with the current time (using CLOCK_MONOTONIC) */
440 static void moonbr_now(struct timeval *now) {
441 struct timespec ts = {0, };
442 if (clock_gettime(CLOCK_MONOTONIC, &ts)) {
443 moonbr_log(LOG_CRIT, "Error in clock_gettime() call: %s", strerror(errno));
444 moonbr_terminate_error();
445 }
446 *now = (struct timeval){ .tv_sec = ts.tv_sec, .tv_usec = ts.tv_nsec / 1000 };
447 }
449 /* Formats a 'struct timeval' value (not thread-safe) */
450 static char *moonbr_format_timeval(struct timeval *t) {
451 static char buf[32];
452 snprintf(buf, 32, "%ji.%06ji seconds", (intmax_t)t->tv_sec, (intmax_t)t->tv_usec);
453 return buf;
454 }
457 /*** Functions for pool creation and startup ***/
459 /* Creates a 'struct moonbr_pool' structure with a given number of listeners */
460 static struct moonbr_pool *moonbr_create_pool(int listener_count) {
461 struct moonbr_pool *pool;
462 pool = calloc(1,
463 sizeof(struct moonbr_pool) + /* size of 'struct moonbr_pool' with one listener */
464 (listener_count-1) * sizeof(struct moonbr_listener) /* size of extra listeners */
465 );
466 if (!pool) {
467 moonbr_log(LOG_CRIT, "Memory allocation error");
468 moonbr_terminate_error();
469 }
470 pool->listener_count = listener_count;
471 {
472 /* initialization of listeners */
473 int i;
474 for (i=0; i<listener_count; i++) {
475 struct moonbr_listener *listener = &pool->listener[i];
476 listener->pool = pool;
477 listener->listenfd = -1;
478 listener->pollidx = -1;
479 }
480 }
481 return pool;
482 }
484 /* Destroys a 'struct moonbr_pool' structure before it has been started */
485 static void moonbr_destroy_pool(struct moonbr_pool *pool) {
486 int i;
487 for (i=0; i<pool->listener_count; i++) {
488 struct moonbr_listener *listener = &pool->listener[i];
489 if (
490 listener->proto == MOONBR_PROTO_INTERVAL &&
491 listener->proto_specific.interval.name
492 ) {
493 free(listener->proto_specific.interval.name);
494 }
495 if (
496 listener->proto == MOONBR_PROTO_LOCAL &&
497 listener->proto_specific.local.path
498 ) {
499 free(listener->proto_specific.local.path);
500 }
501 }
502 free(pool);
503 }
505 /* Starts a all listeners in a pool */
506 static int moonbr_start_pool(struct moonbr_pool *pool) {
507 moonbr_log(LOG_INFO, "Creating pool", pool->poolnum);
508 {
509 int i;
510 for (i=0; i<pool->listener_count; i++) {
511 struct moonbr_listener *listener = &pool->listener[i];
512 switch (listener->proto) {
513 case MOONBR_PROTO_INTERVAL:
514 /* nothing to do here: starting intervals is performed in moonbr_run() function */
515 if (!listener->proto_specific.interval.name) {
516 moonbr_log(LOG_INFO, "Adding unnamed interval listener");
517 } else {
518 moonbr_log(LOG_INFO, "Adding interval listener \"%s\"", listener->proto_specific.interval.name);
519 }
520 break;
521 case MOONBR_PROTO_LOCAL:
522 moonbr_log(LOG_INFO, "Adding local socket listener for path \"%s\"", listener->proto_specific.local.path);
523 {
524 struct sockaddr_un servaddr = { .sun_family = AF_UNIX };
525 const int path_maxlen = sizeof(struct sockaddr_un) - (
526 (void *)&servaddr.sun_path - (void *)&servaddr
527 );
528 if (
529 snprintf(
530 servaddr.sun_path,
531 path_maxlen,
532 "%s",
533 listener->proto_specific.local.path
534 ) >= path_maxlen
535 ) {
536 errno = ENAMETOOLONG;
537 };
538 listener->listenfd = socket(PF_LOCAL, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
539 if (listener->listenfd == -1) goto moonbr_start_pool_error;
540 if (!unlink(listener->proto_specific.local.path)) {
541 moonbr_log(LOG_WARNING, "Unlinked named socket \"%s\" prior to listening", listener->proto_specific.local.path);
542 } else {
543 if (errno != ENOENT) {
544 moonbr_log(LOG_ERR, "Could not unlink named socket \"%s\" prior to listening: %s", listener->proto_specific.local.path, strerror(errno));
545 }
546 }
547 if (
548 bind(listener->listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr))
549 ) goto moonbr_start_pool_error;
550 if (listen(listener->listenfd, MOONBR_LISTEN_BACKLOG)) goto moonbr_start_pool_error;
551 }
552 break;
553 case MOONBR_PROTO_TCP6:
554 if (listener->proto_specific.tcp.localhost_only) {
555 moonbr_log(LOG_INFO, "Adding localhost TCP/IPv6 listener on port %i", listener->proto_specific.tcp.port);
556 } else {
557 moonbr_log(LOG_INFO, "Adding public TCP/IPv6 listener on port %i", listener->proto_specific.tcp.port);
558 }
559 {
560 struct sockaddr_in6 servaddr = {
561 .sin6_family = AF_INET6,
562 .sin6_port = htons(listener->proto_specific.tcp.port)
563 };
564 listener->listenfd = socket(PF_INET6, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
565 if (listener->listenfd == -1) goto moonbr_start_pool_error;
566 {
567 /* avoid "Address already in use" error when restarting service */
568 static const int reuseval = 1;
569 if (setsockopt(
570 listener->listenfd, SOL_SOCKET, SO_REUSEADDR, &reuseval, sizeof(reuseval)
571 )) goto moonbr_start_pool_error;
572 }
573 {
574 /* default to send TCP RST when process terminates unexpectedly */
575 static const struct linger lingerval = {
576 .l_onoff = 1,
577 .l_linger = 0
578 };
579 if (setsockopt(
580 listener->listenfd, SOL_SOCKET, SO_LINGER, &lingerval, sizeof(lingerval)
581 )) goto moonbr_start_pool_error;
582 }
583 if (listener->proto_specific.tcp.localhost_only) {
584 servaddr.sin6_addr.s6_addr[15] = 1;
585 }
586 if (
587 bind(listener->listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr))
588 ) goto moonbr_start_pool_error;
589 if (listen(listener->listenfd, MOONBR_LISTEN_BACKLOG)) goto moonbr_start_pool_error;
590 }
591 break;
592 case MOONBR_PROTO_TCP4:
593 if (listener->proto_specific.tcp.localhost_only) {
594 moonbr_log(LOG_INFO, "Adding localhost TCP/IPv4 listener on port %i", listener->proto_specific.tcp.port);
595 } else {
596 moonbr_log(LOG_INFO, "Adding public TCP/IPv4 listener on port %i", listener->proto_specific.tcp.port);
597 }
598 {
599 struct sockaddr_in servaddr = {
600 .sin_family = AF_INET,
601 .sin_port = htons(listener->proto_specific.tcp.port)
602 };
603 listener->listenfd = socket(PF_INET, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
604 if (listener->listenfd == -1) goto moonbr_start_pool_error;
605 {
606 /* avoid "Address already in use" error when restarting service */
607 static const int reuseval = 1;
608 if (setsockopt(
609 listener->listenfd, SOL_SOCKET, SO_REUSEADDR, &reuseval, sizeof(reuseval)
610 )) goto moonbr_start_pool_error;
611 }
612 {
613 /* default to send TCP RST when process terminates unexpectedly */
614 static const struct linger lingerval = {
615 .l_onoff = 1,
616 .l_linger = 0
617 };
618 if (setsockopt(
619 listener->listenfd, SOL_SOCKET, SO_LINGER, &lingerval, sizeof(lingerval)
620 )) goto moonbr_start_pool_error;
621 }
622 if (listener->proto_specific.tcp.localhost_only) {
623 ((uint8_t *)&servaddr.sin_addr.s_addr)[0] = 127;
624 ((uint8_t *)&servaddr.sin_addr.s_addr)[3] = 1;
625 }
626 if (
627 bind(listener->listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr))
628 ) goto moonbr_start_pool_error;
629 if (listen(listener->listenfd, MOONBR_LISTEN_BACKLOG)) goto moonbr_start_pool_error;
630 }
631 break;
632 default:
633 moonbr_log(LOG_CRIT, "Internal error (should not happen): Unexpected value in listener.proto field");
634 moonbr_terminate_error();
635 }
636 }
637 goto moonbr_start_pool_ok;
638 moonbr_start_pool_error:
639 {
640 int j = i;
641 int errno2 = errno;
642 for (; i>=0; i--) {
643 struct moonbr_listener *listener = &pool->listener[i];
644 if (listener->listenfd != -1) close(listener->listenfd);
645 }
646 errno = errno2;
647 return j;
648 }
649 }
650 moonbr_start_pool_ok:
651 pool->poolnum = ++moonbr_pool_count;
652 moonbr_log(LOG_INFO, "Pool #%i created", pool->poolnum);
653 if (moonbr_last_pool) moonbr_last_pool->next_pool = pool;
654 else moonbr_first_pool = pool;
655 moonbr_last_pool = pool;
656 return -1;
657 }
660 /*** Function to send data and a file descriptor to child process */
662 /* Sends control message of one bye plus optional file descriptor plus optional pointer to child process */
663 static void moonbr_send_control_message(struct moonbr_worker *worker, char status, int fd, void *ptr) {
664 {
665 struct iovec iovector = { .iov_base = &status, .iov_len = 1 }; /* carrying status byte */
666 char control_message_buffer[CMSG_SPACE(sizeof(int))] = {0, }; /* used to transfer file descriptor */
667 struct msghdr message = { .msg_iov = &iovector, .msg_iovlen = 1 }; /* data structure passed to sendmsg() call */
668 if (moonbr_debug) {
669 if (fd == -1) {
670 moonbr_log(LOG_DEBUG, "Sending control message \"%c\" to child process in pool #%i (PID %i)", (int)status, worker->pool->poolnum, (int)worker->pid);
671 } else {
672 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);
673 }
674 }
675 if (fd != -1) {
676 /* attach control message with file descriptor */
677 message.msg_control = control_message_buffer;
678 message.msg_controllen = CMSG_SPACE(sizeof(int));
679 {
680 struct cmsghdr *control_message = CMSG_FIRSTHDR(&message);
681 control_message->cmsg_level = SOL_SOCKET;
682 control_message->cmsg_type = SCM_RIGHTS;
683 control_message->cmsg_len = CMSG_LEN(sizeof(int));
684 memcpy(CMSG_DATA(control_message), &fd, sizeof(int));
685 }
686 }
687 while (sendmsg(worker->controlfd, &message, MSG_NOSIGNAL) < 0) {
688 if (errno == EPIPE) {
689 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));
690 return; /* do not close socket; socket is closed when reading from it */
691 }
692 if (errno != EINTR) {
693 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));
694 moonbr_terminate_error();
695 }
696 }
697 }
698 if (ptr) {
699 char buf[sizeof(void *)];
700 char *pos = buf;
701 int len = sizeof(void *);
702 ssize_t written;
703 if (moonbr_debug) {
704 moonbr_log(LOG_DEBUG, "Sending memory pointer to child process in pool #%i (PID %i)", (int)status, worker->pool->poolnum, (int)worker->pid);
705 }
706 memcpy(buf, &ptr, sizeof(void *));
707 while (len) {
708 written = send(worker->controlfd, pos, len, MSG_NOSIGNAL);
709 if (written > 0) {
710 pos += written;
711 len -= written;
712 } else if (errno == EPIPE) {
713 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));
714 return; /* do not close socket; socket is closed when reading from it */
715 } else if (errno != EINTR) {
716 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));
717 moonbr_terminate_error();
718 }
719 }
720 }
721 }
724 /*** Functions running in child process ***/
726 /* Logs an error in child process */
727 static void moonbr_child_log(const char *message) {
728 fprintf(stderr, "%s\n", message);
729 }
731 /* Logs a fatal error in child process and terminates process with error status */
732 static void moonbr_child_log_fatal(const char *message) {
733 moonbr_child_log(message);
734 exit(1);
735 }
737 /* Logs an error in child process while appending error string for global errno variable */
738 static void moonbr_child_log_errno(const char *message) {
739 char errmsg[MOONBR_MAXSTRERRORLEN];
740 strerror_r(errno, errmsg, MOONBR_MAXSTRERRORLEN); /* use thread-safe call in case child created threads */
741 fprintf(stderr, "%s: %s\n", message, errmsg);
742 }
744 /* Logs a fatal error in child process while appending error string for errno and terminating process */
745 static void moonbr_child_log_errno_fatal(const char *message) {
746 moonbr_child_log_errno(message);
747 exit(1);
748 }
750 /* Receives a control message consisting of one character plus an optional file descriptor from parent process */
751 static void moonbr_child_receive_control_message(int socketfd, char *status, int *fd) {
752 struct iovec iovector = { .iov_base = status, .iov_len = 1 }; /* reference to status byte variable */
753 char control_message_buffer[CMSG_SPACE(sizeof(int))] = {0, }; /* used to receive file descriptor */
754 struct msghdr message = { /* data structure passed to recvmsg() call */
755 .msg_iov = &iovector,
756 .msg_iovlen = 1,
757 .msg_control = control_message_buffer,
758 .msg_controllen = CMSG_SPACE(sizeof(int))
759 };
760 {
761 int received;
762 while ((received = recvmsg(socketfd, &message, MSG_CMSG_CLOEXEC)) < 0) {
763 if (errno != EINTR) {
764 moonbr_child_log_errno_fatal("Error while trying to receive connection socket from parent process");
765 }
766 }
767 if (!received) {
768 moonbr_child_log_fatal("Unexpected EOF while trying to receive connection socket from parent process");
769 }
770 }
771 {
772 struct cmsghdr *control_message = CMSG_FIRSTHDR(&message);
773 if (control_message) {
774 if (control_message->cmsg_level != SOL_SOCKET) {
775 moonbr_child_log_fatal("Received control message with cmsg_level not equal to SOL_SOCKET");
776 }
777 if (control_message->cmsg_type != SCM_RIGHTS) {
778 moonbr_child_log_fatal("Received control message with cmsg_type not equal to SCM_RIGHTS");
779 }
780 memcpy(fd, CMSG_DATA(control_message), sizeof(int));
781 } else {
782 *fd = -1;
783 }
784 }
785 }
787 /* Receives a pointer from parent process */
788 static void *moonbr_child_receive_pointer(int socketfd) {
789 char buf[sizeof(void *)];
790 char *pos = buf;
791 int len = sizeof(void *);
792 ssize_t bytes_read;
793 while (len) {
794 bytes_read = recv(socketfd, pos, len, 0);
795 if (bytes_read > 0) {
796 pos += bytes_read;
797 len -= bytes_read;
798 } else if (!bytes_read) {
799 moonbr_child_log_fatal("Unexpected EOF while trying to receive memory pointer from parent process");
800 } else if (errno != EINTR) {
801 moonbr_child_log_errno_fatal("Error while trying to receive memory pointer from parent process");
802 }
803 }
804 {
805 void *ptr; /* avoid breaking strict-aliasing rules */
806 memcpy(&ptr, buf, sizeof(void *));
807 return ptr;
808 }
809 }
811 /* Closes the input stream from peer unless it has already been closed */
812 static int moonbr_child_close_peersocket_inputstream(
813 int cleanshut, /* nonzero = use shutdown() if applicable */
814 int mark /* nonzero = mark the stream as closed for Lua */
815 ) {
816 int err = 0; /* nonzero = error occurred */
817 int errno2; /* stores previous errno values that take precedence */
818 if (moonbr_child_peersocket_inputstream->f) {
819 /* NOTE: shutdown() with SHUT_RD shows different behavior on different
820 * operating systems and particularly causes problems with Linux. Hence it
821 * is disabled here. */
822 /*
823 if (cleanshut && moonbr_child_peersocket_type == MOONBR_SOCKETTYPE_NETWORK) {
824 if (shutdown(moonbr_child_peersocket_fd, SHUT_RD)) {
825 errno2 = errno;
826 err = -1;
827 }
828 }
829 */
830 if (fclose(moonbr_child_peersocket_inputstream->f)) {
831 if (!err) errno2 = errno;
832 err = -1;
833 }
834 moonbr_child_peersocket_inputstream->f = NULL;
835 }
836 if (mark) moonbr_child_peersocket_inputstream->closef = NULL;
837 if (err) errno = errno2;
838 return err;
839 }
841 /* Closes the output stream to peer unless it has already been closed */
842 static int moonbr_child_close_peersocket_outputstream(
843 int cleanshut, /* nonzero = use fflush() and shutdown() if applicable */
844 int mark /* nonzero = mark the stream as closed for Lua */
845 ) {
846 int err = 0; /* nonzero = error occurred */
847 int errno2; /* stores previous errno values that take precedence */
848 if (moonbr_child_peersocket_outputstream->f) {
849 if (moonbr_child_peersocket_type == MOONBR_SOCKETTYPE_NETWORK) {
850 if (cleanshut) {
851 if (fflush(moonbr_child_peersocket_outputstream->f)) {
852 errno2 = errno;
853 err = -1;
854 } else {
855 if (shutdown(moonbr_child_peersocket_fd, SHUT_WR)) {
856 errno2 = errno;
857 err = -1;
858 }
859 }
860 } else {
861 fpurge(moonbr_child_peersocket_outputstream->f);
862 }
863 }
864 if (fclose(moonbr_child_peersocket_outputstream->f)) {
865 if (!err) errno2 = errno;
866 err = -1;
867 }
868 moonbr_child_peersocket_outputstream->f = NULL;
869 }
870 if (mark) moonbr_child_peersocket_outputstream->closef = NULL;
871 if (err) errno = errno2;
872 return err;
873 }
875 /* Perform a clean shutdown of input and output stream (may be called multiple times) */
876 static int moonbr_child_close_peersocket(int timeout) {
877 int errprio = 0;
878 int errno2;
879 if (moonbr_child_peersocket_fd == -1) return 0;
880 if (moonbr_child_close_peersocket_inputstream(1, 1)) {
881 errprio = 1;
882 errno2 = errno;
883 }
884 if (moonbr_child_close_peersocket_outputstream(1, 1)) {
885 errprio = 4;
886 errno2 = errno;
887 }
888 if (moonbr_child_peersocket_type == MOONBR_SOCKETTYPE_NETWORK) {
889 struct linger lingerval = { 0, };
890 if (timeout && !errprio) {
891 lingerval.l_onoff = 1;
892 lingerval.l_linger = timeout;
893 }
894 if (setsockopt(moonbr_child_peersocket_fd, SOL_SOCKET, SO_LINGER, &lingerval, sizeof(lingerval))) {
895 if (errprio < 2) {
896 errprio = 2;
897 errno2 = errno;
898 }
899 }
900 }
901 if (close(moonbr_child_peersocket_fd)) {
902 if (errprio < 3) {
903 errprio = 3;
904 errno2 = errno;
905 }
906 }
907 moonbr_child_peersocket_fd = -1;
908 if (errprio) {
909 errno = errno2;
910 return -1;
911 }
912 return 0;
913 }
915 /* Close socket and cause reset of TCP connection (TCP RST aka "Connection reset by peer") if possible */
916 static int moonbr_child_cancel_peersocket() {
917 int err = 0;
918 if (moonbr_child_close_peersocket_inputstream(0, 1)) err = -1;
919 if (moonbr_child_close_peersocket_outputstream(0, 1)) err = -1;
920 if (close(moonbr_child_peersocket_fd)) err = -1;
921 moonbr_child_peersocket_fd = -1;
922 return err;
923 }
925 /* Lua method for socket object to read from input stream */
926 static int moonbr_child_lua_read_stream(lua_State *L) {
927 lua_getfield(L, 1, "input");
928 lua_getfield(L, -1, "read");
929 lua_insert(L, 1);
930 lua_replace(L, 2);
931 lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
932 return lua_gettop(L);
933 }
935 /* Lua method for socket object to read from input stream until terminator */
936 static int moonbr_child_lua_readuntil_stream(lua_State *L) {
937 lua_getfield(L, 1, "input");
938 lua_getfield(L, -1, "readuntil");
939 lua_insert(L, 1);
940 lua_replace(L, 2);
941 lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
942 return lua_gettop(L);
943 }
945 /* Lua method for socket object to iterate over input stream */
946 static int moonbr_child_lua_lines_stream(lua_State *L) {
947 lua_getfield(L, 1, "input");
948 lua_getfield(L, -1, "lines");
949 lua_insert(L, 1);
950 lua_replace(L, 2);
951 lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
952 return lua_gettop(L);
953 }
955 /* Lua method for socket object to write to output stream */
956 static int moonbr_child_lua_write_stream(lua_State *L) {
957 lua_getfield(L, 1, "output");
958 lua_getfield(L, -1, "write");
959 lua_insert(L, 1);
960 lua_replace(L, 2);
961 lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
962 return lua_gettop(L);
963 }
965 /* Lua method for socket object to flush the output stream */
966 static int moonbr_child_lua_flush_stream(lua_State *L) {
967 lua_getfield(L, 1, "output");
968 lua_getfield(L, -1, "flush");
969 lua_insert(L, 1);
970 lua_replace(L, 2);
971 lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
972 return lua_gettop(L);
973 }
975 /* Lua function to close a single stream (input or output) from/to peer */
976 static int moonbr_child_lua_close_stream(lua_State *L) {
977 luaL_Stream *stream = lua_touserdata(L, 1);
978 if (stream == moonbr_child_peersocket_inputstream) {
979 if (moonbr_child_close_peersocket_inputstream(1, 0)) { /* don't mark as closed as it's done by Lua */
980 char errmsg[MOONBR_MAXSTRERRORLEN];
981 strerror_r(errno, errmsg, MOONBR_MAXSTRERRORLEN); /* use thread-safe call in case child created threads */
982 lua_pushnil(L);
983 lua_pushfstring(L, "Could not close input stream from peer: %s", errmsg);
984 return 2;
985 }
986 } else if (stream == moonbr_child_peersocket_outputstream) {
987 if (moonbr_child_close_peersocket_outputstream(1, 0)) { /* don't mark as closed as it's done by Lua */
988 char errmsg[MOONBR_MAXSTRERRORLEN];
989 strerror_r(errno, errmsg, MOONBR_MAXSTRERRORLEN); /* use thread-safe call in case child created threads */
990 lua_pushnil(L);
991 lua_pushfstring(L, "Could not close output stream to peer: %s", errmsg);
992 return 2;
993 }
994 } else {
995 luaL_argerror(L, 1, "Not a connection socket");
996 }
997 lua_pushboolean(L, 1);
998 return 1;
999 }
1001 /* Lua function to close both input and output stream from/to peer */
1002 static int moonbr_child_lua_close_both_streams(lua_State *L) {
1003 int timeout = 0;
1004 if (!lua_isnoneornil(L, 2)) {
1005 lua_Integer n = luaL_checkinteger(L, 2);
1006 luaL_argcheck(L, n >= 0 && n <= INT_MAX, 2, "out of range");
1007 timeout = n;
1009 if (moonbr_child_peersocket_fd == -1) {
1010 luaL_error(L, "Connection with peer has already been explicitly closed");
1012 if (moonbr_child_close_peersocket(timeout)) {
1013 char errmsg[MOONBR_MAXSTRERRORLEN];
1014 strerror_r(errno, errmsg, MOONBR_MAXSTRERRORLEN); /* use thread-safe call in case child created threads */
1015 lua_pushnil(L);
1016 lua_pushfstring(L, "Could not close socket connection with peer: %s", errmsg);
1017 return 2;
1019 lua_pushboolean(L, 1);
1020 return 1;
1023 /* Lua function to close both input and output stream from/to peer */
1024 static int moonbr_child_lua_cancel_both_streams(lua_State *L) {
1025 if (moonbr_child_peersocket_fd == -1) {
1026 luaL_error(L, "Connection with peer has already been explicitly closed");
1028 if (moonbr_child_cancel_peersocket()) {
1029 char errmsg[MOONBR_MAXSTRERRORLEN];
1030 strerror_r(errno, errmsg, MOONBR_MAXSTRERRORLEN); /* use thread-safe call in case child created threads */
1031 lua_pushnil(L);
1032 lua_pushfstring(L, "Could not cancel socket connection with peer: %s", errmsg);
1033 return 2;
1035 lua_pushboolean(L, 1);
1036 return 1;
1039 /* Methods of (bidirectional) socket object passed to handler */
1040 static luaL_Reg moonbr_child_lua_socket_functions[] = {
1041 {"read", moonbr_child_lua_read_stream},
1042 {"readuntil", moonbr_child_lua_readuntil_stream},
1043 {"lines", moonbr_child_lua_lines_stream},
1044 {"write", moonbr_child_lua_write_stream},
1045 {"flush", moonbr_child_lua_flush_stream},
1046 {"close", moonbr_child_lua_close_both_streams},
1047 {"cancel", moonbr_child_lua_cancel_both_streams},
1048 {NULL, NULL}
1049 };
1051 /* Main function of child process to be called after fork() and file descriptor rearrangement */
1052 void moonbr_child_run(struct moonbr_pool *pool, lua_State *L) {
1053 char controlmsg;
1054 struct itimerval notimer = { { 0, }, { 0, } };
1055 lua_rawgetp(L, LUA_REGISTRYINDEX, moonbr_luakey_prepare_func(pool));
1056 if (lua_isnil(L, -1)) lua_pop(L, 1);
1057 else if (lua_pcall(L, 0, 0, 1)) {
1058 fprintf(stderr, "Error in \"prepare\" function: %s\n", lua_tostring(L, -1));
1059 exit(1);
1061 while (1) {
1062 struct moonbr_listener *listener;
1063 if (setitimer(ITIMER_REAL, &notimer, NULL)) {
1064 moonbr_child_log_errno_fatal("Could not reset ITIMER_REAL via setitimer()");
1066 controlmsg = MOONBR_STATUS_IDLE;
1067 if (write(MOONBR_FD_CONTROL, &controlmsg, 1) <= 0) {
1068 moonbr_child_log_errno_fatal("Error while sending ready message to parent process");
1070 moonbr_child_receive_control_message(
1071 MOONBR_FD_CONTROL,
1072 &controlmsg,
1073 &moonbr_child_peersocket_fd
1074 );
1075 if (!(
1076 (controlmsg == MOONBR_COMMAND_TERMINATE && moonbr_child_peersocket_fd == -1) ||
1077 (controlmsg == MOONBR_SOCKETTYPE_INTERVAL && moonbr_child_peersocket_fd == -1) ||
1078 (controlmsg == MOONBR_SOCKETTYPE_LOCAL && moonbr_child_peersocket_fd != -1) ||
1079 (controlmsg == MOONBR_SOCKETTYPE_NETWORK && moonbr_child_peersocket_fd != -1)
1080 )) {
1081 moonbr_child_log_fatal("Received illegal control message from parent process");
1083 if (controlmsg == MOONBR_COMMAND_TERMINATE) break;
1084 listener = moonbr_child_receive_pointer(MOONBR_FD_CONTROL);
1085 moonbr_child_peersocket_type = controlmsg;
1086 if (moonbr_child_peersocket_fd != -1) {
1088 int clonedfd;
1089 clonedfd = dup(moonbr_child_peersocket_fd);
1090 if (!clonedfd) {
1091 moonbr_child_log_errno_fatal("Could not duplicate file descriptor for input stream");
1093 moonbr_child_peersocket_inputstream = lua_newuserdata(L, sizeof(luaL_Stream));
1094 if (!moonbr_child_peersocket_inputstream) {
1095 moonbr_child_log_fatal("Memory allocation error");
1097 moonbr_child_peersocket_inputstream->f = fdopen(clonedfd, "rb");
1098 if (!moonbr_child_peersocket_inputstream->f) {
1099 moonbr_child_log_errno_fatal("Could not open input stream for remote connection");
1101 moonbr_child_peersocket_inputstream->closef = moonbr_child_lua_close_stream;
1102 if (luaL_newmetatable(L, LUA_FILEHANDLE)) {
1103 moonbr_child_log_fatal("Lua metatable LUA_FILEHANDLE does not exist");
1105 lua_setmetatable(L, -2);
1108 int clonedfd;
1109 clonedfd = dup(moonbr_child_peersocket_fd);
1110 if (!clonedfd) {
1111 moonbr_child_log_errno_fatal("Could not duplicate file descriptor for output stream");
1113 moonbr_child_peersocket_outputstream = lua_newuserdata(L, sizeof(luaL_Stream));
1114 if (!moonbr_child_peersocket_outputstream) {
1115 moonbr_child_log_fatal("Memory allocation error");
1117 moonbr_child_peersocket_outputstream->f = fdopen(clonedfd, "wb");
1118 if (!moonbr_child_peersocket_outputstream->f) {
1119 moonbr_child_log_errno_fatal("Could not open output stream for remote connection");
1121 moonbr_child_peersocket_outputstream->closef = moonbr_child_lua_close_stream;
1122 if (luaL_newmetatable(L, LUA_FILEHANDLE)) {
1123 moonbr_child_log_fatal("Lua metatable LUA_FILEHANDLE does not exist");
1125 lua_setmetatable(L, -2);
1128 lua_rawgetp(L, LUA_REGISTRYINDEX, moonbr_luakey_connect_func(pool));
1129 if (listener->proto == MOONBR_PROTO_INTERVAL) {
1130 lua_newtable(L);
1131 lua_pushstring(L,
1132 listener->proto_specific.interval.name ?
1133 listener->proto_specific.interval.name : ""
1134 );
1135 lua_setfield(L, -2, "interval");
1136 } else {
1137 lua_newtable(L);
1138 lua_pushvalue(L, -4);
1139 lua_setfield(L, -2, "input");
1140 lua_pushvalue(L, -3);
1141 lua_setfield(L, -2, "output");
1142 luaL_setfuncs(L, moonbr_child_lua_socket_functions, 0);
1143 if (listener->proto == MOONBR_PROTO_TCP6) {
1144 struct sockaddr_in6 addr;
1145 socklen_t addr_len = sizeof(struct sockaddr_in6);
1146 if (getsockname(moonbr_child_peersocket_fd, (struct sockaddr *)&addr, &addr_len)) {
1147 moonbr_child_log_errno("Could not get local IP address/port");
1148 } else {
1149 lua_pushlstring(L, (char *)addr.sin6_addr.s6_addr, 16);
1150 lua_setfield(L, -2, "local_ip6");
1151 lua_pushinteger(L, ntohs(addr.sin6_port));
1152 lua_setfield(L, -2, "local_tcpport");
1154 if (getpeername(moonbr_child_peersocket_fd, (struct sockaddr *)&addr, &addr_len)) {
1155 moonbr_child_log_errno("Could not get remote IP address/port");
1156 } else {
1157 lua_pushlstring(L, (char *)addr.sin6_addr.s6_addr, 16);
1158 lua_setfield(L, -2, "remote_ip6");
1159 lua_pushinteger(L, ntohs(addr.sin6_port));
1160 lua_setfield(L, -2, "remote_tcpport");
1162 } else if (listener->proto == MOONBR_PROTO_TCP4) {
1163 struct sockaddr_in addr;
1164 socklen_t addr_len = sizeof(struct sockaddr_in);
1165 if (getsockname(moonbr_child_peersocket_fd, (struct sockaddr *)&addr, &addr_len)) {
1166 moonbr_child_log_errno("Could not get local IP address/port");
1167 } else {
1168 lua_pushlstring(L, (char *)&addr.sin_addr.s_addr, 4);
1169 lua_setfield(L, -2, "local_ip4");
1170 lua_pushinteger(L, ntohs(addr.sin_port));
1171 lua_setfield(L, -2, "local_tcpport");
1173 if (getpeername(moonbr_child_peersocket_fd, (struct sockaddr *)&addr, &addr_len)) {
1174 moonbr_child_log_errno("Could not get remote IP address/port");
1175 } else {
1176 lua_pushlstring(L, (char *)&addr.sin_addr.s_addr, 4);
1177 lua_setfield(L, -2, "remote_ip4");
1178 lua_pushinteger(L, ntohs(addr.sin_port));
1179 lua_setfield(L, -2, "remote_tcpport");
1183 if (lua_pcall(L, 1, 1, 1)) {
1184 fprintf(stderr, "Error in \"connect\" function: %s\n", lua_tostring(L, -1));
1185 exit(1);
1187 if (moonbr_child_close_peersocket(0)) {
1188 moonbr_child_log_errno("Could not close socket connection with peer");
1190 if (lua_type(L, -1) != LUA_TBOOLEAN || !lua_toboolean(L, -1)) break;
1191 #ifdef MOONBR_LUA_PANIC_BUG_WORKAROUND
1192 lua_settop(L, 2);
1193 #else
1194 lua_settop(L, 1);
1195 #endif
1197 controlmsg = MOONBR_STATUS_GOODBYE;
1198 if (write(MOONBR_FD_CONTROL, &controlmsg, 1) <= 0) {
1199 moonbr_child_log_errno_fatal("Error while sending goodbye message to parent process");
1201 if (close(MOONBR_FD_CONTROL) && errno != EINTR) {
1202 moonbr_child_log_errno("Error while closing control socket");
1204 lua_rawgetp(L, LUA_REGISTRYINDEX, moonbr_luakey_finish_func(pool));
1205 if (lua_isnil(L, -1)) lua_pop(L, 1);
1206 else if (lua_pcall(L, 0, 0, 1)) {
1207 fprintf(stderr, "Error in \"finish\" function: %s\n", lua_tostring(L, -1));
1208 exit(1);
1210 lua_close(L);
1211 exit(0);
1215 /*** Functions to spawn child process ***/
1217 /* Helper function to send an error message to a file descriptor (not needing a file stream) */
1218 static void moonbr_child_emergency_print(int fd, char *message) {
1219 size_t len = strlen(message);
1220 ssize_t written;
1221 while (len) {
1222 written = write(fd, message, len);
1223 if (written > 0) {
1224 message += written;
1225 len -= written;
1226 } else {
1227 if (written != -1 || errno != EINTR) break;
1232 /* Helper function to send an error message plus a text for errno to a file descriptor and terminate the process */
1233 static void moonbr_child_emergency_error(int fd, char *message) {
1234 int errno2 = errno;
1235 moonbr_child_emergency_print(fd, message);
1236 moonbr_child_emergency_print(fd, ": ");
1237 moonbr_child_emergency_print(fd, strerror(errno2));
1238 moonbr_child_emergency_print(fd, "\n");
1239 exit(1);
1242 /* Creates a child process and (in case of success) registers it in the 'struct moonbr_pool' structure */
1243 static int moonbr_create_worker(struct moonbr_pool *pool, lua_State *L) {
1244 struct moonbr_worker *worker;
1245 worker = calloc(1, sizeof(struct moonbr_worker));
1246 if (!worker) {
1247 moonbr_log(LOG_CRIT, "Memory allocation error");
1248 return -1;
1250 worker->pool = pool;
1252 int controlfds[2];
1253 int errorfds[2];
1254 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, controlfds)) {
1255 moonbr_log(LOG_ERR, "Could not create control socket pair for communcation with child process: %s", strerror(errno));
1256 free(worker);
1257 return -1;
1259 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, errorfds)) {
1260 moonbr_log(LOG_ERR, "Could not create socket pair to redirect stderr of child process: %s", strerror(errno));
1261 close(controlfds[0]);
1262 close(controlfds[1]);
1263 free(worker);
1264 return -1;
1266 if (moonbr_logfile && fflush(moonbr_logfile)) {
1267 moonbr_log(LOG_CRIT, "Could not flush log file prior to forking: %s", strerror(errno));
1268 moonbr_terminate_error();
1270 worker->pid = fork();
1271 if (worker->pid == -1) {
1272 moonbr_log(LOG_ERR, "Could not fork: %s", strerror(errno));
1273 close(controlfds[0]);
1274 close(controlfds[1]);
1275 close(errorfds[0]);
1276 close(errorfds[1]);
1277 free(worker);
1278 return -1;
1279 } else if (!worker->pid) {
1280 moonbr_pstate = MOONBR_PSTATE_FORKED;
1281 #ifdef MOONBR_LUA_PANIC_BUG_WORKAROUND
1282 lua_pushliteral(L, "Failed to pass error message due to bug in Lua panic handler (hint: not enough memory?)");
1283 #endif
1284 moonbr_memory_limit = pool->memory_limit;
1285 if (moonbr_pidfh && pidfile_close(moonbr_pidfh)) {
1286 moonbr_child_emergency_error(errorfds[1], "Could not close PID file in forked child process");
1288 if (moonbr_logfile && moonbr_logfile != stderr && fclose(moonbr_logfile)) {
1289 moonbr_child_emergency_error(errorfds[1], "Could not close log file in forked child process");
1291 if (dup2(errorfds[1], MOONBR_FD_STDERR) == -1) {
1292 moonbr_child_emergency_error(errorfds[1], "Could not duplicate socket to stderr file descriptor");
1294 if (dup2(controlfds[1], MOONBR_FD_CONTROL) == -1) {
1295 moonbr_child_emergency_error(errorfds[1], "Could not duplicate control socket");
1297 closefrom(MOONBR_FD_END);
1298 moonbr_child_run(pool, L);
1300 if (moonbr_stat) {
1301 moonbr_log(LOG_INFO, "Created new worker in pool #%i with PID %i", worker->pool->poolnum, (int)worker->pid);
1303 worker->controlfd = controlfds[0];
1304 worker->errorfd = errorfds[0];
1305 if (close(controlfds[1]) && errno != EINTR) {
1306 moonbr_log(LOG_CRIT, "Could not close opposite end of control file descriptor after forking");
1307 moonbr_terminate_error();
1309 if (close(errorfds[1]) && errno != EINTR) {
1310 moonbr_log(LOG_CRIT, "Could not close opposite end of control file descriptor after forking");
1311 moonbr_terminate_error();
1314 worker->prev_worker = pool->last_worker;
1315 if (worker->prev_worker) worker->prev_worker->next_worker = worker;
1316 else pool->first_worker = worker;
1317 pool->last_worker = worker;
1318 pool->unassigned_worker_count++;
1319 pool->total_worker_count++;
1320 pool->worker_count_stat = 1;
1321 moonbr_poll_refresh_needed = 1;
1322 return 0; /* return zero only in case of success */
1326 /*** Functions to handle previously created 'struct moonbr_worker' structures ***/
1328 #define moonbr_try_destroy_worker_stat(str, field) \
1329 moonbr_log(LOG_INFO, "Resource usage in pool #%i for PID %i: " str " %li", worker->pool->poolnum, (int)worker->pid, (long)childusage.field);
1331 /* Destroys a worker structure if socket connections have been closed and child process has terminated */
1332 static int moonbr_try_destroy_worker(struct moonbr_worker *worker) {
1333 if (worker->controlfd != -1 || worker->errorfd != -1) return MOONBR_DESTROY_NONE;
1335 int childstatus;
1336 struct rusage childusage;
1338 pid_t waitedpid;
1339 while (
1340 (waitedpid = wait4(worker->pid, &childstatus, WNOHANG, &childusage)) == -1
1341 ) {
1342 if (errno != EINTR) {
1343 moonbr_log(LOG_CRIT, "Error in wait4() call: %s", strerror(errno));
1344 moonbr_terminate_error();
1347 if (!waitedpid) return 0; /* return 0 if worker couldn't be destroyed */
1348 if (waitedpid != worker->pid) {
1349 moonbr_log(LOG_CRIT, "Wrong PID returned by wait4() call");
1350 moonbr_terminate_error();
1353 if (WIFEXITED(childstatus)) {
1354 if (WEXITSTATUS(childstatus) || moonbr_stat) {
1355 moonbr_log(
1356 WEXITSTATUS(childstatus) ? LOG_WARNING : LOG_INFO,
1357 "Child process in pool #%i with PID %i returned with exit code %i", worker->pool->poolnum, (int)worker->pid, WEXITSTATUS(childstatus)
1358 );
1360 } else if (WIFSIGNALED(childstatus)) {
1361 if (WCOREDUMP(childstatus)) {
1362 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));
1363 } else if (WTERMSIG(childstatus) == SIGALRM) {
1364 moonbr_log(LOG_WARNING, "Child process in pool #%i with PID %i exited prematurely due to timeout", worker->pool->poolnum, (int)worker->pid);
1365 } else {
1366 moonbr_log(LOG_ERR, "Child process in pool #%i with PID %i died from signal %i", worker->pool->poolnum, (int)worker->pid, WTERMSIG(childstatus));
1368 } else {
1369 moonbr_log(LOG_CRIT, "Illegal exit status from child process in pool #%i with PID %i", worker->pool->poolnum, (int)worker->pid);
1370 moonbr_terminate_error();
1372 if (moonbr_stat) {
1373 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));
1374 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));
1375 moonbr_try_destroy_worker_stat("max resident set size", ru_maxrss);
1376 moonbr_try_destroy_worker_stat("integral shared memory size", ru_ixrss);
1377 moonbr_try_destroy_worker_stat("integral unshared data", ru_idrss);
1378 moonbr_try_destroy_worker_stat("integral unshared stack", ru_isrss);
1379 moonbr_try_destroy_worker_stat("page replaims", ru_minflt);
1380 moonbr_try_destroy_worker_stat("page faults", ru_majflt);
1381 moonbr_try_destroy_worker_stat("swaps", ru_nswap);
1382 moonbr_try_destroy_worker_stat("block input operations", ru_inblock);
1383 moonbr_try_destroy_worker_stat("block output operations", ru_oublock);
1384 moonbr_try_destroy_worker_stat("messages sent", ru_msgsnd);
1385 moonbr_try_destroy_worker_stat("messages received", ru_msgrcv);
1386 moonbr_try_destroy_worker_stat("signals received", ru_nsignals);
1387 moonbr_try_destroy_worker_stat("voluntary context switches", ru_nvcsw);
1388 moonbr_try_destroy_worker_stat("involuntary context switches", ru_nivcsw);
1392 int retval = (
1393 (worker->idle || worker->assigned) ?
1394 MOONBR_DESTROY_IDLE_OR_ASSIGNED :
1395 MOONBR_DESTROY_PREPARE
1396 );
1397 if (worker->prev_worker) worker->prev_worker->next_worker = worker->next_worker;
1398 else worker->pool->first_worker = worker->next_worker;
1399 if (worker->next_worker) worker->next_worker->prev_worker = worker->prev_worker;
1400 else worker->pool->last_worker = worker->prev_worker;
1401 if (worker->idle) {
1402 if (worker->prev_idle_worker) worker->prev_idle_worker->next_idle_worker = worker->next_idle_worker;
1403 else worker->pool->first_idle_worker = worker->next_idle_worker;
1404 if (worker->next_idle_worker) worker->next_idle_worker->prev_idle_worker = worker->prev_idle_worker;
1405 else worker->pool->last_idle_worker = worker->prev_idle_worker;
1406 worker->pool->idle_worker_count--;
1408 if (!worker->assigned) worker->pool->unassigned_worker_count--;
1409 worker->pool->total_worker_count--;
1410 worker->pool->worker_count_stat = 1;
1411 if (worker->errorlinebuf) free(worker->errorlinebuf);
1412 free(worker);
1413 return retval;
1417 /* Marks a worker as idle and stores it in a queue, optionally setting 'idle_expiration' value */
1418 static void moonbr_add_idle_worker(struct moonbr_worker *worker) {
1419 worker->prev_idle_worker = worker->pool->last_idle_worker;
1420 if (worker->prev_idle_worker) worker->prev_idle_worker->next_idle_worker = worker;
1421 else worker->pool->first_idle_worker = worker;
1422 worker->pool->last_idle_worker = worker;
1423 worker->idle = 1;
1424 worker->pool->idle_worker_count++;
1425 if (worker->assigned) {
1426 worker->assigned = 0;
1427 worker->pool->unassigned_worker_count++;
1429 worker->pool->worker_count_stat = 1;
1430 if (timerisset(&worker->pool->idle_timeout)) {
1431 struct timeval now;
1432 moonbr_now(&now);
1433 timeradd(&now, &worker->pool->idle_timeout, &worker->idle_expiration);
1437 /* Pops a worker from the queue of idle workers (idle queue must not be empty) */
1438 static struct moonbr_worker *moonbr_pop_idle_worker(struct moonbr_pool *pool) {
1439 struct moonbr_worker *worker;
1440 worker = pool->first_idle_worker;
1441 pool->first_idle_worker = worker->next_idle_worker;
1442 if (pool->first_idle_worker) pool->first_idle_worker->prev_idle_worker = NULL;
1443 else pool->last_idle_worker = NULL;
1444 worker->next_idle_worker = NULL;
1445 worker->idle = 0;
1446 worker->pool->idle_worker_count--;
1447 worker->assigned = 1;
1448 worker->pool->unassigned_worker_count--;
1449 worker->pool->worker_count_stat = 1;
1450 return worker;
1454 /*** Functions for queues of 'struct moonbr_listener' ***/
1456 /* Appends a 'struct moonbr_listener' to the queue of idle listeners and registers it for poll() */
1457 static void moonbr_add_idle_listener(struct moonbr_listener *listener) {
1458 listener->prev_listener = listener->pool->last_idle_listener;
1459 if (listener->prev_listener) listener->prev_listener->next_listener = listener;
1460 else listener->pool->first_idle_listener = listener;
1461 listener->pool->last_idle_listener = listener;
1462 if (listener->pollidx != -1) moonbr_poll_fds[listener->pollidx].events |= POLLIN;
1465 /* Removes a 'struct moonbr_listener' from the queue of idle listeners and unregisters it from poll() */
1466 static void moonbr_remove_idle_listener(struct moonbr_listener *listener) {
1467 if (listener->prev_listener) listener->prev_listener->next_listener = listener->next_listener;
1468 else listener->pool->first_idle_listener = listener->next_listener;
1469 if (listener->next_listener) listener->next_listener->prev_listener = listener->prev_listener;
1470 else listener->pool->last_idle_listener = listener->prev_listener;
1471 listener->prev_listener = NULL;
1472 listener->next_listener = NULL;
1473 if (listener->pollidx != -1) moonbr_poll_fds[listener->pollidx].events &= ~POLLIN;
1476 /* Adds a listener to the queue of connected listeners (i.e. waiting to have their incoming connection accepted) */
1477 static void moonbr_add_connected_listener(struct moonbr_listener *listener) {
1478 listener->prev_listener = listener->pool->last_connected_listener;
1479 if (listener->prev_listener) listener->prev_listener->next_listener = listener;
1480 else listener->pool->first_connected_listener = listener;
1481 listener->pool->last_connected_listener = listener;
1484 /* Removes and returns the first connected listener in the queue */
1485 static struct moonbr_listener *moonbr_pop_connected_listener(struct moonbr_pool *pool) {
1486 struct moonbr_listener *listener = pool->first_connected_listener;
1487 listener->pool->first_connected_listener = listener->next_listener;
1488 if (listener->pool->first_connected_listener) listener->pool->first_connected_listener->prev_listener = NULL;
1489 else listener->pool->last_connected_listener = NULL;
1490 listener->next_listener = NULL;
1491 return listener;
1495 /*** Functions to handle polling ***/
1497 /* Returns an index to a new initialized entry in moonbr_poll_fds[] */
1498 int moonbr_poll_fds_nextindex() {
1499 if (moonbr_poll_fds_count >= moonbr_poll_fds_bufsize) {
1500 if (moonbr_poll_fds_bufsize) moonbr_poll_fds_bufsize *= 2;
1501 else moonbr_poll_fds_bufsize = 1;
1502 moonbr_poll_fds = realloc(
1503 moonbr_poll_fds, moonbr_poll_fds_bufsize * sizeof(struct pollfd)
1504 );
1505 if (!moonbr_poll_fds) {
1506 moonbr_log(LOG_CRIT, "Memory allocation error");
1507 moonbr_terminate_error();
1510 moonbr_poll_fds[moonbr_poll_fds_count] = (struct pollfd){0, };
1511 return moonbr_poll_fds_count++;
1514 /* Returns an index to a new initialized entry in moonbr_poll_workers[] */
1515 int moonbr_poll_workers_nextindex() {
1516 if (moonbr_poll_worker_count >= moonbr_poll_workers_bufsize) {
1517 if (moonbr_poll_workers_bufsize) moonbr_poll_workers_bufsize *= 2;
1518 else moonbr_poll_workers_bufsize = 1;
1519 moonbr_poll_workers = realloc(
1520 moonbr_poll_workers, moonbr_poll_workers_bufsize * sizeof(struct moonbr_poll_worker)
1521 );
1522 if (!moonbr_poll_workers) {
1523 moonbr_log(LOG_CRIT, "Memory allocation error");
1524 moonbr_terminate_error();
1527 moonbr_poll_workers[moonbr_poll_worker_count] = (struct moonbr_poll_worker){0, };
1528 return moonbr_poll_worker_count++;
1531 /* Queues all listeners as idle, and initializes static part of moonbr_poll_fds[], which is passed to poll() */
1532 static void moonbr_poll_init() {
1533 if (socketpair(
1534 PF_LOCAL,
1535 SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
1536 0,
1537 moonbr_poll_signalfds
1538 )) {
1539 moonbr_log(LOG_CRIT, "Could not create socket pair for signal delivery during polling: %s", strerror(errno));
1540 moonbr_terminate_error();
1543 int j = moonbr_poll_fds_nextindex();
1544 struct pollfd *pollfd = &moonbr_poll_fds[j];
1545 pollfd->fd = moonbr_poll_signalfd_read;
1546 pollfd->events = POLLIN;
1549 struct moonbr_pool *pool;
1550 for (pool=moonbr_first_pool; pool; pool=pool->next_pool) {
1551 int i;
1552 for (i=0; i<pool->listener_count; i++) {
1553 struct moonbr_listener *listener = &pool->listener[i];
1554 if (listener->listenfd != -1) {
1555 int j = moonbr_poll_fds_nextindex();
1556 listener->pollidx = j;
1557 moonbr_poll_fds[j].fd = listener->listenfd;
1559 moonbr_add_idle_listener(listener);
1563 moonbr_poll_fds_static_count = moonbr_poll_fds_count; /* remember size of static part of array */
1566 /* Disables polling of all listeners (required for clean shutdown) */
1567 static void moonbr_poll_shutdown() {
1568 int i;
1569 for (i=1; i<moonbr_poll_fds_static_count; i++) {
1570 moonbr_poll_fds[i].fd = -1;
1574 /* (Re)builds dynamic part of moonbr_poll_fds[] array, and (re)builds moonbr_poll_workers[] array */
1575 static void moonbr_poll_refresh() {
1576 moonbr_poll_refresh_needed = 0;
1577 moonbr_poll_fds_count = moonbr_poll_fds_static_count;
1578 moonbr_poll_worker_count = 0;
1580 struct moonbr_pool *pool;
1581 for (pool=moonbr_first_pool; pool; pool=pool->next_pool) {
1582 struct moonbr_worker *worker;
1583 for (worker=pool->first_worker; worker; worker=worker->next_worker) {
1584 if (worker->controlfd != -1) {
1585 int j = moonbr_poll_fds_nextindex();
1586 int k = moonbr_poll_workers_nextindex();
1587 struct pollfd *pollfd = &moonbr_poll_fds[j];
1588 struct moonbr_poll_worker *poll_worker = &moonbr_poll_workers[k];
1589 pollfd->fd = worker->controlfd;
1590 pollfd->events = POLLIN;
1591 poll_worker->channel = MOONBR_POLL_WORKER_CONTROLCHANNEL;
1592 poll_worker->worker = worker;
1594 if (worker->errorfd != -1) {
1595 int j = moonbr_poll_fds_nextindex();
1596 int k = moonbr_poll_workers_nextindex();
1597 struct pollfd *pollfd = &moonbr_poll_fds[j];
1598 struct moonbr_poll_worker *poll_worker = &moonbr_poll_workers[k];
1599 pollfd->fd = worker->errorfd;
1600 pollfd->events = POLLIN;
1601 poll_worker->channel = MOONBR_POLL_WORKER_ERRORCHANNEL;
1602 poll_worker->worker = worker;
1609 /* resets socket and 'revents' field of moonbr_poll_fds[] for signal delivery just before poll() is called */
1610 static void moonbr_poll_reset_signal() {
1611 ssize_t readcount;
1612 char buf[1];
1613 moonbr_poll_fds[0].revents = 0;
1614 while ((readcount = read(moonbr_poll_signalfd_read, buf, 1)) < 0) {
1615 if (errno == EAGAIN) break;
1616 if (errno != EINTR) {
1617 moonbr_log(LOG_CRIT, "Error while reading from signal delivery socket: %s", strerror(errno));
1618 moonbr_terminate_error();
1621 if (!readcount) {
1622 moonbr_log(LOG_CRIT, "Unexpected EOF when reading from signal delivery socket: %s", strerror(errno));
1623 moonbr_terminate_error();
1628 /*** Shutdown initiation ***/
1630 /* Sets global variable 'moonbr_shutdown_in_progress', closes listeners, and demands worker termination */
1631 static void moonbr_initiate_shutdown() {
1632 struct moonbr_pool *pool;
1633 int i;
1634 if (moonbr_shutdown_in_progress) {
1635 moonbr_log(LOG_NOTICE, "Shutdown already in progress");
1636 return;
1638 moonbr_shutdown_in_progress = 1;
1639 moonbr_log(LOG_NOTICE, "Initiate shutdown");
1640 for (pool = moonbr_first_pool; pool; pool = pool->next_pool) {
1641 for (i=0; i<pool->listener_count; i++) {
1642 struct moonbr_listener *listener = &pool->listener[i];
1643 if (listener->listenfd != -1) {
1644 if (close(listener->listenfd) && errno != EINTR) {
1645 moonbr_log(LOG_CRIT, "Could not close listening socket: %s", strerror(errno));
1646 moonbr_terminate_error();
1650 pool->pre_fork = 0;
1651 pool->min_fork = 0;
1652 pool->max_fork = 0;
1653 timerclear(&pool->exit_delay);
1655 moonbr_poll_shutdown(); /* avoids loops due to error condition when polling closed listeners */
1659 /*** Functions to communicate with child processes ***/
1661 /* Tells child process to terminate */
1662 static void moonbr_terminate_idle_worker(struct moonbr_worker *worker) {
1663 moonbr_send_control_message(worker, MOONBR_COMMAND_TERMINATE, -1, NULL);
1666 /* Handles status messages from child process */
1667 static void moonbr_read_controlchannel(struct moonbr_worker *worker) {
1668 char controlmsg;
1670 ssize_t bytes_read;
1671 while ((bytes_read = read(worker->controlfd, &controlmsg, 1)) <= 0) {
1672 if (bytes_read == 0 || errno == ECONNRESET) {
1673 moonbr_log(LOG_WARNING, "Child process in pool #%i with PID %i unexpectedly closed control socket", worker->pool->poolnum, (int)worker->pid);
1674 if (close(worker->controlfd) && errno != EINTR) {
1675 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));
1676 moonbr_terminate_error();
1678 worker->controlfd = -1;
1679 moonbr_poll_refresh_needed = 1;
1680 return;
1682 if (errno != EINTR) {
1683 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));
1684 moonbr_terminate_error();
1688 if (worker->idle) {
1689 moonbr_log(LOG_CRIT, "Unexpected data from supposedly idle child process in pool #%i with PID %i", worker->pool->poolnum, (int)worker->pid);
1690 moonbr_terminate_error();
1692 if (moonbr_debug) {
1693 moonbr_log(LOG_DEBUG, "Received control message from child in pool #%i with PID %i: \"%c\"", worker->pool->poolnum, (int)worker->pid, (int)controlmsg);
1695 switch (controlmsg) {
1696 case MOONBR_STATUS_IDLE:
1697 if (moonbr_stat) {
1698 moonbr_log(LOG_INFO, "Child process in pool #%i with PID %i reports as idle", worker->pool->poolnum, (int)worker->pid);
1700 moonbr_add_idle_worker(worker);
1701 break;
1702 case MOONBR_STATUS_GOODBYE:
1703 if (moonbr_stat) {
1704 moonbr_log(LOG_INFO, "Child process in pool #%i with PID %i announced termination", worker->pool->poolnum, (int)worker->pid);
1706 if (close(worker->controlfd) && errno != EINTR) {
1707 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));
1708 moonbr_terminate_error();
1710 worker->controlfd = -1;
1711 moonbr_poll_refresh_needed = 1;
1712 break;
1713 default:
1714 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);
1715 moonbr_terminate_error();
1719 /* Handles stderr stream from child process */
1720 static void moonbr_read_errorchannel(struct moonbr_worker *worker) {
1721 char staticbuf[MOONBR_MAXERRORLINELEN+1];
1722 char *buf = worker->errorlinebuf;
1723 if (!buf) buf = staticbuf;
1725 ssize_t bytes_read;
1726 while (
1727 (bytes_read = read(
1728 worker->errorfd,
1729 buf + worker->errorlinelen,
1730 MOONBR_MAXERRORLINELEN+1 - worker->errorlinelen
1731 )) <= 0
1732 ) {
1733 if (bytes_read == 0 || errno == ECONNRESET) {
1734 if (moonbr_debug) {
1735 moonbr_log(LOG_DEBUG, "Child process in pool #%i with PID %i closed stderr socket", worker->pool->poolnum, (int)worker->pid);
1737 if (close(worker->errorfd) && errno != EINTR) {
1738 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));
1739 moonbr_terminate_error();
1741 worker->errorfd = -1;
1742 moonbr_poll_refresh_needed = 1;
1743 break;
1745 if (errno != EINTR) {
1746 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));
1747 moonbr_terminate_error();
1750 worker->errorlinelen += bytes_read;
1753 int i;
1754 for (i=0; i<worker->errorlinelen; i++) {
1755 if (buf[i] == '\n') buf[i] = 0;
1756 if (!buf[i]) {
1757 if (worker->errorlineovf) {
1758 worker->errorlineovf = 0;
1759 } else {
1760 moonbr_log(LOG_WARNING, "Error log from process in pool #%i with PID %i: %s", worker->pool->poolnum, (int)worker->pid, buf);
1762 worker->errorlinelen -= i+1;
1763 memmove(buf, buf+i+1, worker->errorlinelen);
1764 i = -1;
1767 if (i > MOONBR_MAXERRORLINELEN) {
1768 buf[MOONBR_MAXERRORLINELEN] = 0;
1769 if (!worker->errorlineovf) {
1770 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);
1772 worker->errorlinelen = 0;
1773 worker->errorlineovf = 1;
1776 if (!worker->errorlinebuf && worker->errorlinelen) { /* allocate buffer on heap only if necessary */
1777 worker->errorlinebuf = malloc((MOONBR_MAXERRORLINELEN+1) * sizeof(char));
1778 if (!worker->errorlinebuf) {
1779 moonbr_log(LOG_CRIT, "Memory allocation error");
1780 moonbr_terminate_error();
1782 memcpy(worker->errorlinebuf, staticbuf, worker->errorlinelen);
1787 /*** Handler for incoming connections ***/
1789 /* Accepts one or more incoming connections on listener socket and passes it to worker(s) popped from idle queue */
1790 static void moonbr_connect(struct moonbr_pool *pool) {
1791 struct moonbr_listener *listener = moonbr_pop_connected_listener(pool);
1792 struct moonbr_worker *worker;
1793 switch (listener->proto) {
1794 case MOONBR_PROTO_INTERVAL:
1795 worker = moonbr_pop_idle_worker(pool);
1796 if (moonbr_stat) {
1797 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);
1799 worker->restart_interval_listener = listener;
1800 moonbr_send_control_message(worker, MOONBR_SOCKETTYPE_INTERVAL, -1, listener);
1801 /* do not push listener to queue of idle listeners yet */
1802 break;
1803 case MOONBR_PROTO_LOCAL:
1804 do {
1805 int peerfd;
1806 struct sockaddr_un peeraddr;
1807 socklen_t peeraddr_len = sizeof(struct sockaddr_un);
1808 peerfd = accept4(
1809 listener->listenfd,
1810 (struct sockaddr *)&peeraddr,
1811 &peeraddr_len,
1812 SOCK_CLOEXEC
1813 );
1814 if (peerfd == -1) {
1815 if (errno == EWOULDBLOCK) {
1816 break;
1817 } else if (errno == ECONNABORTED) {
1818 moonbr_log(LOG_WARNING, "Connection aborted before accepting it (proto=\"local\", path=\"%s\")", listener->proto_specific.local.path);
1819 break;
1820 } else if (errno != EINTR) {
1821 moonbr_log(LOG_ERR, "Could not accept socket connection: %s", strerror(errno));
1822 moonbr_terminate_error();
1824 } else {
1825 worker = moonbr_pop_idle_worker(pool);
1826 if (moonbr_stat) {
1827 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);
1829 moonbr_send_control_message(worker, MOONBR_SOCKETTYPE_LOCAL, peerfd, listener);
1830 if (close(peerfd) && errno != EINTR) {
1831 moonbr_log(LOG_ERR, "Could not close incoming socket connection in parent process: %s", strerror(errno));
1832 moonbr_terminate_error();
1835 } while (pool->first_idle_worker);
1836 moonbr_add_idle_listener(listener);
1837 break;
1838 case MOONBR_PROTO_TCP6:
1839 do {
1840 int peerfd;
1841 struct sockaddr_in6 peeraddr;
1842 socklen_t peeraddr_len = sizeof(struct sockaddr_in6);
1843 peerfd = accept4(
1844 listener->listenfd,
1845 (struct sockaddr *)&peeraddr,
1846 &peeraddr_len,
1847 SOCK_CLOEXEC
1848 );
1849 if (peerfd == -1) {
1850 if (errno == EWOULDBLOCK) {
1851 break;
1852 } else if (errno == ECONNABORTED) {
1853 moonbr_log(LOG_WARNING, "Connection aborted before accepting it (proto=\"tcp6\", port=%i)", listener->proto_specific.tcp.port);
1854 break;
1855 } else if (errno != EINTR) {
1856 moonbr_log(LOG_ERR, "Could not accept socket connection: %s", strerror(errno));
1857 moonbr_terminate_error();
1859 } else {
1860 worker = moonbr_pop_idle_worker(pool);
1861 if (moonbr_stat) {
1862 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);
1864 moonbr_send_control_message(worker, MOONBR_SOCKETTYPE_NETWORK, peerfd, listener);
1865 if (close(peerfd) && errno != EINTR) {
1866 moonbr_log(LOG_ERR, "Could not close incoming socket connection in parent process: %s", strerror(errno));
1867 moonbr_terminate_error();
1870 } while (pool->first_idle_worker);
1871 moonbr_add_idle_listener(listener);
1872 break;
1873 case MOONBR_PROTO_TCP4:
1874 do {
1875 int peerfd;
1876 struct sockaddr_in peeraddr;
1877 socklen_t peeraddr_len = sizeof(struct sockaddr_in);
1878 peerfd = accept4(
1879 listener->listenfd,
1880 (struct sockaddr *)&peeraddr,
1881 &peeraddr_len,
1882 SOCK_CLOEXEC
1883 );
1884 if (peerfd == -1) {
1885 if (errno == EWOULDBLOCK) {
1886 break;
1887 } else if (errno == ECONNABORTED) {
1888 moonbr_log(LOG_WARNING, "Connection aborted before accepting it (proto=\"tcp4\", port=%i)", listener->proto_specific.tcp.port);
1889 break;
1890 } else if (errno != EINTR) {
1891 moonbr_log(LOG_ERR, "Could not accept socket connection: %s", strerror(errno));
1892 moonbr_terminate_error();
1894 } else {
1895 worker = moonbr_pop_idle_worker(pool);
1896 if (moonbr_stat) {
1897 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);
1899 moonbr_send_control_message(worker, MOONBR_SOCKETTYPE_NETWORK, peerfd, listener);
1900 if (close(peerfd) && errno != EINTR) {
1901 moonbr_log(LOG_ERR, "Could not close incoming socket connection in parent process: %s", strerror(errno));
1902 moonbr_terminate_error();
1905 } while (pool->first_idle_worker);
1906 moonbr_add_idle_listener(listener);
1907 break;
1908 default:
1909 moonbr_log(LOG_ERR, "Internal error (should not happen): Unexpected value in listener.proto field");
1910 moonbr_terminate_error();
1915 /*** Functions to initialize and restart interval timers ***/
1917 /* Initializes all interval timers */
1918 static void moonbr_interval_initialize() {
1919 struct timeval now;
1920 struct moonbr_pool *pool;
1921 moonbr_now(&now);
1922 for (pool=moonbr_first_pool; pool; pool=pool->next_pool) {
1923 int i;
1924 for (i=0; i<pool->listener_count; i++) {
1925 struct moonbr_listener *listener = &pool->listener[i];
1926 if (listener->proto == MOONBR_PROTO_INTERVAL) {
1927 timeradd(
1928 &now,
1929 &listener->proto_specific.interval.delay,
1930 &listener->proto_specific.interval.wakeup
1931 );
1937 /* If necessary, restarts interval timers and queues interval listener as idle after a worker changed status */
1938 static void moonbr_interval_restart(
1939 struct moonbr_worker *worker,
1940 struct timeval *now /* passed to synchronize with moonbr_run() function */
1941 ) {
1942 struct moonbr_listener *listener = worker->restart_interval_listener;
1943 if (listener) {
1944 moonbr_add_idle_listener(listener);
1945 worker->restart_interval_listener = NULL;
1946 if (listener->proto_specific.interval.strict) {
1947 timeradd(
1948 &listener->proto_specific.interval.wakeup,
1949 &listener->proto_specific.interval.delay,
1950 &listener->proto_specific.interval.wakeup
1951 );
1952 if (timercmp(&listener->proto_specific.interval.wakeup, now, <)) {
1953 listener->proto_specific.interval.wakeup = *now;
1955 } else {
1956 timeradd(
1957 now,
1958 &listener->proto_specific.interval.delay,
1959 &listener->proto_specific.interval.wakeup
1960 );
1966 /*** Main loop and helper functions ***/
1968 /* Stores the earliest required wakeup time in 'wait' variable */
1969 static void moonbr_calc_wait(struct timeval *wait, struct timeval *wakeup) {
1970 if (!timerisset(wait) || timercmp(wakeup, wait, <)) *wait = *wakeup;
1973 /* Main loop of Moonbridge system (including initialization of signal handlers and polling structures) */
1974 static void moonbr_run(lua_State *L) {
1975 struct timeval now;
1976 struct moonbr_pool *pool;
1977 struct moonbr_worker *worker;
1978 struct moonbr_worker *next_worker; /* needed when worker is removed during iteration of workers */
1979 struct moonbr_listener *listener;
1980 struct moonbr_listener *next_listener; /* needed when listener is removed during iteration of listeners */
1981 int i;
1982 moonbr_poll_init(); /* must be executed before moonbr_signal_init() */
1983 moonbr_signal_init();
1984 moonbr_interval_initialize();
1985 moonbr_pstate = MOONBR_PSTATE_RUNNING;
1986 while (1) {
1987 struct timeval wait = {0, }; /* point in time when premature wakeup of poll() is required */
1988 if (moonbr_cond_interrupt) {
1989 moonbr_log(LOG_WARNING, "Fast shutdown requested");
1990 moonbr_terminate(MOONBR_EXITCODE_GRACEFUL);
1992 if (moonbr_cond_terminate) {
1993 moonbr_initiate_shutdown();
1994 moonbr_cond_terminate = 0;
1996 moonbr_cond_child = 0; /* must not be reset between moonbr_try_destroy_worker() and poll() */
1997 moonbr_now(&now);
1998 for (pool=moonbr_first_pool; pool; pool=pool->next_pool) {
1999 int terminated_worker_count = 0; /* allows shortcut for new worker creation */
2000 /* terminate idle workers when expired */
2001 if (timerisset(&pool->idle_timeout)) {
2002 while ((worker = pool->first_idle_worker) != NULL) {
2003 if (timercmp(&worker->idle_expiration, &now, >)) break;
2004 moonbr_pop_idle_worker(pool);
2005 moonbr_terminate_idle_worker(worker);
2008 /* mark listeners as connected when incoming connection is pending */
2009 for (listener=pool->first_idle_listener; listener; listener=next_listener) {
2010 next_listener = listener->next_listener; /* extra variable necessary due to changing list */
2011 if (listener->pollidx != -1) {
2012 if (moonbr_poll_fds[listener->pollidx].revents) {
2013 moonbr_poll_fds[listener->pollidx].revents = 0;
2014 moonbr_remove_idle_listener(listener);
2015 moonbr_add_connected_listener(listener);
2017 } else if (listener->proto == MOONBR_PROTO_INTERVAL) {
2018 if (!timercmp(&listener->proto_specific.interval.wakeup, &now, >)) {
2019 moonbr_remove_idle_listener(listener);
2020 moonbr_add_connected_listener(listener);
2022 } else {
2023 moonbr_log(LOG_CRIT, "Internal error (should not happen): Listener is neither an interval timer nor has the 'pollidx' value set");
2024 moonbr_terminate_error();
2027 /* process input from child processes */
2028 for (i=0; i<moonbr_poll_worker_count; i++) {
2029 if (moonbr_poll_worker_fds[i].revents) {
2030 moonbr_poll_worker_fds[i].revents = 0;
2031 struct moonbr_poll_worker *poll_worker = &moonbr_poll_workers[i];
2032 switch (poll_worker->channel) {
2033 case MOONBR_POLL_WORKER_CONTROLCHANNEL:
2034 moonbr_read_controlchannel(poll_worker->worker);
2035 moonbr_interval_restart(poll_worker->worker, &now);
2036 break;
2037 case MOONBR_POLL_WORKER_ERRORCHANNEL:
2038 moonbr_read_errorchannel(poll_worker->worker);
2039 break;
2043 /* collect dead child processes */
2044 for (worker=pool->first_worker; worker; worker=next_worker) {
2045 next_worker = worker->next_worker; /* extra variable necessary due to changing list */
2046 switch (moonbr_try_destroy_worker(worker)) {
2047 case MOONBR_DESTROY_PREPARE:
2048 pool->use_fork_error_wakeup = 1;
2049 break;
2050 case MOONBR_DESTROY_IDLE_OR_ASSIGNED:
2051 terminated_worker_count++;
2052 break;
2055 /* connect listeners with idle workers */
2056 if (!moonbr_shutdown_in_progress) {
2057 while (pool->first_connected_listener && pool->first_idle_worker) {
2058 moonbr_connect(pool);
2061 /* create new worker processes */
2062 while (
2063 pool->total_worker_count < pool->max_fork && (
2064 pool->unassigned_worker_count < pool->pre_fork ||
2065 pool->total_worker_count < pool->min_fork
2067 ) {
2068 if (pool->use_fork_error_wakeup) {
2069 if (timercmp(&pool->fork_error_wakeup, &now, >)) {
2070 moonbr_calc_wait(&wait, &pool->fork_error_wakeup);
2071 break;
2073 } else {
2074 if (terminated_worker_count) {
2075 terminated_worker_count--;
2076 } else if (timercmp(&pool->fork_wakeup, &now, >)) {
2077 moonbr_calc_wait(&wait, &pool->fork_wakeup);
2078 break;
2081 if (moonbr_create_worker(pool, L)) {
2082 /* on error, enforce error delay */
2083 timeradd(&now, &pool->fork_error_delay, &pool->fork_error_wakeup);
2084 pool->use_fork_error_wakeup = 1;
2085 moonbr_calc_wait(&wait, &pool->fork_error_wakeup);
2086 break;
2087 } else {
2088 /* normal fork delay on success */
2089 timeradd(&now, &pool->fork_delay, &pool->fork_wakeup);
2090 timeradd(&now, &pool->fork_error_delay, &pool->fork_error_wakeup);
2091 pool->use_fork_error_wakeup = 0; /* gets set later if error occures during preparation */
2094 /* terminate excessive worker processes */
2095 while (
2096 pool->total_worker_count > pool->min_fork &&
2097 pool->idle_worker_count > pool->pre_fork
2098 ) {
2099 if (timerisset(&pool->exit_wakeup)) {
2100 if (timercmp(&pool->exit_wakeup, &now, >)) {
2101 moonbr_calc_wait(&wait, &pool->exit_wakeup);
2102 break;
2104 moonbr_terminate_idle_worker(moonbr_pop_idle_worker(pool));
2105 timeradd(&now, &pool->exit_delay, &pool->exit_wakeup);
2106 } else {
2107 timeradd(&now, &pool->exit_delay, &pool->exit_wakeup);
2108 break;
2111 if (!(
2112 pool->total_worker_count > pool->min_fork &&
2113 pool->idle_worker_count > pool->pre_fork
2114 )) {
2115 timerclear(&pool->exit_wakeup); /* timer gets restarted later when there are excessive workers */
2117 /* optionally output worker count stats */
2118 if (moonbr_stat && pool->worker_count_stat) {
2119 pool->worker_count_stat = 0;
2120 moonbr_log(
2121 LOG_INFO,
2122 "Worker count for pool #%i: %i idle, %i assigned, %i total",
2123 pool->poolnum, pool->idle_worker_count,
2124 pool->total_worker_count - pool->unassigned_worker_count,
2125 pool->total_worker_count);
2127 /* calculate wakeup time for interval listeners */
2128 for (listener=pool->first_idle_listener; listener; listener=listener->next_listener) {
2129 if (listener->proto == MOONBR_PROTO_INTERVAL) {
2130 moonbr_calc_wait(&wait, &listener->proto_specific.interval.wakeup);
2133 /* calculate wakeup time for idle workers (only first idle worker is significant) */
2134 if (timerisset(&pool->idle_timeout) && pool->first_idle_worker) {
2135 moonbr_calc_wait(&wait, &pool->first_idle_worker->idle_expiration);
2138 /* check if shutdown is complete */
2139 if (moonbr_shutdown_in_progress) {
2140 for (pool=moonbr_first_pool; pool; pool=pool->next_pool) {
2141 if (pool->first_worker) break;
2143 if (!pool) {
2144 moonbr_log(LOG_INFO, "All worker threads have terminated");
2145 moonbr_terminate(MOONBR_EXITCODE_GRACEFUL);
2148 if (moonbr_poll_refresh_needed) moonbr_poll_refresh();
2149 moonbr_cond_poll = 1;
2150 if (!moonbr_cond_child && !moonbr_cond_terminate && !moonbr_cond_interrupt) {
2151 int timeout;
2152 if (timerisset(&wait)) {
2153 if (timercmp(&wait, &now, <)) {
2154 moonbr_log(LOG_CRIT, "Internal error (should not happen): Future is in the past");
2155 moonbr_terminate_error();
2157 timersub(&wait, &now, &wait);
2158 timeout = wait.tv_sec * 1000 + wait.tv_usec / 1000;
2159 } else {
2160 timeout = INFTIM;
2162 if (moonbr_debug) {
2163 moonbr_log(LOG_DEBUG, "Waiting for I/O");
2165 poll(moonbr_poll_fds, moonbr_poll_fds_count, timeout);
2166 } else {
2167 if (moonbr_debug) {
2168 moonbr_log(LOG_DEBUG, "Do not wait for I/O");
2171 moonbr_cond_poll = 0;
2172 moonbr_poll_reset_signal();
2177 /*** Lua interface ***/
2179 static int moonbr_lua_panic(lua_State *L) {
2180 const char *errmsg;
2181 errmsg = lua_tostring(L, -1);
2182 if (!errmsg) {
2183 if (lua_isnoneornil(L, -1)) errmsg = "(error message is nil)";
2184 else errmsg = "(error message is not a string)";
2186 if (moonbr_pstate == MOONBR_PSTATE_FORKED) {
2187 fprintf(stderr, "Uncaught Lua error: %s\n", errmsg);
2188 exit(1);
2189 } else {
2190 moonbr_log(LOG_CRIT, "Uncaught Lua error: %s", errmsg);
2191 moonbr_terminate_error();
2193 return 0;
2196 static int moonbr_addtraceback(lua_State *L) {
2197 luaL_traceback(L, L, luaL_tolstring(L, 1, NULL), 1);
2198 return 1;
2201 /* Memory allocator that allows limiting memory consumption */
2202 static void *moonbr_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
2203 (void)ud; /* not used */
2204 if (nsize == 0) {
2205 if (ptr) {
2206 moonbr_memory_usage -= osize;
2207 free(ptr);
2209 return NULL;
2210 } else if (ptr) {
2211 if (
2212 moonbr_memory_limit &&
2213 nsize > osize &&
2214 moonbr_memory_usage + (nsize - osize) > moonbr_memory_limit
2215 ) {
2216 return NULL;
2217 } else {
2218 ptr = realloc(ptr, nsize);
2219 if (ptr) moonbr_memory_usage += nsize - osize;
2221 } else {
2222 if (
2223 moonbr_memory_limit &&
2224 moonbr_memory_usage + nsize > moonbr_memory_limit
2225 ) {
2226 return NULL;
2227 } else {
2228 ptr = realloc(ptr, nsize);
2229 if (ptr) moonbr_memory_usage += nsize;
2232 return ptr;
2235 /* New method for Lua file objects: read until terminator or length exceeded */
2236 static int moonbr_readuntil(lua_State *L) {
2237 luaL_Stream *stream;
2238 FILE *file;
2239 const char *terminatorstr;
2240 size_t terminatorlen;
2241 luaL_Buffer buf;
2242 lua_Integer maxlen;
2243 char terminator;
2244 int byte;
2245 stream = luaL_checkudata(L, 1, LUA_FILEHANDLE);
2246 terminatorstr = luaL_checklstring(L, 2, &terminatorlen);
2247 luaL_argcheck(L, terminatorlen == 1, 2, "single byte expected");
2248 maxlen = luaL_optinteger(L, 3, 0);
2249 if (!stream->closef) luaL_error(L, "attempt to use a closed file");
2250 file = stream->f;
2251 luaL_buffinit(L, &buf);
2252 if (!maxlen) maxlen = -1;
2253 terminator = terminatorstr[0];
2254 while (maxlen > 0 ? maxlen-- : maxlen) {
2255 byte = fgetc(file);
2256 if (byte == EOF) {
2257 if (ferror(file)) {
2258 char errmsg[MOONBR_MAXSTRERRORLEN];
2259 strerror_r(errno, errmsg, MOONBR_MAXSTRERRORLEN); /* use thread-safe call in case child created threads */
2260 lua_pushnil(L);
2261 lua_pushstring(L, errmsg);
2262 return 2;
2263 } else {
2264 break;
2267 luaL_addchar(&buf, byte);
2268 if (byte == terminator) break;
2270 luaL_pushresult(&buf);
2271 if (!lua_rawlen(L, -1)) lua_pushnil(L);
2272 return 1;
2275 static int moonbr_lua_tonatural(lua_State *L, int idx) {
2276 int isnum;
2277 lua_Number n;
2278 n = lua_tonumberx(L, idx, &isnum);
2279 if (isnum && n>=0 && n<INT_MAX && (lua_Number)(int)n == n) return n;
2280 else return -1;
2283 static int moonbr_lua_totimeval(lua_State *L, int idx, struct timeval *value) {
2284 int isnum;
2285 lua_Number n;
2286 n = lua_tonumberx(L, idx, &isnum);
2287 if (isnum && n>=0 && n<=100000000) {
2288 value->tv_sec = n;
2289 value->tv_usec = 1e6 * (n - value->tv_sec);
2290 return 1;
2291 } else {
2292 return 0;
2296 static int moonbr_timeout(lua_State *L) {
2297 struct itimerval oldval;
2298 if (lua_isnoneornil(L, 1) && lua_isnoneornil(L, 2)) {
2299 getitimer(ITIMER_REAL, &oldval);
2300 } else {
2301 struct itimerval newval = {};
2302 timerclear(&newval.it_interval);
2303 timerclear(&newval.it_value);
2304 if (lua_toboolean(L, 1)) {
2305 luaL_argcheck(
2306 L, moonbr_lua_totimeval(L, 1, &newval.it_value), 1,
2307 "interval in seconds expected"
2308 );
2310 if (lua_isnoneornil(L, 2)) {
2311 if (setitimer(ITIMER_REAL, &newval, &oldval)) {
2312 moonbr_log(LOG_CRIT, "Could not set ITIMER_REAL via setitimer()");
2313 moonbr_terminate_error();
2315 } else {
2316 getitimer(ITIMER_REAL, &oldval);
2317 if (!timerisset(&oldval.it_value)) {
2318 if (setitimer(ITIMER_REAL, &newval, NULL)) {
2319 moonbr_log(LOG_CRIT, "Could not set ITIMER_REAL via setitimer()");
2320 moonbr_terminate_error();
2322 lua_call(L, lua_gettop(L) - 2, LUA_MULTRET);
2323 timerclear(&newval.it_value);
2324 if (setitimer(ITIMER_REAL, &newval, NULL)) {
2325 moonbr_log(LOG_CRIT, "Could not set ITIMER_REAL via setitimer()");
2326 moonbr_terminate_error();
2328 } else if (timercmp(&newval.it_value, &oldval.it_value, <)) {
2329 struct itimerval remval;
2330 if (setitimer(ITIMER_REAL, &newval, NULL)) {
2331 moonbr_log(LOG_CRIT, "Could not set ITIMER_REAL via setitimer()");
2332 moonbr_terminate_error();
2334 lua_call(L, lua_gettop(L) - 2, LUA_MULTRET);
2335 getitimer(ITIMER_REAL, &remval);
2336 timersub(&oldval.it_value, &newval.it_value, &newval.it_value);
2337 timeradd(&newval.it_value, &remval.it_value, &newval.it_value);
2338 if (setitimer(ITIMER_REAL, &newval, NULL)) {
2339 moonbr_log(LOG_CRIT, "Could not set ITIMER_REAL via setitimer()");
2340 moonbr_terminate_error();
2342 } else {
2343 lua_call(L, lua_gettop(L) - 2, LUA_MULTRET);
2345 return lua_gettop(L) - 1;
2348 lua_pushnumber(L, oldval.it_value.tv_sec + 1e-6 * oldval.it_value.tv_usec);
2349 return 1;
2352 #define moonbr_listen_init_pool_forkoption(luaname, cname, defval) { \
2353 lua_getfield(L, 2, luaname); \
2354 pool->cname = lua_isnil(L, -1) ? (defval) : moonbr_lua_tonatural(L, -1); \
2355 } while(0)
2357 #define moonbr_listen_init_pool_timeoption(luaname, cname, defval, defvalu) ( \
2358 lua_getfield(L, 2, luaname), \
2359 lua_isnil(L, -1) ? ( \
2360 pool->cname.tv_sec = (defval), pool->cname.tv_usec = (defvalu), \
2361 1 \
2362 ) : ( \
2363 (lua_isboolean(L, -1) && !lua_toboolean(L, -1)) ? ( \
2364 pool->cname.tv_sec = 0, pool->cname.tv_usec = 0, \
2365 1 \
2366 ) : ( \
2367 moonbr_lua_totimeval(L, -1, &pool->cname) \
2368 ) \
2369 ) \
2372 static int moonbr_listen_init_pool(lua_State *L) {
2373 struct moonbr_pool *pool;
2374 const char *proto;
2375 int i;
2376 pool = lua_touserdata(L, 1);
2377 for (i=0; i<pool->listener_count; i++) {
2378 struct moonbr_listener *listener = &pool->listener[i];
2379 lua_settop(L, 2);
2380 #if LUA_VERSION_NUM >= 503
2381 lua_geti(L, 2, i+1);
2382 #else
2383 lua_pushinteger(L, i+1);
2384 lua_gettable(L, 2);
2385 #endif
2386 lua_getfield(L, 3, "proto");
2387 proto = lua_tostring(L, -1);
2388 if (proto && !strcmp(proto, "interval")) {
2389 listener->proto = MOONBR_PROTO_INTERVAL;
2390 lua_getfield(L, 3, "name");
2392 const char *name = lua_tostring(L, -1);
2393 if (name) {
2394 if (asprintf(&listener->proto_specific.interval.name, "%s", name) < 0) {
2395 moonbr_log(LOG_CRIT, "Memory allocation_error");
2396 moonbr_terminate_error();
2400 lua_getfield(L, 3, "delay");
2401 if (
2402 !moonbr_lua_totimeval(L, -1, &listener->proto_specific.interval.delay) ||
2403 !timerisset(&listener->proto_specific.interval.delay)
2404 ) {
2405 luaL_error(L, "No valid interval delay specified; use listen{{proto=\"interval\", delay=...}, ...}");
2407 lua_getfield(L, 3, "strict");
2408 if (!lua_isnil(L, -1)) {
2409 if (lua_isboolean(L, -1)) {
2410 if (lua_toboolean(L, -1)) listener->proto_specific.interval.strict = 1;
2411 } else {
2412 luaL_error(L, "Option \"strict\" must be a boolean if set; use listen{{proto=\"interval\", strict=true, ...}, ...}");
2415 } else if (proto && !strcmp(proto, "local")) {
2416 listener->proto = MOONBR_PROTO_LOCAL;
2417 lua_getfield(L, 3, "path");
2419 const char *path = lua_tostring(L, -1);
2420 if (!path) {
2421 luaL_error(L, "No valid path specified for local socket; use listen{{proto=\"local\", path=...}, ...}");
2423 if (asprintf(&listener->proto_specific.local.path, "%s", path) < 0) {
2424 moonbr_log(LOG_CRIT, "Memory allocation_error");
2425 moonbr_terminate_error();
2428 } else if (proto && !strcmp(proto, "tcp6")) {
2429 listener->proto = MOONBR_PROTO_TCP6;
2430 lua_getfield(L, 3, "port");
2431 listener->proto_specific.tcp.port = lua_tointeger(L, -1);
2432 if (
2433 listener->proto_specific.tcp.port < 1 ||
2434 listener->proto_specific.tcp.port > 65535
2435 ) {
2436 luaL_error(L, "No valid port number specified; use listen{{proto=\"tcp6\", port=...}, ...}");
2438 lua_getfield(L, 3, "localhost");
2439 if (!lua_isnil(L, -1)) {
2440 if (lua_isboolean(L, -1)) {
2441 if (lua_toboolean(L, -1)) listener->proto_specific.tcp.localhost_only = 1;
2442 } else {
2443 luaL_error(L, "Option \"localhost\" must be a boolean if set; use listen{{proto=\"tcp6\", localhost=true, ...}, ...}");
2446 } else if (proto && !strcmp(proto, "tcp4")) {
2447 listener->proto = MOONBR_PROTO_TCP4;
2448 lua_getfield(L, 3, "port");
2449 listener->proto_specific.tcp.port = lua_tointeger(L, -1);
2450 if (
2451 listener->proto_specific.tcp.port < 1 ||
2452 listener->proto_specific.tcp.port > 65535
2453 ) {
2454 luaL_error(L, "No valid port number specified; use listen{{proto=\"tcp4\", port=...}, ...}");
2456 lua_getfield(L, 3, "localhost");
2457 if (!lua_isnil(L, -1)) {
2458 if (lua_isboolean(L, -1)) {
2459 if (lua_toboolean(L, -1)) listener->proto_specific.tcp.localhost_only = 1;
2460 } else {
2461 luaL_error(L, "Option \"localhost\" must be a boolean if set; use listen{{proto=\"tcp4\", localhost=true, ...}, ...}");
2466 lua_settop(L, 2);
2467 moonbr_listen_init_pool_forkoption("pre_fork", pre_fork, 1);
2468 moonbr_listen_init_pool_forkoption("min_fork", min_fork, pool->pre_fork > 2 ? pool->pre_fork : 2);
2469 moonbr_listen_init_pool_forkoption("max_fork", max_fork, pool->min_fork > 16 ? pool->min_fork : 16);
2470 if (!moonbr_listen_init_pool_timeoption("fork_delay", fork_delay, 1, 0)) {
2471 luaL_error(L, "Option \"fork_delay\" is expected to be a non-negative number");
2473 if (!moonbr_listen_init_pool_timeoption("fork_error_delay", fork_error_delay, 2, 0)) {
2474 luaL_error(L, "Option \"fork_error_delay\" is expected to be a non-negative number");
2476 if (!moonbr_listen_init_pool_timeoption("exit_delay", exit_delay, 60, 0)) {
2477 luaL_error(L, "Option \"exit_delay\" is expected to be a non-negative number");
2479 if (timercmp(&pool->fork_error_delay, &pool->fork_delay, <)) {
2480 pool->fork_error_delay = pool->fork_delay;
2482 if (!moonbr_listen_init_pool_timeoption("idle_timeout", idle_timeout, 0, 0)) {
2483 luaL_error(L, "Option \"idle_timeout\" is expected to be a non-negative number");
2485 lua_getfield(L, 2, "memory_limit");
2486 if (!lua_isnil(L, -1)) {
2487 int isnum;
2488 lua_Number n;
2489 n = lua_tonumberx(L, -1, &isnum);
2490 if (n < 0 || !isnum) {
2491 luaL_error(L, "Option \"memory_limit\" is expected to be a non-negative number");
2493 pool->memory_limit = n;
2495 lua_settop(L, 2);
2496 lua_getfield(L, 2, "prepare");
2497 if (!lua_isnil(L, -1) && !lua_isfunction(L, -1)) {
2498 luaL_error(L, "Option \"prepare\" must be nil or a function");
2500 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_prepare_func(pool));
2501 lua_getfield(L, 2, "connect");
2502 if (!lua_isfunction(L, -1)) {
2503 luaL_error(L, "Option \"connect\" must be a function; use listen{{...}, {...}, connect=function(socket) ... end, ...}");
2505 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_connect_func(pool));
2506 lua_getfield(L, 2, "finish");
2507 if (!lua_isnil(L, -1) && !lua_isfunction(L, -1)) {
2508 luaL_error(L, "Option \"finish\" must be nil or a function");
2510 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_finish_func(pool));
2511 return 0;
2514 static int moonbr_listen(lua_State *L) {
2515 struct moonbr_pool *pool;
2516 lua_Integer listener_count;
2517 if (moonbr_booted) luaL_error(L, "Moonbridge bootup is already complete");
2518 luaL_checktype(L, 1, LUA_TTABLE);
2519 listener_count = luaL_len(L, 1);
2520 if (!listener_count) luaL_error(L, "No listen ports specified; use listen{{proto=..., port=...},...}");
2521 if (listener_count > 100) luaL_error(L, "Too many listeners");
2522 pool = moonbr_create_pool(listener_count);
2523 lua_pushcfunction(L, moonbr_listen_init_pool);
2524 lua_pushlightuserdata(L, pool);
2525 lua_pushvalue(L, 1);
2526 if (lua_pcall(L, 2, 0, 0)) goto moonbr_listen_error;
2528 int i;
2529 i = moonbr_start_pool(pool);
2530 if (i >= 0) {
2531 struct moonbr_listener *listener = &pool->listener[i];
2532 switch (listener->proto) {
2533 case MOONBR_PROTO_INTERVAL:
2534 lua_pushfstring(L, "Could not initialize listener #%d (proto=\"interval\"): %s", i+1, strerror(errno));
2535 break;
2536 case MOONBR_PROTO_LOCAL:
2537 lua_pushfstring(L, "Could not initialize listener #%d (proto=\"local\", path=\"%s\"): %s", i+1, listener->proto_specific.local.path, strerror(errno));
2538 break;
2539 case MOONBR_PROTO_TCP6:
2540 lua_pushfstring(L, "Could not initialize listener #%d (proto=\"tcp6\", port=%d): %s", i+1, listener->proto_specific.tcp.port, strerror(errno));
2541 break;
2542 case MOONBR_PROTO_TCP4:
2543 lua_pushfstring(L, "Could not initialize listener #%d (proto=\"tcp4\", port=%d): %s", i+1, listener->proto_specific.tcp.port, strerror(errno));
2544 break;
2545 default:
2546 moonbr_log(LOG_ERR, "Internal error (should not happen): Unexpected value in listener.proto field");
2547 moonbr_terminate_error();
2549 goto moonbr_listen_error;
2552 return 0;
2553 moonbr_listen_error:
2554 moonbr_destroy_pool(pool);
2555 lua_pushnil(L);
2556 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_prepare_func(pool));
2557 lua_pushnil(L);
2558 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_connect_func(pool));
2559 lua_pushnil(L);
2560 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_finish_func(pool));
2561 lua_error(L);
2562 return 0; /* avoid compiler warning */
2566 /*** Function to modify Lua's library path and/or cpath ***/
2568 #if defined(MOONBR_LUA_PATH) || defined(MOONBR_LUA_CPATH)
2569 static void moonbr_modify_path(lua_State *L, char *key, char *value) {
2570 int stackbase;
2571 stackbase = lua_gettop(L);
2572 lua_getglobal(L, "package");
2573 lua_getfield(L, stackbase+1, key);
2575 const char *current_str;
2576 size_t current_strlen;
2577 luaL_Buffer buf;
2578 current_str = lua_tolstring(L, stackbase+2, &current_strlen);
2579 luaL_buffinit(L, &buf);
2580 if (current_str) {
2581 lua_pushvalue(L, stackbase+2);
2582 luaL_addvalue(&buf);
2583 if (current_strlen && current_str[current_strlen-1] != ';') {
2584 luaL_addchar(&buf, ';');
2587 luaL_addstring(&buf, value);
2588 luaL_pushresult(&buf);
2590 lua_setfield(L, stackbase+1, key);
2591 lua_settop(L, stackbase);
2593 #endif
2596 /*** Main function and command line invokation ***/
2598 static void moonbr_usage(int err, const char *cmd) {
2599 FILE *out;
2600 out = err ? stderr : stdout;
2601 if (!cmd) cmd = "moonbridge";
2602 fprintf(out, "Get this help message: %s {-h|--help}\n", cmd);
2603 fprintf(out, "Usage: %s \\\n", cmd);
2604 fprintf(out, " [-b|--background] \\\n");
2605 fprintf(out, " [-d|--debug] \\\n");
2606 fprintf(out, " [-f|--logfacility {DAEMON|USER|0|1|...|7}] \\\n");
2607 fprintf(out, " [-i|--logident <syslog ident> \\\n");
2608 fprintf(out, " [-l|--logfile <logfile>] \\\n");
2609 fprintf(out, " [-p|--pidfile <pidfile>] \\\n");
2610 fprintf(out, " [-s|--stats] \\\n");
2611 fprintf(out, " -- <Lua script> [<cmdline options for Lua script>]\n");
2612 exit(err);
2615 #define moonbr_usage_error() moonbr_usage(MOONBR_EXITCODE_CMDLINEERROR, argc ? argv[0] : NULL)
2617 int main(int argc, char **argv) {
2619 int daemonize = 0;
2620 int log_facility = LOG_USER;
2621 const char *log_ident = "moonbridge";
2622 const char *log_filename = NULL;
2623 const char *pid_filename = NULL;
2624 int option;
2625 struct option longopts[] = {
2626 { "background", no_argument, NULL, 'b' },
2627 { "debug", no_argument, NULL, 'd' },
2628 { "logfacility", required_argument, NULL, 'f' },
2629 { "help", no_argument, NULL, 'h' },
2630 { "logident", required_argument, NULL, 'i' },
2631 { "logfile", required_argument, NULL, 'l' },
2632 { "pidfile", required_argument, NULL, 'p' },
2633 { "stats", no_argument, NULL, 's' }
2634 };
2635 while ((option = getopt_long(argc, argv, "bdf:hi:l:p:s", longopts, NULL)) != -1) {
2636 switch (option) {
2637 case 'b':
2638 daemonize = 1;
2639 break;
2640 case 'd':
2641 moonbr_debug = 1;
2642 moonbr_stat = 1;
2643 break;
2644 case 'f':
2645 if (!strcmp(optarg, "DAEMON")) {
2646 log_facility = LOG_DAEMON;
2647 } else if (!strcmp(optarg, "USER")) {
2648 log_facility = LOG_USER;
2649 } else if (!strcmp(optarg, "0")) {
2650 log_facility = LOG_LOCAL0;
2651 } else if (!strcmp(optarg, "1")) {
2652 log_facility = LOG_LOCAL1;
2653 } else if (!strcmp(optarg, "2")) {
2654 log_facility = LOG_LOCAL2;
2655 } else if (!strcmp(optarg, "3")) {
2656 log_facility = LOG_LOCAL3;
2657 } else if (!strcmp(optarg, "4")) {
2658 log_facility = LOG_LOCAL4;
2659 } else if (!strcmp(optarg, "5")) {
2660 log_facility = LOG_LOCAL5;
2661 } else if (!strcmp(optarg, "6")) {
2662 log_facility = LOG_LOCAL6;
2663 } else if (!strcmp(optarg, "7")) {
2664 log_facility = LOG_LOCAL7;
2665 } else {
2666 moonbr_usage_error();
2668 moonbr_use_syslog = 1;
2669 break;
2670 case 'h':
2671 moonbr_usage(MOONBR_EXITCODE_GRACEFUL, argv[0]);
2672 break;
2673 case 'i':
2674 log_ident = optarg;
2675 moonbr_use_syslog = 1;
2676 break;
2677 case 'l':
2678 log_filename = optarg;
2679 break;
2680 case 'p':
2681 pid_filename = optarg;
2682 break;
2683 case 's':
2684 moonbr_stat = 1;
2685 break;
2686 default:
2687 moonbr_usage_error();
2690 if (argc - optind < 1) moonbr_usage_error();
2691 if (pid_filename) {
2692 pid_t otherpid;
2693 while ((moonbr_pidfh = pidfile_open(pid_filename, 0644, &otherpid)) == NULL) {
2694 if (errno == EEXIST) {
2695 if (otherpid == -1) {
2696 fprintf(stderr, "PID file \"%s\" is already locked\n", pid_filename);
2697 } else {
2698 fprintf(stderr, "PID file \"%s\" is already locked by process with PID: %i\n", pid_filename, (int)otherpid);
2700 exit(MOONBR_EXITCODE_ALREADYRUNNING);
2701 } else if (errno != EINTR) {
2702 fprintf(stderr, "Could not write PID file \"%s\": %s\n", pid_filename, strerror(errno));
2703 exit(MOONBR_EXITCODE_STARTUPERROR);
2707 if (log_filename) {
2708 int logfd;
2709 while (
2710 ( logfd = flopen(
2711 log_filename,
2712 O_WRONLY|O_NONBLOCK|O_CREAT|O_APPEND|O_CLOEXEC,
2713 0640
2715 ) < 0
2716 ) {
2717 if (errno == EWOULDBLOCK) {
2718 fprintf(stderr, "Logfile \"%s\" is locked\n", log_filename);
2719 exit(MOONBR_EXITCODE_ALREADYRUNNING);
2720 } else if (errno != EINTR) {
2721 fprintf(stderr, "Could not open logfile \"%s\": %s\n", log_filename, strerror(errno));
2722 exit(MOONBR_EXITCODE_STARTUPERROR);
2725 moonbr_logfile = fdopen(logfd, "a");
2726 if (!moonbr_logfile) {
2727 fprintf(stderr, "Could not open write stream to logfile \"%s\": %s\n", log_filename, strerror(errno));
2728 exit(MOONBR_EXITCODE_STARTUPERROR);
2731 if (daemonize == 0 && !moonbr_logfile) moonbr_logfile = stderr;
2732 if (moonbr_logfile) setlinebuf(moonbr_logfile);
2733 else moonbr_use_syslog = 1;
2734 if (moonbr_use_syslog) openlog(log_ident, LOG_NDELAY | LOG_PID, log_facility);
2735 if (daemonize) {
2736 if (daemon(1, 0)) {
2737 moonbr_log(LOG_ERR, "Could not daemonize moonbridge process");
2738 moonbr_terminate_error();
2742 moonbr_log(LOG_NOTICE, "Starting moonbridge server");
2743 if (moonbr_pidfh && pidfile_write(moonbr_pidfh)) {
2744 moonbr_log(LOG_ERR, "Could not write pidfile (after locking)");
2747 lua_State *L;
2748 L = lua_newstate(moonbr_alloc, NULL);
2749 if (!L) {
2750 moonbr_log(LOG_CRIT, "Could not initialize Lua state");
2751 moonbr_terminate_error();
2753 lua_atpanic(L, moonbr_lua_panic);
2754 luaL_openlibs(L);
2755 #ifdef MOONBR_LUA_PATH
2756 moonbr_modify_path(L, "path", MOONBR_LUA_PATH);
2757 #endif
2758 #ifdef MOONBR_LUA_CPATH
2759 moonbr_modify_path(L, "cpath", MOONBR_LUA_CPATH);
2760 #endif
2761 if (luaL_newmetatable(L, LUA_FILEHANDLE)) {
2762 moonbr_log(LOG_CRIT, "Lua metatable LUA_FILEHANDLE does not exist");
2763 moonbr_terminate_error();
2765 lua_getfield(L, -1, "__index");
2766 lua_pushcfunction(L, moonbr_readuntil);
2767 lua_setfield(L, -2, "readuntil");
2768 lua_pop(L, 2);
2769 lua_pushcfunction(L, moonbr_timeout);
2770 lua_setglobal(L, "timeout");
2771 lua_pushcfunction(L, moonbr_listen);
2772 lua_setglobal(L, "listen");
2773 lua_pushcfunction(L, moonbr_addtraceback); /* on stack position 1 */
2774 moonbr_log(LOG_INFO, "Loading \"%s\"", argv[optind]);
2775 if (luaL_loadfile(L, argv[optind])) {
2776 moonbr_log(LOG_ERR, "Error while loading \"%s\": %s", argv[optind], lua_tostring(L, -1));
2777 moonbr_terminate_error();
2779 { int i; for (i=optind+1; i<argc; i++) lua_pushstring(L, argv[i]); }
2780 if (lua_pcall(L, argc-(optind+1), 0, 1)) {
2781 moonbr_log(LOG_ERR, "Error while executing \"%s\": %s", argv[optind], lua_tostring(L, -1));
2782 moonbr_terminate_error();
2784 if (!moonbr_first_pool) {
2785 moonbr_log(LOG_WARNING, "No listener initialized.");
2786 moonbr_terminate_error();
2788 lua_getglobal(L, "listen");
2789 lua_pushcfunction(L, moonbr_listen);
2790 if (lua_compare(L, -2, -1, LUA_OPEQ)) {
2791 lua_pushnil(L);
2792 lua_setglobal(L, "listen");
2794 lua_settop(L, 1);
2795 lua_gc(L, LUA_GCCOLLECT, 0); // collect garbage before forking later
2796 moonbr_run(L);
2798 return 0;

Impressum / About Us