do not forget to free an imsgbuf when gotwebd socket process exits
[got-portable.git] / gotwebd / sockets.c
blobd1cb213b88599f9479aa4b9e553a9684e28e5985
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 ((env->iev_parent = malloc(sizeof(*env->iev_parent))) == NULL)
96 fatal("malloc");
97 if (imsgbuf_init(&env->iev_parent->ibuf, fd) == -1)
98 fatal("imsgbuf_init");
99 imsgbuf_allow_fdpass(&env->iev_parent->ibuf);
100 env->iev_parent->handler = sockets_dispatch_main;
101 env->iev_parent->data = env->iev_parent;
102 event_set(&env->iev_parent->ev, fd, EV_READ, sockets_dispatch_main,
103 env->iev_parent);
104 event_add(&env->iev_parent->ev, NULL);
106 signal(SIGPIPE, SIG_IGN);
108 signal_set(&sighup, SIGHUP, sockets_sighdlr, env);
109 signal_add(&sighup, NULL);
110 signal_set(&sigint, SIGINT, sockets_sighdlr, env);
111 signal_add(&sigint, NULL);
112 signal_set(&sigusr1, SIGUSR1, sockets_sighdlr, env);
113 signal_add(&sigusr1, NULL);
114 signal_set(&sigchld, SIGCHLD, sockets_sighdlr, env);
115 signal_add(&sigchld, NULL);
116 signal_set(&sigterm, SIGTERM, sockets_sighdlr, env);
117 signal_add(&sigterm, NULL);
119 #ifndef PROFILE
120 if (pledge("stdio rpath inet recvfd proc exec sendfd unveil",
121 NULL) == -1)
122 fatal("pledge");
123 #endif
125 event_dispatch();
126 sockets_shutdown();
129 void
130 sockets_parse_sockets(struct gotwebd *env)
132 struct address *a;
133 struct socket *new_sock = NULL;
134 int sock_id = 1;
136 TAILQ_FOREACH(a, &env->addresses, entry) {
137 new_sock = sockets_conf_new_socket(env, sock_id, a);
138 if (new_sock) {
139 sock_id++;
140 TAILQ_INSERT_TAIL(&env->sockets,
141 new_sock, entry);
146 static struct socket *
147 sockets_conf_new_socket(struct gotwebd *env, int id, struct address *a)
149 struct socket *sock;
150 struct address *acp;
152 if ((sock = calloc(1, sizeof(*sock))) == NULL)
153 fatalx("%s: calloc", __func__);
155 sock->conf.id = id;
156 sock->fd = -1;
157 sock->conf.af_type = a->ss.ss_family;
159 if (a->ss.ss_family == AF_UNIX) {
160 struct sockaddr_un *sun;
162 sun = (struct sockaddr_un *)&a->ss;
163 if (strlcpy(sock->conf.unix_socket_name, sun->sun_path,
164 sizeof(sock->conf.unix_socket_name)) >=
165 sizeof(sock->conf.unix_socket_name))
166 fatalx("unix socket path too long: %s", sun->sun_path);
169 sock->conf.fcgi_socket_port = a->port;
171 acp = &sock->conf.addr;
173 memcpy(&acp->ss, &a->ss, sizeof(acp->ss));
174 acp->slen = a->slen;
175 acp->ai_family = a->ai_family;
176 acp->ai_socktype = a->ai_socktype;
177 acp->ai_protocol = a->ai_protocol;
178 acp->port = a->port;
179 if (*a->ifname != '\0') {
180 if (strlcpy(acp->ifname, a->ifname,
181 sizeof(acp->ifname)) >= sizeof(acp->ifname)) {
182 fatalx("%s: interface name truncated",
183 __func__);
187 return (sock);
190 static void
191 sockets_launch(void)
193 struct socket *sock;
194 struct server *srv;
195 const struct got_error *error;
197 TAILQ_FOREACH(sock, &gotwebd_env->sockets, entry) {
198 log_info("%s: configuring socket %d (%d)", __func__,
199 sock->conf.id, sock->fd);
201 event_set(&sock->ev, sock->fd, EV_READ | EV_PERSIST,
202 sockets_socket_accept, sock);
204 if (event_add(&sock->ev, NULL))
205 fatalx("event add sock");
207 evtimer_set(&sock->pause, sockets_accept_paused, sock);
209 log_info("%s: running socket listener %d", __func__,
210 sock->conf.id);
213 TAILQ_FOREACH(srv, &gotwebd_env->servers, entry) {
214 if (unveil(srv->repos_path, "r") == -1)
215 fatal("unveil %s", srv->repos_path);
218 error = got_privsep_unveil_exec_helpers();
219 if (error)
220 fatal("%s", error->msg);
222 if (unveil(NULL, NULL) == -1)
223 fatal("unveil");
226 void
227 sockets_purge(struct gotwebd *env)
229 struct socket *sock, *tsock;
231 /* shutdown and remove sockets */
232 TAILQ_FOREACH_SAFE(sock, &env->sockets, entry, tsock) {
233 if (event_initialized(&sock->ev))
234 event_del(&sock->ev);
235 if (evtimer_initialized(&sock->evt))
236 evtimer_del(&sock->evt);
237 if (evtimer_initialized(&sock->pause))
238 evtimer_del(&sock->pause);
239 if (sock->fd != -1)
240 close(sock->fd);
241 TAILQ_REMOVE(&env->sockets, sock, entry);
242 free(sock);
246 static void
247 sockets_dispatch_main(int fd, short event, void *arg)
249 struct imsgev *iev = arg;
250 struct imsgbuf *ibuf;
251 struct imsg imsg;
252 struct gotwebd *env = gotwebd_env;
253 ssize_t n;
254 int shut = 0;
256 ibuf = &iev->ibuf;
258 if (event & EV_READ) {
259 if ((n = imsgbuf_read(ibuf)) == -1)
260 fatal("imsgbuf_read error");
261 if (n == 0) /* Connection closed */
262 shut = 1;
264 if (event & EV_WRITE) {
265 if (imsgbuf_write(ibuf) == -1)
266 fatal("imsgbuf_write");
269 for (;;) {
270 if ((n = imsg_get(ibuf, &imsg)) == -1)
271 fatal("imsg_get");
272 if (n == 0) /* No more messages. */
273 break;
275 switch (imsg.hdr.type) {
276 case IMSG_CFG_SRV:
277 config_getserver(env, &imsg);
278 break;
279 case IMSG_CFG_SOCK:
280 config_getsock(env, &imsg);
281 break;
282 case IMSG_CFG_FD:
283 config_getfd(env, &imsg);
284 break;
285 case IMSG_CFG_DONE:
286 config_getcfg(env, &imsg);
287 break;
288 case IMSG_CTL_START:
289 sockets_launch();
290 break;
291 default:
292 fatalx("%s: unknown imsg type %d", __func__,
293 imsg.hdr.type);
296 imsg_free(&imsg);
299 if (!shut)
300 imsg_event_add(iev);
301 else {
302 /* This pipe is dead. Remove its event handler */
303 event_del(&iev->ev);
304 event_loopexit(NULL);
308 static void
309 sockets_sighdlr(int sig, short event, void *arg)
311 switch (sig) {
312 case SIGHUP:
313 log_info("%s: ignoring SIGHUP", __func__);
314 break;
315 case SIGPIPE:
316 log_info("%s: ignoring SIGPIPE", __func__);
317 break;
318 case SIGUSR1:
319 log_info("%s: ignoring SIGUSR1", __func__);
320 break;
321 case SIGCHLD:
322 break;
323 case SIGINT:
324 case SIGTERM:
325 sockets_shutdown();
326 break;
327 default:
328 log_info("SIGNAL: %d", sig);
329 fatalx("unexpected signal");
333 static void
334 sockets_shutdown(void)
336 sockets_purge(gotwebd_env);
338 /* clean servers */
339 while (!TAILQ_EMPTY(&gotwebd_env->servers)) {
340 struct server *srv;
342 srv = TAILQ_FIRST(&gotwebd_env->servers);
343 TAILQ_REMOVE(&gotwebd_env->servers, srv, entry);
344 free(srv);
347 while (!TAILQ_EMPTY(&gotwebd_env->addresses)) {
348 struct address *h;
350 h = TAILQ_FIRST(&gotwebd_env->addresses);
351 TAILQ_REMOVE(&gotwebd_env->addresses, h, entry);
352 free(h);
355 imsgbuf_clear(&gotwebd_env->iev_parent->ibuf);
356 free(gotwebd_env->iev_parent);
357 free(gotwebd_env);
359 exit(0);
363 sockets_privinit(struct gotwebd *env, struct socket *sock)
365 if (sock->conf.af_type == AF_UNIX) {
366 log_info("%s: initializing unix socket %s", __func__,
367 sock->conf.unix_socket_name);
368 sock->fd = sockets_unix_socket_listen(env, sock);
369 if (sock->fd == -1)
370 return -1;
373 if (sock->conf.af_type == AF_INET || sock->conf.af_type == AF_INET6) {
374 log_info("%s: initializing %s FCGI socket on port %d",
375 __func__, sock->conf.af_type == AF_INET ? "inet" : "inet6",
376 sock->conf.fcgi_socket_port);
377 sock->fd = sockets_create_socket(&sock->conf.addr);
378 if (sock->fd == -1)
379 return -1;
382 return 0;
385 static int
386 sockets_unix_socket_listen(struct gotwebd *env, struct socket *sock)
388 int u_fd = -1;
389 mode_t old_umask, mode;
390 int flags = SOCK_STREAM | SOCK_NONBLOCK;
392 #ifdef SOCK_CLOEXEC
393 flags |= SOCK_CLOEXEC;
394 #endif
396 u_fd = socket(AF_UNIX, flags, 0);
397 if (u_fd == -1) {
398 log_warn("%s: socket", __func__);
399 return -1;
402 if (unlink(sock->conf.unix_socket_name) == -1) {
403 if (errno != ENOENT) {
404 log_warn("%s: unlink %s", __func__,
405 sock->conf.unix_socket_name);
406 close(u_fd);
407 return -1;
411 old_umask = umask(S_IXUSR|S_IXGRP|S_IWOTH|S_IROTH|S_IXOTH);
412 mode = S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP;
414 if (bind(u_fd, (struct sockaddr *)&sock->conf.addr.ss,
415 sock->conf.addr.slen) == -1) {
416 log_warn("%s: bind: %s", __func__, sock->conf.unix_socket_name);
417 close(u_fd);
418 (void)umask(old_umask);
419 return -1;
422 (void)umask(old_umask);
424 if (chmod(sock->conf.unix_socket_name, mode) == -1) {
425 log_warn("%s: chmod", __func__);
426 close(u_fd);
427 (void)unlink(sock->conf.unix_socket_name);
428 return -1;
431 if (chown(sock->conf.unix_socket_name, env->pw->pw_uid,
432 env->pw->pw_gid) == -1) {
433 log_warn("%s: chown", __func__);
434 close(u_fd);
435 (void)unlink(sock->conf.unix_socket_name);
436 return -1;
439 if (listen(u_fd, SOCKS_BACKLOG) == -1) {
440 log_warn("%s: listen", __func__);
441 return -1;
444 return u_fd;
447 static int
448 sockets_create_socket(struct address *a)
450 int fd = -1, o_val = 1, flags;
452 fd = socket(a->ai_family, a->ai_socktype, a->ai_protocol);
453 if (fd == -1)
454 return -1;
456 log_debug("%s: opened socket (%d) for %s", __func__,
457 fd, a->ifname);
459 if (setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &o_val,
460 sizeof(int)) == -1) {
461 log_warn("%s: setsockopt error", __func__);
462 close(fd);
463 return -1;
466 /* non-blocking */
467 flags = fcntl(fd, F_GETFL);
468 flags |= O_NONBLOCK;
469 if (fcntl(fd, F_SETFL, flags) == -1) {
470 log_warn("%s: could not enable non-blocking I/O", __func__);
471 close(fd);
472 return -1;
475 if (bind(fd, (struct sockaddr *)&a->ss, a->slen) == -1) {
476 close(fd);
477 log_warn("%s: can't bind to port %d", __func__, a->port);
478 return -1;
481 if (listen(fd, SOMAXCONN) == -1) {
482 log_warn("%s, unable to listen on socket", __func__);
483 close(fd);
484 return -1;
487 return (fd);
490 static int
491 sockets_accept_reserve(int sockfd, struct sockaddr *addr, socklen_t *addrlen,
492 int reserve, volatile int *counter)
494 int ret;
496 if (getdtablecount() + reserve +
497 ((*counter + 1) * FD_NEEDED) >= getdtablesize()) {
498 log_warnx("inflight fds exceeded");
499 errno = EMFILE;
500 return -1;
502 /* TA: This needs fixing upstream. */
503 #ifdef __APPLE__
504 ret = accept(sockfd, addr, addrlen);
505 #else
506 ret = accept4(sockfd, addr, addrlen, SOCK_NONBLOCK | SOCK_CLOEXEC);
507 #endif
509 if (ret > -1) {
510 (*counter)++;
511 log_debug("inflight incremented, now %d", *counter);
514 return ret;
517 static void
518 sockets_accept_paused(int fd, short events, void *arg)
520 struct socket *sock = (struct socket *)arg;
522 event_add(&sock->ev, NULL);
525 void
526 sockets_socket_accept(int fd, short event, void *arg)
528 struct socket *sock = (struct socket *)arg;
529 struct sockaddr_storage ss;
530 struct timeval backoff;
531 struct request *c = NULL;
532 socklen_t len;
533 int s;
535 backoff.tv_sec = 1;
536 backoff.tv_usec = 0;
538 event_add(&sock->ev, NULL);
539 if (event & EV_TIMEOUT)
540 return;
542 len = sizeof(ss);
544 s = sockets_accept_reserve(fd, (struct sockaddr *)&ss, &len,
545 FD_RESERVE, &cgi_inflight);
547 if (s == -1) {
548 switch (errno) {
549 case EINTR:
550 case EWOULDBLOCK:
551 case ECONNABORTED:
552 return;
553 case EMFILE:
554 case ENFILE:
555 event_del(&sock->ev);
556 evtimer_add(&sock->pause, &backoff);
557 return;
558 default:
559 log_warn("%s: accept", __func__);
563 if (client_cnt > GOTWEBD_MAXCLIENTS)
564 goto err;
566 c = calloc(1, sizeof(struct request));
567 if (c == NULL) {
568 log_warn("%s", __func__);
569 close(s);
570 cgi_inflight--;
571 return;
574 c->tp = template(c, &fcgi_write, c->outbuf, sizeof(c->outbuf));
575 if (c->tp == NULL) {
576 log_warn("%s", __func__);
577 close(s);
578 cgi_inflight--;
579 free(c);
580 return;
583 c->fd = s;
584 c->sock = sock;
585 memcpy(c->priv_fd, gotwebd_env->priv_fd, sizeof(c->priv_fd));
586 c->buf_pos = 0;
587 c->buf_len = 0;
588 c->request_started = 0;
589 c->sock->client_status = CLIENT_CONNECT;
591 event_set(&c->ev, s, EV_READ|EV_PERSIST, fcgi_request, c);
592 event_add(&c->ev, NULL);
594 evtimer_set(&c->tmo, fcgi_timeout, c);
595 evtimer_add(&c->tmo, &timeout);
597 client_cnt++;
599 return;
600 err:
601 cgi_inflight--;
602 close(s);
603 if (c != NULL)
604 free(c);
607 static void
608 sockets_rlimit(int maxfd)
610 struct rlimit rl;
612 if (getrlimit(RLIMIT_NOFILE, &rl) == -1)
613 fatal("%s: failed to get resource limit", __func__);
614 log_info("%s: max open files %llu", __func__,
615 (unsigned long long)rl.rlim_max);
618 * Allow the maximum number of open file descriptors for this
619 * login class (which should be the class "daemon" by default).
621 if (maxfd == -1)
622 rl.rlim_cur = rl.rlim_max;
623 else
624 rl.rlim_cur = MAXIMUM(rl.rlim_max, (rlim_t)maxfd);
625 if (setrlimit(RLIMIT_NOFILE, &rl) == -1)
626 fatal("%s: failed to set resource limit", __func__);