moonbridge

view moonbridge.c @ 0:f6d3b3f70dab

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

Impressum / About Us