Upstream NetBSD libedit has readline.h in readline/ not editline/
[heimdal.git] / kdc / connect.c
blob628f9352674dbf7fd739cda8319c33be1b257113
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 for(p = q = (unsigned char *)buf; *p; p++, q++) {
519 if(*p == '%' && isxdigit(p[1]) && isxdigit(p[2])) {
520 unsigned int x;
521 if(sscanf((char *)p + 1, "%2x", &x) != 1)
522 return -1;
523 *q = x;
524 p += 2;
525 } else
526 *q = *p;
528 *q = '\0';
529 return 0;
532 #define TCP_TIMEOUT 4
535 * accept a new TCP connection on `d[parent]' and store it in `d[child]'
538 static void
539 add_new_tcp (krb5_context context,
540 krb5_kdc_configuration *config,
541 struct descr *d, int parent, int child)
543 krb5_socket_t s;
545 if (child == -1)
546 return;
548 d[child].sock_len = sizeof(d[child].__ss);
549 s = accept(d[parent].s, d[child].sa, &d[child].sock_len);
550 if(rk_IS_BAD_SOCKET(s)) {
551 if (rk_SOCK_ERRNO != EAGAIN && rk_SOCK_ERRNO != EINTR)
552 krb5_warn(context, rk_SOCK_ERRNO, "accept");
553 return;
556 #ifdef FD_SETSIZE
557 if (s >= FD_SETSIZE) {
558 krb5_warnx(context, "socket FD too large");
559 rk_closesocket (s);
560 return;
562 #endif
564 d[child].s = s;
565 d[child].timeout = time(NULL) + TCP_TIMEOUT;
566 d[child].type = SOCK_STREAM;
567 addr_to_string (context,
568 d[child].sa, d[child].sock_len,
569 d[child].addr_string, sizeof(d[child].addr_string));
573 * Grow `d' to handle at least `n'.
574 * Return != 0 if fails
577 static int
578 grow_descr (krb5_context context,
579 krb5_kdc_configuration *config,
580 struct descr *d, size_t n)
582 if (d->size - d->len < n) {
583 unsigned char *tmp;
584 size_t grow;
586 grow = max(1024, d->len + n);
587 if (d->size + grow > max_request_tcp) {
588 kdc_log(context, config, 0, "Request exceeds max request size (%lu bytes).",
589 (unsigned long)d->size + grow);
590 clear_descr(d);
591 return -1;
593 tmp = realloc (d->buf, d->size + grow);
594 if (tmp == NULL) {
595 kdc_log(context, config, 0, "Failed to re-allocate %lu bytes.",
596 (unsigned long)d->size + grow);
597 clear_descr(d);
598 return -1;
600 d->size += grow;
601 d->buf = tmp;
603 return 0;
607 * Try to handle the TCP data at `d->buf, d->len'.
608 * Return -1 if failed, 0 if succesful, and 1 if data is complete.
611 static int
612 handle_vanilla_tcp (krb5_context context,
613 krb5_kdc_configuration *config,
614 struct descr *d)
616 krb5_storage *sp;
617 uint32_t len;
619 sp = krb5_storage_from_mem(d->buf, d->len);
620 if (sp == NULL) {
621 kdc_log (context, config, 0, "krb5_storage_from_mem failed");
622 return -1;
624 krb5_ret_uint32(sp, &len);
625 krb5_storage_free(sp);
626 if(d->len - 4 >= len) {
627 memmove(d->buf, d->buf + 4, d->len - 4);
628 d->len -= 4;
629 return 1;
631 return 0;
635 * Try to handle the TCP/HTTP data at `d->buf, d->len'.
636 * Return -1 if failed, 0 if succesful, and 1 if data is complete.
639 static int
640 handle_http_tcp (krb5_context context,
641 krb5_kdc_configuration *config,
642 struct descr *d)
644 char *s, *p, *t;
645 void *data;
646 char *proto;
647 int len;
649 s = (char *)d->buf;
651 /* If its a multi line query, truncate off the first line */
652 p = strstr(s, "\r\n");
653 if (p)
654 *p = 0;
656 p = NULL;
657 t = strtok_r(s, " \t", &p);
658 if (t == NULL) {
659 kdc_log(context, config, 0,
660 "Missing HTTP operand (GET) request from %s", d->addr_string);
661 return -1;
664 t = strtok_r(NULL, " \t", &p);
665 if(t == NULL) {
666 kdc_log(context, config, 0,
667 "Missing HTTP GET data in request from %s", d->addr_string);
668 return -1;
671 data = malloc(strlen(t));
672 if (data == NULL) {
673 kdc_log(context, config, 0, "Failed to allocate %lu bytes",
674 (unsigned long)strlen(t));
675 return -1;
677 if(*t == '/')
678 t++;
679 if(de_http(t) != 0) {
680 kdc_log(context, config, 0, "Malformed HTTP request from %s", d->addr_string);
681 kdc_log(context, config, 5, "HTTP request: %s", t);
682 free(data);
683 return -1;
685 proto = strtok_r(NULL, " \t", &p);
686 if (proto == NULL) {
687 kdc_log(context, config, 0, "Malformed HTTP request from %s", d->addr_string);
688 free(data);
689 return -1;
691 len = rk_base64_decode(t, data);
692 if(len <= 0){
693 const char *msg =
694 " 404 Not found\r\n"
695 "Server: Heimdal/" VERSION "\r\n"
696 "Cache-Control: no-cache\r\n"
697 "Pragma: no-cache\r\n"
698 "Content-type: text/html\r\n"
699 "Content-transfer-encoding: 8bit\r\n\r\n"
700 "<TITLE>404 Not found</TITLE>\r\n"
701 "<H1>404 Not found</H1>\r\n"
702 "That page doesn't exist, maybe you are looking for "
703 "<A HREF=\"http://www.h5l.org/\">Heimdal</A>?\r\n";
704 kdc_log(context, config, 0, "HTTP request from %s is non KDC request", d->addr_string);
705 kdc_log(context, config, 5, "HTTP request: %s", t);
706 free(data);
707 if (rk_IS_SOCKET_ERROR(send(d->s, proto, strlen(proto), 0))) {
708 kdc_log(context, config, 0, "HTTP write failed: %s: %s",
709 d->addr_string, strerror(rk_SOCK_ERRNO));
710 return -1;
712 if (rk_IS_SOCKET_ERROR(send(d->s, msg, strlen(msg), 0))) {
713 kdc_log(context, config, 0, "HTTP write failed: %s: %s",
714 d->addr_string, strerror(rk_SOCK_ERRNO));
715 return -1;
717 return -1;
720 const char *msg =
721 " 200 OK\r\n"
722 "Server: Heimdal/" VERSION "\r\n"
723 "Cache-Control: no-cache\r\n"
724 "Pragma: no-cache\r\n"
725 "Content-type: application/octet-stream\r\n"
726 "Content-transfer-encoding: binary\r\n\r\n";
727 if (rk_IS_SOCKET_ERROR(send(d->s, proto, strlen(proto), 0))) {
728 free(data);
729 kdc_log(context, config, 0, "HTTP write failed: %s: %s",
730 d->addr_string, strerror(rk_SOCK_ERRNO));
731 return -1;
733 if (rk_IS_SOCKET_ERROR(send(d->s, msg, strlen(msg), 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;
740 if ((size_t)len > d->len)
741 len = d->len;
742 memcpy(d->buf, data, len);
743 d->len = len;
744 free(data);
745 return 1;
749 * Handle incoming data to the TCP socket in `d[index]'
752 static void
753 handle_tcp(krb5_context context,
754 krb5_kdc_configuration *config,
755 struct descr *d, int idx, int min_free)
757 unsigned char buf[1024];
758 int n;
759 int ret = 0;
761 if (d[idx].timeout == 0) {
762 add_new_tcp (context, config, d, idx, min_free);
763 return;
766 n = recvfrom(d[idx].s, buf, sizeof(buf), 0, NULL, NULL);
767 if(rk_IS_SOCKET_ERROR(n)){
768 krb5_warn(context, rk_SOCK_ERRNO, "recvfrom failed from %s to %s/%d",
769 d[idx].addr_string, descr_type(d + idx),
770 ntohs(d[idx].port));
771 return;
772 } else if (n == 0) {
773 krb5_warnx(context, "connection closed before end of data after %lu "
774 "bytes from %s to %s/%d", (unsigned long)d[idx].len,
775 d[idx].addr_string, descr_type(d + idx),
776 ntohs(d[idx].port));
777 clear_descr (d + idx);
778 return;
780 if (grow_descr (context, config, &d[idx], n))
781 return;
782 memcpy(d[idx].buf + d[idx].len, buf, n);
783 d[idx].len += n;
784 if(d[idx].len > 4 && d[idx].buf[0] == 0) {
785 ret = handle_vanilla_tcp (context, config, &d[idx]);
786 } else if(enable_http &&
787 d[idx].len >= 4 &&
788 strncmp((char *)d[idx].buf, "GET ", 4) == 0 &&
789 strncmp((char *)d[idx].buf + d[idx].len - 4,
790 "\r\n\r\n", 4) == 0) {
792 /* remove the trailing \r\n\r\n so the string is NUL terminated */
793 d[idx].buf[d[idx].len - 4] = '\0';
795 ret = handle_http_tcp (context, config, &d[idx]);
796 if (ret < 0)
797 clear_descr (d + idx);
798 } else if (d[idx].len > 4) {
799 kdc_log (context, config,
800 0, "TCP data of strange type from %s to %s/%d",
801 d[idx].addr_string, descr_type(d + idx),
802 ntohs(d[idx].port));
803 if (d[idx].buf[0] & 0x80) {
804 krb5_data reply;
806 kdc_log (context, config, 0, "TCP extension not supported");
808 ret = krb5_mk_error(context,
809 KRB5KRB_ERR_FIELD_TOOLONG,
810 NULL,
811 NULL,
812 NULL,
813 NULL,
814 NULL,
815 NULL,
816 &reply);
817 if (ret == 0) {
818 send_reply(context, config, TRUE, d + idx, &reply);
819 krb5_data_free(&reply);
822 clear_descr(d + idx);
823 return;
825 if (ret < 0)
826 return;
827 else if (ret == 1) {
828 do_request(context, config,
829 d[idx].buf, d[idx].len, TRUE, &d[idx]);
830 clear_descr(d + idx);
834 #ifdef HAVE_FORK
835 static void
836 handle_islive(int fd)
838 char buf;
839 int ret;
841 ret = read(fd, &buf, 1);
842 if (ret != 1)
843 exit_flag = -1;
845 #endif
847 krb5_boolean
848 realloc_descrs(struct descr **d, unsigned int *ndescr)
850 struct descr *tmp;
851 size_t i;
853 tmp = realloc(*d, (*ndescr + 4) * sizeof(**d));
854 if(tmp == NULL)
855 return FALSE;
857 *d = tmp;
858 reinit_descrs (*d, *ndescr);
859 memset(*d + *ndescr, 0, 4 * sizeof(**d));
860 for(i = *ndescr; i < *ndescr + 4; i++)
861 init_descr (*d + i);
863 *ndescr += 4;
865 return TRUE;
869 next_min_free(krb5_context context, struct descr **d, unsigned int *ndescr)
871 size_t i;
872 int min_free;
874 for(i = 0; i < *ndescr; i++) {
875 int s = (*d + i)->s;
876 if(rk_IS_BAD_SOCKET(s))
877 return i;
880 min_free = *ndescr;
881 if(!realloc_descrs(d, ndescr)) {
882 min_free = -1;
883 krb5_warnx(context, "No memory");
886 return min_free;
889 static void
890 loop(krb5_context context, krb5_kdc_configuration *config,
891 struct descr *d, unsigned int ndescr, int islive)
894 while (exit_flag == 0) {
895 struct timeval tmout;
896 fd_set fds;
897 int min_free = -1;
898 int max_fd = 0;
899 size_t i;
901 FD_ZERO(&fds);
902 if (islive > -1) {
903 FD_SET(islive, &fds);
904 max_fd = islive;
906 for (i = 0; i < ndescr; i++) {
907 if (!rk_IS_BAD_SOCKET(d[i].s)) {
908 if (d[i].type == SOCK_STREAM &&
909 d[i].timeout && d[i].timeout < time(NULL)) {
910 kdc_log(context, config, 1,
911 "TCP-connection from %s expired after %lu bytes",
912 d[i].addr_string, (unsigned long)d[i].len);
913 clear_descr(&d[i]);
914 continue;
916 #ifndef NO_LIMIT_FD_SETSIZE
917 if (max_fd < d[i].s)
918 max_fd = d[i].s;
919 #ifdef FD_SETSIZE
920 if (max_fd >= FD_SETSIZE)
921 krb5_errx(context, 1, "fd too large");
922 #endif
923 #endif
924 FD_SET(d[i].s, &fds);
928 tmout.tv_sec = TCP_TIMEOUT;
929 tmout.tv_usec = 0;
930 switch(select(max_fd + 1, &fds, 0, 0, &tmout)){
931 case 0:
932 break;
933 case -1:
934 if (errno != EINTR)
935 krb5_warn(context, rk_SOCK_ERRNO, "select");
936 break;
937 default:
938 #ifdef HAVE_FORK
939 if (islive > -1 && FD_ISSET(islive, &fds))
940 handle_islive(islive);
941 #endif
942 for (i = 0; i < ndescr; i++)
943 if (!rk_IS_BAD_SOCKET(d[i].s) && FD_ISSET(d[i].s, &fds)) {
944 min_free = next_min_free(context, &d, &ndescr);
946 if (d[i].type == SOCK_DGRAM)
947 handle_udp(context, config, &d[i]);
948 else if (d[i].type == SOCK_STREAM)
949 handle_tcp(context, config, d, i, min_free);
954 switch (exit_flag) {
955 case -1:
956 kdc_log(context, config, 0,
957 "KDC worker process exiting because KDC master exited.");
958 break;
959 #ifdef SIGXCPU
960 case SIGXCPU:
961 kdc_log(context, config, 0, "CPU time limit exceeded");
962 break;
963 #endif
964 case SIGINT:
965 case SIGTERM:
966 kdc_log(context, config, 0, "Terminated");
967 break;
968 default:
969 kdc_log(context, config, 0, "Unexpected exit reason: %d", exit_flag);
970 break;
974 #ifdef __APPLE__
975 static void
976 bonjour_kid(krb5_context context, krb5_kdc_configuration *config, const char *argv0, int *islive)
978 char buf;
980 if (do_bonjour > 0) {
981 bonjour_announce(context, config);
983 while (read(0, &buf, 1) == 1)
984 continue;
985 _exit(0);
988 if ((bonjour_pid = fork()) != 0)
989 return;
991 close(islive[0]);
992 if (dup2(islive[1], 0) == -1)
993 err(1, "failed to announce with bonjour (dup)");
994 if (islive[1] != 0)
995 close(islive[1]);
996 execlp(argv0, "kdc", "--bonjour", NULL);
997 err(1, "failed to announce with bonjour (exec)");
999 #endif
1001 #ifdef HAVE_FORK
1002 static void
1003 kill_kids(pid_t *pids, int max_kids, int sig)
1005 int i;
1007 for (i=0; i < max_kids; i++)
1008 if (pids[i] > 0)
1009 kill(sig, pids[i]);
1010 if (bonjour_pid > 0)
1011 kill(sig, bonjour_pid);
1014 static int
1015 reap_kid(krb5_context context, krb5_kdc_configuration *config,
1016 pid_t *pids, int max_kids, int options)
1018 pid_t pid;
1019 char *what;
1020 int status;
1021 int i;
1023 pid = waitpid(-1, &status, options);
1024 if (pid < 1)
1025 return 0;
1027 if (pid != bonjour_pid) {
1028 for (i=0; i < max_kids; i++) {
1029 if (pids[i] == pid)
1030 break;
1033 if (i == max_kids) {
1034 /* XXXrcd: this should not happen, have to do something, though */
1035 return 0;
1039 if (pid == bonjour_pid)
1040 what = "bonjour";
1041 else
1042 what = "worker";
1043 if (WIFEXITED(status))
1044 kdc_log(context, config, 0, "KDC reaped %s process: %d, exit status: %d",
1045 what, (int)pid, WEXITSTATUS(status));
1046 else if (WIFSIGNALED(status))
1047 kdc_log(context, config, 0, "KDC reaped %s process: %d, term signal %d%s",
1048 what, (int)pid, WTERMSIG(status),
1049 WCOREDUMP(status) ? " (core dumped)" : "");
1050 else
1051 kdc_log(context, config, 0, "KDC reaped %s process: %d",
1052 what, (int)pid);
1053 if (pid == bonjour_pid) {
1054 bonjour_pid = (pid_t)-1;
1055 return 0;
1056 } else {
1057 pids[i] = (pid_t)-1;
1058 return 1;
1062 static int
1063 reap_kids(krb5_context context, krb5_kdc_configuration *config,
1064 pid_t *pids, int max_kids)
1066 int reaped = 0;
1068 for (;;) {
1069 if (reap_kid(context, config, pids, max_kids, WNOHANG) == 0)
1070 break;
1071 reaped++;
1074 return reaped;
1077 static void
1078 select_sleep(int microseconds)
1080 struct timeval tv;
1082 tv.tv_sec = microseconds / 1000000;
1083 tv.tv_usec = microseconds % 1000000;
1084 select(0, NULL, NULL, NULL, &tv);
1086 #endif
1088 void
1089 start_kdc(krb5_context context,
1090 krb5_kdc_configuration *config, const char *argv0)
1092 struct timeval tv1;
1093 struct timeval tv2;
1094 struct descr *d;
1095 unsigned int ndescr;
1096 pid_t pid;
1097 #ifdef HAVE_FORK
1098 pid_t *pids;
1099 int max_kdcs = config->num_kdc_processes;
1100 int num_kdcs = 0;
1101 int i;
1102 int islive[2];
1103 #endif
1105 #ifdef __APPLE__
1106 if (do_bonjour > 0)
1107 bonjour_kid(context, config, argv0, NULL);
1108 #endif
1110 #ifdef HAVE_FORK
1111 #ifdef _SC_NPROCESSORS_ONLN
1112 if (max_kdcs < 1)
1113 max_kdcs = sysconf(_SC_NPROCESSORS_ONLN);
1114 #endif
1116 if (max_kdcs < 1)
1117 max_kdcs = 1;
1119 pids = malloc(max_kdcs * sizeof(*pids));
1120 if (!pids)
1121 krb5_err(context, 1, errno, "malloc");
1122 memset(pids, 0x0, max_kdcs * sizeof(*pids));
1125 * We open a socketpair of which we hand one end to each of our kids.
1126 * When we exit, for whatever reason, the children will notice an EOF
1127 * on their end and be able to cleanly exit.
1130 if (socketpair(PF_LOCAL, SOCK_STREAM, 0, islive) == -1)
1131 krb5_errx(context, 1, "socketpair");
1132 socket_set_nonblocking(islive[1], 1);
1133 #endif
1135 ndescr = init_sockets(context, config, &d);
1136 if(ndescr <= 0)
1137 krb5_errx(context, 1, "No sockets!");
1139 #ifdef HAVE_FORK
1141 # ifdef __APPLE__
1142 if (do_bonjour < 0)
1143 bonjour_kid(context, config, argv0, islive);
1144 # endif
1146 kdc_log(context, config, 0, "KDC started master process pid=%d", getpid());
1147 #else
1148 kdc_log(context, config, 0, "KDC started pid=%d", getpid());
1149 #endif
1151 roken_detach_finish(NULL, daemon_child);
1153 tv1.tv_sec = 0;
1154 tv1.tv_usec = 0;
1156 #ifdef HAVE_FORK
1157 while (exit_flag == 0) {
1159 /* Slow down the creation of KDCs... */
1161 gettimeofday(&tv2, NULL);
1162 if (tv1.tv_sec == tv2.tv_sec && tv2.tv_usec - tv1.tv_usec < 25000) {
1163 #if 0 /* XXXrcd: should print a message... */
1164 kdc_log(context, config, 0, "Spawning KDCs too quickly, "
1165 "pausing for 50ms");
1166 #endif
1167 select_sleep(12500);
1168 continue;
1171 if (num_kdcs >= max_kdcs) {
1172 num_kdcs -= reap_kid(context, config, pids, max_kdcs, 0);
1173 continue;
1176 if (num_kdcs > 0)
1177 num_kdcs -= reap_kids(context, config, pids, max_kdcs);
1179 pid = fork();
1180 switch (pid) {
1181 case 0:
1182 close(islive[0]);
1183 loop(context, config, d, ndescr, islive[1]);
1184 exit(0);
1185 case -1:
1186 /* XXXrcd: hmmm, do something useful?? */
1187 kdc_log(context, config, 0,
1188 "KDC master process could not fork worker process");
1189 sleep(10);
1190 break;
1191 default:
1192 for (i=0; i < max_kdcs; i++)
1193 if (pids[i] == 0)
1194 break;
1195 pids[i] = pid;
1196 kdc_log(context, config, 0, "KDC worker process started: %d", pid);
1197 num_kdcs++;
1198 gettimeofday(&tv1, NULL);
1199 break;
1203 /* Closing these sockets should cause the kids to die... */
1205 close(islive[0]);
1206 close(islive[1]);
1208 /* Close our listener sockets before terminating workers */
1209 for (i = 0; i < ndescr; ++i)
1210 clear_descr(&d[i]);
1212 gettimeofday(&tv1, NULL);
1213 tv2 = tv1;
1215 /* Reap every 10ms, terminate stragglers once a second, give up after 10 */
1216 for (;;) {
1217 struct timeval tv3;
1218 num_kdcs -= reap_kids(context, config, pids, max_kdcs);
1219 if (num_kdcs == 0 && bonjour_pid <= 0)
1220 goto end;
1222 * Using select to sleep will fail with EINTR if we receive a
1223 * SIGCHLD. This is desirable.
1225 select_sleep(10000);
1226 gettimeofday(&tv3, NULL);
1227 if (tv3.tv_sec - tv1.tv_sec > 10 ||
1228 (tv3.tv_sec - tv1.tv_sec == 10 && tv3.tv_usec >= tv1.tv_usec))
1229 break;
1230 if (tv3.tv_sec - tv2.tv_sec > 1 ||
1231 (tv3.tv_sec - tv2.tv_sec == 1 && tv3.tv_usec >= tv2.tv_usec)) {
1232 kill_kids(pids, max_kdcs, SIGTERM);
1233 tv2 = tv3;
1237 /* Kill stragglers and reap every 200ms, give up after 15s */
1238 for (;;) {
1239 kill_kids(pids, max_kdcs, SIGKILL);
1240 num_kdcs -= reap_kids(context, config, pids, max_kdcs);
1241 if (num_kdcs == 0 && bonjour_pid <= 0)
1242 break;
1243 select_sleep(200000);
1244 gettimeofday(&tv2, NULL);
1245 if (tv2.tv_sec - tv1.tv_sec > 15 ||
1246 (tv2.tv_sec - tv1.tv_sec == 15 && tv2.tv_usec >= tv1.tv_usec))
1247 break;
1250 end:
1251 kdc_log(context, config, 0, "KDC master process exiting", pid);
1252 free(pids);
1253 #else
1254 loop(context, config, d, ndescr, -1);
1255 kdc_log(context, config, 0, "KDC exiting", pid);
1256 #endif
1258 free (d);