heimdal Fix DNS name qualification to not mangle IP addresses
[samba.git] / source4 / heimdal / lib / krb5 / krbhst.c
1 /*
2  * Copyright (c) 2001 - 2003 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 "krb5_locl.h"
35 #include <resolve.h>
36 #include "locate_plugin.h"
37
38 static int
39 string_to_proto(const char *string)
40 {
41     if(strcasecmp(string, "udp") == 0)
42         return KRB5_KRBHST_UDP;
43     else if(strcasecmp(string, "tcp") == 0)
44         return KRB5_KRBHST_TCP;
45     else if(strcasecmp(string, "http") == 0)
46         return KRB5_KRBHST_HTTP;
47     return -1;
48 }
49
50 /*
51  * set `res' and `count' to the result of looking up SRV RR in DNS for
52  * `proto', `proto', `realm' using `dns_type'.
53  * if `port' != 0, force that port number
54  */
55
56 static krb5_error_code
57 srv_find_realm(krb5_context context, krb5_krbhst_info ***res, int *count,
58                const char *realm, const char *dns_type,
59                const char *proto, const char *service, int port)
60 {
61     char domain[1024];
62     struct rk_dns_reply *r;
63     struct rk_resource_record *rr;
64     int num_srv;
65     int proto_num;
66     int def_port;
67
68     *res = NULL;
69     *count = 0;
70
71     proto_num = string_to_proto(proto);
72     if(proto_num < 0) {
73         krb5_set_error_message(context, EINVAL,
74                                N_("unknown protocol `%s' to lookup", ""),
75                                proto);
76         return EINVAL;
77     }
78
79     if(proto_num == KRB5_KRBHST_HTTP)
80         def_port = ntohs(krb5_getportbyname (context, "http", "tcp", 80));
81     else if(port == 0)
82         def_port = ntohs(krb5_getportbyname (context, service, proto, 88));
83     else
84         def_port = port;
85
86     snprintf(domain, sizeof(domain), "_%s._%s.%s.", service, proto, realm);
87
88     r = rk_dns_lookup(domain, dns_type);
89     if(r == NULL) {
90         _krb5_debug(context, 0,
91                     "DNS lookup failed domain: %s", domain);
92         return KRB5_KDC_UNREACH;
93     }
94
95     for(num_srv = 0, rr = r->head; rr; rr = rr->next)
96         if(rr->type == rk_ns_t_srv)
97             num_srv++;
98
99     *res = malloc(num_srv * sizeof(**res));
100     if(*res == NULL) {
101         rk_dns_free_data(r);
102         krb5_set_error_message(context, ENOMEM,
103                                N_("malloc: out of memory", ""));
104         return ENOMEM;
105     }
106
107     rk_dns_srv_order(r);
108
109     for(num_srv = 0, rr = r->head; rr; rr = rr->next)
110         if(rr->type == rk_ns_t_srv) {
111             krb5_krbhst_info *hi;
112             size_t len = strlen(rr->u.srv->target);
113
114             hi = calloc(1, sizeof(*hi) + len);
115             if(hi == NULL) {
116                 rk_dns_free_data(r);
117                 while(--num_srv >= 0)
118                     free((*res)[num_srv]);
119                 free(*res);
120                 *res = NULL;
121                 return ENOMEM;
122             }
123             (*res)[num_srv++] = hi;
124
125             hi->proto = proto_num;
126         
127             hi->def_port = def_port;
128             if (port != 0)
129                 hi->port = port;
130             else
131                 hi->port = rr->u.srv->port;
132
133             strlcpy(hi->hostname, rr->u.srv->target, len + 1);
134         }
135
136     *count = num_srv;
137         
138     rk_dns_free_data(r);
139     return 0;
140 }
141
142
143 struct krb5_krbhst_data {
144     char *realm;
145     unsigned int flags;
146     int def_port;
147     int port;                   /* hardwired port number if != 0 */
148 #define KD_CONFIG                1
149 #define KD_SRV_UDP               2
150 #define KD_SRV_TCP               4
151 #define KD_SRV_HTTP              8
152 #define KD_FALLBACK             16
153 #define KD_CONFIG_EXISTS        32
154 #define KD_LARGE_MSG            64
155 #define KD_PLUGIN              128
156     krb5_error_code (*get_next)(krb5_context, struct krb5_krbhst_data *,
157                                 krb5_krbhst_info**);
158
159     unsigned int fallback_count;
160
161     struct krb5_krbhst_info *hosts, **index, **end;
162 };
163
164 static krb5_boolean
165 krbhst_empty(const struct krb5_krbhst_data *kd)
166 {
167     return kd->index == &kd->hosts;
168 }
169
170 /*
171  * Return the default protocol for the `kd' (either TCP or UDP)
172  */
173
174 static int
175 krbhst_get_default_proto(struct krb5_krbhst_data *kd)
176 {
177     if (kd->flags & KD_LARGE_MSG)
178         return KRB5_KRBHST_TCP;
179     return KRB5_KRBHST_UDP;
180 }
181
182 /*
183  *
184  */
185
186 const char *
187 _krb5_krbhst_get_realm(krb5_krbhst_handle handle)
188 {
189     return handle->realm;
190 }
191
192 /*
193  * parse `spec' into a krb5_krbhst_info, defaulting the port to `def_port'
194  * and forcing it to `port' if port != 0
195  */
196
197 static struct krb5_krbhst_info*
198 parse_hostspec(krb5_context context, struct krb5_krbhst_data *kd,
199                const char *spec, int def_port, int port)
200 {
201     const char *p = spec, *q;
202     struct krb5_krbhst_info *hi;
203
204     hi = calloc(1, sizeof(*hi) + strlen(spec));
205     if(hi == NULL)
206         return NULL;
207
208     hi->proto = krbhst_get_default_proto(kd);
209
210     if(strncmp(p, "http://", 7) == 0){
211         hi->proto = KRB5_KRBHST_HTTP;
212         p += 7;
213     } else if(strncmp(p, "http/", 5) == 0) {
214         hi->proto = KRB5_KRBHST_HTTP;
215         p += 5;
216         def_port = ntohs(krb5_getportbyname (context, "http", "tcp", 80));
217     }else if(strncmp(p, "tcp/", 4) == 0){
218         hi->proto = KRB5_KRBHST_TCP;
219         p += 4;
220     } else if(strncmp(p, "udp/", 4) == 0) {
221         p += 4;
222     }
223
224     if (p[0] == '[' && (q = strchr(p, ']')) != NULL) {
225         /* if address looks like [foo:bar] or [foo:bar]: its a ipv6
226            adress, strip of [] */
227         memcpy(hi->hostname, &p[1], q - p - 1);
228         hi->hostname[q - p - 1] = '\0';
229         p = q + 1;
230         /* get trailing : */
231         if (p[0] == ':')
232             p++;
233     } else if(strsep_copy(&p, ":", hi->hostname, strlen(spec) + 1) < 0) {
234         /* copy everything before : */
235         free(hi);
236         return NULL;
237     }
238     /* get rid of trailing /, and convert to lower case */
239     hi->hostname[strcspn(hi->hostname, "/")] = '\0';
240     strlwr(hi->hostname);
241
242     hi->port = hi->def_port = def_port;
243     if(p != NULL && p[0]) {
244         char *end;
245         hi->port = strtol(p, &end, 0);
246         if(end == p) {
247             free(hi);
248             return NULL;
249         }
250     }
251     if (port)
252         hi->port = port;
253     return hi;
254 }
255
256 void
257 _krb5_free_krbhst_info(krb5_krbhst_info *hi)
258 {
259     if (hi->ai != NULL)
260         freeaddrinfo(hi->ai);
261     free(hi);
262 }
263
264 krb5_error_code
265 _krb5_krbhost_info_move(krb5_context context,
266                         krb5_krbhst_info *from,
267                         krb5_krbhst_info **to)
268 {
269     size_t hostnamelen = strlen(from->hostname);
270     /* trailing NUL is included in structure */
271     *to = calloc(1, sizeof(**to) + hostnamelen);
272     if(*to == NULL) {
273         krb5_set_error_message(context, ENOMEM,
274                                N_("malloc: out of memory", ""));
275         return ENOMEM;
276     }
277
278     (*to)->proto = from->proto;
279     (*to)->port = from->port;
280     (*to)->def_port = from->def_port;
281     (*to)->ai = from->ai;
282     from->ai = NULL;
283     (*to)->next = NULL;
284     memcpy((*to)->hostname, from->hostname, hostnamelen + 1);
285     return 0;
286 }
287
288
289 static void
290 append_host_hostinfo(struct krb5_krbhst_data *kd, struct krb5_krbhst_info *host)
291 {
292     struct krb5_krbhst_info *h;
293
294     for(h = kd->hosts; h; h = h->next)
295         if(h->proto == host->proto &&
296            h->port == host->port &&
297            strcmp(h->hostname, host->hostname) == 0) {
298             _krb5_free_krbhst_info(host);
299             return;
300         }
301     *kd->end = host;
302     kd->end = &host->next;
303 }
304
305 static krb5_error_code
306 append_host_string(krb5_context context, struct krb5_krbhst_data *kd,
307                    const char *host, int def_port, int port)
308 {
309     struct krb5_krbhst_info *hi;
310
311     hi = parse_hostspec(context, kd, host, def_port, port);
312     if(hi == NULL)
313         return ENOMEM;
314
315     append_host_hostinfo(kd, hi);
316     return 0;
317 }
318
319 /*
320  * return a readable representation of `host' in `hostname, hostlen'
321  */
322
323 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
324 krb5_krbhst_format_string(krb5_context context, const krb5_krbhst_info *host,
325                           char *hostname, size_t hostlen)
326 {
327     const char *proto = "";
328     char portstr[7] = "";
329     if(host->proto == KRB5_KRBHST_TCP)
330         proto = "tcp/";
331     else if(host->proto == KRB5_KRBHST_HTTP)
332         proto = "http://";
333     if(host->port != host->def_port)
334         snprintf(portstr, sizeof(portstr), ":%d", host->port);
335     snprintf(hostname, hostlen, "%s%s%s", proto, host->hostname, portstr);
336     return 0;
337 }
338
339 /*
340  * create a getaddrinfo `hints' based on `proto'
341  */
342
343 static void
344 make_hints(struct addrinfo *hints, int proto)
345 {
346     memset(hints, 0, sizeof(*hints));
347     hints->ai_family = AF_UNSPEC;
348     switch(proto) {
349     case KRB5_KRBHST_UDP :
350         hints->ai_socktype = SOCK_DGRAM;
351         break;
352     case KRB5_KRBHST_HTTP :
353     case KRB5_KRBHST_TCP :
354         hints->ai_socktype = SOCK_STREAM;
355         break;
356     }
357 }
358
359 /*
360  * return an `struct addrinfo *' in `ai' corresponding to the information
361  * in `host'.  free:ing is handled by krb5_krbhst_free.
362  */
363
364 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
365 krb5_krbhst_get_addrinfo(krb5_context context, krb5_krbhst_info *host,
366                          struct addrinfo **ai)
367 {
368     struct addrinfo hints;
369     char portstr[NI_MAXSERV];
370     int ret;
371
372     if (host->ai == NULL) {
373         make_hints(&hints, host->proto);
374         hints.ai_flags = AI_NUMERICHOST | AI_NUMERICSERV;
375         snprintf (portstr, sizeof(portstr), "%d", host->port);
376
377         /* First try this as an IP address - the flags we have set
378          * will prevent it from looking up a name */
379         ret = getaddrinfo(host->hostname, portstr, &hints, &host->ai);
380         if (ret == 0) {
381                 *ai = host->ai;
382                 return 0;
383         }
384
385         hints.ai_flags &= ~AI_NUMERICHOST;
386
387         /* Now that we know it's not an IP, we can manipulate
388            it as a dotted-name, to add a final . if we think
389            it's a fully qualified DNS name */
390         if (strchr(host->hostname, '.') &&
391             host->hostname[strlen(host->hostname)-1] != '.') {
392                 char *hostname_dot = NULL;
393
394                 /* avoid expansion of search domains from resolv.conf
395                    - these can be very slow if the DNS server is not up
396                    for the searched domain */
397                 hostname_dot = malloc(strlen(host->hostname)+2);
398                 if (hostname_dot) {
399                         strcpy(hostname_dot, host->hostname);
400                         hostname_dot[strlen(host->hostname)] = '.';
401                         hostname_dot[strlen(host->hostname)+1] = 0;
402                 }
403                 ret = getaddrinfo(hostname_dot?hostname_dot:host->hostname, portstr, &hints, &host->ai);
404                 if (hostname_dot)
405                         free(hostname_dot);
406         } else {
407                 ret = getaddrinfo(host->hostname, portstr, &hints, &host->ai);
408         }
409         if (ret)
410             return krb5_eai_to_heim_errno(ret, errno);
411     }
412     *ai = host->ai;
413     return 0;
414 }
415
416 static krb5_boolean
417 get_next(struct krb5_krbhst_data *kd, krb5_krbhst_info **host)
418 {
419     struct krb5_krbhst_info *hi = *kd->index;
420     if(hi != NULL) {
421         *host = hi;
422         kd->index = &(*kd->index)->next;
423         return TRUE;
424     }
425     return FALSE;
426 }
427
428 static void
429 srv_get_hosts(krb5_context context, struct krb5_krbhst_data *kd,
430               const char *proto, const char *service)
431 {
432     krb5_error_code ret;
433     krb5_krbhst_info **res;
434     int count, i;
435
436     ret = srv_find_realm(context, &res, &count, kd->realm, "SRV", proto, service,
437                          kd->port);
438     _krb5_debug(context, 2, "searching DNS for realm %s %s.%s -> %d",
439                 kd->realm, proto, service, ret);
440     if (ret)
441         return;
442     for(i = 0; i < count; i++)
443         append_host_hostinfo(kd, res[i]);
444     free(res);
445 }
446
447 /*
448  * read the configuration for `conf_string', defaulting to kd->def_port and
449  * forcing it to `kd->port' if kd->port != 0
450  */
451
452 static void
453 config_get_hosts(krb5_context context, struct krb5_krbhst_data *kd,
454                  const char *conf_string)
455 {
456     int i;
457     char **hostlist;
458     hostlist = krb5_config_get_strings(context, NULL,
459                                        "realms", kd->realm, conf_string, NULL);
460
461     _krb5_debug(context, 2, "configuration file for realm %s%s found",
462                 kd->realm, hostlist ? "" : " not");
463
464     if(hostlist == NULL)
465         return;
466     kd->flags |= KD_CONFIG_EXISTS;
467     for(i = 0; hostlist && hostlist[i] != NULL; i++)
468         append_host_string(context, kd, hostlist[i], kd->def_port, kd->port);
469
470     krb5_config_free_strings(hostlist);
471 }
472
473 /*
474  * as a fallback, look for `serv_string.kd->realm' (typically
475  * kerberos.REALM, kerberos-1.REALM, ...
476  * `port' is the default port for the service, and `proto' the
477  * protocol
478  */
479
480 static krb5_error_code
481 fallback_get_hosts(krb5_context context, struct krb5_krbhst_data *kd,
482                    const char *serv_string, int port, int proto)
483 {
484     char *host;
485     int ret;
486     struct addrinfo *ai;
487     struct addrinfo hints;
488     char portstr[NI_MAXSERV];
489
490     _krb5_debug(context, 2, "fallback lookup %d for realm %s (service %s)",
491                 kd->fallback_count, kd->realm, serv_string);
492
493     /*
494      * Don't try forever in case the DNS server keep returning us
495      * entries (like wildcard entries or the .nu TLD)
496      */
497     if(kd->fallback_count >= 5) {
498         kd->flags |= KD_FALLBACK;
499         return 0;
500     }
501
502     if(kd->fallback_count == 0)
503         asprintf(&host, "%s.%s.", serv_string, kd->realm);
504     else
505         asprintf(&host, "%s-%d.%s.",
506                  serv_string, kd->fallback_count, kd->realm);   
507
508     if (host == NULL)
509         return ENOMEM;
510
511     make_hints(&hints, proto);
512     snprintf(portstr, sizeof(portstr), "%d", port);
513     ret = getaddrinfo(host, portstr, &hints, &ai);
514     if (ret) {
515         /* no more hosts, so we're done here */
516         free(host);
517         kd->flags |= KD_FALLBACK;
518     } else {
519         struct krb5_krbhst_info *hi;
520         size_t hostlen = strlen(host);
521
522         hi = calloc(1, sizeof(*hi) + hostlen);
523         if(hi == NULL) {
524             free(host);
525             return ENOMEM;
526         }
527
528         hi->proto = proto;
529         hi->port  = hi->def_port = port;
530         hi->ai    = ai;
531         memmove(hi->hostname, host, hostlen);
532         hi->hostname[hostlen] = '\0';
533         free(host);
534         append_host_hostinfo(kd, hi);
535         kd->fallback_count++;
536     }
537     return 0;
538 }
539
540 /*
541  * Fetch hosts from plugin
542  */
543
544 static krb5_error_code
545 add_locate(void *ctx, int type, struct sockaddr *addr)
546 {
547     struct krb5_krbhst_info *hi;
548     struct krb5_krbhst_data *kd = ctx;
549     char host[NI_MAXHOST], port[NI_MAXSERV];
550     struct addrinfo hints, *ai;
551     socklen_t socklen;
552     size_t hostlen;
553     int ret;
554
555     socklen = socket_sockaddr_size(addr);
556
557     ret = getnameinfo(addr, socklen, host, sizeof(host), port, sizeof(port),
558                       NI_NUMERICHOST|NI_NUMERICSERV);
559     if (ret != 0)
560         return 0;
561
562     make_hints(&hints, krbhst_get_default_proto(kd));
563     ret = getaddrinfo(host, port, &hints, &ai);
564     if (ret)
565         return 0;
566
567     hostlen = strlen(host);
568
569     hi = calloc(1, sizeof(*hi) + hostlen);
570     if(hi == NULL)
571         return ENOMEM;
572
573     hi->proto = krbhst_get_default_proto(kd);
574     hi->port  = hi->def_port = socket_get_port(addr);
575     hi->ai    = ai;
576     memmove(hi->hostname, host, hostlen);
577     hi->hostname[hostlen] = '\0';
578     append_host_hostinfo(kd, hi);
579
580     return 0;
581 }
582
583 static void
584 plugin_get_hosts(krb5_context context,
585                  struct krb5_krbhst_data *kd,
586                  enum locate_service_type type)
587 {
588     struct krb5_plugin *list = NULL, *e;
589     krb5_error_code ret;
590
591     ret = _krb5_plugin_find(context, PLUGIN_TYPE_DATA,
592                             KRB5_PLUGIN_LOCATE, &list);
593     if(ret != 0 || list == NULL)
594         return;
595
596     for (e = list; e != NULL; e = _krb5_plugin_get_next(e)) {
597         krb5plugin_service_locate_ftable *service;
598         void *ctx;
599
600         service = _krb5_plugin_get_symbol(e);
601         if (service->minor_version != 0)
602             continue;
603         
604         (*service->init)(context, &ctx);
605         ret = (*service->lookup)(ctx, type, kd->realm, 0, 0, add_locate, kd);
606         (*service->fini)(ctx);
607         if (ret && ret != KRB5_PLUGIN_NO_HANDLE) {
608             krb5_set_error_message(context, ret,
609                                    N_("Locate plugin failed to lookup realm %s: %d", ""),
610                                    kd->realm, ret);
611             break;
612         } else if (ret == 0) {
613             _krb5_debug(context, 2, "plugin found result for realm %s", kd->realm);
614             kd->flags |= KD_CONFIG_EXISTS;
615         }
616
617     }
618     _krb5_plugin_free(list);
619 }
620
621 /*
622  *
623  */
624
625 static krb5_error_code
626 kdc_get_next(krb5_context context,
627              struct krb5_krbhst_data *kd,
628              krb5_krbhst_info **host)
629 {
630     krb5_error_code ret;
631
632     if ((kd->flags & KD_PLUGIN) == 0) {
633         plugin_get_hosts(context, kd, locate_service_kdc);
634         kd->flags |= KD_PLUGIN;
635         if(get_next(kd, host))
636             return 0;
637     }
638
639     if((kd->flags & KD_CONFIG) == 0) {
640         config_get_hosts(context, kd, "kdc");
641         kd->flags |= KD_CONFIG;
642         if(get_next(kd, host))
643             return 0;
644     }
645
646     if (kd->flags & KD_CONFIG_EXISTS) {
647         _krb5_debug(context, 1,
648                     "Configuration exists for realm %s, wont go to DNS",
649                     kd->realm);
650         return KRB5_KDC_UNREACH;
651     }
652
653     if(context->srv_lookup) {
654         if((kd->flags & KD_SRV_UDP) == 0 && (kd->flags & KD_LARGE_MSG) == 0) {
655             srv_get_hosts(context, kd, "udp", "kerberos");
656             kd->flags |= KD_SRV_UDP;
657             if(get_next(kd, host))
658                 return 0;
659         }
660
661         if((kd->flags & KD_SRV_TCP) == 0) {
662             srv_get_hosts(context, kd, "tcp", "kerberos");
663             kd->flags |= KD_SRV_TCP;
664             if(get_next(kd, host))
665                 return 0;
666         }
667         if((kd->flags & KD_SRV_HTTP) == 0) {
668             srv_get_hosts(context, kd, "http", "kerberos");
669             kd->flags |= KD_SRV_HTTP;
670             if(get_next(kd, host))
671                 return 0;
672         }
673     }
674
675     while((kd->flags & KD_FALLBACK) == 0) {
676         ret = fallback_get_hosts(context, kd, "kerberos",
677                                  kd->def_port,
678                                  krbhst_get_default_proto(kd));
679         if(ret)
680             return ret;
681         if(get_next(kd, host))
682             return 0;
683     }
684
685     _krb5_debug(context, 0, "No KDC entries found for %s", kd->realm);
686
687     return KRB5_KDC_UNREACH; /* XXX */
688 }
689
690 static krb5_error_code
691 admin_get_next(krb5_context context,
692                struct krb5_krbhst_data *kd,
693                krb5_krbhst_info **host)
694 {
695     krb5_error_code ret;
696
697     if ((kd->flags & KD_PLUGIN) == 0) {
698         plugin_get_hosts(context, kd, locate_service_kadmin);
699         kd->flags |= KD_PLUGIN;
700         if(get_next(kd, host))
701             return 0;
702     }
703
704     if((kd->flags & KD_CONFIG) == 0) {
705         config_get_hosts(context, kd, "admin_server");
706         kd->flags |= KD_CONFIG;
707         if(get_next(kd, host))
708             return 0;
709     }
710
711     if (kd->flags & KD_CONFIG_EXISTS) {
712         _krb5_debug(context, 1,
713                     "Configuration exists for realm %s, wont go to DNS",
714                     kd->realm);
715         return KRB5_KDC_UNREACH;
716     }
717
718     if(context->srv_lookup) {
719         if((kd->flags & KD_SRV_TCP) == 0) {
720             srv_get_hosts(context, kd, "tcp", "kerberos-adm");
721             kd->flags |= KD_SRV_TCP;
722             if(get_next(kd, host))
723                 return 0;
724         }
725     }
726
727     if (krbhst_empty(kd)
728         && (kd->flags & KD_FALLBACK) == 0) {
729         ret = fallback_get_hosts(context, kd, "kerberos",
730                                  kd->def_port,
731                                  krbhst_get_default_proto(kd));
732         if(ret)
733             return ret;
734         kd->flags |= KD_FALLBACK;
735         if(get_next(kd, host))
736             return 0;
737     }
738
739     _krb5_debug(context, 0, "No admin entries found for realm %s", kd->realm);
740
741     return KRB5_KDC_UNREACH;    /* XXX */
742 }
743
744 static krb5_error_code
745 kpasswd_get_next(krb5_context context,
746                  struct krb5_krbhst_data *kd,
747                  krb5_krbhst_info **host)
748 {
749     krb5_error_code ret;
750
751     if ((kd->flags & KD_PLUGIN) == 0) {
752         plugin_get_hosts(context, kd, locate_service_kpasswd);
753         kd->flags |= KD_PLUGIN;
754         if(get_next(kd, host))
755             return 0;
756     }
757
758     if((kd->flags & KD_CONFIG) == 0) {
759         config_get_hosts(context, kd, "kpasswd_server");
760         kd->flags |= KD_CONFIG;
761         if(get_next(kd, host))
762             return 0;
763     }
764
765     if (kd->flags & KD_CONFIG_EXISTS) {
766         _krb5_debug(context, 1,
767                     "Configuration exists for realm %s, wont go to DNS",
768                     kd->realm);
769         return KRB5_KDC_UNREACH;
770     }
771
772     if(context->srv_lookup) {
773         if((kd->flags & KD_SRV_UDP) == 0) {
774             srv_get_hosts(context, kd, "udp", "kpasswd");
775             kd->flags |= KD_SRV_UDP;
776             if(get_next(kd, host))
777                 return 0;
778         }
779         if((kd->flags & KD_SRV_TCP) == 0) {
780             srv_get_hosts(context, kd, "tcp", "kpasswd");
781             kd->flags |= KD_SRV_TCP;
782             if(get_next(kd, host))
783                 return 0;
784         }
785     }
786
787     /* no matches -> try admin */
788
789     if (krbhst_empty(kd)) {
790         kd->flags = 0;
791         kd->port  = kd->def_port;
792         kd->get_next = admin_get_next;
793         ret = (*kd->get_next)(context, kd, host);
794         if (ret == 0)
795             (*host)->proto = krbhst_get_default_proto(kd);
796         return ret;
797     }
798
799     _krb5_debug(context, 0, "No kpasswd entries found for realm %s", kd->realm);
800
801     return KRB5_KDC_UNREACH;
802 }
803
804 static krb5_error_code
805 krb524_get_next(krb5_context context,
806                 struct krb5_krbhst_data *kd,
807                 krb5_krbhst_info **host)
808 {
809     if ((kd->flags & KD_PLUGIN) == 0) {
810         plugin_get_hosts(context, kd, locate_service_krb524);
811         kd->flags |= KD_PLUGIN;
812         if(get_next(kd, host))
813             return 0;
814     }
815
816     if((kd->flags & KD_CONFIG) == 0) {
817         config_get_hosts(context, kd, "krb524_server");
818         if(get_next(kd, host))
819             return 0;
820         kd->flags |= KD_CONFIG;
821     }
822
823     if (kd->flags & KD_CONFIG_EXISTS) {
824         _krb5_debug(context, 1,
825                     "Configuration exists for realm %s, wont go to DNS",
826                     kd->realm);
827         return KRB5_KDC_UNREACH;
828     }
829
830     if(context->srv_lookup) {
831         if((kd->flags & KD_SRV_UDP) == 0) {
832             srv_get_hosts(context, kd, "udp", "krb524");
833             kd->flags |= KD_SRV_UDP;
834             if(get_next(kd, host))
835                 return 0;
836         }
837
838         if((kd->flags & KD_SRV_TCP) == 0) {
839             srv_get_hosts(context, kd, "tcp", "krb524");
840             kd->flags |= KD_SRV_TCP;
841             if(get_next(kd, host))
842                 return 0;
843         }
844     }
845
846     /* no matches -> try kdc */
847
848     if (krbhst_empty(kd)) {
849         kd->flags = 0;
850         kd->port  = kd->def_port;
851         kd->get_next = kdc_get_next;
852         return (*kd->get_next)(context, kd, host);
853     }
854
855     _krb5_debug(context, 0, "No kpasswd entries found for realm %s", kd->realm);
856
857     return KRB5_KDC_UNREACH;
858 }
859
860 static struct krb5_krbhst_data*
861 common_init(krb5_context context,
862             const char *service,
863             const char *realm,
864             int flags)
865 {
866     struct krb5_krbhst_data *kd;
867
868     if((kd = calloc(1, sizeof(*kd))) == NULL)
869         return NULL;
870
871     if((kd->realm = strdup(realm)) == NULL) {
872         free(kd);
873         return NULL;
874     }
875
876     _krb5_debug(context, 2, "Trying to find service %s for realm %s flags %x",
877                 service, realm, flags);
878
879     /* For 'realms' without a . do not even think of going to DNS */
880     if (!strchr(realm, '.'))
881         kd->flags |= KD_CONFIG_EXISTS;
882
883     if (flags & KRB5_KRBHST_FLAGS_LARGE_MSG)
884         kd->flags |= KD_LARGE_MSG;
885     kd->end = kd->index = &kd->hosts;
886     return kd;
887 }
888
889 /*
890  * initialize `handle' to look for hosts of type `type' in realm `realm'
891  */
892
893 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
894 krb5_krbhst_init(krb5_context context,
895                  const char *realm,
896                  unsigned int type,
897                  krb5_krbhst_handle *handle)
898 {
899     return krb5_krbhst_init_flags(context, realm, type, 0, handle);
900 }
901
902 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
903 krb5_krbhst_init_flags(krb5_context context,
904                        const char *realm,
905                        unsigned int type,
906                        int flags,
907                        krb5_krbhst_handle *handle)
908 {
909     struct krb5_krbhst_data *kd;
910     krb5_error_code (*next)(krb5_context, struct krb5_krbhst_data *,
911                             krb5_krbhst_info **);
912     int def_port;
913     const char *service;
914
915     switch(type) {
916     case KRB5_KRBHST_KDC:
917         next = kdc_get_next;
918         def_port = ntohs(krb5_getportbyname (context, "kerberos", "udp", 88));
919         service = "kdc";
920         break;
921     case KRB5_KRBHST_ADMIN:
922         next = admin_get_next;
923         def_port = ntohs(krb5_getportbyname (context, "kerberos-adm",
924                                              "tcp", 749));
925         service = "admin";
926         break;
927     case KRB5_KRBHST_CHANGEPW:
928         next = kpasswd_get_next;
929         def_port = ntohs(krb5_getportbyname (context, "kpasswd", "udp",
930                                              KPASSWD_PORT));
931         service = "change_password";
932         break;
933     case KRB5_KRBHST_KRB524:
934         next = krb524_get_next;
935         def_port = ntohs(krb5_getportbyname (context, "krb524", "udp", 4444));
936         service = "524";
937         break;
938     default:
939         krb5_set_error_message(context, ENOTTY,
940                                N_("unknown krbhst type (%u)", ""), type);
941         return ENOTTY;
942     }
943     if((kd = common_init(context, service, realm, flags)) == NULL)
944         return ENOMEM;
945     kd->get_next = next;
946     kd->def_port = def_port;
947     *handle = kd;
948     return 0;
949 }
950
951 /*
952  * return the next host information from `handle' in `host'
953  */
954
955 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
956 krb5_krbhst_next(krb5_context context,
957                  krb5_krbhst_handle handle,
958                  krb5_krbhst_info **host)
959 {
960     if(get_next(handle, host))
961         return 0;
962
963     return (*handle->get_next)(context, handle, host);
964 }
965
966 /*
967  * return the next host information from `handle' as a host name
968  * in `hostname' (or length `hostlen)
969  */
970
971 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
972 krb5_krbhst_next_as_string(krb5_context context,
973                            krb5_krbhst_handle handle,
974                            char *hostname,
975                            size_t hostlen)
976 {
977     krb5_error_code ret;
978     krb5_krbhst_info *host;
979     ret = krb5_krbhst_next(context, handle, &host);
980     if(ret)
981         return ret;
982     return krb5_krbhst_format_string(context, host, hostname, hostlen);
983 }
984
985
986 KRB5_LIB_FUNCTION void KRB5_LIB_CALL
987 krb5_krbhst_reset(krb5_context context, krb5_krbhst_handle handle)
988 {
989     handle->index = &handle->hosts;
990 }
991
992 KRB5_LIB_FUNCTION void KRB5_LIB_CALL
993 krb5_krbhst_free(krb5_context context, krb5_krbhst_handle handle)
994 {
995     krb5_krbhst_info *h, *next;
996
997     if (handle == NULL)
998         return;
999
1000     for (h = handle->hosts; h != NULL; h = next) {
1001         next = h->next;
1002         _krb5_free_krbhst_info(h);
1003     }
1004
1005     free(handle->realm);
1006     free(handle);
1007 }
1008
1009 /* backwards compatibility ahead */
1010
1011 static krb5_error_code
1012 gethostlist(krb5_context context, const char *realm,
1013             unsigned int type, char ***hostlist)
1014 {
1015     krb5_error_code ret;
1016     int nhost = 0;
1017     krb5_krbhst_handle handle;
1018     char host[MAXHOSTNAMELEN];
1019     krb5_krbhst_info *hostinfo;
1020
1021     ret = krb5_krbhst_init(context, realm, type, &handle);
1022     if (ret)
1023         return ret;
1024
1025     while(krb5_krbhst_next(context, handle, &hostinfo) == 0)
1026         nhost++;
1027     if(nhost == 0) {
1028         krb5_set_error_message(context, KRB5_KDC_UNREACH,
1029                                N_("No KDC found for realm %s", ""), realm);
1030         return KRB5_KDC_UNREACH;
1031     }
1032     *hostlist = calloc(nhost + 1, sizeof(**hostlist));
1033     if(*hostlist == NULL) {
1034         krb5_krbhst_free(context, handle);
1035         return ENOMEM;
1036     }
1037
1038     krb5_krbhst_reset(context, handle);
1039     nhost = 0;
1040     while(krb5_krbhst_next_as_string(context, handle,
1041                                      host, sizeof(host)) == 0) {
1042         if(((*hostlist)[nhost++] = strdup(host)) == NULL) {
1043             krb5_free_krbhst(context, *hostlist);
1044             krb5_krbhst_free(context, handle);
1045             return ENOMEM;
1046         }
1047     }
1048     (*hostlist)[nhost] = NULL;
1049     krb5_krbhst_free(context, handle);
1050     return 0;
1051 }
1052
1053 /*
1054  * return an malloced list of kadmin-hosts for `realm' in `hostlist'
1055  */
1056
1057 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
1058 krb5_get_krb_admin_hst (krb5_context context,
1059                         const krb5_realm *realm,
1060                         char ***hostlist)
1061 {
1062     return gethostlist(context, *realm, KRB5_KRBHST_ADMIN, hostlist);
1063 }
1064
1065 /*
1066  * return an malloced list of changepw-hosts for `realm' in `hostlist'
1067  */
1068
1069 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
1070 krb5_get_krb_changepw_hst (krb5_context context,
1071                            const krb5_realm *realm,
1072                            char ***hostlist)
1073 {
1074     return gethostlist(context, *realm, KRB5_KRBHST_CHANGEPW, hostlist);
1075 }
1076
1077 /*
1078  * return an malloced list of 524-hosts for `realm' in `hostlist'
1079  */
1080
1081 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
1082 krb5_get_krb524hst (krb5_context context,
1083                     const krb5_realm *realm,
1084                     char ***hostlist)
1085 {
1086     return gethostlist(context, *realm, KRB5_KRBHST_KRB524, hostlist);
1087 }
1088
1089
1090 /*
1091  * return an malloced list of KDC's for `realm' in `hostlist'
1092  */
1093
1094 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
1095 krb5_get_krbhst (krb5_context context,
1096                  const krb5_realm *realm,
1097                  char ***hostlist)
1098 {
1099     return gethostlist(context, *realm, KRB5_KRBHST_KDC, hostlist);
1100 }
1101
1102 /*
1103  * free all the memory allocated in `hostlist'
1104  */
1105
1106 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
1107 krb5_free_krbhst (krb5_context context,
1108                   char **hostlist)
1109 {
1110     char **p;
1111
1112     for (p = hostlist; *p; ++p)
1113         free (*p);
1114     free (hostlist);
1115     return 0;
1116 }