moonbridge

view moonbridge.c @ 67:c488f2ea29aa

Fixed typo in moonbridge.c
author jbe
date Sat Apr 04 11:42:34 2015 +0200 (2015-04-04)
parents 3d1f23f1dbc6
children ad06fc76906a
line source
2 /*** Version ***/
3 #define MOONBR_VERSION_STRING "0.4.0"
6 /*** Compile-time configuration ***/
8 #define MOONBR_LUA_PANIC_BUG_WORKAROUND 1
11 /*** C preprocessor macros for portability support ***/
13 #ifndef __has_include
14 #define __has_include(x) 0
15 #endif
18 /*** Include directives for used system libraries ***/
20 #if defined(__linux__)
21 #define _GNU_SOURCE
22 #endif
23 #include <stdlib.h>
24 #include <unistd.h>
25 #include <stdint.h>
26 #include <errno.h>
27 #include <getopt.h>
28 #include <syslog.h>
29 #include <string.h>
30 #include <stdio.h>
31 #include <time.h>
32 #include <sys/time.h>
33 #include <sys/socket.h>
34 #include <sys/un.h>
35 #include <netinet/in.h>
36 #include <poll.h>
37 #include <signal.h>
38 #include <sys/wait.h>
39 #include <sys/resource.h>
40 #include <sys/file.h>
41 #if defined(__FreeBSD__) || __has_include(<libutil.h>)
42 #include <libutil.h>
43 #endif
44 #if defined(__linux__) || __has_include(<bsd/stdio.h>)
45 #include <bsd/stdio.h>
46 #endif
47 #if defined(__linux__) || __has_include(<bsd/libutil.h>)
48 #include <bsd/libutil.h>
49 #endif
50 #if defined(__linux__) || __has_include(<bsd/unistd.h>)
51 #include <bsd/unistd.h>
52 #endif
55 /*** Fallback definitions for missing constants on some platforms ***/
57 /* INFTIM is used as timeout parameter for poll() */
58 #ifndef INFTIM
59 #define INFTIM -1
60 #endif
63 /*** Include directives for Lua ***/
65 #include <lua.h>
66 #include <lauxlib.h>
67 #include <lualib.h>
70 /*** Constants ***/
72 /* Backlog option for listen() call */
73 #define MOONBR_LISTEN_BACKLOG 1024
75 /* Maximum length of a timestamp used for strftime() */
76 #define MOONBR_LOG_MAXTIMELEN 40
78 /* Maximum length of a log message */
79 #define MOONBR_LOG_MAXMSGLEN 4095
81 /* Exitcodes passed to exit() call */
82 #define MOONBR_EXITCODE_GRACEFUL 0
83 #define MOONBR_EXITCODE_CMDLINEERROR 1
84 #define MOONBR_EXITCODE_ALREADYRUNNING 2
85 #define MOONBR_EXITCODE_STARTUPERROR 3
86 #define MOONBR_EXITCODE_RUNTIMEERROR 4
88 /* Maximum length of a line sent to stderr by child processes */
89 #define MOONBR_MAXERRORLINELEN 1024
91 /* Maximum length of an error string returned by strerror() */
92 #define MOONBR_MAXSTRERRORLEN 80
94 /* Status bytes exchanged between master and child processes */
95 #define MOONBR_SOCKETTYPE_INTERVAL 'I'
96 #define MOONBR_SOCKETTYPE_LOCAL 'L'
97 #define MOONBR_SOCKETTYPE_NETWORK 'N'
98 #define MOONBR_STATUS_IDLE '1'
99 #define MOONBR_COMMAND_TERMINATE '2'
100 #define MOONBR_STATUS_GOODBYE '3'
102 /* Constant file descriptors */
103 #define MOONBR_FD_STDERR 2
104 #define MOONBR_FD_CONTROL 3
105 #define MOONBR_FD_END 4
107 /* Return values of moonbr_try_destroy_worker() */
108 #define MOONBR_DESTROY_NONE 0
109 #define MOONBR_DESTROY_PREPARE 1
110 #define MOONBR_DESTROY_IDLE_OR_ASSIGNED 2
113 /*** Types ***/
115 /* Enum for 'moonbr_pstate' */
116 #define MOONBR_PSTATE_STARTUP 0
117 #define MOONBR_PSTATE_RUNNING 1
118 #define MOONBR_PSTATE_FORKED 2
120 /* Enum for 'proto' field of struct moonbr_listener */
121 #define MOONBR_PROTO_INTERVAL 1
122 #define MOONBR_PROTO_LOCAL 2
123 #define MOONBR_PROTO_TCP6 3
124 #define MOONBR_PROTO_TCP4 4
126 /* Data structure for a pool's listener that can accept incoming connections */
127 struct moonbr_listener {
128 struct moonbr_pool *pool;
129 struct moonbr_listener *prev_listener; /* previous idle or(!) connected listener */
130 struct moonbr_listener *next_listener; /* next idle or(!) connected listener */
131 int proto;
132 union {
133 struct {
134 char *name; /* name of interval passed to 'connect' function as 'interval' field in table */
135 int strict; /* nonzero = runtime of 'connect' function does not delay interval */
136 struct timeval delay; /* interval between invocations of 'connect' function */
137 struct timeval wakeup; /* point in time of next invocation */
138 } interval;
139 struct {
140 char *path; /* full path name (i.e. filename with path) of UNIX domain socket */
141 } local;
142 struct {
143 int port; /* port number to listen on (in host endianess) */
144 int localhost_only; /* nonzero = listen on localhost only */
145 } tcp;
146 } proto_specific;
147 int listenfd; /* -1 = none */
148 int pollidx; /* -1 = none */
149 };
151 /* Data structure for a child process that is handling incoming connections */
152 struct moonbr_worker {
153 struct moonbr_pool *pool;
154 struct moonbr_worker *prev_worker;
155 struct moonbr_worker *next_worker;
156 struct moonbr_worker *prev_idle_worker;
157 struct moonbr_worker *next_idle_worker;
158 int idle; /* nonzero = waiting for command from parent process */
159 int assigned; /* nonzero = currently handling a connection */
160 pid_t pid;
161 int controlfd; /* socket to send/receive control message to/from child process */
162 int errorfd; /* socket to receive error output from child process' stderr */
163 char *errorlinebuf; /* optional buffer for collecting stderr data from child process */
164 int errorlinelen; /* number of bytes stored in 'errorlinebuf' */
165 int errorlineovf; /* nonzero = line length overflow */
166 struct timeval idle_expiration; /* point in time until child process may stay in idle state */
167 struct moonbr_listener *restart_interval_listener; /* set while interval listener is assigned */
168 };
170 /* Data structure for a pool of workers and listeners */
171 struct moonbr_pool {
172 int poolnum; /* number of pool for log output */
173 struct moonbr_pool *next_pool; /* next entry in linked list starting with 'moonbr_first_pool' */
174 struct moonbr_worker *first_worker; /* first worker of pool */
175 struct moonbr_worker *last_worker; /* last worker of pool */
176 struct moonbr_worker *first_idle_worker; /* first idle worker of pool */
177 struct moonbr_worker *last_idle_worker; /* last idle worker of pool */
178 int idle_worker_count;
179 int unassigned_worker_count;
180 int total_worker_count;
181 int worker_count_stat; /* only needed for statistics */
182 int pre_fork; /* desired minimum number of unassigned workers */
183 int min_fork; /* desired minimum number of workers in total */
184 int max_fork; /* maximum number of workers */
185 struct timeval fork_delay; /* delay after each fork() until a fork may happen again */
186 struct timeval fork_wakeup; /* point in time when a fork may happen again (unless a worker terminates before) */
187 struct timeval fork_error_delay; /* delay between fork()s when an error during fork or preparation occurred */
188 struct timeval fork_error_wakeup; /* point in time when fork may happen again if an error in preparation occurred */
189 int use_fork_error_wakeup; /* nonzero = error in preparation occured; gets reset on next fork */
190 struct timeval exit_delay; /* delay for terminating excessive workers (unassigned_worker_count > pre_fork) */
191 struct timeval exit_wakeup; /* point in time when terminating an excessive worker */
192 struct timeval idle_timeout; /* delay before an idle worker is terminated */
193 size_t memory_limit; /* maximum bytes of memory that the Lua machine may allocate */
194 int listener_count; /* total number of listeners of pool (and size of 'listener' array at end of this struct) */
195 struct moonbr_listener *first_idle_listener; /* first listener that is idle (i.e. has no waiting connection) */
196 struct moonbr_listener *last_idle_listener; /* last listener that is idle (i.e. has no waiting connection) */
197 struct moonbr_listener *first_connected_listener; /* first listener that has a pending connection */
198 struct moonbr_listener *last_connected_listener; /* last listener that has a pending connection */
199 struct moonbr_listener listener[1]; /* static array of variable(!) size to contain 'listener' structures */
200 };
202 /* Enum for 'channel' field of struct moonbr_poll_worker */
203 #define MOONBR_POLL_WORKER_CONTROLCHANNEL 1
204 #define MOONBR_POLL_WORKER_ERRORCHANNEL 2
206 /* Structure to refer from 'moonbr_poll_worker_fds' entry to worker structure */
207 struct moonbr_poll_worker {
208 struct moonbr_worker *worker;
209 int channel; /* field indicating whether file descriptor is 'controlfd' or 'errorfd' */
210 };
212 /* Variable indicating that clean shutdown was requested */
213 static int moonbr_shutdown_in_progress = 0;
216 /*** Macros for Lua registry ***/
218 /* Lightuserdata keys for Lua registry to store 'prepare', 'connect', and 'finish' functions */
219 #define moonbr_luakey_prepare_func(pool) ((void *)(intptr_t)(pool) + 0)
220 #define moonbr_luakey_connect_func(pool) ((void *)(intptr_t)(pool) + 1)
221 #define moonbr_luakey_finish_func(pool) ((void *)(intptr_t)(pool) + 2)
224 /*** Global variables ***/
226 /* State of process execution */
227 static int moonbr_pstate = MOONBR_PSTATE_STARTUP;
229 /* Process ID of the main process */
230 static pid_t moonbr_masterpid;
232 /* Condition variables set by the signal handler */
233 static volatile sig_atomic_t moonbr_cond_poll = 0;
234 static volatile sig_atomic_t moonbr_cond_terminate = 0;
235 static volatile sig_atomic_t moonbr_cond_interrupt = 0;
236 static volatile sig_atomic_t moonbr_cond_child = 0;
238 /* Socket pair to denote signal delivery when signal handler was called just before poll() */
239 static int moonbr_poll_signalfds[2];
240 #define moonbr_poll_signalfd_read moonbr_poll_signalfds[0]
241 #define moonbr_poll_signalfd_write moonbr_poll_signalfds[1]
243 /* Global variables for pidfile and logging */
244 static struct pidfh *moonbr_pidfh = NULL;
245 static FILE *moonbr_logfile = NULL;
246 static int moonbr_use_syslog = 0;
248 /* First and last entry of linked list of all created pools during initialization */
249 static struct moonbr_pool *moonbr_first_pool = NULL;
250 static struct moonbr_pool *moonbr_last_pool = NULL;
252 /* Total count of pools */
253 static int moonbr_pool_count = 0;
255 /* Set to a nonzero value if dynamic part of 'moonbr_poll_fds' ('moonbr_poll_worker_fds') needs an update */
256 static int moonbr_poll_refresh_needed = 0;
258 /* Array passed to poll(), consisting of static part and dynamic part ('moonbr_poll_worker_fds') */
259 static struct pollfd *moonbr_poll_fds = NULL; /* the array */
260 static int moonbr_poll_fds_bufsize = 0; /* memory allocated for this number of elements */
261 static int moonbr_poll_fds_count = 0; /* total number of elements */
262 static int moonbr_poll_fds_static_count; /* number of elements in static part */
264 /* Dynamic part of 'moonbr_poll_fds' array */
265 #define moonbr_poll_worker_fds (moonbr_poll_fds+moonbr_poll_fds_static_count)
267 /* Additional information for dynamic part of 'moonbr_poll_fds' array */
268 struct moonbr_poll_worker *moonbr_poll_workers; /* the array */
269 static int moonbr_poll_workers_bufsize = 0; /* memory allocated for this number of elements */
270 static int moonbr_poll_worker_count = 0; /* number of elements in array */
272 /* Variable set to nonzero value to disallow further calls of 'listen' function */
273 static int moonbr_booted = 0;
275 /* Global variables to store information on connection socket in child process */
276 static int moonbr_child_peersocket_type; /* type of socket by MOONBR_SOCKETTYPE constant */
277 static int moonbr_child_peersocket_fd; /* Original file descriptor of peer socket */
278 static luaL_Stream *moonbr_child_peersocket_inputstream; /* Lua input stream of socket */
279 static luaL_Stream *moonbr_child_peersocket_outputstream; /* Lua output stream of socket */
281 /* Verbosity settings */
282 static int moonbr_debug = 0;
283 static int moonbr_stat = 0;
285 /* Memory consumption by Lua machine */
286 static size_t moonbr_memory_usage = 0;
287 static size_t moonbr_memory_limit = 0;
290 /*** Functions for signal handling ***/
292 /* Signal handler for master and child processes */
293 static void moonbr_signal(int sig) {
294 if (getpid() == moonbr_masterpid) {
295 /* master process */
296 switch (sig) {
297 case SIGHUP:
298 case SIGINT:
299 /* fast shutdown requested */
300 moonbr_cond_interrupt = 1;
301 break;
302 case SIGTERM:
303 /* clean shutdown requested */
304 moonbr_cond_terminate = 1;
305 break;
306 case SIGCHLD:
307 /* child process terminated */
308 moonbr_cond_child = 1;
309 break;
310 }
311 if (moonbr_cond_poll) {
312 /* avoid race condition if signal handler is invoked right before poll() */
313 char buf[1] = {0};
314 write(moonbr_poll_signalfd_write, buf, 1);
315 }
316 } else {
317 /* child process forwards certain signals to parent process */
318 switch (sig) {
319 case SIGHUP:
320 case SIGINT:
321 case SIGTERM:
322 kill(moonbr_masterpid, sig);
323 }
324 }
325 }
327 /* Initialize signal handling */
328 static void moonbr_signal_init(){
329 moonbr_masterpid = getpid();
330 signal(SIGHUP, moonbr_signal);
331 signal(SIGINT, moonbr_signal);
332 signal(SIGTERM, moonbr_signal);
333 signal(SIGCHLD, moonbr_signal);
334 signal(SIGPIPE, SIG_IGN); /* generate I/O errors instead of signal 13 */
335 }
338 /*** Functions for logging in master process ***/
340 /* Logs a pre-formatted message with given syslog() priority */
341 static void moonbr_log_msg(int priority, const char *msg) {
342 if (moonbr_logfile) {
343 /* logging to logfile desired (timestamp is prepended in that case) */
344 time_t now_time = 0;
345 struct tm now_tmstruct;
346 char timestr[MOONBR_LOG_MAXTIMELEN+1];
347 time(&now_time);
348 localtime_r(&now_time, &now_tmstruct);
349 if (!strftime(
350 timestr, MOONBR_LOG_MAXTIMELEN+1, "%Y-%m-%d %H:%M:%S %Z: ", &now_tmstruct
351 )) timestr[0] = 0;
352 fprintf(moonbr_logfile, "%s%s\n", timestr, msg);
353 }
354 if (moonbr_use_syslog) {
355 /* logging through syslog desired */
356 syslog(priority, "%s", msg);
357 }
358 }
360 /* Formats a message via vsnprintf() and logs it with given syslog() priority */
361 static void moonbr_log(int priority, const char *message, ...) {
362 char msgbuf[MOONBR_LOG_MAXMSGLEN+1]; /* buffer of static size to store formatted message */
363 int msglen; /* length of full message (may exceed MOONBR_LOG_MAXMSGLEN) */
364 {
365 /* pass variable arguments to vsnprintf() to format message */
366 va_list ap;
367 va_start(ap, message);
368 msglen = vsnprintf(msgbuf, MOONBR_LOG_MAXMSGLEN+1, message, ap);
369 va_end(ap);
370 }
371 {
372 /* split and log message line by line */
373 char *line = msgbuf;
374 while (1) {
375 char *endptr = strchr(line, '\n');
376 if (endptr) {
377 /* terminate string where newline character is found */
378 *endptr = 0;
379 } else if (line != msgbuf && msglen > MOONBR_LOG_MAXMSGLEN) {
380 /* break if line is incomplete and not the first line */
381 break;
382 }
383 moonbr_log_msg(priority, line);
384 if (!endptr) break; /* break if end of formatted message is reached */
385 line = endptr+1; /* otherwise continue with remaining message */
386 }
387 }
388 if (msglen > MOONBR_LOG_MAXMSGLEN) {
389 /* print warning if message was truncated */
390 moonbr_log_msg(priority, "Previous log message has been truncated due to excessive length");
391 }
392 }
395 /*** Termination function ***/
397 /* Kill all child processes, remove PID file (if existent), and exit master process with given exitcode */
398 static void moonbr_terminate(int exitcode) {
399 {
400 struct moonbr_pool *pool;
401 for (pool=moonbr_first_pool; pool; pool=pool->next_pool) {
402 {
403 struct moonbr_worker *worker;
404 for (worker=pool->first_worker; worker; worker=worker->next_worker) {
405 moonbr_log(LOG_INFO, "Sending SIGKILL to child with PID %i", (int)worker->pid);
406 if (kill(worker->pid, SIGKILL)) {
407 moonbr_log(LOG_ERR, "Error while killing child process: %s", strerror(errno));
408 }
409 }
410 }
411 {
412 int i;
413 for (i=0; i<pool->listener_count; i++) {
414 struct moonbr_listener *listener = &pool->listener[i];
415 if (listener->proto == MOONBR_PROTO_LOCAL) {
416 moonbr_log(LOG_INFO, "Unlinking local socket \"%s\"", listener->proto_specific.local.path);
417 if (unlink(listener->proto_specific.local.path)) {
418 moonbr_log(LOG_ERR, "Error while unlinking local socket: %s", strerror(errno));
419 }
420 }
421 }
422 }
423 }
424 }
425 moonbr_log(exitcode ? LOG_ERR : LOG_NOTICE, "Terminating with exit code %i", exitcode);
426 if (moonbr_pidfh && pidfile_remove(moonbr_pidfh)) {
427 moonbr_log(LOG_ERR, "Error while removing PID file: %s", strerror(errno));
428 }
429 exit(exitcode);
430 }
432 /* Terminate with either MOONBR_EXITCODE_STARTUPERROR or MOONBR_EXITCODE_RUNTIMEERROR */
433 #define moonbr_terminate_error() \
434 moonbr_terminate( \
435 moonbr_pstate == MOONBR_PSTATE_STARTUP ? \
436 MOONBR_EXITCODE_STARTUPERROR : \
437 MOONBR_EXITCODE_RUNTIMEERROR \
438 )
441 /*** Helper functions ***/
443 /* Fills a 'struct timeval' structure with the current time (using CLOCK_MONOTONIC) */
444 static void moonbr_now(struct timeval *now) {
445 struct timespec ts = {0, };
446 if (clock_gettime(CLOCK_MONOTONIC, &ts)) {
447 moonbr_log(LOG_CRIT, "Error in clock_gettime() call: %s", strerror(errno));
448 moonbr_terminate_error();
449 }
450 *now = (struct timeval){ .tv_sec = ts.tv_sec, .tv_usec = ts.tv_nsec / 1000 };
451 }
453 /* Formats a 'struct timeval' value (not thread-safe) */
454 static char *moonbr_format_timeval(struct timeval *t) {
455 static char buf[32];
456 snprintf(buf, 32, "%ji.%06ji seconds", (intmax_t)t->tv_sec, (intmax_t)t->tv_usec);
457 return buf;
458 }
461 /*** Functions for pool creation and startup ***/
463 /* Creates a 'struct moonbr_pool' structure with a given number of listeners */
464 static struct moonbr_pool *moonbr_create_pool(int listener_count) {
465 struct moonbr_pool *pool;
466 pool = calloc(1,
467 sizeof(struct moonbr_pool) + /* size of 'struct moonbr_pool' with one listener */
468 (listener_count-1) * sizeof(struct moonbr_listener) /* size of extra listeners */
469 );
470 if (!pool) {
471 moonbr_log(LOG_CRIT, "Memory allocation error");
472 moonbr_terminate_error();
473 }
474 pool->listener_count = listener_count;
475 {
476 /* initialization of listeners */
477 int i;
478 for (i=0; i<listener_count; i++) {
479 struct moonbr_listener *listener = &pool->listener[i];
480 listener->pool = pool;
481 listener->listenfd = -1;
482 listener->pollidx = -1;
483 }
484 }
485 return pool;
486 }
488 /* Destroys a 'struct moonbr_pool' structure before it has been started */
489 static void moonbr_destroy_pool(struct moonbr_pool *pool) {
490 int i;
491 for (i=0; i<pool->listener_count; i++) {
492 struct moonbr_listener *listener = &pool->listener[i];
493 if (
494 listener->proto == MOONBR_PROTO_INTERVAL &&
495 listener->proto_specific.interval.name
496 ) {
497 free(listener->proto_specific.interval.name);
498 }
499 if (
500 listener->proto == MOONBR_PROTO_LOCAL &&
501 listener->proto_specific.local.path
502 ) {
503 free(listener->proto_specific.local.path);
504 }
505 }
506 free(pool);
507 }
509 /* Starts a all listeners in a pool */
510 static int moonbr_start_pool(struct moonbr_pool *pool) {
511 moonbr_log(LOG_INFO, "Creating pool", pool->poolnum);
512 {
513 int i;
514 for (i=0; i<pool->listener_count; i++) {
515 struct moonbr_listener *listener = &pool->listener[i];
516 switch (listener->proto) {
517 case MOONBR_PROTO_INTERVAL:
518 /* nothing to do here: starting intervals is performed in moonbr_run() function */
519 if (!listener->proto_specific.interval.name) {
520 moonbr_log(LOG_INFO, "Adding unnamed interval listener");
521 } else {
522 moonbr_log(LOG_INFO, "Adding interval listener \"%s\"", listener->proto_specific.interval.name);
523 }
524 break;
525 case MOONBR_PROTO_LOCAL:
526 moonbr_log(LOG_INFO, "Adding local socket listener for path \"%s\"", listener->proto_specific.local.path);
527 {
528 struct sockaddr_un servaddr = { .sun_family = AF_UNIX };
529 const int path_maxlen = sizeof(struct sockaddr_un) - (
530 (void *)&servaddr.sun_path - (void *)&servaddr
531 );
532 if (
533 snprintf(
534 servaddr.sun_path,
535 path_maxlen,
536 "%s",
537 listener->proto_specific.local.path
538 ) >= path_maxlen
539 ) {
540 errno = ENAMETOOLONG;
541 };
542 listener->listenfd = socket(PF_LOCAL, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
543 if (listener->listenfd == -1) goto moonbr_start_pool_error;
544 if (!unlink(listener->proto_specific.local.path)) {
545 moonbr_log(LOG_WARNING, "Unlinked named socket \"%s\" prior to listening", listener->proto_specific.local.path);
546 } else {
547 if (errno != ENOENT) {
548 moonbr_log(LOG_ERR, "Could not unlink named socket \"%s\" prior to listening: %s", listener->proto_specific.local.path, strerror(errno));
549 }
550 }
551 if (
552 bind(listener->listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr))
553 ) goto moonbr_start_pool_error;
554 if (listen(listener->listenfd, MOONBR_LISTEN_BACKLOG)) goto moonbr_start_pool_error;
555 }
556 break;
557 case MOONBR_PROTO_TCP6:
558 if (listener->proto_specific.tcp.localhost_only) {
559 moonbr_log(LOG_INFO, "Adding localhost TCP/IPv6 listener on port %i", listener->proto_specific.tcp.port);
560 } else {
561 moonbr_log(LOG_INFO, "Adding public TCP/IPv6 listener on port %i", listener->proto_specific.tcp.port);
562 }
563 {
564 struct sockaddr_in6 servaddr = {
565 .sin6_family = AF_INET6,
566 .sin6_port = htons(listener->proto_specific.tcp.port)
567 };
568 listener->listenfd = socket(PF_INET6, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
569 if (listener->listenfd == -1) goto moonbr_start_pool_error;
570 {
571 /* avoid "Address already in use" error when restarting service */
572 static const int reuseval = 1;
573 if (setsockopt(
574 listener->listenfd, SOL_SOCKET, SO_REUSEADDR, &reuseval, sizeof(reuseval)
575 )) goto moonbr_start_pool_error;
576 }
577 {
578 /* default to send TCP RST when process terminates unexpectedly */
579 static const struct linger lingerval = {
580 .l_onoff = 1,
581 .l_linger = 0
582 };
583 if (setsockopt(
584 listener->listenfd, SOL_SOCKET, SO_LINGER, &lingerval, sizeof(lingerval)
585 )) goto moonbr_start_pool_error;
586 }
587 if (listener->proto_specific.tcp.localhost_only) {
588 servaddr.sin6_addr.s6_addr[15] = 1;
589 }
590 if (
591 bind(listener->listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr))
592 ) goto moonbr_start_pool_error;
593 if (listen(listener->listenfd, MOONBR_LISTEN_BACKLOG)) goto moonbr_start_pool_error;
594 }
595 break;
596 case MOONBR_PROTO_TCP4:
597 if (listener->proto_specific.tcp.localhost_only) {
598 moonbr_log(LOG_INFO, "Adding localhost TCP/IPv4 listener on port %i", listener->proto_specific.tcp.port);
599 } else {
600 moonbr_log(LOG_INFO, "Adding public TCP/IPv4 listener on port %i", listener->proto_specific.tcp.port);
601 }
602 {
603 struct sockaddr_in servaddr = {
604 .sin_family = AF_INET,
605 .sin_port = htons(listener->proto_specific.tcp.port)
606 };
607 listener->listenfd = socket(PF_INET, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
608 if (listener->listenfd == -1) goto moonbr_start_pool_error;
609 {
610 /* avoid "Address already in use" error when restarting service */
611 static const int reuseval = 1;
612 if (setsockopt(
613 listener->listenfd, SOL_SOCKET, SO_REUSEADDR, &reuseval, sizeof(reuseval)
614 )) goto moonbr_start_pool_error;
615 }
616 {
617 /* default to send TCP RST when process terminates unexpectedly */
618 static const struct linger lingerval = {
619 .l_onoff = 1,
620 .l_linger = 0
621 };
622 if (setsockopt(
623 listener->listenfd, SOL_SOCKET, SO_LINGER, &lingerval, sizeof(lingerval)
624 )) goto moonbr_start_pool_error;
625 }
626 if (listener->proto_specific.tcp.localhost_only) {
627 ((uint8_t *)&servaddr.sin_addr.s_addr)[0] = 127;
628 ((uint8_t *)&servaddr.sin_addr.s_addr)[3] = 1;
629 }
630 if (
631 bind(listener->listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr))
632 ) goto moonbr_start_pool_error;
633 if (listen(listener->listenfd, MOONBR_LISTEN_BACKLOG)) goto moonbr_start_pool_error;
634 }
635 break;
636 default:
637 moonbr_log(LOG_CRIT, "Internal error (should not happen): Unexpected value in listener.proto field");
638 moonbr_terminate_error();
639 }
640 }
641 goto moonbr_start_pool_ok;
642 moonbr_start_pool_error:
643 {
644 int j = i;
645 int errno2 = errno;
646 for (; i>=0; i--) {
647 struct moonbr_listener *listener = &pool->listener[i];
648 if (listener->listenfd != -1) close(listener->listenfd);
649 }
650 errno = errno2;
651 return j;
652 }
653 }
654 moonbr_start_pool_ok:
655 pool->poolnum = ++moonbr_pool_count;
656 moonbr_log(LOG_INFO, "Pool #%i created", pool->poolnum);
657 if (moonbr_last_pool) moonbr_last_pool->next_pool = pool;
658 else moonbr_first_pool = pool;
659 moonbr_last_pool = pool;
660 return -1;
661 }
664 /*** Function to send data and a file descriptor to child process */
666 /* Sends control message of one bye plus optional file descriptor plus optional pointer to child process */
667 static void moonbr_send_control_message(struct moonbr_worker *worker, char status, int fd, void *ptr) {
668 {
669 struct iovec iovector = { .iov_base = &status, .iov_len = 1 }; /* carrying status byte */
670 char control_message_buffer[CMSG_SPACE(sizeof(int))] = {0, }; /* used to transfer file descriptor */
671 struct msghdr message = { .msg_iov = &iovector, .msg_iovlen = 1 }; /* data structure passed to sendmsg() call */
672 if (moonbr_debug) {
673 if (fd == -1) {
674 moonbr_log(LOG_DEBUG, "Sending control message \"%c\" to child process in pool #%i (PID %i)", (int)status, worker->pool->poolnum, (int)worker->pid);
675 } else {
676 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);
677 }
678 }
679 if (fd != -1) {
680 /* attach control message with file descriptor */
681 message.msg_control = control_message_buffer;
682 message.msg_controllen = CMSG_SPACE(sizeof(int));
683 {
684 struct cmsghdr *control_message = CMSG_FIRSTHDR(&message);
685 control_message->cmsg_level = SOL_SOCKET;
686 control_message->cmsg_type = SCM_RIGHTS;
687 control_message->cmsg_len = CMSG_LEN(sizeof(int));
688 memcpy(CMSG_DATA(control_message), &fd, sizeof(int));
689 }
690 }
691 while (sendmsg(worker->controlfd, &message, MSG_NOSIGNAL) < 0) {
692 if (errno == EPIPE) {
693 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));
694 return; /* do not close socket; socket is closed when reading from it */
695 }
696 if (errno != EINTR) {
697 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));
698 moonbr_terminate_error();
699 }
700 }
701 }
702 if (ptr) {
703 char buf[sizeof(void *)];
704 char *pos = buf;
705 int len = sizeof(void *);
706 ssize_t written;
707 if (moonbr_debug) {
708 moonbr_log(LOG_DEBUG, "Sending memory pointer to child process in pool #%i (PID %i)", (int)status, worker->pool->poolnum, (int)worker->pid);
709 }
710 memcpy(buf, &ptr, sizeof(void *));
711 while (len) {
712 written = send(worker->controlfd, pos, len, MSG_NOSIGNAL);
713 if (written > 0) {
714 pos += written;
715 len -= written;
716 } else if (errno == EPIPE) {
717 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));
718 return; /* do not close socket; socket is closed when reading from it */
719 } else if (errno != EINTR) {
720 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));
721 moonbr_terminate_error();
722 }
723 }
724 }
725 }
728 /*** Functions running in child process ***/
730 /* Logs an error in child process */
731 static void moonbr_child_log(const char *message) {
732 fprintf(stderr, "%s\n", message);
733 }
735 /* Logs a fatal error in child process and terminates process with error status */
736 static void moonbr_child_log_fatal(const char *message) {
737 moonbr_child_log(message);
738 exit(1);
739 }
741 /* Logs an error in child process while appending error string for global errno variable */
742 static void moonbr_child_log_errno(const char *message) {
743 char errmsg[MOONBR_MAXSTRERRORLEN];
744 strerror_r(errno, errmsg, MOONBR_MAXSTRERRORLEN); /* use thread-safe call in case child created threads */
745 fprintf(stderr, "%s: %s\n", message, errmsg);
746 }
748 /* Logs a fatal error in child process while appending error string for errno and terminating process */
749 static void moonbr_child_log_errno_fatal(const char *message) {
750 moonbr_child_log_errno(message);
751 exit(1);
752 }
754 /* Receives a control message consisting of one character plus an optional file descriptor from parent process */
755 static void moonbr_child_receive_control_message(int socketfd, char *status, int *fd) {
756 struct iovec iovector = { .iov_base = status, .iov_len = 1 }; /* reference to status byte variable */
757 char control_message_buffer[CMSG_SPACE(sizeof(int))] = {0, }; /* used to receive file descriptor */
758 struct msghdr message = { /* data structure passed to recvmsg() call */
759 .msg_iov = &iovector,
760 .msg_iovlen = 1,
761 .msg_control = control_message_buffer,
762 .msg_controllen = CMSG_SPACE(sizeof(int))
763 };
764 {
765 int received;
766 while ((received = recvmsg(socketfd, &message, MSG_CMSG_CLOEXEC)) < 0) {
767 if (errno != EINTR) {
768 moonbr_child_log_errno_fatal("Error while trying to receive connection socket from parent process");
769 }
770 }
771 if (!received) {
772 moonbr_child_log_fatal("Unexpected EOF while trying to receive connection socket from parent process");
773 }
774 }
775 {
776 struct cmsghdr *control_message = CMSG_FIRSTHDR(&message);
777 if (control_message) {
778 if (control_message->cmsg_level != SOL_SOCKET) {
779 moonbr_child_log_fatal("Received control message with cmsg_level not equal to SOL_SOCKET");
780 }
781 if (control_message->cmsg_type != SCM_RIGHTS) {
782 moonbr_child_log_fatal("Received control message with cmsg_type not equal to SCM_RIGHTS");
783 }
784 memcpy(fd, CMSG_DATA(control_message), sizeof(int));
785 } else {
786 *fd = -1;
787 }
788 }
789 }
791 /* Receives a pointer from parent process */
792 static void *moonbr_child_receive_pointer(int socketfd) {
793 char buf[sizeof(void *)];
794 char *pos = buf;
795 int len = sizeof(void *);
796 ssize_t bytes_read;
797 while (len) {
798 bytes_read = recv(socketfd, pos, len, 0);
799 if (bytes_read > 0) {
800 pos += bytes_read;
801 len -= bytes_read;
802 } else if (!bytes_read) {
803 moonbr_child_log_fatal("Unexpected EOF while trying to receive memory pointer from parent process");
804 } else if (errno != EINTR) {
805 moonbr_child_log_errno_fatal("Error while trying to receive memory pointer from parent process");
806 }
807 }
808 {
809 void *ptr; /* avoid breaking strict-aliasing rules */
810 memcpy(&ptr, buf, sizeof(void *));
811 return ptr;
812 }
813 }
815 /* Closes the input stream from peer unless it has already been closed */
816 static int moonbr_child_close_peersocket_inputstream(
817 int cleanshut, /* nonzero = use shutdown() if applicable */
818 int mark /* nonzero = mark the stream as closed for Lua */
819 ) {
820 int err = 0; /* nonzero = error occurred */
821 int errno2; /* stores previous errno values that take precedence */
822 if (moonbr_child_peersocket_inputstream->f) {
823 /* NOTE: shutdown() with SHUT_RD shows different behavior on different
824 * operating systems and particularly causes problems with Linux. Hence it
825 * is disabled here. */
826 /*
827 if (cleanshut && moonbr_child_peersocket_type == MOONBR_SOCKETTYPE_NETWORK) {
828 if (shutdown(moonbr_child_peersocket_fd, SHUT_RD)) {
829 errno2 = errno;
830 err = -1;
831 }
832 }
833 */
834 if (fclose(moonbr_child_peersocket_inputstream->f)) {
835 if (!err) errno2 = errno;
836 err = -1;
837 }
838 moonbr_child_peersocket_inputstream->f = NULL;
839 }
840 if (mark) moonbr_child_peersocket_inputstream->closef = NULL;
841 if (err) errno = errno2;
842 return err;
843 }
845 /* Closes the output stream to peer unless it has already been closed */
846 static int moonbr_child_close_peersocket_outputstream(
847 int cleanshut, /* nonzero = use fflush() and shutdown() if applicable */
848 int mark /* nonzero = mark the stream as closed for Lua */
849 ) {
850 int err = 0; /* nonzero = error occurred */
851 int errno2; /* stores previous errno values that take precedence */
852 if (moonbr_child_peersocket_outputstream->f) {
853 if (moonbr_child_peersocket_type == MOONBR_SOCKETTYPE_NETWORK) {
854 if (cleanshut) {
855 if (fflush(moonbr_child_peersocket_outputstream->f)) {
856 errno2 = errno;
857 err = -1;
858 } else {
859 if (shutdown(moonbr_child_peersocket_fd, SHUT_WR)) {
860 errno2 = errno;
861 err = -1;
862 }
863 }
864 } else {
865 fpurge(moonbr_child_peersocket_outputstream->f);
866 }
867 }
868 if (fclose(moonbr_child_peersocket_outputstream->f)) {
869 if (!err) errno2 = errno;
870 err = -1;
871 }
872 moonbr_child_peersocket_outputstream->f = NULL;
873 }
874 if (mark) moonbr_child_peersocket_outputstream->closef = NULL;
875 if (err) errno = errno2;
876 return err;
877 }
879 /* Perform a clean shutdown of input and output stream (may be called multiple times) */
880 static int moonbr_child_close_peersocket(int timeout) {
881 int errprio = 0;
882 int errno2;
883 if (moonbr_child_peersocket_fd == -1) return 0;
884 if (moonbr_child_close_peersocket_inputstream(1, 1)) {
885 errprio = 1;
886 errno2 = errno;
887 }
888 if (moonbr_child_close_peersocket_outputstream(1, 1)) {
889 errprio = 4;
890 errno2 = errno;
891 }
892 if (moonbr_child_peersocket_type == MOONBR_SOCKETTYPE_NETWORK) {
893 struct linger lingerval = { 0, };
894 if (timeout && !errprio) {
895 lingerval.l_onoff = 1;
896 lingerval.l_linger = timeout;
897 }
898 if (setsockopt(moonbr_child_peersocket_fd, SOL_SOCKET, SO_LINGER, &lingerval, sizeof(lingerval))) {
899 if (errprio < 2) {
900 errprio = 2;
901 errno2 = errno;
902 }
903 }
904 }
905 if (close(moonbr_child_peersocket_fd)) {
906 if (errprio < 3) {
907 errprio = 3;
908 errno2 = errno;
909 }
910 }
911 moonbr_child_peersocket_fd = -1;
912 if (errprio) {
913 errno = errno2;
914 return -1;
915 }
916 return 0;
917 }
919 /* Close socket and cause reset of TCP connection (TCP RST aka "Connection reset by peer") if possible */
920 static int moonbr_child_cancel_peersocket() {
921 int err = 0;
922 if (moonbr_child_close_peersocket_inputstream(0, 1)) err = -1;
923 if (moonbr_child_close_peersocket_outputstream(0, 1)) err = -1;
924 if (close(moonbr_child_peersocket_fd)) err = -1;
925 moonbr_child_peersocket_fd = -1;
926 return err;
927 }
929 /* Lua method for socket object to read from input stream */
930 static int moonbr_child_lua_read_stream(lua_State *L) {
931 lua_getfield(L, 1, "input");
932 lua_getfield(L, -1, "read");
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 read from input stream until terminator */
940 static int moonbr_child_lua_readuntil_stream(lua_State *L) {
941 lua_getfield(L, 1, "input");
942 lua_getfield(L, -1, "readuntil");
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 iterate over input stream */
950 static int moonbr_child_lua_lines_stream(lua_State *L) {
951 lua_getfield(L, 1, "input");
952 lua_getfield(L, -1, "lines");
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 write to output stream */
960 static int moonbr_child_lua_write_stream(lua_State *L) {
961 lua_getfield(L, 1, "output");
962 lua_getfield(L, -1, "write");
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 method for socket object to flush the output stream */
970 static int moonbr_child_lua_flush_stream(lua_State *L) {
971 lua_getfield(L, 1, "output");
972 lua_getfield(L, -1, "flush");
973 lua_insert(L, 1);
974 lua_replace(L, 2);
975 lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
976 return lua_gettop(L);
977 }
979 /* Lua function to close a single stream (input or output) from/to peer */
980 static int moonbr_child_lua_close_stream(lua_State *L) {
981 luaL_Stream *stream = lua_touserdata(L, 1);
982 if (stream == moonbr_child_peersocket_inputstream) {
983 if (moonbr_child_close_peersocket_inputstream(1, 0)) { /* don't mark as closed as it's done by Lua */
984 char errmsg[MOONBR_MAXSTRERRORLEN];
985 strerror_r(errno, errmsg, MOONBR_MAXSTRERRORLEN); /* use thread-safe call in case child created threads */
986 lua_pushnil(L);
987 lua_pushfstring(L, "Could not close input stream from peer: %s", errmsg);
988 return 2;
989 }
990 } else if (stream == moonbr_child_peersocket_outputstream) {
991 if (moonbr_child_close_peersocket_outputstream(1, 0)) { /* don't mark as closed as it's done by Lua */
992 char errmsg[MOONBR_MAXSTRERRORLEN];
993 strerror_r(errno, errmsg, MOONBR_MAXSTRERRORLEN); /* use thread-safe call in case child created threads */
994 lua_pushnil(L);
995 lua_pushfstring(L, "Could not close output stream to peer: %s", errmsg);
996 return 2;
997 }
998 } else {
999 luaL_argerror(L, 1, "Not a connection socket");
1001 lua_pushboolean(L, 1);
1002 return 1;
1005 /* Lua function to close both input and output stream from/to peer */
1006 static int moonbr_child_lua_close_both_streams(lua_State *L) {
1007 int timeout = 0;
1008 if (!lua_isnoneornil(L, 2)) {
1009 lua_Integer n = luaL_checkinteger(L, 2);
1010 luaL_argcheck(L, n >= 0 && n <= INT_MAX, 2, "out of range");
1011 timeout = n;
1013 if (moonbr_child_peersocket_fd == -1) {
1014 luaL_error(L, "Connection with peer has already been explicitly closed");
1016 if (moonbr_child_close_peersocket(timeout)) {
1017 char errmsg[MOONBR_MAXSTRERRORLEN];
1018 strerror_r(errno, errmsg, MOONBR_MAXSTRERRORLEN); /* use thread-safe call in case child created threads */
1019 lua_pushnil(L);
1020 lua_pushfstring(L, "Could not close socket connection with peer: %s", errmsg);
1021 return 2;
1023 lua_pushboolean(L, 1);
1024 return 1;
1027 /* Lua function to close both input and output stream from/to peer */
1028 static int moonbr_child_lua_cancel_both_streams(lua_State *L) {
1029 if (moonbr_child_peersocket_fd == -1) {
1030 luaL_error(L, "Connection with peer has already been explicitly closed");
1032 if (moonbr_child_cancel_peersocket()) {
1033 char errmsg[MOONBR_MAXSTRERRORLEN];
1034 strerror_r(errno, errmsg, MOONBR_MAXSTRERRORLEN); /* use thread-safe call in case child created threads */
1035 lua_pushnil(L);
1036 lua_pushfstring(L, "Could not cancel socket connection with peer: %s", errmsg);
1037 return 2;
1039 lua_pushboolean(L, 1);
1040 return 1;
1043 /* Methods of (bidirectional) socket object passed to handler */
1044 static luaL_Reg moonbr_child_lua_socket_functions[] = {
1045 {"read", moonbr_child_lua_read_stream},
1046 {"readuntil", moonbr_child_lua_readuntil_stream},
1047 {"lines", moonbr_child_lua_lines_stream},
1048 {"write", moonbr_child_lua_write_stream},
1049 {"flush", moonbr_child_lua_flush_stream},
1050 {"close", moonbr_child_lua_close_both_streams},
1051 {"cancel", moonbr_child_lua_cancel_both_streams},
1052 {NULL, NULL}
1053 };
1055 /* Main function of child process to be called after fork() and file descriptor rearrangement */
1056 void moonbr_child_run(struct moonbr_pool *pool, lua_State *L) {
1057 char controlmsg;
1058 struct itimerval notimer = { { 0, }, { 0, } };
1059 lua_rawgetp(L, LUA_REGISTRYINDEX, moonbr_luakey_prepare_func(pool));
1060 if (lua_isnil(L, -1)) lua_pop(L, 1);
1061 else if (lua_pcall(L, 0, 0, 1)) {
1062 fprintf(stderr, "Error in \"prepare\" function: %s\n", lua_tostring(L, -1));
1063 exit(1);
1065 while (1) {
1066 struct moonbr_listener *listener;
1067 if (setitimer(ITIMER_REAL, &notimer, NULL)) {
1068 moonbr_child_log_errno_fatal("Could not reset ITIMER_REAL via setitimer()");
1070 controlmsg = MOONBR_STATUS_IDLE;
1071 if (write(MOONBR_FD_CONTROL, &controlmsg, 1) <= 0) {
1072 moonbr_child_log_errno_fatal("Error while sending ready message to parent process");
1074 moonbr_child_receive_control_message(
1075 MOONBR_FD_CONTROL,
1076 &controlmsg,
1077 &moonbr_child_peersocket_fd
1078 );
1079 if (!(
1080 (controlmsg == MOONBR_COMMAND_TERMINATE && moonbr_child_peersocket_fd == -1) ||
1081 (controlmsg == MOONBR_SOCKETTYPE_INTERVAL && moonbr_child_peersocket_fd == -1) ||
1082 (controlmsg == MOONBR_SOCKETTYPE_LOCAL && moonbr_child_peersocket_fd != -1) ||
1083 (controlmsg == MOONBR_SOCKETTYPE_NETWORK && moonbr_child_peersocket_fd != -1)
1084 )) {
1085 moonbr_child_log_fatal("Received illegal control message from parent process");
1087 if (controlmsg == MOONBR_COMMAND_TERMINATE) break;
1088 listener = moonbr_child_receive_pointer(MOONBR_FD_CONTROL);
1089 moonbr_child_peersocket_type = controlmsg;
1090 if (moonbr_child_peersocket_fd != -1) {
1092 int clonedfd;
1093 clonedfd = dup(moonbr_child_peersocket_fd);
1094 if (!clonedfd) {
1095 moonbr_child_log_errno_fatal("Could not duplicate file descriptor for input stream");
1097 moonbr_child_peersocket_inputstream = lua_newuserdata(L, sizeof(luaL_Stream));
1098 if (!moonbr_child_peersocket_inputstream) {
1099 moonbr_child_log_fatal("Memory allocation error");
1101 moonbr_child_peersocket_inputstream->f = fdopen(clonedfd, "rb");
1102 if (!moonbr_child_peersocket_inputstream->f) {
1103 moonbr_child_log_errno_fatal("Could not open input stream for remote connection");
1105 moonbr_child_peersocket_inputstream->closef = moonbr_child_lua_close_stream;
1106 if (luaL_newmetatable(L, LUA_FILEHANDLE)) {
1107 moonbr_child_log_fatal("Lua metatable LUA_FILEHANDLE does not exist");
1109 lua_setmetatable(L, -2);
1112 int clonedfd;
1113 clonedfd = dup(moonbr_child_peersocket_fd);
1114 if (!clonedfd) {
1115 moonbr_child_log_errno_fatal("Could not duplicate file descriptor for output stream");
1117 moonbr_child_peersocket_outputstream = lua_newuserdata(L, sizeof(luaL_Stream));
1118 if (!moonbr_child_peersocket_outputstream) {
1119 moonbr_child_log_fatal("Memory allocation error");
1121 moonbr_child_peersocket_outputstream->f = fdopen(clonedfd, "wb");
1122 if (!moonbr_child_peersocket_outputstream->f) {
1123 moonbr_child_log_errno_fatal("Could not open output stream for remote connection");
1125 moonbr_child_peersocket_outputstream->closef = moonbr_child_lua_close_stream;
1126 if (luaL_newmetatable(L, LUA_FILEHANDLE)) {
1127 moonbr_child_log_fatal("Lua metatable LUA_FILEHANDLE does not exist");
1129 lua_setmetatable(L, -2);
1132 lua_rawgetp(L, LUA_REGISTRYINDEX, moonbr_luakey_connect_func(pool));
1133 if (listener->proto == MOONBR_PROTO_INTERVAL) {
1134 lua_newtable(L);
1135 lua_pushstring(L,
1136 listener->proto_specific.interval.name ?
1137 listener->proto_specific.interval.name : ""
1138 );
1139 lua_setfield(L, -2, "interval");
1140 } else {
1141 lua_newtable(L);
1142 lua_pushvalue(L, -4);
1143 lua_setfield(L, -2, "input");
1144 lua_pushvalue(L, -3);
1145 lua_setfield(L, -2, "output");
1146 luaL_setfuncs(L, moonbr_child_lua_socket_functions, 0);
1147 if (listener->proto == MOONBR_PROTO_TCP6) {
1148 struct sockaddr_in6 addr;
1149 socklen_t addr_len = sizeof(struct sockaddr_in6);
1150 if (getsockname(moonbr_child_peersocket_fd, (struct sockaddr *)&addr, &addr_len)) {
1151 moonbr_child_log_errno("Could not get local IP address/port");
1152 } else {
1153 lua_pushlstring(L, (char *)addr.sin6_addr.s6_addr, 16);
1154 lua_setfield(L, -2, "local_ip6");
1155 lua_pushinteger(L, ntohs(addr.sin6_port));
1156 lua_setfield(L, -2, "local_tcpport");
1158 if (getpeername(moonbr_child_peersocket_fd, (struct sockaddr *)&addr, &addr_len)) {
1159 moonbr_child_log_errno("Could not get remote IP address/port");
1160 } else {
1161 lua_pushlstring(L, (char *)addr.sin6_addr.s6_addr, 16);
1162 lua_setfield(L, -2, "remote_ip6");
1163 lua_pushinteger(L, ntohs(addr.sin6_port));
1164 lua_setfield(L, -2, "remote_tcpport");
1166 } else if (listener->proto == MOONBR_PROTO_TCP4) {
1167 struct sockaddr_in addr;
1168 socklen_t addr_len = sizeof(struct sockaddr_in);
1169 if (getsockname(moonbr_child_peersocket_fd, (struct sockaddr *)&addr, &addr_len)) {
1170 moonbr_child_log_errno("Could not get local IP address/port");
1171 } else {
1172 lua_pushlstring(L, (char *)&addr.sin_addr.s_addr, 4);
1173 lua_setfield(L, -2, "local_ip4");
1174 lua_pushinteger(L, ntohs(addr.sin_port));
1175 lua_setfield(L, -2, "local_tcpport");
1177 if (getpeername(moonbr_child_peersocket_fd, (struct sockaddr *)&addr, &addr_len)) {
1178 moonbr_child_log_errno("Could not get remote IP address/port");
1179 } else {
1180 lua_pushlstring(L, (char *)&addr.sin_addr.s_addr, 4);
1181 lua_setfield(L, -2, "remote_ip4");
1182 lua_pushinteger(L, ntohs(addr.sin_port));
1183 lua_setfield(L, -2, "remote_tcpport");
1187 if (lua_pcall(L, 1, 1, 1)) {
1188 fprintf(stderr, "Error in \"connect\" function: %s\n", lua_tostring(L, -1));
1189 exit(1);
1191 if (moonbr_child_close_peersocket(0)) {
1192 moonbr_child_log_errno("Could not close socket connection with peer");
1194 if (lua_type(L, -1) != LUA_TBOOLEAN || !lua_toboolean(L, -1)) break;
1195 #ifdef MOONBR_LUA_PANIC_BUG_WORKAROUND
1196 lua_settop(L, 2);
1197 #else
1198 lua_settop(L, 1);
1199 #endif
1201 controlmsg = MOONBR_STATUS_GOODBYE;
1202 if (write(MOONBR_FD_CONTROL, &controlmsg, 1) <= 0) {
1203 moonbr_child_log_errno_fatal("Error while sending goodbye message to parent process");
1205 if (close(MOONBR_FD_CONTROL) && errno != EINTR) {
1206 moonbr_child_log_errno("Error while closing control socket");
1208 lua_rawgetp(L, LUA_REGISTRYINDEX, moonbr_luakey_finish_func(pool));
1209 if (lua_isnil(L, -1)) lua_pop(L, 1);
1210 else if (lua_pcall(L, 0, 0, 1)) {
1211 fprintf(stderr, "Error in \"finish\" function: %s\n", lua_tostring(L, -1));
1212 exit(1);
1214 lua_close(L);
1215 exit(0);
1219 /*** Functions to spawn child process ***/
1221 /* Helper function to send an error message to a file descriptor (not needing a file stream) */
1222 static void moonbr_child_emergency_print(int fd, char *message) {
1223 size_t len = strlen(message);
1224 ssize_t written;
1225 while (len) {
1226 written = write(fd, message, len);
1227 if (written > 0) {
1228 message += written;
1229 len -= written;
1230 } else {
1231 if (written != -1 || errno != EINTR) break;
1236 /* Helper function to send an error message plus a text for errno to a file descriptor and terminate the process */
1237 static void moonbr_child_emergency_error(int fd, char *message) {
1238 int errno2 = errno;
1239 moonbr_child_emergency_print(fd, message);
1240 moonbr_child_emergency_print(fd, ": ");
1241 moonbr_child_emergency_print(fd, strerror(errno2));
1242 moonbr_child_emergency_print(fd, "\n");
1243 exit(1);
1246 /* Creates a child process and (in case of success) registers it in the 'struct moonbr_pool' structure */
1247 static int moonbr_create_worker(struct moonbr_pool *pool, lua_State *L) {
1248 struct moonbr_worker *worker;
1249 worker = calloc(1, sizeof(struct moonbr_worker));
1250 if (!worker) {
1251 moonbr_log(LOG_CRIT, "Memory allocation error");
1252 return -1;
1254 worker->pool = pool;
1256 int controlfds[2];
1257 int errorfds[2];
1258 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, controlfds)) {
1259 moonbr_log(LOG_ERR, "Could not create control socket pair for communcation with child process: %s", strerror(errno));
1260 free(worker);
1261 return -1;
1263 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, errorfds)) {
1264 moonbr_log(LOG_ERR, "Could not create socket pair to redirect stderr of child process: %s", strerror(errno));
1265 close(controlfds[0]);
1266 close(controlfds[1]);
1267 free(worker);
1268 return -1;
1270 if (moonbr_logfile && fflush(moonbr_logfile)) {
1271 moonbr_log(LOG_CRIT, "Could not flush log file prior to forking: %s", strerror(errno));
1272 moonbr_terminate_error();
1274 worker->pid = fork();
1275 if (worker->pid == -1) {
1276 moonbr_log(LOG_ERR, "Could not fork: %s", strerror(errno));
1277 close(controlfds[0]);
1278 close(controlfds[1]);
1279 close(errorfds[0]);
1280 close(errorfds[1]);
1281 free(worker);
1282 return -1;
1283 } else if (!worker->pid) {
1284 moonbr_pstate = MOONBR_PSTATE_FORKED;
1285 #ifdef MOONBR_LUA_PANIC_BUG_WORKAROUND
1286 lua_pushliteral(L, "Failed to pass error message due to bug in Lua panic handler (hint: not enough memory?)");
1287 #endif
1288 moonbr_memory_limit = pool->memory_limit;
1289 if (moonbr_pidfh && pidfile_close(moonbr_pidfh)) {
1290 moonbr_child_emergency_error(errorfds[1], "Could not close PID file in forked child process");
1292 if (moonbr_logfile && moonbr_logfile != stderr && fclose(moonbr_logfile)) {
1293 moonbr_child_emergency_error(errorfds[1], "Could not close log file in forked child process");
1295 if (dup2(errorfds[1], MOONBR_FD_STDERR) == -1) {
1296 moonbr_child_emergency_error(errorfds[1], "Could not duplicate socket to stderr file descriptor");
1298 if (dup2(controlfds[1], MOONBR_FD_CONTROL) == -1) {
1299 moonbr_child_emergency_error(errorfds[1], "Could not duplicate control socket");
1301 closefrom(MOONBR_FD_END);
1302 moonbr_child_run(pool, L);
1304 if (moonbr_stat) {
1305 moonbr_log(LOG_INFO, "Created new worker in pool #%i with PID %i", worker->pool->poolnum, (int)worker->pid);
1307 worker->controlfd = controlfds[0];
1308 worker->errorfd = errorfds[0];
1309 if (close(controlfds[1]) && errno != EINTR) {
1310 moonbr_log(LOG_CRIT, "Could not close opposite end of control file descriptor after forking");
1311 moonbr_terminate_error();
1313 if (close(errorfds[1]) && errno != EINTR) {
1314 moonbr_log(LOG_CRIT, "Could not close opposite end of control file descriptor after forking");
1315 moonbr_terminate_error();
1318 worker->prev_worker = pool->last_worker;
1319 if (worker->prev_worker) worker->prev_worker->next_worker = worker;
1320 else pool->first_worker = worker;
1321 pool->last_worker = worker;
1322 pool->unassigned_worker_count++;
1323 pool->total_worker_count++;
1324 pool->worker_count_stat = 1;
1325 moonbr_poll_refresh_needed = 1;
1326 return 0; /* return zero only in case of success */
1330 /*** Functions to handle previously created 'struct moonbr_worker' structures ***/
1332 #define moonbr_try_destroy_worker_stat(str, field) \
1333 moonbr_log(LOG_INFO, "Resource usage in pool #%i for PID %i: " str " %li", worker->pool->poolnum, (int)worker->pid, (long)childusage.field);
1335 /* Destroys a worker structure if socket connections have been closed and child process has terminated */
1336 static int moonbr_try_destroy_worker(struct moonbr_worker *worker) {
1337 if (worker->controlfd != -1 || worker->errorfd != -1) return MOONBR_DESTROY_NONE;
1339 int childstatus;
1340 struct rusage childusage;
1342 pid_t waitedpid;
1343 while (
1344 (waitedpid = wait4(worker->pid, &childstatus, WNOHANG, &childusage)) == -1
1345 ) {
1346 if (errno != EINTR) {
1347 moonbr_log(LOG_CRIT, "Error in wait4() call: %s", strerror(errno));
1348 moonbr_terminate_error();
1351 if (!waitedpid) return 0; /* return 0 if worker couldn't be destroyed */
1352 if (waitedpid != worker->pid) {
1353 moonbr_log(LOG_CRIT, "Wrong PID returned by wait4() call");
1354 moonbr_terminate_error();
1357 if (WIFEXITED(childstatus)) {
1358 if (WEXITSTATUS(childstatus) || moonbr_stat) {
1359 moonbr_log(
1360 WEXITSTATUS(childstatus) ? LOG_WARNING : LOG_INFO,
1361 "Child process in pool #%i with PID %i returned with exit code %i", worker->pool->poolnum, (int)worker->pid, WEXITSTATUS(childstatus)
1362 );
1364 } else if (WIFSIGNALED(childstatus)) {
1365 if (WCOREDUMP(childstatus)) {
1366 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));
1367 } else if (WTERMSIG(childstatus) == SIGALRM) {
1368 moonbr_log(LOG_WARNING, "Child process in pool #%i with PID %i exited prematurely due to timeout", worker->pool->poolnum, (int)worker->pid);
1369 } else {
1370 moonbr_log(LOG_ERR, "Child process in pool #%i with PID %i died from signal %i", worker->pool->poolnum, (int)worker->pid, WTERMSIG(childstatus));
1372 } else {
1373 moonbr_log(LOG_CRIT, "Illegal exit status from child process in pool #%i with PID %i", worker->pool->poolnum, (int)worker->pid);
1374 moonbr_terminate_error();
1376 if (moonbr_stat) {
1377 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));
1378 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));
1379 moonbr_try_destroy_worker_stat("max resident set size", ru_maxrss);
1380 moonbr_try_destroy_worker_stat("integral shared memory size", ru_ixrss);
1381 moonbr_try_destroy_worker_stat("integral unshared data", ru_idrss);
1382 moonbr_try_destroy_worker_stat("integral unshared stack", ru_isrss);
1383 moonbr_try_destroy_worker_stat("page replaims", ru_minflt);
1384 moonbr_try_destroy_worker_stat("page faults", ru_majflt);
1385 moonbr_try_destroy_worker_stat("swaps", ru_nswap);
1386 moonbr_try_destroy_worker_stat("block input operations", ru_inblock);
1387 moonbr_try_destroy_worker_stat("block output operations", ru_oublock);
1388 moonbr_try_destroy_worker_stat("messages sent", ru_msgsnd);
1389 moonbr_try_destroy_worker_stat("messages received", ru_msgrcv);
1390 moonbr_try_destroy_worker_stat("signals received", ru_nsignals);
1391 moonbr_try_destroy_worker_stat("voluntary context switches", ru_nvcsw);
1392 moonbr_try_destroy_worker_stat("involuntary context switches", ru_nivcsw);
1396 int retval = (
1397 (worker->idle || worker->assigned) ?
1398 MOONBR_DESTROY_IDLE_OR_ASSIGNED :
1399 MOONBR_DESTROY_PREPARE
1400 );
1401 if (worker->prev_worker) worker->prev_worker->next_worker = worker->next_worker;
1402 else worker->pool->first_worker = worker->next_worker;
1403 if (worker->next_worker) worker->next_worker->prev_worker = worker->prev_worker;
1404 else worker->pool->last_worker = worker->prev_worker;
1405 if (worker->idle) {
1406 if (worker->prev_idle_worker) worker->prev_idle_worker->next_idle_worker = worker->next_idle_worker;
1407 else worker->pool->first_idle_worker = worker->next_idle_worker;
1408 if (worker->next_idle_worker) worker->next_idle_worker->prev_idle_worker = worker->prev_idle_worker;
1409 else worker->pool->last_idle_worker = worker->prev_idle_worker;
1410 worker->pool->idle_worker_count--;
1412 if (!worker->assigned) worker->pool->unassigned_worker_count--;
1413 worker->pool->total_worker_count--;
1414 worker->pool->worker_count_stat = 1;
1415 if (worker->errorlinebuf) free(worker->errorlinebuf);
1416 free(worker);
1417 return retval;
1421 /* Marks a worker as idle and stores it in a queue, optionally setting 'idle_expiration' value */
1422 static void moonbr_add_idle_worker(struct moonbr_worker *worker) {
1423 worker->prev_idle_worker = worker->pool->last_idle_worker;
1424 if (worker->prev_idle_worker) worker->prev_idle_worker->next_idle_worker = worker;
1425 else worker->pool->first_idle_worker = worker;
1426 worker->pool->last_idle_worker = worker;
1427 worker->idle = 1;
1428 worker->pool->idle_worker_count++;
1429 if (worker->assigned) {
1430 worker->assigned = 0;
1431 worker->pool->unassigned_worker_count++;
1433 worker->pool->worker_count_stat = 1;
1434 if (timerisset(&worker->pool->idle_timeout)) {
1435 struct timeval now;
1436 moonbr_now(&now);
1437 timeradd(&now, &worker->pool->idle_timeout, &worker->idle_expiration);
1441 /* Pops a worker from the queue of idle workers (idle queue must not be empty) */
1442 static struct moonbr_worker *moonbr_pop_idle_worker(struct moonbr_pool *pool) {
1443 struct moonbr_worker *worker;
1444 worker = pool->first_idle_worker;
1445 pool->first_idle_worker = worker->next_idle_worker;
1446 if (pool->first_idle_worker) pool->first_idle_worker->prev_idle_worker = NULL;
1447 else pool->last_idle_worker = NULL;
1448 worker->next_idle_worker = NULL;
1449 worker->idle = 0;
1450 worker->pool->idle_worker_count--;
1451 worker->assigned = 1;
1452 worker->pool->unassigned_worker_count--;
1453 worker->pool->worker_count_stat = 1;
1454 return worker;
1458 /*** Functions for queues of 'struct moonbr_listener' ***/
1460 /* Appends a 'struct moonbr_listener' to the queue of idle listeners and registers it for poll() */
1461 static void moonbr_add_idle_listener(struct moonbr_listener *listener) {
1462 listener->prev_listener = listener->pool->last_idle_listener;
1463 if (listener->prev_listener) listener->prev_listener->next_listener = listener;
1464 else listener->pool->first_idle_listener = listener;
1465 listener->pool->last_idle_listener = listener;
1466 if (listener->pollidx != -1) moonbr_poll_fds[listener->pollidx].events |= POLLIN;
1469 /* Removes a 'struct moonbr_listener' from the queue of idle listeners and unregisters it from poll() */
1470 static void moonbr_remove_idle_listener(struct moonbr_listener *listener) {
1471 if (listener->prev_listener) listener->prev_listener->next_listener = listener->next_listener;
1472 else listener->pool->first_idle_listener = listener->next_listener;
1473 if (listener->next_listener) listener->next_listener->prev_listener = listener->prev_listener;
1474 else listener->pool->last_idle_listener = listener->prev_listener;
1475 listener->prev_listener = NULL;
1476 listener->next_listener = NULL;
1477 if (listener->pollidx != -1) moonbr_poll_fds[listener->pollidx].events &= ~POLLIN;
1480 /* Adds a listener to the queue of connected listeners (i.e. waiting to have their incoming connection accepted) */
1481 static void moonbr_add_connected_listener(struct moonbr_listener *listener) {
1482 listener->prev_listener = listener->pool->last_connected_listener;
1483 if (listener->prev_listener) listener->prev_listener->next_listener = listener;
1484 else listener->pool->first_connected_listener = listener;
1485 listener->pool->last_connected_listener = listener;
1488 /* Removes and returns the first connected listener in the queue */
1489 static struct moonbr_listener *moonbr_pop_connected_listener(struct moonbr_pool *pool) {
1490 struct moonbr_listener *listener = pool->first_connected_listener;
1491 listener->pool->first_connected_listener = listener->next_listener;
1492 if (listener->pool->first_connected_listener) listener->pool->first_connected_listener->prev_listener = NULL;
1493 else listener->pool->last_connected_listener = NULL;
1494 listener->next_listener = NULL;
1495 return listener;
1499 /*** Functions to handle polling ***/
1501 /* Returns an index to a new initialized entry in moonbr_poll_fds[] */
1502 int moonbr_poll_fds_nextindex() {
1503 if (moonbr_poll_fds_count >= moonbr_poll_fds_bufsize) {
1504 if (moonbr_poll_fds_bufsize) moonbr_poll_fds_bufsize *= 2;
1505 else moonbr_poll_fds_bufsize = 1;
1506 moonbr_poll_fds = realloc(
1507 moonbr_poll_fds, moonbr_poll_fds_bufsize * sizeof(struct pollfd)
1508 );
1509 if (!moonbr_poll_fds) {
1510 moonbr_log(LOG_CRIT, "Memory allocation error");
1511 moonbr_terminate_error();
1514 moonbr_poll_fds[moonbr_poll_fds_count] = (struct pollfd){0, };
1515 return moonbr_poll_fds_count++;
1518 /* Returns an index to a new initialized entry in moonbr_poll_workers[] */
1519 int moonbr_poll_workers_nextindex() {
1520 if (moonbr_poll_worker_count >= moonbr_poll_workers_bufsize) {
1521 if (moonbr_poll_workers_bufsize) moonbr_poll_workers_bufsize *= 2;
1522 else moonbr_poll_workers_bufsize = 1;
1523 moonbr_poll_workers = realloc(
1524 moonbr_poll_workers, moonbr_poll_workers_bufsize * sizeof(struct moonbr_poll_worker)
1525 );
1526 if (!moonbr_poll_workers) {
1527 moonbr_log(LOG_CRIT, "Memory allocation error");
1528 moonbr_terminate_error();
1531 moonbr_poll_workers[moonbr_poll_worker_count] = (struct moonbr_poll_worker){0, };
1532 return moonbr_poll_worker_count++;
1535 /* Queues all listeners as idle, and initializes static part of moonbr_poll_fds[], which is passed to poll() */
1536 static void moonbr_poll_init() {
1537 if (socketpair(
1538 PF_LOCAL,
1539 SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
1540 0,
1541 moonbr_poll_signalfds
1542 )) {
1543 moonbr_log(LOG_CRIT, "Could not create socket pair for signal delivery during polling: %s", strerror(errno));
1544 moonbr_terminate_error();
1547 int j = moonbr_poll_fds_nextindex();
1548 struct pollfd *pollfd = &moonbr_poll_fds[j];
1549 pollfd->fd = moonbr_poll_signalfd_read;
1550 pollfd->events = POLLIN;
1553 struct moonbr_pool *pool;
1554 for (pool=moonbr_first_pool; pool; pool=pool->next_pool) {
1555 int i;
1556 for (i=0; i<pool->listener_count; i++) {
1557 struct moonbr_listener *listener = &pool->listener[i];
1558 if (listener->listenfd != -1) {
1559 int j = moonbr_poll_fds_nextindex();
1560 listener->pollidx = j;
1561 moonbr_poll_fds[j].fd = listener->listenfd;
1563 moonbr_add_idle_listener(listener);
1567 moonbr_poll_fds_static_count = moonbr_poll_fds_count; /* remember size of static part of array */
1570 /* Disables polling of all listeners (required for clean shutdown) */
1571 static void moonbr_poll_shutdown() {
1572 int i;
1573 for (i=1; i<moonbr_poll_fds_static_count; i++) {
1574 moonbr_poll_fds[i].fd = -1;
1578 /* (Re)builds dynamic part of moonbr_poll_fds[] array, and (re)builds moonbr_poll_workers[] array */
1579 static void moonbr_poll_refresh() {
1580 moonbr_poll_refresh_needed = 0;
1581 moonbr_poll_fds_count = moonbr_poll_fds_static_count;
1582 moonbr_poll_worker_count = 0;
1584 struct moonbr_pool *pool;
1585 for (pool=moonbr_first_pool; pool; pool=pool->next_pool) {
1586 struct moonbr_worker *worker;
1587 for (worker=pool->first_worker; worker; worker=worker->next_worker) {
1588 if (worker->controlfd != -1) {
1589 int j = moonbr_poll_fds_nextindex();
1590 int k = moonbr_poll_workers_nextindex();
1591 struct pollfd *pollfd = &moonbr_poll_fds[j];
1592 struct moonbr_poll_worker *poll_worker = &moonbr_poll_workers[k];
1593 pollfd->fd = worker->controlfd;
1594 pollfd->events = POLLIN;
1595 poll_worker->channel = MOONBR_POLL_WORKER_CONTROLCHANNEL;
1596 poll_worker->worker = worker;
1598 if (worker->errorfd != -1) {
1599 int j = moonbr_poll_fds_nextindex();
1600 int k = moonbr_poll_workers_nextindex();
1601 struct pollfd *pollfd = &moonbr_poll_fds[j];
1602 struct moonbr_poll_worker *poll_worker = &moonbr_poll_workers[k];
1603 pollfd->fd = worker->errorfd;
1604 pollfd->events = POLLIN;
1605 poll_worker->channel = MOONBR_POLL_WORKER_ERRORCHANNEL;
1606 poll_worker->worker = worker;
1613 /* resets socket and 'revents' field of moonbr_poll_fds[] for signal delivery just before poll() is called */
1614 static void moonbr_poll_reset_signal() {
1615 ssize_t readcount;
1616 char buf[1];
1617 moonbr_poll_fds[0].revents = 0;
1618 while ((readcount = read(moonbr_poll_signalfd_read, buf, 1)) < 0) {
1619 if (errno == EAGAIN) break;
1620 if (errno != EINTR) {
1621 moonbr_log(LOG_CRIT, "Error while reading from signal delivery socket: %s", strerror(errno));
1622 moonbr_terminate_error();
1625 if (!readcount) {
1626 moonbr_log(LOG_CRIT, "Unexpected EOF when reading from signal delivery socket: %s", strerror(errno));
1627 moonbr_terminate_error();
1632 /*** Shutdown initiation ***/
1634 /* Sets global variable 'moonbr_shutdown_in_progress', closes listeners, and demands worker termination */
1635 static void moonbr_initiate_shutdown() {
1636 struct moonbr_pool *pool;
1637 int i;
1638 if (moonbr_shutdown_in_progress) {
1639 moonbr_log(LOG_NOTICE, "Shutdown already in progress");
1640 return;
1642 moonbr_shutdown_in_progress = 1;
1643 moonbr_log(LOG_NOTICE, "Initiate shutdown");
1644 for (pool = moonbr_first_pool; pool; pool = pool->next_pool) {
1645 for (i=0; i<pool->listener_count; i++) {
1646 struct moonbr_listener *listener = &pool->listener[i];
1647 if (listener->listenfd != -1) {
1648 if (close(listener->listenfd) && errno != EINTR) {
1649 moonbr_log(LOG_CRIT, "Could not close listening socket: %s", strerror(errno));
1650 moonbr_terminate_error();
1654 pool->pre_fork = 0;
1655 pool->min_fork = 0;
1656 pool->max_fork = 0;
1657 timerclear(&pool->exit_delay);
1659 moonbr_poll_shutdown(); /* avoids loops due to error condition when polling closed listeners */
1663 /*** Functions to communicate with child processes ***/
1665 /* Tells child process to terminate */
1666 static void moonbr_terminate_idle_worker(struct moonbr_worker *worker) {
1667 moonbr_send_control_message(worker, MOONBR_COMMAND_TERMINATE, -1, NULL);
1670 /* Handles status messages from child process */
1671 static void moonbr_read_controlchannel(struct moonbr_worker *worker) {
1672 char controlmsg;
1674 ssize_t bytes_read;
1675 while ((bytes_read = read(worker->controlfd, &controlmsg, 1)) <= 0) {
1676 if (bytes_read == 0 || errno == ECONNRESET) {
1677 moonbr_log(LOG_WARNING, "Child process in pool #%i with PID %i unexpectedly closed control socket", worker->pool->poolnum, (int)worker->pid);
1678 if (close(worker->controlfd) && errno != EINTR) {
1679 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));
1680 moonbr_terminate_error();
1682 worker->controlfd = -1;
1683 moonbr_poll_refresh_needed = 1;
1684 return;
1686 if (errno != EINTR) {
1687 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));
1688 moonbr_terminate_error();
1692 if (worker->idle) {
1693 moonbr_log(LOG_CRIT, "Unexpected data from supposedly idle child process in pool #%i with PID %i", worker->pool->poolnum, (int)worker->pid);
1694 moonbr_terminate_error();
1696 if (moonbr_debug) {
1697 moonbr_log(LOG_DEBUG, "Received control message from child in pool #%i with PID %i: \"%c\"", worker->pool->poolnum, (int)worker->pid, (int)controlmsg);
1699 switch (controlmsg) {
1700 case MOONBR_STATUS_IDLE:
1701 if (moonbr_stat) {
1702 moonbr_log(LOG_INFO, "Child process in pool #%i with PID %i reports as idle", worker->pool->poolnum, (int)worker->pid);
1704 moonbr_add_idle_worker(worker);
1705 break;
1706 case MOONBR_STATUS_GOODBYE:
1707 if (moonbr_stat) {
1708 moonbr_log(LOG_INFO, "Child process in pool #%i with PID %i announced termination", worker->pool->poolnum, (int)worker->pid);
1710 if (close(worker->controlfd) && errno != EINTR) {
1711 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));
1712 moonbr_terminate_error();
1714 worker->controlfd = -1;
1715 moonbr_poll_refresh_needed = 1;
1716 break;
1717 default:
1718 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);
1719 moonbr_terminate_error();
1723 /* Handles stderr stream from child process */
1724 static void moonbr_read_errorchannel(struct moonbr_worker *worker) {
1725 char staticbuf[MOONBR_MAXERRORLINELEN+1];
1726 char *buf = worker->errorlinebuf;
1727 if (!buf) buf = staticbuf;
1729 ssize_t bytes_read;
1730 while (
1731 (bytes_read = read(
1732 worker->errorfd,
1733 buf + worker->errorlinelen,
1734 MOONBR_MAXERRORLINELEN+1 - worker->errorlinelen
1735 )) <= 0
1736 ) {
1737 if (bytes_read == 0 || errno == ECONNRESET) {
1738 if (moonbr_debug) {
1739 moonbr_log(LOG_DEBUG, "Child process in pool #%i with PID %i closed stderr socket", worker->pool->poolnum, (int)worker->pid);
1741 if (close(worker->errorfd) && errno != EINTR) {
1742 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));
1743 moonbr_terminate_error();
1745 worker->errorfd = -1;
1746 moonbr_poll_refresh_needed = 1;
1747 break;
1749 if (errno != EINTR) {
1750 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));
1751 moonbr_terminate_error();
1754 worker->errorlinelen += bytes_read;
1757 int i;
1758 for (i=0; i<worker->errorlinelen; i++) {
1759 if (buf[i] == '\n') buf[i] = 0;
1760 if (!buf[i]) {
1761 if (worker->errorlineovf) {
1762 worker->errorlineovf = 0;
1763 } else {
1764 moonbr_log(LOG_WARNING, "Error log from process in pool #%i with PID %i: %s", worker->pool->poolnum, (int)worker->pid, buf);
1766 worker->errorlinelen -= i+1;
1767 memmove(buf, buf+i+1, worker->errorlinelen);
1768 i = -1;
1771 if (i > MOONBR_MAXERRORLINELEN) {
1772 buf[MOONBR_MAXERRORLINELEN] = 0;
1773 if (!worker->errorlineovf) {
1774 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);
1776 worker->errorlinelen = 0;
1777 worker->errorlineovf = 1;
1780 if (!worker->errorlinebuf && worker->errorlinelen) { /* allocate buffer on heap only if necessary */
1781 worker->errorlinebuf = malloc((MOONBR_MAXERRORLINELEN+1) * sizeof(char));
1782 if (!worker->errorlinebuf) {
1783 moonbr_log(LOG_CRIT, "Memory allocation error");
1784 moonbr_terminate_error();
1786 memcpy(worker->errorlinebuf, staticbuf, worker->errorlinelen);
1791 /*** Handler for incoming connections ***/
1793 /* Accepts one or more incoming connections on listener socket and passes it to worker(s) popped from idle queue */
1794 static void moonbr_connect(struct moonbr_pool *pool) {
1795 struct moonbr_listener *listener = moonbr_pop_connected_listener(pool);
1796 struct moonbr_worker *worker;
1797 switch (listener->proto) {
1798 case MOONBR_PROTO_INTERVAL:
1799 worker = moonbr_pop_idle_worker(pool);
1800 if (moonbr_stat) {
1801 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);
1803 worker->restart_interval_listener = listener;
1804 moonbr_send_control_message(worker, MOONBR_SOCKETTYPE_INTERVAL, -1, listener);
1805 /* do not push listener to queue of idle listeners yet */
1806 break;
1807 case MOONBR_PROTO_LOCAL:
1808 do {
1809 int peerfd;
1810 struct sockaddr_un peeraddr;
1811 socklen_t peeraddr_len = sizeof(struct sockaddr_un);
1812 peerfd = accept4(
1813 listener->listenfd,
1814 (struct sockaddr *)&peeraddr,
1815 &peeraddr_len,
1816 SOCK_CLOEXEC
1817 );
1818 if (peerfd == -1) {
1819 if (errno == EWOULDBLOCK) {
1820 break;
1821 } else if (errno == ECONNABORTED) {
1822 moonbr_log(LOG_WARNING, "Connection aborted before accepting it (proto=\"local\", path=\"%s\")", listener->proto_specific.local.path);
1823 break;
1824 } else if (errno != EINTR) {
1825 moonbr_log(LOG_ERR, "Could not accept socket connection: %s", strerror(errno));
1826 moonbr_terminate_error();
1828 } else {
1829 worker = moonbr_pop_idle_worker(pool);
1830 if (moonbr_stat) {
1831 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);
1833 moonbr_send_control_message(worker, MOONBR_SOCKETTYPE_LOCAL, peerfd, listener);
1834 if (close(peerfd) && errno != EINTR) {
1835 moonbr_log(LOG_ERR, "Could not close incoming socket connection in parent process: %s", strerror(errno));
1836 moonbr_terminate_error();
1839 } while (pool->first_idle_worker);
1840 moonbr_add_idle_listener(listener);
1841 break;
1842 case MOONBR_PROTO_TCP6:
1843 do {
1844 int peerfd;
1845 struct sockaddr_in6 peeraddr;
1846 socklen_t peeraddr_len = sizeof(struct sockaddr_in6);
1847 peerfd = accept4(
1848 listener->listenfd,
1849 (struct sockaddr *)&peeraddr,
1850 &peeraddr_len,
1851 SOCK_CLOEXEC
1852 );
1853 if (peerfd == -1) {
1854 if (errno == EWOULDBLOCK) {
1855 break;
1856 } else if (errno == ECONNABORTED) {
1857 moonbr_log(LOG_WARNING, "Connection aborted before accepting it (proto=\"tcp6\", port=%i)", listener->proto_specific.tcp.port);
1858 break;
1859 } else if (errno != EINTR) {
1860 moonbr_log(LOG_ERR, "Could not accept socket connection: %s", strerror(errno));
1861 moonbr_terminate_error();
1863 } else {
1864 worker = moonbr_pop_idle_worker(pool);
1865 if (moonbr_stat) {
1866 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);
1868 moonbr_send_control_message(worker, MOONBR_SOCKETTYPE_NETWORK, peerfd, listener);
1869 if (close(peerfd) && errno != EINTR) {
1870 moonbr_log(LOG_ERR, "Could not close incoming socket connection in parent process: %s", strerror(errno));
1871 moonbr_terminate_error();
1874 } while (pool->first_idle_worker);
1875 moonbr_add_idle_listener(listener);
1876 break;
1877 case MOONBR_PROTO_TCP4:
1878 do {
1879 int peerfd;
1880 struct sockaddr_in peeraddr;
1881 socklen_t peeraddr_len = sizeof(struct sockaddr_in);
1882 peerfd = accept4(
1883 listener->listenfd,
1884 (struct sockaddr *)&peeraddr,
1885 &peeraddr_len,
1886 SOCK_CLOEXEC
1887 );
1888 if (peerfd == -1) {
1889 if (errno == EWOULDBLOCK) {
1890 break;
1891 } else if (errno == ECONNABORTED) {
1892 moonbr_log(LOG_WARNING, "Connection aborted before accepting it (proto=\"tcp4\", port=%i)", listener->proto_specific.tcp.port);
1893 break;
1894 } else if (errno != EINTR) {
1895 moonbr_log(LOG_ERR, "Could not accept socket connection: %s", strerror(errno));
1896 moonbr_terminate_error();
1898 } else {
1899 worker = moonbr_pop_idle_worker(pool);
1900 if (moonbr_stat) {
1901 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);
1903 moonbr_send_control_message(worker, MOONBR_SOCKETTYPE_NETWORK, peerfd, listener);
1904 if (close(peerfd) && errno != EINTR) {
1905 moonbr_log(LOG_ERR, "Could not close incoming socket connection in parent process: %s", strerror(errno));
1906 moonbr_terminate_error();
1909 } while (pool->first_idle_worker);
1910 moonbr_add_idle_listener(listener);
1911 break;
1912 default:
1913 moonbr_log(LOG_ERR, "Internal error (should not happen): Unexpected value in listener.proto field");
1914 moonbr_terminate_error();
1919 /*** Functions to initialize and restart interval timers ***/
1921 /* Initializes all interval timers */
1922 static void moonbr_interval_initialize() {
1923 struct timeval now;
1924 struct moonbr_pool *pool;
1925 moonbr_now(&now);
1926 for (pool=moonbr_first_pool; pool; pool=pool->next_pool) {
1927 int i;
1928 for (i=0; i<pool->listener_count; i++) {
1929 struct moonbr_listener *listener = &pool->listener[i];
1930 if (listener->proto == MOONBR_PROTO_INTERVAL) {
1931 timeradd(
1932 &now,
1933 &listener->proto_specific.interval.delay,
1934 &listener->proto_specific.interval.wakeup
1935 );
1941 /* If necessary, restarts interval timers and queues interval listener as idle after a worker changed status */
1942 static void moonbr_interval_restart(
1943 struct moonbr_worker *worker,
1944 struct timeval *now /* passed to synchronize with moonbr_run() function */
1945 ) {
1946 struct moonbr_listener *listener = worker->restart_interval_listener;
1947 if (listener) {
1948 moonbr_add_idle_listener(listener);
1949 worker->restart_interval_listener = NULL;
1950 if (listener->proto_specific.interval.strict) {
1951 timeradd(
1952 &listener->proto_specific.interval.wakeup,
1953 &listener->proto_specific.interval.delay,
1954 &listener->proto_specific.interval.wakeup
1955 );
1956 if (timercmp(&listener->proto_specific.interval.wakeup, now, <)) {
1957 listener->proto_specific.interval.wakeup = *now;
1959 } else {
1960 timeradd(
1961 now,
1962 &listener->proto_specific.interval.delay,
1963 &listener->proto_specific.interval.wakeup
1964 );
1970 /*** Main loop and helper functions ***/
1972 /* Stores the earliest required wakeup time in 'wait' variable */
1973 static void moonbr_calc_wait(struct timeval *wait, struct timeval *wakeup) {
1974 if (!timerisset(wait) || timercmp(wakeup, wait, <)) *wait = *wakeup;
1977 /* Main loop of Moonbridge system (including initialization of signal handlers and polling structures) */
1978 static void moonbr_run(lua_State *L) {
1979 struct timeval now;
1980 struct moonbr_pool *pool;
1981 struct moonbr_worker *worker;
1982 struct moonbr_worker *next_worker; /* needed when worker is removed during iteration of workers */
1983 struct moonbr_listener *listener;
1984 struct moonbr_listener *next_listener; /* needed when listener is removed during iteration of listeners */
1985 int i;
1986 moonbr_poll_init(); /* must be executed before moonbr_signal_init() */
1987 moonbr_signal_init();
1988 moonbr_interval_initialize();
1989 moonbr_pstate = MOONBR_PSTATE_RUNNING;
1990 while (1) {
1991 struct timeval wait = {0, }; /* point in time when premature wakeup of poll() is required */
1992 if (moonbr_cond_interrupt) {
1993 moonbr_log(LOG_WARNING, "Fast shutdown requested");
1994 moonbr_terminate(MOONBR_EXITCODE_GRACEFUL);
1996 if (moonbr_cond_terminate) {
1997 moonbr_initiate_shutdown();
1998 moonbr_cond_terminate = 0;
2000 moonbr_cond_child = 0; /* must not be reset between moonbr_try_destroy_worker() and poll() */
2001 moonbr_now(&now);
2002 for (pool=moonbr_first_pool; pool; pool=pool->next_pool) {
2003 int terminated_worker_count = 0; /* allows shortcut for new worker creation */
2004 /* terminate idle workers when expired */
2005 if (timerisset(&pool->idle_timeout)) {
2006 while ((worker = pool->first_idle_worker) != NULL) {
2007 if (timercmp(&worker->idle_expiration, &now, >)) break;
2008 moonbr_pop_idle_worker(pool);
2009 moonbr_terminate_idle_worker(worker);
2012 /* mark listeners as connected when incoming connection is pending */
2013 for (listener=pool->first_idle_listener; listener; listener=next_listener) {
2014 next_listener = listener->next_listener; /* extra variable necessary due to changing list */
2015 if (listener->pollidx != -1) {
2016 if (moonbr_poll_fds[listener->pollidx].revents) {
2017 moonbr_poll_fds[listener->pollidx].revents = 0;
2018 moonbr_remove_idle_listener(listener);
2019 moonbr_add_connected_listener(listener);
2021 } else if (listener->proto == MOONBR_PROTO_INTERVAL) {
2022 if (!timercmp(&listener->proto_specific.interval.wakeup, &now, >)) {
2023 moonbr_remove_idle_listener(listener);
2024 moonbr_add_connected_listener(listener);
2026 } else {
2027 moonbr_log(LOG_CRIT, "Internal error (should not happen): Listener is neither an interval timer nor has the 'pollidx' value set");
2028 moonbr_terminate_error();
2031 /* process input from child processes */
2032 for (i=0; i<moonbr_poll_worker_count; i++) {
2033 if (moonbr_poll_worker_fds[i].revents) {
2034 moonbr_poll_worker_fds[i].revents = 0;
2035 struct moonbr_poll_worker *poll_worker = &moonbr_poll_workers[i];
2036 switch (poll_worker->channel) {
2037 case MOONBR_POLL_WORKER_CONTROLCHANNEL:
2038 moonbr_read_controlchannel(poll_worker->worker);
2039 moonbr_interval_restart(poll_worker->worker, &now);
2040 break;
2041 case MOONBR_POLL_WORKER_ERRORCHANNEL:
2042 moonbr_read_errorchannel(poll_worker->worker);
2043 break;
2047 /* collect dead child processes */
2048 for (worker=pool->first_worker; worker; worker=next_worker) {
2049 next_worker = worker->next_worker; /* extra variable necessary due to changing list */
2050 switch (moonbr_try_destroy_worker(worker)) {
2051 case MOONBR_DESTROY_PREPARE:
2052 pool->use_fork_error_wakeup = 1;
2053 break;
2054 case MOONBR_DESTROY_IDLE_OR_ASSIGNED:
2055 terminated_worker_count++;
2056 break;
2059 /* connect listeners with idle workers */
2060 if (!moonbr_shutdown_in_progress) {
2061 while (pool->first_connected_listener && pool->first_idle_worker) {
2062 moonbr_connect(pool);
2065 /* create new worker processes */
2066 while (
2067 pool->total_worker_count < pool->max_fork && (
2068 pool->unassigned_worker_count < pool->pre_fork ||
2069 pool->total_worker_count < pool->min_fork
2071 ) {
2072 if (pool->use_fork_error_wakeup) {
2073 if (timercmp(&pool->fork_error_wakeup, &now, >)) {
2074 moonbr_calc_wait(&wait, &pool->fork_error_wakeup);
2075 break;
2077 } else {
2078 if (terminated_worker_count) {
2079 terminated_worker_count--;
2080 } else if (timercmp(&pool->fork_wakeup, &now, >)) {
2081 moonbr_calc_wait(&wait, &pool->fork_wakeup);
2082 break;
2085 if (moonbr_create_worker(pool, L)) {
2086 /* on error, enforce error delay */
2087 timeradd(&now, &pool->fork_error_delay, &pool->fork_error_wakeup);
2088 pool->use_fork_error_wakeup = 1;
2089 moonbr_calc_wait(&wait, &pool->fork_error_wakeup);
2090 break;
2091 } else {
2092 /* normal fork delay on success */
2093 timeradd(&now, &pool->fork_delay, &pool->fork_wakeup);
2094 timeradd(&now, &pool->fork_error_delay, &pool->fork_error_wakeup);
2095 pool->use_fork_error_wakeup = 0; /* gets set later if error occures during preparation */
2098 /* terminate excessive worker processes */
2099 while (
2100 pool->total_worker_count > pool->min_fork &&
2101 pool->idle_worker_count > pool->pre_fork
2102 ) {
2103 if (timerisset(&pool->exit_wakeup)) {
2104 if (timercmp(&pool->exit_wakeup, &now, >)) {
2105 moonbr_calc_wait(&wait, &pool->exit_wakeup);
2106 break;
2108 moonbr_terminate_idle_worker(moonbr_pop_idle_worker(pool));
2109 timeradd(&now, &pool->exit_delay, &pool->exit_wakeup);
2110 } else {
2111 timeradd(&now, &pool->exit_delay, &pool->exit_wakeup);
2112 break;
2115 if (!(
2116 pool->total_worker_count > pool->min_fork &&
2117 pool->idle_worker_count > pool->pre_fork
2118 )) {
2119 timerclear(&pool->exit_wakeup); /* timer gets restarted later when there are excessive workers */
2121 /* optionally output worker count stats */
2122 if (moonbr_stat && pool->worker_count_stat) {
2123 pool->worker_count_stat = 0;
2124 moonbr_log(
2125 LOG_INFO,
2126 "Worker count for pool #%i: %i idle, %i assigned, %i total",
2127 pool->poolnum, pool->idle_worker_count,
2128 pool->total_worker_count - pool->unassigned_worker_count,
2129 pool->total_worker_count);
2131 /* calculate wakeup time for interval listeners */
2132 for (listener=pool->first_idle_listener; listener; listener=listener->next_listener) {
2133 if (listener->proto == MOONBR_PROTO_INTERVAL) {
2134 moonbr_calc_wait(&wait, &listener->proto_specific.interval.wakeup);
2137 /* calculate wakeup time for idle workers (only first idle worker is significant) */
2138 if (timerisset(&pool->idle_timeout) && pool->first_idle_worker) {
2139 moonbr_calc_wait(&wait, &pool->first_idle_worker->idle_expiration);
2142 /* check if shutdown is complete */
2143 if (moonbr_shutdown_in_progress) {
2144 for (pool=moonbr_first_pool; pool; pool=pool->next_pool) {
2145 if (pool->first_worker) break;
2147 if (!pool) {
2148 moonbr_log(LOG_INFO, "All worker threads have terminated");
2149 moonbr_terminate(MOONBR_EXITCODE_GRACEFUL);
2152 if (moonbr_poll_refresh_needed) moonbr_poll_refresh();
2153 moonbr_cond_poll = 1;
2154 if (!moonbr_cond_child && !moonbr_cond_terminate && !moonbr_cond_interrupt) {
2155 int timeout;
2156 if (timerisset(&wait)) {
2157 if (timercmp(&wait, &now, <)) {
2158 moonbr_log(LOG_CRIT, "Internal error (should not happen): Future is in the past");
2159 moonbr_terminate_error();
2161 timersub(&wait, &now, &wait);
2162 timeout = wait.tv_sec * 1000 + wait.tv_usec / 1000;
2163 } else {
2164 timeout = INFTIM;
2166 if (moonbr_debug) {
2167 moonbr_log(LOG_DEBUG, "Waiting for I/O");
2169 poll(moonbr_poll_fds, moonbr_poll_fds_count, timeout);
2170 } else {
2171 if (moonbr_debug) {
2172 moonbr_log(LOG_DEBUG, "Do not wait for I/O");
2175 moonbr_cond_poll = 0;
2176 moonbr_poll_reset_signal();
2181 /*** Lua interface ***/
2183 static int moonbr_lua_panic(lua_State *L) {
2184 const char *errmsg;
2185 errmsg = lua_tostring(L, -1);
2186 if (!errmsg) {
2187 if (lua_isnoneornil(L, -1)) errmsg = "(error message is nil)";
2188 else errmsg = "(error message is not a string)";
2190 if (moonbr_pstate == MOONBR_PSTATE_FORKED) {
2191 fprintf(stderr, "Uncaught Lua error: %s\n", errmsg);
2192 exit(1);
2193 } else {
2194 moonbr_log(LOG_CRIT, "Uncaught Lua error: %s", errmsg);
2195 moonbr_terminate_error();
2197 return 0;
2200 static int moonbr_addtraceback(lua_State *L) {
2201 luaL_traceback(L, L, luaL_tolstring(L, 1, NULL), 1);
2202 return 1;
2205 /* Memory allocator that allows limiting memory consumption */
2206 static void *moonbr_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
2207 (void)ud; /* not used */
2208 if (nsize == 0) {
2209 if (ptr) {
2210 moonbr_memory_usage -= osize;
2211 free(ptr);
2213 return NULL;
2214 } else if (ptr) {
2215 if (
2216 moonbr_memory_limit &&
2217 nsize > osize &&
2218 moonbr_memory_usage + (nsize - osize) > moonbr_memory_limit
2219 ) {
2220 return NULL;
2221 } else {
2222 ptr = realloc(ptr, nsize);
2223 if (ptr) moonbr_memory_usage += nsize - osize;
2225 } else {
2226 if (
2227 moonbr_memory_limit &&
2228 moonbr_memory_usage + nsize > moonbr_memory_limit
2229 ) {
2230 return NULL;
2231 } else {
2232 ptr = realloc(ptr, nsize);
2233 if (ptr) moonbr_memory_usage += nsize;
2236 return ptr;
2239 /* Helper function to convert a value at the given stack index to a natural number */
2240 static int moonbr_lua_tonatural(lua_State *L, int idx) {
2241 int isnum;
2242 lua_Number n;
2243 n = lua_tonumberx(L, idx, &isnum);
2244 if (isnum && n>=0 && n<INT_MAX && (lua_Number)(int)n == n) return n;
2245 else return -1;
2248 /* Helper function to convert a value at the given stack index to a timeval struct */
2249 static int moonbr_lua_totimeval(lua_State *L, int idx, struct timeval *value) {
2250 int isnum;
2251 lua_Number n;
2252 n = lua_tonumberx(L, idx, &isnum);
2253 if (isnum && n>=0 && n<=100000000) {
2254 value->tv_sec = n;
2255 value->tv_usec = 1e6 * (n - value->tv_sec);
2256 return 1;
2257 } else {
2258 return 0;
2262 /* New function io.poll(...) */
2263 static int moonbr_io_poll(lua_State *L) {
2264 int i;
2265 luaL_Stream *stream;
2266 int fd, isnum;
2267 int nfds = 0;
2268 fd_set readfds, writefds, exceptfds;
2269 struct timeval timeout = {0, };
2270 int status;
2271 FD_ZERO(&readfds);
2272 FD_ZERO(&writefds);
2273 FD_ZERO(&exceptfds);
2274 if (!lua_isnoneornil(L, 1)) {
2275 luaL_checktype(L, 1, LUA_TTABLE);
2276 for (i=1; ; i++) {
2277 #if LUA_VERSION_NUM >= 503
2278 if (lua_geti(L, 1, i) == LUA_TNIL) break;
2279 #else
2280 lua_pushinteger(L, i);
2281 lua_gettable(L, 1);
2282 if (lua_isnil(L, -1)) break;
2283 #endif
2284 stream = luaL_testudata(L, -1, LUA_FILEHANDLE);
2285 if (stream) {
2286 fd = fileno(stream->f);
2287 } else {
2288 fd = lua_tointegerx(L, -1, &isnum);
2289 if (!isnum) luaL_error(L, "File descriptor is not an integer");
2291 FD_SET(fd, &readfds);
2292 if (fd+1 > nfds) nfds = fd+1;
2293 lua_pop(L, 1);
2296 if (!lua_isnoneornil(L, 2)) {
2297 luaL_checktype(L, 2, LUA_TTABLE);
2298 for (i=1; ; i++) {
2299 #if LUA_VERSION_NUM >= 503
2300 if (lua_geti(L, 2, i) == LUA_TNIL) break;
2301 #else
2302 lua_pushinteger(L, i);
2303 lua_gettable(L, 2);
2304 if (lua_isnil(L, -1)) break;
2305 #endif
2306 stream = luaL_testudata(L, -1, LUA_FILEHANDLE);
2307 if (stream) {
2308 fd = fileno(stream->f);
2309 } else {
2310 fd = lua_tointegerx(L, -1, &isnum);
2311 if (!isnum) luaL_error(L, "File descriptor is not an integer");
2313 FD_SET(fd, &writefds);
2314 if (fd+1 > nfds) nfds = fd+1;
2315 lua_pop(L, 1);
2317 lua_pop(L, 2);
2319 if (!lua_isnoneornil(L, 3)) {
2320 luaL_argcheck(L, moonbr_lua_totimeval(L, 3, &timeout), 3, "not a valid timeout");
2322 status = select(nfds, &readfds, &writefds, &exceptfds, &timeout);
2323 if (status == -1) {
2324 if (errno == EINTR) {
2325 lua_pushboolean(L, 0);
2326 lua_pushliteral(L, "Signal received while polling file descriptors");
2327 return 2;
2328 } else {
2329 char errmsg[MOONBR_MAXSTRERRORLEN];
2330 strerror_r(errno, errmsg, MOONBR_MAXSTRERRORLEN); /* use thread-safe call in case child created threads */
2331 return luaL_error(L, "Unexpected error during \"select\" system call: %s", errmsg);
2333 } else if (status == 0) {
2334 lua_pushboolean(L, 0);
2335 lua_pushliteral(L, "Timeout while polling file descriptors");
2336 return 2;
2337 } else {
2338 lua_pushboolean(L, 1);
2339 return 1;
2343 /* New method for Lua file objects: check if non-blocking reading is possible */
2344 static int moonbr_io_pending(lua_State *L) {
2345 luaL_Stream *stream;
2346 FILE *file;
2347 int fd, flags, chr;
2348 stream = luaL_checkudata(L, 1, LUA_FILEHANDLE);
2349 if (!stream->closef) luaL_error(L, "attempt to use a closed file");
2350 file = stream->f;
2351 flockfile(file);
2352 fd = fileno_unlocked(file);
2353 if (ferror(file) || feof(file)) {
2354 funlockfile(file);
2355 lua_pushboolean(L, 1);
2356 return 1;
2358 flags = fcntl(fd, F_GETFL, 0);
2359 if (flags == -1) goto moonbr_io_pending_error;
2360 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) goto moonbr_io_pending_error;
2361 chr = getc_unlocked(file);
2362 lua_pushboolean(L, 1);
2363 if (chr == EOF) {
2364 if (ferror(file) && errno == EAGAIN) {
2365 clearerr_unlocked(file);
2366 lua_pushboolean(L, 0);
2368 } else {
2369 if (ungetc(chr, file) == EOF) goto moonbr_io_pending_error;
2371 if (fcntl(fd, F_SETFL, flags) == -1) goto moonbr_io_pending_error;
2372 funlockfile(file);
2373 return 1;
2374 moonbr_io_pending_error:
2375 funlockfile(file);
2377 char errmsg[MOONBR_MAXSTRERRORLEN];
2378 strerror_r(errno, errmsg, MOONBR_MAXSTRERRORLEN); /* use thread-safe call in case child created threads */
2379 luaL_error(L, "Unexpected error in method \"pending\" of FILE handle: %s", errmsg);
2381 return 0;
2384 /* New method for Lua file objects: read until terminator or length exceeded */
2385 static int moonbr_io_readuntil(lua_State *L) {
2386 luaL_Stream *stream;
2387 FILE *file;
2388 const char *terminatorstr;
2389 size_t terminatorlen;
2390 luaL_Buffer buf;
2391 lua_Integer maxlen;
2392 char terminator;
2393 int byte;
2394 stream = luaL_checkudata(L, 1, LUA_FILEHANDLE);
2395 terminatorstr = luaL_checklstring(L, 2, &terminatorlen);
2396 luaL_argcheck(L, terminatorlen == 1, 2, "single byte expected");
2397 maxlen = luaL_optinteger(L, 3, 0);
2398 if (!stream->closef) luaL_error(L, "attempt to use a closed file");
2399 file = stream->f;
2400 luaL_buffinit(L, &buf);
2401 if (!maxlen) maxlen = -1;
2402 terminator = terminatorstr[0];
2403 flockfile(file);
2404 while (maxlen > 0 ? maxlen-- : maxlen) {
2405 byte = getc_unlocked(file);
2406 if (byte == EOF) {
2407 if (ferror(file)) {
2408 char errmsg[MOONBR_MAXSTRERRORLEN];
2409 strerror_r(errno, errmsg, MOONBR_MAXSTRERRORLEN); /* use thread-safe call in case child created threads */
2410 funlockfile(file);
2411 lua_pushnil(L);
2412 lua_pushstring(L, errmsg);
2413 return 2;
2414 } else {
2415 break;
2418 luaL_addchar(&buf, byte);
2419 if (byte == terminator) break;
2421 funlockfile(file);
2422 luaL_pushresult(&buf);
2423 if (!lua_rawlen(L, -1)) lua_pushnil(L);
2424 return 1;
2427 static int moonbr_timeout(lua_State *L) {
2428 struct itimerval oldval;
2429 if (lua_isnoneornil(L, 1) && lua_isnoneornil(L, 2)) {
2430 getitimer(ITIMER_REAL, &oldval);
2431 } else {
2432 struct itimerval newval = {};
2433 timerclear(&newval.it_interval);
2434 timerclear(&newval.it_value);
2435 if (lua_toboolean(L, 1)) {
2436 luaL_argcheck(
2437 L, moonbr_lua_totimeval(L, 1, &newval.it_value), 1,
2438 "interval in seconds expected"
2439 );
2441 if (lua_isnoneornil(L, 2)) {
2442 if (setitimer(ITIMER_REAL, &newval, &oldval)) {
2443 moonbr_log(LOG_CRIT, "Could not set ITIMER_REAL via setitimer()");
2444 moonbr_terminate_error();
2446 } else {
2447 getitimer(ITIMER_REAL, &oldval);
2448 if (!timerisset(&oldval.it_value)) {
2449 if (setitimer(ITIMER_REAL, &newval, NULL)) {
2450 moonbr_log(LOG_CRIT, "Could not set ITIMER_REAL via setitimer()");
2451 moonbr_terminate_error();
2453 lua_call(L, lua_gettop(L) - 2, LUA_MULTRET);
2454 timerclear(&newval.it_value);
2455 if (setitimer(ITIMER_REAL, &newval, NULL)) {
2456 moonbr_log(LOG_CRIT, "Could not set ITIMER_REAL via setitimer()");
2457 moonbr_terminate_error();
2459 } else if (timercmp(&newval.it_value, &oldval.it_value, <)) {
2460 struct itimerval remval;
2461 if (setitimer(ITIMER_REAL, &newval, NULL)) {
2462 moonbr_log(LOG_CRIT, "Could not set ITIMER_REAL via setitimer()");
2463 moonbr_terminate_error();
2465 lua_call(L, lua_gettop(L) - 2, LUA_MULTRET);
2466 getitimer(ITIMER_REAL, &remval);
2467 timersub(&oldval.it_value, &newval.it_value, &newval.it_value);
2468 timeradd(&newval.it_value, &remval.it_value, &newval.it_value);
2469 if (setitimer(ITIMER_REAL, &newval, NULL)) {
2470 moonbr_log(LOG_CRIT, "Could not set ITIMER_REAL via setitimer()");
2471 moonbr_terminate_error();
2473 } else {
2474 lua_call(L, lua_gettop(L) - 2, LUA_MULTRET);
2476 return lua_gettop(L) - 1;
2479 lua_pushnumber(L, oldval.it_value.tv_sec + 1e-6 * oldval.it_value.tv_usec);
2480 return 1;
2483 #define moonbr_listen_init_pool_forkoption(luaname, cname, defval) { \
2484 lua_getfield(L, 2, luaname); \
2485 pool->cname = lua_isnil(L, -1) ? (defval) : moonbr_lua_tonatural(L, -1); \
2486 } while(0)
2488 #define moonbr_listen_init_pool_timeoption(luaname, cname, defval, defvalu) ( \
2489 lua_getfield(L, 2, luaname), \
2490 lua_isnil(L, -1) ? ( \
2491 pool->cname.tv_sec = (defval), pool->cname.tv_usec = (defvalu), \
2492 1 \
2493 ) : ( \
2494 (lua_isboolean(L, -1) && !lua_toboolean(L, -1)) ? ( \
2495 pool->cname.tv_sec = 0, pool->cname.tv_usec = 0, \
2496 1 \
2497 ) : ( \
2498 moonbr_lua_totimeval(L, -1, &pool->cname) \
2499 ) \
2500 ) \
2503 static int moonbr_listen_init_pool(lua_State *L) {
2504 struct moonbr_pool *pool;
2505 const char *proto;
2506 int i;
2507 pool = lua_touserdata(L, 1);
2508 for (i=0; i<pool->listener_count; i++) {
2509 struct moonbr_listener *listener = &pool->listener[i];
2510 lua_settop(L, 2);
2511 #if LUA_VERSION_NUM >= 503
2512 lua_geti(L, 2, i+1);
2513 #else
2514 lua_pushinteger(L, i+1);
2515 lua_gettable(L, 2);
2516 #endif
2517 lua_getfield(L, 3, "proto");
2518 proto = lua_tostring(L, -1);
2519 if (proto && !strcmp(proto, "interval")) {
2520 listener->proto = MOONBR_PROTO_INTERVAL;
2521 lua_getfield(L, 3, "name");
2523 const char *name = lua_tostring(L, -1);
2524 if (name) {
2525 if (asprintf(&listener->proto_specific.interval.name, "%s", name) < 0) {
2526 moonbr_log(LOG_CRIT, "Memory allocation_error");
2527 moonbr_terminate_error();
2531 lua_getfield(L, 3, "delay");
2532 if (
2533 !moonbr_lua_totimeval(L, -1, &listener->proto_specific.interval.delay) ||
2534 !timerisset(&listener->proto_specific.interval.delay)
2535 ) {
2536 luaL_error(L, "No valid interval delay specified; use listen{{proto=\"interval\", delay=...}, ...}");
2538 lua_getfield(L, 3, "strict");
2539 if (!lua_isnil(L, -1)) {
2540 if (lua_isboolean(L, -1)) {
2541 if (lua_toboolean(L, -1)) listener->proto_specific.interval.strict = 1;
2542 } else {
2543 luaL_error(L, "Option \"strict\" must be a boolean if set; use listen{{proto=\"interval\", strict=true, ...}, ...}");
2546 } else if (proto && !strcmp(proto, "local")) {
2547 listener->proto = MOONBR_PROTO_LOCAL;
2548 lua_getfield(L, 3, "path");
2550 const char *path = lua_tostring(L, -1);
2551 if (!path) {
2552 luaL_error(L, "No valid path specified for local socket; use listen{{proto=\"local\", path=...}, ...}");
2554 if (asprintf(&listener->proto_specific.local.path, "%s", path) < 0) {
2555 moonbr_log(LOG_CRIT, "Memory allocation_error");
2556 moonbr_terminate_error();
2559 } else if (proto && !strcmp(proto, "tcp6")) {
2560 listener->proto = MOONBR_PROTO_TCP6;
2561 lua_getfield(L, 3, "port");
2562 listener->proto_specific.tcp.port = lua_tointeger(L, -1);
2563 if (
2564 listener->proto_specific.tcp.port < 1 ||
2565 listener->proto_specific.tcp.port > 65535
2566 ) {
2567 luaL_error(L, "No valid port number specified; use listen{{proto=\"tcp6\", port=...}, ...}");
2569 lua_getfield(L, 3, "localhost");
2570 if (!lua_isnil(L, -1)) {
2571 if (lua_isboolean(L, -1)) {
2572 if (lua_toboolean(L, -1)) listener->proto_specific.tcp.localhost_only = 1;
2573 } else {
2574 luaL_error(L, "Option \"localhost\" must be a boolean if set; use listen{{proto=\"tcp6\", localhost=true, ...}, ...}");
2577 } else if (proto && !strcmp(proto, "tcp4")) {
2578 listener->proto = MOONBR_PROTO_TCP4;
2579 lua_getfield(L, 3, "port");
2580 listener->proto_specific.tcp.port = lua_tointeger(L, -1);
2581 if (
2582 listener->proto_specific.tcp.port < 1 ||
2583 listener->proto_specific.tcp.port > 65535
2584 ) {
2585 luaL_error(L, "No valid port number specified; use listen{{proto=\"tcp4\", port=...}, ...}");
2587 lua_getfield(L, 3, "localhost");
2588 if (!lua_isnil(L, -1)) {
2589 if (lua_isboolean(L, -1)) {
2590 if (lua_toboolean(L, -1)) listener->proto_specific.tcp.localhost_only = 1;
2591 } else {
2592 luaL_error(L, "Option \"localhost\" must be a boolean if set; use listen{{proto=\"tcp4\", localhost=true, ...}, ...}");
2597 lua_settop(L, 2);
2598 moonbr_listen_init_pool_forkoption("pre_fork", pre_fork, 1);
2599 moonbr_listen_init_pool_forkoption("min_fork", min_fork, pool->pre_fork > 2 ? pool->pre_fork : 2);
2600 moonbr_listen_init_pool_forkoption("max_fork", max_fork, pool->min_fork > 16 ? pool->min_fork : 16);
2601 if (!moonbr_listen_init_pool_timeoption("fork_delay", fork_delay, 0, 250000)) {
2602 luaL_error(L, "Option \"fork_delay\" is expected to be a non-negative number");
2604 if (!moonbr_listen_init_pool_timeoption("fork_error_delay", fork_error_delay, 2, 0)) {
2605 luaL_error(L, "Option \"fork_error_delay\" is expected to be a non-negative number");
2607 if (!moonbr_listen_init_pool_timeoption("exit_delay", exit_delay, 60, 0)) {
2608 luaL_error(L, "Option \"exit_delay\" is expected to be a non-negative number");
2610 if (timercmp(&pool->fork_error_delay, &pool->fork_delay, <)) {
2611 pool->fork_error_delay = pool->fork_delay;
2613 if (!moonbr_listen_init_pool_timeoption("idle_timeout", idle_timeout, 0, 0)) {
2614 luaL_error(L, "Option \"idle_timeout\" is expected to be a non-negative number");
2616 lua_getfield(L, 2, "memory_limit");
2617 if (!lua_isnil(L, -1)) {
2618 int isnum;
2619 lua_Number n;
2620 n = lua_tonumberx(L, -1, &isnum);
2621 if (n < 0 || !isnum) {
2622 luaL_error(L, "Option \"memory_limit\" is expected to be a non-negative number");
2624 pool->memory_limit = n;
2626 lua_settop(L, 2);
2627 lua_getfield(L, 2, "prepare");
2628 if (!lua_isnil(L, -1) && !lua_isfunction(L, -1)) {
2629 luaL_error(L, "Option \"prepare\" must be nil or a function");
2631 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_prepare_func(pool));
2632 lua_getfield(L, 2, "connect");
2633 if (!lua_isfunction(L, -1)) {
2634 luaL_error(L, "Option \"connect\" must be a function; use listen{{...}, {...}, connect=function(socket) ... end, ...}");
2636 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_connect_func(pool));
2637 lua_getfield(L, 2, "finish");
2638 if (!lua_isnil(L, -1) && !lua_isfunction(L, -1)) {
2639 luaL_error(L, "Option \"finish\" must be nil or a function");
2641 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_finish_func(pool));
2642 return 0;
2645 static int moonbr_listen(lua_State *L) {
2646 struct moonbr_pool *pool;
2647 lua_Integer listener_count;
2648 if (moonbr_booted) luaL_error(L, "Moonbridge bootup is already complete");
2649 luaL_checktype(L, 1, LUA_TTABLE);
2650 listener_count = luaL_len(L, 1);
2651 if (!listener_count) luaL_error(L, "No listen ports specified; use listen{{proto=..., port=...},...}");
2652 if (listener_count > 100) luaL_error(L, "Too many listeners");
2653 pool = moonbr_create_pool(listener_count);
2654 lua_pushcfunction(L, moonbr_listen_init_pool);
2655 lua_pushlightuserdata(L, pool);
2656 lua_pushvalue(L, 1);
2657 if (lua_pcall(L, 2, 0, 0)) goto moonbr_listen_error;
2659 int i;
2660 i = moonbr_start_pool(pool);
2661 if (i >= 0) {
2662 struct moonbr_listener *listener = &pool->listener[i];
2663 switch (listener->proto) {
2664 case MOONBR_PROTO_INTERVAL:
2665 lua_pushfstring(L, "Could not initialize listener #%d (proto=\"interval\"): %s", i+1, strerror(errno));
2666 break;
2667 case MOONBR_PROTO_LOCAL:
2668 lua_pushfstring(L, "Could not initialize listener #%d (proto=\"local\", path=\"%s\"): %s", i+1, listener->proto_specific.local.path, strerror(errno));
2669 break;
2670 case MOONBR_PROTO_TCP6:
2671 lua_pushfstring(L, "Could not initialize listener #%d (proto=\"tcp6\", port=%d): %s", i+1, listener->proto_specific.tcp.port, strerror(errno));
2672 break;
2673 case MOONBR_PROTO_TCP4:
2674 lua_pushfstring(L, "Could not initialize listener #%d (proto=\"tcp4\", port=%d): %s", i+1, listener->proto_specific.tcp.port, strerror(errno));
2675 break;
2676 default:
2677 moonbr_log(LOG_ERR, "Internal error (should not happen): Unexpected value in listener.proto field");
2678 moonbr_terminate_error();
2680 goto moonbr_listen_error;
2683 return 0;
2684 moonbr_listen_error:
2685 moonbr_destroy_pool(pool);
2686 lua_pushnil(L);
2687 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_prepare_func(pool));
2688 lua_pushnil(L);
2689 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_connect_func(pool));
2690 lua_pushnil(L);
2691 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_finish_func(pool));
2692 lua_error(L);
2693 return 0; /* avoid compiler warning */
2697 /*** Function to modify Lua's library path and/or cpath ***/
2699 #if defined(MOONBR_LUA_PATH) || defined(MOONBR_LUA_CPATH)
2700 static void moonbr_modify_path(lua_State *L, char *key, char *value) {
2701 int stackbase;
2702 stackbase = lua_gettop(L);
2703 lua_getglobal(L, "package");
2704 lua_getfield(L, stackbase+1, key);
2706 const char *current_str;
2707 size_t current_strlen;
2708 luaL_Buffer buf;
2709 current_str = lua_tolstring(L, stackbase+2, &current_strlen);
2710 luaL_buffinit(L, &buf);
2711 if (current_str) {
2712 lua_pushvalue(L, stackbase+2);
2713 luaL_addvalue(&buf);
2714 if (current_strlen && current_str[current_strlen-1] != ';') {
2715 luaL_addchar(&buf, ';');
2718 luaL_addstring(&buf, value);
2719 luaL_pushresult(&buf);
2721 lua_setfield(L, stackbase+1, key);
2722 lua_settop(L, stackbase);
2724 #endif
2727 /*** Main function and command line invokation ***/
2729 static void moonbr_usage(int err, const char *cmd) {
2730 FILE *out;
2731 out = err ? stderr : stdout;
2732 if (!cmd) cmd = "moonbridge";
2733 fprintf(out, "Get this help message: %s {-h|--help}\n", cmd);
2734 fprintf(out, "Usage: %s \\\n", cmd);
2735 fprintf(out, " [-b|--background] \\\n");
2736 fprintf(out, " [-d|--debug] \\\n");
2737 fprintf(out, " [-f|--logfacility {DAEMON|USER|0|1|...|7}] \\\n");
2738 fprintf(out, " [-i|--logident <syslog ident> \\\n");
2739 fprintf(out, " [-l|--logfile <logfile>] \\\n");
2740 fprintf(out, " [-p|--pidfile <pidfile>] \\\n");
2741 fprintf(out, " [-s|--stats] \\\n");
2742 fprintf(out, " -- <Lua script> [<cmdline options for Lua script>]\n");
2743 exit(err);
2746 #define moonbr_usage_error() moonbr_usage(MOONBR_EXITCODE_CMDLINEERROR, argc ? argv[0] : NULL)
2748 int main(int argc, char **argv) {
2750 int daemonize = 0;
2751 int log_facility = LOG_USER;
2752 const char *log_ident = "moonbridge";
2753 const char *log_filename = NULL;
2754 const char *pid_filename = NULL;
2755 int option;
2756 struct option longopts[] = {
2757 { "background", no_argument, NULL, 'b' },
2758 { "debug", no_argument, NULL, 'd' },
2759 { "logfacility", required_argument, NULL, 'f' },
2760 { "help", no_argument, NULL, 'h' },
2761 { "logident", required_argument, NULL, 'i' },
2762 { "logfile", required_argument, NULL, 'l' },
2763 { "pidfile", required_argument, NULL, 'p' },
2764 { "stats", no_argument, NULL, 's' }
2765 };
2766 while ((option = getopt_long(argc, argv, "bdf:hi:l:p:s", longopts, NULL)) != -1) {
2767 switch (option) {
2768 case 'b':
2769 daemonize = 1;
2770 break;
2771 case 'd':
2772 moonbr_debug = 1;
2773 moonbr_stat = 1;
2774 break;
2775 case 'f':
2776 if (!strcmp(optarg, "DAEMON")) {
2777 log_facility = LOG_DAEMON;
2778 } else if (!strcmp(optarg, "USER")) {
2779 log_facility = LOG_USER;
2780 } else if (!strcmp(optarg, "0")) {
2781 log_facility = LOG_LOCAL0;
2782 } else if (!strcmp(optarg, "1")) {
2783 log_facility = LOG_LOCAL1;
2784 } else if (!strcmp(optarg, "2")) {
2785 log_facility = LOG_LOCAL2;
2786 } else if (!strcmp(optarg, "3")) {
2787 log_facility = LOG_LOCAL3;
2788 } else if (!strcmp(optarg, "4")) {
2789 log_facility = LOG_LOCAL4;
2790 } else if (!strcmp(optarg, "5")) {
2791 log_facility = LOG_LOCAL5;
2792 } else if (!strcmp(optarg, "6")) {
2793 log_facility = LOG_LOCAL6;
2794 } else if (!strcmp(optarg, "7")) {
2795 log_facility = LOG_LOCAL7;
2796 } else {
2797 moonbr_usage_error();
2799 moonbr_use_syslog = 1;
2800 break;
2801 case 'h':
2802 moonbr_usage(MOONBR_EXITCODE_GRACEFUL, argv[0]);
2803 break;
2804 case 'i':
2805 log_ident = optarg;
2806 moonbr_use_syslog = 1;
2807 break;
2808 case 'l':
2809 log_filename = optarg;
2810 break;
2811 case 'p':
2812 pid_filename = optarg;
2813 break;
2814 case 's':
2815 moonbr_stat = 1;
2816 break;
2817 default:
2818 moonbr_usage_error();
2821 if (argc - optind < 1) moonbr_usage_error();
2822 if (pid_filename) {
2823 pid_t otherpid;
2824 while ((moonbr_pidfh = pidfile_open(pid_filename, 0644, &otherpid)) == NULL) {
2825 if (errno == EEXIST) {
2826 if (otherpid == -1) {
2827 fprintf(stderr, "PID file \"%s\" is already locked\n", pid_filename);
2828 } else {
2829 fprintf(stderr, "PID file \"%s\" is already locked by process with PID: %i\n", pid_filename, (int)otherpid);
2831 exit(MOONBR_EXITCODE_ALREADYRUNNING);
2832 } else if (errno != EINTR) {
2833 fprintf(stderr, "Could not write PID file \"%s\": %s\n", pid_filename, strerror(errno));
2834 exit(MOONBR_EXITCODE_STARTUPERROR);
2838 if (log_filename) {
2839 int logfd;
2840 while (
2841 ( logfd = flopen(
2842 log_filename,
2843 O_WRONLY|O_NONBLOCK|O_CREAT|O_APPEND|O_CLOEXEC,
2844 0640
2846 ) < 0
2847 ) {
2848 if (errno == EWOULDBLOCK) {
2849 fprintf(stderr, "Logfile \"%s\" is locked\n", log_filename);
2850 exit(MOONBR_EXITCODE_ALREADYRUNNING);
2851 } else if (errno != EINTR) {
2852 fprintf(stderr, "Could not open logfile \"%s\": %s\n", log_filename, strerror(errno));
2853 exit(MOONBR_EXITCODE_STARTUPERROR);
2856 moonbr_logfile = fdopen(logfd, "a");
2857 if (!moonbr_logfile) {
2858 fprintf(stderr, "Could not open write stream to logfile \"%s\": %s\n", log_filename, strerror(errno));
2859 exit(MOONBR_EXITCODE_STARTUPERROR);
2862 if (daemonize == 0 && !moonbr_logfile) moonbr_logfile = stderr;
2863 if (moonbr_logfile) setlinebuf(moonbr_logfile);
2864 else moonbr_use_syslog = 1;
2865 if (moonbr_use_syslog) openlog(log_ident, LOG_NDELAY | LOG_PID, log_facility);
2866 if (daemonize) {
2867 if (daemon(1, 0)) {
2868 moonbr_log(LOG_ERR, "Could not daemonize moonbridge process");
2869 moonbr_terminate_error();
2873 moonbr_log(LOG_NOTICE, "Starting moonbridge server");
2874 if (moonbr_pidfh && pidfile_write(moonbr_pidfh)) {
2875 moonbr_log(LOG_ERR, "Could not write pidfile (after locking)");
2878 lua_State *L;
2879 L = lua_newstate(moonbr_alloc, NULL);
2880 if (!L) {
2881 moonbr_log(LOG_CRIT, "Could not initialize Lua state");
2882 moonbr_terminate_error();
2884 lua_atpanic(L, moonbr_lua_panic);
2885 lua_pushliteral(L, MOONBR_VERSION_STRING);
2886 lua_setglobal(L, "_MOONBRIDGE_VERSION");
2887 luaL_openlibs(L);
2888 #ifdef MOONBR_LUA_PATH
2889 moonbr_modify_path(L, "path", MOONBR_LUA_PATH);
2890 #endif
2891 #ifdef MOONBR_LUA_CPATH
2892 moonbr_modify_path(L, "cpath", MOONBR_LUA_CPATH);
2893 #endif
2894 lua_getglobal(L, "io");
2895 lua_pushcfunction(L, moonbr_io_poll);
2896 lua_setfield(L, -2, "poll");
2897 lua_pop(L, 1);
2898 if (luaL_newmetatable(L, LUA_FILEHANDLE)) {
2899 moonbr_log(LOG_CRIT, "Lua metatable LUA_FILEHANDLE does not exist");
2900 moonbr_terminate_error();
2902 lua_getfield(L, -1, "__index");
2903 lua_pushcfunction(L, moonbr_io_pending);
2904 lua_setfield(L, -2, "pending");
2905 lua_pushcfunction(L, moonbr_io_readuntil);
2906 lua_setfield(L, -2, "readuntil");
2907 lua_pop(L, 2);
2908 lua_pushcfunction(L, moonbr_timeout);
2909 lua_setglobal(L, "timeout");
2910 lua_pushcfunction(L, moonbr_listen);
2911 lua_setglobal(L, "listen");
2912 lua_pushcfunction(L, moonbr_addtraceback); /* on stack position 1 */
2913 moonbr_log(LOG_INFO, "Loading \"%s\"", argv[optind]);
2914 if (luaL_loadfile(L, argv[optind])) {
2915 moonbr_log(LOG_ERR, "Error while loading \"%s\": %s", argv[optind], lua_tostring(L, -1));
2916 moonbr_terminate_error();
2918 { int i; for (i=optind+1; i<argc; i++) lua_pushstring(L, argv[i]); }
2919 if (lua_pcall(L, argc-(optind+1), 0, 1)) {
2920 moonbr_log(LOG_ERR, "Error while executing \"%s\": %s", argv[optind], lua_tostring(L, -1));
2921 moonbr_terminate_error();
2923 if (!moonbr_first_pool) {
2924 moonbr_log(LOG_WARNING, "No listener initialized.");
2925 moonbr_terminate_error();
2927 lua_getglobal(L, "listen");
2928 lua_pushcfunction(L, moonbr_listen);
2929 if (lua_compare(L, -2, -1, LUA_OPEQ)) {
2930 lua_pushnil(L);
2931 lua_setglobal(L, "listen");
2933 lua_settop(L, 1);
2934 lua_gc(L, LUA_GCCOLLECT, 0); // collect garbage before forking later
2935 moonbr_run(L);
2937 return 0;

Impressum / About Us