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