Blob


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>
6 *
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.
10 *
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.
18 */
20 #include <sys/param.h>
21 #include <sys/ioctl.h>
22 #include <sys/queue.h>
23 #include <sys/wait.h>
24 #include <sys/uio.h>
25 #include <sys/resource.h>
26 #include <sys/socket.h>
27 #include <sys/stat.h>
28 #include <sys/time.h>
29 #include <sys/types.h>
30 #include <sys/mman.h>
31 #include <sys/un.h>
33 #include <net/if.h>
34 #include <netinet/in.h>
36 #include <errno.h>
37 #include <event.h>
38 #include <fcntl.h>
39 #include <ifaddrs.h>
40 #include <imsg.h>
41 #include <limits.h>
42 #include <netdb.h>
43 #include <poll.h>
44 #include <pwd.h>
45 #include <stddef.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <unistd.h>
50 #include <util.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 "tmpl.h"
61 #define SOCKS_BACKLOG 5
62 #define MAXIMUM(a, b) (((a) > (b)) ? (a) : (b))
64 volatile int client_cnt;
66 static struct timeval timeout = { TIMEOUT_DEFAULT, 0 };
68 static void sockets_sighdlr(int, short, void *);
69 static void sockets_shutdown(void);
70 static void sockets_launch(void);
71 static void sockets_purge(struct gotwebd *);
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)
88 {
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 imsg_init(&env->iev_parent->ibuf, fd);
101 env->iev_parent->handler = sockets_dispatch_main;
102 env->iev_parent->data = env->iev_parent;
103 event_set(&env->iev_parent->ev, fd, EV_READ, sockets_dispatch_main,
104 env->iev_parent);
105 event_add(&env->iev_parent->ev, NULL);
107 signal(SIGPIPE, SIG_IGN);
109 signal_set(&sighup, SIGHUP, sockets_sighdlr, env);
110 signal_add(&sighup, NULL);
111 signal_set(&sigint, SIGINT, sockets_sighdlr, env);
112 signal_add(&sigint, NULL);
113 signal_set(&sigusr1, SIGUSR1, sockets_sighdlr, env);
114 signal_add(&sigusr1, NULL);
115 signal_set(&sigchld, SIGCHLD, sockets_sighdlr, env);
116 signal_add(&sigchld, NULL);
117 signal_set(&sigterm, SIGTERM, sockets_sighdlr, env);
118 signal_add(&sigterm, NULL);
120 #ifndef PROFILE
121 if (pledge("stdio rpath inet recvfd proc exec sendfd unveil",
122 NULL) == -1)
123 fatal("pledge");
124 #endif
126 event_dispatch();
127 sockets_shutdown();
130 void
131 sockets_parse_sockets(struct gotwebd *env)
133 struct address *a;
134 struct socket *new_sock = NULL;
135 int sock_id = 1;
137 TAILQ_FOREACH(a, &env->addresses, entry) {
138 new_sock = sockets_conf_new_socket(env, sock_id, a);
139 if (new_sock) {
140 sock_id++;
141 TAILQ_INSERT_TAIL(&env->sockets,
142 new_sock, entry);
147 static struct socket *
148 sockets_conf_new_socket(struct gotwebd *env, int id, struct address *a)
150 struct socket *sock;
151 struct address *acp;
153 if ((sock = calloc(1, sizeof(*sock))) == NULL)
154 fatalx("%s: calloc", __func__);
156 sock->conf.id = id;
157 sock->fd = -1;
158 sock->conf.af_type = a->ss.ss_family;
160 if (a->ss.ss_family == AF_UNIX) {
161 struct sockaddr_un *sun;
163 sun = (struct sockaddr_un *)&a->ss;
164 if (strlcpy(sock->conf.unix_socket_name, sun->sun_path,
165 sizeof(sock->conf.unix_socket_name)) >=
166 sizeof(sock->conf.unix_socket_name))
167 fatalx("unix socket path too long: %s", sun->sun_path);
170 sock->conf.fcgi_socket_port = a->port;
172 acp = &sock->conf.addr;
174 memcpy(&acp->ss, &a->ss, sizeof(acp->ss));
175 acp->slen = a->slen;
176 acp->ai_family = a->ai_family;
177 acp->ai_socktype = a->ai_socktype;
178 acp->ai_protocol = a->ai_protocol;
179 acp->port = a->port;
180 if (*a->ifname != '\0') {
181 if (strlcpy(acp->ifname, a->ifname,
182 sizeof(acp->ifname)) >= sizeof(acp->ifname)) {
183 fatalx("%s: interface name truncated",
184 __func__);
188 return (sock);
191 static void
192 sockets_launch(void)
194 struct socket *sock;
195 struct server *srv;
196 const struct got_error *error;
198 TAILQ_FOREACH(sock, &gotwebd_env->sockets, entry) {
199 log_debug("%s: configuring socket %d (%d)", __func__,
200 sock->conf.id, sock->fd);
202 event_set(&sock->ev, sock->fd, EV_READ | EV_PERSIST,
203 sockets_socket_accept, sock);
205 if (event_add(&sock->ev, NULL))
206 fatalx("event add sock");
208 evtimer_set(&sock->pause, sockets_accept_paused, sock);
210 log_debug("%s: running socket listener %d", __func__,
211 sock->conf.id);
214 TAILQ_FOREACH(srv, &gotwebd_env->servers, entry) {
215 if (unveil(srv->repos_path, "r") == -1)
216 fatal("unveil %s", srv->repos_path);
219 error = got_privsep_unveil_exec_helpers();
220 if (error)
221 fatal("%s", error->msg);
223 if (unveil(NULL, NULL) == -1)
224 fatal("unveil");
227 static void
228 sockets_purge(struct gotwebd *env)
230 struct socket *sock, *tsock;
232 /* shutdown and remove sockets */
233 TAILQ_FOREACH_SAFE(sock, &env->sockets, entry, tsock) {
234 if (event_initialized(&sock->ev))
235 event_del(&sock->ev);
236 if (evtimer_initialized(&sock->evt))
237 evtimer_del(&sock->evt);
238 if (evtimer_initialized(&sock->pause))
239 evtimer_del(&sock->pause);
240 if (sock->fd != -1)
241 close(sock->fd);
242 TAILQ_REMOVE(&env->sockets, sock, entry);
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 = imsg_read(ibuf)) == -1 && errno != EAGAIN)
260 fatal("imsg_read error");
261 if (n == 0) /* Connection closed */
262 shut = 1;
264 if (event & EV_WRITE) {
265 if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
266 fatal("msgbuf_write");
267 if (n == 0) /* Connection closed */
268 shut = 1;
271 for (;;) {
272 if ((n = imsg_get(ibuf, &imsg)) == -1)
273 fatal("imsg_get");
274 if (n == 0) /* No more messages. */
275 break;
277 switch (imsg.hdr.type) {
278 case IMSG_CFG_SRV:
279 config_getserver(env, &imsg);
280 break;
281 case IMSG_CFG_SOCK:
282 config_getsock(env, &imsg);
283 break;
284 case IMSG_CFG_FD:
285 config_getfd(env, &imsg);
286 break;
287 case IMSG_CFG_DONE:
288 config_getcfg(env, &imsg);
289 break;
290 case IMSG_CTL_START:
291 sockets_launch();
292 break;
293 default:
294 fatalx("%s: unknown imsg type %d", __func__,
295 imsg.hdr.type);
298 imsg_free(&imsg);
301 if (!shut)
302 imsg_event_add(iev);
303 else {
304 /* This pipe is dead. Remove its event handler */
305 event_del(&iev->ev);
306 event_loopexit(NULL);
310 static void
311 sockets_sighdlr(int sig, short event, void *arg)
313 switch (sig) {
314 case SIGHUP:
315 log_info("%s: ignoring SIGHUP", __func__);
316 break;
317 case SIGPIPE:
318 log_info("%s: ignoring SIGPIPE", __func__);
319 break;
320 case SIGUSR1:
321 log_info("%s: ignoring SIGUSR1", __func__);
322 break;
323 case SIGCHLD:
324 break;
325 case SIGINT:
326 case SIGTERM:
327 sockets_shutdown();
328 break;
329 default:
330 log_info("SIGNAL: %d", sig);
331 fatalx("unexpected signal");
335 static void
336 sockets_shutdown(void)
338 struct server *srv, *tsrv;
339 struct socket *sock, *tsock;
341 sockets_purge(gotwebd_env);
343 /* clean sockets */
344 TAILQ_FOREACH_SAFE(sock, &gotwebd_env->sockets, entry, tsock) {
345 TAILQ_REMOVE(&gotwebd_env->sockets, sock, entry);
346 close(sock->fd);
347 free(sock);
350 /* clean servers */
351 TAILQ_FOREACH_SAFE(srv, &gotwebd_env->servers, entry, tsrv)
352 free(srv);
354 free(gotwebd_env);
356 exit(0);
359 int
360 sockets_privinit(struct gotwebd *env, struct socket *sock)
362 if (sock->conf.af_type == AF_UNIX) {
363 log_debug("%s: initializing unix socket %s", __func__,
364 sock->conf.unix_socket_name);
365 sock->fd = sockets_unix_socket_listen(env, sock);
366 if (sock->fd == -1) {
367 log_warnx("%s: create unix socket failed", __func__);
368 return -1;
372 if (sock->conf.af_type == AF_INET || sock->conf.af_type == AF_INET6) {
373 log_debug("%s: initializing %s FCGI socket on port %d",
374 __func__, sock->conf.af_type == AF_INET ? "inet" : "inet6",
375 sock->conf.fcgi_socket_port);
376 sock->fd = sockets_create_socket(&sock->conf.addr);
377 if (sock->fd == -1) {
378 log_warnx("%s: create FCGI socket failed", __func__);
379 return -1;
383 return 0;
386 static int
387 sockets_unix_socket_listen(struct gotwebd *env, struct socket *sock)
389 int u_fd = -1;
390 mode_t old_umask, mode;
392 u_fd = socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK| SOCK_CLOEXEC, 0);
393 if (u_fd == -1) {
394 log_warn("%s: socket", __func__);
395 return -1;
398 if (unlink(sock->conf.unix_socket_name) == -1) {
399 if (errno != ENOENT) {
400 log_warn("%s: unlink %s", __func__,
401 sock->conf.unix_socket_name);
402 close(u_fd);
403 return -1;
407 old_umask = umask(S_IXUSR|S_IXGRP|S_IWOTH|S_IROTH|S_IXOTH);
408 mode = S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP;
410 if (bind(u_fd, (struct sockaddr *)&sock->conf.addr.ss,
411 sock->conf.addr.slen) == -1) {
412 log_warn("%s: bind: %s", __func__, sock->conf.unix_socket_name);
413 close(u_fd);
414 (void)umask(old_umask);
415 return -1;
418 (void)umask(old_umask);
420 if (chmod(sock->conf.unix_socket_name, mode) == -1) {
421 log_warn("%s: chmod", __func__);
422 close(u_fd);
423 (void)unlink(sock->conf.unix_socket_name);
424 return -1;
427 if (chown(sock->conf.unix_socket_name, env->pw->pw_uid,
428 env->pw->pw_gid) == -1) {
429 log_warn("%s: chown", __func__);
430 close(u_fd);
431 (void)unlink(sock->conf.unix_socket_name);
432 return -1;
435 if (listen(u_fd, SOCKS_BACKLOG) == -1) {
436 log_warn("%s: listen", __func__);
437 return -1;
440 return u_fd;
443 static int
444 sockets_create_socket(struct address *a)
446 int fd = -1, o_val = 1, flags;
448 fd = socket(a->ai_family, a->ai_socktype, a->ai_protocol);
449 if (fd == -1)
450 return -1;
452 log_debug("%s: opened socket (%d) for %s", __func__,
453 fd, a->ifname);
455 if (setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &o_val,
456 sizeof(int)) == -1) {
457 log_warn("%s: setsockopt error", __func__);
458 close(fd);
459 return -1;
462 /* non-blocking */
463 flags = fcntl(fd, F_GETFL);
464 flags |= O_NONBLOCK;
465 if (fcntl(fd, F_SETFL, flags) == -1) {
466 log_info("%s: could not enable non-blocking I/O", __func__);
467 close(fd);
468 return -1;
471 if (bind(fd, (struct sockaddr *)&a->ss, a->slen) == -1) {
472 close(fd);
473 log_info("%s: can't bind to port %d", __func__, a->port);
474 return -1;
477 if (listen(fd, SOMAXCONN) == -1) {
478 log_warn("%s, unable to listen on socket", __func__);
479 close(fd);
480 return -1;
483 return (fd);
486 static int
487 sockets_accept_reserve(int sockfd, struct sockaddr *addr, socklen_t *addrlen,
488 int reserve, volatile int *counter)
490 int ret;
492 if (getdtablecount() + reserve +
493 ((*counter + 1) * FD_NEEDED) >= getdtablesize()) {
494 log_debug("inflight fds exceeded");
495 errno = EMFILE;
496 return -1;
499 if ((ret = accept4(sockfd, addr, addrlen,
500 SOCK_NONBLOCK | SOCK_CLOEXEC)) > -1) {
501 (*counter)++;
502 log_debug("inflight incremented, now %d", *counter);
505 return ret;
508 static void
509 sockets_accept_paused(int fd, short events, void *arg)
511 struct socket *sock = (struct socket *)arg;
513 event_add(&sock->ev, NULL);
516 void
517 sockets_socket_accept(int fd, short event, void *arg)
519 struct socket *sock = (struct socket *)arg;
520 struct sockaddr_storage ss;
521 struct timeval backoff;
522 struct request *c = NULL;
523 socklen_t len;
524 int s;
526 backoff.tv_sec = 1;
527 backoff.tv_usec = 0;
529 event_add(&sock->ev, NULL);
530 if (event & EV_TIMEOUT)
531 return;
533 len = sizeof(ss);
535 s = sockets_accept_reserve(fd, (struct sockaddr *)&ss, &len,
536 FD_RESERVE, &cgi_inflight);
538 if (s == -1) {
539 switch (errno) {
540 case EINTR:
541 case EWOULDBLOCK:
542 case ECONNABORTED:
543 return;
544 case EMFILE:
545 case ENFILE:
546 event_del(&sock->ev);
547 evtimer_add(&sock->pause, &backoff);
548 return;
549 default:
550 log_warn("%s: accept", __func__);
554 if (client_cnt > GOTWEBD_MAXCLIENTS)
555 goto err;
557 c = calloc(1, sizeof(struct request));
558 if (c == NULL) {
559 log_warn("%s", __func__);
560 close(s);
561 cgi_inflight--;
562 return;
565 c->tp = template(c, &fcgi_write, c->outbuf, sizeof(c->outbuf));
566 if (c->tp == NULL) {
567 log_warn("%s", __func__);
568 close(s);
569 cgi_inflight--;
570 free(c);
571 return;
574 c->fd = s;
575 c->sock = sock;
576 memcpy(c->priv_fd, sock->priv_fd, sizeof(c->priv_fd));
577 c->buf_pos = 0;
578 c->buf_len = 0;
579 c->request_started = 0;
580 c->sock->client_status = CLIENT_CONNECT;
582 event_set(&c->ev, s, EV_READ|EV_PERSIST, fcgi_request, c);
583 event_add(&c->ev, NULL);
585 evtimer_set(&c->tmo, fcgi_timeout, c);
586 evtimer_add(&c->tmo, &timeout);
588 client_cnt++;
590 return;
591 err:
592 cgi_inflight--;
593 close(s);
594 if (c != NULL)
595 free(c);
598 static void
599 sockets_rlimit(int maxfd)
601 struct rlimit rl;
603 if (getrlimit(RLIMIT_NOFILE, &rl) == -1)
604 fatal("%s: failed to get resource limit", __func__);
605 log_debug("%s: max open files %llu", __func__,
606 (unsigned long long)rl.rlim_max);
608 /*
609 * Allow the maximum number of open file descriptors for this
610 * login class (which should be the class "daemon" by default).
611 */
612 if (maxfd == -1)
613 rl.rlim_cur = rl.rlim_max;
614 else
615 rl.rlim_cur = MAXIMUM(rl.rlim_max, (rlim_t)maxfd);
616 if (setrlimit(RLIMIT_NOFILE, &rl) == -1)
617 fatal("%s: failed to set resource limit", __func__);