2 * Copyright (c) 2022 Stefan Sperling <stsp@openbsd.org>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 #include <sys/types.h>
18 #include <sys/queue.h>
19 #include <sys/socket.h>
36 #include "got_error.h"
43 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
46 struct gotd_listen_client {
47 STAILQ_ENTRY(gotd_listen_client) entry;
52 STAILQ_HEAD(gotd_listen_clients, gotd_listen_client);
54 static struct gotd_listen_clients gotd_listen_clients[GOTD_CLIENT_TABLE_SIZE];
55 static SIPHASH_KEY clients_hash_key;
56 static volatile int listen_client_cnt;
59 struct gotd_uid_connection_counter {
60 STAILQ_ENTRY(gotd_uid_connection_counter) entry;
64 STAILQ_HEAD(gotd_client_uids, gotd_uid_connection_counter);
65 static struct gotd_client_uids gotd_client_uids[GOTD_CLIENT_TABLE_SIZE];
66 static SIPHASH_KEY uid_hash_key;
72 struct gotd_imsgev iev;
73 struct gotd_imsgev pause;
74 struct gotd_uid_connection_limit *connection_limits;
75 size_t nconnection_limits;
80 static void listen_shutdown(void);
83 listen_sighdlr(int sig, short event, void *arg)
86 * Normal signal handler rules don't apply because libevent
101 fatalx("unexpected signal");
106 client_hash(uint32_t client_id)
108 return SipHash24(&clients_hash_key, &client_id, sizeof(client_id));
112 add_client(struct gotd_listen_client *client)
114 uint64_t slot = client_hash(client->id) % nitems(gotd_listen_clients);
115 STAILQ_INSERT_HEAD(&gotd_listen_clients[slot], client, entry);
119 static struct gotd_listen_client *
120 find_client(uint32_t client_id)
123 struct gotd_listen_client *c;
125 slot = client_hash(client_id) % nitems(gotd_listen_clients);
126 STAILQ_FOREACH(c, &gotd_listen_clients[slot], entry) {
127 if (c->id == client_id)
142 duplicate = (find_client(id) != NULL);
143 } while (duplicate || id == 0);
151 return SipHash24(&uid_hash_key, &euid, sizeof(euid));
155 add_uid_connection_counter(struct gotd_uid_connection_counter *counter)
157 uint64_t slot = uid_hash(counter->euid) % nitems(gotd_client_uids);
158 STAILQ_INSERT_HEAD(&gotd_client_uids[slot], counter, entry);
162 remove_uid_connection_counter(struct gotd_uid_connection_counter *counter)
164 uint64_t slot = uid_hash(counter->euid) % nitems(gotd_client_uids);
165 STAILQ_REMOVE(&gotd_client_uids[slot], counter,
166 gotd_uid_connection_counter, entry);
169 static struct gotd_uid_connection_counter *
170 find_uid_connection_counter(uid_t euid)
173 struct gotd_uid_connection_counter *c;
175 slot = uid_hash(euid) % nitems(gotd_client_uids);
176 STAILQ_FOREACH(c, &gotd_client_uids[slot], entry) {
184 struct gotd_uid_connection_limit *
185 gotd_find_uid_connection_limit(struct gotd_uid_connection_limit *limits,
186 size_t nlimits, uid_t uid)
188 /* This array is always sorted to allow for binary search. */
189 int i, left = 0, right = nlimits - 1;
191 while (left <= right) {
192 i = ((left + right) / 2);
193 if (limits[i].uid == uid)
195 if (limits[i].uid > uid)
204 static const struct got_error *
205 disconnect(struct gotd_listen_client *client)
207 struct gotd_uid_connection_counter *counter;
211 log_debug("client on fd %d disconnecting", client->fd);
213 slot = client_hash(client->id) % nitems(gotd_listen_clients);
214 STAILQ_REMOVE(&gotd_listen_clients[slot], client,
215 gotd_listen_client, entry);
217 counter = find_uid_connection_counter(client->euid);
219 if (counter->nconnections > 0)
220 counter->nconnections--;
221 if (counter->nconnections == 0) {
222 remove_uid_connection_counter(counter);
227 client_fd = client->fd;
231 if (close(client_fd) == -1)
232 return got_error_from_errno("close");
238 accept_reserve(int fd, struct sockaddr *addr, socklen_t *addrlen,
239 int reserve, volatile int *counter)
243 if (getdtablecount() + reserve +
244 ((*counter + 1) * GOTD_FD_NEEDED) >= getdtablesize()) {
245 log_debug("inflight fds exceeded");
250 if ((ret = accept4(fd, addr, addrlen,
251 SOCK_NONBLOCK | SOCK_CLOEXEC)) > -1) {
259 gotd_accept_paused(int fd, short event, void *arg)
261 event_add(&gotd_listen.iev.ev, NULL);
265 gotd_accept(int fd, short event, void *arg)
267 struct gotd_imsgev *iev = arg;
268 struct sockaddr_storage ss;
269 struct timeval backoff;
272 struct gotd_listen_client *client = NULL;
273 struct gotd_uid_connection_counter *counter = NULL;
274 struct gotd_imsg_connect iconn;
281 if (event_add(&gotd_listen.iev.ev, NULL) == -1) {
282 log_warn("event_add");
285 if (event & EV_TIMEOUT)
290 /* Other backoff conditions apart from EMFILE/ENFILE? */
291 s = accept_reserve(fd, (struct sockaddr *)&ss, &len, GOTD_FD_RESERVE,
301 event_del(&gotd_listen.iev.ev);
302 evtimer_add(&gotd_listen.pause.ev, &backoff);
310 if (listen_client_cnt >= GOTD_MAXCLIENTS)
313 if (getpeereid(s, &euid, &egid) == -1) {
314 log_warn("getpeerid");
318 counter = find_uid_connection_counter(euid);
319 if (counter == NULL) {
320 counter = calloc(1, sizeof(*counter));
321 if (counter == NULL) {
322 log_warn("%s: calloc", __func__);
325 counter->euid = euid;
326 counter->nconnections = 1;
327 add_uid_connection_counter(counter);
329 int max_connections = GOTD_MAX_CONN_PER_UID;
330 struct gotd_uid_connection_limit *limit;
332 limit = gotd_find_uid_connection_limit(
333 gotd_listen.connection_limits,
334 gotd_listen.nconnection_limits, euid);
336 max_connections = limit->max_connections;
338 if (counter->nconnections >= max_connections) {
339 log_warnx("maximum connections exceeded for uid %d",
343 counter->nconnections++;
346 client = calloc(1, sizeof(*client));
347 if (client == NULL) {
348 log_warn("%s: calloc", __func__);
351 client->id = get_client_id();
356 log_debug("%s: new client connected on fd %d uid %d gid %d", __func__,
357 client->fd, euid, egid);
359 memset(&iconn, 0, sizeof(iconn));
360 iconn.client_id = client->id;
365 log_warn("%s: dup", __func__);
368 if (gotd_imsg_compose_event(iev, GOTD_IMSG_CONNECT, PROC_LISTEN, s,
369 &iconn, sizeof(iconn)) == -1) {
370 log_warn("imsg compose CONNECT");
383 static const struct got_error *
384 recv_disconnect(struct imsg *imsg)
386 struct gotd_imsg_disconnect idisconnect;
388 struct gotd_listen_client *client = NULL;
390 datalen = imsg->hdr.len - IMSG_HEADER_SIZE;
391 if (datalen != sizeof(idisconnect))
392 return got_error(GOT_ERR_PRIVSEP_LEN);
393 memcpy(&idisconnect, imsg->data, sizeof(idisconnect));
395 log_debug("client disconnecting");
397 client = find_client(idisconnect.client_id);
399 return got_error(GOT_ERR_CLIENT_ID);
401 return disconnect(client);
405 listen_dispatch(int fd, short event, void *arg)
407 const struct got_error *err = NULL;
408 struct gotd_imsgev *iev = arg;
409 struct imsgbuf *ibuf = &iev->ibuf;
414 if (event & EV_READ) {
415 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
416 fatal("imsg_read error");
417 if (n == 0) /* Connection closed. */
421 if (event & EV_WRITE) {
422 n = msgbuf_write(&ibuf->w);
423 if (n == -1 && errno != EAGAIN)
424 fatal("msgbuf_write");
425 if (n == 0) /* Connection closed. */
430 if ((n = imsg_get(ibuf, &imsg)) == -1)
431 fatal("%s: imsg_get", __func__);
432 if (n == 0) /* No more messages. */
435 switch (imsg.hdr.type) {
436 case GOTD_IMSG_DISCONNECT:
437 err = recv_disconnect(&imsg);
439 log_warnx("disconnect: %s", err->msg);
442 log_debug("unexpected imsg %d", imsg.hdr.type);
450 gotd_imsg_event_add(iev);
452 /* This pipe is dead. Remove its event handler */
454 event_loopexit(NULL);
459 listen_main(const char *title, int gotd_socket,
460 struct gotd_uid_connection_limit *connection_limits,
461 size_t nconnection_limits)
463 struct gotd_imsgev iev;
464 struct event evsigint, evsigterm, evsighup, evsigusr1;
466 arc4random_buf(&clients_hash_key, sizeof(clients_hash_key));
467 arc4random_buf(&uid_hash_key, sizeof(uid_hash_key));
469 gotd_listen.title = title;
470 gotd_listen.pid = getpid();
471 gotd_listen.fd = gotd_socket;
472 gotd_listen.connection_limits = connection_limits;
473 gotd_listen.nconnection_limits = nconnection_limits;
475 signal_set(&evsigint, SIGINT, listen_sighdlr, NULL);
476 signal_set(&evsigterm, SIGTERM, listen_sighdlr, NULL);
477 signal_set(&evsighup, SIGHUP, listen_sighdlr, NULL);
478 signal_set(&evsigusr1, SIGUSR1, listen_sighdlr, NULL);
479 signal(SIGPIPE, SIG_IGN);
481 signal_add(&evsigint, NULL);
482 signal_add(&evsigterm, NULL);
483 signal_add(&evsighup, NULL);
484 signal_add(&evsigusr1, NULL);
486 imsg_init(&iev.ibuf, GOTD_FILENO_MSG_PIPE);
487 iev.handler = listen_dispatch;
488 iev.events = EV_READ;
489 iev.handler_arg = NULL;
490 event_set(&iev.ev, iev.ibuf.fd, EV_READ, listen_dispatch, &iev);
491 if (event_add(&iev.ev, NULL) == -1)
494 event_set(&gotd_listen.iev.ev, gotd_listen.fd, EV_READ | EV_PERSIST,
496 if (event_add(&gotd_listen.iev.ev, NULL))
498 evtimer_set(&gotd_listen.pause.ev, gotd_accept_paused, NULL);
506 listen_shutdown(void)
508 log_debug("shutting down");
510 free(gotd_listen.connection_limits);
511 if (gotd_listen.fd != -1)
512 close(gotd_listen.fd);