xref: /freebsd/crypto/heimdal/kdc/connect.c (revision 195ebc7e9e4b129de810833791a19dfb4349d6a9)
1 /*
2  * Copyright (c) 1997-2005 Kungliga Tekniska H�gskolan
3  * (Royal Institute of Technology, Stockholm, Sweden).
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  *
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.
16  *
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.
20  *
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.
32  */
33 
34 #include "kdc_locl.h"
35 
36 RCSID("$Id: connect.c 22434 2008-01-14 09:21:37Z lha $");
37 
38 /* Should we enable the HTTP hack? */
39 int enable_http = -1;
40 
41 /* Log over requests to the KDC */
42 const char *request_log;
43 
44 /* A string describing on what ports to listen */
45 const char *port_str;
46 
47 krb5_addresses explicit_addresses;
48 
49 size_t max_request;		/* maximal size of a request */
50 
51 /*
52  * a tuple describing on what to listen
53  */
54 
55 struct port_desc{
56     int family;
57     int type;
58     int port;
59 };
60 
61 /* the current ones */
62 
63 static struct port_desc *ports;
64 static int num_ports;
65 
66 /*
67  * add `family, port, protocol' to the list with duplicate suppresion.
68  */
69 
70 static void
71 add_port(krb5_context context,
72 	 int family, int port, const char *protocol)
73 {
74     int type;
75     int i;
76 
77     if(strcmp(protocol, "udp") == 0)
78 	type = SOCK_DGRAM;
79     else if(strcmp(protocol, "tcp") == 0)
80 	type = SOCK_STREAM;
81     else
82 	return;
83     for(i = 0; i < num_ports; i++){
84 	if(ports[i].type == type
85 	   && ports[i].port == port
86 	   && ports[i].family == family)
87 	    return;
88     }
89     ports = realloc(ports, (num_ports + 1) * sizeof(*ports));
90     if (ports == NULL)
91 	krb5_err (context, 1, errno, "realloc");
92     ports[num_ports].family = family;
93     ports[num_ports].type   = type;
94     ports[num_ports].port   = port;
95     num_ports++;
96 }
97 
98 /*
99  * add a triple but with service -> port lookup
100  * (this prints warnings for stuff that does not exist)
101  */
102 
103 static void
104 add_port_service(krb5_context context,
105 		 int family, const char *service, int port,
106 		 const char *protocol)
107 {
108     port = krb5_getportbyname (context, service, protocol, port);
109     add_port (context, family, port, protocol);
110 }
111 
112 /*
113  * add the port with service -> port lookup or string -> number
114  * (no warning is printed)
115  */
116 
117 static void
118 add_port_string (krb5_context context,
119 		 int family, const char *str, const char *protocol)
120 {
121     struct servent *sp;
122     int port;
123 
124     sp = roken_getservbyname (str, protocol);
125     if (sp != NULL) {
126 	port = sp->s_port;
127     } else {
128 	char *end;
129 
130 	port = htons(strtol(str, &end, 0));
131 	if (end == str)
132 	    return;
133     }
134     add_port (context, family, port, protocol);
135 }
136 
137 /*
138  * add the standard collection of ports for `family'
139  */
140 
141 static void
142 add_standard_ports (krb5_context context,
143 		    krb5_kdc_configuration *config,
144 		    int family)
145 {
146     add_port_service(context, family, "kerberos", 88, "udp");
147     add_port_service(context, family, "kerberos", 88, "tcp");
148     add_port_service(context, family, "kerberos-sec", 88, "udp");
149     add_port_service(context, family, "kerberos-sec", 88, "tcp");
150     if(enable_http)
151 	add_port_service(context, family, "http", 80, "tcp");
152     if(config->enable_524) {
153 	add_port_service(context, family, "krb524", 4444, "udp");
154 	add_port_service(context, family, "krb524", 4444, "tcp");
155     }
156     if(config->enable_v4) {
157 	add_port_service(context, family, "kerberos-iv", 750, "udp");
158 	add_port_service(context, family, "kerberos-iv", 750, "tcp");
159     }
160     if (config->enable_kaserver)
161 	add_port_service(context, family, "afs3-kaserver", 7004, "udp");
162     if(config->enable_kx509) {
163 	add_port_service(context, family, "kca_service", 9878, "udp");
164 	add_port_service(context, family, "kca_service", 9878, "tcp");
165     }
166 
167 }
168 
169 /*
170  * parse the set of space-delimited ports in `str' and add them.
171  * "+" => all the standard ones
172  * otherwise it's port|service[/protocol]
173  */
174 
175 static void
176 parse_ports(krb5_context context,
177 	    krb5_kdc_configuration *config,
178 	    const char *str)
179 {
180     char *pos = NULL;
181     char *p;
182     char *str_copy = strdup (str);
183 
184     p = strtok_r(str_copy, " \t", &pos);
185     while(p != NULL) {
186 	if(strcmp(p, "+") == 0) {
187 #ifdef HAVE_IPV6
188 	    add_standard_ports(context, config, AF_INET6);
189 #endif
190 	    add_standard_ports(context, config, AF_INET);
191 	} else {
192 	    char *q = strchr(p, '/');
193 	    if(q){
194 		*q++ = 0;
195 #ifdef HAVE_IPV6
196 		add_port_string(context, AF_INET6, p, q);
197 #endif
198 		add_port_string(context, AF_INET, p, q);
199 	    }else {
200 #ifdef HAVE_IPV6
201 		add_port_string(context, AF_INET6, p, "udp");
202 		add_port_string(context, AF_INET6, p, "tcp");
203 #endif
204 		add_port_string(context, AF_INET, p, "udp");
205 		add_port_string(context, AF_INET, p, "tcp");
206 	    }
207 	}
208 
209 	p = strtok_r(NULL, " \t", &pos);
210     }
211     free (str_copy);
212 }
213 
214 /*
215  * every socket we listen on
216  */
217 
218 struct descr {
219     int s;
220     int type;
221     int port;
222     unsigned char *buf;
223     size_t size;
224     size_t len;
225     time_t timeout;
226     struct sockaddr_storage __ss;
227     struct sockaddr *sa;
228     socklen_t sock_len;
229     char addr_string[128];
230 };
231 
232 static void
233 init_descr(struct descr *d)
234 {
235     memset(d, 0, sizeof(*d));
236     d->sa = (struct sockaddr *)&d->__ss;
237     d->s = -1;
238 }
239 
240 /*
241  * re-initialize all `n' ->sa in `d'.
242  */
243 
244 static void
245 reinit_descrs (struct descr *d, int n)
246 {
247     int i;
248 
249     for (i = 0; i < n; ++i)
250 	d[i].sa = (struct sockaddr *)&d[i].__ss;
251 }
252 
253 /*
254  * Create the socket (family, type, port) in `d'
255  */
256 
257 static void
258 init_socket(krb5_context context,
259 	    krb5_kdc_configuration *config,
260 	    struct descr *d, krb5_address *a, int family, int type, int port)
261 {
262     krb5_error_code ret;
263     struct sockaddr_storage __ss;
264     struct sockaddr *sa = (struct sockaddr *)&__ss;
265     krb5_socklen_t sa_size = sizeof(__ss);
266 
267     init_descr (d);
268 
269     ret = krb5_addr2sockaddr (context, a, sa, &sa_size, port);
270     if (ret) {
271 	krb5_warn(context, ret, "krb5_addr2sockaddr");
272 	close(d->s);
273 	d->s = -1;
274 	return;
275     }
276 
277     if (sa->sa_family != family)
278 	return;
279 
280     d->s = socket(family, type, 0);
281     if(d->s < 0){
282 	krb5_warn(context, errno, "socket(%d, %d, 0)", family, type);
283 	d->s = -1;
284 	return;
285     }
286 #if defined(HAVE_SETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_REUSEADDR)
287     {
288 	int one = 1;
289 	setsockopt(d->s, SOL_SOCKET, SO_REUSEADDR, (void *)&one, sizeof(one));
290     }
291 #endif
292     d->type = type;
293     d->port = port;
294 
295     if(bind(d->s, sa, sa_size) < 0){
296 	char a_str[256];
297 	size_t len;
298 
299 	krb5_print_address (a, a_str, sizeof(a_str), &len);
300 	krb5_warn(context, errno, "bind %s/%d", a_str, ntohs(port));
301 	close(d->s);
302 	d->s = -1;
303 	return;
304     }
305     if(type == SOCK_STREAM && listen(d->s, SOMAXCONN) < 0){
306 	char a_str[256];
307 	size_t len;
308 
309 	krb5_print_address (a, a_str, sizeof(a_str), &len);
310 	krb5_warn(context, errno, "listen %s/%d", a_str, ntohs(port));
311 	close(d->s);
312 	d->s = -1;
313 	return;
314     }
315 }
316 
317 /*
318  * Allocate descriptors for all the sockets that we should listen on
319  * and return the number of them.
320  */
321 
322 static int
323 init_sockets(krb5_context context,
324 	     krb5_kdc_configuration *config,
325 	     struct descr **desc)
326 {
327     krb5_error_code ret;
328     int i, j;
329     struct descr *d;
330     int num = 0;
331     krb5_addresses addresses;
332 
333     if (explicit_addresses.len) {
334 	addresses = explicit_addresses;
335     } else {
336 	ret = krb5_get_all_server_addrs (context, &addresses);
337 	if (ret)
338 	    krb5_err (context, 1, ret, "krb5_get_all_server_addrs");
339     }
340     parse_ports(context, config, port_str);
341     d = malloc(addresses.len * num_ports * sizeof(*d));
342     if (d == NULL)
343 	krb5_errx(context, 1, "malloc(%lu) failed",
344 		  (unsigned long)num_ports * sizeof(*d));
345 
346     for (i = 0; i < num_ports; i++){
347 	for (j = 0; j < addresses.len; ++j) {
348 	    init_socket(context, config, &d[num], &addresses.val[j],
349 			ports[i].family, ports[i].type, ports[i].port);
350 	    if(d[num].s != -1){
351 		char a_str[80];
352 		size_t len;
353 
354 		krb5_print_address (&addresses.val[j], a_str,
355 				    sizeof(a_str), &len);
356 
357 		kdc_log(context, config, 5, "listening on %s port %u/%s",
358 			a_str,
359 			ntohs(ports[i].port),
360 			(ports[i].type == SOCK_STREAM) ? "tcp" : "udp");
361 		/* XXX */
362 		num++;
363 	    }
364 	}
365     }
366     krb5_free_addresses (context, &addresses);
367     d = realloc(d, num * sizeof(*d));
368     if (d == NULL && num != 0)
369 	krb5_errx(context, 1, "realloc(%lu) failed",
370 		  (unsigned long)num * sizeof(*d));
371     reinit_descrs (d, num);
372     *desc = d;
373     return num;
374 }
375 
376 /*
377  *
378  */
379 
380 static const char *
381 descr_type(struct descr *d)
382 {
383     if (d->type == SOCK_DGRAM)
384 	return "udp";
385     else if (d->type == SOCK_STREAM)
386 	return "tcp";
387     return "unknown";
388 }
389 
390 static void
391 addr_to_string(krb5_context context,
392 	       struct sockaddr *addr, size_t addr_len, char *str, size_t len)
393 {
394     krb5_address a;
395     if(krb5_sockaddr2address(context, addr, &a) == 0) {
396 	if(krb5_print_address(&a, str, len, &len) == 0) {
397 	    krb5_free_address(context, &a);
398 	    return;
399 	}
400 	krb5_free_address(context, &a);
401     }
402     snprintf(str, len, "<family=%d>", addr->sa_family);
403 }
404 
405 /*
406  *
407  */
408 
409 static void
410 send_reply(krb5_context context,
411 	   krb5_kdc_configuration *config,
412 	   krb5_boolean prependlength,
413 	   struct descr *d,
414 	   krb5_data *reply)
415 {
416     kdc_log(context, config, 5,
417 	    "sending %lu bytes to %s", (unsigned long)reply->length,
418 	    d->addr_string);
419     if(prependlength){
420 	unsigned char l[4];
421 	l[0] = (reply->length >> 24) & 0xff;
422 	l[1] = (reply->length >> 16) & 0xff;
423 	l[2] = (reply->length >> 8) & 0xff;
424 	l[3] = reply->length & 0xff;
425 	if(sendto(d->s, l, sizeof(l), 0, d->sa, d->sock_len) < 0) {
426 	    kdc_log (context, config,
427 		     0, "sendto(%s): %s", d->addr_string, strerror(errno));
428 	    return;
429 	}
430     }
431     if(sendto(d->s, reply->data, reply->length, 0, d->sa, d->sock_len) < 0) {
432 	kdc_log (context, config,
433 		 0, "sendto(%s): %s", d->addr_string, strerror(errno));
434 	return;
435     }
436 }
437 
438 /*
439  * Handle the request in `buf, len' to socket `d'
440  */
441 
442 static void
443 do_request(krb5_context context,
444 	   krb5_kdc_configuration *config,
445 	   void *buf, size_t len, krb5_boolean prependlength,
446 	   struct descr *d)
447 {
448     krb5_error_code ret;
449     krb5_data reply;
450     int datagram_reply = (d->type == SOCK_DGRAM);
451 
452     krb5_kdc_update_time(NULL);
453 
454     krb5_data_zero(&reply);
455     ret = krb5_kdc_process_request(context, config,
456 				   buf, len, &reply, &prependlength,
457 				   d->addr_string, d->sa,
458 				   datagram_reply);
459     if(request_log)
460 	krb5_kdc_save_request(context, request_log, buf, len, &reply, d->sa);
461     if(reply.length){
462 	send_reply(context, config, prependlength, d, &reply);
463 	krb5_data_free(&reply);
464     }
465     if(ret)
466 	kdc_log(context, config, 0,
467 		"Failed processing %lu byte request from %s",
468 		(unsigned long)len, d->addr_string);
469 }
470 
471 /*
472  * Handle incoming data to the UDP socket in `d'
473  */
474 
475 static void
476 handle_udp(krb5_context context,
477 	   krb5_kdc_configuration *config,
478 	   struct descr *d)
479 {
480     unsigned char *buf;
481     int n;
482 
483     buf = malloc(max_request);
484     if(buf == NULL){
485 	kdc_log(context, config, 0, "Failed to allocate %lu bytes", (unsigned long)max_request);
486 	return;
487     }
488 
489     d->sock_len = sizeof(d->__ss);
490     n = recvfrom(d->s, buf, max_request, 0, d->sa, &d->sock_len);
491     if(n < 0)
492 	krb5_warn(context, errno, "recvfrom");
493     else {
494 	addr_to_string (context, d->sa, d->sock_len,
495 			d->addr_string, sizeof(d->addr_string));
496 	do_request(context, config, buf, n, FALSE, d);
497     }
498     free (buf);
499 }
500 
501 static void
502 clear_descr(struct descr *d)
503 {
504     if(d->buf)
505 	memset(d->buf, 0, d->size);
506     d->len = 0;
507     if(d->s != -1)
508 	close(d->s);
509     d->s = -1;
510 }
511 
512 
513 /* remove HTTP %-quoting from buf */
514 static int
515 de_http(char *buf)
516 {
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;
527     }
528     *q = '\0';
529     return 0;
530 }
531 
532 #define TCP_TIMEOUT 4
533 
534 /*
535  * accept a new TCP connection on `d[parent]' and store it in `d[child]'
536  */
537 
538 static void
539 add_new_tcp (krb5_context context,
540 	     krb5_kdc_configuration *config,
541 	     struct descr *d, int parent, int child)
542 {
543     int s;
544 
545     if (child == -1)
546 	return;
547 
548     d[child].sock_len = sizeof(d[child].__ss);
549     s = accept(d[parent].s, d[child].sa, &d[child].sock_len);
550     if(s < 0) {
551 	krb5_warn(context, errno, "accept");
552 	return;
553     }
554 
555     if (s >= FD_SETSIZE) {
556 	krb5_warnx(context, "socket FD too large");
557 	close (s);
558 	return;
559     }
560 
561     d[child].s = s;
562     d[child].timeout = time(NULL) + TCP_TIMEOUT;
563     d[child].type = SOCK_STREAM;
564     addr_to_string (context,
565 		    d[child].sa, d[child].sock_len,
566 		    d[child].addr_string, sizeof(d[child].addr_string));
567 }
568 
569 /*
570  * Grow `d' to handle at least `n'.
571  * Return != 0 if fails
572  */
573 
574 static int
575 grow_descr (krb5_context context,
576 	    krb5_kdc_configuration *config,
577 	    struct descr *d, size_t n)
578 {
579     if (d->size - d->len < n) {
580 	unsigned char *tmp;
581 	size_t grow;
582 
583 	grow = max(1024, d->len + n);
584 	if (d->size + grow > max_request) {
585 	    kdc_log(context, config, 0, "Request exceeds max request size (%lu bytes).",
586 		    (unsigned long)d->size + grow);
587 	    clear_descr(d);
588 	    return -1;
589 	}
590 	tmp = realloc (d->buf, d->size + grow);
591 	if (tmp == NULL) {
592 	    kdc_log(context, config, 0, "Failed to re-allocate %lu bytes.",
593 		    (unsigned long)d->size + grow);
594 	    clear_descr(d);
595 	    return -1;
596 	}
597 	d->size += grow;
598 	d->buf = tmp;
599     }
600     return 0;
601 }
602 
603 /*
604  * Try to handle the TCP data at `d->buf, d->len'.
605  * Return -1 if failed, 0 if succesful, and 1 if data is complete.
606  */
607 
608 static int
609 handle_vanilla_tcp (krb5_context context,
610 		    krb5_kdc_configuration *config,
611 		    struct descr *d)
612 {
613     krb5_storage *sp;
614     uint32_t len;
615 
616     sp = krb5_storage_from_mem(d->buf, d->len);
617     if (sp == NULL) {
618 	kdc_log (context, config, 0, "krb5_storage_from_mem failed");
619 	return -1;
620     }
621     krb5_ret_uint32(sp, &len);
622     krb5_storage_free(sp);
623     if(d->len - 4 >= len) {
624 	memmove(d->buf, d->buf + 4, d->len - 4);
625 	d->len -= 4;
626 	return 1;
627     }
628     return 0;
629 }
630 
631 /*
632  * Try to handle the TCP/HTTP data at `d->buf, d->len'.
633  * Return -1 if failed, 0 if succesful, and 1 if data is complete.
634  */
635 
636 static int
637 handle_http_tcp (krb5_context context,
638 		 krb5_kdc_configuration *config,
639 		 struct descr *d)
640 {
641     char *s, *p, *t;
642     void *data;
643     char *proto;
644     int len;
645 
646     s = (char *)d->buf;
647 
648     p = strstr(s, "\r\n");
649     if (p == NULL) {
650 	kdc_log(context, config, 0, "Malformed HTTP request from %s", d->addr_string);
651 	return -1;
652     }
653     *p = 0;
654 
655     p = NULL;
656     t = strtok_r(s, " \t", &p);
657     if (t == NULL) {
658 	kdc_log(context, config, 0, "Malformed HTTP request from %s", d->addr_string);
659 	return -1;
660     }
661     t = strtok_r(NULL, " \t", &p);
662     if(t == NULL) {
663 	kdc_log(context, config, 0, "Malformed HTTP request from %s", d->addr_string);
664 	return -1;
665     }
666     data = malloc(strlen(t));
667     if (data == NULL) {
668 	kdc_log(context, config, 0, "Failed to allocate %lu bytes",
669 		(unsigned long)strlen(t));
670 	return -1;
671     }
672     if(*t == '/')
673 	t++;
674     if(de_http(t) != 0) {
675 	kdc_log(context, config, 0, "Malformed HTTP request from %s", d->addr_string);
676 	kdc_log(context, config, 5, "HTTP request: %s", t);
677 	free(data);
678 	return -1;
679     }
680     proto = strtok_r(NULL, " \t", &p);
681     if (proto == NULL) {
682 	kdc_log(context, config, 0, "Malformed HTTP request from %s", d->addr_string);
683 	free(data);
684 	return -1;
685     }
686     len = base64_decode(t, data);
687     if(len <= 0){
688 	const char *msg =
689 	    " 404 Not found\r\n"
690 	    "Server: Heimdal/" VERSION "\r\n"
691 	    "Cache-Control: no-cache\r\n"
692 	    "Pragma: no-cache\r\n"
693 	    "Content-type: text/html\r\n"
694 	    "Content-transfer-encoding: 8bit\r\n\r\n"
695 	    "<TITLE>404 Not found</TITLE>\r\n"
696 	    "<H1>404 Not found</H1>\r\n"
697 	    "That page doesn't exist, maybe you are looking for "
698 	    "<A HREF=\"http://www.h5l.org/\">Heimdal</A>?\r\n";
699 	kdc_log(context, config, 0, "HTTP request from %s is non KDC request", d->addr_string);
700 	kdc_log(context, config, 5, "HTTP request: %s", t);
701 	free(data);
702 	if (write(d->s, proto, strlen(proto)) < 0) {
703 	    kdc_log(context, config, 0, "HTTP write failed: %s: %s",
704 		    d->addr_string, strerror(errno));
705 	    return -1;
706 	}
707 	if (write(d->s, msg, strlen(msg)) < 0) {
708 	    kdc_log(context, config, 0, "HTTP write failed: %s: %s",
709 		    d->addr_string, strerror(errno));
710 	    return -1;
711 	}
712 	return -1;
713     }
714     {
715 	const char *msg =
716 	    " 200 OK\r\n"
717 	    "Server: Heimdal/" VERSION "\r\n"
718 	    "Cache-Control: no-cache\r\n"
719 	    "Pragma: no-cache\r\n"
720 	    "Content-type: application/octet-stream\r\n"
721 	    "Content-transfer-encoding: binary\r\n\r\n";
722 	if (write(d->s, proto, strlen(proto)) < 0) {
723 	    kdc_log(context, config, 0, "HTTP write failed: %s: %s",
724 		    d->addr_string, strerror(errno));
725 	    return -1;
726 	}
727 	if (write(d->s, msg, strlen(msg)) < 0) {
728 	    kdc_log(context, config, 0, "HTTP write failed: %s: %s",
729 		    d->addr_string, strerror(errno));
730 	    return -1;
731 	}
732     }
733     memcpy(d->buf, data, len);
734     d->len = len;
735     free(data);
736     return 1;
737 }
738 
739 /*
740  * Handle incoming data to the TCP socket in `d[index]'
741  */
742 
743 static void
744 handle_tcp(krb5_context context,
745 	   krb5_kdc_configuration *config,
746 	   struct descr *d, int idx, int min_free)
747 {
748     unsigned char buf[1024];
749     int n;
750     int ret = 0;
751 
752     if (d[idx].timeout == 0) {
753 	add_new_tcp (context, config, d, idx, min_free);
754 	return;
755     }
756 
757     n = recvfrom(d[idx].s, buf, sizeof(buf), 0, NULL, NULL);
758     if(n < 0){
759 	krb5_warn(context, errno, "recvfrom failed from %s to %s/%d",
760 		  d[idx].addr_string, descr_type(d + idx),
761 		  ntohs(d[idx].port));
762 	return;
763     } else if (n == 0) {
764 	krb5_warnx(context, "connection closed before end of data after %lu "
765 		   "bytes from %s to %s/%d", (unsigned long)d[idx].len,
766 		   d[idx].addr_string, descr_type(d + idx),
767 		   ntohs(d[idx].port));
768 	clear_descr (d + idx);
769 	return;
770     }
771     if (grow_descr (context, config, &d[idx], n))
772 	return;
773     memcpy(d[idx].buf + d[idx].len, buf, n);
774     d[idx].len += n;
775     if(d[idx].len > 4 && d[idx].buf[0] == 0) {
776 	ret = handle_vanilla_tcp (context, config, &d[idx]);
777     } else if(enable_http &&
778 	      d[idx].len >= 4 &&
779 	      strncmp((char *)d[idx].buf, "GET ", 4) == 0 &&
780 	      strncmp((char *)d[idx].buf + d[idx].len - 4,
781 		      "\r\n\r\n", 4) == 0) {
782 	ret = handle_http_tcp (context, config, &d[idx]);
783 	if (ret < 0)
784 	    clear_descr (d + idx);
785     } else if (d[idx].len > 4) {
786 	kdc_log (context, config,
787 		 0, "TCP data of strange type from %s to %s/%d",
788 		 d[idx].addr_string, descr_type(d + idx),
789 		 ntohs(d[idx].port));
790 	if (d[idx].buf[0] & 0x80) {
791 	    krb5_data reply;
792 
793 	    kdc_log (context, config, 0, "TCP extension not supported");
794 
795 	    ret = krb5_mk_error(context,
796 				KRB5KRB_ERR_FIELD_TOOLONG,
797 				NULL,
798 				NULL,
799 				NULL,
800 				NULL,
801 				NULL,
802 				NULL,
803 				&reply);
804 	    if (ret == 0) {
805 		send_reply(context, config, TRUE, d + idx, &reply);
806 		krb5_data_free(&reply);
807 	    }
808 	}
809 	clear_descr(d + idx);
810 	return;
811     }
812     if (ret < 0)
813 	return;
814     else if (ret == 1) {
815 	do_request(context, config,
816 		   d[idx].buf, d[idx].len, TRUE, &d[idx]);
817 	clear_descr(d + idx);
818     }
819 }
820 
821 void
822 loop(krb5_context context,
823      krb5_kdc_configuration *config)
824 {
825     struct descr *d;
826     int ndescr;
827 
828     ndescr = init_sockets(context, config, &d);
829     if(ndescr <= 0)
830 	krb5_errx(context, 1, "No sockets!");
831     kdc_log(context, config, 0, "KDC started");
832     while(exit_flag == 0){
833 	struct timeval tmout;
834 	fd_set fds;
835 	int min_free = -1;
836 	int max_fd = 0;
837 	int i;
838 
839 	FD_ZERO(&fds);
840 	for(i = 0; i < ndescr; i++) {
841 	    if(d[i].s >= 0){
842 		if(d[i].type == SOCK_STREAM &&
843 		   d[i].timeout && d[i].timeout < time(NULL)) {
844 		    kdc_log(context, config, 1,
845 			    "TCP-connection from %s expired after %lu bytes",
846 			    d[i].addr_string, (unsigned long)d[i].len);
847 		    clear_descr(&d[i]);
848 		    continue;
849 		}
850 		if(max_fd < d[i].s)
851 		    max_fd = d[i].s;
852 		if (max_fd >= FD_SETSIZE)
853 		    krb5_errx(context, 1, "fd too large");
854 		FD_SET(d[i].s, &fds);
855 	    } else if(min_free < 0 || i < min_free)
856 		min_free = i;
857 	}
858 	if(min_free == -1){
859 	    struct descr *tmp;
860 	    tmp = realloc(d, (ndescr + 4) * sizeof(*d));
861 	    if(tmp == NULL)
862 		krb5_warnx(context, "No memory");
863 	    else {
864 		d = tmp;
865 		reinit_descrs (d, ndescr);
866 		memset(d + ndescr, 0, 4 * sizeof(*d));
867 		for(i = ndescr; i < ndescr + 4; i++)
868 		    init_descr (&d[i]);
869 		min_free = ndescr;
870 		ndescr += 4;
871 	    }
872 	}
873 
874 	tmout.tv_sec = TCP_TIMEOUT;
875 	tmout.tv_usec = 0;
876 	switch(select(max_fd + 1, &fds, 0, 0, &tmout)){
877 	case 0:
878 	    break;
879 	case -1:
880 	    if (errno != EINTR)
881 		krb5_warn(context, errno, "select");
882 	    break;
883 	default:
884 	    for(i = 0; i < ndescr; i++)
885 		if(d[i].s >= 0 && FD_ISSET(d[i].s, &fds)) {
886 		    if(d[i].type == SOCK_DGRAM)
887 			handle_udp(context, config, &d[i]);
888 		    else if(d[i].type == SOCK_STREAM)
889 			handle_tcp(context, config, d, i, min_free);
890 		}
891 	}
892     }
893     if(exit_flag == SIGXCPU)
894 	kdc_log(context, config, 0, "CPU time limit exceeded");
895     else if(exit_flag == SIGINT || exit_flag == SIGTERM)
896 	kdc_log(context, config, 0, "Terminated");
897     else
898 	kdc_log(context, config, 0, "Unexpected exit reason: %d", exit_flag);
899     free (d);
900 }
901