do not leak gotwebd sockets memory at shutdown time
[got-portable.git] / gotwebd / sockets.c
blobfaa2875c39e9246b2607ca0f6e8722b91e201e46
1 /*
2 * Copyright (c) 2016, 2019, 2020-2021 Tracey Emery <tracey@traceyemery.net>
3 * Copyright (c) 2015 Mike Larkin <mlarkin@openbsd.org>
4 * Copyright (c) 2013 David Gwynne <dlg@openbsd.org>
5 * Copyright (c) 2013 Florian Obser <florian@openbsd.org>
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20 #include "got_compat.h"
22 #include <sys/param.h>
23 #include <sys/ioctl.h>
24 #include <sys/queue.h>
25 #include <sys/wait.h>
26 #include <sys/uio.h>
27 #include <sys/resource.h>
28 #include <sys/socket.h>
29 #include <sys/stat.h>
30 #include <sys/time.h>
31 #include <sys/types.h>
32 #include <sys/mman.h>
33 #include <sys/un.h>
35 #include <net/if.h>
36 #include <netinet/in.h>
38 #include <errno.h>
39 #include <event.h>
40 #include <fcntl.h>
41 #include <ifaddrs.h>
42 #include <limits.h>
43 #include <netdb.h>
44 #include <poll.h>
45 #include <pwd.h>
46 #include <stddef.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <unistd.h>
52 #include "got_error.h"
53 #include "got_opentemp.h"
54 #include "got_reference.h"
55 #include "got_repository.h"
56 #include "got_privsep.h"
58 #include "gotwebd.h"
59 #include "log.h"
60 #include "tmpl.h"
62 #define SOCKS_BACKLOG 5
63 #define MAXIMUM(a, b) (((a) > (b)) ? (a) : (b))
65 volatile int client_cnt;
67 static struct timeval timeout = { TIMEOUT_DEFAULT, 0 };
69 static void sockets_sighdlr(int, short, void *);
70 static void sockets_shutdown(void);
71 static void sockets_launch(void);
72 static void sockets_accept_paused(int, short, void *);
73 static void sockets_rlimit(int);
75 static void sockets_dispatch_main(int, short, void *);
76 static int sockets_unix_socket_listen(struct gotwebd *, struct socket *);
77 static int sockets_create_socket(struct address *);
78 static int sockets_accept_reserve(int, struct sockaddr *, socklen_t *,
79 int, volatile int *);
81 static struct socket *sockets_conf_new_socket(struct gotwebd *,
82 int, struct address *);
84 int cgi_inflight = 0;
86 void
87 sockets(struct gotwebd *env, int fd)
89 struct event sighup, sigint, sigusr1, sigchld, sigterm;
91 event_init();
93 sockets_rlimit(-1);
95 if (config_init(env) == -1)
96 fatal("failed to initialize configuration");
98 if ((env->iev_parent = malloc(sizeof(*env->iev_parent))) == NULL)
99 fatal("malloc");
100 if (imsgbuf_init(&env->iev_parent->ibuf, fd) == -1)
101 fatal("imsgbuf_init");
102 imsgbuf_allow_fdpass(&env->iev_parent->ibuf);
103 env->iev_parent->handler = sockets_dispatch_main;
104 env->iev_parent->data = env->iev_parent;
105 event_set(&env->iev_parent->ev, fd, EV_READ, sockets_dispatch_main,
106 env->iev_parent);
107 event_add(&env->iev_parent->ev, NULL);
109 signal(SIGPIPE, SIG_IGN);
111 signal_set(&sighup, SIGHUP, sockets_sighdlr, env);
112 signal_add(&sighup, NULL);
113 signal_set(&sigint, SIGINT, sockets_sighdlr, env);
114 signal_add(&sigint, NULL);
115 signal_set(&sigusr1, SIGUSR1, sockets_sighdlr, env);
116 signal_add(&sigusr1, NULL);
117 signal_set(&sigchld, SIGCHLD, sockets_sighdlr, env);
118 signal_add(&sigchld, NULL);
119 signal_set(&sigterm, SIGTERM, sockets_sighdlr, env);
120 signal_add(&sigterm, NULL);
122 #ifndef PROFILE
123 if (pledge("stdio rpath inet recvfd proc exec sendfd unveil",
124 NULL) == -1)
125 fatal("pledge");
126 #endif
128 event_dispatch();
129 sockets_shutdown();
132 void
133 sockets_parse_sockets(struct gotwebd *env)
135 struct address *a;
136 struct socket *new_sock = NULL;
137 int sock_id = 1;
139 TAILQ_FOREACH(a, &env->addresses, entry) {
140 new_sock = sockets_conf_new_socket(env, sock_id, a);
141 if (new_sock) {
142 sock_id++;
143 TAILQ_INSERT_TAIL(&env->sockets,
144 new_sock, entry);
149 static struct socket *
150 sockets_conf_new_socket(struct gotwebd *env, int id, struct address *a)
152 struct socket *sock;
153 struct address *acp;
155 if ((sock = calloc(1, sizeof(*sock))) == NULL)
156 fatalx("%s: calloc", __func__);
158 sock->conf.id = id;
159 sock->fd = -1;
160 sock->conf.af_type = a->ss.ss_family;
162 if (a->ss.ss_family == AF_UNIX) {
163 struct sockaddr_un *sun;
165 sun = (struct sockaddr_un *)&a->ss;
166 if (strlcpy(sock->conf.unix_socket_name, sun->sun_path,
167 sizeof(sock->conf.unix_socket_name)) >=
168 sizeof(sock->conf.unix_socket_name))
169 fatalx("unix socket path too long: %s", sun->sun_path);
172 sock->conf.fcgi_socket_port = a->port;
174 acp = &sock->conf.addr;
176 memcpy(&acp->ss, &a->ss, sizeof(acp->ss));
177 acp->slen = a->slen;
178 acp->ai_family = a->ai_family;
179 acp->ai_socktype = a->ai_socktype;
180 acp->ai_protocol = a->ai_protocol;
181 acp->port = a->port;
182 if (*a->ifname != '\0') {
183 if (strlcpy(acp->ifname, a->ifname,
184 sizeof(acp->ifname)) >= sizeof(acp->ifname)) {
185 fatalx("%s: interface name truncated",
186 __func__);
190 return (sock);
193 static void
194 sockets_launch(void)
196 struct socket *sock;
197 struct server *srv;
198 const struct got_error *error;
200 TAILQ_FOREACH(sock, &gotwebd_env->sockets, entry) {
201 log_info("%s: configuring socket %d (%d)", __func__,
202 sock->conf.id, sock->fd);
204 event_set(&sock->ev, sock->fd, EV_READ | EV_PERSIST,
205 sockets_socket_accept, sock);
207 if (event_add(&sock->ev, NULL))
208 fatalx("event add sock");
210 evtimer_set(&sock->pause, sockets_accept_paused, sock);
212 log_info("%s: running socket listener %d", __func__,
213 sock->conf.id);
216 TAILQ_FOREACH(srv, &gotwebd_env->servers, entry) {
217 if (unveil(srv->repos_path, "r") == -1)
218 fatal("unveil %s", srv->repos_path);
221 error = got_privsep_unveil_exec_helpers();
222 if (error)
223 fatal("%s", error->msg);
225 if (unveil(NULL, NULL) == -1)
226 fatal("unveil");
229 void
230 sockets_purge(struct gotwebd *env)
232 struct socket *sock, *tsock;
234 /* shutdown and remove sockets */
235 TAILQ_FOREACH_SAFE(sock, &env->sockets, entry, tsock) {
236 if (event_initialized(&sock->ev))
237 event_del(&sock->ev);
238 if (evtimer_initialized(&sock->evt))
239 evtimer_del(&sock->evt);
240 if (evtimer_initialized(&sock->pause))
241 evtimer_del(&sock->pause);
242 if (sock->fd != -1)
243 close(sock->fd);
244 TAILQ_REMOVE(&env->sockets, sock, entry);
245 free(sock);
249 static void
250 sockets_dispatch_main(int fd, short event, void *arg)
252 struct imsgev *iev = arg;
253 struct imsgbuf *ibuf;
254 struct imsg imsg;
255 struct gotwebd *env = gotwebd_env;
256 ssize_t n;
257 int shut = 0;
259 ibuf = &iev->ibuf;
261 if (event & EV_READ) {
262 if ((n = imsgbuf_read(ibuf)) == -1)
263 fatal("imsgbuf_read error");
264 if (n == 0) /* Connection closed */
265 shut = 1;
267 if (event & EV_WRITE) {
268 if (imsgbuf_write(ibuf) == -1)
269 fatal("imsgbuf_write");
272 for (;;) {
273 if ((n = imsg_get(ibuf, &imsg)) == -1)
274 fatal("imsg_get");
275 if (n == 0) /* No more messages. */
276 break;
278 switch (imsg.hdr.type) {
279 case IMSG_CFG_SRV:
280 config_getserver(env, &imsg);
281 break;
282 case IMSG_CFG_SOCK:
283 config_getsock(env, &imsg);
284 break;
285 case IMSG_CFG_FD:
286 config_getfd(env, &imsg);
287 break;
288 case IMSG_CFG_DONE:
289 config_getcfg(env, &imsg);
290 break;
291 case IMSG_CTL_START:
292 sockets_launch();
293 break;
294 default:
295 fatalx("%s: unknown imsg type %d", __func__,
296 imsg.hdr.type);
299 imsg_free(&imsg);
302 if (!shut)
303 imsg_event_add(iev);
304 else {
305 /* This pipe is dead. Remove its event handler */
306 event_del(&iev->ev);
307 event_loopexit(NULL);
311 static void
312 sockets_sighdlr(int sig, short event, void *arg)
314 switch (sig) {
315 case SIGHUP:
316 log_info("%s: ignoring SIGHUP", __func__);
317 break;
318 case SIGPIPE:
319 log_info("%s: ignoring SIGPIPE", __func__);
320 break;
321 case SIGUSR1:
322 log_info("%s: ignoring SIGUSR1", __func__);
323 break;
324 case SIGCHLD:
325 break;
326 case SIGINT:
327 case SIGTERM:
328 sockets_shutdown();
329 break;
330 default:
331 log_info("SIGNAL: %d", sig);
332 fatalx("unexpected signal");
336 static void
337 sockets_shutdown(void)
339 struct server *srv, *tsrv;
341 sockets_purge(gotwebd_env);
343 /* clean servers */
344 TAILQ_FOREACH_SAFE(srv, &gotwebd_env->servers, entry, tsrv)
345 free(srv);
347 free(gotwebd_env);
349 exit(0);
353 sockets_privinit(struct gotwebd *env, struct socket *sock)
355 if (sock->conf.af_type == AF_UNIX) {
356 log_info("%s: initializing unix socket %s", __func__,
357 sock->conf.unix_socket_name);
358 sock->fd = sockets_unix_socket_listen(env, sock);
359 if (sock->fd == -1)
360 return -1;
363 if (sock->conf.af_type == AF_INET || sock->conf.af_type == AF_INET6) {
364 log_info("%s: initializing %s FCGI socket on port %d",
365 __func__, sock->conf.af_type == AF_INET ? "inet" : "inet6",
366 sock->conf.fcgi_socket_port);
367 sock->fd = sockets_create_socket(&sock->conf.addr);
368 if (sock->fd == -1)
369 return -1;
372 return 0;
375 static int
376 sockets_unix_socket_listen(struct gotwebd *env, struct socket *sock)
378 int u_fd = -1;
379 mode_t old_umask, mode;
380 int flags = SOCK_STREAM | SOCK_NONBLOCK;
382 #ifdef SOCK_CLOEXEC
383 flags |= SOCK_CLOEXEC;
384 #endif
386 u_fd = socket(AF_UNIX, flags, 0);
387 if (u_fd == -1) {
388 log_warn("%s: socket", __func__);
389 return -1;
392 if (unlink(sock->conf.unix_socket_name) == -1) {
393 if (errno != ENOENT) {
394 log_warn("%s: unlink %s", __func__,
395 sock->conf.unix_socket_name);
396 close(u_fd);
397 return -1;
401 old_umask = umask(S_IXUSR|S_IXGRP|S_IWOTH|S_IROTH|S_IXOTH);
402 mode = S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP;
404 if (bind(u_fd, (struct sockaddr *)&sock->conf.addr.ss,
405 sock->conf.addr.slen) == -1) {
406 log_warn("%s: bind: %s", __func__, sock->conf.unix_socket_name);
407 close(u_fd);
408 (void)umask(old_umask);
409 return -1;
412 (void)umask(old_umask);
414 if (chmod(sock->conf.unix_socket_name, mode) == -1) {
415 log_warn("%s: chmod", __func__);
416 close(u_fd);
417 (void)unlink(sock->conf.unix_socket_name);
418 return -1;
421 if (chown(sock->conf.unix_socket_name, env->pw->pw_uid,
422 env->pw->pw_gid) == -1) {
423 log_warn("%s: chown", __func__);
424 close(u_fd);
425 (void)unlink(sock->conf.unix_socket_name);
426 return -1;
429 if (listen(u_fd, SOCKS_BACKLOG) == -1) {
430 log_warn("%s: listen", __func__);
431 return -1;
434 return u_fd;
437 static int
438 sockets_create_socket(struct address *a)
440 int fd = -1, o_val = 1, flags;
442 fd = socket(a->ai_family, a->ai_socktype, a->ai_protocol);
443 if (fd == -1)
444 return -1;
446 log_debug("%s: opened socket (%d) for %s", __func__,
447 fd, a->ifname);
449 if (setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &o_val,
450 sizeof(int)) == -1) {
451 log_warn("%s: setsockopt error", __func__);
452 close(fd);
453 return -1;
456 /* non-blocking */
457 flags = fcntl(fd, F_GETFL);
458 flags |= O_NONBLOCK;
459 if (fcntl(fd, F_SETFL, flags) == -1) {
460 log_warn("%s: could not enable non-blocking I/O", __func__);
461 close(fd);
462 return -1;
465 if (bind(fd, (struct sockaddr *)&a->ss, a->slen) == -1) {
466 close(fd);
467 log_warn("%s: can't bind to port %d", __func__, a->port);
468 return -1;
471 if (listen(fd, SOMAXCONN) == -1) {
472 log_warn("%s, unable to listen on socket", __func__);
473 close(fd);
474 return -1;
477 return (fd);
480 static int
481 sockets_accept_reserve(int sockfd, struct sockaddr *addr, socklen_t *addrlen,
482 int reserve, volatile int *counter)
484 int ret;
486 if (getdtablecount() + reserve +
487 ((*counter + 1) * FD_NEEDED) >= getdtablesize()) {
488 log_warnx("inflight fds exceeded");
489 errno = EMFILE;
490 return -1;
492 /* TA: This needs fixing upstream. */
493 #ifdef __APPLE__
494 ret = accept(sockfd, addr, addrlen);
495 #else
496 ret = accept4(sockfd, addr, addrlen, SOCK_NONBLOCK | SOCK_CLOEXEC);
497 #endif
499 if (ret > -1) {
500 (*counter)++;
501 log_debug("inflight incremented, now %d", *counter);
504 return ret;
507 static void
508 sockets_accept_paused(int fd, short events, void *arg)
510 struct socket *sock = (struct socket *)arg;
512 event_add(&sock->ev, NULL);
515 void
516 sockets_socket_accept(int fd, short event, void *arg)
518 struct socket *sock = (struct socket *)arg;
519 struct sockaddr_storage ss;
520 struct timeval backoff;
521 struct request *c = NULL;
522 socklen_t len;
523 int s;
525 backoff.tv_sec = 1;
526 backoff.tv_usec = 0;
528 event_add(&sock->ev, NULL);
529 if (event & EV_TIMEOUT)
530 return;
532 len = sizeof(ss);
534 s = sockets_accept_reserve(fd, (struct sockaddr *)&ss, &len,
535 FD_RESERVE, &cgi_inflight);
537 if (s == -1) {
538 switch (errno) {
539 case EINTR:
540 case EWOULDBLOCK:
541 case ECONNABORTED:
542 return;
543 case EMFILE:
544 case ENFILE:
545 event_del(&sock->ev);
546 evtimer_add(&sock->pause, &backoff);
547 return;
548 default:
549 log_warn("%s: accept", __func__);
553 if (client_cnt > GOTWEBD_MAXCLIENTS)
554 goto err;
556 c = calloc(1, sizeof(struct request));
557 if (c == NULL) {
558 log_warn("%s", __func__);
559 close(s);
560 cgi_inflight--;
561 return;
564 c->tp = template(c, &fcgi_write, c->outbuf, sizeof(c->outbuf));
565 if (c->tp == NULL) {
566 log_warn("%s", __func__);
567 close(s);
568 cgi_inflight--;
569 free(c);
570 return;
573 c->fd = s;
574 c->sock = sock;
575 memcpy(c->priv_fd, gotwebd_env->priv_fd, sizeof(c->priv_fd));
576 c->buf_pos = 0;
577 c->buf_len = 0;
578 c->request_started = 0;
579 c->sock->client_status = CLIENT_CONNECT;
581 event_set(&c->ev, s, EV_READ|EV_PERSIST, fcgi_request, c);
582 event_add(&c->ev, NULL);
584 evtimer_set(&c->tmo, fcgi_timeout, c);
585 evtimer_add(&c->tmo, &timeout);
587 client_cnt++;
589 return;
590 err:
591 cgi_inflight--;
592 close(s);
593 if (c != NULL)
594 free(c);
597 static void
598 sockets_rlimit(int maxfd)
600 struct rlimit rl;
602 if (getrlimit(RLIMIT_NOFILE, &rl) == -1)
603 fatal("%s: failed to get resource limit", __func__);
604 log_info("%s: max open files %llu", __func__,
605 (unsigned long long)rl.rlim_max);
608 * Allow the maximum number of open file descriptors for this
609 * login class (which should be the class "daemon" by default).
611 if (maxfd == -1)
612 rl.rlim_cur = rl.rlim_max;
613 else
614 rl.rlim_cur = MAXIMUM(rl.rlim_max, (rlim_t)maxfd);
615 if (setrlimit(RLIMIT_NOFILE, &rl) == -1)
616 fatal("%s: failed to set resource limit", __func__);