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