libtommath: Fix possible integer overflow CVE-2023-36328
[heimdal.git] / kdc / connect.c
blobba8c8ad7ba5425f67903a4c45e519f044d88d5a5
1 /*
2 * Copyright (c) 1997-2005 Kungliga Tekniska Högskolan
3 * (Royal Institute of Technology, Stockholm, Sweden).
4 * All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of the Institute nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
34 #include "kdc_locl.h"
37 * a tuple describing on what to listen
40 struct port_desc{
41 int family;
42 int type;
43 int port;
46 /* the current ones */
48 static struct port_desc *ports;
49 static size_t num_ports;
50 static pid_t bonjour_pid = -1;
53 * add `family, port, protocol' to the list with duplicate suppresion.
56 static void
57 add_port(krb5_context context,
58 int family, int port, const char *protocol)
60 int type;
61 size_t i;
63 if(strcmp(protocol, "udp") == 0)
64 type = SOCK_DGRAM;
65 else if(strcmp(protocol, "tcp") == 0)
66 type = SOCK_STREAM;
67 else
68 return;
69 for(i = 0; i < num_ports; i++){
70 if(ports[i].type == type
71 && ports[i].port == port
72 && ports[i].family == family)
73 return;
75 ports = realloc(ports, (num_ports + 1) * sizeof(*ports));
76 if (ports == NULL)
77 krb5_err (context, 1, errno, "realloc");
78 ports[num_ports].family = family;
79 ports[num_ports].type = type;
80 ports[num_ports].port = port;
81 num_ports++;
85 * add a triple but with service -> port lookup
86 * (this prints warnings for stuff that does not exist)
89 static void
90 add_port_service(krb5_context context,
91 int family, const char *service, int port,
92 const char *protocol)
94 port = krb5_getportbyname (context, service, protocol, port);
95 add_port (context, family, port, protocol);
99 * add the port with service -> port lookup or string -> number
100 * (no warning is printed)
103 static void
104 add_port_string (krb5_context context,
105 int family, const char *str, const char *protocol)
107 struct servent *sp;
108 int port;
110 sp = roken_getservbyname (str, protocol);
111 if (sp != NULL) {
112 port = sp->s_port;
113 } else {
114 char *end;
116 port = htons(strtol(str, &end, 0));
117 if (end == str)
118 return;
120 add_port (context, family, port, protocol);
124 * add the standard collection of ports for `family'
127 static void
128 add_standard_ports (krb5_context context,
129 krb5_kdc_configuration *config,
130 int family)
132 add_port_service(context, family, "kerberos", 88, "udp");
133 add_port_service(context, family, "kerberos", 88, "tcp");
134 add_port_service(context, family, "kerberos-sec", 88, "udp");
135 add_port_service(context, family, "kerberos-sec", 88, "tcp");
136 if(enable_http)
137 add_port_service(context, family, "http", 80, "tcp");
138 if(config->enable_kx509) {
139 add_port_service(context, family, "kca_service", 9878, "udp");
140 add_port_service(context, family, "kca_service", 9878, "tcp");
146 * parse the set of space-delimited ports in `str' and add them.
147 * "+" => all the standard ones
148 * otherwise it's port|service[/protocol]
151 static void
152 parse_ports(krb5_context context,
153 krb5_kdc_configuration *config,
154 const char *str)
156 char *pos = NULL;
157 char *p;
158 char *str_copy = strdup (str);
160 p = strtok_r(str_copy, " \t", &pos);
161 while(p != NULL) {
162 if(strcmp(p, "+") == 0) {
163 #ifdef HAVE_IPV6
164 add_standard_ports(context, config, AF_INET6);
165 #endif
166 add_standard_ports(context, config, AF_INET);
167 } else {
168 char *q = strchr(p, '/');
169 if(q){
170 *q++ = 0;
171 #ifdef HAVE_IPV6
172 add_port_string(context, AF_INET6, p, q);
173 #endif
174 add_port_string(context, AF_INET, p, q);
175 }else {
176 #ifdef HAVE_IPV6
177 add_port_string(context, AF_INET6, p, "udp");
178 add_port_string(context, AF_INET6, p, "tcp");
179 #endif
180 add_port_string(context, AF_INET, p, "udp");
181 add_port_string(context, AF_INET, p, "tcp");
185 p = strtok_r(NULL, " \t", &pos);
187 free (str_copy);
191 * every socket we listen on
194 struct descr {
195 krb5_socket_t s;
196 int type;
197 int port;
198 unsigned char *buf;
199 size_t size;
200 size_t len;
201 time_t timeout;
202 struct sockaddr_storage __ss;
203 struct sockaddr *sa;
204 socklen_t sock_len;
205 char addr_string[128];
208 static void
209 init_descr(struct descr *d)
211 memset(d, 0, sizeof(*d));
212 d->sa = (struct sockaddr *)&d->__ss;
213 d->s = rk_INVALID_SOCKET;
217 * re-initialize all `n' ->sa in `d'.
220 static void
221 reinit_descrs (struct descr *d, int n)
223 int i;
225 for (i = 0; i < n; ++i)
226 d[i].sa = (struct sockaddr *)&d[i].__ss;
230 * Create the socket (family, type, port) in `d'
233 static void
234 init_socket(krb5_context context,
235 krb5_kdc_configuration *config,
236 struct descr *d, krb5_address *a, int family, int type, int port)
238 krb5_error_code ret;
239 struct sockaddr_storage __ss;
240 struct sockaddr *sa = (struct sockaddr *)&__ss;
241 krb5_socklen_t sa_size = sizeof(__ss);
243 init_descr (d);
245 ret = krb5_addr2sockaddr (context, a, sa, &sa_size, port);
246 if (ret) {
247 krb5_warn(context, ret, "krb5_addr2sockaddr");
248 rk_closesocket(d->s);
249 d->s = rk_INVALID_SOCKET;
250 return;
253 if (sa->sa_family != family)
254 return;
256 d->s = socket(family, type, 0);
257 if(rk_IS_BAD_SOCKET(d->s)){
258 krb5_warn(context, errno, "socket(%d, %d, 0)", family, type);
259 d->s = rk_INVALID_SOCKET;
260 return;
262 rk_cloexec(d->s);
263 #if defined(HAVE_SETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_REUSEADDR)
265 int one = 1;
266 (void) setsockopt(d->s, SOL_SOCKET, SO_REUSEADDR, (void *)&one,
267 sizeof(one));
269 #endif
270 d->type = type;
271 d->port = port;
273 socket_set_nonblocking(d->s, 1);
275 if(rk_IS_SOCKET_ERROR(bind(d->s, sa, sa_size))){
276 char a_str[256];
277 size_t len;
279 krb5_print_address (a, a_str, sizeof(a_str), &len);
280 krb5_warn(context, errno, "bind %s/%d", a_str, ntohs(port));
281 rk_closesocket(d->s);
282 d->s = rk_INVALID_SOCKET;
283 return;
285 if(type == SOCK_STREAM && rk_IS_SOCKET_ERROR(listen(d->s, SOMAXCONN))){
286 char a_str[256];
287 size_t len;
289 krb5_print_address (a, a_str, sizeof(a_str), &len);
290 krb5_warn(context, errno, "listen %s/%d", a_str, ntohs(port));
291 rk_closesocket(d->s);
292 d->s = rk_INVALID_SOCKET;
293 return;
295 socket_set_keepalive(d->s, 1);
299 * Allocate descriptors for all the sockets that we should listen on
300 * and return the number of them.
303 static int
304 init_sockets(krb5_context context,
305 krb5_kdc_configuration *config,
306 struct descr **desc)
308 krb5_error_code ret;
309 size_t i, j;
310 struct descr *d;
311 int num = 0;
312 krb5_addresses addresses;
314 if (explicit_addresses.len) {
315 addresses = explicit_addresses;
316 } else {
317 ret = krb5_get_all_server_addrs (context, &addresses);
318 if (ret)
319 krb5_err (context, 1, ret, "krb5_get_all_server_addrs");
321 parse_ports(context, config, port_str);
322 d = malloc(addresses.len * num_ports * sizeof(*d));
323 if (d == NULL)
324 krb5_errx(context, 1, "malloc(%lu) failed",
325 (unsigned long)num_ports * sizeof(*d));
327 for (i = 0; i < num_ports; i++){
328 for (j = 0; j < addresses.len; ++j) {
329 init_socket(context, config, &d[num], &addresses.val[j],
330 ports[i].family, ports[i].type, ports[i].port);
331 if(d[num].s != rk_INVALID_SOCKET){
332 char a_str[80];
333 size_t len;
335 krb5_print_address (&addresses.val[j], a_str,
336 sizeof(a_str), &len);
338 kdc_log(context, config, 3, "listening on %s port %u/%s",
339 a_str,
340 ntohs(ports[i].port),
341 (ports[i].type == SOCK_STREAM) ? "tcp" : "udp");
342 /* XXX */
343 num++;
347 krb5_free_addresses (context, &addresses);
348 d = realloc(d, num * sizeof(*d));
349 if (d == NULL && num != 0)
350 krb5_errx(context, 1, "realloc(%lu) failed",
351 (unsigned long)num * sizeof(*d));
352 reinit_descrs (d, num);
353 *desc = d;
354 return num;
361 static const char *
362 descr_type(struct descr *d)
364 if (d->type == SOCK_DGRAM)
365 return "udp";
366 else if (d->type == SOCK_STREAM)
367 return "tcp";
368 return "unknown";
371 static void
372 addr_to_string(krb5_context context,
373 struct sockaddr *addr, size_t addr_len, char *str, size_t len)
375 krb5_address a;
376 if(krb5_sockaddr2address(context, addr, &a) == 0) {
377 if(krb5_print_address(&a, str, len, &len) == 0) {
378 krb5_free_address(context, &a);
379 return;
381 krb5_free_address(context, &a);
383 snprintf(str, len, "<family=%d>", addr->sa_family);
390 static void
391 send_reply(krb5_context context,
392 krb5_kdc_configuration *config,
393 krb5_boolean prependlength,
394 struct descr *d,
395 krb5_data *reply)
397 kdc_log(context, config, 4,
398 "sending %lu bytes to %s", (unsigned long)reply->length,
399 d->addr_string);
400 if(prependlength){
401 unsigned char l[4];
402 l[0] = (reply->length >> 24) & 0xff;
403 l[1] = (reply->length >> 16) & 0xff;
404 l[2] = (reply->length >> 8) & 0xff;
405 l[3] = reply->length & 0xff;
406 if(rk_IS_SOCKET_ERROR(sendto(d->s, l, sizeof(l), 0, d->sa, d->sock_len))) {
407 kdc_log (context, config,
408 1, "sendto(%s): %s", d->addr_string,
409 strerror(rk_SOCK_ERRNO));
410 return;
413 if(rk_IS_SOCKET_ERROR(sendto(d->s, reply->data, reply->length, 0, d->sa, d->sock_len))) {
414 kdc_log (context, config, 1, "sendto(%s): %s", d->addr_string,
415 strerror(rk_SOCK_ERRNO));
416 return;
421 * Handle the request in `buf, len' to socket `d'
424 static void
425 do_request(krb5_context context,
426 krb5_kdc_configuration *config,
427 void *buf, size_t len, krb5_boolean prependlength,
428 struct descr *d)
430 krb5_error_code ret;
431 krb5_data reply;
432 int datagram_reply = (d->type == SOCK_DGRAM);
434 krb5_kdc_update_time(NULL);
436 krb5_data_zero(&reply);
437 ret = krb5_kdc_process_request(context, config,
438 buf, len, &reply, &prependlength,
439 d->addr_string, d->sa,
440 datagram_reply);
441 if(request_log)
442 krb5_kdc_save_request(context, request_log, buf, len, &reply, d->sa);
443 if(reply.length){
444 send_reply(context, config, prependlength, d, &reply);
445 krb5_data_free(&reply);
447 if(ret)
448 kdc_log(context, config, 1,
449 "Failed processing %lu byte request from %s",
450 (unsigned long)len, d->addr_string);
454 * Handle incoming data to the UDP socket in `d'
457 static void
458 handle_udp(krb5_context context,
459 krb5_kdc_configuration *config,
460 struct descr *d)
462 unsigned char *buf;
463 ssize_t n;
465 buf = malloc(max_request_udp);
466 if (buf == NULL){
467 kdc_log(context, config, 1, "Failed to allocate %lu bytes",
468 (unsigned long)max_request_udp);
469 return;
472 d->sock_len = sizeof(d->__ss);
473 n = recvfrom(d->s, buf, max_request_udp, 0, d->sa, &d->sock_len);
474 if (rk_IS_SOCKET_ERROR(n)) {
475 if (rk_SOCK_ERRNO != EAGAIN && rk_SOCK_ERRNO != EINTR)
476 krb5_warn(context, rk_SOCK_ERRNO, "recvfrom");
477 } else {
478 addr_to_string (context, d->sa, d->sock_len,
479 d->addr_string, sizeof(d->addr_string));
480 if ((size_t)n == max_request_udp) {
481 krb5_data data;
482 krb5_warn(context, errno,
483 "recvfrom: truncated packet from %s, asking for TCP",
484 d->addr_string);
485 krb5_mk_error(context,
486 KRB5KRB_ERR_RESPONSE_TOO_BIG,
487 NULL,
488 NULL,
489 NULL,
490 NULL,
491 NULL,
492 NULL,
493 &data);
494 send_reply(context, config, FALSE, d, &data);
495 krb5_data_free(&data);
496 } else {
497 do_request(context, config, buf, n, FALSE, d);
500 free (buf);
503 static void
504 clear_descr(struct descr *d)
506 if(d->buf)
507 memset(d->buf, 0, d->size);
508 d->len = 0;
509 if(d->s != rk_INVALID_SOCKET)
510 rk_closesocket(d->s);
511 d->s = rk_INVALID_SOCKET;
515 /* remove HTTP %-quoting from buf */
516 static int
517 de_http(char *buf)
519 unsigned char *p, *q;
520 unsigned int x;
522 for (p = q = (unsigned char *)buf; *p; p++, q++) {
523 if (*p == '%') {
524 if (!(isxdigit(p[1]) && isxdigit(p[2])))
525 return -1;
527 if (sscanf((char *)p + 1, "%2x", &x) != 1)
528 return -1;
530 *q = x;
531 p += 2;
532 } else {
533 *q = *p;
536 *q = '\0';
537 return 0;
540 #define TCP_TIMEOUT 4
543 * accept a new TCP connection on `d[parent]' and store it in `d[child]'
546 static void
547 add_new_tcp (krb5_context context,
548 krb5_kdc_configuration *config,
549 struct descr *d, int parent, int child)
551 krb5_socket_t s;
553 if (child == -1)
554 return;
556 d[child].sock_len = sizeof(d[child].__ss);
557 s = accept(d[parent].s, d[child].sa, &d[child].sock_len);
558 if(rk_IS_BAD_SOCKET(s)) {
559 if (rk_SOCK_ERRNO != EAGAIN && rk_SOCK_ERRNO != EINTR)
560 krb5_warn(context, rk_SOCK_ERRNO, "accept");
561 return;
564 #ifdef FD_SETSIZE
565 if (s >= FD_SETSIZE) {
566 krb5_warnx(context, "socket FD too large");
567 rk_closesocket (s);
568 return;
570 #endif
572 d[child].s = s;
573 d[child].timeout = time(NULL) + TCP_TIMEOUT;
574 d[child].type = SOCK_STREAM;
575 addr_to_string (context,
576 d[child].sa, d[child].sock_len,
577 d[child].addr_string, sizeof(d[child].addr_string));
581 * Grow `d' to handle at least `n'.
582 * Return != 0 if fails
585 static int
586 grow_descr (krb5_context context,
587 krb5_kdc_configuration *config,
588 struct descr *d, size_t n)
590 if (d->size - d->len < n) {
591 unsigned char *tmp;
592 size_t grow;
594 grow = max(1024, d->len + n);
595 if (d->size + grow > max_request_tcp) {
596 kdc_log(context, config, 2, "Request exceeds max request size (%lu bytes).",
597 (unsigned long)d->size + grow);
598 clear_descr(d);
599 return -1;
601 tmp = realloc (d->buf, d->size + grow);
602 if (tmp == NULL) {
603 kdc_log(context, config, 1, "Failed to re-allocate %lu bytes.",
604 (unsigned long)d->size + grow);
605 clear_descr(d);
606 return -1;
608 d->size += grow;
609 d->buf = tmp;
611 return 0;
615 * Try to handle the TCP data at `d->buf, d->len'.
616 * Return -1 if failed, 0 if succesful, and 1 if data is complete.
619 static int
620 handle_vanilla_tcp (krb5_context context,
621 krb5_kdc_configuration *config,
622 struct descr *d)
624 krb5_error_code ret;
625 krb5_storage *sp;
626 uint32_t len;
628 if (d->len < 4)
629 return 0;
630 sp = krb5_storage_from_mem(d->buf, d->len);
631 if (sp == NULL) {
632 kdc_log (context, config, 1, "krb5_storage_from_mem failed");
633 return -1;
635 ret = krb5_ret_uint32(sp, &len);
636 if (ret) {
637 kdc_log(context, config, 4, "failed to read request length");
638 return -1;
640 krb5_storage_free(sp);
641 if(d->len - 4 >= len) {
642 memmove(d->buf, d->buf + 4, d->len - 4);
643 d->len -= 4;
644 return 1;
646 return 0;
650 * Try to handle the TCP/HTTP data at `d->buf, d->len'.
651 * Return -1 if failed, 0 if succesful, and 1 if data is complete.
654 static int
655 handle_http_tcp (krb5_context context,
656 krb5_kdc_configuration *config,
657 struct descr *d)
659 char *s, *p, *t;
660 void *data;
661 char *proto;
662 int len;
664 s = (char *)d->buf;
666 /* If its a multi line query, truncate off the first line */
667 p = strstr(s, "\r\n");
668 if (p)
669 *p = 0;
671 p = NULL;
672 t = strtok_r(s, " \t", &p);
673 if (t == NULL) {
674 kdc_log(context, config, 2,
675 "Missing HTTP operand (GET) request from %s", d->addr_string);
676 return -1;
679 t = strtok_r(NULL, " \t", &p);
680 if(t == NULL) {
681 kdc_log(context, config, 2,
682 "Missing HTTP GET data in request from %s", d->addr_string);
683 return -1;
686 data = malloc(strlen(t));
687 if (data == NULL) {
688 kdc_log(context, config, 1, "Failed to allocate %lu bytes",
689 (unsigned long)strlen(t));
690 return -1;
692 if(*t == '/')
693 t++;
694 if(de_http(t) != 0) {
695 kdc_log(context, config, 2, "Malformed HTTP request from %s", d->addr_string);
696 kdc_log(context, config, 4, "HTTP request: %s", t);
697 free(data);
698 return -1;
700 proto = strtok_r(NULL, " \t", &p);
701 if (proto == NULL) {
702 kdc_log(context, config, 2, "Malformed HTTP request from %s", d->addr_string);
703 free(data);
704 return -1;
706 len = rk_base64_decode(t, data);
707 if(len <= 0){
708 const char *msg =
709 " 404 Not found\r\n"
710 "Server: Heimdal/" VERSION "\r\n"
711 "Cache-Control: no-cache\r\n"
712 "Pragma: no-cache\r\n"
713 "Content-type: text/html\r\n"
714 "Content-transfer-encoding: 8bit\r\n\r\n"
715 "<TITLE>404 Not found</TITLE>\r\n"
716 "<H1>404 Not found</H1>\r\n"
717 "That page doesn't exist, maybe you are looking for "
718 "<A HREF=\"http://www.h5l.org/\">Heimdal</A>?\r\n";
719 kdc_log(context, config, 2, "HTTP request from %s is non KDC request", d->addr_string);
720 kdc_log(context, config, 4, "HTTP request: %s", t);
721 free(data);
722 if (rk_IS_SOCKET_ERROR(send(d->s, proto, strlen(proto), 0))) {
723 kdc_log(context, config, 1, "HTTP write failed: %s: %s",
724 d->addr_string, strerror(rk_SOCK_ERRNO));
725 return -1;
727 if (rk_IS_SOCKET_ERROR(send(d->s, msg, strlen(msg), 0))) {
728 kdc_log(context, config, 1, "HTTP write failed: %s: %s",
729 d->addr_string, strerror(rk_SOCK_ERRNO));
730 return -1;
732 return -1;
735 const char *msg =
736 " 200 OK\r\n"
737 "Server: Heimdal/" VERSION "\r\n"
738 "Cache-Control: no-cache\r\n"
739 "Pragma: no-cache\r\n"
740 "Content-type: application/octet-stream\r\n"
741 "Content-transfer-encoding: binary\r\n\r\n";
742 if (rk_IS_SOCKET_ERROR(send(d->s, proto, strlen(proto), 0))) {
743 free(data);
744 kdc_log(context, config, 1, "HTTP write failed: %s: %s",
745 d->addr_string, strerror(rk_SOCK_ERRNO));
746 return -1;
748 if (rk_IS_SOCKET_ERROR(send(d->s, msg, strlen(msg), 0))) {
749 free(data);
750 kdc_log(context, config, 1, "HTTP write failed: %s: %s",
751 d->addr_string, strerror(rk_SOCK_ERRNO));
752 return -1;
755 if ((size_t)len > d->len)
756 len = d->len;
757 memcpy(d->buf, data, len);
758 d->len = len;
759 free(data);
760 return 1;
763 static int
764 http1_request_taste(const unsigned char *req, size_t len)
766 return !!((len >= sizeof("GET ") - 1 &&
767 memcmp(req, "GET ", sizeof("GET ") - 1) == 0) ||
768 (len >= sizeof("HEAD ") - 1 &&
769 memcmp(req, "HEAD ", sizeof("HEAD ") - 1) == 0));
772 static int
773 http1_request_is_complete(const unsigned char *req, size_t len)
776 return http1_request_taste(req, len) &&
777 memmem(req, len, "\r\n\r\n", sizeof("\r\n\r\n") - 4) != NULL;
780 * For POST (the MSFT variant of this protocol) we'll need something like
781 * this (plus check for Content-Length/Transfer-Encoding):
783 * const unsigned char *body;
784 * if ((body = memmem(req, len, "\r\n\r\n", sizeof("\r\n\r\n") - 4)) == NULL)
785 * return 0;
786 * body += sizeof("\r\n\r\n") - 4;
787 * len -= (body - req);
788 * return memmem(body, len, "\r\n\r\n", sizeof("\r\n\r\n") - 4) != NULL;
790 * Since the POST-based variant runs over HTTPS, we'll probably implement
791 * that in a proxy instead of here.
796 * Handle incoming data to the TCP socket in `d[index]'
799 static void
800 handle_tcp(krb5_context context,
801 krb5_kdc_configuration *config,
802 struct descr *d, int idx, int min_free)
804 unsigned char buf[1024];
805 int n;
806 int ret = 0;
808 if (d[idx].timeout == 0) {
809 add_new_tcp (context, config, d, idx, min_free);
810 return;
813 n = recvfrom(d[idx].s, buf, sizeof(buf), 0, NULL, NULL);
814 if(rk_IS_SOCKET_ERROR(n)){
815 krb5_warn(context, rk_SOCK_ERRNO, "recvfrom failed from %s to %s/%d",
816 d[idx].addr_string, descr_type(d + idx),
817 ntohs(d[idx].port));
818 return;
819 } else if (n == 0) {
820 krb5_warnx(context, "connection closed before end of data after %lu "
821 "bytes from %s to %s/%d", (unsigned long)d[idx].len,
822 d[idx].addr_string, descr_type(d + idx),
823 ntohs(d[idx].port));
824 clear_descr (d + idx);
825 return;
827 if (grow_descr (context, config, &d[idx], n))
828 return;
829 memcpy(d[idx].buf + d[idx].len, buf, n);
830 d[idx].len += n;
831 if(d[idx].len > 4 && d[idx].buf[0] == 0) {
832 ret = handle_vanilla_tcp (context, config, &d[idx]);
833 } else if (enable_http &&
834 http1_request_taste(d[idx].buf, d[idx].len)) {
836 if (http1_request_is_complete(d[idx].buf, d[idx].len)) {
837 /* NUL-terminate at the request header ending \r\n\r\n */
838 d[idx].buf[d[idx].len - 4] = '\0';
839 ret = handle_http_tcp (context, config, &d[idx]);
841 } else if (d[idx].len > 4) {
842 kdc_log (context, config,
843 2, "TCP data of strange type from %s to %s/%d",
844 d[idx].addr_string, descr_type(d + idx),
845 ntohs(d[idx].port));
846 if (d[idx].buf[0] & 0x80) {
847 krb5_data reply;
849 kdc_log (context, config, 2, "TCP extension not supported");
851 ret = krb5_mk_error(context,
852 KRB5KRB_ERR_FIELD_TOOLONG,
853 NULL,
854 NULL,
855 NULL,
856 NULL,
857 NULL,
858 NULL,
859 &reply);
860 if (ret == 0) {
861 send_reply(context, config, TRUE, d + idx, &reply);
862 krb5_data_free(&reply);
865 clear_descr(d + idx);
866 return;
870 * ret == 0 -> not enough of request buffered -> wait for more
871 * ret == 1 -> go ahead and perform the request
872 * ret != 0 (really, < 0) -> error, probably ENOMEM, close connection
874 if (ret == 1)
875 do_request(context, config,
876 d[idx].buf, d[idx].len, TRUE, &d[idx]);
879 * Note: this means we don't keep the connection open even where we
880 * the protocol permits it.
882 if (ret != 0)
883 clear_descr(d + idx);
886 #ifdef HAVE_FORK
887 static void
888 handle_islive(int fd)
890 char buf;
891 int ret;
893 ret = read(fd, &buf, 1);
894 if (ret != 1)
895 exit_flag = -1;
897 #endif
899 static krb5_boolean
900 realloc_descrs(struct descr **d, unsigned int *ndescr)
902 struct descr *tmp;
903 size_t i;
905 tmp = realloc(*d, (*ndescr + 4) * sizeof(**d));
906 if(tmp == NULL)
907 return FALSE;
909 *d = tmp;
910 reinit_descrs (*d, *ndescr);
911 memset(*d + *ndescr, 0, 4 * sizeof(**d));
912 for(i = *ndescr; i < *ndescr + 4; i++)
913 init_descr (*d + i);
915 *ndescr += 4;
917 return TRUE;
920 static int
921 next_min_free(krb5_context context, struct descr **d, unsigned int *ndescr)
923 size_t i;
924 int min_free;
926 for(i = 0; i < *ndescr; i++) {
927 int s = (*d + i)->s;
928 if(rk_IS_BAD_SOCKET(s))
929 return i;
932 min_free = *ndescr;
933 if(!realloc_descrs(d, ndescr)) {
934 min_free = -1;
935 krb5_warnx(context, "No memory");
938 return min_free;
941 static void
942 loop(krb5_context context, krb5_kdc_configuration *config,
943 struct descr **dp, unsigned int *ndescrp, int islive)
945 struct descr *d = *dp;
946 unsigned int ndescr = *ndescrp;
948 while (exit_flag == 0) {
949 struct timeval tmout;
950 fd_set fds;
951 int min_free = -1;
952 int max_fd = 0;
953 size_t i;
955 FD_ZERO(&fds);
956 if (islive > -1) {
957 FD_SET(islive, &fds);
958 max_fd = islive;
960 for (i = 0; i < ndescr; i++) {
961 if (!rk_IS_BAD_SOCKET(d[i].s)) {
962 if (d[i].type == SOCK_STREAM &&
963 d[i].timeout && d[i].timeout < time(NULL)) {
964 kdc_log(context, config, 2,
965 "TCP-connection from %s expired after %lu bytes",
966 d[i].addr_string, (unsigned long)d[i].len);
967 clear_descr(&d[i]);
968 continue;
970 #ifndef NO_LIMIT_FD_SETSIZE
971 if (max_fd < d[i].s)
972 max_fd = d[i].s;
973 #ifdef FD_SETSIZE
974 if (max_fd >= FD_SETSIZE)
975 krb5_errx(context, 1, "fd too large");
976 #endif
977 #endif
978 FD_SET(d[i].s, &fds);
982 tmout.tv_sec = TCP_TIMEOUT;
983 tmout.tv_usec = 0;
984 switch(select(max_fd + 1, &fds, 0, 0, &tmout)){
985 case 0:
986 break;
987 case -1:
988 if (errno != EINTR)
989 krb5_warn(context, rk_SOCK_ERRNO, "select");
990 break;
991 default:
992 #ifdef HAVE_FORK
993 if (islive > -1 && FD_ISSET(islive, &fds))
994 handle_islive(islive);
995 #endif
996 for (i = 0; i < ndescr; i++)
997 if (!rk_IS_BAD_SOCKET(d[i].s) && FD_ISSET(d[i].s, &fds)) {
998 min_free = next_min_free(context, dp, ndescrp);
999 ndescr = *ndescrp;
1000 d = *dp;
1002 if (d[i].type == SOCK_DGRAM)
1003 handle_udp(context, config, &d[i]);
1004 else if (d[i].type == SOCK_STREAM)
1005 handle_tcp(context, config, d, i, min_free);
1010 switch (exit_flag) {
1011 case -1:
1012 kdc_log(context, config, 0,
1013 "KDC worker process exiting because KDC master exited.");
1014 break;
1015 #ifdef SIGXCPU
1016 case SIGXCPU:
1017 kdc_log(context, config, 0, "CPU time limit exceeded");
1018 break;
1019 #endif
1020 case SIGINT:
1021 case SIGTERM:
1022 kdc_log(context, config, 0, "Terminated");
1023 break;
1024 default:
1025 kdc_log(context, config, 0, "Unexpected exit reason: %d", exit_flag);
1026 break;
1030 #ifdef __APPLE__
1031 static void
1032 bonjour_kid(krb5_context context, krb5_kdc_configuration *config, const char *argv0, int *islive)
1034 char buf;
1036 if (do_bonjour > 0) {
1037 bonjour_announce(context, config);
1039 while (read(0, &buf, 1) == 1)
1040 continue;
1041 _exit(0);
1044 if ((bonjour_pid = fork()) != 0)
1045 return;
1047 close(islive[0]);
1048 if (dup2(islive[1], 0) == -1)
1049 err(1, "failed to announce with bonjour (dup)");
1050 if (islive[1] != 0)
1051 close(islive[1]);
1052 execlp(argv0, "kdc", "--bonjour", NULL);
1053 err(1, "failed to announce with bonjour (exec)");
1055 #endif
1057 #ifdef HAVE_FORK
1058 static void
1059 kill_kids(pid_t *pids, int max_kids, int sig)
1061 int i;
1063 for (i=0; i < max_kids; i++)
1064 if (pids[i] > 0)
1065 kill(sig, pids[i]);
1066 if (bonjour_pid > 0)
1067 kill(sig, bonjour_pid);
1070 static int
1071 reap_kid(krb5_context context, krb5_kdc_configuration *config,
1072 pid_t *pids, int max_kids, int options)
1074 pid_t pid;
1075 char *what = "untracked";
1076 int status;
1077 int i = 0; /* quiet warnings */
1078 int ret = 0;
1079 int level = 3;
1080 const char *sev = "info: ";
1082 pid = waitpid(-1, &status, options);
1083 if (pid <= 0)
1084 return 0;
1086 if (pid == bonjour_pid) {
1087 bonjour_pid = (pid_t)-1;
1088 what = "bonjour";
1089 } else {
1090 for (i=0; i < max_kids; i++) {
1091 if (pids[i] == pid) {
1092 pids[i] = (pid_t)-1;
1093 what = "worker";
1094 ret = 1;
1095 break;
1099 if (i == max_kids) {
1100 /* should not happen */
1101 sev = "warning: ";
1102 level = 2;
1106 if (WIFEXITED(status))
1107 kdc_log(context, config, level,
1108 "%sKDC reaped %s process: %d, exit status: %d",
1109 sev, what, (int)pid, WEXITSTATUS(status));
1110 else if (WIFSIGNALED(status))
1111 kdc_log(context, config, level,
1112 "%sKDC reaped %s process: %d, term signal %d%s",
1113 sev, what, (int)pid, WTERMSIG(status),
1114 WCOREDUMP(status) ? " (core dumped)" : "");
1115 else
1116 kdc_log(context, config, level, "%sKDC reaped %s process: %d",
1117 sev, what, (int)pid);
1119 return ret;
1122 static int
1123 reap_kids(krb5_context context, krb5_kdc_configuration *config,
1124 pid_t *pids, int max_kids)
1126 int reaped = 0;
1128 for (;;) {
1129 if (reap_kid(context, config, pids, max_kids, WNOHANG) == 0)
1130 break;
1131 reaped++;
1134 return reaped;
1137 static void
1138 select_sleep(int microseconds)
1140 struct timeval tv;
1142 tv.tv_sec = microseconds / 1000000;
1143 tv.tv_usec = microseconds % 1000000;
1144 select(0, NULL, NULL, NULL, &tv);
1146 #endif
1148 void
1149 start_kdc(krb5_context context,
1150 krb5_kdc_configuration *config, const char *argv0)
1152 struct timeval tv1;
1153 struct timeval tv2;
1154 struct descr *d;
1155 unsigned int ndescr;
1156 pid_t pid = -1;
1157 #ifdef HAVE_FORK
1158 pid_t *pids;
1159 int max_kdcs = config->num_kdc_processes;
1160 int num_kdcs = 0;
1161 int i;
1162 int islive[2];
1163 #endif
1165 #ifdef __APPLE__
1166 if (!testing_flag && do_bonjour > 0)
1167 bonjour_kid(context, config, argv0, NULL);
1168 #endif
1170 #ifdef HAVE_FORK
1171 #ifdef _SC_NPROCESSORS_ONLN
1172 if (max_kdcs < 1)
1173 max_kdcs = sysconf(_SC_NPROCESSORS_ONLN);
1174 #endif
1176 if (max_kdcs < 1)
1177 max_kdcs = 1;
1179 pids = calloc(max_kdcs, sizeof(*pids));
1180 if (pids == NULL)
1181 krb5_err(context, 1, errno, "malloc");
1184 * We open a socketpair of which we hand one end to each of our kids.
1185 * When we exit, for whatever reason, the children will notice an EOF
1186 * on their end and be able to cleanly exit.
1189 if (socketpair(PF_UNIX, SOCK_STREAM, 0, islive) == -1)
1190 krb5_errx(context, 1, "socketpair");
1191 socket_set_nonblocking(islive[1], 1);
1192 #endif
1194 ndescr = init_sockets(context, config, &d);
1195 if(ndescr <= 0)
1196 krb5_errx(context, 1, "No sockets!");
1198 #ifdef HAVE_FORK
1200 # ifdef __APPLE__
1201 if (!testing_flag && do_bonjour < 0)
1202 bonjour_kid(context, config, argv0, islive);
1203 # endif
1205 kdc_log(context, config, 3, "KDC started master process pid=%d", getpid());
1206 #else
1207 kdc_log(context, config, 3, "KDC started pid=%d", getpid());
1208 #endif
1210 roken_detach_finish(NULL, daemon_child);
1212 #ifdef HAVE_FORK
1213 if (!testing_flag) {
1214 /* Note that we might never execute the body of this loop */
1215 while (exit_flag == 0) {
1217 if (num_kdcs >= max_kdcs) {
1218 num_kdcs -= reap_kid(context, config, pids, max_kdcs, 0);
1219 continue;
1222 if (num_kdcs > 0)
1223 num_kdcs -= reap_kids(context, config, pids, max_kdcs);
1225 pid = fork();
1226 switch (pid) {
1227 case 0:
1228 close(islive[0]);
1229 loop(context, config, &d, &ndescr, islive[1]);
1230 exit(0);
1231 case -1:
1232 /* XXXrcd: hmmm, do something useful?? */
1233 kdc_log(context, config, 1,
1234 "KDC master process could not fork worker process");
1235 sleep(10);
1236 break;
1237 default:
1238 for (i = 0; i < max_kdcs; i++) {
1239 if (pids[i] <= 0) {
1240 pids[i] = pid;
1241 break;
1244 if (i >= max_kdcs) {
1245 /* This should not happen */
1246 kdc_log(context, config, 1,
1247 "warning: forked untracked child process: %d",
1248 (int)pid);
1250 kdc_log(context, config, 3, "KDC worker process started: %d",
1251 pid);
1252 num_kdcs++;
1253 /* Slow down the creation of KDCs... */
1254 select_sleep(12500);
1255 break;
1259 /* Closing these sockets should cause the kids to die... */
1261 close(islive[0]);
1262 close(islive[1]);
1264 /* Close our listener sockets before terminating workers */
1265 for (i = 0; i < ndescr; ++i)
1266 clear_descr(&d[i]);
1268 gettimeofday(&tv1, NULL);
1269 tv2 = tv1;
1271 /* Reap every 10ms, terminate stragglers once a second, give up after 10 */
1272 for (;;) {
1273 struct timeval tv3;
1274 num_kdcs -= reap_kids(context, config, pids, max_kdcs);
1275 if (num_kdcs == 0 && bonjour_pid <= 0)
1276 goto end;
1278 * Using select to sleep will fail with EINTR if we receive a
1279 * SIGCHLD. This is desirable.
1281 select_sleep(10000);
1282 gettimeofday(&tv3, NULL);
1283 if (tv3.tv_sec - tv1.tv_sec > 10 ||
1284 (tv3.tv_sec - tv1.tv_sec == 10 && tv3.tv_usec >= tv1.tv_usec))
1285 break;
1286 if (tv3.tv_sec - tv2.tv_sec > 1 ||
1287 (tv3.tv_sec - tv2.tv_sec == 1 && tv3.tv_usec >= tv2.tv_usec)) {
1288 kill_kids(pids, max_kdcs, SIGTERM);
1289 tv2 = tv3;
1293 /* Kill stragglers and reap every 200ms, give up after 15s */
1294 for (;;) {
1295 kill_kids(pids, max_kdcs, SIGKILL);
1296 num_kdcs -= reap_kids(context, config, pids, max_kdcs);
1297 if (num_kdcs == 0 && bonjour_pid <= 0)
1298 break;
1299 select_sleep(200000);
1300 gettimeofday(&tv2, NULL);
1301 if (tv2.tv_sec - tv1.tv_sec > 15 ||
1302 (tv2.tv_sec - tv1.tv_sec == 15 && tv2.tv_usec >= tv1.tv_usec))
1303 break;
1306 end:
1307 kdc_log(context, config, 3, "KDC master process exiting");
1308 } else {
1309 loop(context, config, &d, &ndescr, -1);
1310 kdc_log(context, config, 3, "KDC exiting");
1312 free(pids);
1313 #else
1314 loop(context, config, &d, &ndescr, -1);
1315 kdc_log(context, config, 3, "KDC exiting");
1316 #endif
1318 free(d);