lib/krb5: fix the build without KRB4
[metze/heimdal/wip.git] / 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 /**
500  * Unparse the Kerberos name into a string
501  *
502  * @param context Kerberos 5 context
503  * @param principal principal to query
504  * @param name resulting string, free with krb5_xfree()
505  *
506  * @return An krb5 error code, see krb5_get_error_message().
507  *
508  * @ingroup krb5_principal
509  */
510
511 krb5_error_code KRB5_LIB_FUNCTION
512 krb5_unparse_name(krb5_context context,
513                   krb5_const_principal principal,
514                   char **name)
515 {
516     return unparse_name(context, principal, name, 0);
517 }
518
519 /**
520  * Unparse the Kerberos name into a string
521  *
522  * @param context Kerberos 5 context
523  * @param principal principal to query
524  * @param flags flag to determine the behavior
525  * @param name resulting string, free with krb5_xfree()
526  *
527  * @return An krb5 error code, see krb5_get_error_message().
528  *
529  * @ingroup krb5_principal
530  */
531
532 krb5_error_code KRB5_LIB_FUNCTION
533 krb5_unparse_name_flags(krb5_context context,
534                         krb5_const_principal principal,
535                         int flags,
536                         char **name)
537 {
538     return unparse_name(context, principal, name, flags);
539 }
540
541 krb5_error_code KRB5_LIB_FUNCTION
542 krb5_unparse_name_short(krb5_context context,
543                         krb5_const_principal principal,
544                         char **name)
545 {
546     return unparse_name(context, principal, name, KRB5_PRINCIPAL_UNPARSE_SHORT);
547 }
548
549 #if 0 /* not implemented */
550
551 krb5_error_code KRB5_LIB_FUNCTION
552 krb5_unparse_name_ext(krb5_context context,
553                       krb5_const_principal principal,
554                       char **name,
555                       size_t *size)
556 {
557     krb5_abortx(context, "unimplemented krb5_unparse_name_ext called");
558 }
559
560 #endif
561
562 krb5_error_code KRB5_LIB_FUNCTION
563 krb5_principal_set_realm(krb5_context context,
564                          krb5_principal principal,
565                          krb5_const_realm realm)
566 {
567     if (princ_realm(principal))
568         free(princ_realm(principal));
569
570     princ_realm(principal) = strdup(realm);
571     if (princ_realm(principal) == NULL) {
572         krb5_set_error_message(context, ENOMEM,
573                                N_("malloc: out of memory", ""));
574         return ENOMEM;
575     }
576     return 0;
577 }
578
579
580 krb5_error_code KRB5_LIB_FUNCTION
581 krb5_build_principal(krb5_context context,
582                      krb5_principal *principal,
583                      int rlen,
584                      krb5_const_realm realm,
585                      ...)
586 {
587     krb5_error_code ret;
588     va_list ap;
589     va_start(ap, realm);
590     ret = krb5_build_principal_va(context, principal, rlen, realm, ap);
591     va_end(ap);
592     return ret;
593 }
594
595 static krb5_error_code
596 append_component(krb5_context context, krb5_principal p,
597                  const char *comp,
598                  size_t comp_len)
599 {
600     heim_general_string *tmp;
601     size_t len = princ_num_comp(p);
602
603     tmp = realloc(princ_comp(p), (len + 1) * sizeof(*tmp));
604     if(tmp == NULL) {
605         krb5_set_error_message(context, ENOMEM,
606                                N_("malloc: out of memory", ""));
607         return ENOMEM;
608     }
609     princ_comp(p) = tmp;
610     princ_ncomp(p, len) = malloc(comp_len + 1);
611     if (princ_ncomp(p, len) == NULL) {
612         krb5_set_error_message(context, ENOMEM,
613                                N_("malloc: out of memory", ""));
614         return ENOMEM;
615     }
616     memcpy (princ_ncomp(p, len), comp, comp_len);
617     princ_ncomp(p, len)[comp_len] = '\0';
618     princ_num_comp(p)++;
619     return 0;
620 }
621
622 static void
623 va_ext_princ(krb5_context context, krb5_principal p, va_list ap)
624 {
625     while(1){
626         const char *s;
627         int len;
628         len = va_arg(ap, int);
629         if(len == 0)
630             break;
631         s = va_arg(ap, const char*);
632         append_component(context, p, s, len);
633     }
634 }
635
636 static void
637 va_princ(krb5_context context, krb5_principal p, va_list ap)
638 {
639     while(1){
640         const char *s;
641         s = va_arg(ap, const char*);
642         if(s == NULL)
643             break;
644         append_component(context, p, s, strlen(s));
645     }
646 }
647
648 static krb5_error_code
649 build_principal(krb5_context context,
650                 krb5_principal *principal,
651                 int rlen,
652                 krb5_const_realm realm,
653                 void (*func)(krb5_context, krb5_principal, va_list),
654                 va_list ap)
655 {
656     krb5_principal p;
657
658     p = calloc(1, sizeof(*p));
659     if (p == NULL) {
660         krb5_set_error_message(context, ENOMEM,
661                                N_("malloc: out of memory", ""));
662         return ENOMEM;
663     }
664     princ_type(p) = KRB5_NT_PRINCIPAL;
665
666     princ_realm(p) = strdup(realm);
667     if(p->realm == NULL){
668         free(p);
669         krb5_set_error_message(context, ENOMEM,
670                                N_("malloc: out of memory", ""));
671         return ENOMEM;
672     }
673
674     (*func)(context, p, ap);
675     *principal = p;
676     return 0;
677 }
678
679 krb5_error_code KRB5_LIB_FUNCTION
680 krb5_make_principal(krb5_context context,
681                     krb5_principal *principal,
682                     krb5_const_realm realm,
683                     ...)
684 {
685     krb5_error_code ret;
686     krb5_realm r = NULL;
687     va_list ap;
688     if(realm == NULL) {
689         ret = krb5_get_default_realm(context, &r);
690         if(ret)
691             return ret;
692         realm = r;
693     }
694     va_start(ap, realm);
695     ret = krb5_build_principal_va(context, principal, strlen(realm), realm, ap);
696     va_end(ap);
697     if(r)
698         free(r);
699     return ret;
700 }
701
702 krb5_error_code KRB5_LIB_FUNCTION
703 krb5_build_principal_va(krb5_context context,
704                         krb5_principal *principal,
705                         int rlen,
706                         krb5_const_realm realm,
707                         va_list ap)
708 {
709     return build_principal(context, principal, rlen, realm, va_princ, ap);
710 }
711
712 krb5_error_code KRB5_LIB_FUNCTION
713 krb5_build_principal_va_ext(krb5_context context,
714                             krb5_principal *principal,
715                             int rlen,
716                             krb5_const_realm realm,
717                             va_list ap)
718 {
719     return build_principal(context, principal, rlen, realm, va_ext_princ, ap);
720 }
721
722
723 krb5_error_code KRB5_LIB_FUNCTION
724 krb5_build_principal_ext(krb5_context context,
725                          krb5_principal *principal,
726                          int rlen,
727                          krb5_const_realm realm,
728                          ...)
729 {
730     krb5_error_code ret;
731     va_list ap;
732     va_start(ap, realm);
733     ret = krb5_build_principal_va_ext(context, principal, rlen, realm, ap);
734     va_end(ap);
735     return ret;
736 }
737
738
739 krb5_error_code KRB5_LIB_FUNCTION
740 krb5_copy_principal(krb5_context context,
741                     krb5_const_principal inprinc,
742                     krb5_principal *outprinc)
743 {
744     krb5_principal p = malloc(sizeof(*p));
745     if (p == NULL) {
746         krb5_set_error_message(context, ENOMEM,
747                                N_("malloc: out of memory", ""));
748         return ENOMEM;
749     }
750     if(copy_Principal(inprinc, p)) {
751         free(p);
752         krb5_set_error_message(context, ENOMEM,
753                                N_("malloc: out of memory", ""));
754         return ENOMEM;
755     }
756     *outprinc = p;
757     return 0;
758 }
759
760 /**
761  * Return TRUE iff princ1 == princ2 (without considering the realm)
762  *
763  * @param context Kerberos 5 context
764  * @param princ1 first principal to compare
765  * @param princ2 second principal to compare
766  *
767  * @return non zero if equal, 0 if not
768  *
769  * @ingroup krb5_principal
770  */
771
772 krb5_boolean KRB5_LIB_FUNCTION
773 krb5_principal_compare_any_realm(krb5_context context,
774                                  krb5_const_principal princ1,
775                                  krb5_const_principal princ2)
776 {
777     int i;
778     if(princ_num_comp(princ1) != princ_num_comp(princ2))
779         return FALSE;
780     for(i = 0; i < princ_num_comp(princ1); i++){
781         if(strcmp(princ_ncomp(princ1, i), princ_ncomp(princ2, i)) != 0)
782             return FALSE;
783     }
784     return TRUE;
785 }
786
787 krb5_boolean KRB5_LIB_FUNCTION
788 _krb5_principal_compare_PrincipalName(krb5_context context,
789                                       krb5_const_principal princ1,
790                                       PrincipalName *princ2)
791 {
792     int i;
793     if (princ_num_comp(princ1) != princ2->name_string.len)
794         return FALSE;
795     for(i = 0; i < princ_num_comp(princ1); i++){
796         if(strcmp(princ_ncomp(princ1, i), princ2->name_string.val[i]) != 0)
797             return FALSE;
798     }
799     return TRUE;
800 }
801
802
803 /*
804  * return TRUE iff princ1 == princ2
805  */
806
807 krb5_boolean KRB5_LIB_FUNCTION
808 krb5_principal_compare(krb5_context context,
809                        krb5_const_principal princ1,
810                        krb5_const_principal princ2)
811 {
812     if(!krb5_realm_compare(context, princ1, princ2))
813         return FALSE;
814     return krb5_principal_compare_any_realm(context, princ1, princ2);
815 }
816
817 /*
818  * return TRUE iff realm(princ1) == realm(princ2)
819  */
820
821 krb5_boolean KRB5_LIB_FUNCTION
822 krb5_realm_compare(krb5_context context,
823                    krb5_const_principal princ1,
824                    krb5_const_principal princ2)
825 {
826     return strcmp(princ_realm(princ1), princ_realm(princ2)) == 0;
827 }
828
829 /*
830  * return TRUE iff princ matches pattern
831  */
832
833 krb5_boolean KRB5_LIB_FUNCTION
834 krb5_principal_match(krb5_context context,
835                      krb5_const_principal princ,
836                      krb5_const_principal pattern)
837 {
838     int i;
839     if(princ_num_comp(princ) != princ_num_comp(pattern))
840         return FALSE;
841     if(fnmatch(princ_realm(pattern), princ_realm(princ), 0) != 0)
842         return FALSE;
843     for(i = 0; i < princ_num_comp(princ); i++){
844         if(fnmatch(princ_ncomp(pattern, i), princ_ncomp(princ, i), 0) != 0)
845             return FALSE;
846     }
847     return TRUE;
848 }
849
850 #if defined(KRB4) || !defined(HEIMDAL_SMALLER)
851
852 static struct v4_name_convert {
853     const char *from;
854     const char *to;
855 } default_v4_name_convert[] = {
856     { "ftp",    "ftp" },
857     { "hprop",  "hprop" },
858     { "pop",    "pop" },
859     { "imap",   "imap" },
860     { "rcmd",   "host" },
861     { "smtp",   "smtp" },
862     { NULL, NULL }
863 };
864
865 #endif
866
867 #ifdef KRB4
868
869 /*
870  * return the converted instance name of `name' in `realm'.
871  * look in the configuration file and then in the default set above.
872  * return NULL if no conversion is appropriate.
873  */
874
875 static const char*
876 get_name_conversion(krb5_context context, const char *realm, const char *name)
877 {
878     struct v4_name_convert *q;
879     const char *p;
880
881     p = krb5_config_get_string(context, NULL, "realms", realm,
882                                "v4_name_convert", "host", name, NULL);
883     if(p == NULL)
884         p = krb5_config_get_string(context, NULL, "libdefaults",
885                                    "v4_name_convert", "host", name, NULL);
886     if(p)
887         return p;
888
889     /* XXX should be possible to override default list */
890     p = krb5_config_get_string(context, NULL,
891                                "realms",
892                                realm,
893                                "v4_name_convert",
894                                "plain",
895                                name,
896                                NULL);
897     if(p)
898         return NULL;
899     p = krb5_config_get_string(context, NULL,
900                                "libdefaults",
901                                "v4_name_convert",
902                                "plain",
903                                name,
904                                NULL);
905     if(p)
906         return NULL;
907     for(q = default_v4_name_convert; q->from; q++)
908         if(strcmp(q->from, name) == 0)
909             return q->to;
910     return NULL;
911 }
912
913 /*
914  * convert the v4 principal `name.instance@realm' to a v5 principal in `princ'.
915  * if `resolve', use DNS.
916  * if `func', use that function for validating the conversion
917  */
918
919 krb5_error_code KRB5_LIB_FUNCTION
920 krb5_425_conv_principal_ext2(krb5_context context,
921                              const char *name,
922                              const char *instance,
923                              const char *realm,
924                              krb5_boolean (*func)(krb5_context,
925                                                   void *, krb5_principal),
926                              void *funcctx,
927                              krb5_boolean resolve,
928                              krb5_principal *princ)
929 {
930     const char *p;
931     krb5_error_code ret;
932     krb5_principal pr;
933     char host[MAXHOSTNAMELEN];
934     char local_hostname[MAXHOSTNAMELEN];
935
936     /* do the following: if the name is found in the
937        `v4_name_convert:host' part, is assumed to be a `host' type
938        principal, and the instance is looked up in the
939        `v4_instance_convert' part. if not found there the name is
940        (optionally) looked up as a hostname, and if that doesn't yield
941        anything, the `default_domain' is appended to the instance
942        */
943
944     if(instance == NULL)
945         goto no_host;
946     if(instance[0] == 0){
947         instance = NULL;
948         goto no_host;
949     }
950     p = get_name_conversion(context, realm, name);
951     if(p == NULL)
952         goto no_host;
953     name = p;
954     p = krb5_config_get_string(context, NULL, "realms", realm,
955                                "v4_instance_convert", instance, NULL);
956     if(p){
957         instance = p;
958         ret = krb5_make_principal(context, &pr, realm, name, instance, NULL);
959         if (ret)
960             return ret;
961         if(func == NULL || (*func)(context, funcctx, pr)){
962             *princ = pr;
963             return 0;
964         }
965         krb5_free_principal(context, pr);
966         *princ = NULL;
967         krb5_clear_error_message (context);
968         return HEIM_ERR_V4_PRINC_NO_CONV;
969     }
970     if(resolve){
971         krb5_boolean passed = FALSE;
972         char *inst = NULL;
973 #ifdef USE_RESOLVER
974         struct rk_dns_reply *r;
975
976         r = rk_dns_lookup(instance, "aaaa");
977         if (r) {
978             if (r->head && r->head->type == rk_ns_t_aaaa) {
979                 inst = strdup(r->head->domain);
980                 passed = TRUE;
981             }
982             rk_dns_free_data(r);
983         } else {
984             r = rk_dns_lookup(instance, "a");
985             if (r) {
986                 if(r->head && r->head->type == rk_ns_t_a) {
987                     inst = strdup(r->head->domain);
988                     passed = TRUE;
989                 }
990                 rk_dns_free_data(r);
991             }
992         }
993 #else
994         struct addrinfo hints, *ai;
995         
996         memset (&hints, 0, sizeof(hints));
997         hints.ai_flags = AI_CANONNAME;
998         ret = getaddrinfo(instance, NULL, &hints, &ai);
999         if (ret == 0) {
1000             const struct addrinfo *a;
1001             for (a = ai; a != NULL; a = a->ai_next) {
1002                 if (a->ai_canonname != NULL) {
1003                     inst = strdup (a->ai_canonname);
1004                     passed = TRUE;
1005                     break;
1006                 }
1007             }
1008             freeaddrinfo (ai);
1009         }
1010 #endif
1011         if (passed) {
1012             if (inst == NULL) {
1013                 krb5_set_error_message(context, ENOMEM,
1014                                        N_("malloc: out of memory", ""));
1015                 return ENOMEM;
1016             }
1017             strlwr(inst);
1018             ret = krb5_make_principal(context, &pr, realm, name, inst,
1019                                       NULL);
1020             free (inst);
1021             if(ret == 0) {
1022                 if(func == NULL || (*func)(context, funcctx, pr)){
1023                     *princ = pr;
1024                     return 0;
1025                 }
1026                 krb5_free_principal(context, pr);
1027             }
1028         }
1029     }
1030     if(func != NULL) {
1031         snprintf(host, sizeof(host), "%s.%s", instance, realm);
1032         strlwr(host);
1033         ret = krb5_make_principal(context, &pr, realm, name, host, NULL);
1034         if (ret)
1035             return ret;
1036         if((*func)(context, funcctx, pr)){
1037             *princ = pr;
1038             return 0;
1039         }
1040         krb5_free_principal(context, pr);
1041     }
1042
1043     /*
1044      * if the instance is the first component of the local hostname,
1045      * the converted host should be the long hostname.
1046      */
1047
1048     if (func == NULL &&
1049         gethostname (local_hostname, sizeof(local_hostname)) == 0 &&
1050         strncmp(instance, local_hostname, strlen(instance)) == 0 &&
1051         local_hostname[strlen(instance)] == '.') {
1052         strlcpy(host, local_hostname, sizeof(host));
1053         goto local_host;
1054     }
1055
1056     {
1057         char **domains, **d;
1058         domains = krb5_config_get_strings(context, NULL, "realms", realm,
1059                                           "v4_domains", NULL);
1060         for(d = domains; d && *d; d++){
1061             snprintf(host, sizeof(host), "%s.%s", instance, *d);
1062             ret = krb5_make_principal(context, &pr, realm, name, host, NULL);
1063             if (ret) {
1064                 krb5_config_free_strings(domains);
1065                 return ret;
1066             }
1067             if(func == NULL || (*func)(context, funcctx, pr)){
1068                 *princ = pr;
1069                 krb5_config_free_strings(domains);
1070                 return 0;
1071             }
1072             krb5_free_principal(context, pr);
1073         }
1074         krb5_config_free_strings(domains);
1075     }
1076
1077
1078     p = krb5_config_get_string(context, NULL, "realms", realm,
1079                                "default_domain", NULL);
1080     if(p == NULL){
1081         /* this should be an error, just faking a name is not good */
1082         krb5_clear_error_message (context);
1083         return HEIM_ERR_V4_PRINC_NO_CONV;
1084     }
1085         
1086     if (*p == '.')
1087         ++p;
1088     snprintf(host, sizeof(host), "%s.%s", instance, p);
1089 local_host:
1090     ret = krb5_make_principal(context, &pr, realm, name, host, NULL);
1091     if (ret)
1092         return ret;
1093     if(func == NULL || (*func)(context, funcctx, pr)){
1094         *princ = pr;
1095         return 0;
1096     }
1097     krb5_free_principal(context, pr);
1098     krb5_clear_error_message (context);
1099     return HEIM_ERR_V4_PRINC_NO_CONV;
1100 no_host:
1101     p = krb5_config_get_string(context, NULL,
1102                                "realms",
1103                                realm,
1104                                "v4_name_convert",
1105                                "plain",
1106                                name,
1107                                NULL);
1108     if(p == NULL)
1109         p = krb5_config_get_string(context, NULL,
1110                                    "libdefaults",
1111                                    "v4_name_convert",
1112                                    "plain",
1113                                    name,
1114                                    NULL);
1115     if(p)
1116         name = p;
1117
1118     ret = krb5_make_principal(context, &pr, realm, name, instance, NULL);
1119     if (ret)
1120         return ret;
1121     if(func == NULL || (*func)(context, funcctx, pr)){
1122         *princ = pr;
1123         return 0;
1124     }
1125     krb5_free_principal(context, pr);
1126     krb5_clear_error_message (context);
1127     return HEIM_ERR_V4_PRINC_NO_CONV;
1128 }
1129
1130 #endif /* KRB4 */
1131
1132 #ifndef HEIMDAL_SMALLER
1133
1134 static int
1135 check_list(const krb5_config_binding *l, const char *name, const char **out)
1136 {
1137     while(l){
1138         if (l->type != krb5_config_string)
1139             continue;
1140         if(strcmp(name, l->u.string) == 0) {
1141             *out = l->name;
1142             return 1;
1143         }
1144         l = l->next;
1145     }
1146     return 0;
1147 }
1148
1149 static int
1150 name_convert(krb5_context context, const char *name, const char *realm,
1151              const char **out)
1152 {
1153     const krb5_config_binding *l;
1154     l = krb5_config_get_list (context,
1155                               NULL,
1156                               "realms",
1157                               realm,
1158                               "v4_name_convert",
1159                               "host",
1160                               NULL);
1161     if(l && check_list(l, name, out))
1162         return KRB5_NT_SRV_HST;
1163     l = krb5_config_get_list (context,
1164                               NULL,
1165                               "libdefaults",
1166                               "v4_name_convert",
1167                               "host",
1168                               NULL);
1169     if(l && check_list(l, name, out))
1170         return KRB5_NT_SRV_HST;
1171     l = krb5_config_get_list (context,
1172                               NULL,
1173                               "realms",
1174                               realm,
1175                               "v4_name_convert",
1176                               "plain",
1177                               NULL);
1178     if(l && check_list(l, name, out))
1179         return KRB5_NT_UNKNOWN;
1180     l = krb5_config_get_list (context,
1181                               NULL,
1182                               "libdefaults",
1183                               "v4_name_convert",
1184                               "host",
1185                               NULL);
1186     if(l && check_list(l, name, out))
1187         return KRB5_NT_UNKNOWN;
1188
1189     /* didn't find it in config file, try built-in list */
1190 #ifdef KRB4
1191     {
1192         struct v4_name_convert *q;
1193         for(q = default_v4_name_convert; q->from; q++) {
1194             if(strcmp(name, q->to) == 0) {
1195                 *out = q->from;
1196                 return KRB5_NT_SRV_HST;
1197             }
1198         }
1199     }
1200 #endif
1201     return -1;
1202 }
1203
1204 /*
1205  * convert the v5 principal in `principal' into a v4 corresponding one
1206  * in `name, instance, realm'
1207  * this is limited interface since there's no length given for these
1208  * three parameters.  They have to be 40 bytes each (ANAME_SZ).
1209  */
1210
1211 krb5_error_code KRB5_LIB_FUNCTION
1212 krb5_524_conv_principal(krb5_context context,
1213                         const krb5_principal principal,
1214                         char *name,
1215                         char *instance,
1216                         char *realm)
1217 {
1218     const char *n, *i, *r;
1219     char tmpinst[40];
1220     int type = princ_type(principal);
1221     const int aname_sz = 40;
1222
1223     r = principal->realm;
1224
1225     switch(principal->name.name_string.len){
1226     case 1:
1227         n = principal->name.name_string.val[0];
1228         i = "";
1229         break;
1230     case 2:
1231         n = principal->name.name_string.val[0];
1232         i = principal->name.name_string.val[1];
1233         break;
1234     default:
1235         krb5_set_error_message(context, KRB5_PARSE_MALFORMED,
1236                                N_("cannot convert a %d "
1237                                   "component principal", ""),
1238                                principal->name.name_string.len);
1239         return KRB5_PARSE_MALFORMED;
1240     }
1241
1242     {
1243         const char *tmp;
1244         int t = name_convert(context, n, r, &tmp);
1245         if(t >= 0) {
1246             type = t;
1247             n = tmp;
1248         }
1249     }
1250
1251     if(type == KRB5_NT_SRV_HST){
1252         char *p;
1253
1254         strlcpy (tmpinst, i, sizeof(tmpinst));
1255         p = strchr(tmpinst, '.');
1256         if(p)
1257             *p = 0;
1258         i = tmpinst;
1259     }
1260
1261     if (strlcpy (name, n, aname_sz) >= aname_sz) {
1262         krb5_set_error_message(context, KRB5_PARSE_MALFORMED,
1263                                N_("too long name component to convert", ""));
1264         return KRB5_PARSE_MALFORMED;
1265     }
1266     if (strlcpy (instance, i, aname_sz) >= aname_sz) {
1267         krb5_set_error_message(context, KRB5_PARSE_MALFORMED,
1268                                N_("too long instance component to convert", ""));
1269         return KRB5_PARSE_MALFORMED;
1270     }
1271     if (strlcpy (realm, r, aname_sz) >= aname_sz) {
1272         krb5_set_error_message(context, KRB5_PARSE_MALFORMED,
1273                                N_("too long realm component to convert", ""));
1274         return KRB5_PARSE_MALFORMED;
1275     }
1276     return 0;
1277 }
1278
1279 #endif /* !HEIMDAL_SMALLER */
1280
1281 /**
1282  * Create a principal for the service running on hostname. If
1283  * KRB5_NT_SRV_HST is used, the hostname is canonization using DNS (or
1284  * some other service), this is potentially insecure.
1285  *
1286  * @param context A Kerberos context.
1287  * @param hostname hostname to use
1288  * @param sname Service name to use
1289  * @param type name type of pricipal, use KRB5_NT_SRV_HST or KRB5_NT_UNKNOWN.
1290  * @param ret_princ return principal, free with krb5_free_principal().
1291  *
1292  * @return An krb5 error code, see krb5_get_error_message().
1293  *
1294  * @ingroup krb5_principal
1295  */
1296                         
1297 krb5_error_code KRB5_LIB_FUNCTION
1298 krb5_sname_to_principal (krb5_context context,
1299                          const char *hostname,
1300                          const char *sname,
1301                          int32_t type,
1302                          krb5_principal *ret_princ)
1303 {
1304     krb5_error_code ret;
1305     char localhost[MAXHOSTNAMELEN];
1306     char **realms, *host = NULL;
1307         
1308     if(type != KRB5_NT_SRV_HST && type != KRB5_NT_UNKNOWN) {
1309         krb5_set_error_message(context, KRB5_SNAME_UNSUPP_NAMETYPE,
1310                                N_("unsupported name type %d", ""),
1311                                (int)type);
1312         return KRB5_SNAME_UNSUPP_NAMETYPE;
1313     }
1314     if(hostname == NULL) {
1315         ret = gethostname(localhost, sizeof(localhost) - 1);
1316         if (ret != 0) {
1317             ret = errno;
1318             krb5_set_error_message(context, ret,
1319                                    N_("Failed to get local hostname", ""));
1320             return ret;
1321         }       
1322         localhost[sizeof(localhost) - 1] = '\0';
1323         hostname = localhost;
1324     }
1325     if(sname == NULL)
1326         sname = "host";
1327     if(type == KRB5_NT_SRV_HST) {
1328         ret = krb5_expand_hostname_realms (context, hostname,
1329                                            &host, &realms);
1330         if (ret)
1331             return ret;
1332         strlwr(host);
1333         hostname = host;
1334     } else {
1335         ret = krb5_get_host_realm(context, hostname, &realms);
1336         if(ret)
1337             return ret;
1338     }
1339
1340     ret = krb5_make_principal(context, ret_princ, realms[0], sname,
1341                               hostname, NULL);
1342     if(host)
1343         free(host);
1344     krb5_free_host_realm(context, realms);
1345     return ret;
1346 }
1347
1348 static const struct {
1349     const char *type;
1350     int32_t value;
1351 } nametypes[] = {
1352     { "UNKNOWN", KRB5_NT_UNKNOWN },
1353     { "PRINCIPAL", KRB5_NT_PRINCIPAL },
1354     { "SRV_INST", KRB5_NT_SRV_INST },
1355     { "SRV_HST", KRB5_NT_SRV_HST },
1356     { "SRV_XHST", KRB5_NT_SRV_XHST },
1357     { "UID", KRB5_NT_UID },
1358     { "X500_PRINCIPAL", KRB5_NT_X500_PRINCIPAL },
1359     { "SMTP_NAME", KRB5_NT_SMTP_NAME },
1360     { "ENTERPRISE_PRINCIPAL", KRB5_NT_ENTERPRISE_PRINCIPAL },
1361     { "ENT_PRINCIPAL_AND_ID", KRB5_NT_ENT_PRINCIPAL_AND_ID },
1362     { "MS_PRINCIPAL", KRB5_NT_MS_PRINCIPAL },
1363     { "MS_PRINCIPAL_AND_ID", KRB5_NT_MS_PRINCIPAL_AND_ID },
1364     { NULL }
1365 };
1366
1367 krb5_error_code
1368 krb5_parse_nametype(krb5_context context, const char *str, int32_t *nametype)
1369 {
1370     size_t i;
1371
1372     for(i = 0; nametypes[i].type; i++) {
1373         if (strcasecmp(nametypes[i].type, str) == 0) {
1374             *nametype = nametypes[i].value;
1375             return 0;
1376         }
1377     }
1378     krb5_set_error_message(context, KRB5_PARSE_MALFORMED,
1379                            N_("Failed to find name type %s", ""), str);
1380     return KRB5_PARSE_MALFORMED;
1381 }