s4:torture: Adapt KDC canon test to Heimdal upstream changes
[samba.git] / source4 / heimdal / kdc / connect.c
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 /*
37  * a tuple describing on what to listen
38  */
39
40 struct port_desc{
41     int family;
42     int type;
43     int port;
44 };
45
46 /* the current ones */
47
48 static struct port_desc *ports;
49 static size_t num_ports;
50 static pid_t bonjour_pid = -1;
51
52 /*
53  * add `family, port, protocol' to the list with duplicate suppresion.
54  */
55
56 static void
57 add_port(krb5_context context,
58          int family, int port, const char *protocol)
59 {
60     int type;
61     size_t i;
62
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;
74     }
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++;
82 }
83
84 /*
85  * add a triple but with service -> port lookup
86  * (this prints warnings for stuff that does not exist)
87  */
88
89 static void
90 add_port_service(krb5_context context,
91                  int family, const char *service, int port,
92                  const char *protocol)
93 {
94     port = krb5_getportbyname (context, service, protocol, port);
95     add_port (context, family, port, protocol);
96 }
97
98 /*
99  * add the port with service -> port lookup or string -> number
100  * (no warning is printed)
101  */
102
103 static void
104 add_port_string (krb5_context context,
105                  int family, const char *str, const char *protocol)
106 {
107     struct servent *sp;
108     int port;
109
110     sp = roken_getservbyname (str, protocol);
111     if (sp != NULL) {
112         port = sp->s_port;
113     } else {
114         char *end;
115
116         port = htons(strtol(str, &end, 0));
117         if (end == str)
118             return;
119     }
120     add_port (context, family, port, protocol);
121 }
122
123 /*
124  * add the standard collection of ports for `family'
125  */
126
127 static void
128 add_standard_ports (krb5_context context,
129                     krb5_kdc_configuration *config,
130                     int family)
131 {
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");
141     }
142
143 }
144
145 /*
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]
149  */
150
151 static void
152 parse_ports(krb5_context context,
153             krb5_kdc_configuration *config,
154             const char *str)
155 {
156     char *pos = NULL;
157     char *p;
158     char *str_copy = strdup (str);
159
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");
182             }
183         }
184
185         p = strtok_r(NULL, " \t", &pos);
186     }
187     free (str_copy);
188 }
189
190 /*
191  * every socket we listen on
192  */
193
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];
206 };
207
208 static void
209 init_descr(struct descr *d)
210 {
211     memset(d, 0, sizeof(*d));
212     d->sa = (struct sockaddr *)&d->__ss;
213     d->s = rk_INVALID_SOCKET;
214 }
215
216 /*
217  * re-initialize all `n' ->sa in `d'.
218  */
219
220 static void
221 reinit_descrs (struct descr *d, int n)
222 {
223     int i;
224
225     for (i = 0; i < n; ++i)
226         d[i].sa = (struct sockaddr *)&d[i].__ss;
227 }
228
229 /*
230  * Create the socket (family, type, port) in `d'
231  */
232
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)
237 {
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);
242
243     init_descr (d);
244
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;
251     }
252
253     if (sa->sa_family != family)
254         return;
255
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;
261     }
262     rk_cloexec(d->s);
263 #if defined(HAVE_SETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_REUSEADDR)
264     {
265         int one = 1;
266         setsockopt(d->s, SOL_SOCKET, SO_REUSEADDR, (void *)&one, sizeof(one));
267     }
268 #endif
269     d->type = type;
270     d->port = port;
271
272     socket_set_nonblocking(d->s, 1);
273
274     if(rk_IS_SOCKET_ERROR(bind(d->s, sa, sa_size))){
275         char a_str[256];
276         size_t len;
277
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;
283     }
284     if(type == SOCK_STREAM && rk_IS_SOCKET_ERROR(listen(d->s, SOMAXCONN))){
285         char a_str[256];
286         size_t len;
287
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;
293     }
294     socket_set_keepalive(d->s, 1);
295 }
296
297 /*
298  * Allocate descriptors for all the sockets that we should listen on
299  * and return the number of them.
300  */
301
302 static int
303 init_sockets(krb5_context context,
304              krb5_kdc_configuration *config,
305              struct descr **desc)
306 {
307     krb5_error_code ret;
308     size_t i, j;
309     struct descr *d;
310     int num = 0;
311     krb5_addresses addresses;
312
313     if (explicit_addresses.len) {
314         addresses = explicit_addresses;
315     } else {
316         ret = krb5_get_all_server_addrs (context, &addresses);
317         if (ret)
318             krb5_err (context, 1, ret, "krb5_get_all_server_addrs");
319     }
320     parse_ports(context, config, port_str);
321     d = malloc(addresses.len * num_ports * sizeof(*d));
322     if (d == NULL)
323         krb5_errx(context, 1, "malloc(%lu) failed",
324                   (unsigned long)num_ports * sizeof(*d));
325
326     for (i = 0; i < num_ports; i++){
327         for (j = 0; j < addresses.len; ++j) {
328             init_socket(context, config, &d[num], &addresses.val[j],
329                         ports[i].family, ports[i].type, ports[i].port);
330             if(d[num].s != rk_INVALID_SOCKET){
331                 char a_str[80];
332                 size_t len;
333
334                 krb5_print_address (&addresses.val[j], a_str,
335                                     sizeof(a_str), &len);
336
337                 kdc_log(context, config, 3, "listening on %s port %u/%s",
338                         a_str,
339                         ntohs(ports[i].port),
340                         (ports[i].type == SOCK_STREAM) ? "tcp" : "udp");
341                 /* XXX */
342                 num++;
343             }
344         }
345     }
346     krb5_free_addresses (context, &addresses);
347     d = realloc(d, num * sizeof(*d));
348     if (d == NULL && num != 0)
349         krb5_errx(context, 1, "realloc(%lu) failed",
350                   (unsigned long)num * sizeof(*d));
351     reinit_descrs (d, num);
352     *desc = d;
353     return num;
354 }
355
356 /*
357  *
358  */
359
360 static const char *
361 descr_type(struct descr *d)
362 {
363     if (d->type == SOCK_DGRAM)
364         return "udp";
365     else if (d->type == SOCK_STREAM)
366         return "tcp";
367     return "unknown";
368 }
369
370 static void
371 addr_to_string(krb5_context context,
372                struct sockaddr *addr, size_t addr_len, char *str, size_t len)
373 {
374     krb5_address a;
375     if(krb5_sockaddr2address(context, addr, &a) == 0) {
376         if(krb5_print_address(&a, str, len, &len) == 0) {
377             krb5_free_address(context, &a);
378             return;
379         }
380         krb5_free_address(context, &a);
381     }
382     snprintf(str, len, "<family=%d>", addr->sa_family);
383 }
384
385 /*
386  *
387  */
388
389 static void
390 send_reply(krb5_context context,
391            krb5_kdc_configuration *config,
392            krb5_boolean prependlength,
393            struct descr *d,
394            krb5_data *reply)
395 {
396     kdc_log(context, config, 4,
397             "sending %lu bytes to %s", (unsigned long)reply->length,
398             d->addr_string);
399     if(prependlength){
400         unsigned char l[4];
401         l[0] = (reply->length >> 24) & 0xff;
402         l[1] = (reply->length >> 16) & 0xff;
403         l[2] = (reply->length >> 8) & 0xff;
404         l[3] = reply->length & 0xff;
405         if(rk_IS_SOCKET_ERROR(sendto(d->s, l, sizeof(l), 0, d->sa, d->sock_len))) {
406             kdc_log (context, config,
407                      1, "sendto(%s): %s", d->addr_string,
408                      strerror(rk_SOCK_ERRNO));
409             return;
410         }
411     }
412     if(rk_IS_SOCKET_ERROR(sendto(d->s, reply->data, reply->length, 0, d->sa, d->sock_len))) {
413         kdc_log (context, config, 1, "sendto(%s): %s", d->addr_string,
414                  strerror(rk_SOCK_ERRNO));
415         return;
416     }
417 }
418
419 /*
420  * Handle the request in `buf, len' to socket `d'
421  */
422
423 static void
424 do_request(krb5_context context,
425            krb5_kdc_configuration *config,
426            void *buf, size_t len, krb5_boolean prependlength,
427            struct descr *d)
428 {
429     krb5_error_code ret;
430     krb5_data reply;
431     int datagram_reply = (d->type == SOCK_DGRAM);
432
433     krb5_kdc_update_time(NULL);
434
435     krb5_data_zero(&reply);
436     ret = krb5_kdc_process_request(context, config,
437                                    buf, len, &reply, &prependlength,
438                                    d->addr_string, d->sa,
439                                    datagram_reply);
440     if(request_log)
441         krb5_kdc_save_request(context, request_log, buf, len, &reply, d->sa);
442     if(reply.length){
443         send_reply(context, config, prependlength, d, &reply);
444         krb5_data_free(&reply);
445     }
446     if(ret)
447         kdc_log(context, config, 1,
448                 "Failed processing %lu byte request from %s",
449                 (unsigned long)len, d->addr_string);
450 }
451
452 /*
453  * Handle incoming data to the UDP socket in `d'
454  */
455
456 static void
457 handle_udp(krb5_context context,
458            krb5_kdc_configuration *config,
459            struct descr *d)
460 {
461     unsigned char *buf;
462     ssize_t n;
463
464     buf = malloc(max_request_udp);
465     if (buf == NULL){
466         kdc_log(context, config, 1, "Failed to allocate %lu bytes",
467                 (unsigned long)max_request_udp);
468         return;
469     }
470
471     d->sock_len = sizeof(d->__ss);
472     n = recvfrom(d->s, buf, max_request_udp, 0, d->sa, &d->sock_len);
473     if (rk_IS_SOCKET_ERROR(n)) {
474         if (rk_SOCK_ERRNO != EAGAIN && rk_SOCK_ERRNO != EINTR)
475             krb5_warn(context, rk_SOCK_ERRNO, "recvfrom");
476     } else {
477         addr_to_string (context, d->sa, d->sock_len,
478                         d->addr_string, sizeof(d->addr_string));
479         if ((size_t)n == max_request_udp) {
480             krb5_data data;
481             krb5_warn(context, errno,
482                       "recvfrom: truncated packet from %s, asking for TCP",
483                       d->addr_string);
484             krb5_mk_error(context,
485                           KRB5KRB_ERR_RESPONSE_TOO_BIG,
486                           NULL,
487                           NULL,
488                           NULL,
489                           NULL,
490                           NULL,
491                           NULL,
492                           &data);
493             send_reply(context, config, FALSE, d, &data);
494             krb5_data_free(&data);
495         } else {
496             do_request(context, config, buf, n, FALSE, d);
497         }
498     }
499     free (buf);
500 }
501
502 static void
503 clear_descr(struct descr *d)
504 {
505     if(d->buf)
506         memset(d->buf, 0, d->size);
507     d->len = 0;
508     if(d->s != rk_INVALID_SOCKET)
509         rk_closesocket(d->s);
510     d->s = rk_INVALID_SOCKET;
511 }
512
513
514 /* remove HTTP %-quoting from buf */
515 static int
516 de_http(char *buf)
517 {
518     unsigned char *p, *q;
519     unsigned int x;
520
521     for (p = q = (unsigned char *)buf; *p; p++, q++) {
522         if (*p == '%') {
523             if (!(isxdigit(p[1]) && isxdigit(p[2])))
524                 return -1;
525
526             if (sscanf((char *)p + 1, "%2x", &x) != 1)
527                 return -1;
528
529             *q = x;
530             p += 2;
531         } else {
532             *q = *p;
533         }
534     }
535     *q = '\0';
536     return 0;
537 }
538
539 #define TCP_TIMEOUT 4
540
541 /*
542  * accept a new TCP connection on `d[parent]' and store it in `d[child]'
543  */
544
545 static void
546 add_new_tcp (krb5_context context,
547              krb5_kdc_configuration *config,
548              struct descr *d, int parent, int child)
549 {
550     krb5_socket_t s;
551
552     if (child == -1)
553         return;
554
555     d[child].sock_len = sizeof(d[child].__ss);
556     s = accept(d[parent].s, d[child].sa, &d[child].sock_len);
557     if(rk_IS_BAD_SOCKET(s)) {
558         if (rk_SOCK_ERRNO != EAGAIN && rk_SOCK_ERRNO != EINTR)
559             krb5_warn(context, rk_SOCK_ERRNO, "accept");
560         return;
561     }
562
563 #ifdef FD_SETSIZE
564     if (s >= FD_SETSIZE) {
565         krb5_warnx(context, "socket FD too large");
566         rk_closesocket (s);
567         return;
568     }
569 #endif
570
571     d[child].s = s;
572     d[child].timeout = time(NULL) + TCP_TIMEOUT;
573     d[child].type = SOCK_STREAM;
574     addr_to_string (context,
575                     d[child].sa, d[child].sock_len,
576                     d[child].addr_string, sizeof(d[child].addr_string));
577 }
578
579 /*
580  * Grow `d' to handle at least `n'.
581  * Return != 0 if fails
582  */
583
584 static int
585 grow_descr (krb5_context context,
586             krb5_kdc_configuration *config,
587             struct descr *d, size_t n)
588 {
589     if (d->size - d->len < n) {
590         unsigned char *tmp;
591         size_t grow;
592
593         grow = max(1024, d->len + n);
594         if (d->size + grow > max_request_tcp) {
595             kdc_log(context, config, 2, "Request exceeds max request size (%lu bytes).",
596                     (unsigned long)d->size + grow);
597             clear_descr(d);
598             return -1;
599         }
600         tmp = realloc (d->buf, d->size + grow);
601         if (tmp == NULL) {
602             kdc_log(context, config, 1, "Failed to re-allocate %lu bytes.",
603                     (unsigned long)d->size + grow);
604             clear_descr(d);
605             return -1;
606         }
607         d->size += grow;
608         d->buf = tmp;
609     }
610     return 0;
611 }
612
613 /*
614  * Try to handle the TCP data at `d->buf, d->len'.
615  * Return -1 if failed, 0 if succesful, and 1 if data is complete.
616  */
617
618 static int
619 handle_vanilla_tcp (krb5_context context,
620                     krb5_kdc_configuration *config,
621                     struct descr *d)
622 {
623     krb5_storage *sp;
624     uint32_t len;
625
626     sp = krb5_storage_from_mem(d->buf, d->len);
627     if (sp == NULL) {
628         kdc_log (context, config, 1, "krb5_storage_from_mem failed");
629         return -1;
630     }
631     krb5_ret_uint32(sp, &len);
632     krb5_storage_free(sp);
633     if(d->len - 4 >= len) {
634         memmove(d->buf, d->buf + 4, d->len - 4);
635         d->len -= 4;
636         return 1;
637     }
638     return 0;
639 }
640
641 /*
642  * Try to handle the TCP/HTTP data at `d->buf, d->len'.
643  * Return -1 if failed, 0 if succesful, and 1 if data is complete.
644  */
645
646 static int
647 handle_http_tcp (krb5_context context,
648                  krb5_kdc_configuration *config,
649                  struct descr *d)
650 {
651     char *s, *p, *t;
652     void *data;
653     char *proto;
654     int len;
655
656     s = (char *)d->buf;
657
658     /* If its a multi line query, truncate off the first line */
659     p = strstr(s, "\r\n");
660     if (p)
661         *p = 0;
662
663     p = NULL;
664     t = strtok_r(s, " \t", &p);
665     if (t == NULL) {
666         kdc_log(context, config, 2,
667                 "Missing HTTP operand (GET) request from %s", d->addr_string);
668         return -1;
669     }
670
671     t = strtok_r(NULL, " \t", &p);
672     if(t == NULL) {
673         kdc_log(context, config, 2,
674                 "Missing HTTP GET data in request from %s", d->addr_string);
675         return -1;
676     }
677
678     data = malloc(strlen(t));
679     if (data == NULL) {
680         kdc_log(context, config, 1, "Failed to allocate %lu bytes",
681                 (unsigned long)strlen(t));
682         return -1;
683     }
684     if(*t == '/')
685         t++;
686     if(de_http(t) != 0) {
687         kdc_log(context, config, 2, "Malformed HTTP request from %s", d->addr_string);
688         kdc_log(context, config, 4, "HTTP request: %s", t);
689         free(data);
690         return -1;
691     }
692     proto = strtok_r(NULL, " \t", &p);
693     if (proto == NULL) {
694         kdc_log(context, config, 2, "Malformed HTTP request from %s", d->addr_string);
695         free(data);
696         return -1;
697     }
698     len = rk_base64_decode(t, data);
699     if(len <= 0){
700         const char *msg =
701             " 404 Not found\r\n"
702             "Server: Heimdal/" VERSION "\r\n"
703             "Cache-Control: no-cache\r\n"
704             "Pragma: no-cache\r\n"
705             "Content-type: text/html\r\n"
706             "Content-transfer-encoding: 8bit\r\n\r\n"
707             "<TITLE>404 Not found</TITLE>\r\n"
708             "<H1>404 Not found</H1>\r\n"
709             "That page doesn't exist, maybe you are looking for "
710             "<A HREF=\"http://www.h5l.org/\">Heimdal</A>?\r\n";
711         kdc_log(context, config, 2, "HTTP request from %s is non KDC request", d->addr_string);
712         kdc_log(context, config, 4, "HTTP request: %s", t);
713         free(data);
714         if (rk_IS_SOCKET_ERROR(send(d->s, proto, strlen(proto), 0))) {
715             kdc_log(context, config, 1, "HTTP write failed: %s: %s",
716                     d->addr_string, strerror(rk_SOCK_ERRNO));
717             return -1;
718         }
719         if (rk_IS_SOCKET_ERROR(send(d->s, msg, strlen(msg), 0))) {
720             kdc_log(context, config, 1, "HTTP write failed: %s: %s",
721                     d->addr_string, strerror(rk_SOCK_ERRNO));
722             return -1;
723         }
724         return -1;
725     }
726     {
727         const char *msg =
728             " 200 OK\r\n"
729             "Server: Heimdal/" VERSION "\r\n"
730             "Cache-Control: no-cache\r\n"
731             "Pragma: no-cache\r\n"
732             "Content-type: application/octet-stream\r\n"
733             "Content-transfer-encoding: binary\r\n\r\n";
734         if (rk_IS_SOCKET_ERROR(send(d->s, proto, strlen(proto), 0))) {
735             free(data);
736             kdc_log(context, config, 1, "HTTP write failed: %s: %s",
737                     d->addr_string, strerror(rk_SOCK_ERRNO));
738             return -1;
739         }
740         if (rk_IS_SOCKET_ERROR(send(d->s, msg, strlen(msg), 0))) {
741             free(data);
742             kdc_log(context, config, 1, "HTTP write failed: %s: %s",
743                     d->addr_string, strerror(rk_SOCK_ERRNO));
744             return -1;
745         }
746     }
747     if ((size_t)len > d->len)
748         len = d->len;
749     memcpy(d->buf, data, len);
750     d->len = len;
751     free(data);
752     return 1;
753 }
754
755 static int
756 http1_request_taste(const unsigned char *req, size_t len)
757 {
758     return !!((len >= sizeof("GET ") - 1 &&
759                memcmp(req, "GET ", sizeof("GET ") - 1) == 0) ||
760               (len >= sizeof("HEAD ") - 1 &&
761                memcmp(req, "HEAD ", sizeof("HEAD ") - 1) == 0));
762 }
763
764 static int
765 http1_request_is_complete(const unsigned char *req, size_t len)
766 {
767
768     return http1_request_taste(req, len) &&
769         memmem(req, len, "\r\n\r\n", sizeof("\r\n\r\n") - 4) != NULL;
770
771     /*
772      * For POST (the MSFT variant of this protocol) we'll need something like
773      * this (plus check for Content-Length/Transfer-Encoding):
774      *
775      *  const unsigned char *body;
776      *  if ((body = memmem(req, len, "\r\n\r\n", sizeof("\r\n\r\n") - 4)) == NULL)
777      *      return 0;
778      *  body += sizeof("\r\n\r\n") - 4;
779      *  len -= (body - req);
780      *  return memmem(body, len, "\r\n\r\n", sizeof("\r\n\r\n") - 4) != NULL;
781      *
782      * Since the POST-based variant runs over HTTPS, we'll probably implement
783      * that in a proxy instead of here.
784      */
785 }
786
787 /*
788  * Handle incoming data to the TCP socket in `d[index]'
789  */
790
791 static void
792 handle_tcp(krb5_context context,
793            krb5_kdc_configuration *config,
794            struct descr *d, int idx, int min_free)
795 {
796     unsigned char buf[1024];
797     int n;
798     int ret = 0;
799
800     if (d[idx].timeout == 0) {
801         add_new_tcp (context, config, d, idx, min_free);
802         return;
803     }
804
805     n = recvfrom(d[idx].s, buf, sizeof(buf), 0, NULL, NULL);
806     if(rk_IS_SOCKET_ERROR(n)){
807         krb5_warn(context, rk_SOCK_ERRNO, "recvfrom failed from %s to %s/%d",
808                   d[idx].addr_string, descr_type(d + idx),
809                   ntohs(d[idx].port));
810         return;
811     } else if (n == 0) {
812         krb5_warnx(context, "connection closed before end of data after %lu "
813                    "bytes from %s to %s/%d", (unsigned long)d[idx].len,
814                    d[idx].addr_string, descr_type(d + idx),
815                    ntohs(d[idx].port));
816         clear_descr (d + idx);
817         return;
818     }
819     if (grow_descr (context, config, &d[idx], n))
820         return;
821     memcpy(d[idx].buf + d[idx].len, buf, n);
822     d[idx].len += n;
823     if(d[idx].len > 4 && d[idx].buf[0] == 0) {
824         ret = handle_vanilla_tcp (context, config, &d[idx]);
825     } else if (enable_http &&
826                http1_request_taste(d[idx].buf, d[idx].len)) {
827
828         if (http1_request_is_complete(d[idx].buf, d[idx].len)) {
829             /* NUL-terminate at the request header ending \r\n\r\n */
830             d[idx].buf[d[idx].len - 4] = '\0';
831             ret = handle_http_tcp (context, config, &d[idx]);
832         }
833     } else if (d[idx].len > 4) {
834         kdc_log (context, config,
835                  2, "TCP data of strange type from %s to %s/%d",
836                  d[idx].addr_string, descr_type(d + idx),
837                  ntohs(d[idx].port));
838         if (d[idx].buf[0] & 0x80) {
839             krb5_data reply;
840
841             kdc_log (context, config, 2, "TCP extension not supported");
842
843             ret = krb5_mk_error(context,
844                                 KRB5KRB_ERR_FIELD_TOOLONG,
845                                 NULL,
846                                 NULL,
847                                 NULL,
848                                 NULL,
849                                 NULL,
850                                 NULL,
851                                 &reply);
852             if (ret == 0) {
853                 send_reply(context, config, TRUE, d + idx, &reply);
854                 krb5_data_free(&reply);
855             }
856         }
857         clear_descr(d + idx);
858         return;
859     }
860
861     /*
862      * ret == 0 -> not enough of request buffered -> wait for more
863      * ret == 1 -> go ahead and perform the request
864      * ret != 0 (really, < 0) -> error, probably ENOMEM, close connection
865      */
866     if (ret == 1)
867         do_request(context, config,
868                    d[idx].buf, d[idx].len, TRUE, &d[idx]);
869
870     /*
871      * Note: this means we don't keep the connection open even where we
872      * the protocol permits it.
873      */
874     if (ret != 0)
875         clear_descr(d + idx);
876 }
877
878 #ifdef HAVE_FORK
879 static void
880 handle_islive(int fd)
881 {
882     char buf;
883     int ret;
884
885     ret = read(fd, &buf, 1);
886     if (ret != 1)
887         exit_flag = -1;
888 }
889 #endif
890
891 static krb5_boolean
892 realloc_descrs(struct descr **d, unsigned int *ndescr)
893 {
894     struct descr *tmp;
895     size_t i;
896
897     tmp = realloc(*d, (*ndescr + 4) * sizeof(**d));
898     if(tmp == NULL)
899         return FALSE;
900
901     *d = tmp;
902     reinit_descrs (*d, *ndescr);
903     memset(*d + *ndescr, 0, 4 * sizeof(**d));
904     for(i = *ndescr; i < *ndescr + 4; i++)
905         init_descr (*d + i);
906
907     *ndescr += 4;
908
909     return TRUE;
910 }
911
912 static int
913 next_min_free(krb5_context context, struct descr **d, unsigned int *ndescr)
914 {
915     size_t i;
916     int min_free;
917
918     for(i = 0; i < *ndescr; i++) {
919         int s = (*d + i)->s;
920         if(rk_IS_BAD_SOCKET(s))
921             return i;
922     }
923
924     min_free = *ndescr;
925     if(!realloc_descrs(d, ndescr)) {
926         min_free = -1;
927         krb5_warnx(context, "No memory");
928     }
929
930     return min_free;
931 }
932
933 static void
934 loop(krb5_context context, krb5_kdc_configuration *config,
935      struct descr **dp, unsigned int *ndescrp, int islive)
936 {
937     struct descr *d = *dp;
938     unsigned int ndescr = *ndescrp;
939
940     while (exit_flag == 0) {
941         struct timeval tmout;
942         fd_set fds;
943         int min_free = -1;
944         int max_fd = 0;
945         size_t i;
946
947         FD_ZERO(&fds);
948         if (islive > -1) {
949             FD_SET(islive, &fds);
950             max_fd = islive;
951         }
952         for (i = 0; i < ndescr; i++) {
953             if (!rk_IS_BAD_SOCKET(d[i].s)) {
954                 if (d[i].type == SOCK_STREAM &&
955                    d[i].timeout && d[i].timeout < time(NULL)) {
956                     kdc_log(context, config, 2,
957                             "TCP-connection from %s expired after %lu bytes",
958                             d[i].addr_string, (unsigned long)d[i].len);
959                     clear_descr(&d[i]);
960                     continue;
961                 }
962 #ifndef NO_LIMIT_FD_SETSIZE
963                 if (max_fd < d[i].s)
964                     max_fd = d[i].s;
965 #ifdef FD_SETSIZE
966                 if (max_fd >= FD_SETSIZE)
967                     krb5_errx(context, 1, "fd too large");
968 #endif
969 #endif
970                 FD_SET(d[i].s, &fds);
971             }
972         }
973
974         tmout.tv_sec = TCP_TIMEOUT;
975         tmout.tv_usec = 0;
976         switch(select(max_fd + 1, &fds, 0, 0, &tmout)){
977         case 0:
978             break;
979         case -1:
980             if (errno != EINTR)
981                 krb5_warn(context, rk_SOCK_ERRNO, "select");
982             break;
983         default:
984 #ifdef HAVE_FORK
985             if (islive > -1 && FD_ISSET(islive, &fds))
986                 handle_islive(islive);
987 #endif
988             for (i = 0; i < ndescr; i++)
989                 if (!rk_IS_BAD_SOCKET(d[i].s) && FD_ISSET(d[i].s, &fds)) {
990                     min_free = next_min_free(context, dp, ndescrp);
991                     ndescr = *ndescrp;
992                     d = *dp;
993
994                     if (d[i].type == SOCK_DGRAM)
995                         handle_udp(context, config, &d[i]);
996                     else if (d[i].type == SOCK_STREAM)
997                         handle_tcp(context, config, d, i, min_free);
998                 }
999         }
1000     }
1001
1002     switch (exit_flag) {
1003     case -1:
1004         kdc_log(context, config, 0,
1005                 "KDC worker process exiting because KDC master exited.");
1006         break;
1007 #ifdef SIGXCPU
1008     case SIGXCPU:
1009         kdc_log(context, config, 0, "CPU time limit exceeded");
1010         break;
1011 #endif
1012     case SIGINT:
1013     case SIGTERM:
1014         kdc_log(context, config, 0, "Terminated");
1015         break;
1016     default:
1017         kdc_log(context, config, 0, "Unexpected exit reason: %d", exit_flag);
1018         break;
1019     }
1020 }
1021
1022 #ifdef __APPLE__
1023 static void
1024 bonjour_kid(krb5_context context, krb5_kdc_configuration *config, const char *argv0, int *islive)
1025 {
1026     char buf;
1027
1028     if (do_bonjour > 0) {
1029         bonjour_announce(context, config);
1030
1031         while (read(0, &buf, 1) == 1)
1032             continue;
1033         _exit(0);
1034     }
1035
1036     if ((bonjour_pid = fork()) != 0)
1037         return;
1038
1039     close(islive[0]);
1040     if (dup2(islive[1], 0) == -1)
1041         err(1, "failed to announce with bonjour (dup)");
1042     if (islive[1] != 0)
1043         close(islive[1]);
1044     execlp(argv0, "kdc", "--bonjour", NULL);
1045     err(1, "failed to announce with bonjour (exec)");
1046 }
1047 #endif
1048
1049 #ifdef HAVE_FORK
1050 static void
1051 kill_kids(pid_t *pids, int max_kids, int sig)
1052 {
1053     int i;
1054
1055     for (i=0; i < max_kids; i++)
1056         if (pids[i] > 0)
1057             kill(sig, pids[i]);
1058     if (bonjour_pid > 0)
1059         kill(sig, bonjour_pid);
1060 }
1061
1062 static int
1063 reap_kid(krb5_context context, krb5_kdc_configuration *config,
1064          pid_t *pids, int max_kids, int options)
1065 {
1066     pid_t pid;
1067     char *what;
1068     int status;
1069     int i = 0; /* quiet warnings */
1070     int ret = 0;
1071     int level = 3;
1072     const char *sev = "info: ";
1073
1074     pid = waitpid(-1, &status, options);
1075     if (pid <= 0)
1076         return 0;
1077
1078     if (pid == bonjour_pid) {
1079         bonjour_pid = (pid_t)-1;
1080         what = "bonjour";
1081     } else {
1082         for (i=0; i < max_kids; i++) {
1083             if (pids[i] == pid) {
1084                 pids[i] = (pid_t)-1;
1085                 what = "worker";
1086                 ret = 1;
1087                 break;
1088             }
1089         }
1090
1091         if (i == max_kids) {
1092             /* should not happen */
1093             what = "untracked";
1094             sev = "warning: ";
1095             level = 2;
1096         }
1097     }
1098
1099     if (WIFEXITED(status))
1100         kdc_log(context, config, level,
1101                 "%sKDC reaped %s process: %d, exit status: %d",
1102                 sev, what, (int)pid, WEXITSTATUS(status));
1103     else if (WIFSIGNALED(status))
1104         kdc_log(context, config, level,
1105                 "%sKDC reaped %s process: %d, term signal %d%s",
1106                 sev, what, (int)pid, WTERMSIG(status),
1107                 WCOREDUMP(status) ? " (core dumped)" : "");
1108     else
1109         kdc_log(context, config, level, "%sKDC reaped %s process: %d",
1110                 sev, what, (int)pid);
1111
1112     return ret;
1113 }
1114
1115 static int
1116 reap_kids(krb5_context context, krb5_kdc_configuration *config,
1117           pid_t *pids, int max_kids)
1118 {
1119     int reaped = 0;
1120
1121     for (;;) {
1122         if (reap_kid(context, config, pids, max_kids, WNOHANG) == 0)
1123             break;
1124         reaped++;
1125     }
1126
1127     return reaped;
1128 }
1129
1130 static void
1131 select_sleep(int microseconds)
1132 {
1133     struct timeval tv;
1134
1135     tv.tv_sec = microseconds / 1000000;
1136     tv.tv_usec = microseconds % 1000000;
1137     select(0, NULL, NULL, NULL, &tv);
1138 }
1139 #endif
1140
1141 void
1142 start_kdc(krb5_context context,
1143           krb5_kdc_configuration *config, const char *argv0)
1144 {
1145     struct timeval tv1;
1146     struct timeval tv2;
1147     struct descr *d;
1148     unsigned int ndescr;
1149     pid_t pid = -1;
1150 #ifdef HAVE_FORK
1151     pid_t *pids;
1152     int max_kdcs = config->num_kdc_processes;
1153     int num_kdcs = 0;
1154     int i;
1155     int islive[2];
1156 #endif
1157
1158 #ifdef __APPLE__
1159     if (do_bonjour > 0)
1160         bonjour_kid(context, config, argv0, NULL);
1161 #endif
1162
1163 #ifdef HAVE_FORK
1164 #ifdef _SC_NPROCESSORS_ONLN
1165     if (max_kdcs < 1)
1166         max_kdcs = sysconf(_SC_NPROCESSORS_ONLN);
1167 #endif
1168
1169     if (max_kdcs < 1)
1170         max_kdcs = 1;
1171
1172     pids = calloc(max_kdcs, sizeof(*pids));
1173     if (pids == NULL)
1174         krb5_err(context, 1, errno, "malloc");
1175
1176     /*
1177      * We open a socketpair of which we hand one end to each of our kids.
1178      * When we exit, for whatever reason, the children will notice an EOF
1179      * on their end and be able to cleanly exit.
1180      */
1181
1182     if (socketpair(PF_UNIX, SOCK_STREAM, 0, islive) == -1)
1183         krb5_errx(context, 1, "socketpair");
1184     socket_set_nonblocking(islive[1], 1);
1185 #endif
1186
1187     ndescr = init_sockets(context, config, &d);
1188     if(ndescr <= 0)
1189         krb5_errx(context, 1, "No sockets!");
1190
1191 #ifdef HAVE_FORK
1192
1193 # ifdef __APPLE__
1194     if (do_bonjour < 0)
1195         bonjour_kid(context, config, argv0, islive);
1196 # endif
1197
1198     kdc_log(context, config, 3, "KDC started master process pid=%d", getpid());
1199 #else
1200     kdc_log(context, config, 3, "KDC started pid=%d", getpid());
1201 #endif
1202
1203     roken_detach_finish(NULL, daemon_child);
1204
1205 #ifdef HAVE_FORK
1206     if (!testing_flag) {
1207         /* Note that we might never execute the body of this loop */
1208         while (exit_flag == 0) {
1209
1210             if (num_kdcs >= max_kdcs) {
1211                 num_kdcs -= reap_kid(context, config, pids, max_kdcs, 0);
1212                 continue;
1213             }
1214
1215             if (num_kdcs > 0)
1216                 num_kdcs -= reap_kids(context, config, pids, max_kdcs);
1217
1218             pid = fork();
1219             switch (pid) {
1220             case 0:
1221                 close(islive[0]);
1222                 loop(context, config, &d, &ndescr, islive[1]);
1223                 exit(0);
1224             case -1:
1225                 /* XXXrcd: hmmm, do something useful?? */
1226                 kdc_log(context, config, 1,
1227                         "KDC master process could not fork worker process");
1228                 sleep(10);
1229                 break;
1230             default:
1231                 for (i = 0; i < max_kdcs; i++) {
1232                     if (pids[i] <= 0) {
1233                         pids[i] = pid;
1234                         break;
1235                     }
1236                 }
1237                 if (i >= max_kdcs) {
1238                     /* This should not happen */
1239                     kdc_log(context, config, 1,
1240                             "warning: forked untracked child process: %d",
1241                             (int)pid);
1242                 }
1243                 kdc_log(context, config, 3, "KDC worker process started: %d",
1244                         pid);
1245                 num_kdcs++;
1246                 /* Slow down the creation of KDCs... */
1247                 select_sleep(12500);
1248                 break;
1249             }
1250         }
1251
1252         /* Closing these sockets should cause the kids to die... */
1253
1254         close(islive[0]);
1255         close(islive[1]);
1256
1257         /* Close our listener sockets before terminating workers */
1258         for (i = 0; i < ndescr; ++i)
1259             clear_descr(&d[i]);
1260
1261         gettimeofday(&tv1, NULL);
1262         tv2 = tv1;
1263
1264         /* Reap every 10ms, terminate stragglers once a second, give up after 10 */
1265         for (;;) {
1266             struct timeval tv3;
1267             num_kdcs -= reap_kids(context, config, pids, max_kdcs);
1268             if (num_kdcs == 0 && bonjour_pid <= 0)
1269                 goto end;
1270             /*
1271              * Using select to sleep will fail with EINTR if we receive a
1272              * SIGCHLD.  This is desirable.
1273              */
1274             select_sleep(10000);
1275             gettimeofday(&tv3, NULL);
1276             if (tv3.tv_sec - tv1.tv_sec > 10 ||
1277                 (tv3.tv_sec - tv1.tv_sec == 10 && tv3.tv_usec >= tv1.tv_usec))
1278                 break;
1279             if (tv3.tv_sec - tv2.tv_sec > 1 ||
1280                 (tv3.tv_sec - tv2.tv_sec == 1 && tv3.tv_usec >= tv2.tv_usec)) {
1281                 kill_kids(pids, max_kdcs, SIGTERM);
1282                 tv2 = tv3;
1283             }
1284         }
1285
1286         /* Kill stragglers and reap every 200ms, give up after 15s */
1287         for (;;) {
1288             kill_kids(pids, max_kdcs, SIGKILL);
1289             num_kdcs -= reap_kids(context, config, pids, max_kdcs);
1290             if (num_kdcs == 0 && bonjour_pid <= 0)
1291                 break;
1292             select_sleep(200000);
1293             gettimeofday(&tv2, NULL);
1294             if (tv2.tv_sec - tv1.tv_sec > 15 ||
1295                 (tv2.tv_sec - tv1.tv_sec == 15 && tv2.tv_usec >= tv1.tv_usec))
1296                 break;
1297         }
1298
1299      end:
1300         kdc_log(context, config, 3, "KDC master process exiting");
1301     } else {
1302         loop(context, config, &d, &ndescr, -1);
1303         kdc_log(context, config, 3, "KDC exiting");
1304     }
1305     free(pids);
1306 #else
1307     loop(context, config, &d, &ndescr, -1);
1308     kdc_log(context, config, 3, "KDC exiting");
1309 #endif
1310
1311     free(d);
1312 }