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