krb5_kt_next_entry() needs to operate on a zero'd krb5_keytab_entry.
[heimdal.git] / kdc / connect.c
blobbc63f58a466cbd79e7d3ad613fadd5d24f1a3684
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 setsockopt(d->s, SOL_SOCKET, SO_REUSEADDR, (void *)&one, sizeof(one));
268 #endif
269 d->type = type;
270 d->port = port;
272 socket_set_nonblocking(d->s, 1);
274 if(rk_IS_SOCKET_ERROR(bind(d->s, sa, sa_size))){
275 char a_str[256];
276 size_t len;
278 krb5_print_address (a, a_str, sizeof(a_str), &len);
279 krb5_warn(context, errno, "bind %s/%d", a_str, ntohs(port));
280 rk_closesocket(d->s);
281 d->s = rk_INVALID_SOCKET;
282 return;
284 if(type == SOCK_STREAM && rk_IS_SOCKET_ERROR(listen(d->s, SOMAXCONN))){
285 char a_str[256];
286 size_t len;
288 krb5_print_address (a, a_str, sizeof(a_str), &len);
289 krb5_warn(context, errno, "listen %s/%d", a_str, ntohs(port));
290 rk_closesocket(d->s);
291 d->s = rk_INVALID_SOCKET;
292 return;
297 * Allocate descriptors for all the sockets that we should listen on
298 * and return the number of them.
301 static int
302 init_sockets(krb5_context context,
303 krb5_kdc_configuration *config,
304 struct descr **desc)
306 krb5_error_code ret;
307 size_t i, j;
308 struct descr *d;
309 int num = 0;
310 krb5_addresses addresses;
312 if (explicit_addresses.len) {
313 addresses = explicit_addresses;
314 } else {
315 ret = krb5_get_all_server_addrs (context, &addresses);
316 if (ret)
317 krb5_err (context, 1, ret, "krb5_get_all_server_addrs");
319 parse_ports(context, config, port_str);
320 d = malloc(addresses.len * num_ports * sizeof(*d));
321 if (d == NULL)
322 krb5_errx(context, 1, "malloc(%lu) failed",
323 (unsigned long)num_ports * sizeof(*d));
325 for (i = 0; i < num_ports; i++){
326 for (j = 0; j < addresses.len; ++j) {
327 init_socket(context, config, &d[num], &addresses.val[j],
328 ports[i].family, ports[i].type, ports[i].port);
329 if(d[num].s != rk_INVALID_SOCKET){
330 char a_str[80];
331 size_t len;
333 krb5_print_address (&addresses.val[j], a_str,
334 sizeof(a_str), &len);
336 kdc_log(context, config, 5, "listening on %s port %u/%s",
337 a_str,
338 ntohs(ports[i].port),
339 (ports[i].type == SOCK_STREAM) ? "tcp" : "udp");
340 /* XXX */
341 num++;
345 krb5_free_addresses (context, &addresses);
346 d = realloc(d, num * sizeof(*d));
347 if (d == NULL && num != 0)
348 krb5_errx(context, 1, "realloc(%lu) failed",
349 (unsigned long)num * sizeof(*d));
350 reinit_descrs (d, num);
351 *desc = d;
352 return num;
359 static const char *
360 descr_type(struct descr *d)
362 if (d->type == SOCK_DGRAM)
363 return "udp";
364 else if (d->type == SOCK_STREAM)
365 return "tcp";
366 return "unknown";
369 static void
370 addr_to_string(krb5_context context,
371 struct sockaddr *addr, size_t addr_len, char *str, size_t len)
373 krb5_address a;
374 if(krb5_sockaddr2address(context, addr, &a) == 0) {
375 if(krb5_print_address(&a, str, len, &len) == 0) {
376 krb5_free_address(context, &a);
377 return;
379 krb5_free_address(context, &a);
381 snprintf(str, len, "<family=%d>", addr->sa_family);
388 static void
389 send_reply(krb5_context context,
390 krb5_kdc_configuration *config,
391 krb5_boolean prependlength,
392 struct descr *d,
393 krb5_data *reply)
395 kdc_log(context, config, 5,
396 "sending %lu bytes to %s", (unsigned long)reply->length,
397 d->addr_string);
398 if(prependlength){
399 unsigned char l[4];
400 l[0] = (reply->length >> 24) & 0xff;
401 l[1] = (reply->length >> 16) & 0xff;
402 l[2] = (reply->length >> 8) & 0xff;
403 l[3] = reply->length & 0xff;
404 if(rk_IS_SOCKET_ERROR(sendto(d->s, l, sizeof(l), 0, d->sa, d->sock_len))) {
405 kdc_log (context, config,
406 0, "sendto(%s): %s", d->addr_string,
407 strerror(rk_SOCK_ERRNO));
408 return;
411 if(rk_IS_SOCKET_ERROR(sendto(d->s, reply->data, reply->length, 0, d->sa, d->sock_len))) {
412 kdc_log (context, config, 0, "sendto(%s): %s", d->addr_string,
413 strerror(rk_SOCK_ERRNO));
414 return;
419 * Handle the request in `buf, len' to socket `d'
422 static void
423 do_request(krb5_context context,
424 krb5_kdc_configuration *config,
425 void *buf, size_t len, krb5_boolean prependlength,
426 struct descr *d)
428 krb5_error_code ret;
429 krb5_data reply;
430 int datagram_reply = (d->type == SOCK_DGRAM);
432 krb5_kdc_update_time(NULL);
434 krb5_data_zero(&reply);
435 ret = krb5_kdc_process_request(context, config,
436 buf, len, &reply, &prependlength,
437 d->addr_string, d->sa,
438 datagram_reply);
439 if(request_log)
440 krb5_kdc_save_request(context, request_log, buf, len, &reply, d->sa);
441 if(reply.length){
442 send_reply(context, config, prependlength, d, &reply);
443 krb5_data_free(&reply);
445 if(ret)
446 kdc_log(context, config, 0,
447 "Failed processing %lu byte request from %s",
448 (unsigned long)len, d->addr_string);
452 * Handle incoming data to the UDP socket in `d'
455 static void
456 handle_udp(krb5_context context,
457 krb5_kdc_configuration *config,
458 struct descr *d)
460 unsigned char *buf;
461 ssize_t n;
463 buf = malloc(max_request_udp);
464 if (buf == NULL){
465 kdc_log(context, config, 0, "Failed to allocate %lu bytes",
466 (unsigned long)max_request_udp);
467 return;
470 d->sock_len = sizeof(d->__ss);
471 n = recvfrom(d->s, buf, max_request_udp, 0, d->sa, &d->sock_len);
472 if (rk_IS_SOCKET_ERROR(n)) {
473 if (rk_SOCK_ERRNO != EAGAIN && rk_SOCK_ERRNO != EINTR)
474 krb5_warn(context, rk_SOCK_ERRNO, "recvfrom");
475 } else {
476 addr_to_string (context, d->sa, d->sock_len,
477 d->addr_string, sizeof(d->addr_string));
478 if ((size_t)n == max_request_udp) {
479 krb5_data data;
480 krb5_warn(context, errno,
481 "recvfrom: truncated packet from %s, asking for TCP",
482 d->addr_string);
483 krb5_mk_error(context,
484 KRB5KRB_ERR_RESPONSE_TOO_BIG,
485 NULL,
486 NULL,
487 NULL,
488 NULL,
489 NULL,
490 NULL,
491 &data);
492 send_reply(context, config, FALSE, d, &data);
493 krb5_data_free(&data);
494 } else {
495 do_request(context, config, buf, n, FALSE, d);
498 free (buf);
501 static void
502 clear_descr(struct descr *d)
504 if(d->buf)
505 memset(d->buf, 0, d->size);
506 d->len = 0;
507 if(d->s != rk_INVALID_SOCKET)
508 rk_closesocket(d->s);
509 d->s = rk_INVALID_SOCKET;
513 /* remove HTTP %-quoting from buf */
514 static int
515 de_http(char *buf)
517 unsigned char *p, *q;
518 unsigned int x;
520 for (p = q = (unsigned char *)buf; *p; p++, q++) {
521 if (*p == '%') {
522 if (!(isxdigit(p[1]) && isxdigit(p[2])))
523 return -1;
525 if (sscanf((char *)p + 1, "%2x", &x) != 1)
526 return -1;
528 *q = x;
529 p += 2;
530 } else {
531 *q = *p;
534 *q = '\0';
535 return 0;
538 #define TCP_TIMEOUT 4
541 * accept a new TCP connection on `d[parent]' and store it in `d[child]'
544 static void
545 add_new_tcp (krb5_context context,
546 krb5_kdc_configuration *config,
547 struct descr *d, int parent, int child)
549 krb5_socket_t s;
551 if (child == -1)
552 return;
554 d[child].sock_len = sizeof(d[child].__ss);
555 s = accept(d[parent].s, d[child].sa, &d[child].sock_len);
556 if(rk_IS_BAD_SOCKET(s)) {
557 if (rk_SOCK_ERRNO != EAGAIN && rk_SOCK_ERRNO != EINTR)
558 krb5_warn(context, rk_SOCK_ERRNO, "accept");
559 return;
562 #ifdef FD_SETSIZE
563 if (s >= FD_SETSIZE) {
564 krb5_warnx(context, "socket FD too large");
565 rk_closesocket (s);
566 return;
568 #endif
570 d[child].s = s;
571 d[child].timeout = time(NULL) + TCP_TIMEOUT;
572 d[child].type = SOCK_STREAM;
573 addr_to_string (context,
574 d[child].sa, d[child].sock_len,
575 d[child].addr_string, sizeof(d[child].addr_string));
579 * Grow `d' to handle at least `n'.
580 * Return != 0 if fails
583 static int
584 grow_descr (krb5_context context,
585 krb5_kdc_configuration *config,
586 struct descr *d, size_t n)
588 if (d->size - d->len < n) {
589 unsigned char *tmp;
590 size_t grow;
592 grow = max(1024, d->len + n);
593 if (d->size + grow > max_request_tcp) {
594 kdc_log(context, config, 0, "Request exceeds max request size (%lu bytes).",
595 (unsigned long)d->size + grow);
596 clear_descr(d);
597 return -1;
599 tmp = realloc (d->buf, d->size + grow);
600 if (tmp == NULL) {
601 kdc_log(context, config, 0, "Failed to re-allocate %lu bytes.",
602 (unsigned long)d->size + grow);
603 clear_descr(d);
604 return -1;
606 d->size += grow;
607 d->buf = tmp;
609 return 0;
613 * Try to handle the TCP data at `d->buf, d->len'.
614 * Return -1 if failed, 0 if succesful, and 1 if data is complete.
617 static int
618 handle_vanilla_tcp (krb5_context context,
619 krb5_kdc_configuration *config,
620 struct descr *d)
622 krb5_storage *sp;
623 uint32_t len;
625 sp = krb5_storage_from_mem(d->buf, d->len);
626 if (sp == NULL) {
627 kdc_log (context, config, 0, "krb5_storage_from_mem failed");
628 return -1;
630 krb5_ret_uint32(sp, &len);
631 krb5_storage_free(sp);
632 if(d->len - 4 >= len) {
633 memmove(d->buf, d->buf + 4, d->len - 4);
634 d->len -= 4;
635 return 1;
637 return 0;
641 * Try to handle the TCP/HTTP data at `d->buf, d->len'.
642 * Return -1 if failed, 0 if succesful, and 1 if data is complete.
645 static int
646 handle_http_tcp (krb5_context context,
647 krb5_kdc_configuration *config,
648 struct descr *d)
650 char *s, *p, *t;
651 void *data;
652 char *proto;
653 int len;
655 s = (char *)d->buf;
657 /* If its a multi line query, truncate off the first line */
658 p = strstr(s, "\r\n");
659 if (p)
660 *p = 0;
662 p = NULL;
663 t = strtok_r(s, " \t", &p);
664 if (t == NULL) {
665 kdc_log(context, config, 0,
666 "Missing HTTP operand (GET) request from %s", d->addr_string);
667 return -1;
670 t = strtok_r(NULL, " \t", &p);
671 if(t == NULL) {
672 kdc_log(context, config, 0,
673 "Missing HTTP GET data in request from %s", d->addr_string);
674 return -1;
677 data = malloc(strlen(t));
678 if (data == NULL) {
679 kdc_log(context, config, 0, "Failed to allocate %lu bytes",
680 (unsigned long)strlen(t));
681 return -1;
683 if(*t == '/')
684 t++;
685 if(de_http(t) != 0) {
686 kdc_log(context, config, 0, "Malformed HTTP request from %s", d->addr_string);
687 kdc_log(context, config, 5, "HTTP request: %s", t);
688 free(data);
689 return -1;
691 proto = strtok_r(NULL, " \t", &p);
692 if (proto == NULL) {
693 kdc_log(context, config, 0, "Malformed HTTP request from %s", d->addr_string);
694 free(data);
695 return -1;
697 len = rk_base64_decode(t, data);
698 if(len <= 0){
699 const char *msg =
700 " 404 Not found\r\n"
701 "Server: Heimdal/" VERSION "\r\n"
702 "Cache-Control: no-cache\r\n"
703 "Pragma: no-cache\r\n"
704 "Content-type: text/html\r\n"
705 "Content-transfer-encoding: 8bit\r\n\r\n"
706 "<TITLE>404 Not found</TITLE>\r\n"
707 "<H1>404 Not found</H1>\r\n"
708 "That page doesn't exist, maybe you are looking for "
709 "<A HREF=\"http://www.h5l.org/\">Heimdal</A>?\r\n";
710 kdc_log(context, config, 0, "HTTP request from %s is non KDC request", d->addr_string);
711 kdc_log(context, config, 5, "HTTP request: %s", t);
712 free(data);
713 if (rk_IS_SOCKET_ERROR(send(d->s, proto, strlen(proto), 0))) {
714 kdc_log(context, config, 0, "HTTP write failed: %s: %s",
715 d->addr_string, strerror(rk_SOCK_ERRNO));
716 return -1;
718 if (rk_IS_SOCKET_ERROR(send(d->s, msg, strlen(msg), 0))) {
719 kdc_log(context, config, 0, "HTTP write failed: %s: %s",
720 d->addr_string, strerror(rk_SOCK_ERRNO));
721 return -1;
723 return -1;
726 const char *msg =
727 " 200 OK\r\n"
728 "Server: Heimdal/" VERSION "\r\n"
729 "Cache-Control: no-cache\r\n"
730 "Pragma: no-cache\r\n"
731 "Content-type: application/octet-stream\r\n"
732 "Content-transfer-encoding: binary\r\n\r\n";
733 if (rk_IS_SOCKET_ERROR(send(d->s, proto, strlen(proto), 0))) {
734 free(data);
735 kdc_log(context, config, 0, "HTTP write failed: %s: %s",
736 d->addr_string, strerror(rk_SOCK_ERRNO));
737 return -1;
739 if (rk_IS_SOCKET_ERROR(send(d->s, msg, strlen(msg), 0))) {
740 free(data);
741 kdc_log(context, config, 0, "HTTP write failed: %s: %s",
742 d->addr_string, strerror(rk_SOCK_ERRNO));
743 return -1;
746 if ((size_t)len > d->len)
747 len = d->len;
748 memcpy(d->buf, data, len);
749 d->len = len;
750 free(data);
751 return 1;
755 * Handle incoming data to the TCP socket in `d[index]'
758 static void
759 handle_tcp(krb5_context context,
760 krb5_kdc_configuration *config,
761 struct descr *d, int idx, int min_free)
763 unsigned char buf[1024];
764 int n;
765 int ret = 0;
767 if (d[idx].timeout == 0) {
768 add_new_tcp (context, config, d, idx, min_free);
769 return;
772 n = recvfrom(d[idx].s, buf, sizeof(buf), 0, NULL, NULL);
773 if(rk_IS_SOCKET_ERROR(n)){
774 krb5_warn(context, rk_SOCK_ERRNO, "recvfrom failed from %s to %s/%d",
775 d[idx].addr_string, descr_type(d + idx),
776 ntohs(d[idx].port));
777 return;
778 } else if (n == 0) {
779 krb5_warnx(context, "connection closed before end of data after %lu "
780 "bytes from %s to %s/%d", (unsigned long)d[idx].len,
781 d[idx].addr_string, descr_type(d + idx),
782 ntohs(d[idx].port));
783 clear_descr (d + idx);
784 return;
786 if (grow_descr (context, config, &d[idx], n))
787 return;
788 memcpy(d[idx].buf + d[idx].len, buf, n);
789 d[idx].len += n;
790 if(d[idx].len > 4 && d[idx].buf[0] == 0) {
791 ret = handle_vanilla_tcp (context, config, &d[idx]);
792 } else if(enable_http &&
793 d[idx].len >= 4 &&
794 strncmp((char *)d[idx].buf, "GET ", 4) == 0 &&
795 strncmp((char *)d[idx].buf + d[idx].len - 4,
796 "\r\n\r\n", 4) == 0) {
798 /* remove the trailing \r\n\r\n so the string is NUL terminated */
799 d[idx].buf[d[idx].len - 4] = '\0';
801 ret = handle_http_tcp (context, config, &d[idx]);
802 if (ret < 0)
803 clear_descr (d + idx);
804 } else if (d[idx].len > 4) {
805 kdc_log (context, config,
806 0, "TCP data of strange type from %s to %s/%d",
807 d[idx].addr_string, descr_type(d + idx),
808 ntohs(d[idx].port));
809 if (d[idx].buf[0] & 0x80) {
810 krb5_data reply;
812 kdc_log (context, config, 0, "TCP extension not supported");
814 ret = krb5_mk_error(context,
815 KRB5KRB_ERR_FIELD_TOOLONG,
816 NULL,
817 NULL,
818 NULL,
819 NULL,
820 NULL,
821 NULL,
822 &reply);
823 if (ret == 0) {
824 send_reply(context, config, TRUE, d + idx, &reply);
825 krb5_data_free(&reply);
828 clear_descr(d + idx);
829 return;
831 if (ret < 0)
832 return;
833 else if (ret == 1) {
834 do_request(context, config,
835 d[idx].buf, d[idx].len, TRUE, &d[idx]);
836 clear_descr(d + idx);
840 #ifdef HAVE_FORK
841 static void
842 handle_islive(int fd)
844 char buf;
845 int ret;
847 ret = read(fd, &buf, 1);
848 if (ret != 1)
849 exit_flag = -1;
851 #endif
853 krb5_boolean
854 realloc_descrs(struct descr **d, unsigned int *ndescr)
856 struct descr *tmp;
857 size_t i;
859 tmp = realloc(*d, (*ndescr + 4) * sizeof(**d));
860 if(tmp == NULL)
861 return FALSE;
863 *d = tmp;
864 reinit_descrs (*d, *ndescr);
865 memset(*d + *ndescr, 0, 4 * sizeof(**d));
866 for(i = *ndescr; i < *ndescr + 4; i++)
867 init_descr (*d + i);
869 *ndescr += 4;
871 return TRUE;
875 next_min_free(krb5_context context, struct descr **d, unsigned int *ndescr)
877 size_t i;
878 int min_free;
880 for(i = 0; i < *ndescr; i++) {
881 int s = (*d + i)->s;
882 if(rk_IS_BAD_SOCKET(s))
883 return i;
886 min_free = *ndescr;
887 if(!realloc_descrs(d, ndescr)) {
888 min_free = -1;
889 krb5_warnx(context, "No memory");
892 return min_free;
895 static void
896 loop(krb5_context context, krb5_kdc_configuration *config,
897 struct descr *d, unsigned int ndescr, int islive)
900 while (exit_flag == 0) {
901 struct timeval tmout;
902 fd_set fds;
903 int min_free = -1;
904 int max_fd = 0;
905 size_t i;
907 FD_ZERO(&fds);
908 if (islive > -1) {
909 FD_SET(islive, &fds);
910 max_fd = islive;
912 for (i = 0; i < ndescr; i++) {
913 if (!rk_IS_BAD_SOCKET(d[i].s)) {
914 if (d[i].type == SOCK_STREAM &&
915 d[i].timeout && d[i].timeout < time(NULL)) {
916 kdc_log(context, config, 1,
917 "TCP-connection from %s expired after %lu bytes",
918 d[i].addr_string, (unsigned long)d[i].len);
919 clear_descr(&d[i]);
920 continue;
922 #ifndef NO_LIMIT_FD_SETSIZE
923 if (max_fd < d[i].s)
924 max_fd = d[i].s;
925 #ifdef FD_SETSIZE
926 if (max_fd >= FD_SETSIZE)
927 krb5_errx(context, 1, "fd too large");
928 #endif
929 #endif
930 FD_SET(d[i].s, &fds);
934 tmout.tv_sec = TCP_TIMEOUT;
935 tmout.tv_usec = 0;
936 switch(select(max_fd + 1, &fds, 0, 0, &tmout)){
937 case 0:
938 break;
939 case -1:
940 if (errno != EINTR)
941 krb5_warn(context, rk_SOCK_ERRNO, "select");
942 break;
943 default:
944 #ifdef HAVE_FORK
945 if (islive > -1 && FD_ISSET(islive, &fds))
946 handle_islive(islive);
947 #endif
948 for (i = 0; i < ndescr; i++)
949 if (!rk_IS_BAD_SOCKET(d[i].s) && FD_ISSET(d[i].s, &fds)) {
950 min_free = next_min_free(context, &d, &ndescr);
952 if (d[i].type == SOCK_DGRAM)
953 handle_udp(context, config, &d[i]);
954 else if (d[i].type == SOCK_STREAM)
955 handle_tcp(context, config, d, i, min_free);
960 switch (exit_flag) {
961 case -1:
962 kdc_log(context, config, 0,
963 "KDC worker process exiting because KDC master exited.");
964 break;
965 #ifdef SIGXCPU
966 case SIGXCPU:
967 kdc_log(context, config, 0, "CPU time limit exceeded");
968 break;
969 #endif
970 case SIGINT:
971 case SIGTERM:
972 kdc_log(context, config, 0, "Terminated");
973 break;
974 default:
975 kdc_log(context, config, 0, "Unexpected exit reason: %d", exit_flag);
976 break;
980 #ifdef __APPLE__
981 static void
982 bonjour_kid(krb5_context context, krb5_kdc_configuration *config, const char *argv0, int *islive)
984 char buf;
986 if (do_bonjour > 0) {
987 bonjour_announce(context, config);
989 while (read(0, &buf, 1) == 1)
990 continue;
991 _exit(0);
994 if ((bonjour_pid = fork()) != 0)
995 return;
997 close(islive[0]);
998 if (dup2(islive[1], 0) == -1)
999 err(1, "failed to announce with bonjour (dup)");
1000 if (islive[1] != 0)
1001 close(islive[1]);
1002 execlp(argv0, "kdc", "--bonjour", NULL);
1003 err(1, "failed to announce with bonjour (exec)");
1005 #endif
1007 #ifdef HAVE_FORK
1008 static void
1009 kill_kids(pid_t *pids, int max_kids, int sig)
1011 int i;
1013 for (i=0; i < max_kids; i++)
1014 if (pids[i] > 0)
1015 kill(sig, pids[i]);
1016 if (bonjour_pid > 0)
1017 kill(sig, bonjour_pid);
1020 static int
1021 reap_kid(krb5_context context, krb5_kdc_configuration *config,
1022 pid_t *pids, int max_kids, int options)
1024 pid_t pid;
1025 char *what;
1026 int status;
1027 int i = 0; /* quiet warnings */
1029 pid = waitpid(-1, &status, options);
1030 if (pid < 1)
1031 return 0;
1033 if (pid != bonjour_pid) {
1034 for (i=0; i < max_kids; i++) {
1035 if (pids[i] == pid)
1036 break;
1039 if (i == max_kids) {
1040 /* XXXrcd: this should not happen, have to do something, though */
1041 return 0;
1045 if (pid == bonjour_pid)
1046 what = "bonjour";
1047 else
1048 what = "worker";
1049 if (WIFEXITED(status))
1050 kdc_log(context, config, 0, "KDC reaped %s process: %d, exit status: %d",
1051 what, (int)pid, WEXITSTATUS(status));
1052 else if (WIFSIGNALED(status))
1053 kdc_log(context, config, 0, "KDC reaped %s process: %d, term signal %d%s",
1054 what, (int)pid, WTERMSIG(status),
1055 WCOREDUMP(status) ? " (core dumped)" : "");
1056 else
1057 kdc_log(context, config, 0, "KDC reaped %s process: %d",
1058 what, (int)pid);
1059 if (pid == bonjour_pid) {
1060 bonjour_pid = (pid_t)-1;
1061 return 0;
1062 } else {
1063 pids[i] = (pid_t)-1;
1064 return 1;
1068 static int
1069 reap_kids(krb5_context context, krb5_kdc_configuration *config,
1070 pid_t *pids, int max_kids)
1072 int reaped = 0;
1074 for (;;) {
1075 if (reap_kid(context, config, pids, max_kids, WNOHANG) == 0)
1076 break;
1077 reaped++;
1080 return reaped;
1083 static void
1084 select_sleep(int microseconds)
1086 struct timeval tv;
1088 tv.tv_sec = microseconds / 1000000;
1089 tv.tv_usec = microseconds % 1000000;
1090 select(0, NULL, NULL, NULL, &tv);
1092 #endif
1094 void
1095 start_kdc(krb5_context context,
1096 krb5_kdc_configuration *config, const char *argv0)
1098 struct timeval tv1;
1099 struct timeval tv2;
1100 struct descr *d;
1101 unsigned int ndescr;
1102 pid_t pid = -1;
1103 #ifdef HAVE_FORK
1104 pid_t *pids;
1105 int max_kdcs = config->num_kdc_processes;
1106 int num_kdcs = 0;
1107 int i;
1108 int islive[2];
1109 #endif
1111 #ifdef __APPLE__
1112 if (do_bonjour > 0)
1113 bonjour_kid(context, config, argv0, NULL);
1114 #endif
1116 #ifdef HAVE_FORK
1117 #ifdef _SC_NPROCESSORS_ONLN
1118 if (max_kdcs < 1)
1119 max_kdcs = sysconf(_SC_NPROCESSORS_ONLN);
1120 #endif
1122 if (max_kdcs < 1)
1123 max_kdcs = 1;
1125 pids = calloc(max_kdcs, sizeof(*pids));
1126 if (!pids)
1127 krb5_err(context, 1, errno, "malloc");
1130 * We open a socketpair of which we hand one end to each of our kids.
1131 * When we exit, for whatever reason, the children will notice an EOF
1132 * on their end and be able to cleanly exit.
1135 if (socketpair(PF_LOCAL, SOCK_STREAM, 0, islive) == -1)
1136 krb5_errx(context, 1, "socketpair");
1137 socket_set_nonblocking(islive[1], 1);
1138 #endif
1140 ndescr = init_sockets(context, config, &d);
1141 if(ndescr <= 0)
1142 krb5_errx(context, 1, "No sockets!");
1144 #ifdef HAVE_FORK
1146 # ifdef __APPLE__
1147 if (do_bonjour < 0)
1148 bonjour_kid(context, config, argv0, islive);
1149 # endif
1151 kdc_log(context, config, 0, "KDC started master process pid=%d", getpid());
1152 #else
1153 kdc_log(context, config, 0, "KDC started pid=%d", getpid());
1154 #endif
1156 roken_detach_finish(NULL, daemon_child);
1158 tv1.tv_sec = 0;
1159 tv1.tv_usec = 0;
1161 #ifdef HAVE_FORK
1162 if (!testing_flag) {
1163 /* Note that we might never execute the body of this loop */
1164 while (exit_flag == 0) {
1166 /* Slow down the creation of KDCs... */
1168 gettimeofday(&tv2, NULL);
1169 if (tv1.tv_sec == tv2.tv_sec && tv2.tv_usec - tv1.tv_usec < 25000) {
1170 #if 0 /* XXXrcd: should print a message... */
1171 kdc_log(context, config, 0, "Spawning KDCs too quickly, "
1172 "pausing for 50ms");
1173 #endif
1174 select_sleep(12500);
1175 continue;
1178 if (num_kdcs >= max_kdcs) {
1179 num_kdcs -= reap_kid(context, config, pids, max_kdcs, 0);
1180 continue;
1183 if (num_kdcs > 0)
1184 num_kdcs -= reap_kids(context, config, pids, max_kdcs);
1186 pid = fork();
1187 switch (pid) {
1188 case 0:
1189 close(islive[0]);
1190 loop(context, config, d, ndescr, islive[1]);
1191 exit(0);
1192 case -1:
1193 /* XXXrcd: hmmm, do something useful?? */
1194 kdc_log(context, config, 0,
1195 "KDC master process could not fork worker process");
1196 sleep(10);
1197 break;
1198 default:
1199 for (i=0; i < max_kdcs; i++) {
1200 if (pids[i] == 0) {
1201 pids[i] = pid;
1202 break;
1205 kdc_log(context, config, 0, "KDC worker process started: %d",
1206 pid);
1207 num_kdcs++;
1208 gettimeofday(&tv1, NULL);
1209 break;
1213 /* Closing these sockets should cause the kids to die... */
1215 close(islive[0]);
1216 close(islive[1]);
1218 /* Close our listener sockets before terminating workers */
1219 for (i = 0; i < ndescr; ++i)
1220 clear_descr(&d[i]);
1222 gettimeofday(&tv1, NULL);
1223 tv2 = tv1;
1225 /* Reap every 10ms, terminate stragglers once a second, give up after 10 */
1226 for (;;) {
1227 struct timeval tv3;
1228 num_kdcs -= reap_kids(context, config, pids, max_kdcs);
1229 if (num_kdcs == 0 && bonjour_pid <= 0)
1230 goto end;
1232 * Using select to sleep will fail with EINTR if we receive a
1233 * SIGCHLD. This is desirable.
1235 select_sleep(10000);
1236 gettimeofday(&tv3, NULL);
1237 if (tv3.tv_sec - tv1.tv_sec > 10 ||
1238 (tv3.tv_sec - tv1.tv_sec == 10 && tv3.tv_usec >= tv1.tv_usec))
1239 break;
1240 if (tv3.tv_sec - tv2.tv_sec > 1 ||
1241 (tv3.tv_sec - tv2.tv_sec == 1 && tv3.tv_usec >= tv2.tv_usec)) {
1242 kill_kids(pids, max_kdcs, SIGTERM);
1243 tv2 = tv3;
1247 /* Kill stragglers and reap every 200ms, give up after 15s */
1248 for (;;) {
1249 kill_kids(pids, max_kdcs, SIGKILL);
1250 num_kdcs -= reap_kids(context, config, pids, max_kdcs);
1251 if (num_kdcs == 0 && bonjour_pid <= 0)
1252 break;
1253 select_sleep(200000);
1254 gettimeofday(&tv2, NULL);
1255 if (tv2.tv_sec - tv1.tv_sec > 15 ||
1256 (tv2.tv_sec - tv1.tv_sec == 15 && tv2.tv_usec >= tv1.tv_usec))
1257 break;
1260 end:
1261 kdc_log(context, config, 0, "KDC master process exiting", pid);
1262 free(pids);
1263 } else {
1264 loop(context, config, d, ndescr, -1);
1265 kdc_log(context, config, 0, "KDC exiting", pid);
1267 #else
1268 loop(context, config, d, ndescr, -1);
1269 kdc_log(context, config, 0, "KDC exiting", pid);
1270 #endif
1272 free(d);