1 #include "first.h"
2
3 #include "base.h"
4 #include "buffer.h"
5 #include "network.h"
6 #include "log.h"
7 #include "rand.h"
8 #include "chunk.h"
9 #include "h2.h" /* h2_send_1xx() */
10 #include "http_range.h" /* http_range_config_allow_http10() */
11 #include "fdevent.h"
12 #include "fdlog.h"
13 #include "connections.h"
14 #include "sock_addr.h"
15 #include "stat_cache.h"
16 #include "plugin.h"
17 #include "plugins.h"
18 #include "plugin_config.h" /* config_plugin_value_tobool() */
19 #include "network_write.h" /* network_write_show_handlers() */
20 #include "reqpool.h" /* request_pool_init() request_pool_free() */
21 #include "response.h" /* http_response_send_1xx_cb_set() strftime_cache_reset() */
22
23 #ifdef HAVE_VERSIONSTAMP_H
24 # include "versionstamp.h"
25 #else
26 # define REPO_VERSION ""
27 #endif
28
29 #define PACKAGE_DESC PACKAGE_NAME "/" PACKAGE_VERSION REPO_VERSION
30 static const buffer default_server_tag =
31 { PACKAGE_DESC "\0server", sizeof(PACKAGE_DESC), 0 };
32
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #include "sys-setjmp.h"
36 #include "sys-time.h"
37
38 #include <string.h>
39 #include <errno.h>
40 #include <fcntl.h>
41 #include <unistd.h>
42 #include <stdlib.h>
43 #include <signal.h>
44 #include <locale.h>
45
46 #include <stdio.h>
47
48 #ifdef HAVE_GETOPT_H
49 # include <getopt.h>
50 #endif
51
52 #ifdef HAVE_VALGRIND_VALGRIND_H
53 # include <valgrind/valgrind.h>
54 #endif
55
56 #ifdef HAVE_PWD_H
57 # include <grp.h>
58 # include <pwd.h>
59 #endif
60
61 #ifdef HAVE_SYS_LOADAVG_H
62 # include <sys/loadavg.h>
63 #endif
64
65 #ifdef HAVE_SYS_RESOURCE_H
66 # include <sys/resource.h>
67 #endif
68
69 #ifdef HAVE_SYS_PRCTL_H
70 # include <sys/prctl.h>
71 #endif
72 #ifdef HAVE_SYS_PROCCTL_H
73 # include <sys/procctl.h>
74 #endif
75 #ifdef HAVE_PRIV_H
76 # include <priv.h>
77 #endif
78
79 #ifdef HAVE_MALLOC_H
80 #ifndef LIGHTTPD_STATIC
81 #ifdef HAVE_DLFCN_H
82 #include <dlfcn.h>
83 #endif
84 #endif
85 #include <malloc.h>
86 #if defined(HAVE_MALLOC_TRIM)
87 static int(*malloc_trim_fn)(size_t);
88 static size_t malloc_top_pad;
89 #endif
90 #endif
91
92 #include "sys-crypto.h"
93 #if defined(USE_OPENSSL_CRYPTO) \
94 || defined(USE_MBEDTLS_CRYPTO) \
95 || defined(USE_NSS_CRYPTO) \
96 || defined(USE_GNUTLS_CRYPTO) \
97 || defined(USE_WOLFTLS_CRYPTO)
98 #define TEXT_SSL " (ssl)"
99 #else
100 #define TEXT_SSL
101 #endif
102
103 #ifndef __sgi
104 /* IRIX doesn't like the alarm based time() optimization */
105 /* #define USE_ALARM */
106 #endif
107
108 static int oneshot_fd = 0;
109 static int oneshot_fdout = -1;
110 static fdnode *oneshot_fdn = NULL;
111 static int (*oneshot_read_cq)(connection *con, chunkqueue *cq, off_t max_bytes);
112 static volatile int pid_fd = -2;
113 static server_socket_array graceful_sockets;
114 static server_socket_array inherited_sockets;
115 static volatile sig_atomic_t graceful_restart = 0;
116 static volatile sig_atomic_t graceful_shutdown = 0;
117 static volatile sig_atomic_t srv_shutdown = 0;
118 static volatile sig_atomic_t handle_sig_child = 0;
119 static volatile sig_atomic_t handle_sig_alarm = 1;
120 static volatile sig_atomic_t handle_sig_hup = 0;
121 static int idle_limit = 0;
122
123 #if defined(HAVE_SIGACTION) && defined(SA_SIGINFO)
124 static volatile siginfo_t last_sigterm_info;
125 static volatile siginfo_t last_sighup_info;
126
sigaction_handler(int sig,siginfo_t * si,void * context)127 static void sigaction_handler(int sig, siginfo_t *si, void *context) {
128 static const siginfo_t empty_siginfo;
129 UNUSED(context);
130
131 if (!si) *(const siginfo_t **)&si = &empty_siginfo;
132
133 switch (sig) {
134 case SIGTERM:
135 srv_shutdown = 1;
136 last_sigterm_info = *si;
137 break;
138 case SIGUSR1:
139 if (!graceful_shutdown) {
140 graceful_restart = 1;
141 graceful_shutdown = 1;
142 last_sigterm_info = *si;
143 }
144 break;
145 case SIGINT:
146 if (graceful_shutdown) {
147 if (2 == graceful_restart)
148 graceful_restart = 1;
149 else
150 srv_shutdown = 1;
151 } else {
152 graceful_shutdown = 1;
153 }
154 last_sigterm_info = *si;
155
156 break;
157 case SIGALRM:
158 handle_sig_alarm = 1;
159 break;
160 case SIGHUP:
161 handle_sig_hup = 1;
162 last_sighup_info = *si;
163 break;
164 case SIGCHLD:
165 handle_sig_child = 1;
166 break;
167 }
168 }
169 #elif defined(HAVE_SIGNAL) || defined(HAVE_SIGACTION)
signal_handler(int sig)170 static void signal_handler(int sig) {
171 switch (sig) {
172 case SIGTERM: srv_shutdown = 1; break;
173 case SIGUSR1:
174 if (!graceful_shutdown) {
175 graceful_restart = 1;
176 graceful_shutdown = 1;
177 }
178 break;
179 case SIGINT:
180 if (graceful_shutdown) {
181 if (2 == graceful_restart)
182 graceful_restart = 1;
183 else
184 srv_shutdown = 1;
185 } else {
186 graceful_shutdown = 1;
187 }
188 break;
189 case SIGALRM: handle_sig_alarm = 1; break;
190 case SIGHUP: handle_sig_hup = 1; break;
191 case SIGCHLD: handle_sig_child = 1; break;
192 }
193 }
194 #endif
195
196
server_main_setup_signals(void)197 static void server_main_setup_signals (void) {
198 #ifdef HAVE_SIGACTION
199 struct sigaction act;
200 memset(&act, 0, sizeof(act));
201 sigemptyset(&act.sa_mask);
202
203 act.sa_handler = SIG_IGN;
204 sigaction(SIGPIPE, &act, NULL);
205
206 #ifndef _MSC_VER
207 act.sa_flags = SA_NODEFER;
208 act.sa_handler = sys_setjmp_sigbus;
209 sigaction(SIGBUS, &act, NULL);
210 act.sa_flags = 0;
211 #endif
212
213 #if defined(SA_SIGINFO)
214 last_sighup_info.si_uid = 0,
215 last_sighup_info.si_pid = 0;
216 last_sigterm_info.si_uid = 0,
217 last_sigterm_info.si_pid = 0;
218 act.sa_sigaction = sigaction_handler;
219 act.sa_flags = SA_SIGINFO;
220 #else
221 act.sa_handler = signal_handler;
222 act.sa_flags = 0;
223 #endif
224 sigaction(SIGINT, &act, NULL);
225 sigaction(SIGTERM, &act, NULL);
226 sigaction(SIGHUP, &act, NULL);
227 sigaction(SIGALRM, &act, NULL);
228 sigaction(SIGUSR1, &act, NULL);
229
230 /* it should be safe to restart syscalls after SIGCHLD */
231 act.sa_flags |= SA_RESTART | SA_NOCLDSTOP;
232 sigaction(SIGCHLD, &act, NULL);
233 #elif defined(HAVE_SIGNAL)
234 /* ignore the SIGPIPE from sendfile() */
235 signal(SIGPIPE, SIG_IGN);
236 signal(SIGALRM, signal_handler);
237 signal(SIGTERM, signal_handler);
238 signal(SIGHUP, signal_handler);
239 signal(SIGCHLD, signal_handler);
240 signal(SIGINT, signal_handler);
241 signal(SIGUSR1, signal_handler);
242 #ifndef _MSC_VER
243 signal(SIGBUS, sys_setjmp_sigbus);
244 #endif
245 #endif
246 }
247
248
249 #ifdef HAVE_FORK
daemonize(void)250 static int daemonize(void) {
251 int pipefd[2];
252 pid_t pid;
253 #ifdef SIGTTOU
254 signal(SIGTTOU, SIG_IGN);
255 #endif
256 #ifdef SIGTTIN
257 signal(SIGTTIN, SIG_IGN);
258 #endif
259 #ifdef SIGTSTP
260 signal(SIGTSTP, SIG_IGN);
261 #endif
262
263 if (fdevent_pipe_cloexec(pipefd, 64) < 0) exit(-1);
264
265 if (0 > (pid = fork())) exit(-1);
266
267 if (0 < pid) {
268 char buf;
269 ssize_t bytes;
270
271 close(pipefd[1]);
272 /* parent waits for grandchild to be ready */
273 do {
274 bytes = read(pipefd[0], &buf, sizeof(buf));
275 } while (bytes < 0 && EINTR == errno);
276 close(pipefd[0]);
277
278 if (bytes <= 0) {
279 /* closed fd (without writing) == failure in grandchild */
280 fputs("daemonized server failed to start; check error log for details\n", stderr);
281 exit(-1);
282 }
283
284 exit(0);
285 }
286
287 close(pipefd[0]);
288
289 if (-1 == setsid()) exit(0);
290
291 signal(SIGHUP, SIG_IGN);
292
293 if (0 != fork()) exit(0);
294
295 if (0 != chdir("/")) exit(0);
296
297 return pipefd[1];
298 }
299 #endif
300
301 static int clockid_mono_coarse = 0;
302
303 static unix_time64_t
server_monotonic_secs(void)304 server_monotonic_secs (void)
305 {
306 unix_timespec64_t ts;
307 return (0 == log_clock_gettime(clockid_mono_coarse, &ts))
308 ? ts.tv_sec
309 : log_monotonic_secs;
310 }
311
312 static unix_time64_t
server_epoch_secs(server * const srv,unix_time64_t mono_ts_delta)313 server_epoch_secs (server * const srv, unix_time64_t mono_ts_delta)
314 {
315 const unix_time64_t cur_ts = log_epoch_secs;
316 const unix_time64_t new_ts = TIME64_CAST(time(NULL));
317 const unix_time64_t new_ts_adj = new_ts - mono_ts_delta;
318 /* attempt to detect large clock jump */
319 if (new_ts_adj < cur_ts || new_ts_adj - cur_ts > 300) { /*(5 mins)*/
320 log_error(srv->errh, __FILE__, __LINE__,
321 "warning: clock jumped %lld secs",
322 (long long)((int64_t)new_ts_adj - (int64_t)cur_ts));
323 int delta = /*(30 mins default)*/
324 config_feature_int(srv, "server.clock-jump-restart", 1800);
325 if (delta && (new_ts_adj > cur_ts
326 ? new_ts_adj-cur_ts
327 : cur_ts-new_ts_adj) > delta) {
328 log_error(srv->errh, __FILE__, __LINE__,
329 "attempting graceful restart in < ~5 seconds, else hard restart");
330 srv->graceful_expire_ts = log_monotonic_secs + 5;
331 raise(SIGUSR1);
332 }
333 }
334 return new_ts;
335 }
336
337 __attribute_cold__
338 __attribute_noinline__
339 __attribute_returns_nonnull__
server_init(void)340 static server *server_init(void) {
341 server *srv = ck_calloc(1, sizeof(*srv));
342
343 srv->tmp_buf = buffer_init();
344
345 strftime_cache_reset();
346
347 li_rand_reseed();
348
349 srv->startup_ts = log_epoch_secs = TIME64_CAST(time(NULL));
350 #ifdef HAVE_CLOCK_GETTIME
351 unix_timespec64_t ts;
352 UNUSED(&ts);
353 #ifdef CLOCK_MONOTONIC_COARSE
354 if (0 == log_clock_gettime(CLOCK_MONOTONIC_COARSE, &ts))
355 clockid_mono_coarse = CLOCK_MONOTONIC_COARSE;
356 else
357 #endif
358 #ifdef CLOCK_MONOTONIC_RAW_APPROX
359 if (0 == log_clock_gettime(CLOCK_MONOTONIC_RAW_APPROX, &ts))
360 clockid_mono_coarse = CLOCK_MONOTONIC_RAW_APPROX;
361 else
362 #endif
363 #ifdef CLOCK_MONOTONIC_RAW
364 if (0 == log_clock_gettime(CLOCK_MONOTONIC_RAW, &ts))
365 clockid_mono_coarse = CLOCK_MONOTONIC_RAW;
366 else
367 #endif
368 clockid_mono_coarse = CLOCK_MONOTONIC;
369 #endif
370 log_monotonic_secs = server_monotonic_secs();
371
372 srv->errh = log_set_global_errh(NULL, 0);
373
374 config_init(srv);
375
376 srv->request_env = plugins_call_handle_request_env;
377 srv->plugins_request_reset = plugins_call_handle_request_reset;
378
379 srv->loadavg[0] = 0.0;
380 srv->loadavg[1] = 0.0;
381 srv->loadavg[2] = 0.0;
382 srv->stdin_fd = -1;
383 srv->default_server_tag = &default_server_tag;
384
385 log_con_jqueue = (connection *)(uintptr_t)&log_con_jqueue;/*(sentinel)*/
386
387 return srv;
388 }
389
390 __attribute_cold__
391 __attribute_noinline__
server_free(server * srv)392 static void server_free(server *srv) {
393 if (oneshot_fd > 0) {
394 if (oneshot_fdn) {
395 fdevent_fdnode_event_del(srv->ev, oneshot_fdn);
396 fdevent_unregister(srv->ev, oneshot_fdn);
397 oneshot_fdn = NULL;
398 }
399 close(oneshot_fd);
400 }
401 if (oneshot_fdout >= 0) {
402 close(oneshot_fdout);
403 }
404 if (srv->stdin_fd >= 0) {
405 close(srv->stdin_fd);
406 }
407
408 buffer_free(srv->tmp_buf);
409
410 fdevent_free(srv->ev);
411
412 config_free(srv);
413
414 stat_cache_free();
415
416 li_rand_cleanup();
417 chunkqueue_chunk_pool_free();
418
419 if (srv->errh != log_set_global_errh(NULL, 0))
420 fdlog_free(srv->errh);
421 free(srv);
422 }
423
424 __attribute_cold__
425 __attribute_noinline__
remove_pid_file(server * srv)426 static void remove_pid_file(server *srv) {
427 if (pid_fd <= -2) return;
428 if (srv->srvconf.pid_file && 0 <= pid_fd) {
429 if (0 != ftruncate(pid_fd, 0)) {
430 log_perror(srv->errh, __FILE__, __LINE__,
431 "ftruncate failed for: %s", srv->srvconf.pid_file->ptr);
432 }
433 }
434 if (0 <= pid_fd) {
435 close(pid_fd);
436 pid_fd = -1;
437 }
438 if (srv->srvconf.pid_file && !srv->srvconf.changeroot) {
439 if (0 != unlink(srv->srvconf.pid_file->ptr)) {
440 if (errno != EACCES && errno != EPERM) {
441 log_perror(srv->errh, __FILE__, __LINE__,
442 "unlink failed for: %s", srv->srvconf.pid_file->ptr);
443 }
444 }
445 }
446 }
447
448
449 __attribute_cold__
server_oneshot_getsock(server * srv,sock_addr * cnt_addr)450 static server_socket * server_oneshot_getsock(server *srv, sock_addr *cnt_addr) {
451 server_socket *srv_socket, *srv_socket_wild = NULL;
452 for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) {
453 srv_socket = srv->srv_sockets.ptr[i];
454 if (!sock_addr_is_port_eq(&srv_socket->addr,cnt_addr)) continue;
455 if (sock_addr_is_addr_eq(&srv_socket->addr,cnt_addr)) return srv_socket;
456
457 if (NULL != srv_socket_wild) continue;
458 if (sock_addr_is_addr_wildcard(&srv_socket->addr)) {
459 srv_socket_wild = srv_socket;
460 }
461 }
462
463 if (NULL != srv_socket_wild) {
464 return srv_socket_wild;
465 } else if (srv->srv_sockets.used) {
466 return srv->srv_sockets.ptr[0];
467 } else {
468 log_error(srv->errh, __FILE__, __LINE__, "no sockets configured");
469 return NULL;
470 }
471 }
472
473
server_oneshot_read_cq(connection * con,chunkqueue * cq,off_t max_bytes)474 static int server_oneshot_read_cq(connection *con, chunkqueue *cq, off_t max_bytes) {
475 /* temporary set con->fd to oneshot_fd (fd input) rather than outshot_fdout
476 * (lighttpd generally assumes operation on sockets, so this is a kludge) */
477 int fd = con->fd;
478 con->fd = oneshot_fdn->fd;
479 int rc = oneshot_read_cq(con, cq, max_bytes);
480 con->fd = fd;
481
482 /* note: optimistic reads (elsewhere) may or may not be enough to re-enable
483 * read interest after FDEVENT_IN interest was paused for other reasons */
484
485 const int events = fdevent_fdnode_interest(oneshot_fdn);
486 int n = con->is_readable > 0 ? 0 : FDEVENT_IN;
487 if (events & FDEVENT_RDHUP)
488 n |= FDEVENT_RDHUP;
489 fdevent_fdnode_event_set(con->srv->ev, oneshot_fdn, n);
490 return rc;
491 }
492
493
server_oneshot_handle_fdevent(void * context,int revents)494 static handler_t server_oneshot_handle_fdevent(void *context, int revents) {
495 connection *con = context;
496
497 /* note: not sync'd with con->fdn or connection_set_fdevent_interest() */
498 int rdhup = 0;
499 int n = fdevent_fdnode_interest(oneshot_fdn);
500 if (revents & FDEVENT_IN)
501 n &= ~FDEVENT_IN;
502 request_st * const r = &con->request;
503 if (r->state != CON_STATE_ERROR && (revents & (FDEVENT_HUP|FDEVENT_RDHUP))){
504 revents &= ~(FDEVENT_HUP|FDEVENT_RDHUP);
505 /* copied and modified from connection_handle_fdevent()
506 * fdevent_is_tcp_half_closed() will fail on pipe
507 * and, besides, read end of pipes should treat POLLHUP as POLLRDHUP */
508 n &= ~(FDEVENT_IN|FDEVENT_RDHUP);
509 rdhup = 1;
510 }
511 fdevent_fdnode_event_set(con->srv->ev, oneshot_fdn, n);
512
513 fdnode * const fdn = con->fdn; /* fdn->ctx == con */
514 handler_t rc = (fdn && (fdevent_handler)NULL != fdn->handler)
515 ? (*fdn->handler)(con, revents)
516 : HANDLER_FINISHED;
517
518 if (rdhup) {
519 r->conf.stream_request_body &=
520 ~(FDEVENT_STREAM_REQUEST_BUFMIN|FDEVENT_STREAM_REQUEST_POLLIN);
521 r->conf.stream_request_body |= FDEVENT_STREAM_REQUEST_POLLRDHUP;
522 r->conf.stream_request_body |= FDEVENT_STREAM_REQUEST_TCP_FIN;
523 con->is_readable = 1; /*(can read 0 for end-of-stream)*/
524 if (chunkqueue_is_empty(con->read_queue)) r->keep_alive = 0;
525 if (r->reqbody_length < -1) /*(transparent proxy mode; no more data)*/
526 r->reqbody_length = r->reqbody_queue.bytes_in;
527 }
528
529 return rc;
530 }
531
532
533 __attribute_cold__
server_oneshot_init_pipe(server * srv,int fdin,int fdout)534 static int server_oneshot_init_pipe(server *srv, int fdin, int fdout) {
535 /* Note: attempt to work with netcat pipes though other code expects socket.
536 * netcat has different fds (pipes) for stdin and stdout. To support
537 * netcat, need to avoid S_ISSOCK(), getsockname(), and getpeername(),
538 * reconstructing addresses from environment variables:
539 * NCAT_LOCAL_ADDR NCAT_LOCAL_PORT
540 * NCAT_REMOTE_ADDR NCAT_REMOTE_PORT
541 * NCAT_PROTO (TCP, UDP, SCTP)
542 */
543 connection *con;
544 const server_socket *srv_socket;
545 sock_addr cnt_addr;
546
547 /* detect if called from netcat or else fabricate localhost addrs */
548 const char * const ncat =
549 getenv("NCAT_LOCAL_ADDR");
550 const char * const ncat_local_addr =
551 ncat ? ncat : "127.0.0.1"; /*(fabricated)*/
552 const char * const ncat_local_port =
553 ncat ? getenv("NCAT_LOCAL_PORT") : "80"; /*(fabricated)*/
554 const char * const ncat_remote_addr =
555 ncat ? getenv("NCAT_REMOTE_ADDR") : "127.0.0.1"; /*(fabricated)*/
556 const char * const ncat_remote_port =
557 ncat ? getenv("NCAT_REMOTE_PORT") : "48080"; /*(fabricated)*/
558 if (NULL == ncat_local_addr || NULL == ncat_local_port) return 0;
559 if (NULL == ncat_remote_addr || NULL == ncat_remote_port) return 0;
560
561 const int family = ncat && strchr(ncat_local_addr,':') ? AF_INET6 : AF_INET;
562 unsigned short port;
563
564 port = (unsigned short)strtol(ncat_local_port, NULL, 10);
565 if (1 != sock_addr_inet_pton(&cnt_addr, ncat_local_addr, family, port)) {
566 log_error(srv->errh, __FILE__, __LINE__, "invalid local addr");
567 return 0;
568 }
569
570 srv_socket = server_oneshot_getsock(srv, &cnt_addr);
571 if (NULL == srv_socket) return 0;
572
573 port = (unsigned short)strtol(ncat_remote_port, NULL, 10);
574 if (1 != sock_addr_inet_pton(&cnt_addr, ncat_remote_addr, family, port)) {
575 log_error(srv->errh, __FILE__, __LINE__, "invalid remote addr");
576 return 0;
577 }
578
579 /*(must set flags; fd did not pass through fdevent accept() logic)*/
580 if (-1 == fdevent_fcntl_set_nb_cloexec(fdin)) {
581 log_perror(srv->errh, __FILE__, __LINE__, "fcntl()");
582 return 0;
583 }
584 if (-1 == fdevent_fcntl_set_nb_cloexec(fdout)) {
585 log_perror(srv->errh, __FILE__, __LINE__, "fcntl()");
586 return 0;
587 }
588
589 con = connection_accepted(srv, srv_socket, &cnt_addr, fdout);
590 if (NULL == con) return 0;
591
592 /* note: existing routines assume socket, not pipe
593 * connections.c:connection_read_cq()
594 * uses recv() ifdef __WIN32
595 * passes S_IFSOCK to fdevent_ioctl_fionread()
596 * (The routine could be copied and modified, if required)
597 * This is unlikely to work if TLS is used over pipe since the SSL_CTX
598 * is associated with the other end of the pipe. However, if using
599 * pipes, using TLS is unexpected behavior.
600 */
601
602 /*assert(oneshot_fd == fdin);*/
603 oneshot_read_cq = con->network_read;
604 con->network_read = server_oneshot_read_cq;
605 oneshot_fdn =
606 fdevent_register(srv->ev, fdin, server_oneshot_handle_fdevent, con);
607 fdevent_fdnode_event_set(srv->ev, oneshot_fdn, FDEVENT_RDHUP);
608
609 connection_state_machine(con);
610 return 1;
611 }
612
613
614 __attribute_cold__
server_oneshot_init(server * srv,int fd)615 static int server_oneshot_init(server *srv, int fd) {
616 connection *con;
617 const server_socket *srv_socket;
618 sock_addr cnt_addr;
619 socklen_t cnt_len;
620
621 cnt_len = sizeof(cnt_addr);
622 if (0 != getsockname(fd, (struct sockaddr *)&cnt_addr, &cnt_len)) {
623 log_perror(srv->errh, __FILE__, __LINE__, "getsockname()");
624 return 0;
625 }
626
627 srv_socket = server_oneshot_getsock(srv, &cnt_addr);
628 if (NULL == srv_socket) return 0;
629
630 #ifdef __clang_analyzer__
631 memset(&cnt_addr, 0, sizeof(cnt_addr));
632 #endif
633 cnt_len = sizeof(cnt_addr);
634 if (0 != getpeername(fd, (struct sockaddr *)&cnt_addr, &cnt_len)) {
635 log_perror(srv->errh, __FILE__, __LINE__, "getpeername()");
636 return 0;
637 }
638
639 /*(must set flags; fd did not pass through fdevent accept() logic)*/
640 if (-1 == fdevent_fcntl_set_nb_cloexec(fd)) {
641 log_perror(srv->errh, __FILE__, __LINE__, "fcntl()");
642 return 0;
643 }
644
645 if (sock_addr_get_family(&cnt_addr) != AF_UNIX) {
646 network_accept_tcp_nagle_disable(fd);
647 }
648
649 con = connection_accepted(srv, srv_socket, &cnt_addr, fd);
650 if (NULL == con) return 0;
651
652 connection_state_machine(con);
653 return 1;
654 }
655
656
657 __attribute_cold__
show_version(void)658 static void show_version (void) {
659 char *b = PACKAGE_DESC TEXT_SSL \
660 " - a light and fast webserver\n"
661 #ifdef NONREPRODUCIBLE_BUILD
662 "Build-Date: " __DATE__ " " __TIME__ "\n";
663 #endif
664 ;
665 write_all(STDOUT_FILENO, b, strlen(b));
666 }
667
668 __attribute_cold__
show_features(void)669 static void show_features (void) {
670 static const char features[] =
671 "\nFeatures:\n\n"
672 #ifdef HAVE_IPV6
673 "\t+ IPv6 support\n"
674 #else
675 "\t- IPv6 support\n"
676 #endif
677 #if defined HAVE_ZLIB_H && defined HAVE_LIBZ
678 "\t+ zlib support\n"
679 #else
680 "\t- zlib support\n"
681 #endif
682 #if defined HAVE_ZSTD_H && defined HAVE_ZSTD
683 "\t+ zstd support\n"
684 #else
685 "\t- zstd support\n"
686 #endif
687 #if defined HAVE_BZLIB_H && defined HAVE_LIBBZ2
688 "\t+ bzip2 support\n"
689 #else
690 "\t- bzip2 support\n"
691 #endif
692 #if defined HAVE_BROTLI_ENCODE_H && defined HAVE_BROTLI
693 "\t+ brotli support\n"
694 #else
695 "\t- brotli support\n"
696 #endif
697 #if defined(HAVE_CRYPT) || defined(HAVE_CRYPT_R)
698 "\t+ crypt support\n"
699 #else
700 "\t- crypt support\n"
701 #endif
702 #ifdef USE_OPENSSL_CRYPTO
703 "\t+ OpenSSL support\n"
704 #else
705 "\t- OpenSSL support\n"
706 #endif
707 #ifdef USE_MBEDTLS_CRYPTO
708 "\t+ mbedTLS support\n"
709 #else
710 "\t- mbedTLS support\n"
711 #endif
712 #ifdef USE_NSS_CRYPTO
713 "\t+ NSS crypto support\n"
714 #else
715 "\t- NSS crypto support\n"
716 #endif
717 #ifdef USE_GNUTLS_CRYPTO
718 "\t+ GnuTLS support\n"
719 #else
720 "\t- GnuTLS support\n"
721 #endif
722 #ifdef USE_WOLFSSL_CRYPTO
723 "\t+ WolfSSL support\n"
724 #else
725 "\t- WolfSSL support\n"
726 #endif
727 #ifdef USE_NETTLE_CRYPTO
728 "\t+ Nettle support\n"
729 #else
730 "\t- Nettle support\n"
731 #endif
732 #ifdef HAVE_PCRE
733 "\t+ PCRE support\n"
734 #else
735 "\t- PCRE support\n"
736 #endif
737 #ifdef HAVE_MYSQL
738 "\t+ MySQL support\n"
739 #else
740 "\t- MySQL support\n"
741 #endif
742 #ifdef HAVE_PGSQL
743 "\t+ PgSQL support\n"
744 #else
745 "\t- PgSQL support\n"
746 #endif
747 #ifdef HAVE_DBI
748 "\t+ DBI support\n"
749 #else
750 "\t- DBI support\n"
751 #endif
752 #ifdef HAVE_KRB5
753 "\t+ Kerberos support\n"
754 #else
755 "\t- Kerberos support\n"
756 #endif
757 #if defined(HAVE_LDAP_H) && defined(HAVE_LBER_H) && defined(HAVE_LIBLDAP) && defined(HAVE_LIBLBER)
758 "\t+ LDAP support\n"
759 #else
760 "\t- LDAP support\n"
761 #endif
762 #ifdef HAVE_PAM
763 "\t+ PAM support\n"
764 #else
765 "\t- PAM support\n"
766 #endif
767 #ifdef HAVE_FAM_H
768 "\t+ FAM support\n"
769 #else
770 "\t- FAM support\n"
771 #endif
772 #ifdef HAVE_LUA_H
773 "\t+ LUA support\n"
774 #else
775 "\t- LUA support\n"
776 #endif
777 #ifdef HAVE_LIBXML_H
778 "\t+ xml support\n"
779 #else
780 "\t- xml support\n"
781 #endif
782 #ifdef HAVE_SQLITE3_H
783 "\t+ SQLite support\n"
784 #else
785 "\t- SQLite support\n"
786 #endif
787 ;
788 show_version();
789 printf("%s%s%s%s\n",
790 fdevent_show_event_handlers(),
791 network_write_show_handlers(),
792 features,
793 sizeof(time_t) > 4 || (sizeof(time_t) == 4 && (time_t)-1 > (time_t)1)
794 ? "\t+ Y2038 support\n"
795 : "\t- Y2038 support (unsafe 32-bit signed time_t)\n");
796 }
797
798 __attribute_cold__
show_help(void)799 static void show_help (void) {
800 char *b = PACKAGE_DESC TEXT_SSL
801 #ifdef NONREPRODUCIBLE_BUILD
802 " ("__DATE__ " " __TIME__ ")"
803 #endif
804 " - a light and fast webserver\n" \
805 "usage:\n" \
806 " -f <name> filename of the config-file\n" \
807 " -m <name> module directory (default: "LIBRARY_DIR")\n" \
808 " -i <secs> graceful shutdown after <secs> of inactivity\n" \
809 " -1 process single (one) request on stdin socket, then exit\n" \
810 " -p print the parsed config-file in internal form, and exit\n" \
811 " -t test config-file syntax, then exit\n" \
812 " -tt test config-file syntax, load and init modules, then exit\n" \
813 " -D don't go to background (default: go to background)\n" \
814 " -v show version\n" \
815 " -V show compile-time features\n" \
816 " -h show this help\n" \
817 "\n"
818 ;
819 write_all(STDOUT_FILENO, b, strlen(b));
820 }
821
822 __attribute_cold__
823 __attribute_noinline__
server_sockets_save(server * srv)824 static void server_sockets_save (server *srv) { /* graceful_restart */
825 for (uint32_t i = 0; i < srv->srv_sockets.used; ++i)
826 srv->srv_sockets.ptr[i]->srv = NULL; /* srv will shortly be invalid */
827 for (uint32_t i = 0; i < srv->srv_sockets_inherited.used; ++i)
828 srv->srv_sockets_inherited.ptr[i]->srv = NULL; /* srv to be invalid */
829 memcpy(&graceful_sockets, &srv->srv_sockets, sizeof(server_socket_array));
830 memset(&srv->srv_sockets, 0, sizeof(server_socket_array));
831 memcpy(&inherited_sockets, &srv->srv_sockets_inherited, sizeof(server_socket_array));
832 memset(&srv->srv_sockets_inherited, 0, sizeof(server_socket_array));
833 }
834
835 __attribute_cold__
836 __attribute_noinline__
server_sockets_restore(server * srv)837 static void server_sockets_restore (server *srv) { /* graceful_restart */
838 memcpy(&srv->srv_sockets, &graceful_sockets, sizeof(server_socket_array));
839 memset(&graceful_sockets, 0, sizeof(server_socket_array));
840 memcpy(&srv->srv_sockets_inherited, &inherited_sockets, sizeof(server_socket_array));
841 memset(&inherited_sockets, 0, sizeof(server_socket_array));
842 for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) {
843 srv->srv_sockets.ptr[i]->srv = srv; /* update ptr */
844 srv->srv_sockets.ptr[i]->sidx= (unsigned short)~0u;
845 }
846 for (uint32_t i = 0; i < srv->srv_sockets_inherited.used; ++i)
847 srv->srv_sockets_inherited.ptr[i]->srv = srv; /* update ptr */
848 }
849
850 __attribute_cold__
server_sockets_set_nb_cloexec(server * srv)851 static int server_sockets_set_nb_cloexec (server *srv) {
852 if (srv->sockets_disabled) return 0; /* lighttpd -1 (one-shot mode) */
853 for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) {
854 server_socket *srv_socket = srv->srv_sockets.ptr[i];
855 if (-1 == fdevent_fcntl_set_nb_cloexec_sock(srv_socket->fd)) {
856 log_perror(srv->errh, __FILE__, __LINE__, "fcntl()");
857 return -1;
858 }
859 }
860 return 0;
861 }
862
863 __attribute_cold__
server_sockets_set_event(server * srv,int event)864 static void server_sockets_set_event (server *srv, int event) {
865 for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) {
866 server_socket *srv_socket = srv->srv_sockets.ptr[i];
867 fdevent_fdnode_event_set(srv->ev, srv_socket->fdn, event);
868 }
869 }
870
871 __attribute_cold__
server_sockets_unregister(server * srv)872 static void server_sockets_unregister (server *srv) {
873 if (2 == srv->sockets_disabled) return;
874 srv->sockets_disabled = 2;
875 for (uint32_t i = 0; i < srv->srv_sockets.used; ++i)
876 network_unregister_sock(srv, srv->srv_sockets.ptr[i]);
877 }
878
879 __attribute_cold__
server_sockets_close(server * srv)880 static void server_sockets_close (server *srv) {
881 /* closing socket right away will make it possible for the next lighttpd
882 * to take over (old-style graceful restart), but only if backends
883 * (e.g. fastcgi, scgi, etc) are independent from lighttpd, rather
884 * than started by lighttpd via "bin-path")
885 */
886 if (3 == srv->sockets_disabled) return;
887 for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) {
888 server_socket *srv_socket = srv->srv_sockets.ptr[i];
889 if (-1 == srv_socket->fd) continue;
890 if (2 != srv->sockets_disabled) network_unregister_sock(srv,srv_socket);
891 close(srv_socket->fd);
892 srv_socket->fd = -1;
893 /* network_close() will cleanup after us */
894 }
895 srv->sockets_disabled = 3;
896 }
897
898 __attribute_cold__
server_graceful_signal_prev_generation(void)899 static void server_graceful_signal_prev_generation (void)
900 {
901 const char * const prev_gen = getenv("LIGHTTPD_PREV_GEN");
902 if (NULL == prev_gen) return;
903 pid_t pid = (pid_t)strtol(prev_gen, NULL, 10);
904 unsetenv("LIGHTTPD_PREV_GEN");
905 if (pid <= 0) return; /*(should not happen)*/
906 if (pid == fdevent_waitpid(pid,NULL,1)) return; /*(pid exited; unexpected)*/
907 kill(pid, SIGINT); /* signal previous generation for graceful shutdown */
908 }
909
910 __attribute_cold__
server_graceful_state_bg(server * srv)911 static int server_graceful_state_bg (server *srv) {
912 /*assert(graceful_restart);*/
913 /*(SIGUSR1 set to SIG_IGN in workers, so should not reach here if worker)*/
914 if (srv_shutdown) return 0;
915
916 /* check if server should fork and background (bg) itself
917 * to continue processing requests already in progress */
918 if (!config_feature_bool(srv, "server.graceful-restart-bg", 0)) return 0;
919
920 /*(set flag to false to avoid repeating)*/
921 data_unset * const du =
922 array_get_data_unset(srv->srvconf.feature_flags,
923 CONST_STR_LEN("server.graceful-restart-bg"));
924 if (du->type == TYPE_STRING)
925 buffer_copy_string_len(&((data_string *)du)->value,
926 CONST_STR_LEN("false"));
927 else /* (du->type == TYPE_INTEGER) */
928 ((data_integer *)du)->value = 0;
929
930 /* require exec'd via absolute path or daemon in foreground
931 * and exec'd with path containing '/' (e.g. "./xxxxx") */
932 char ** const argv = srv->argv;
933 if (0 == srv->srvconf.dont_daemonize
934 ? argv[0][0] != '/'
935 : NULL == strchr(argv[0], '/')) return 0;
936
937 /* flush log buffers to avoid potential duplication of entries
938 * server_handle_sighup(srv) does the following, but skip logging */
939 plugins_call_handle_sighup(srv);
940 fdlog_files_cycle(srv->errh); /* reopen log files, not pipes */
941
942 /* backgrounding to continue processing requests in progress */
943 /* re-exec lighttpd in original process
944 * Note: using path in re-exec is portable and allows lighttpd upgrade.
945 * OTOH, getauxval() AT_EXECFD and fexecve() could be used on Linux to
946 * re-exec without access to original executable on disk, which might be
947 * desirable in some situations, but is not implemented here.
948 * Alternatively, if argv[] was not available, could use readlink() on
949 * /proc/self/exe (Linux-specific), though there are ways on many other
950 * platforms to achieve the same:
951 * https://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe
952 */
953 #if defined(HAVE_KQUEUE)
954 #if defined(__FreeBSD__) || defined(__DragonFly__)
955 /*(must *exclude* rfork RFFDG flag for kqueue to work across rfork)*/
956 pid_t pid = rfork(RFPROC);
957 #else
958 pid_t pid = -1;
959 if (pid < 0) {
960 /* kqueue is not inherited across fork
961 * future: fdevent kqueue and stat_cache kqueue would need to be closed,
962 * re-opened, and active fds re-registered. Not current done.
963 * Need to create some routines like fdevent_reinit_after_fork*/
964 log_error(srv->errh, __FILE__, __LINE__,
965 "server.graceful-restart-bg ignored on OpenBSD and NetBSD "
966 "due to limitation in kqueue inheritance and lacking rfork");
967 return 0;
968 }
969 #endif
970 #else
971 pid_t pid = fork();
972 #endif
973 if (pid) { /* original process */
974 if (pid < 0) return 0;
975 network_socket_activation_to_env(srv);
976 /* save pid of original server in environment so that it can be
977 * signalled by restarted server once restarted server is ready
978 * to accept new connections */
979 server_graceful_signal_prev_generation();/*(expect no prev gen active)*/
980 if (0 == srv->srvconf.max_worker) {
981 buffer * const tb = srv->tmp_buf;
982 buffer_clear(tb);
983 buffer_append_int(tb, pid);
984 setenv("LIGHTTPD_PREV_GEN", tb->ptr, 1);
985 }
986 /*fdevent_waitpid(pid, NULL, 0);*//* detach? */
987 execv(argv[0], argv);
988 _exit(1);
989 }
990 /* else child/grandchild */
991
992 /*if (-1 == setsid()) _exit(1);*//* should we detach? */
993 /* Note: restarted server will fail with socket-in-use error if
994 * server.systemd-socket-activation not enabled in restarted server */
995 if (0 != srv->srvconf.max_worker)
996 server_sockets_close(srv);/*(close before parent reaps pid in waitpid)*/
997 /*if (0 != fork()) _exit(0);*//* should we detach? */
998 /*(grandchild is now backgrounded and detached from original process)*/
999
1000 /* XXX: might extend code to have new server.feature-flags param specify
1001 * max lifetime before aborting remaining connections */
1002
1003 /* (reached if lighttpd workers or if sole process w/o workers)
1004 * use same code as comment elsewhere in server.c:
1005 * make sure workers do not muck with pid-file */
1006 if (0 <= pid_fd) {
1007 close(pid_fd);
1008 pid_fd = -1;
1009 }
1010 srv->srvconf.pid_file = NULL;
1011
1012 /* (original process is backgrounded -- even if no active connections --
1013 * to allow graceful shutdown tasks to be run by server and by modules) */
1014 log_error(srv->errh, __FILE__, __LINE__,
1015 "[note] pid %lld continuing to handle %u connection(s) in progress",
1016 (long long)getpid(), srv->srvconf.max_conns - srv->lim_conns);
1017
1018 if (0 == srv->srvconf.max_worker) {
1019 /* reset graceful_shutdown; wait for signal from restarted server */
1020 srv->graceful_expire_ts = 0;
1021 graceful_shutdown = 0;
1022 }
1023 graceful_restart = 0;
1024 return 1;
1025 }
1026
1027 __attribute_cold__
1028 __attribute_noinline__
server_graceful_shutdown_maint(server * srv)1029 static void server_graceful_shutdown_maint (server *srv) {
1030 if (oneshot_fd) {
1031 /* permit keep-alive on one-shot connections until graceful_expire_ts */
1032 if (!srv->graceful_expire_ts) return;
1033 if (srv->graceful_expire_ts >= log_monotonic_secs) return;
1034 }
1035 connection_graceful_shutdown_maint(srv);
1036 }
1037
1038 __attribute_cold__
1039 __attribute_noinline__
server_graceful_state(server * srv)1040 static void server_graceful_state (server *srv) {
1041
1042 if (!srv_shutdown) {
1043 if (0 == srv->graceful_expire_ts) {
1044 srv->graceful_expire_ts =
1045 config_feature_int(srv, "server.graceful-shutdown-timeout", 8);
1046 if (srv->graceful_expire_ts)
1047 srv->graceful_expire_ts += log_monotonic_secs;
1048 }
1049 server_graceful_shutdown_maint(srv);
1050 }
1051
1052 if (2 == srv->sockets_disabled || 3 == srv->sockets_disabled) {
1053 if (oneshot_fd) graceful_restart = 0;
1054 return;
1055 }
1056
1057 log_error(srv->errh,__FILE__,__LINE__,"[note] graceful shutdown started");
1058
1059 /* no graceful restart if chroot()ed, if oneshot mode, or if idle timeout */
1060 if (srv->srvconf.changeroot || oneshot_fd || 2 == graceful_shutdown)
1061 graceful_restart = 0;
1062
1063 if (graceful_restart) {
1064 if (!server_graceful_state_bg(srv))
1065 server_sockets_unregister(srv);
1066 if (pid_fd > 0) pid_fd = -pid_fd; /*(flag to skip removing pid file)*/
1067 }
1068 else {
1069 server_sockets_close(srv);
1070 remove_pid_file(srv);
1071 /*(prevent more removal attempts)*/
1072 srv->srvconf.pid_file = NULL;
1073 }
1074 }
1075
1076 __attribute_cold__
1077 __attribute_noinline__
server_sockets_enable(server * srv)1078 static void server_sockets_enable (server *srv) {
1079 server_sockets_set_event(srv, FDEVENT_IN);
1080 srv->sockets_disabled = 0;
1081 log_error(srv->errh, __FILE__, __LINE__, "[note] sockets enabled again");
1082 }
1083
1084 __attribute_cold__
1085 __attribute_noinline__
server_sockets_disable(server * srv)1086 static void server_sockets_disable (server *srv) {
1087 server_sockets_set_event(srv, 0);
1088 srv->sockets_disabled = 1;
1089 log_error(srv->errh, __FILE__, __LINE__,
1090 (0 == srv->lim_conns)
1091 ? "[note] sockets disabled, connection limit reached"
1092 : "[note] sockets disabled, out-of-fds");
1093 }
1094
1095 __attribute_cold__
server_overload_check(server * srv)1096 static void server_overload_check (server *srv) {
1097 if (srv->cur_fds < srv->max_fds_lowat && 0 != srv->lim_conns)
1098 server_sockets_enable(srv);
1099 }
1100
server_load_check(server * srv)1101 static void server_load_check (server *srv) {
1102 /* check if hit limits for num fds used or num connections */
1103 if (srv->cur_fds > srv->max_fds_hiwat || 0 == srv->lim_conns)
1104 server_sockets_disable(srv);
1105 }
1106
1107 #ifdef HAVE_FORK
1108 __attribute_noinline__
server_main_setup_workers(server * const srv,const int npids)1109 static int server_main_setup_workers (server * const srv, const int npids) {
1110 pid_t pid;
1111 int num_childs = npids;
1112 int child = 0;
1113 unsigned int timer = 0;
1114 pid_t pids[npids];
1115 for (int n = 0; n < npids; ++n) pids[n] = -1;
1116 server_graceful_signal_prev_generation();
1117 while (!child && !srv_shutdown && !graceful_shutdown) {
1118 if (num_childs > 0) {
1119 switch ((pid = fork())) {
1120 case -1:
1121 return -1;
1122 case 0:
1123 child = 1;
1124 alarm(0);
1125 break;
1126 default:
1127 num_childs--;
1128 for (int n = 0; n < npids; ++n) {
1129 if (-1 == pids[n]) {
1130 pids[n] = pid;
1131 break;
1132 }
1133 }
1134 break;
1135 }
1136 }
1137 else {
1138 int status;
1139 unix_time64_t mono_ts;
1140 if (-1 != (pid = fdevent_waitpid_intr(-1, &status))) {
1141 mono_ts = log_monotonic_secs;
1142 log_monotonic_secs = server_monotonic_secs();
1143 log_epoch_secs =
1144 server_epoch_secs(srv, log_monotonic_secs - mono_ts);
1145 if (plugins_call_handle_waitpid(srv, pid, status)
1146 != HANDLER_GO_ON) {
1147 if (!timer) alarm((timer = 5));
1148 continue;
1149 }
1150 switch (fdlog_pipes_waitpid_cb(pid)) {
1151 default: break;
1152 case -1: if (!timer) alarm((timer = 5));
1153 __attribute_fallthrough__
1154 case 1: continue;
1155 }
1156 /**
1157 * check if one of our workers went away
1158 */
1159 for (int n = 0; n < npids; ++n) {
1160 if (pid == pids[n]) {
1161 pids[n] = -1;
1162 num_childs++;
1163 break;
1164 }
1165 }
1166 }
1167 else if (errno == EINTR) {
1168 mono_ts = log_monotonic_secs;
1169 log_monotonic_secs = server_monotonic_secs();
1170 log_epoch_secs =
1171 server_epoch_secs(srv, log_monotonic_secs - mono_ts);
1172 /* On SIGHUP, cycle logs (periodic maint runs in children) */
1173 if (handle_sig_hup) {
1174 handle_sig_hup = 0;
1175 fdlog_files_cycle(srv->errh);/*reopen log files, not pipes*/
1176 /* forward SIGHUP to workers */
1177 for (int n = 0; n < npids; ++n) {
1178 if (pids[n] > 0) kill(pids[n], SIGHUP);
1179 }
1180 }
1181 if (handle_sig_alarm) {
1182 handle_sig_alarm = 0;
1183 timer = 0;
1184 plugins_call_handle_trigger(srv);
1185 fdlog_pipes_restart(log_monotonic_secs);
1186 }
1187 }
1188 }
1189 }
1190
1191 if (!child) {
1192 /* exit point for parent monitoring workers;
1193 * signal children, too */
1194 if (graceful_shutdown || graceful_restart) {
1195 /* flag to ignore one SIGINT if graceful_restart */
1196 if (graceful_restart) graceful_restart = 2;
1197 kill(0, SIGINT);
1198 server_graceful_state(srv);
1199 }
1200 else if (srv_shutdown)
1201 kill(0, SIGTERM);
1202
1203 return 0;
1204 }
1205
1206 /* ignore SIGUSR1 in workers; only parent directs graceful restart */
1207 #ifdef HAVE_SIGACTION
1208 struct sigaction actignore;
1209 memset(&actignore, 0, sizeof(actignore));
1210 actignore.sa_handler = SIG_IGN;
1211 sigaction(SIGUSR1, &actignore, NULL);
1212 #elif defined(HAVE_SIGNAL)
1213 signal(SIGUSR1, SIG_IGN);
1214 #endif
1215
1216 /**
1217 * make sure workers do not muck with pid-file
1218 */
1219 if (0 <= pid_fd) {
1220 close(pid_fd);
1221 pid_fd = -1;
1222 }
1223 srv->srvconf.pid_file = NULL;
1224
1225 fdlog_pipes_abandon_pids();
1226 srv->pid = getpid();
1227 li_rand_reseed();
1228
1229 return 1; /* child worker */
1230 }
1231 #endif
1232
1233 __attribute_cold__
1234 __attribute_noinline__
server_main_setup(server * const srv,int argc,char ** argv)1235 static int server_main_setup (server * const srv, int argc, char **argv) {
1236 int print_config = 0;
1237 int test_config = 0;
1238 int i_am_root = 0;
1239 #ifdef HAVE_FORK
1240 int parent_pipe_fd = -1;
1241 #endif
1242
1243 #ifdef HAVE_GETUID
1244 i_am_root = (0 == getuid());
1245 #endif
1246
1247 /* initialize globals (including file-scoped static globals) */
1248 oneshot_fd = 0;
1249 oneshot_fdout = -1;
1250 srv_shutdown = 0;
1251 graceful_shutdown = 0;
1252 handle_sig_alarm = 1;
1253 handle_sig_hup = 0;
1254 idle_limit = 0;
1255 chunkqueue_set_tempdirs_default_reset();
1256 /*graceful_restart = 0;*//*(reset below to avoid further daemonizing)*/
1257 /*(intentionally preserved)*/
1258 /*memset(graceful_sockets, 0, sizeof(graceful_sockets));*/
1259 /*memset(inherited_sockets, 0, sizeof(inherited_sockets));*/
1260 /*pid_fd = -1;*/
1261 srv->argv = argv;
1262
1263 for (int o; -1 != (o = getopt(argc, argv, "f:m:i:hvVD1pt")); ) {
1264 switch(o) {
1265 case 'f':
1266 if (srv->config_data_base) {
1267 log_error(srv->errh, __FILE__, __LINE__,
1268 "Can only read one config file. Use the include command to use multiple config files.");
1269 return -1;
1270 }
1271 if (config_read(srv, optarg)) {
1272 return -1;
1273 }
1274 break;
1275 case 'm':
1276 srv->srvconf.modules_dir = optarg;
1277 break;
1278 case 'i': {
1279 char *endptr;
1280 long timeout = strtol(optarg, &endptr, 0);
1281 if (!*optarg || *endptr || timeout < 0) {
1282 log_error(srv->errh, __FILE__, __LINE__,
1283 "Invalid idle timeout value: %s", optarg);
1284 return -1;
1285 }
1286 idle_limit = (int)timeout;
1287 break;
1288 }
1289 case 'p': print_config = 1; break;
1290 case 't': ++test_config; break;
1291 case '1': if (0 == oneshot_fd) oneshot_fd = dup(STDIN_FILENO);
1292 break;
1293 case 'D': srv->srvconf.dont_daemonize = 1; break;
1294 case 'v': show_version(); return 0;
1295 case 'V': show_features(); return 0;
1296 case 'h': show_help(); return 0;
1297 default:
1298 show_help();
1299 return -1;
1300 }
1301 }
1302
1303 #ifdef __CYGWIN__
1304 if (!srv->config_data_base && NULL != getenv("NSSM_SERVICE_NAME")) {
1305 char *dir = getenv("NSSM_SERVICE_DIR");
1306 if (NULL != dir && 0 != chdir(dir)) {
1307 log_perror(srv->errh, __FILE__, __LINE__, "chdir %s failed", dir);
1308 return -1;
1309 }
1310 srv->srvconf.dont_daemonize = 1;
1311 srv->srvconf.modules_dir = "modules";
1312 if (config_read(srv, "conf/lighttpd.conf")) return -1;
1313 }
1314 #endif
1315
1316 if (!srv->config_data_base) {
1317 log_error(srv->errh, __FILE__, __LINE__,
1318 "No configuration available. Try using -f option.");
1319 return -1;
1320 }
1321
1322 if (1 == srv->srvconf.max_worker)
1323 srv->srvconf.max_worker = 0;
1324
1325 if (print_config) {
1326 config_print(srv);
1327 puts(srv->tmp_buf->ptr);
1328 }
1329
1330 if (test_config) {
1331 srv->srvconf.pid_file = NULL;
1332 if (1 == test_config) {
1333 printf("Syntax OK\n");
1334 } else { /*(test_config > 1)*/
1335 test_config = 0;
1336 srv->srvconf.preflight_check = 1;
1337 srv->srvconf.dont_daemonize = 1;
1338 }
1339 }
1340
1341 if (test_config || print_config) {
1342 return 0;
1343 }
1344
1345 #if defined(HAVE_MALLOC_TRIM)
1346 if (srv->srvconf.max_conns <= 16 && malloc_top_pad == 524288)
1347 malloc_top_pad = 131072; /*(reduce memory use on small systems)*/
1348 #endif
1349
1350 if (oneshot_fd) {
1351 if (oneshot_fd <= STDERR_FILENO) {
1352 log_error(srv->errh, __FILE__, __LINE__,
1353 "Invalid fds at startup with lighttpd -1");
1354 return -1;
1355 }
1356 graceful_shutdown = 1;
1357 srv->sockets_disabled = 2;
1358 srv->srvconf.dont_daemonize = 1;
1359 srv->srvconf.pid_file = NULL;
1360 if (srv->srvconf.max_worker) {
1361 srv->srvconf.max_worker = 0;
1362 log_error(srv->errh, __FILE__, __LINE__,
1363 "server one-shot command line option disables server.max-worker config file option.");
1364 }
1365
1366 struct stat st;
1367 if (0 != fstat(oneshot_fd, &st)) {
1368 log_perror(srv->errh, __FILE__, __LINE__, "fstat()");
1369 return -1;
1370 }
1371
1372 if (S_ISFIFO(st.st_mode)) {
1373 oneshot_fdout = dup(STDOUT_FILENO);
1374 if (oneshot_fdout <= STDERR_FILENO) {
1375 log_perror(srv->errh, __FILE__, __LINE__, "dup()");
1376 return -1;
1377 }
1378 }
1379 else if (!S_ISSOCK(st.st_mode)) {
1380 /* require that fd is a socket
1381 * (modules might expect STDIN_FILENO and STDOUT_FILENO opened to /dev/null) */
1382 log_error(srv->errh, __FILE__, __LINE__,
1383 "lighttpd -1 stdin is not a socket");
1384 return -1;
1385 }
1386 }
1387
1388 if (srv->srvconf.bindhost && buffer_is_equal_string(srv->srvconf.bindhost, CONST_STR_LEN("/dev/stdin"))) {
1389 if (-1 == srv->stdin_fd)
1390 srv->stdin_fd = dup(STDIN_FILENO);
1391 if (srv->stdin_fd <= STDERR_FILENO) {
1392 log_error(srv->errh, __FILE__, __LINE__,
1393 "Invalid fds at startup");
1394 return -1;
1395 }
1396 }
1397
1398 /* close stdin and stdout, as they are not needed */
1399 {
1400 struct stat st;
1401 int devnull;
1402 int errfd;
1403 do {
1404 /* coverity[overwrite_var : FALSE] */
1405 devnull = fdevent_open_devnull();
1406 #ifdef __COVERITY__
1407 __coverity_escape__(devnull);
1408 #endif
1409 } while (-1 != devnull && devnull <= STDERR_FILENO);
1410 if (-1 == devnull) {
1411 log_perror(srv->errh, __FILE__, __LINE__,
1412 "opening /dev/null failed");
1413 return -1;
1414 }
1415 errfd = (0 == fstat(STDERR_FILENO, &st)) ? -1 : devnull;
1416 if (0 != fdevent_set_stdin_stdout_stderr(devnull, devnull, errfd)) {
1417 log_perror(srv->errh, __FILE__, __LINE__,
1418 "setting default fds failed");
1419 #ifdef FD_CLOEXEC
1420 if (-1 != errfd) close(errfd);
1421 if (devnull != errfd) close(devnull);
1422 #endif
1423 return -1;
1424 }
1425 #ifdef FD_CLOEXEC
1426 if (-1 != errfd) close(errfd);
1427 if (devnull != errfd) close(devnull);
1428 #endif
1429 }
1430
1431 http_response_send_1xx_cb_set(NULL, HTTP_VERSION_2);
1432 if (!config_feature_bool(srv, "server.h2-discard-backend-1xx", 0))
1433 http_response_send_1xx_cb_set(h2_send_1xx, HTTP_VERSION_2);
1434
1435 http_response_send_1xx_cb_set(NULL, HTTP_VERSION_1_1);
1436 if (!config_feature_bool(srv, "server.h1-discard-backend-1xx", 0))
1437 http_response_send_1xx_cb_set(connection_send_1xx, HTTP_VERSION_1_1);
1438
1439 http_range_config_allow_http10(config_feature_bool(srv, "http10.range", 0));
1440
1441 if (0 != config_set_defaults(srv)) {
1442 log_error(srv->errh, __FILE__, __LINE__,
1443 "setting default values failed");
1444 return -1;
1445 }
1446
1447 if (plugins_load(srv)) {
1448 log_error(srv->errh, __FILE__, __LINE__,
1449 "loading plugins finally failed");
1450 return -1;
1451 }
1452
1453 if (HANDLER_GO_ON != plugins_call_init(srv)) {
1454 log_error(srv->errh, __FILE__, __LINE__,
1455 "Initialization of plugins failed. Going down.");
1456 return -1;
1457 }
1458
1459 /* mod_indexfile should be listed in server.modules prior to dynamic handlers */
1460 uint32_t i = 0;
1461 for (const char *pname = NULL; i < srv->plugins.used; ++i) {
1462 plugin *p = ((plugin **)srv->plugins.ptr)[i];
1463 if (0 == strcmp(p->name, "indexfile")) {
1464 if (pname)
1465 log_error(srv->errh, __FILE__, __LINE__,
1466 "Warning: mod_indexfile should be listed in server.modules prior to mod_%s", pname);
1467 break;
1468 }
1469 if (p->handle_subrequest_start && p->handle_subrequest) {
1470 if (!pname) pname = p->name;
1471 }
1472 }
1473
1474 /* open pid file BEFORE chroot */
1475 if (-2 == pid_fd) pid_fd = -1; /*(initial startup state)*/
1476 if (-1 == pid_fd && srv->srvconf.pid_file) {
1477 const char *pidfile = srv->srvconf.pid_file->ptr;
1478 if (-1 == (pid_fd = fdevent_open_cloexec(pidfile, 0, O_WRONLY | O_CREAT | O_EXCL | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH))) {
1479 struct stat st;
1480 if (errno != EEXIST) {
1481 log_perror(srv->errh, __FILE__, __LINE__,
1482 "opening pid-file failed: %s", pidfile);
1483 return -1;
1484 }
1485
1486 if (0 != stat(pidfile, &st)) {
1487 log_perror(srv->errh, __FILE__, __LINE__,
1488 "stating existing pid-file failed: %s", pidfile);
1489 }
1490
1491 if (!S_ISREG(st.st_mode)) {
1492 log_error(srv->errh, __FILE__, __LINE__,
1493 "pid-file exists and isn't regular file: %s", pidfile);
1494 return -1;
1495 }
1496
1497 if (-1 == (pid_fd = fdevent_open_cloexec(pidfile, 0, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH))) {
1498 log_perror(srv->errh, __FILE__, __LINE__,
1499 "opening pid-file failed: %s", pidfile);
1500 return -1;
1501 }
1502 }
1503 }
1504
1505 {
1506 #ifdef HAVE_GETRLIMIT
1507 struct rlimit rlim = { 4096, 4096 };
1508 int use_rlimit = 1;
1509 #ifdef HAVE_VALGRIND_VALGRIND_H
1510 if (RUNNING_ON_VALGRIND) use_rlimit = 0;
1511 #endif
1512
1513 if (0 != getrlimit(RLIMIT_NOFILE, &rlim)) {
1514 log_perror(srv->errh, __FILE__, __LINE__, "getrlimit()");
1515 use_rlimit = 0;
1516 }
1517
1518 /**
1519 * if we are not root can can't increase the fd-limit above rlim_max, but we can reduce it
1520 */
1521 if (use_rlimit && srv->srvconf.max_fds
1522 && (i_am_root || srv->srvconf.max_fds <= rlim.rlim_max)) {
1523 /* set rlimits */
1524
1525 rlim_t rlim_cur = rlim.rlim_cur;
1526 rlim.rlim_cur = srv->srvconf.max_fds;
1527 if (i_am_root) rlim.rlim_max = srv->srvconf.max_fds;
1528
1529 if (0 != setrlimit(RLIMIT_NOFILE, &rlim)) {
1530 log_perror(srv->errh, __FILE__, __LINE__, "setrlimit()");
1531 log_error(srv->errh, __FILE__, __LINE__, "setrlimit() may need root to run once: setsebool -P httpd_setrlimit on");
1532 use_rlimit = 0;
1533 if (srv->srvconf.max_fds > rlim_cur)
1534 srv->srvconf.max_fds = rlim_cur;
1535 }
1536 }
1537
1538 /*(default upper limit of 4k if server.max-fds not specified)*/
1539 if (0 == srv->srvconf.max_fds)
1540 srv->srvconf.max_fds = (rlim.rlim_cur <= 4096)
1541 ? (unsigned short)rlim.rlim_cur
1542 : 4096;
1543
1544 /* set core file rlimit, if enable_cores is set */
1545 if (use_rlimit && srv->srvconf.enable_cores && getrlimit(RLIMIT_CORE, &rlim) == 0) {
1546 rlim.rlim_cur = rlim.rlim_max;
1547 setrlimit(RLIMIT_CORE, &rlim);
1548 }
1549 #endif
1550 }
1551
1552 /* we need root-perms for port < 1024 */
1553 if (0 != network_init(srv, srv->stdin_fd)) {
1554 return -1;
1555 }
1556 srv->stdin_fd = -1;
1557
1558 if (i_am_root) {
1559 #ifdef HAVE_PWD_H
1560 /* set user and group */
1561 struct group *grp = NULL;
1562 struct passwd *pwd = NULL;
1563
1564 if (srv->srvconf.groupname) {
1565 if (NULL == (grp = getgrnam(srv->srvconf.groupname->ptr))) {
1566 log_error(srv->errh, __FILE__, __LINE__,
1567 "can't find groupname %s", srv->srvconf.groupname->ptr);
1568 return -1;
1569 }
1570 }
1571
1572 if (srv->srvconf.username) {
1573 if (NULL == (pwd = getpwnam(srv->srvconf.username->ptr))) {
1574 log_error(srv->errh, __FILE__, __LINE__,
1575 "can't find username %s", srv->srvconf.username->ptr);
1576 return -1;
1577 }
1578
1579 if (pwd->pw_uid == 0) {
1580 log_error(srv->errh, __FILE__, __LINE__,
1581 "I will not set uid to 0. Perhaps you should comment out server.username in lighttpd.conf\n");
1582 return -1;
1583 }
1584
1585 if (NULL == grp && NULL == (grp = getgrgid(pwd->pw_gid))) {
1586 log_error(srv->errh, __FILE__, __LINE__,
1587 "can't find group id %d", (int)pwd->pw_gid);
1588 return -1;
1589 }
1590 }
1591
1592 if (NULL != grp) {
1593 if (grp->gr_gid == 0) {
1594 log_error(srv->errh, __FILE__, __LINE__,
1595 "I will not set gid to 0. Perhaps you should comment out server.groupname in lighttpd.conf\n");
1596 return -1;
1597 }
1598 }
1599
1600 /*
1601 * Change group before chroot, when we have access
1602 * to /etc/group
1603 * */
1604 if (NULL != grp) {
1605 if (-1 == setgid(grp->gr_gid)) {
1606 log_perror(srv->errh, __FILE__, __LINE__, "setgid()");
1607 return -1;
1608 }
1609 if (-1 == setgroups(0, NULL)) {
1610 log_perror(srv->errh, __FILE__, __LINE__, "setgroups()");
1611 return -1;
1612 }
1613 if (srv->srvconf.username) {
1614 initgroups(srv->srvconf.username->ptr, grp->gr_gid);
1615 }
1616 }
1617 #endif
1618 #ifdef HAVE_CHROOT
1619 if (srv->srvconf.changeroot) {
1620 tzset();
1621
1622 if (-1 == chroot(srv->srvconf.changeroot->ptr)) {
1623 log_perror(srv->errh, __FILE__, __LINE__, "chroot()");
1624 return -1;
1625 }
1626 if (-1 == chdir("/")) {
1627 log_perror(srv->errh, __FILE__, __LINE__, "chdir()");
1628 return -1;
1629 }
1630 }
1631 #endif
1632 #ifdef HAVE_PWD_H
1633 /* drop root privs */
1634 if (NULL != pwd) {
1635 if (-1 == setuid(pwd->pw_uid)) {
1636 log_perror(srv->errh, __FILE__, __LINE__, "setuid()");
1637 return -1;
1638 }
1639 }
1640 #endif
1641 #if defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_DUMPABLE)
1642 /**
1643 * on IRIX 6.5.30 they have prctl() but no DUMPABLE
1644 */
1645 if (srv->srvconf.enable_cores) {
1646 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
1647 }
1648 #elif defined(HAVE_SYS_PROCCTL_H) && defined(PROC_TRACE_CTL_ENABLE)
1649 /* (DragonFlyBSD has procctl(), but not PROC_TRACE_CTL_ENABLE) */
1650 if (srv->srvconf.enable_cores) {
1651 int dumpable = PROC_TRACE_CTL_ENABLE;
1652 procctl(P_PID, 0, PROC_TRACE_CTL, &dumpable);
1653 }
1654 #elif defined(HAVE_SETPFLAGS) && defined(__PROC_PROTECT)
1655 /**
1656 * setpflags seems uniquely a solaris/illumos feature
1657 * but just taking extra precautions clearing __PROC_PROTECT option
1658 */
1659 if (srv->srvconf.enable_cores) {
1660 setpflags(__PROC_PROTECT, 0);
1661 }
1662 #endif
1663 }
1664
1665 #ifdef HAVE_FORK
1666 /* network is up, let's daemonize ourself */
1667 if (0 == srv->srvconf.dont_daemonize && 0 == graceful_restart) {
1668 parent_pipe_fd = daemonize();
1669 }
1670 #endif
1671 graceful_restart = 0;/*(reset here after avoiding further daemonizing)*/
1672 if (0 == oneshot_fd) graceful_shutdown = 0;
1673
1674 server_main_setup_signals();
1675
1676 srv->gid = getgid();
1677 srv->uid = getuid();
1678 srv->pid = getpid();
1679
1680 /* write pid file */
1681 if (pid_fd > 2) {
1682 buffer * const tb = srv->tmp_buf;
1683 buffer_clear(tb);
1684 buffer_append_int(tb, srv->pid);
1685 buffer_append_char(tb, '\n');
1686 if (-1 == write_all(pid_fd, BUF_PTR_LEN(tb))) {
1687 log_perror(srv->errh, __FILE__, __LINE__, "Couldn't write pid file");
1688 close(pid_fd);
1689 pid_fd = -1;
1690 return -1;
1691 }
1692 } else if (pid_fd < -2) {
1693 pid_fd = -pid_fd;
1694 }
1695
1696 /* Close stderr ASAP in the child process to make sure that nothing
1697 * is being written to that fd which may not be valid anymore. */
1698 if (!srv->srvconf.preflight_check) {
1699 if (-1 == config_log_error_open(srv)) {
1700 log_error(srv->errh, __FILE__, __LINE__, "Opening errorlog failed. Going down.");
1701 return -1;
1702 }
1703 if (!oneshot_fd)
1704 log_error(srv->errh, __FILE__, __LINE__, "server started (" PACKAGE_DESC ")");
1705 }
1706
1707 if (HANDLER_GO_ON != plugins_call_set_defaults(srv)) {
1708 log_error(srv->errh, __FILE__, __LINE__, "Configuration of plugins failed. Going down.");
1709 return -1;
1710 }
1711
1712 if (!config_finalize(srv, &default_server_tag)) {
1713 return -1;
1714 }
1715
1716 if (srv->srvconf.preflight_check) {
1717 /*printf("Preflight OK");*//*(stdout reopened to /dev/null)*/
1718 return 0;
1719 }
1720
1721
1722 #ifdef HAVE_FORK
1723 /**
1724 * notify daemonize-grandparent of successful startup
1725 * do this before any further forking is done (workers)
1726 */
1727 if (0 == srv->srvconf.dont_daemonize && -1 != parent_pipe_fd) {
1728 if (0 > write(parent_pipe_fd, "", 1)) return -1;
1729 close(parent_pipe_fd);
1730 }
1731
1732 if (idle_limit && srv->srvconf.max_worker) {
1733 srv->srvconf.max_worker = 0;
1734 log_error(srv->errh, __FILE__, __LINE__,
1735 "server idle time limit command line option disables server.max-worker config file option.");
1736 }
1737
1738 /* start watcher and workers */
1739 if (srv->srvconf.max_worker > 0) {
1740 int rc = server_main_setup_workers(srv, srv->srvconf.max_worker);
1741 if (rc != 1) /* 1 for worker; 0 for worker parent done; -1 for error */
1742 return rc;
1743 }
1744 #endif
1745
1746 srv->max_fds = (int)srv->srvconf.max_fds;
1747 if (srv->max_fds < 32) /*(sanity check; not expected)*/
1748 srv->max_fds = 32; /*(server load checks will fail if too low)*/
1749 srv->ev = fdevent_init(srv->srvconf.event_handler, &srv->max_fds, &srv->cur_fds, srv->errh);
1750 if (NULL == srv->ev) {
1751 log_error(srv->errh, __FILE__, __LINE__, "fdevent_init failed");
1752 return -1;
1753 }
1754
1755 srv->max_fds_lowat = srv->max_fds * 8 / 10;
1756 srv->max_fds_hiwat = srv->max_fds * 9 / 10;
1757
1758 /* set max-conns */
1759 if (srv->srvconf.max_conns > srv->max_fds/2) {
1760 /* we can't have more connections than max-fds/2 */
1761 log_error(srv->errh, __FILE__, __LINE__,
1762 "can't have more connections than fds/2: %hu %d",
1763 srv->srvconf.max_conns, srv->max_fds);
1764 srv->lim_conns = srv->srvconf.max_conns = srv->max_fds/2;
1765 } else if (srv->srvconf.max_conns) {
1766 /* otherwise respect the wishes of the user */
1767 srv->lim_conns = srv->srvconf.max_conns;
1768 } else {
1769 /* or use the default: we really don't want to hit max-fds */
1770 srv->lim_conns = srv->srvconf.max_conns = srv->max_fds/3;
1771 }
1772
1773 /*
1774 * kqueue() is called here, select resets its internals,
1775 * all server sockets get their handlers
1776 *
1777 * */
1778 if (0 != network_register_fdevents(srv)) {
1779 return -1;
1780 }
1781
1782 chunkqueue_internal_pipes(config_feature_bool(srv, "chunkqueue.splice", 1));
1783
1784 /* might fail if user is using fam (not gamin) and famd isn't running */
1785 if (!stat_cache_init(srv->ev, srv->errh)) {
1786 log_error(srv->errh, __FILE__, __LINE__,
1787 "stat-cache could not be setup, dying.");
1788 return -1;
1789 }
1790
1791 #ifdef USE_ALARM
1792 {
1793 /* setup periodic timer (1 second) */
1794 struct itimerval interval;
1795 interval.it_interval.tv_sec = 1;
1796 interval.it_interval.tv_usec = 0;
1797 interval.it_value.tv_sec = 1;
1798 interval.it_value.tv_usec = 0;
1799 if (setitimer(ITIMER_REAL, &interval, NULL)) {
1800 log_perror(srv->errh, __FILE__, __LINE__, "setitimer()");
1801 return -1;
1802 }
1803 }
1804 #endif
1805
1806 /* get the current number of FDs */
1807 {
1808 int fd = fdevent_open_devnull();
1809 if (fd >= 0) {
1810 srv->cur_fds = fd;
1811 close(fd);
1812 }
1813 }
1814
1815 if (0 != server_sockets_set_nb_cloexec(srv)) {
1816 return -1;
1817 }
1818
1819 /* plugin hook for worker_init */
1820 if (HANDLER_GO_ON != plugins_call_worker_init(srv))
1821 return -1;
1822
1823 if (oneshot_fdout > 0) {
1824 if (server_oneshot_init_pipe(srv, oneshot_fd, oneshot_fdout)) {
1825 oneshot_fd = -1;
1826 oneshot_fdout = -1;
1827 }
1828 }
1829 else if (oneshot_fd && server_oneshot_init(srv, oneshot_fd)) {
1830 oneshot_fd = -1;
1831 }
1832
1833 if (0 == srv->srvconf.max_worker)
1834 server_graceful_signal_prev_generation();
1835
1836 return 1;
1837 }
1838
1839 __attribute_cold__
1840 __attribute_noinline__
server_handle_sighup(server * const srv)1841 static void server_handle_sighup (server * const srv) {
1842
1843 /* cycle logfiles */
1844
1845 plugins_call_handle_sighup(srv);
1846 fdlog_files_cycle(srv->errh); /* reopen log files, not pipes */
1847 #ifdef HAVE_SIGACTION
1848 log_error(srv->errh, __FILE__, __LINE__,
1849 "logfiles cycled UID = %d PID = %d",
1850 (int)last_sighup_info.si_uid,
1851 (int)last_sighup_info.si_pid);
1852 #else
1853 log_error(srv->errh, __FILE__, __LINE__,
1854 "logfiles cycled");
1855 #endif
1856 }
1857
1858 __attribute_noinline__
server_handle_sigalrm(server * const srv,unix_time64_t mono_ts,unix_time64_t last_active_ts)1859 static void server_handle_sigalrm (server * const srv, unix_time64_t mono_ts, unix_time64_t last_active_ts) {
1860
1861 plugins_call_handle_trigger(srv);
1862
1863 log_monotonic_secs = mono_ts;
1864 log_epoch_secs = server_epoch_secs(srv, 0);
1865
1866 /* check idle time limit, if enabled */
1867 if (idle_limit && idle_limit < mono_ts - last_active_ts && !graceful_shutdown) {
1868 log_error(srv->errh, __FILE__, __LINE__,
1869 "[note] idle timeout %ds exceeded, "
1870 "initiating graceful shutdown", (int)idle_limit);
1871 graceful_shutdown = 2; /* value 2 indicates idle timeout */
1872 if (graceful_restart) {
1873 graceful_restart = 0;
1874 if (pid_fd < -2) pid_fd = -pid_fd;
1875 server_sockets_close(srv);
1876 }
1877 }
1878
1879 #ifdef HAVE_GETLOADAVG
1880 /* refresh loadavg data every 30 seconds */
1881 if (srv->loadts + 30 < mono_ts) {
1882 if (-1 != getloadavg(srv->loadavg, 3)) {
1883 srv->loadts = mono_ts;
1884 }
1885 }
1886 #endif
1887
1888 if (0 == (mono_ts & 0x3f)) { /*(once every 64 secs)*/
1889 /* free logger buffers every 64 secs */
1890 fdlog_flushall(srv->errh);
1891 /* free excess chunkqueue buffers every 64 secs */
1892 chunkqueue_chunk_pool_clear();
1893 /* clear request and connection pools every 64 secs */
1894 request_pool_free();
1895 connections_pool_clear(srv);
1896 #if defined(HAVE_MALLOC_TRIM)
1897 if (malloc_trim_fn) malloc_trim_fn(malloc_top_pad);
1898 #endif
1899 /* attempt to restart dead piped loggers every 64 secs */
1900 if (0 == srv->srvconf.max_worker)
1901 fdlog_pipes_restart(mono_ts);
1902 }
1903 /* cleanup stat-cache */
1904 stat_cache_trigger_cleanup();
1905 /* reset global/aggregate rate limit counters */
1906 config_reset_config_bytes_sec(srv->config_data_base);
1907 /* if graceful_shutdown, accelerate cleanup of recently completed request/responses */
1908 if (graceful_shutdown && !srv_shutdown)
1909 server_graceful_shutdown_maint(srv);
1910 connection_periodic_maint(srv, mono_ts);
1911 }
1912
1913 __attribute_noinline__
server_handle_sigchld(server * const srv)1914 static void server_handle_sigchld (server * const srv) {
1915 pid_t pid;
1916 do {
1917 int status;
1918 pid = fdevent_waitpid(-1, &status, 1);
1919 if (pid > 0) {
1920 if (plugins_call_handle_waitpid(srv, pid, status) != HANDLER_GO_ON) {
1921 continue;
1922 }
1923 if (0 == srv->srvconf.max_worker) {
1924 /* check piped-loggers and restart, even if shutting down */
1925 if (fdlog_pipes_waitpid_cb(pid)) {
1926 continue;
1927 }
1928 }
1929 }
1930 } while (pid > 0 || (-1 == pid && errno == EINTR));
1931 }
1932
1933 __attribute_hot__
__attribute_nonnull__()1934 __attribute_nonnull__()
1935 static void server_run_con_queue (connection * const restrict joblist, const connection * const sentinel) {
1936 for (connection *con = joblist, *jqnext; con != sentinel; con = jqnext) {
1937 jqnext = con->jqnext;
1938 con->jqnext = NULL;
1939 connection_state_machine(con);
1940 }
1941 }
1942
1943 __attribute_hot__
1944 __attribute_noinline__
server_main_loop(server * const srv)1945 static void server_main_loop (server * const srv) {
1946 unix_time64_t last_active_ts = server_monotonic_secs();
1947 log_epoch_secs = server_epoch_secs(srv, 0);
1948
1949 while (!srv_shutdown) {
1950
1951 if (handle_sig_hup) {
1952 handle_sig_hup = 0;
1953 server_handle_sighup(srv);
1954 }
1955
1956 /*(USE_ALARM not used; fdevent_poll() is effective periodic timer)*/
1957 #ifdef USE_ALARM
1958 if (handle_sig_alarm) {
1959 handle_sig_alarm = 0;
1960 #endif
1961 unix_time64_t mono_ts = server_monotonic_secs();
1962 if (mono_ts != log_monotonic_secs) {
1963 server_handle_sigalrm(srv, mono_ts, last_active_ts);
1964 }
1965 #ifdef USE_ALARM
1966 }
1967 #endif
1968
1969 if (handle_sig_child) {
1970 handle_sig_child = 0;
1971 server_handle_sigchld(srv);
1972 }
1973
1974 if (graceful_shutdown) {
1975 server_graceful_state(srv);
1976 if (NULL == srv->conns && graceful_shutdown) {
1977 /* we are in graceful shutdown phase and all connections are closed
1978 * we are ready to terminate without harming anyone */
1979 srv_shutdown = 1;
1980 break;
1981 }
1982 } else if (srv->sockets_disabled) {
1983 server_overload_check(srv);
1984 } else {
1985 server_load_check(srv);
1986 }
1987
1988 static connection * const sentinel =
1989 (connection *)(uintptr_t)&log_con_jqueue;
1990 connection * const joblist = log_con_jqueue;
1991 log_con_jqueue = sentinel;
1992 server_run_con_queue(joblist, sentinel);
1993
1994 if (fdevent_poll(srv->ev, log_con_jqueue != sentinel ? 0 : 1000) > 0)
1995 last_active_ts = log_monotonic_secs;
1996 }
1997 }
1998
1999 __attribute_cold__
2000 __attribute_noinline__
main_init_once(void)2001 static int main_init_once (void) {
2002 #ifdef HAVE_GETUID
2003 #ifndef HAVE_ISSETUGID
2004 #define issetugid() (geteuid() != getuid() || getegid() != getgid())
2005 #endif
2006 if (0 != getuid() && issetugid()) { /*check as early as possible in main()*/
2007 fprintf(stderr,
2008 "Are you nuts ? Don't apply a SUID bit to this binary\n");
2009 return 0;
2010 }
2011 #endif
2012
2013 #if defined(HAVE_MALLOPT) && defined(M_ARENA_MAX)
2014 #ifdef LIGHTTPD_STATIC
2015 mallopt(M_ARENA_MAX, 2); /*(ignore error, if any)*/
2016 #else
2017 {
2018 int (*mallopt_fn)(int, int);
2019 mallopt_fn = (int (*)(int, int))(intptr_t)dlsym(RTLD_DEFAULT,"mallopt");
2020 if (mallopt_fn) mallopt_fn(M_ARENA_MAX, 2); /*(ignore error, if any)*/
2021 }
2022 #endif
2023 #endif
2024
2025 #if defined(HAVE_MALLOC_TRIM)
2026 malloc_top_pad = 524288;
2027 {
2028 const char * const top_pad_str = getenv("MALLOC_TOP_PAD_");
2029 if (top_pad_str) {
2030 unsigned long top_pad = strtoul(top_pad_str, NULL, 10);
2031 if (top_pad != ULONG_MAX) malloc_top_pad = (size_t)top_pad;
2032 }
2033 }
2034 #ifdef LIGHTTPD_STATIC
2035 malloc_trim_fn = malloc_trim;
2036 #else
2037 malloc_trim_fn =
2038 (int (*)(size_t))(intptr_t)dlsym(RTLD_DEFAULT,"malloc_trim");
2039 #endif
2040 #endif
2041
2042 /* for nice %b handling in strftime() */
2043 setlocale(LC_TIME, "C");
2044 tzset();
2045
2046 return 1;
2047 }
2048
2049 __attribute_cold__
main(int argc,char ** argv)2050 int main (int argc, char ** argv) {
2051 if (!main_init_once()) return -1;
2052
2053 int rc;
2054
2055 do {
2056 server * const srv = server_init();
2057
2058 if (graceful_restart) {
2059 server_sockets_restore(srv);
2060 optind = 1;
2061 }
2062
2063 rc = server_main_setup(srv, argc, argv);
2064 if (rc > 0) {
2065
2066 server_main_loop(srv);
2067
2068 if (graceful_shutdown || graceful_restart) {
2069 server_graceful_state(srv);
2070 }
2071
2072 if (NULL == srv->conns) rc = 0;
2073 if (2 == graceful_shutdown) { /* value 2 indicates idle timeout */
2074 log_error(srv->errh, __FILE__, __LINE__,
2075 "server stopped after idle timeout");
2076 } else if (!oneshot_fd) {
2077 #ifdef HAVE_SIGACTION
2078 log_error(srv->errh, __FILE__, __LINE__,
2079 "server stopped by UID = %d PID = %d",
2080 (int)last_sigterm_info.si_uid,
2081 (int)last_sigterm_info.si_pid);
2082 #else
2083 log_error(srv->errh, __FILE__, __LINE__,
2084 "server stopped");
2085 #endif
2086 }
2087 }
2088
2089 /* clean-up */
2090 chunkqueue_internal_pipes(0);
2091 remove_pid_file(srv);
2092 config_log_error_close(srv);
2093 if (graceful_restart)
2094 server_sockets_save(srv);
2095 else
2096 network_close(srv);
2097 request_pool_free();
2098 connections_free(srv);
2099 plugins_free(srv);
2100 server_free(srv);
2101
2102 if (rc < 0 || !graceful_restart) break;
2103
2104 /* wait for all children to exit before graceful restart */
2105 while (fdevent_waitpid(-1, NULL, 0) > 0) ;
2106 } while (graceful_restart);
2107
2108 return rc;
2109 }
2110