moonbridge

view moonbridge.c @ 42:0bb356c04f6b

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

Impressum / About Us