s4:heimdal: import lorikeet-heimdal-200906080040 (commit 904d0124b46eed7a8ad6e5b73e89...
[amitay/samba.git] / source4 / heimdal / lib / krb5 / principal.c
1 /*
2  * Copyright (c) 1997-2007 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 /**
35  * @page krb5_principal_intro The principal handing functions.
36  *
37  * A Kerberos principal is a email address looking string that
38  * contains to parts separeted by a @.  The later part is the kerbero
39  * realm the principal belongs to and the former is a list of 0 or
40  * more components. For example
41  * @verbatim
42 lha@SU.SE
43 host/hummel.it.su.se@SU.SE
44 host/admin@H5L.ORG
45 @endverbatim
46  *
47  * See the library functions here: @ref krb5_principal
48  */
49
50 #include "krb5_locl.h"
51 #ifdef HAVE_RES_SEARCH
52 #define USE_RESOLVER
53 #endif
54 #ifdef HAVE_ARPA_NAMESER_H
55 #include <arpa/nameser.h>
56 #endif
57 #include <fnmatch.h>
58 #include "resolve.h"
59
60 #define princ_num_comp(P) ((P)->name.name_string.len)
61 #define princ_type(P) ((P)->name.name_type)
62 #define princ_comp(P) ((P)->name.name_string.val)
63 #define princ_ncomp(P, N) ((P)->name.name_string.val[(N)])
64 #define princ_realm(P) ((P)->realm)
65
66 /**
67  * Frees a Kerberos principal allocated by the library with
68  * krb5_parse_name(), krb5_make_principal() or any other related
69  * principal functions.
70  *
71  * @param context A Kerberos context.
72  * @param p a principal to free.
73  *
74  * @return An krb5 error code, see krb5_get_error_message().
75  *
76  * @ingroup krb5_principal
77  */
78
79 void KRB5_LIB_FUNCTION
80 krb5_free_principal(krb5_context context,
81                     krb5_principal p)
82 {
83     if(p){
84         free_Principal(p);
85         free(p);
86     }
87 }
88
89 /**
90  * Set the type of the principal
91  *
92  * @param context A Kerberos context.
93  * @param principal principal to set the type for
94  * @param type the new type
95  *
96  * @return An krb5 error code, see krb5_get_error_message().
97  *
98  * @ingroup krb5_principal
99  */
100
101 void KRB5_LIB_FUNCTION
102 krb5_principal_set_type(krb5_context context,
103                         krb5_principal principal,
104                         int type)
105 {
106     princ_type(principal) = type;
107 }
108
109 int KRB5_LIB_FUNCTION
110 krb5_principal_get_type(krb5_context context,
111                         krb5_const_principal principal)
112 {
113     return princ_type(principal);
114 }
115
116 const char* KRB5_LIB_FUNCTION
117 krb5_principal_get_realm(krb5_context context,
118                          krb5_const_principal principal)
119 {
120     return princ_realm(principal);
121 }                       
122
123 const char* KRB5_LIB_FUNCTION
124 krb5_principal_get_comp_string(krb5_context context,
125                                krb5_const_principal principal,
126                                unsigned int component)
127 {
128     if(component >= princ_num_comp(principal))
129        return NULL;
130     return princ_ncomp(principal, component);
131 }
132
133 /**
134  * Get number of component is principal.
135  *
136  * @param context Kerberos 5 context
137  * @param principal principal to query
138  *
139  * @return number of components in string
140  *
141  * @ingroup krb5_principal
142  */
143
144 unsigned int KRB5_LIB_FUNCTION
145 krb5_principal_get_num_comp(krb5_context context,
146                             krb5_const_principal principal)
147 {
148     return princ_num_comp(principal);
149 }
150
151 krb5_error_code KRB5_LIB_FUNCTION
152 krb5_parse_name_flags(krb5_context context,
153                       const char *name,
154                       int flags,
155                       krb5_principal *principal)
156 {
157     krb5_error_code ret;
158     heim_general_string *comp;
159     heim_general_string realm = NULL;
160     int ncomp;
161
162     const char *p;
163     char *q;
164     char *s;
165     char *start;
166
167     int n;
168     char c;
169     int got_realm = 0;
170     int first_at = 1;
171     int enterprise = (flags & KRB5_PRINCIPAL_PARSE_ENTERPRISE);
172
173     *principal = NULL;
174
175 #define RFLAGS (KRB5_PRINCIPAL_PARSE_NO_REALM|KRB5_PRINCIPAL_PARSE_REQUIRE_REALM)
176
177     if ((flags & RFLAGS) == RFLAGS) {
178         krb5_set_error_message(context, KRB5_ERR_NO_SERVICE,
179                                N_("Can't require both realm and "
180                                   "no realm at the same time", ""));
181         return KRB5_ERR_NO_SERVICE;
182     }
183 #undef RFLAGS
184
185     /* count number of component,
186      * enterprise names only have one component
187      */
188     ncomp = 1;
189     if (!enterprise) {
190         for(p = name; *p; p++){
191             if(*p=='\\'){
192                 if(!p[1]) {
193                     krb5_set_error_message(context, KRB5_PARSE_MALFORMED,
194                                            N_("trailing \\ in principal name", ""));
195                     return KRB5_PARSE_MALFORMED;
196                 }
197                 p++;
198             } else if(*p == '/')
199                 ncomp++;
200             else if(*p == '@')
201                 break;
202         }
203     }
204     comp = calloc(ncomp, sizeof(*comp));
205     if (comp == NULL) {
206         krb5_set_error_message(context, ENOMEM,
207                                N_("malloc: out of memory", ""));
208         return ENOMEM;
209     }
210
211     n = 0;
212     p = start = q = s = strdup(name);
213     if (start == NULL) {
214         free (comp);
215         krb5_set_error_message(context, ENOMEM,
216                                N_("malloc: out of memory", ""));
217         return ENOMEM;
218     }
219     while(*p){
220         c = *p++;
221         if(c == '\\'){
222             c = *p++;
223             if(c == 'n')
224                 c = '\n';
225             else if(c == 't')
226                 c = '\t';
227             else if(c == 'b')
228                 c = '\b';
229             else if(c == '0')
230                 c = '\0';
231             else if(c == '\0') {
232                 ret = KRB5_PARSE_MALFORMED;
233                 krb5_set_error_message(context, ret,
234                                        N_("trailing \\ in principal name", ""));
235                 goto exit;
236             }
237         }else if(enterprise && first_at) {
238             if (c == '@')
239                 first_at = 0;
240         }else if((c == '/' && !enterprise) || c == '@'){
241             if(got_realm){
242                 ret = KRB5_PARSE_MALFORMED;
243                 krb5_set_error_message(context, ret,
244                                        N_("part after realm in principal name", ""));
245                 goto exit;
246             }else{
247                 comp[n] = malloc(q - start + 1);
248                 if (comp[n] == NULL) {
249                     ret = ENOMEM;
250                     krb5_set_error_message(context, ret,
251                                            N_("malloc: out of memory", ""));
252                     goto exit;
253                 }
254                 memcpy(comp[n], start, q - start);
255                 comp[n][q - start] = 0;
256                 n++;
257             }
258             if(c == '@')
259                 got_realm = 1;
260             start = q;
261             continue;
262         }
263         if(got_realm && (c == '/' || c == '\0')) {
264             ret = KRB5_PARSE_MALFORMED;
265             krb5_set_error_message(context, ret,
266                                    N_("part after realm in principal name", ""));
267             goto exit;
268         }
269         *q++ = c;
270     }
271     if(got_realm){
272         if (flags & KRB5_PRINCIPAL_PARSE_NO_REALM) {
273             ret = KRB5_PARSE_MALFORMED;
274             krb5_set_error_message(context, ret,
275                                    N_("realm found in 'short' principal "
276                                       "expected to be without one", ""));
277             goto exit;
278         }
279         realm = malloc(q - start + 1);
280         if (realm == NULL) {
281             ret = ENOMEM;
282             krb5_set_error_message(context, ret,
283                                    N_("malloc: out of memory", ""));
284             goto exit;
285         }
286         memcpy(realm, start, q - start);
287         realm[q - start] = 0;
288     }else{
289         if (flags & KRB5_PRINCIPAL_PARSE_REQUIRE_REALM) {
290             ret = KRB5_PARSE_MALFORMED;
291             krb5_set_error_message(context, ret,
292                                    N_("realm NOT found in principal "
293                                       "expected to be with one", ""));
294             goto exit;
295         } else if (flags & KRB5_PRINCIPAL_PARSE_NO_REALM) {
296             realm = NULL;
297         } else {
298             ret = krb5_get_default_realm (context, &realm);
299             if (ret)
300                 goto exit;
301         }
302
303         comp[n] = malloc(q - start + 1);
304         if (comp[n] == NULL) {
305             ret = ENOMEM;
306             krb5_set_error_message(context, ret,
307                                    N_("malloc: out of memory", ""));
308             goto exit;
309         }
310         memcpy(comp[n], start, q - start);
311         comp[n][q - start] = 0;
312         n++;
313     }
314     *principal = malloc(sizeof(**principal));
315     if (*principal == NULL) {
316         ret = ENOMEM;
317         krb5_set_error_message(context, ret,
318                                N_("malloc: out of memory", ""));
319         goto exit;
320     }
321     if (enterprise)
322         (*principal)->name.name_type = KRB5_NT_ENTERPRISE_PRINCIPAL;
323     else
324         (*principal)->name.name_type = KRB5_NT_PRINCIPAL;
325     (*principal)->name.name_string.val = comp;
326     princ_num_comp(*principal) = n;
327     (*principal)->realm = realm;
328     free(s);
329     return 0;
330 exit:
331     while(n>0){
332         free(comp[--n]);
333     }
334     free(comp);
335     free(realm);
336     free(s);
337     return ret;
338 }
339
340 krb5_error_code KRB5_LIB_FUNCTION
341 krb5_parse_name(krb5_context context,
342                 const char *name,
343                 krb5_principal *principal)
344 {
345     return krb5_parse_name_flags(context, name, 0, principal);
346 }
347
348 static const char quotable_chars[] = " \n\t\b\\/@";
349 static const char replace_chars[] = " ntb\\/@";
350 static const char nq_chars[] = "    \\/@";
351
352 #define add_char(BASE, INDEX, LEN, C) do { if((INDEX) < (LEN)) (BASE)[(INDEX)++] = (C); }while(0);
353
354 static size_t
355 quote_string(const char *s, char *out, size_t idx, size_t len, int display)
356 {
357     const char *p, *q;
358     for(p = s; *p && idx < len; p++){
359         q = strchr(quotable_chars, *p);
360         if (q && display) {
361             add_char(out, idx, len, replace_chars[q - quotable_chars]);
362         } else if (q) {
363             add_char(out, idx, len, '\\');
364             add_char(out, idx, len, replace_chars[q - quotable_chars]);
365         }else
366             add_char(out, idx, len, *p);
367     }
368     if(idx < len)
369         out[idx] = '\0';
370     return idx;
371 }
372
373
374 static krb5_error_code
375 unparse_name_fixed(krb5_context context,
376                    krb5_const_principal principal,
377                    char *name,
378                    size_t len,
379                    int flags)
380 {
381     size_t idx = 0;
382     int i;
383     int short_form = (flags & KRB5_PRINCIPAL_UNPARSE_SHORT) != 0;
384     int no_realm = (flags & KRB5_PRINCIPAL_UNPARSE_NO_REALM) != 0;
385     int display = (flags & KRB5_PRINCIPAL_UNPARSE_DISPLAY) != 0;
386
387     if (!no_realm && princ_realm(principal) == NULL) {
388         krb5_set_error_message(context, ERANGE,
389                                N_("Realm missing from principal, "
390                                   "can't unparse", ""));
391         return ERANGE;
392     }
393
394     for(i = 0; i < princ_num_comp(principal); i++){
395         if(i)
396             add_char(name, idx, len, '/');
397         idx = quote_string(princ_ncomp(principal, i), name, idx, len, display);
398         if(idx == len) {
399             krb5_set_error_message(context, ERANGE,
400                                    N_("Out of space printing principal", ""));
401             return ERANGE;
402         }
403     }
404     /* add realm if different from default realm */
405     if(short_form && !no_realm) {
406         krb5_realm r;
407         krb5_error_code ret;
408         ret = krb5_get_default_realm(context, &r);
409         if(ret)
410             return ret;
411         if(strcmp(princ_realm(principal), r) != 0)
412             short_form = 0;
413         free(r);
414     }
415     if(!short_form && !no_realm) {
416         add_char(name, idx, len, '@');
417         idx = quote_string(princ_realm(principal), name, idx, len, display);
418         if(idx == len) {
419             krb5_set_error_message(context, ERANGE,
420                                    N_("Out of space printing "
421                                       "realm of principal", ""));
422             return ERANGE;
423         }
424     }
425     return 0;
426 }
427
428 krb5_error_code KRB5_LIB_FUNCTION
429 krb5_unparse_name_fixed(krb5_context context,
430                         krb5_const_principal principal,
431                         char *name,
432                         size_t len)
433 {
434     return unparse_name_fixed(context, principal, name, len, 0);
435 }
436
437 krb5_error_code KRB5_LIB_FUNCTION
438 krb5_unparse_name_fixed_short(krb5_context context,
439                               krb5_const_principal principal,
440                               char *name,
441                               size_t len)
442 {
443     return unparse_name_fixed(context, principal, name, len,
444                               KRB5_PRINCIPAL_UNPARSE_SHORT);
445 }
446
447 krb5_error_code KRB5_LIB_FUNCTION
448 krb5_unparse_name_fixed_flags(krb5_context context,
449                               krb5_const_principal principal,
450                               int flags,
451                               char *name,
452                               size_t len)
453 {
454     return unparse_name_fixed(context, principal, name, len, flags);
455 }
456
457 static krb5_error_code
458 unparse_name(krb5_context context,
459              krb5_const_principal principal,
460              char **name,
461              int flags)
462 {
463     size_t len = 0, plen;
464     int i;
465     krb5_error_code ret;
466     /* count length */
467     if (princ_realm(principal)) {
468         plen = strlen(princ_realm(principal));
469
470         if(strcspn(princ_realm(principal), quotable_chars) == plen)
471             len += plen;
472         else
473             len += 2*plen;
474         len++; /* '@' */
475     }
476     for(i = 0; i < princ_num_comp(principal); i++){
477         plen = strlen(princ_ncomp(principal, i));
478         if(strcspn(princ_ncomp(principal, i), quotable_chars) == plen)
479             len += plen;
480         else
481             len += 2*plen;
482         len++;
483     }
484     len++; /* '\0' */
485     *name = malloc(len);
486     if(*name == NULL) {
487         krb5_set_error_message(context, ENOMEM,
488                                N_("malloc: out of memory", ""));
489         return ENOMEM;
490     }
491     ret = unparse_name_fixed(context, principal, *name, len, flags);
492     if(ret) {
493         free(*name);
494         *name = NULL;
495     }
496     return ret;
497 }
498
499 krb5_error_code KRB5_LIB_FUNCTION
500 krb5_unparse_name(krb5_context context,
501                   krb5_const_principal principal,
502                   char **name)
503 {
504     return unparse_name(context, principal, name, 0);
505 }
506
507 krb5_error_code KRB5_LIB_FUNCTION
508 krb5_unparse_name_flags(krb5_context context,
509                         krb5_const_principal principal,
510                         int flags,
511                         char **name)
512 {
513     return unparse_name(context, principal, name, flags);
514 }
515
516 krb5_error_code KRB5_LIB_FUNCTION
517 krb5_unparse_name_short(krb5_context context,
518                         krb5_const_principal principal,
519                         char **name)
520 {
521     return unparse_name(context, principal, name, KRB5_PRINCIPAL_UNPARSE_SHORT);
522 }
523
524 #if 0 /* not implemented */
525
526 krb5_error_code KRB5_LIB_FUNCTION
527 krb5_unparse_name_ext(krb5_context context,
528                       krb5_const_principal principal,
529                       char **name,
530                       size_t *size)
531 {
532     krb5_abortx(context, "unimplemented krb5_unparse_name_ext called");
533 }
534
535 #endif
536
537 krb5_error_code KRB5_LIB_FUNCTION
538 krb5_principal_set_realm(krb5_context context,
539                          krb5_principal principal,
540                          krb5_const_realm realm)
541 {
542     if (princ_realm(principal))
543         free(princ_realm(principal));
544
545     princ_realm(principal) = strdup(realm);
546     if (princ_realm(principal) == NULL) {
547         krb5_set_error_message(context, ENOMEM,
548                                N_("malloc: out of memory", ""));
549         return ENOMEM;
550     }
551     return 0;
552 }
553
554
555 krb5_error_code KRB5_LIB_FUNCTION
556 krb5_build_principal(krb5_context context,
557                      krb5_principal *principal,
558                      int rlen,
559                      krb5_const_realm realm,
560                      ...)
561 {
562     krb5_error_code ret;
563     va_list ap;
564     va_start(ap, realm);
565     ret = krb5_build_principal_va(context, principal, rlen, realm, ap);
566     va_end(ap);
567     return ret;
568 }
569
570 static krb5_error_code
571 append_component(krb5_context context, krb5_principal p,
572                  const char *comp,
573                  size_t comp_len)
574 {
575     heim_general_string *tmp;
576     size_t len = princ_num_comp(p);
577
578     tmp = realloc(princ_comp(p), (len + 1) * sizeof(*tmp));
579     if(tmp == NULL) {
580         krb5_set_error_message(context, ENOMEM,
581                                N_("malloc: out of memory", ""));
582         return ENOMEM;
583     }
584     princ_comp(p) = tmp;
585     princ_ncomp(p, len) = malloc(comp_len + 1);
586     if (princ_ncomp(p, len) == NULL) {
587         krb5_set_error_message(context, ENOMEM,
588                                N_("malloc: out of memory", ""));
589         return ENOMEM;
590     }
591     memcpy (princ_ncomp(p, len), comp, comp_len);
592     princ_ncomp(p, len)[comp_len] = '\0';
593     princ_num_comp(p)++;
594     return 0;
595 }
596
597 static void
598 va_ext_princ(krb5_context context, krb5_principal p, va_list ap)
599 {
600     while(1){
601         const char *s;
602         int len;
603         len = va_arg(ap, int);
604         if(len == 0)
605             break;
606         s = va_arg(ap, const char*);
607         append_component(context, p, s, len);
608     }
609 }
610
611 static void
612 va_princ(krb5_context context, krb5_principal p, va_list ap)
613 {
614     while(1){
615         const char *s;
616         s = va_arg(ap, const char*);
617         if(s == NULL)
618             break;
619         append_component(context, p, s, strlen(s));
620     }
621 }
622
623
624 static krb5_error_code
625 build_principal(krb5_context context,
626                 krb5_principal *principal,
627                 int rlen,
628                 krb5_const_realm realm,
629                 void (*func)(krb5_context, krb5_principal, va_list),
630                 va_list ap)
631 {
632     krb5_principal p;
633
634     p = calloc(1, sizeof(*p));
635     if (p == NULL) {
636         krb5_set_error_message(context, ENOMEM,
637                                N_("malloc: out of memory", ""));
638         return ENOMEM;
639     }
640     princ_type(p) = KRB5_NT_PRINCIPAL;
641
642     princ_realm(p) = strdup(realm);
643     if(p->realm == NULL){
644         free(p);
645         krb5_set_error_message(context, ENOMEM,
646                                N_("malloc: out of memory", ""));
647         return ENOMEM;
648     }
649
650     (*func)(context, p, ap);
651     *principal = p;
652     return 0;
653 }
654
655 krb5_error_code KRB5_LIB_FUNCTION
656 krb5_make_principal(krb5_context context,
657                     krb5_principal *principal,
658                     krb5_const_realm realm,
659                     ...)
660 {
661     krb5_error_code ret;
662     krb5_realm r = NULL;
663     va_list ap;
664     if(realm == NULL) {
665         ret = krb5_get_default_realm(context, &r);
666         if(ret)
667             return ret;
668         realm = r;
669     }
670     va_start(ap, realm);
671     ret = krb5_build_principal_va(context, principal, strlen(realm), realm, ap);
672     va_end(ap);
673     if(r)
674         free(r);
675     return ret;
676 }
677
678 krb5_error_code KRB5_LIB_FUNCTION
679 krb5_build_principal_va(krb5_context context,
680                         krb5_principal *principal,
681                         int rlen,
682                         krb5_const_realm realm,
683                         va_list ap)
684 {
685     return build_principal(context, principal, rlen, realm, va_princ, ap);
686 }
687
688 krb5_error_code KRB5_LIB_FUNCTION
689 krb5_build_principal_va_ext(krb5_context context,
690                             krb5_principal *principal,
691                             int rlen,
692                             krb5_const_realm realm,
693                             va_list ap)
694 {
695     return build_principal(context, principal, rlen, realm, va_ext_princ, ap);
696 }
697
698
699 krb5_error_code KRB5_LIB_FUNCTION
700 krb5_build_principal_ext(krb5_context context,
701                          krb5_principal *principal,
702                          int rlen,
703                          krb5_const_realm realm,
704                          ...)
705 {
706     krb5_error_code ret;
707     va_list ap;
708     va_start(ap, realm);
709     ret = krb5_build_principal_va_ext(context, principal, rlen, realm, ap);
710     va_end(ap);
711     return ret;
712 }
713
714
715 krb5_error_code KRB5_LIB_FUNCTION
716 krb5_copy_principal(krb5_context context,
717                     krb5_const_principal inprinc,
718                     krb5_principal *outprinc)
719 {
720     krb5_principal p = malloc(sizeof(*p));
721     if (p == NULL) {
722         krb5_set_error_message(context, ENOMEM,
723                                N_("malloc: out of memory", ""));
724         return ENOMEM;
725     }
726     if(copy_Principal(inprinc, p)) {
727         free(p);
728         krb5_set_error_message(context, ENOMEM,
729                                N_("malloc: out of memory", ""));
730         return ENOMEM;
731     }
732     *outprinc = p;
733     return 0;
734 }
735
736 /*
737  * return TRUE iff princ1 == princ2 (without considering the realm)
738  */
739
740 krb5_boolean KRB5_LIB_FUNCTION
741 krb5_principal_compare_any_realm(krb5_context context,
742                                  krb5_const_principal princ1,
743                                  krb5_const_principal princ2)
744 {
745     int i;
746     if(princ_num_comp(princ1) != princ_num_comp(princ2))
747         return FALSE;
748     for(i = 0; i < princ_num_comp(princ1); i++){
749         if(strcmp(princ_ncomp(princ1, i), princ_ncomp(princ2, i)) != 0)
750             return FALSE;
751     }
752     return TRUE;
753 }
754
755 krb5_boolean KRB5_LIB_FUNCTION
756 _krb5_principal_compare_PrincipalName(krb5_context context,
757                                       krb5_const_principal princ1,
758                                       PrincipalName *princ2)
759 {
760     int i;
761     if (princ_num_comp(princ1) != princ2->name_string.len)
762         return FALSE;
763     for(i = 0; i < princ_num_comp(princ1); i++){
764         if(strcmp(princ_ncomp(princ1, i), princ2->name_string.val[i]) != 0)
765             return FALSE;
766     }
767     return TRUE;
768 }
769
770
771 /*
772  * return TRUE iff princ1 == princ2
773  */
774
775 krb5_boolean KRB5_LIB_FUNCTION
776 krb5_principal_compare(krb5_context context,
777                        krb5_const_principal princ1,
778                        krb5_const_principal princ2)
779 {
780     if(!krb5_realm_compare(context, princ1, princ2))
781         return FALSE;
782     return krb5_principal_compare_any_realm(context, princ1, princ2);
783 }
784
785 /*
786  * return TRUE iff realm(princ1) == realm(princ2)
787  */
788
789 krb5_boolean KRB5_LIB_FUNCTION
790 krb5_realm_compare(krb5_context context,
791                    krb5_const_principal princ1,
792                    krb5_const_principal princ2)
793 {
794     return strcmp(princ_realm(princ1), princ_realm(princ2)) == 0;
795 }
796
797 /*
798  * return TRUE iff princ matches pattern
799  */
800
801 krb5_boolean KRB5_LIB_FUNCTION
802 krb5_principal_match(krb5_context context,
803                      krb5_const_principal princ,
804                      krb5_const_principal pattern)
805 {
806     int i;
807     if(princ_num_comp(princ) != princ_num_comp(pattern))
808         return FALSE;
809     if(fnmatch(princ_realm(pattern), princ_realm(princ), 0) != 0)
810         return FALSE;
811     for(i = 0; i < princ_num_comp(princ); i++){
812         if(fnmatch(princ_ncomp(pattern, i), princ_ncomp(princ, i), 0) != 0)
813             return FALSE;
814     }
815     return TRUE;
816 }
817
818 #if defined(KRB4) || !defined(HEIMDAL_SMALLER)
819
820 static struct v4_name_convert {
821     const char *from;
822     const char *to;
823 } default_v4_name_convert[] = {
824     { "ftp",    "ftp" },
825     { "hprop",  "hprop" },
826     { "pop",    "pop" },
827     { "imap",   "imap" },
828     { "rcmd",   "host" },
829     { "smtp",   "smtp" },
830     { NULL, NULL }
831 };
832
833 #endif
834
835 #ifdef KRB4
836
837 /*
838  * return the converted instance name of `name' in `realm'.
839  * look in the configuration file and then in the default set above.
840  * return NULL if no conversion is appropriate.
841  */
842
843 static const char*
844 get_name_conversion(krb5_context context, const char *realm, const char *name)
845 {
846     struct v4_name_convert *q;
847     const char *p;
848
849     p = krb5_config_get_string(context, NULL, "realms", realm,
850                                "v4_name_convert", "host", name, NULL);
851     if(p == NULL)
852         p = krb5_config_get_string(context, NULL, "libdefaults",
853                                    "v4_name_convert", "host", name, NULL);
854     if(p)
855         return p;
856
857     /* XXX should be possible to override default list */
858     p = krb5_config_get_string(context, NULL,
859                                "realms",
860                                realm,
861                                "v4_name_convert",
862                                "plain",
863                                name,
864                                NULL);
865     if(p)
866         return NULL;
867     p = krb5_config_get_string(context, NULL,
868                                "libdefaults",
869                                "v4_name_convert",
870                                "plain",
871                                name,
872                                NULL);
873     if(p)
874         return NULL;
875     for(q = default_v4_name_convert; q->from; q++)
876         if(strcmp(q->from, name) == 0)
877             return q->to;
878     return NULL;
879 }
880
881 /*
882  * convert the v4 principal `name.instance@realm' to a v5 principal in `princ'.
883  * if `resolve', use DNS.
884  * if `func', use that function for validating the conversion
885  */
886
887 krb5_error_code KRB5_LIB_FUNCTION
888 krb5_425_conv_principal_ext2(krb5_context context,
889                              const char *name,
890                              const char *instance,
891                              const char *realm,
892                              krb5_boolean (*func)(krb5_context,
893                                                   void *, krb5_principal),
894                              void *funcctx,
895                              krb5_boolean resolve,
896                              krb5_principal *princ)
897 {
898     const char *p;
899     krb5_error_code ret;
900     krb5_principal pr;
901     char host[MAXHOSTNAMELEN];
902     char local_hostname[MAXHOSTNAMELEN];
903
904     /* do the following: if the name is found in the
905        `v4_name_convert:host' part, is assumed to be a `host' type
906        principal, and the instance is looked up in the
907        `v4_instance_convert' part. if not found there the name is
908        (optionally) looked up as a hostname, and if that doesn't yield
909        anything, the `default_domain' is appended to the instance
910        */
911
912     if(instance == NULL)
913         goto no_host;
914     if(instance[0] == 0){
915         instance = NULL;
916         goto no_host;
917     }
918     p = get_name_conversion(context, realm, name);
919     if(p == NULL)
920         goto no_host;
921     name = p;
922     p = krb5_config_get_string(context, NULL, "realms", realm,
923                                "v4_instance_convert", instance, NULL);
924     if(p){
925         instance = p;
926         ret = krb5_make_principal(context, &pr, realm, name, instance, NULL);
927         if (ret)
928             return ret;
929         if(func == NULL || (*func)(context, funcctx, pr)){
930             *princ = pr;
931             return 0;
932         }
933         krb5_free_principal(context, pr);
934         *princ = NULL;
935         krb5_clear_error_message (context);
936         return HEIM_ERR_V4_PRINC_NO_CONV;
937     }
938     if(resolve){
939         krb5_boolean passed = FALSE;
940         char *inst = NULL;
941 #ifdef USE_RESOLVER
942         struct rk_dns_reply *r;
943
944         r = rk_dns_lookup(instance, "aaaa");
945         if (r) {
946             if (r->head && r->head->type == rk_ns_t_aaaa) {
947                 inst = strdup(r->head->domain);
948                 passed = TRUE;
949             }
950             rk_dns_free_data(r);
951         } else {
952             r = rk_dns_lookup(instance, "a");
953             if (r) {
954                 if(r->head && r->head->type == rk_ns_t_a) {
955                     inst = strdup(r->head->domain);
956                     passed = TRUE;
957                 }
958                 rk_dns_free_data(r);
959             }
960         }
961 #else
962         struct addrinfo hints, *ai;
963         
964         memset (&hints, 0, sizeof(hints));
965         hints.ai_flags = AI_CANONNAME;
966         ret = getaddrinfo(instance, NULL, &hints, &ai);
967         if (ret == 0) {
968             const struct addrinfo *a;
969             for (a = ai; a != NULL; a = a->ai_next) {
970                 if (a->ai_canonname != NULL) {
971                     inst = strdup (a->ai_canonname);
972                     passed = TRUE;
973                     break;
974                 }
975             }
976             freeaddrinfo (ai);
977         }
978 #endif
979         if (passed) {
980             if (inst == NULL) {
981                 krb5_set_error_message(context, ENOMEM,
982                                        N_("malloc: out of memory", ""));
983                 return ENOMEM;
984             }
985             strlwr(inst);
986             ret = krb5_make_principal(context, &pr, realm, name, inst,
987                                       NULL);
988             free (inst);
989             if(ret == 0) {
990                 if(func == NULL || (*func)(context, funcctx, pr)){
991                     *princ = pr;
992                     return 0;
993                 }
994                 krb5_free_principal(context, pr);
995             }
996         }
997     }
998     if(func != NULL) {
999         snprintf(host, sizeof(host), "%s.%s", instance, realm);
1000         strlwr(host);
1001         ret = krb5_make_principal(context, &pr, realm, name, host, NULL);
1002         if (ret)
1003             return ret;
1004         if((*func)(context, funcctx, pr)){
1005             *princ = pr;
1006             return 0;
1007         }
1008         krb5_free_principal(context, pr);
1009     }
1010
1011     /*
1012      * if the instance is the first component of the local hostname,
1013      * the converted host should be the long hostname.
1014      */
1015
1016     if (func == NULL &&
1017         gethostname (local_hostname, sizeof(local_hostname)) == 0 &&
1018         strncmp(instance, local_hostname, strlen(instance)) == 0 &&
1019         local_hostname[strlen(instance)] == '.') {
1020         strlcpy(host, local_hostname, sizeof(host));
1021         goto local_host;
1022     }
1023
1024     {
1025         char **domains, **d;
1026         domains = krb5_config_get_strings(context, NULL, "realms", realm,
1027                                           "v4_domains", NULL);
1028         for(d = domains; d && *d; d++){
1029             snprintf(host, sizeof(host), "%s.%s", instance, *d);
1030             ret = krb5_make_principal(context, &pr, realm, name, host, NULL);
1031             if (ret) {
1032                 krb5_config_free_strings(domains);
1033                 return ret;
1034             }
1035             if(func == NULL || (*func)(context, funcctx, pr)){
1036                 *princ = pr;
1037                 krb5_config_free_strings(domains);
1038                 return 0;
1039             }
1040             krb5_free_principal(context, pr);
1041         }
1042         krb5_config_free_strings(domains);
1043     }
1044
1045
1046     p = krb5_config_get_string(context, NULL, "realms", realm,
1047                                "default_domain", NULL);
1048     if(p == NULL){
1049         /* this should be an error, just faking a name is not good */
1050         krb5_clear_error_message (context);
1051         return HEIM_ERR_V4_PRINC_NO_CONV;
1052     }
1053         
1054     if (*p == '.')
1055         ++p;
1056     snprintf(host, sizeof(host), "%s.%s", instance, p);
1057 local_host:
1058     ret = krb5_make_principal(context, &pr, realm, name, host, NULL);
1059     if (ret)
1060         return ret;
1061     if(func == NULL || (*func)(context, funcctx, pr)){
1062         *princ = pr;
1063         return 0;
1064     }
1065     krb5_free_principal(context, pr);
1066     krb5_clear_error_message (context);
1067     return HEIM_ERR_V4_PRINC_NO_CONV;
1068 no_host:
1069     p = krb5_config_get_string(context, NULL,
1070                                "realms",
1071                                realm,
1072                                "v4_name_convert",
1073                                "plain",
1074                                name,
1075                                NULL);
1076     if(p == NULL)
1077         p = krb5_config_get_string(context, NULL,
1078                                    "libdefaults",
1079                                    "v4_name_convert",
1080                                    "plain",
1081                                    name,
1082                                    NULL);
1083     if(p)
1084         name = p;
1085
1086     ret = krb5_make_principal(context, &pr, realm, name, instance, NULL);
1087     if (ret)
1088         return ret;
1089     if(func == NULL || (*func)(context, funcctx, pr)){
1090         *princ = pr;
1091         return 0;
1092     }
1093     krb5_free_principal(context, pr);
1094     krb5_clear_error_message (context);
1095     return HEIM_ERR_V4_PRINC_NO_CONV;
1096 }
1097
1098 #endif /* KRB4 */
1099
1100 #ifndef HEIMDAL_SMALLER
1101
1102 static int
1103 check_list(const krb5_config_binding *l, const char *name, const char **out)
1104 {
1105     while(l){
1106         if (l->type != krb5_config_string)
1107             continue;
1108         if(strcmp(name, l->u.string) == 0) {
1109             *out = l->name;
1110             return 1;
1111         }
1112         l = l->next;
1113     }
1114     return 0;
1115 }
1116
1117 static int
1118 name_convert(krb5_context context, const char *name, const char *realm,
1119              const char **out)
1120 {
1121     const krb5_config_binding *l;
1122     l = krb5_config_get_list (context,
1123                               NULL,
1124                               "realms",
1125                               realm,
1126                               "v4_name_convert",
1127                               "host",
1128                               NULL);
1129     if(l && check_list(l, name, out))
1130         return KRB5_NT_SRV_HST;
1131     l = krb5_config_get_list (context,
1132                               NULL,
1133                               "libdefaults",
1134                               "v4_name_convert",
1135                               "host",
1136                               NULL);
1137     if(l && check_list(l, name, out))
1138         return KRB5_NT_SRV_HST;
1139     l = krb5_config_get_list (context,
1140                               NULL,
1141                               "realms",
1142                               realm,
1143                               "v4_name_convert",
1144                               "plain",
1145                               NULL);
1146     if(l && check_list(l, name, out))
1147         return KRB5_NT_UNKNOWN;
1148     l = krb5_config_get_list (context,
1149                               NULL,
1150                               "libdefaults",
1151                               "v4_name_convert",
1152                               "host",
1153                               NULL);
1154     if(l && check_list(l, name, out))
1155         return KRB5_NT_UNKNOWN;
1156
1157     /* didn't find it in config file, try built-in list */
1158 #ifdef KRB4
1159     {
1160         struct v4_name_convert *q;
1161         for(q = default_v4_name_convert; q->from; q++) {
1162             if(strcmp(name, q->to) == 0) {
1163                 *out = q->from;
1164                 return KRB5_NT_SRV_HST;
1165             }
1166         }
1167     }
1168 #endif
1169     return -1;
1170 }
1171
1172 /*
1173  * convert the v5 principal in `principal' into a v4 corresponding one
1174  * in `name, instance, realm'
1175  * this is limited interface since there's no length given for these
1176  * three parameters.  They have to be 40 bytes each (ANAME_SZ).
1177  */
1178
1179 krb5_error_code KRB5_LIB_FUNCTION
1180 krb5_524_conv_principal(krb5_context context,
1181                         const krb5_principal principal,
1182                         char *name,
1183                         char *instance,
1184                         char *realm)
1185 {
1186     const char *n, *i, *r;
1187     char tmpinst[40];
1188     int type = princ_type(principal);
1189     const int aname_sz = 40;
1190
1191     r = principal->realm;
1192
1193     switch(principal->name.name_string.len){
1194     case 1:
1195         n = principal->name.name_string.val[0];
1196         i = "";
1197         break;
1198     case 2:
1199         n = principal->name.name_string.val[0];
1200         i = principal->name.name_string.val[1];
1201         break;
1202     default:
1203         krb5_set_error_message(context, KRB5_PARSE_MALFORMED,
1204                                N_("cannot convert a %d "
1205                                   "component principal", ""),
1206                                principal->name.name_string.len);
1207         return KRB5_PARSE_MALFORMED;
1208     }
1209
1210     {
1211         const char *tmp;
1212         int t = name_convert(context, n, r, &tmp);
1213         if(t >= 0) {
1214             type = t;
1215             n = tmp;
1216         }
1217     }
1218
1219     if(type == KRB5_NT_SRV_HST){
1220         char *p;
1221
1222         strlcpy (tmpinst, i, sizeof(tmpinst));
1223         p = strchr(tmpinst, '.');
1224         if(p)
1225             *p = 0;
1226         i = tmpinst;
1227     }
1228
1229     if (strlcpy (name, n, aname_sz) >= aname_sz) {
1230         krb5_set_error_message(context, KRB5_PARSE_MALFORMED,
1231                                N_("too long name component to convert", ""));
1232         return KRB5_PARSE_MALFORMED;
1233     }
1234     if (strlcpy (instance, i, aname_sz) >= aname_sz) {
1235         krb5_set_error_message(context, KRB5_PARSE_MALFORMED,
1236                                N_("too long instance component to convert", ""));
1237         return KRB5_PARSE_MALFORMED;
1238     }
1239     if (strlcpy (realm, r, aname_sz) >= aname_sz) {
1240         krb5_set_error_message(context, KRB5_PARSE_MALFORMED,
1241                                N_("too long realm component to convert", ""));
1242         return KRB5_PARSE_MALFORMED;
1243     }
1244     return 0;
1245 }
1246
1247 #endif /* !HEIMDAL_SMALLER */
1248
1249 /**
1250  * Create a principal for the service running on hostname. If
1251  * KRB5_NT_SRV_HST is used, the hostname is canonization using DNS (or
1252  * some other service), this is potentially insecure.
1253  *
1254  * @param context A Kerberos context.
1255  * @param hostname hostname to use
1256  * @param sname Service name to use
1257  * @param type name type of pricipal, use KRB5_NT_SRV_HST or KRB5_NT_UNKNOWN.
1258  * @param ret_princ return principal, free with krb5_free_principal().
1259  *
1260  * @return An krb5 error code, see krb5_get_error_message().
1261  *
1262  * @ingroup krb5_principal
1263  */
1264                         
1265 krb5_error_code KRB5_LIB_FUNCTION
1266 krb5_sname_to_principal (krb5_context context,
1267                          const char *hostname,
1268                          const char *sname,
1269                          int32_t type,
1270                          krb5_principal *ret_princ)
1271 {
1272     krb5_error_code ret;
1273     char localhost[MAXHOSTNAMELEN];
1274     char **realms, *host = NULL;
1275         
1276     if(type != KRB5_NT_SRV_HST && type != KRB5_NT_UNKNOWN) {
1277         krb5_set_error_message(context, KRB5_SNAME_UNSUPP_NAMETYPE,
1278                                N_("unsupported name type %d", ""),
1279                                (int)type);
1280         return KRB5_SNAME_UNSUPP_NAMETYPE;
1281     }
1282     if(hostname == NULL) {
1283         ret = gethostname(localhost, sizeof(localhost) - 1);
1284         if (ret != 0) {
1285             ret = errno;
1286             krb5_set_error_message(context, ret,
1287                                    N_("Failed to get local hostname", ""));
1288             return ret;
1289         }       
1290         localhost[sizeof(localhost) - 1] = '\0';
1291         hostname = localhost;
1292     }
1293     if(sname == NULL)
1294         sname = "host";
1295     if(type == KRB5_NT_SRV_HST) {
1296         ret = krb5_expand_hostname_realms (context, hostname,
1297                                            &host, &realms);
1298         if (ret)
1299             return ret;
1300         strlwr(host);
1301         hostname = host;
1302     } else {
1303         ret = krb5_get_host_realm(context, hostname, &realms);
1304         if(ret)
1305             return ret;
1306     }
1307
1308     ret = krb5_make_principal(context, ret_princ, realms[0], sname,
1309                               hostname, NULL);
1310     if(host)
1311         free(host);
1312     krb5_free_host_realm(context, realms);
1313     return ret;
1314 }
1315
1316 static const struct {
1317     const char *type;
1318     int32_t value;
1319 } nametypes[] = {
1320     { "UNKNOWN", KRB5_NT_UNKNOWN },
1321     { "PRINCIPAL", KRB5_NT_PRINCIPAL },
1322     { "SRV_INST", KRB5_NT_SRV_INST },
1323     { "SRV_HST", KRB5_NT_SRV_HST },
1324     { "SRV_XHST", KRB5_NT_SRV_XHST },
1325     { "UID", KRB5_NT_UID },
1326     { "X500_PRINCIPAL", KRB5_NT_X500_PRINCIPAL },
1327     { "SMTP_NAME", KRB5_NT_SMTP_NAME },
1328     { "ENTERPRISE_PRINCIPAL", KRB5_NT_ENTERPRISE_PRINCIPAL },
1329     { "ENT_PRINCIPAL_AND_ID", KRB5_NT_ENT_PRINCIPAL_AND_ID },
1330     { "MS_PRINCIPAL", KRB5_NT_MS_PRINCIPAL },
1331     { "MS_PRINCIPAL_AND_ID", KRB5_NT_MS_PRINCIPAL_AND_ID },
1332     { NULL }
1333 };
1334
1335 krb5_error_code
1336 krb5_parse_nametype(krb5_context context, const char *str, int32_t *nametype)
1337 {
1338     size_t i;
1339
1340     for(i = 0; nametypes[i].type; i++) {
1341         if (strcasecmp(nametypes[i].type, str) == 0) {
1342             *nametype = nametypes[i].value;
1343             return 0;
1344         }
1345     }
1346     krb5_set_error_message(context, KRB5_PARSE_MALFORMED,
1347                            N_("Failed to find name type %s", ""), str);
1348     return KRB5_PARSE_MALFORMED;
1349 }