]> git.sur5r.net Git - openldap/blob - libraries/libldap/getdn.c
VLV clean
[openldap] / libraries / libldap / getdn.c
1 /* $OpenLDAP$ */
2 /*
3  * Copyright 1998-2002 The OpenLDAP Foundation, All Rights Reserved.
4  * COPYING RESTRICTIONS APPLY, see COPYRIGHT file
5  */
6 /*  Portions
7  *  Copyright (c) 1994 Regents of the University of Michigan.
8  *  All rights reserved.
9  *
10  *  getdn.c
11  */
12
13 #include "portable.h"
14
15 #include <stdio.h>
16
17 #include <ac/stdlib.h>
18 #include <ac/socket.h>
19 #include <ac/string.h>
20 #include <ac/time.h>
21
22 #include "ldap-int.h"
23 #include "ldap_schema.h"
24
25 /* extension to UFN that turns trailing "dc=value" rdns in DNS style,
26  * e.g. "ou=People,dc=openldap,dc=org" => "People, openldap.org" */
27 #define DC_IN_UFN
28 #define PRETTY_ESCAPE
29
30 /* parsing/printing routines */
31 static int str2strval( const char *str, ber_len_t stoplen, struct berval *val, 
32                 const char **next, unsigned flags, unsigned *retFlags );
33 static int DCE2strval( const char *str, struct berval *val, 
34                 const char **next, unsigned flags );
35 static int IA52strval( const char *str, struct berval *val, 
36                 const char **next, unsigned flags );
37 static int quotedIA52strval( const char *str, struct berval *val, 
38                 const char **next, unsigned flags );
39 static int hexstr2binval( const char *str, struct berval *val, 
40                 const char **next, unsigned flags );
41 static int hexstr2bin( const char *str, char *c );
42 static int byte2hexpair( const char *val, char *pair );
43 static int binval2hexstr( struct berval *val, char *str );
44 static int strval2strlen( struct berval *val, unsigned flags, 
45                 ber_len_t *len );
46 static int strval2str( struct berval *val, char *str, unsigned flags, 
47                 ber_len_t *len );
48 static int strval2IA5strlen( struct berval *val, unsigned flags,
49                 ber_len_t *len );
50 static int strval2IA5str( struct berval *val, char *str, unsigned flags, 
51                 ber_len_t *len );
52 static int strval2DCEstrlen( struct berval *val, unsigned flags,
53                 ber_len_t *len );
54 static int strval2DCEstr( struct berval *val, char *str, unsigned flags, 
55                 ber_len_t *len );
56 static int strval2ADstrlen( struct berval *val, unsigned flags,
57                 ber_len_t *len );
58 static int strval2ADstr( struct berval *val, char *str, unsigned flags, 
59                 ber_len_t *len );
60 static int dn2domain( LDAPDN *dn, struct berval *bv, int pos, int *iRDN );
61
62 /* AVA helpers */
63 static LDAPAVA * ldapava_new(
64         const struct berval *attr, const struct berval *val, unsigned flags );
65
66 /* Higher level helpers */
67 static int rdn2strlen( LDAPRDN *rdn, unsigned flags, ber_len_t *len,
68                 int ( *s2l )( struct berval *, unsigned, ber_len_t * ) );
69 static int rdn2str( LDAPRDN *rdn, char *str, unsigned flags, ber_len_t *len,
70                 int ( *s2s )( struct berval *, char *, unsigned, ber_len_t * ));
71 static int rdn2UFNstrlen( LDAPRDN *rdn, unsigned flags, ber_len_t *len  );
72 static int rdn2UFNstr( LDAPRDN *rdn, char *str, unsigned flags, ber_len_t *len );
73 static int rdn2DCEstrlen( LDAPRDN *rdn, unsigned flags, ber_len_t *len );
74 static int rdn2DCEstr( LDAPRDN *rdn, char *str, unsigned flag, ber_len_t *len, int first );
75 static int rdn2ADstrlen( LDAPRDN *rdn, unsigned flags, ber_len_t *len );
76 static int rdn2ADstr( LDAPRDN *rdn, char *str, unsigned flags, ber_len_t *len, int first );
77
78 /*
79  * RFC 1823 ldap_get_dn
80  */
81 char *
82 ldap_get_dn( LDAP *ld, LDAPMessage *entry )
83 {
84         char            *dn;
85         BerElement      tmp;
86
87 #ifdef NEW_LOGGING
88         LDAP_LOG (( "getdn", LDAP_LEVEL_ENTRY, "ldap_get_dn\n" ));
89 #else
90         Debug( LDAP_DEBUG_TRACE, "ldap_get_dn\n", 0, 0, 0 );
91 #endif
92
93         assert( ld != NULL );
94         assert( LDAP_VALID(ld) );
95         assert( entry != NULL );
96
97         tmp = *entry->lm_ber;   /* struct copy */
98         if ( ber_scanf( &tmp, "{a" /*}*/, &dn ) == LBER_ERROR ) {
99                 ld->ld_errno = LDAP_DECODING_ERROR;
100                 return( NULL );
101         }
102
103         return( dn );
104 }
105
106 /*
107  * RFC 1823 ldap_dn2ufn
108  */
109 char *
110 ldap_dn2ufn( LDAP_CONST char *dn )
111 {
112         char    *out = NULL;
113
114 #ifdef NEW_LOGGING
115         LDAP_LOG (( "getdn", LDAP_LEVEL_ENTRY, "ldap_dn2ufn\n" ));
116 #else
117         Debug( LDAP_DEBUG_TRACE, "ldap_dn2ufn\n", 0, 0, 0 );
118 #endif
119
120         ( void )ldap_dn_normalize( dn, LDAP_DN_FORMAT_LDAP, 
121                 &out, LDAP_DN_FORMAT_UFN );
122         
123         return( out );
124 }
125
126 /*
127  * RFC 1823 ldap_explode_dn
128  */
129 char **
130 ldap_explode_dn( LDAP_CONST char *dn, int notypes )
131 {
132         LDAPDN  *tmpDN;
133         char    **values = NULL;
134         int     iRDN;
135         unsigned flag = notypes ? LDAP_DN_FORMAT_UFN : LDAP_DN_FORMAT_LDAPV3;
136         
137 #ifdef NEW_LOGGING
138         LDAP_LOG (( "getdn", LDAP_LEVEL_ENTRY, "ldap_explode_dn\n" ));
139 #else
140         Debug( LDAP_DEBUG_TRACE, "ldap_explode_dn\n", 0, 0, 0 );
141 #endif
142
143         if ( ldap_str2dn( dn, &tmpDN, LDAP_DN_FORMAT_LDAP ) 
144                         != LDAP_SUCCESS ) {
145                 return NULL;
146         }
147
148         if( tmpDN == NULL ) {
149                 values = LDAP_MALLOC( sizeof( char * ) );
150                 if( values == NULL ) return NULL;
151
152                 values[0] = NULL;
153                 return values;
154         }
155
156         for ( iRDN = 0; tmpDN[ 0 ][ iRDN ]; iRDN++ );
157
158         values = LDAP_MALLOC( sizeof( char * ) * ( 1 + iRDN ) );
159         if ( values == NULL ) {
160                 ldap_dnfree( tmpDN );
161                 return NULL;
162         }
163
164         for ( iRDN = 0; tmpDN[ 0 ][ iRDN ]; iRDN++ ) {
165                 ldap_rdn2str( tmpDN[ 0 ][ iRDN ], &values[ iRDN ], flag );
166         }
167         ldap_dnfree( tmpDN );
168         values[ iRDN ] = NULL;
169
170         return values;
171 }
172
173 char **
174 ldap_explode_rdn( LDAP_CONST char *rdn, int notypes )
175 {
176         LDAPRDN         *tmpRDN;
177         char            **values = NULL;
178         const char      *p;
179         int             iAVA;
180         
181 #ifdef NEW_LOGGING
182         LDAP_LOG (( "getdn", LDAP_LEVEL_ENTRY, "ldap_explode_rdn\n" ));
183 #else
184         Debug( LDAP_DEBUG_TRACE, "ldap_explode_rdn\n", 0, 0, 0 );
185 #endif
186
187         /*
188          * we only parse the first rdn
189          * FIXME: we prefer efficiency over checking if the _ENTIRE_
190          * dn can be parsed
191          */
192         if ( ldap_str2rdn( rdn, &tmpRDN, (char **) &p, LDAP_DN_FORMAT_LDAP ) 
193                         != LDAP_SUCCESS ) {
194                 return( NULL );
195         }
196
197         for ( iAVA = 0; tmpRDN[ 0 ][ iAVA ]; iAVA++ ) ;
198         values = LDAP_MALLOC( sizeof( char * ) * ( 1 + iAVA ) );
199         if ( values == NULL ) {
200                 ldap_rdnfree( tmpRDN );
201                 return( NULL );
202         }
203
204         for ( iAVA = 0; tmpRDN[ 0 ][ iAVA ]; iAVA++ ) {
205                 ber_len_t       l = 0, vl, al = 0;
206                 char            *str;
207                 LDAPAVA         *ava = tmpRDN[ 0 ][ iAVA ];
208                 
209                 if ( ava->la_flags == LDAP_AVA_BINARY ) {
210                         vl = 1 + 2 * ava->la_value.bv_len;
211
212                 } else {
213                         if ( strval2strlen( &ava->la_value, 
214                                                 ava->la_flags, &vl ) ) {
215                                 goto error_return;
216                         }
217                 }
218                 
219                 if ( !notypes ) {
220                         al = ava->la_attr.bv_len;
221                         l = vl + ava->la_attr.bv_len + 1;
222
223                         str = LDAP_MALLOC( l + 1 );
224                         AC_MEMCPY( str, ava->la_attr.bv_val, 
225                                         ava->la_attr.bv_len );
226                         str[ al++ ] = '=';
227
228                 } else {
229                         l = vl;
230                         str = LDAP_MALLOC( l + 1 );
231                 }
232                 
233                 if ( ava->la_flags == LDAP_AVA_BINARY ) {
234                         str[ al++ ] = '#';
235                         if ( binval2hexstr( &ava->la_value, &str[ al ] ) ) {
236                                 goto error_return;
237                         }
238
239                 } else {
240                         if ( strval2str( &ava->la_value, &str[ al ], 
241                                         ava->la_flags, &vl ) ) {
242                                 goto error_return;
243                         }
244                 }
245
246                 str[ l ] = '\0';
247                 values[ iAVA ] = str;
248         }
249         values[ iAVA ] = NULL;
250
251         ldap_rdnfree( tmpRDN );
252
253         return( values );
254
255 error_return:;
256         LBER_VFREE( values );
257         ldap_rdnfree( tmpRDN );
258         return( NULL );
259 }
260
261 char *
262 ldap_dn2dcedn( LDAP_CONST char *dn )
263 {
264         char    *out = NULL;
265
266 #ifdef NEW_LOGGING
267         LDAP_LOG (( "getdn", LDAP_LEVEL_ENTRY, "ldap_dn2dcedn\n" ));
268 #else
269         Debug( LDAP_DEBUG_TRACE, "ldap_dn2dcedn\n", 0, 0, 0 );
270 #endif
271
272         ( void )ldap_dn_normalize( dn, LDAP_DN_FORMAT_LDAP, 
273                                    &out, LDAP_DN_FORMAT_DCE );
274
275         return( out );
276 }
277
278 char *
279 ldap_dcedn2dn( LDAP_CONST char *dce )
280 {
281         char    *out = NULL;
282
283 #ifdef NEW_LOGGING
284         LDAP_LOG (( "getdn", LDAP_LEVEL_ENTRY, "ldap_dcedn2dn\n" ));
285 #else
286         Debug( LDAP_DEBUG_TRACE, "ldap_dcedn2dn\n", 0, 0, 0 );
287 #endif
288
289         ( void )ldap_dn_normalize( dce, LDAP_DN_FORMAT_DCE, &out, LDAP_DN_FORMAT_LDAPV3 );
290
291         return( out );
292 }
293
294 char *
295 ldap_dn2ad_canonical( LDAP_CONST char *dn )
296 {
297         char    *out = NULL;
298
299 #ifdef NEW_LOGGING
300         LDAP_LOG (( "getdn", LDAP_LEVEL_ENTRY, "ldap_dn2ad_canonical\n" ));
301 #else
302         Debug( LDAP_DEBUG_TRACE, "ldap_dn2ad_canonical\n", 0, 0, 0 );
303 #endif
304
305         ( void )ldap_dn_normalize( dn, LDAP_DN_FORMAT_LDAP, 
306                        &out, LDAP_DN_FORMAT_AD_CANONICAL );
307
308         return( out );
309 }
310
311 /*
312  * function that changes the string representation of dnin
313  * from ( fin & LDAP_DN_FORMAT_MASK ) to ( fout & LDAP_DN_FORMAT_MASK )
314  * 
315  * fin can be one of:
316  *      LDAP_DN_FORMAT_LDAP             (rfc 2253 and ldapbis liberal, 
317  *                                      plus some rfc 1779)
318  *      LDAP_DN_FORMAT_LDAPV3           (rfc 2253 and ldapbis)
319  *      LDAP_DN_FORMAT_LDAPV2           (rfc 1779)
320  *      LDAP_DN_FORMAT_DCE              (?)
321  *
322  * fout can be any of the above except
323  *      LDAP_DN_FORMAT_LDAP
324  * plus:
325  *      LDAP_DN_FORMAT_UFN              (rfc 1781, partial and with extensions)
326  *      LDAP_DN_FORMAT_AD_CANONICAL     (?)
327  */
328 int
329 ldap_dn_normalize( LDAP_CONST char *dnin,
330         unsigned fin, char **dnout, unsigned fout )
331 {
332         int     rc;
333         LDAPDN  *tmpDN = NULL;
334
335 #ifdef NEW_LOGGING
336         LDAP_LOG (( "getdn", LDAP_LEVEL_ENTRY, "ldap_dn_normalize\n" ));
337 #else
338         Debug( LDAP_DEBUG_TRACE, "ldap_dn_normalize\n", 0, 0, 0 );
339 #endif
340
341         assert( dnout );
342
343         *dnout = NULL;
344
345         if ( dnin == NULL ) {
346                 return( LDAP_SUCCESS );
347         }
348
349         rc = ldap_str2dn( dnin , &tmpDN, fin );
350         if ( rc != LDAP_SUCCESS ) {
351                 return( rc );
352         }
353
354         rc = ldap_dn2str( tmpDN, dnout, fout );
355
356         ldap_dnfree( tmpDN );
357
358         return( rc );
359 }
360
361 /* States */
362 #define B4AVA                   0x0000
363
364 /* #define      B4ATTRTYPE              0x0001 */
365 #define B4OIDATTRTYPE           0x0002
366 #define B4STRINGATTRTYPE        0x0003
367
368 #define B4AVAEQUALS             0x0100
369 #define B4AVASEP                0x0200
370 #define B4RDNSEP                0x0300
371 #define GOTAVA                  0x0400
372
373 #define B4ATTRVALUE             0x0010
374 #define B4STRINGVALUE           0x0020
375 #define B4IA5VALUEQUOTED        0x0030
376 #define B4IA5VALUE              0x0040
377 #define B4BINARYVALUE           0x0050
378
379 /*
380  * Helpers (mostly from slap.h)
381  * c is assumed to Unicode in an ASCII compatible format (UTF-8)
382  * Macros assume "C" Locale (ASCII)
383  */
384 #define LDAP_DN_ASCII_SPACE(c) \
385         ( (c) == ' ' || (c) == '\t' || (c) == '\n' || (c) == '\r' )
386 #define LDAP_DN_ASCII_LOWER(c)          LDAP_LOWER(c)
387 #define LDAP_DN_ASCII_UPPER(c)          LDAP_UPPER(c)
388 #define LDAP_DN_ASCII_ALPHA(c)          LDAP_ALPHA(c)
389
390 #define LDAP_DN_ASCII_DIGIT(c)          LDAP_DIGIT(c)
391 #define LDAP_DN_ASCII_LCASE_HEXALPHA(c) LDAP_HEXLOWER(c)
392 #define LDAP_DN_ASCII_UCASE_HEXALPHA(c) LDAP_HEXUPPER(c)
393 #define LDAP_DN_ASCII_HEXDIGIT(c)       LDAP_HEX(c)
394 #define LDAP_DN_ASCII_ALNUM(c)          LDAP_ALNUM(c)
395 #define LDAP_DN_ASCII_PRINTABLE(c)      ( (c) >= ' ' && (c) <= '~' )
396
397 /* attribute type */
398 #define LDAP_DN_OID_LEADCHAR(c)         LDAP_DIGIT(c)
399 #define LDAP_DN_DESC_LEADCHAR(c)        LDAP_ALPHA(c)
400 #define LDAP_DN_DESC_CHAR(c)            LDAP_LDH(c)
401 #define LDAP_DN_LANG_SEP(c)             ( (c) == ';' )
402 #define LDAP_DN_ATTRDESC_CHAR(c) \
403         ( LDAP_DN_DESC_CHAR(c) || LDAP_DN_LANG_SEP(c) )
404
405 /* special symbols */
406 #define LDAP_DN_AVA_EQUALS(c)           ( (c) == '=' )
407 #define LDAP_DN_AVA_SEP(c)              ( (c) == '+' )
408 #define LDAP_DN_RDN_SEP(c)              ( (c) == ',' )
409 #define LDAP_DN_RDN_SEP_V2(c)           ( LDAP_DN_RDN_SEP(c) || (c) == ';' )
410 #define LDAP_DN_OCTOTHORPE(c)           ( (c) == '#' )
411 #define LDAP_DN_QUOTES(c)               ( (c) == '\"' )
412 #define LDAP_DN_ESCAPE(c)               ( (c) == '\\' )
413 #define LDAP_DN_VALUE_END(c) \
414         ( LDAP_DN_RDN_SEP(c) || LDAP_DN_AVA_SEP(c) )
415 #define LDAP_DN_NE(c) \
416         ( LDAP_DN_RDN_SEP_V2(c) || LDAP_DN_AVA_SEP(c) \
417           || LDAP_DN_QUOTES(c) || (c) == '<' || (c) == '>' )
418 #define LDAP_DN_MAYESCAPE(c) \
419         ( LDAP_DN_ESCAPE(c) || LDAP_DN_NE(c) \
420           || LDAP_DN_ASCII_SPACE(c) || LDAP_DN_OCTOTHORPE(c) )
421 #define LDAP_DN_NEEDESCAPE(c) \
422         ( LDAP_DN_ESCAPE(c) || LDAP_DN_NE(c) )
423 #define LDAP_DN_NEEDESCAPE_LEAD(c)      LDAP_DN_MAYESCAPE(c)
424 #define LDAP_DN_NEEDESCAPE_TRAIL(c) \
425         ( LDAP_DN_ASCII_SPACE(c) || LDAP_DN_NEEDESCAPE(c) )
426 #define LDAP_DN_WILLESCAPE_CHAR(c) \
427         ( LDAP_DN_RDN_SEP(c) || LDAP_DN_AVA_SEP(c) || LDAP_DN_ESCAPE(c) )
428 #define LDAP_DN_IS_PRETTY(f)            ( (f) & LDAP_DN_PRETTY )
429 #define LDAP_DN_WILLESCAPE_HEX(f, c) \
430         ( ( !LDAP_DN_IS_PRETTY( f ) ) && LDAP_DN_WILLESCAPE_CHAR(c) )
431
432 /* LDAPv2 */
433 #define LDAP_DN_VALUE_END_V2(c) \
434         ( LDAP_DN_RDN_SEP_V2(c) || LDAP_DN_AVA_SEP(c) )
435 /* RFC 1779 */
436 #define LDAP_DN_V2_SPECIAL(c) \
437           ( LDAP_DN_RDN_SEP_V2(c) || LDAP_DN_AVA_EQUALS(c) \
438             || LDAP_DN_AVA_SEP(c) || (c) == '<' || (c) == '>' \
439             || LDAP_DN_OCTOTHORPE(c) )
440 #define LDAP_DN_V2_PAIR(c) \
441           ( LDAP_DN_V2_SPECIAL(c) || LDAP_DN_ESCAPE(c) || LDAP_DN_QUOTES(c) )
442
443 /*
444  * DCE (mostly from Luke Howard and IBM implementation for AIX)
445  *
446  * From: "Application Development Guide - Directory Services" (FIXME: add link?)
447  * Here escapes and valid chars for GDS are considered; as soon as more
448  * specific info is found, the macros will be updated.
449  *
450  * Chars:       'a'-'z', 'A'-'Z', '0'-'9', 
451  *              '.', ':', ',', ''', '+', '-', '=', '(', ')', '?', '/', ' '.
452  *
453  * Metachars:   '/', ',', '=', '\'.
454  *
455  * the '\' is used to escape other metachars.
456  *
457  * Assertion:           '='
458  * RDN separator:       '/'
459  * AVA separator:       ','
460  * 
461  * Attribute types must start with alphabetic chars and can contain 
462  * alphabetic chars and digits (FIXME: no '-'?). OIDs are allowed.
463  */
464 #define LDAP_DN_RDN_SEP_DCE(c)          ( (c) == '/' )
465 #define LDAP_DN_AVA_SEP_DCE(c)          ( (c) == ',' )
466 #define LDAP_DN_ESCAPE_DCE(c)           ( LDAP_DN_ESCAPE(c) )
467 #define LDAP_DN_VALUE_END_DCE(c) \
468         ( LDAP_DN_RDN_SEP_DCE(c) || LDAP_DN_AVA_SEP_DCE(c) )
469 #define LDAP_DN_NEEDESCAPE_DCE(c) \
470         ( LDAP_DN_VALUE_END_DCE(c) || LDAP_DN_AVA_EQUALS(c) )
471
472 /* AD Canonical */
473 #define LDAP_DN_RDN_SEP_AD(c)           ( (c) == '/' )
474 #define LDAP_DN_ESCAPE_AD(c)            ( LDAP_DN_ESCAPE(c) )
475 #define LDAP_DN_AVA_SEP_AD(c)           ( (c) == ',' )  /* assume same as DCE */
476 #define LDAP_DN_VALUE_END_AD(c) \
477         ( LDAP_DN_RDN_SEP_AD(c) || LDAP_DN_AVA_SEP_AD(c) )
478 #define LDAP_DN_NEEDESCAPE_AD(c) \
479         ( LDAP_DN_VALUE_END_AD(c) || LDAP_DN_AVA_EQUALS(c) )
480
481 /* generics */
482 #define LDAP_DN_HEXPAIR(s) \
483         ( LDAP_DN_ASCII_HEXDIGIT((s)[0]) && LDAP_DN_ASCII_HEXDIGIT((s)[1]) )
484 /* better look at the AttributeDescription? */
485
486 /* FIXME: no composite rdn or non-"dc" types, right?
487  * (what about "dc" in OID form?) */
488 /* FIXME: we do not allow binary values in domain, right? */
489 /* NOTE: use this macro only when ABSOLUTELY SURE rdn IS VALID! */
490 /* NOTE: don't use strcasecmp() as it is locale specific! */
491 #define LDAP_DC_ATTR    "dc"
492 #define LDAP_DC_ATTRU   "DC"
493 #define LDAP_DN_IS_RDN_DC( r ) \
494         ( (r) && (r)[0][0] && !(r)[0][1] \
495           && ((r)[0][0]->la_flags == LDAP_AVA_STRING) \
496           && ((r)[0][0]->la_attr.bv_len == 2) \
497           && (((r)[0][0]->la_attr.bv_val[0] == LDAP_DC_ATTR[0]) \
498                 || ((r)[0][0]->la_attr.bv_val[0] == LDAP_DC_ATTRU[0])) \
499           && (((r)[0][0]->la_attr.bv_val[1] == LDAP_DC_ATTR[1]) \
500                 || ((r)[0][0]->la_attr.bv_val[1] == LDAP_DC_ATTRU[1])))
501
502 /* Composite rules */
503 #define LDAP_DN_ALLOW_ONE_SPACE(f) \
504         ( LDAP_DN_LDAPV2(f) \
505           || !( (f) & LDAP_DN_P_NOSPACEAFTERRDN ) )
506 #define LDAP_DN_ALLOW_SPACES(f) \
507         ( LDAP_DN_LDAPV2(f) \
508           || !( (f) & ( LDAP_DN_P_NOLEADTRAILSPACES | LDAP_DN_P_NOSPACEAFTERRDN ) ) )
509 #define LDAP_DN_LDAP(f) \
510         ( ( (f) & LDAP_DN_FORMAT_MASK ) == LDAP_DN_FORMAT_LDAP )
511 #define LDAP_DN_LDAPV3(f) \
512         ( ( (f) & LDAP_DN_FORMAT_MASK ) == LDAP_DN_FORMAT_LDAPV3 )
513 #define LDAP_DN_LDAPV2(f) \
514         ( ( (f) & LDAP_DN_FORMAT_MASK ) == LDAP_DN_FORMAT_LDAPV2 )
515 #define LDAP_DN_DCE(f) \
516         ( ( (f) & LDAP_DN_FORMAT_MASK ) == LDAP_DN_FORMAT_DCE )
517 #define LDAP_DN_UFN(f) \
518         ( ( (f) & LDAP_DN_FORMAT_MASK ) == LDAP_DN_FORMAT_UFN )
519 #define LDAP_DN_ADC(f) \
520         ( ( (f) & LDAP_DN_FORMAT_MASK ) == LDAP_DN_FORMAT_AD_CANONICAL )
521 #define LDAP_DN_FORMAT(f)               ( (f) & LDAP_DN_FORMAT_MASK )
522
523 /*
524  * LDAPAVA helpers (will become part of the API for operations 
525  * on structural representations of DNs).
526  */
527 LDAPAVA *
528 ldapava_new( const struct berval *attr, const struct berval *val, 
529                 unsigned flags )
530 {
531         LDAPAVA *ava;
532
533         assert( attr );
534         assert( val );
535
536         ava = LDAP_MALLOC( sizeof( LDAPAVA ) + attr->bv_len + 1 );
537         
538         /* should we test it? */
539         if ( ava == NULL ) {
540                 return( NULL );
541         }
542
543         ava->la_attr.bv_len = attr->bv_len;
544         ava->la_attr.bv_val = (char *)(ava+1);
545         AC_MEMCPY( ava->la_attr.bv_val, attr->bv_val, attr->bv_len );
546         ava->la_attr.bv_val[attr->bv_len] = '\0';
547
548         ava->la_value = *val;
549         ava->la_flags = flags;
550
551         ava->la_private = NULL;
552
553         return( ava );
554 }
555
556 void
557 ldap_avafree( LDAPAVA *ava )
558 {
559         assert( ava );
560
561 #if 0
562         /* ava's private must be freed by caller
563          * (at present let's skip this check because la_private
564          * basically holds static data) */
565         assert( ava->la_private == NULL );
566 #endif
567
568 #if 0
569         /* la_attr is now contiguous with ava, not freed separately */
570         LDAP_FREE( ava->la_attr.bv_val );
571 #endif
572         LDAP_FREE( ava->la_value.bv_val );
573
574         LDAP_FREE( ava );
575 }
576
577 void
578 ldap_rdnfree( LDAPRDN *rdn )
579 {
580         int iAVA;
581         
582         if ( rdn == NULL ) {
583                 return;
584         }
585
586         for ( iAVA = 0; rdn[ 0 ][ iAVA ]; iAVA++ ) {
587                 ldap_avafree( rdn[ 0 ][ iAVA ] );
588         }
589
590         LDAP_FREE( rdn );
591 }
592
593 void
594 ldap_dnfree( LDAPDN *dn )
595 {
596         int iRDN;
597         
598         if ( dn == NULL ) {
599                 return;
600         }
601
602         for ( iRDN = 0; dn[ 0 ][ iRDN ]; iRDN++ ) {
603                 ldap_rdnfree( dn[ 0 ][ iRDN ] );
604         }
605
606         LDAP_FREE( dn );
607 }
608
609 /*
610  * Converts a string representation of a DN (in LDAPv3, LDAPv2 or DCE)
611  * into a structural representation of the DN, by separating attribute
612  * types and values encoded in the more appropriate form, which is
613  * string or OID for attribute types and binary form of the BER encoded
614  * value or Unicode string. Formats different from LDAPv3 are parsed
615  * according to their own rules and turned into the more appropriate
616  * form according to LDAPv3.
617  *
618  * NOTE: I realize the code is getting spaghettish; it is rather
619  * experimental and will hopefully turn into something more simple
620  * and readable as soon as it works as expected.
621  */
622
623 /*
624  * Default sizes of AVA and RDN static working arrays; if required
625  * the are dynamically resized.  The values can be tuned in case
626  * of special requirements (e.g. very deep DN trees or high number 
627  * of AVAs per RDN).
628  */
629 #define TMP_AVA_SLOTS   8
630 #define TMP_RDN_SLOTS   32
631
632 int
633 ldap_str2dn( LDAP_CONST char *str, LDAPDN **dn, unsigned flags )
634 {
635         struct berval   bv;
636
637         assert( str );
638
639         bv.bv_len = strlen( str );
640         bv.bv_val = (char *) str;
641         
642         return ldap_bv2dn( &bv, dn, flags );
643 }
644
645 int
646 ldap_bv2dn( struct berval *bv, LDAPDN **dn, unsigned flags )
647 {
648         const char      *p;
649         int             rc = LDAP_DECODING_ERROR;
650         int             nrdns = 0;
651
652         LDAPDN          *newDN = NULL;
653         LDAPRDN         *newRDN = NULL, *tmpDN_[TMP_RDN_SLOTS], **tmpDN = tmpDN_;
654         int             num_slots = TMP_RDN_SLOTS;
655         char            *str = bv->bv_val;
656         char            *end = str + bv->bv_len;
657         
658         assert( bv );
659         assert( bv->bv_val );
660         assert( dn );
661
662 #ifdef NEW_LOGGING
663         LDAP_LOG (( "getdn", LDAP_LEVEL_ARGS, "ldap_bv2dn(%s,%u)\n%s", 
664                 str, flags, "" ));
665 #else
666         Debug( LDAP_DEBUG_TRACE, "=> ldap_bv2dn(%s,%u)\n%s", str, flags, "" );
667 #endif
668
669         *dn = NULL;
670
671         switch ( LDAP_DN_FORMAT( flags ) ) {
672         case LDAP_DN_FORMAT_LDAP:
673         case LDAP_DN_FORMAT_LDAPV3:
674         case LDAP_DN_FORMAT_LDAPV2:
675         case LDAP_DN_FORMAT_DCE:
676                 break;
677
678         /* unsupported in str2dn */
679         case LDAP_DN_FORMAT_UFN:
680         case LDAP_DN_FORMAT_AD_CANONICAL:
681                 return LDAP_PARAM_ERROR;
682
683         case LDAP_DN_FORMAT_LBER:
684         default:
685                 return LDAP_PARAM_ERROR;
686         }
687
688         if ( bv->bv_len == 0 ) {
689                 return LDAP_SUCCESS;
690         }
691
692         if( memchr( bv->bv_val, '\0', bv->bv_len ) != NULL ) {
693                 /* value must have embedded NULs */
694                 return LDAP_DECODING_ERROR;
695         }
696
697         p = str;
698         if ( LDAP_DN_DCE( flags ) ) {
699                 
700                 /* 
701                  * (from Luke Howard: thnx) A RDN separator is required
702                  * at the beginning of an (absolute) DN.
703                  */
704                 if ( !LDAP_DN_RDN_SEP_DCE( p[ 0 ] ) ) {
705                         goto parsing_error;
706                 }
707                 p++;
708
709         /*
710          * actually we do not want to accept by default the DCE form,
711          * we do not want to auto-detect it
712          */
713 #if 0
714         } else if ( LDAP_DN_LDAP( flags ) ) {
715                 /*
716                  * if dn starts with '/' let's make it a DCE dn
717                  */
718                 if ( LDAP_DN_RDN_SEP_DCE( p[ 0 ] ) ) {
719                         flags |= LDAP_DN_FORMAT_DCE;
720                         p++;
721                 }
722 #endif
723         }
724
725         for ( ; p < end; p++ ) {
726                 int             err;
727                 struct berval   tmpbv;
728                 tmpbv.bv_len = bv->bv_len - ( p - str );
729                 tmpbv.bv_val = (char *)p;
730                 
731                 err = ldap_bv2rdn( &tmpbv, &newRDN, (char **) &p, flags );
732                 if ( err != LDAP_SUCCESS ) {
733                         goto parsing_error;
734                 }
735
736                 /* 
737                  * We expect a rdn separator
738                  */
739                 if ( p < end && p[ 0 ] ) {
740                         switch ( LDAP_DN_FORMAT( flags ) ) {
741                         case LDAP_DN_FORMAT_LDAPV3:
742                                 if ( !LDAP_DN_RDN_SEP( p[ 0 ] ) ) {
743                                         rc = LDAP_DECODING_ERROR;
744                                         goto parsing_error;
745                                 }
746                                 break;
747         
748                         case LDAP_DN_FORMAT_LDAP:
749                         case LDAP_DN_FORMAT_LDAPV2:
750                                 if ( !LDAP_DN_RDN_SEP_V2( p[ 0 ] ) ) {
751                                         rc = LDAP_DECODING_ERROR;
752                                         goto parsing_error;
753                                 }
754                                 break;
755         
756                         case LDAP_DN_FORMAT_DCE:
757                                 if ( !LDAP_DN_RDN_SEP_DCE( p[ 0 ] ) ) {
758                                         rc = LDAP_DECODING_ERROR;
759                                         goto parsing_error;
760                                 }
761                                 break;
762                         }
763                 }
764
765
766                 tmpDN[nrdns++] = newRDN;
767                 newRDN = NULL;
768
769                 /*
770                  * make the static RDN array dynamically rescalable
771                  */
772                 if ( nrdns == num_slots ) {
773                         LDAPRDN **tmp;
774
775                         if ( tmpDN == tmpDN_ ) {
776                                 tmp = LDAP_MALLOC( num_slots * 2 * sizeof( LDAPRDN * ) );
777                                 if ( tmp == NULL ) {
778                                         rc = LDAP_NO_MEMORY;
779                                         goto parsing_error;
780                                 }
781                                 AC_MEMCPY( tmp, tmpDN, num_slots * sizeof( LDAPRDN * ) );
782
783                         } else {
784                                 tmp = LDAP_REALLOC( tmpDN, num_slots * 2 * sizeof( LDAPRDN * ) );
785                                 if ( tmp == NULL ) {
786                                         rc = LDAP_NO_MEMORY;
787                                         goto parsing_error;
788                                 }
789                         }
790
791                         tmpDN = tmp;
792                         num_slots *= 2;
793                 }
794                                 
795                 if ( p >= end || p[ 0 ] == '\0' ) {
796                         /* 
797                          * the DN is over, phew
798                          */
799                         newDN = (LDAPDN *)LDAP_MALLOC( sizeof(LDAPDN) +
800                                 sizeof(LDAPRDN *) * (nrdns+1));
801                         if ( newDN == NULL ) {
802                                 rc = LDAP_NO_MEMORY;
803                                 goto parsing_error;
804                         } else {
805                                 int i;
806
807                                 newDN[0] = (LDAPRDN **)(newDN+1);
808
809                                 if ( LDAP_DN_DCE( flags ) ) {
810                                         /* add in reversed order */
811                                         for ( i=0; i<nrdns; i++ )
812                                                 newDN[0][i] = tmpDN[nrdns-1-i];
813                                 } else {
814                                         for ( i=0; i<nrdns; i++ )
815                                                 newDN[0][i] = tmpDN[i];
816                                 }
817                                 newDN[0][nrdns] = NULL;
818                                 rc = LDAP_SUCCESS;
819                         }
820                         goto return_result;
821                 }
822         }
823         
824 parsing_error:;
825         if ( newRDN ) {
826                 ldap_rdnfree( newRDN );
827         }
828
829         for ( nrdns-- ;nrdns >= 0; nrdns-- ) {
830                 ldap_rdnfree( tmpDN[nrdns] );
831         }
832
833 return_result:;
834
835         if ( tmpDN != tmpDN_ ) {
836                 LDAP_FREE( tmpDN );
837         }
838
839 #ifdef NEW_LOGGING
840         LDAP_LOG (( "getdn", LDAP_LEVEL_RESULTS, "<= ldap_bv2dn(%s,%u)=%d\n", 
841                 str, flags, rc ));
842 #else
843         Debug( LDAP_DEBUG_TRACE, "<= ldap_bv2dn(%s,%u)=%d\n", str, flags, rc );
844 #endif
845         *dn = newDN;
846         
847         return( rc );
848 }
849
850 /*
851  * ldap_str2rdn
852  *
853  * Parses a relative DN according to flags up to a rdn separator 
854  * or to the end of str.
855  * Returns the rdn and a pointer to the string continuation, which
856  * corresponds to the rdn separator or to '\0' in case the string is over.
857  */
858 int
859 ldap_str2rdn( LDAP_CONST char *str, LDAPRDN **rdn,
860         char **n_in, unsigned flags )
861 {
862         struct berval   bv;
863
864         assert( str );
865         assert( str[ 0 ] != '\0' );     /* FIXME: is this required? */
866
867         bv.bv_len = strlen( str );
868         bv.bv_val = (char *) str;
869
870         return ldap_bv2rdn( &bv, rdn, n_in, flags );
871 }
872
873 int
874 ldap_bv2rdn( struct berval *bv, LDAPRDN **rdn,
875         char **n_in, unsigned flags )
876 {
877         const char      **n = (const char **) n_in;
878         const char      *p;
879         int             navas = 0;
880         int             state = B4AVA;
881         int             rc = LDAP_DECODING_ERROR;
882         int             attrTypeEncoding = LDAP_AVA_STRING, 
883                         attrValueEncoding = LDAP_AVA_STRING;
884
885         struct berval   attrType = { 0, NULL };
886         struct berval   attrValue = { 0, NULL };
887
888         LDAPRDN         *newRDN = NULL;
889         LDAPAVA         *tmpRDN_[TMP_AVA_SLOTS], **tmpRDN = tmpRDN_;
890         int             num_slots = TMP_AVA_SLOTS;
891
892         char            *str;
893         ber_len_t       stoplen;
894         
895         assert( bv );
896         assert( bv->bv_len );
897         assert( bv->bv_val );
898         assert( rdn || flags & LDAP_DN_SKIP );
899         assert( n );
900
901         str = bv->bv_val;
902         stoplen = bv->bv_len;
903
904         if ( rdn ) {
905                 *rdn = NULL;
906         }
907         *n = NULL;
908
909         switch ( LDAP_DN_FORMAT( flags ) ) {
910         case LDAP_DN_FORMAT_LDAP:
911         case LDAP_DN_FORMAT_LDAPV3:
912         case LDAP_DN_FORMAT_LDAPV2:
913         case LDAP_DN_FORMAT_DCE:
914                 break;
915
916         /* unsupported in str2dn */
917         case LDAP_DN_FORMAT_UFN:
918         case LDAP_DN_FORMAT_AD_CANONICAL:
919                 return LDAP_PARAM_ERROR;
920
921         case LDAP_DN_FORMAT_LBER:
922         default:
923                 return LDAP_PARAM_ERROR;
924         }
925
926         if ( bv->bv_len == 0 ) {
927                 return LDAP_SUCCESS;
928
929         }
930
931         if( memchr( bv->bv_val, '\0', bv->bv_len ) != NULL ) {
932                 /* value must have embedded NULs */
933                 return LDAP_DECODING_ERROR;
934         }
935
936         p = str;
937         for ( ; p[ 0 ] || state == GOTAVA; ) {
938                 
939                 /*
940                  * The parser in principle advances one token a time,
941                  * or toggles state if preferable.
942                  */
943                 switch (state) {
944
945                 /*
946                  * an AttributeType can be encoded as:
947                  * - its string representation; in detail, implementations
948                  *   MUST recognize AttributeType string type names listed 
949                  *   in section 2.3 of draft-ietf-ldapbis-dn-XX.txt, and
950                  *   MAY recognize other names.
951                  * - its numeric OID (a dotted decimal string); in detail
952                  *   RFC 2253 asserts that ``Implementations MUST allow 
953                  *   an oid in the attribute type to be prefixed by one 
954                  *   of the character strings "oid." or "OID."''.  As soon
955                  *   as draft-ietf-ldapbis-dn-XX.txt obsoletes RFC 2253 
956                  *   I'm not sure whether this is required or not any 
957                  *   longer; to be liberal, we still implement it.
958                  */
959                 case B4AVA:
960                         if ( LDAP_DN_ASCII_SPACE( p[ 0 ] ) ) {
961                                 if ( !LDAP_DN_ALLOW_ONE_SPACE( flags ) ) {
962                                         /* error */
963                                         goto parsing_error;
964                                 }
965                                 p++;
966                         }
967
968                         if ( LDAP_DN_ASCII_SPACE( p[ 0 ] ) ) {
969                                 if ( !LDAP_DN_ALLOW_SPACES( flags ) ) {
970                                         /* error */
971                                         goto parsing_error;
972                                 }
973
974                                 /* whitespace is allowed (and trimmed) */
975                                 p++;
976                                 while ( p[ 0 ] && LDAP_DN_ASCII_SPACE( p[ 0 ] ) ) {
977                                         p++;
978                                 }
979
980                                 if ( !p[ 0 ] ) {
981                                         /* error: we expected an AVA */
982                                         goto parsing_error;
983                                 }
984                         }
985
986                         /* oid */
987                         if ( LDAP_DN_OID_LEADCHAR( p[ 0 ] ) ) {
988                                 state = B4OIDATTRTYPE;
989                                 break;
990                         }
991                         
992                         /* else must be alpha */
993                         if ( !LDAP_DN_DESC_LEADCHAR( p[ 0 ] ) ) {
994                                 goto parsing_error;
995                         }
996                         
997                         /* LDAPv2 "oid." prefix */
998                         if ( LDAP_DN_LDAPV2( flags ) ) {
999                                 /*
1000                                  * to be overly pedantic, we only accept
1001                                  * "OID." or "oid."
1002                                  */
1003                                 if ( flags & LDAP_DN_PEDANTIC ) {
1004                                         if ( !strncmp( p, "OID.", 4 )
1005                                                 || !strncmp( p, "oid.", 4 ) ) {
1006                                                 p += 4;
1007                                                 state = B4OIDATTRTYPE;
1008                                                 break;
1009                                         }
1010                                 } else {
1011                                        if ( !strncasecmp( p, "oid.", 4 ) ) {
1012                                                p += 4;
1013                                                state = B4OIDATTRTYPE;
1014                                                break;
1015                                        }
1016                                 }
1017                         }
1018
1019                         state = B4STRINGATTRTYPE;
1020                         break;
1021                 
1022                 case B4OIDATTRTYPE: {
1023                         int             err = LDAP_SUCCESS;
1024                         
1025                         attrType.bv_val = ldap_int_parse_numericoid( &p, &err,
1026                                 LDAP_SCHEMA_SKIP);
1027
1028                         if ( err != LDAP_SUCCESS ) {
1029                                 goto parsing_error;
1030                         }
1031                         attrType.bv_len = p - attrType.bv_val;
1032
1033                         attrTypeEncoding = LDAP_AVA_BINARY;
1034
1035                         state = B4AVAEQUALS;
1036                         break;
1037                 }
1038
1039                 case B4STRINGATTRTYPE: {
1040                         const char      *startPos, *endPos = NULL;
1041                         ber_len_t       len;
1042                         
1043                         /* 
1044                          * the starting char has been found to be
1045                          * a LDAP_DN_DESC_LEADCHAR so we don't re-check it
1046                          * FIXME: DCE attr types seem to have a more
1047                          * restrictive syntax (no '-' ...) 
1048                          */
1049                         for ( startPos = p++; p[ 0 ]; p++ ) {
1050                                 if ( LDAP_DN_DESC_CHAR( p[ 0 ] ) ) {
1051                                         continue;
1052                                 }
1053
1054                                 if ( LDAP_DN_LANG_SEP( p[ 0 ] ) ) {
1055                                         
1056                                         /*
1057                                          * RFC 2253 does not explicitly
1058                                          * allow lang extensions to attribute 
1059                                          * types in DNs ... 
1060                                          */
1061                                         if ( flags & LDAP_DN_PEDANTIC ) {
1062                                                 goto parsing_error;
1063                                         }
1064
1065                                         /*
1066                                          * we trim ';' and following lang 
1067                                          * and so from attribute types
1068                                          */
1069                                         endPos = p;
1070                                         for ( ; LDAP_DN_ATTRDESC_CHAR( p[ 0 ] )
1071                                                         || LDAP_DN_LANG_SEP( p[ 0 ] ); p++ ) {
1072                                                 /* no op */ ;
1073                                         }
1074                                         break;
1075                                 }
1076                                 break;
1077                         }
1078
1079                         len = ( endPos ? endPos : p ) - startPos;
1080                         if ( len == 0 ) {
1081                                 goto parsing_error;
1082                         }
1083                         
1084                         attrTypeEncoding = LDAP_AVA_STRING;
1085
1086                         /*
1087                          * here we need to decide whether to use it as is 
1088                          * or turn it in OID form; as a consequence, we
1089                          * need to decide whether to binary encode the value
1090                          */
1091                         
1092                         state = B4AVAEQUALS;
1093
1094                         if ( flags & LDAP_DN_SKIP ) {
1095                                 break;
1096                         }
1097
1098                         attrType.bv_val = (char *)startPos;
1099                         attrType.bv_len = len;
1100
1101                         break;
1102                 }
1103                                 
1104                 case B4AVAEQUALS:
1105                         /* spaces may not be allowed */
1106                         if ( LDAP_DN_ASCII_SPACE( p[ 0 ] ) ) {
1107                                 if ( !LDAP_DN_ALLOW_SPACES( flags ) ) {
1108                                         goto parsing_error;
1109                                 }
1110                         
1111                                 /* trim spaces */
1112                                 for ( p++; LDAP_DN_ASCII_SPACE( p[ 0 ] ); p++ ) {
1113                                         /* no op */
1114                                 }
1115                         }
1116
1117                         /* need equal sign */
1118                         if ( !LDAP_DN_AVA_EQUALS( p[ 0 ] ) ) {
1119                                 goto parsing_error;
1120                         }
1121                         p++;
1122
1123                         /* spaces may not be allowed */
1124                         if ( LDAP_DN_ASCII_SPACE( p[ 0 ] ) ) {
1125                                 if ( !LDAP_DN_ALLOW_SPACES( flags ) ) {
1126                                         goto parsing_error;
1127                                 }
1128
1129                                 /* trim spaces */
1130                                 for ( p++; LDAP_DN_ASCII_SPACE( p[ 0 ] ); p++ ) {
1131                                         /* no op */
1132                                 }
1133                         }
1134
1135                         /*
1136                          * octothorpe means a BER encoded value will follow
1137                          * FIXME: I don't think DCE will allow it
1138                          */
1139                         if ( LDAP_DN_OCTOTHORPE( p[ 0 ] ) ) {
1140                                 p++;
1141                                 attrValueEncoding = LDAP_AVA_BINARY;
1142                                 state = B4BINARYVALUE;
1143                                 break;
1144                         }
1145
1146                         /* STRING value expected */
1147
1148                         /* 
1149                          * if we're pedantic, an attribute type in OID form
1150                          * SHOULD imply a BER encoded attribute value; we
1151                          * should at least issue a warning
1152                          */
1153                         if ( ( flags & LDAP_DN_PEDANTIC )
1154                                 && ( attrTypeEncoding == LDAP_AVA_BINARY ) ) {
1155                                 /* OID attrType SHOULD use binary encoding */
1156                                 goto parsing_error;
1157                         }
1158
1159                         attrValueEncoding = LDAP_AVA_STRING;
1160
1161                         /* 
1162                          * LDAPv2 allows the attribute value to be quoted;
1163                          * also, IA5 values are expected, in principle
1164                          */
1165                         if ( LDAP_DN_LDAPV2( flags ) || LDAP_DN_LDAP( flags ) ) {
1166                                 if ( LDAP_DN_QUOTES( p[ 0 ] ) ) {
1167                                         p++;
1168                                         state = B4IA5VALUEQUOTED;
1169                                         break;
1170                                 }
1171
1172                                 if ( LDAP_DN_LDAPV2( flags ) ) {
1173                                         state = B4IA5VALUE;
1174                                         break;
1175                                 }
1176                         }
1177
1178                         /*
1179                          * here STRING means RFC 2253 string
1180                          * FIXME: what about DCE strings? 
1181                          */
1182                         if ( !p[ 0 ] ) {
1183                                 /* empty value */
1184                                 state = GOTAVA;
1185                         } else {
1186                                 state = B4STRINGVALUE;
1187                         }
1188                         break;
1189
1190                 case B4BINARYVALUE:
1191                         if ( hexstr2binval( p, &attrValue, &p, flags ) ) {
1192                                 goto parsing_error;
1193                         }
1194
1195                         state = GOTAVA;
1196                         break;
1197
1198                 case B4STRINGVALUE:
1199                         switch ( LDAP_DN_FORMAT( flags ) ) {
1200                         case LDAP_DN_FORMAT_LDAP:
1201                         case LDAP_DN_FORMAT_LDAPV3:
1202                                 if ( str2strval( p, stoplen - ( p - str ),
1203                                                         &attrValue, &p, flags, 
1204                                                         &attrValueEncoding ) ) {
1205                                         goto parsing_error;
1206                                 }
1207                                 break;
1208
1209                         case LDAP_DN_FORMAT_DCE:
1210                                 if ( DCE2strval( p, &attrValue, &p, flags ) ) {
1211                                         goto parsing_error;
1212                                 }
1213                                 break;
1214
1215                         default:
1216                                 assert( 0 );
1217                         }
1218
1219                         state = GOTAVA;
1220                         break;
1221
1222                 case B4IA5VALUE:
1223                         if ( IA52strval( p, &attrValue, &p, flags ) ) {
1224                                 goto parsing_error;
1225                         }
1226
1227                         state = GOTAVA;
1228                         break;
1229                 
1230                 case B4IA5VALUEQUOTED:
1231
1232                         /* lead quote already stripped */
1233                         if ( quotedIA52strval( p, &attrValue, 
1234                                                 &p, flags ) ) {
1235                                 goto parsing_error;
1236                         }
1237
1238                         state = GOTAVA;
1239                         break;
1240
1241                 case GOTAVA: {
1242                         int     rdnsep = 0;
1243
1244                         if ( !( flags & LDAP_DN_SKIP ) ) {
1245                                 LDAPAVA *ava;
1246
1247                                 /*
1248                                  * we accept empty values
1249                                  */
1250                                 ava = ldapava_new( &attrType, &attrValue, 
1251                                                 attrValueEncoding );
1252                                 
1253                                 if ( ava == NULL ) {
1254                                         rc = LDAP_NO_MEMORY;
1255                                         goto parsing_error;
1256                                 }
1257                                 tmpRDN[navas++] = ava;
1258
1259                                 attrValue.bv_val = NULL;
1260                                 attrValue.bv_len = 0;
1261
1262                                 /*
1263                                  * prepare room for new AVAs if needed
1264                                  */
1265                                 if (navas == num_slots) {
1266                                         LDAPAVA **tmp;
1267                                         
1268                                         if ( tmpRDN == tmpRDN_ ) {
1269                                                 tmp = LDAP_MALLOC( num_slots * 2 * sizeof( LDAPAVA * ) );
1270                                                 if ( tmp == NULL ) {
1271                                                         rc = LDAP_NO_MEMORY;
1272                                                         goto parsing_error;
1273                                                 }
1274                                                 AC_MEMCPY( tmp, tmpRDN, num_slots * sizeof( LDAPAVA * ) );
1275
1276                                         } else {
1277                                                 tmp = LDAP_REALLOC( tmpRDN, num_slots * 2 * sizeof( LDAPAVA * ) );
1278                                                 if ( tmp == NULL ) {
1279                                                         rc = LDAP_NO_MEMORY;
1280                                                         goto parsing_error;
1281                                                 }
1282                                         }
1283
1284                                         tmpRDN = tmp;
1285                                         num_slots *= 2;
1286                                 }
1287                         }
1288                         
1289                         /* 
1290                          * if we got an AVA separator ('+', or ',' for DCE ) 
1291                          * we expect a new AVA for this RDN; otherwise 
1292                          * we add the RDN to the DN
1293                          */
1294                         switch ( LDAP_DN_FORMAT( flags ) ) {
1295                         case LDAP_DN_FORMAT_LDAP:
1296                         case LDAP_DN_FORMAT_LDAPV3:
1297                         case LDAP_DN_FORMAT_LDAPV2:
1298                                 if ( !LDAP_DN_AVA_SEP( p[ 0 ] ) ) {
1299                                         rdnsep = 1;
1300                                 }
1301                                 break;
1302
1303                         case LDAP_DN_FORMAT_DCE:
1304                                 if ( !LDAP_DN_AVA_SEP_DCE( p[ 0 ] ) ) {
1305                                         rdnsep = 1;
1306                                 }
1307                                 break;
1308                         }
1309
1310                         if ( rdnsep ) {
1311                                 /* 
1312                                  * the RDN is over, phew
1313                                  */
1314                                 *n = p;
1315                                 if ( !( flags & LDAP_DN_SKIP ) ) {
1316                                         newRDN = (LDAPRDN *)LDAP_MALLOC( sizeof(LDAPRDN)
1317                                                 + sizeof(LDAPAVA *) * (navas+1) );
1318                                         if ( newRDN == NULL ) {
1319                                                 rc = LDAP_NO_MEMORY;
1320                                                 goto parsing_error;
1321                                         } else {
1322                                                 int i;
1323
1324                                                 newRDN[0] = (LDAPAVA**)(newRDN+1);
1325
1326                                                 for (i=0; i<navas; i++)
1327                                                         newRDN[0][i] = tmpRDN[i];
1328                                                 newRDN[0][i] = NULL;
1329                                         }
1330
1331                                 }
1332                                 rc = LDAP_SUCCESS;
1333                                 goto return_result;
1334                         }
1335
1336                         /* they should have been used in an AVA */
1337                         attrType.bv_val = NULL;
1338                         attrValue.bv_val = NULL;
1339                         
1340                         p++;
1341                         state = B4AVA;
1342                         break;
1343                 }
1344
1345                 default:
1346                         assert( 0 );
1347                         goto parsing_error;
1348                 }
1349         }
1350         *n = p;
1351         
1352 parsing_error:;
1353         /* They are set to NULL after they're used in an AVA */
1354
1355         if ( attrValue.bv_val ) {
1356                 free( attrValue.bv_val );
1357         }
1358
1359         for ( navas-- ; navas >= 0; navas-- ) {
1360                 ldap_avafree( tmpRDN[navas] );
1361         }
1362
1363 return_result:;
1364
1365         if ( tmpRDN != tmpRDN_ ) {
1366                 LDAP_FREE( tmpRDN );
1367         }
1368
1369         if ( rdn ) {
1370                 *rdn = newRDN;
1371         }
1372         
1373         return( rc );
1374 }
1375
1376 /*
1377  * reads in a UTF-8 string value, unescaping stuff:
1378  * '\' + LDAP_DN_NEEDESCAPE(c) -> 'c'
1379  * '\' + HEXPAIR(p) -> unhex(p)
1380  */
1381 static int
1382 str2strval( const char *str, ber_len_t stoplen, struct berval *val, const char **next, unsigned flags, unsigned *retFlags )
1383 {
1384         const char      *p, *end, *startPos, *endPos = NULL;
1385         ber_len_t       len, escapes;
1386
1387         assert( str );
1388         assert( val );
1389         assert( next );
1390
1391         *next = NULL;
1392         end = str + stoplen;
1393         for ( startPos = p = str, escapes = 0; p < end; p++ ) {
1394                 if ( LDAP_DN_ESCAPE( p[ 0 ] ) ) {
1395                         p++;
1396                         if ( p[ 0 ] == '\0' ) {
1397                                 return( 1 );
1398                         }
1399                         if ( LDAP_DN_MAYESCAPE( p[ 0 ] ) ) {
1400                                 escapes++;
1401                                 continue;
1402                         }
1403
1404                         if ( LDAP_DN_HEXPAIR( p ) ) {
1405                                 char c;
1406
1407                                 hexstr2bin( p, &c );
1408                                 escapes += 2;
1409
1410                                 if ( !LDAP_DN_ASCII_PRINTABLE( c ) ) {
1411
1412                                         /*
1413                                          * we assume the string is UTF-8
1414                                          */
1415                                         *retFlags = LDAP_AVA_NONPRINTABLE;
1416                                 }
1417                                 p++;
1418
1419                                 continue;
1420                         }
1421
1422                         if ( LDAP_DN_PEDANTIC & flags ) {
1423                                 return( 1 );
1424                         }
1425                         /* 
1426                          * we do not allow escaping 
1427                          * of chars that don't need 
1428                          * to and do not belong to 
1429                          * HEXDIGITS
1430                          */
1431                         return( 1 );
1432
1433                 } else if (!LDAP_DN_ASCII_PRINTABLE( p[ 0 ] ) ) {
1434                         if ( p[ 0 ] == '\0' ) {
1435                                 return( 1 );
1436                         }
1437                         *retFlags = LDAP_AVA_NONPRINTABLE;
1438
1439                 } else if ( ( LDAP_DN_LDAP( flags ) && LDAP_DN_VALUE_END_V2( p[ 0 ] ) ) 
1440                                 || ( LDAP_DN_LDAPV3( flags ) && LDAP_DN_VALUE_END( p[ 0 ] ) ) ) {
1441                         break;
1442
1443                 } else if ( LDAP_DN_NEEDESCAPE( p[ 0 ] ) ) {
1444                         /* 
1445                          * FIXME: maybe we can add 
1446                          * escapes if not pedantic?
1447                          */
1448                         return( 1 );
1449                 }
1450         }
1451
1452         /*
1453          * we do allow unescaped spaces at the end
1454          * of the value only in non-pedantic mode
1455          */
1456         if ( p > startPos + 1 && LDAP_DN_ASCII_SPACE( p[ -1 ] ) &&
1457                         !LDAP_DN_ESCAPE( p[ -2 ] ) ) {
1458                 if ( flags & LDAP_DN_PEDANTIC ) {
1459                         return( 1 );
1460                 }
1461
1462                 /* strip trailing (unescaped) spaces */
1463                 for ( endPos = p - 1; 
1464                                 endPos > startPos + 1 && 
1465                                 LDAP_DN_ASCII_SPACE( endPos[ -1 ] ) &&
1466                                 !LDAP_DN_ESCAPE( endPos[ -2 ] );
1467                                 endPos-- ) {
1468                         /* no op */
1469                 }
1470         }
1471
1472         *next = p;
1473         if ( flags & LDAP_DN_SKIP ) {
1474                 return( 0 );
1475         }
1476
1477         /*
1478          * FIXME: test memory?
1479          */
1480         len = ( endPos ? endPos : p ) - startPos - escapes;
1481         val->bv_len = len;
1482
1483         if ( escapes == 0 ) {
1484                 if ( *retFlags == LDAP_AVA_NONPRINTABLE ) {
1485                         val->bv_val = LDAP_MALLOC( len + 1 );
1486                         AC_MEMCPY( val->bv_val, startPos, len );
1487                         val->bv_val[ len ] = '\0';
1488                 } else {
1489                         val->bv_val = LDAP_STRNDUP( startPos, len );
1490                 }
1491
1492         } else {
1493                 ber_len_t       s, d;
1494
1495                 val->bv_val = LDAP_MALLOC( len + 1 );
1496                 for ( s = 0, d = 0; d < len; ) {
1497                         if ( LDAP_DN_ESCAPE( startPos[ s ] ) ) {
1498                                 s++;
1499                                 if ( LDAP_DN_MAYESCAPE( startPos[ s ] ) ) {
1500                                         val->bv_val[ d++ ] = 
1501                                                 startPos[ s++ ];
1502                                         
1503                                 } else if ( LDAP_DN_HEXPAIR( &startPos[ s ] ) ) {
1504                                         char    c;
1505
1506                                         hexstr2bin( &startPos[ s ], &c );
1507                                         val->bv_val[ d++ ] = c;
1508                                         s += 2;
1509                                         
1510                                 } else {
1511                                         /* we should never get here */
1512                                         assert( 0 );
1513                                 }
1514
1515                         } else {
1516                                 val->bv_val[ d++ ] = startPos[ s++ ];
1517                         }
1518                 }
1519
1520                 val->bv_val[ d ] = '\0';
1521                 assert( d == len );
1522         }
1523
1524         return( 0 );
1525 }
1526
1527 static int
1528 DCE2strval( const char *str, struct berval *val, const char **next, unsigned flags )
1529 {
1530         const char      *p, *startPos, *endPos = NULL;
1531         ber_len_t       len, escapes;
1532
1533         assert( str );
1534         assert( val );
1535         assert( next );
1536
1537         *next = NULL;
1538         
1539         for ( startPos = p = str, escapes = 0; p[ 0 ]; p++ ) {
1540                 if ( LDAP_DN_ESCAPE_DCE( p[ 0 ] ) ) {
1541                         p++;
1542                         if ( LDAP_DN_NEEDESCAPE_DCE( p[ 0 ] ) ) {
1543                                 escapes++;
1544
1545                         } else {
1546                                 return( 1 );
1547                         }
1548
1549                 } else if ( LDAP_DN_VALUE_END_DCE( p[ 0 ] ) ) {
1550                         break;
1551                 }
1552
1553                 /*
1554                  * FIXME: can we accept anything else? I guess we need
1555                  * to stop if a value is not legal
1556                  */
1557         }
1558
1559         /* 
1560          * (unescaped) trailing spaces are trimmed must be silently ignored;
1561          * so we eat them
1562          */
1563         if ( p > startPos + 1 && LDAP_DN_ASCII_SPACE( p[ -1 ] ) &&
1564                         !LDAP_DN_ESCAPE( p[ -2 ] ) ) {
1565                 if ( flags & LDAP_DN_PEDANTIC ) {
1566                         return( 1 );
1567                 }
1568
1569                 /* strip trailing (unescaped) spaces */
1570                 for ( endPos = p - 1; 
1571                                 endPos > startPos + 1 && 
1572                                 LDAP_DN_ASCII_SPACE( endPos[ -1 ] ) &&
1573                                 !LDAP_DN_ESCAPE( endPos[ -2 ] );
1574                                 endPos-- ) {
1575                         /* no op */
1576                 }
1577         }
1578
1579         *next = p;
1580         if ( flags & LDAP_DN_SKIP ) {
1581                 return( 0 );
1582         }
1583         
1584         len = ( endPos ? endPos : p ) - startPos - escapes;
1585         val->bv_len = len;
1586         if ( escapes == 0 ){
1587                 val->bv_val = LDAP_STRNDUP( startPos, len );
1588
1589         } else {
1590                 ber_len_t       s, d;
1591
1592                 val->bv_val = LDAP_MALLOC( len + 1 );
1593                 for ( s = 0, d = 0; d < len; ) {
1594                         /*
1595                          * This point is reached only if escapes 
1596                          * are properly used, so all we need to
1597                          * do is eat them
1598                          */
1599                         if (  LDAP_DN_ESCAPE_DCE( startPos[ s ] ) ) {
1600                                 s++;
1601
1602                         }
1603                         val->bv_val[ d++ ] = startPos[ s++ ];
1604                 }
1605                 val->bv_val[ d ] = '\0';
1606                 assert( strlen( val->bv_val ) == len );
1607         }
1608         
1609         return( 0 );
1610 }
1611
1612 static int
1613 IA52strval( const char *str, struct berval *val, const char **next, unsigned flags )
1614 {
1615         const char      *p, *startPos, *endPos = NULL;
1616         ber_len_t       len, escapes;
1617
1618         assert( str );
1619         assert( val );
1620         assert( next );
1621
1622         *next = NULL;
1623
1624         /*
1625          * LDAPv2 (RFC 1779)
1626          */
1627         
1628         for ( startPos = p = str, escapes = 0; p[ 0 ]; p++ ) {
1629                 if ( LDAP_DN_ESCAPE( p[ 0 ] ) ) {
1630                         p++;
1631                         if ( p[ 0 ] == '\0' ) {
1632                                 return( 1 );
1633                         }
1634
1635                         if ( !LDAP_DN_NEEDESCAPE( p[ 0 ] )
1636                                         && ( LDAP_DN_PEDANTIC & flags ) ) {
1637                                 return( 1 );
1638                         }
1639                         escapes++;
1640
1641                 } else if ( LDAP_DN_VALUE_END_V2( p[ 0 ] ) ) {
1642                         break;
1643                 }
1644
1645                 /*
1646                  * FIXME: can we accept anything else? I guess we need
1647                  * to stop if a value is not legal
1648                  */
1649         }
1650
1651         /* strip trailing (unescaped) spaces */
1652         for ( endPos = p; 
1653                         endPos > startPos + 1 && 
1654                         LDAP_DN_ASCII_SPACE( endPos[ -1 ] ) &&
1655                         !LDAP_DN_ESCAPE( endPos[ -2 ] );
1656                         endPos-- ) {
1657                 /* no op */
1658         }
1659
1660         *next = p;
1661         if ( flags & LDAP_DN_SKIP ) {
1662                 return( 0 );
1663         }
1664
1665         len = ( endPos ? endPos : p ) - startPos - escapes;
1666         val->bv_len = len;
1667         if ( escapes == 0 ) {
1668                 val->bv_val = LDAP_STRNDUP( startPos, len );
1669
1670         } else {
1671                 ber_len_t       s, d;
1672                 
1673                 val->bv_val = LDAP_MALLOC( len + 1 );
1674                 for ( s = 0, d = 0; d < len; ) {
1675                         if ( LDAP_DN_ESCAPE( startPos[ s ] ) ) {
1676                                 s++;
1677                         }
1678                         val->bv_val[ d++ ] = startPos[ s++ ];
1679                 }
1680                 val->bv_val[ d ] = '\0';
1681                 assert( strlen( val->bv_val ) == len );
1682         }
1683
1684         return( 0 );
1685 }
1686
1687 static int
1688 quotedIA52strval( const char *str, struct berval *val, const char **next, unsigned flags )
1689 {
1690         const char      *p, *startPos, *endPos = NULL;
1691         ber_len_t       len;
1692         unsigned        escapes = 0;
1693
1694         assert( str );
1695         assert( val );
1696         assert( next );
1697
1698         *next = NULL;
1699
1700         /* initial quote already eaten */
1701         for ( startPos = p = str; p[ 0 ]; p++ ) {
1702                 /* 
1703                  * According to RFC 1779, the quoted value can
1704                  * contain escaped as well as unescaped special values;
1705                  * as a consequence we tolerate escaped values 
1706                  * (e.g. '"\,"' -> '\,') and escape unescaped specials
1707                  * (e.g. '","' -> '\,').
1708                  */
1709                 if ( LDAP_DN_ESCAPE( p[ 0 ] ) ) {
1710                         if ( p[ 1 ] == '\0' ) {
1711                                 return( 1 );
1712                         }
1713                         p++;
1714
1715                         if ( !LDAP_DN_V2_PAIR( p[ 0 ] )
1716                                         && ( LDAP_DN_PEDANTIC & flags ) ) {
1717                                 /*
1718                                  * do we allow to escape normal chars?
1719                                  * LDAPv2 does not allow any mechanism 
1720                                  * for escaping chars with '\' and hex 
1721                                  * pair
1722                                  */
1723                                 return( 1 );
1724                         }
1725                         escapes++;
1726
1727                 } else if ( LDAP_DN_QUOTES( p[ 0 ] ) ) {
1728                         endPos = p;
1729                         /* eat closing quotes */
1730                         p++;
1731                         break;
1732                 }
1733
1734                 /*
1735                  * FIXME: can we accept anything else? I guess we need
1736                  * to stop if a value is not legal
1737                  */
1738         }
1739
1740         if ( endPos == NULL ) {
1741                 return( 1 );
1742         }
1743
1744         /* Strip trailing (unescaped) spaces */
1745         for ( ; p[ 0 ] && LDAP_DN_ASCII_SPACE( p[ 0 ] ); p++ ) {
1746                 /* no op */
1747         }
1748
1749         *next = p;
1750         if ( flags & LDAP_DN_SKIP ) {
1751                 return( 0 );
1752         }
1753
1754         len = endPos - startPos - escapes;
1755         assert( endPos >= startPos + escapes );
1756         val->bv_len = len;
1757         if ( escapes == 0 ) {
1758                 val->bv_val = LDAP_STRNDUP( startPos, len );
1759
1760         } else {
1761                 ber_len_t       s, d;
1762                 
1763                 val->bv_val = LDAP_MALLOC( len + 1 );
1764                 val->bv_len = len;
1765
1766                 for ( s = d = 0; d < len; ) {
1767                         if ( LDAP_DN_ESCAPE( str[ s ] ) ) {
1768                                 s++;
1769                         }
1770                         val->bv_val[ d++ ] = str[ s++ ];
1771                 }
1772                 val->bv_val[ d ] = '\0';
1773                 assert( strlen( val->bv_val ) == len );
1774         }
1775
1776         return( 0 );
1777 }
1778
1779 static int
1780 hexstr2bin( const char *str, char *c )
1781 {
1782         char    c1, c2;
1783
1784         assert( str );
1785         assert( c );
1786
1787         c1 = str[ 0 ];
1788         c2 = str[ 1 ];
1789
1790         if ( LDAP_DN_ASCII_DIGIT( c1 ) ) {
1791                 *c = c1 - '0';
1792
1793         } else {
1794                 if ( LDAP_DN_ASCII_UCASE_HEXALPHA( c1 ) ) {
1795                         *c = c1 - 'A' + 10;
1796                 } else {
1797                         assert( LDAP_DN_ASCII_LCASE_HEXALPHA( c1 ) );
1798                         *c = c1 - 'a' + 10;
1799                 }
1800         }
1801
1802         *c <<= 4;
1803
1804         if ( LDAP_DN_ASCII_DIGIT( c2 ) ) {
1805                 *c += c2 - '0';
1806                 
1807         } else {
1808                 if ( LDAP_DN_ASCII_UCASE_HEXALPHA( c2 ) ) {
1809                         *c += c2 - 'A' + 10;
1810                 } else {
1811                         assert( LDAP_DN_ASCII_LCASE_HEXALPHA( c2 ) );
1812                         *c += c2 - 'a' + 10;
1813                 }
1814         }
1815
1816         return( 0 );
1817 }
1818
1819 static int
1820 hexstr2binval( const char *str, struct berval *val, const char **next, unsigned flags )
1821 {
1822         const char      *p, *startPos, *endPos = NULL;
1823         ber_len_t       len;
1824         ber_len_t       s, d;
1825
1826         assert( str );
1827         assert( val );
1828         assert( next );
1829
1830         *next = NULL;
1831
1832         for ( startPos = p = str; p[ 0 ]; p += 2 ) {
1833                 switch ( LDAP_DN_FORMAT( flags ) ) {
1834                 case LDAP_DN_FORMAT_LDAPV3:
1835                         if ( LDAP_DN_VALUE_END( p[ 0 ] ) ) {
1836                                 goto end_of_value;
1837                         }
1838                         break;
1839
1840                 case LDAP_DN_FORMAT_LDAP:
1841                 case LDAP_DN_FORMAT_LDAPV2:
1842                         if ( LDAP_DN_VALUE_END_V2( p[ 0 ] ) ) {
1843                                 goto end_of_value;
1844                         }
1845                         break;
1846
1847                 case LDAP_DN_FORMAT_DCE:
1848                         if ( LDAP_DN_VALUE_END_DCE( p[ 0 ] ) ) {
1849                                 goto end_of_value;
1850                         }
1851                         break;
1852                 }
1853
1854                 if ( LDAP_DN_ASCII_SPACE( p[ 0 ] ) ) {
1855                         if ( flags & LDAP_DN_PEDANTIC ) {
1856                                 return( 1 );
1857                         }
1858                         endPos = p;
1859
1860                         for ( ; p[ 0 ]; p++ ) {
1861                                 switch ( LDAP_DN_FORMAT( flags ) ) {
1862                                 case LDAP_DN_FORMAT_LDAPV3:
1863                                         if ( LDAP_DN_VALUE_END( p[ 0 ] ) ) {
1864                                                 goto end_of_value;
1865                                         }
1866                                         break;
1867
1868                                 case LDAP_DN_FORMAT_LDAP:
1869                                 case LDAP_DN_FORMAT_LDAPV2:
1870                                         if ( LDAP_DN_VALUE_END_V2( p[ 0 ] ) ) {
1871                                                 goto end_of_value;
1872                                         }
1873                                         break;
1874
1875                                 case LDAP_DN_FORMAT_DCE:
1876                                         if ( LDAP_DN_VALUE_END_DCE( p[ 0 ] ) ) {
1877                                                 goto end_of_value;
1878                                         }
1879                                         break;
1880                                 }
1881                         }
1882                         break;
1883                 }
1884                 
1885                 if ( !LDAP_DN_HEXPAIR( p ) ) {
1886                         return( 1 );
1887                 }
1888         }
1889
1890 end_of_value:;
1891
1892         *next = p;
1893         if ( flags & LDAP_DN_SKIP ) {
1894                 return( 0 );
1895         }
1896
1897         len = ( ( endPos ? endPos : p ) - startPos ) / 2;
1898         /* must be even! */
1899         assert( 2 * len == (ber_len_t) (( endPos ? endPos : p ) - startPos ));
1900
1901         val->bv_len = len;
1902         val->bv_val = LDAP_MALLOC( len + 1 );
1903         if ( val->bv_val == NULL ) {
1904                 return( LDAP_NO_MEMORY );
1905         }
1906
1907         for ( s = 0, d = 0; d < len; s += 2, d++ ) {
1908                 char    c;
1909
1910                 hexstr2bin( &startPos[ s ], &c );
1911
1912                 val->bv_val[ d ] = c;
1913         }
1914
1915         val->bv_val[ d ] = '\0';
1916
1917         return( 0 );
1918 }
1919
1920 /*
1921  * convert a byte in a hexadecimal pair
1922  */
1923 static int
1924 byte2hexpair( const char *val, char *pair )
1925 {
1926         static const char       hexdig[] = "0123456789ABCDEF";
1927
1928         assert( val );
1929         assert( pair );
1930
1931         /* 
1932          * we assume the string has enough room for the hex encoding
1933          * of the value
1934          */
1935
1936         pair[ 0 ] = hexdig[ 0x0f & ( val[ 0 ] >> 4 ) ];
1937         pair[ 1 ] = hexdig[ 0x0f & val[ 0 ] ];
1938         
1939         return( 0 );
1940 }
1941
1942 /*
1943  * convert a binary value in hexadecimal pairs
1944  */
1945 static int
1946 binval2hexstr( struct berval *val, char *str )
1947 {
1948         ber_len_t       s, d;
1949
1950         assert( val );
1951         assert( str );
1952
1953         if ( val->bv_len == 0 ) {
1954                 return( 0 );
1955         }
1956
1957         /* 
1958          * we assume the string has enough room for the hex encoding
1959          * of the value
1960          */
1961
1962         for ( s = 0, d = 0; s < val->bv_len; s++, d += 2 ) {
1963                 byte2hexpair( &val->bv_val[ s ], &str[ d ] );
1964         }
1965         
1966         return( 0 );
1967 }
1968
1969 /*
1970  * Length of the string representation, accounting for escaped hex
1971  * of UTF-8 chars
1972  */
1973 static int
1974 strval2strlen( struct berval *val, unsigned flags, ber_len_t *len )
1975 {
1976         ber_len_t       l, cl = 1;
1977         char            *p;
1978         int             escaped_byte_len = LDAP_DN_IS_PRETTY( flags ) ? 1 : 3;
1979 #ifdef PRETTY_ESCAPE
1980         int             escaped_ascii_len = LDAP_DN_IS_PRETTY( flags ) ? 2 : 3;
1981 #endif /* PRETTY_ESCAPE */
1982         
1983         assert( val );
1984         assert( len );
1985
1986         *len = 0;
1987         if ( val->bv_len == 0 ) {
1988                 return( 0 );
1989         }
1990
1991         for ( l = 0, p = val->bv_val; p < val->bv_val + val->bv_len; p += cl ) {
1992
1993                 /* 
1994                  * escape '%x00' 
1995                  */
1996                 if ( p[ 0 ] == '\0' ) {
1997                         cl = 1;
1998                         l += 3;
1999                         continue;
2000                 }
2001
2002                 cl = LDAP_UTF8_CHARLEN2( p, cl );
2003                 if ( cl == 0 ) {
2004                         /* illegal utf-8 char! */
2005                         return( -1 );
2006
2007                 } else if ( cl > 1 ) {
2008                         ber_len_t cnt;
2009
2010                         for ( cnt = 1; cnt < cl; cnt++ ) {
2011                                 if ( ( p[ cnt ] & 0xc0 ) != 0x80 ) {
2012                                         return( -1 );
2013                                 }
2014                         }
2015                         l += escaped_byte_len * cl;
2016
2017                 } else if ( LDAP_DN_NEEDESCAPE( p[ 0 ] )
2018                                 || ( p == val->bv_val && LDAP_DN_NEEDESCAPE_LEAD( p[ 0 ] ) )
2019                                 || ( !p[ 1 ] && LDAP_DN_NEEDESCAPE_TRAIL( p[ 0 ] ) ) ) {
2020 #ifdef PRETTY_ESCAPE
2021 #if 0
2022                         if ( LDAP_DN_WILLESCAPE_HEX( flags, p[ 0 ] ) ) {
2023 #else
2024                         if ( LDAP_DN_WILLESCAPE_CHAR( p[ 0 ] ) ) {
2025 #endif
2026
2027                                 /* 
2028                                  * there might be some chars we want 
2029                                  * to escape in form of a couple 
2030                                  * of hexdigits for optimization purposes
2031                                  */
2032                                 l += 3;
2033
2034                         } else {
2035                                 l += escaped_ascii_len;
2036                         }
2037 #else /* ! PRETTY_ESCAPE */
2038                         l += 3;
2039 #endif /* ! PRETTY_ESCAPE */
2040
2041                 } else {
2042                         l++;
2043                 }
2044         }
2045
2046         *len = l;
2047
2048         return( 0 );
2049 }
2050
2051 /*
2052  * convert to string representation, escaping with hex the UTF-8 stuff;
2053  * assume the destination has enough room for escaping
2054  */
2055 static int
2056 strval2str( struct berval *val, char *str, unsigned flags, ber_len_t *len )
2057 {
2058         ber_len_t       s, d, end;
2059
2060         assert( val );
2061         assert( str );
2062         assert( len );
2063
2064         if ( val->bv_len == 0 ) {
2065                 *len = 0;
2066                 return( 0 );
2067         }
2068
2069         /* 
2070          * we assume the string has enough room for the hex encoding
2071          * of the value
2072          */
2073         for ( s = 0, d = 0, end = val->bv_len - 1; s < val->bv_len; ) {
2074                 ber_len_t       cl;
2075
2076                 /* 
2077                  * escape '%x00' 
2078                  */
2079                 if ( val->bv_val[ s ] == '\0' ) {
2080                         cl = 1;
2081                         str[ d++ ] = '\\';
2082                         str[ d++ ] = '0';
2083                         str[ d++ ] = '0';
2084                         s++;
2085                         continue;
2086                 }
2087                 
2088                 /*
2089                  * The length was checked in strval2strlen();
2090                  * LDAP_UTF8_CHARLEN() should suffice
2091                  */
2092                 cl = LDAP_UTF8_CHARLEN2( &val->bv_val[ s ], cl );
2093                 assert( cl > 0 );
2094                 
2095                 /* 
2096                  * there might be some chars we want to escape in form
2097                  * of a couple of hexdigits for optimization purposes
2098                  */
2099                 if ( ( cl > 1 && !LDAP_DN_IS_PRETTY( flags ) ) 
2100 #ifdef PRETTY_ESCAPE
2101 #if 0
2102                                 || LDAP_DN_WILLESCAPE_HEX( flags, val->bv_val[ s ] ) 
2103 #else
2104                                 || LDAP_DN_WILLESCAPE_CHAR( val->bv_val[ s ] ) 
2105 #endif
2106 #else /* ! PRETTY_ESCAPE */
2107                                 || LDAP_DN_NEEDESCAPE( val->bv_val[ s ] )
2108                                 || ( d == 0 && LDAP_DN_NEEDESCAPE_LEAD( val->bv_val[ s ] ) )
2109                                 || ( s == end && LDAP_DN_NEEDESCAPE_TRAIL( val->bv_val[ s ] ) )
2110
2111 #endif /* ! PRETTY_ESCAPE */
2112                                 ) {
2113                         for ( ; cl--; ) {
2114                                 str[ d++ ] = '\\';
2115                                 byte2hexpair( &val->bv_val[ s ], &str[ d ] );
2116                                 s++;
2117                                 d += 2;
2118                         }
2119
2120                 } else if ( cl > 1 ) {
2121                         for ( ; cl--; ) {
2122                                 str[ d++ ] = val->bv_val[ s++ ];
2123                         }
2124
2125                 } else {
2126 #ifdef PRETTY_ESCAPE
2127                         if ( LDAP_DN_NEEDESCAPE( val->bv_val[ s ] )
2128                                         || ( d == 0 && LDAP_DN_NEEDESCAPE_LEAD( val->bv_val[ s ] ) )
2129                                         || ( s == end && LDAP_DN_NEEDESCAPE_TRAIL( val->bv_val[ s ] ) ) ) {
2130                                 str[ d++ ] = '\\';
2131                                 if ( !LDAP_DN_IS_PRETTY( flags ) ) {
2132                                         byte2hexpair( &val->bv_val[ s ], &str[ d ] );
2133                                         s++;
2134                                         d += 2;
2135                                         continue;
2136                                 }
2137                         }
2138 #endif /* PRETTY_ESCAPE */
2139                         str[ d++ ] = val->bv_val[ s++ ];
2140                 }
2141         }
2142
2143         *len = d;
2144         
2145         return( 0 );
2146 }
2147
2148 /*
2149  * Length of the IA5 string representation (no UTF-8 allowed)
2150  */
2151 static int
2152 strval2IA5strlen( struct berval *val, unsigned flags, ber_len_t *len )
2153 {
2154         ber_len_t       l;
2155         char            *p;
2156
2157         assert( val );
2158         assert( len );
2159
2160         *len = 0;
2161         if ( val->bv_len == 0 ) {
2162                 return( 0 );
2163         }
2164
2165         if ( flags & LDAP_AVA_NONPRINTABLE ) {
2166                 /*
2167                  * Turn value into a binary encoded BER
2168                  */
2169                 return( -1 );
2170
2171         } else {
2172                 for ( l = 0, p = val->bv_val; p[ 0 ]; p++ ) {
2173                         if ( LDAP_DN_NEEDESCAPE( p[ 0 ] )
2174                                         || ( p == val->bv_val && LDAP_DN_NEEDESCAPE_LEAD( p[ 0 ] ) )
2175                                         || ( !p[ 1 ] && LDAP_DN_NEEDESCAPE_TRAIL( p[ 0 ] ) ) ) {
2176                                 l += 2;
2177
2178                         } else {
2179                                 l++;
2180                         }
2181                 }
2182         }
2183
2184         *len = l;
2185         
2186         return( 0 );
2187 }
2188
2189 /*
2190  * convert to string representation (np UTF-8)
2191  * assume the destination has enough room for escaping
2192  */
2193 static int
2194 strval2IA5str( struct berval *val, char *str, unsigned flags, ber_len_t *len )
2195 {
2196         ber_len_t       s, d, end;
2197
2198         assert( val );
2199         assert( str );
2200         assert( len );
2201
2202         if ( val->bv_len == 0 ) {
2203                 *len = 0;
2204                 return( 0 );
2205         }
2206
2207         if ( flags & LDAP_AVA_NONPRINTABLE ) {
2208                 /*
2209                  * Turn value into a binary encoded BER
2210                  */
2211                 *len = 0;
2212                 return( -1 );
2213
2214         } else {
2215                 /* 
2216                  * we assume the string has enough room for the hex encoding
2217                  * of the value
2218                  */
2219
2220                 for ( s = 0, d = 0, end = val->bv_len - 1; s < val->bv_len; ) {
2221                         if ( LDAP_DN_NEEDESCAPE( val->bv_val[ s ] )
2222                                         || ( s == 0 && LDAP_DN_NEEDESCAPE_LEAD( val->bv_val[ s ] ) )
2223                                         || ( s == end && LDAP_DN_NEEDESCAPE_TRAIL( val->bv_val[ s ] ) ) ) {
2224                                 str[ d++ ] = '\\';
2225                         }
2226                         str[ d++ ] = val->bv_val[ s++ ];
2227                 }
2228         }
2229
2230         *len = d;
2231         
2232         return( 0 );
2233 }
2234
2235 /*
2236  * Length of the (supposedly) DCE string representation, 
2237  * accounting for escaped hex of UTF-8 chars
2238  */
2239 static int
2240 strval2DCEstrlen( struct berval *val, unsigned flags, ber_len_t *len )
2241 {
2242         ber_len_t       l;
2243         char            *p;
2244
2245         assert( val );
2246         assert( len );
2247
2248         *len = 0;
2249         if ( val->bv_len == 0 ) {
2250                 return( 0 );
2251         }
2252
2253         if ( flags & LDAP_AVA_NONPRINTABLE ) {
2254                 /* 
2255                  * FIXME: Turn the value into a binary encoded BER?
2256                  */
2257                 return( -1 );
2258                 
2259         } else {
2260                 for ( l = 0, p = val->bv_val; p[ 0 ]; p++ ) {
2261                         if ( LDAP_DN_NEEDESCAPE_DCE( p[ 0 ] ) ) {
2262                                 l += 2;
2263
2264                         } else {
2265                                 l++;
2266                         }
2267                 }
2268         }
2269
2270         *len = l;
2271
2272         return( 0 );
2273 }
2274
2275 /*
2276  * convert to (supposedly) DCE string representation, 
2277  * escaping with hex the UTF-8 stuff;
2278  * assume the destination has enough room for escaping
2279  */
2280 static int
2281 strval2DCEstr( struct berval *val, char *str, unsigned flags, ber_len_t *len )
2282 {
2283         ber_len_t       s, d;
2284
2285         assert( val );
2286         assert( str );
2287         assert( len );
2288
2289         if ( val->bv_len == 0 ) {
2290                 *len = 0;
2291                 return( 0 );
2292         }
2293
2294         if ( flags & LDAP_AVA_NONPRINTABLE ) {
2295                 /*
2296                  * FIXME: Turn the value into a binary encoded BER?
2297                  */
2298                 *len = 0;
2299                 return( -1 );
2300                 
2301         } else {
2302
2303                 /* 
2304                  * we assume the string has enough room for the hex encoding
2305                  * of the value
2306                  */
2307
2308                 for ( s = 0, d = 0; s < val->bv_len; ) {
2309                         if ( LDAP_DN_NEEDESCAPE_DCE( val->bv_val[ s ] ) ) {
2310                                 str[ d++ ] = '\\';
2311                         }
2312                         str[ d++ ] = val->bv_val[ s++ ];
2313                 }
2314         }
2315
2316         *len = d;
2317         
2318         return( 0 );
2319 }
2320
2321 /*
2322  * Length of the (supposedly) AD canonical string representation, 
2323  * accounting for escaped hex of UTF-8 chars
2324  */
2325 static int
2326 strval2ADstrlen( struct berval *val, unsigned flags, ber_len_t *len )
2327 {
2328         ber_len_t       l;
2329         char            *p;
2330
2331         assert( val );
2332         assert( len );
2333
2334         *len = 0;
2335         if ( val->bv_len == 0 ) {
2336                 return( 0 );
2337         }
2338
2339         if ( flags & LDAP_AVA_NONPRINTABLE ) {
2340                 /* 
2341                  * FIXME: Turn the value into a binary encoded BER?
2342                  */
2343                 return( -1 );
2344                 
2345         } else {
2346                 for ( l = 0, p = val->bv_val; p[ 0 ]; p++ ) {
2347                         if ( LDAP_DN_NEEDESCAPE_AD( p[ 0 ] ) ) {
2348                                 l += 2;
2349
2350                         } else {
2351                                 l++;
2352                         }
2353                 }
2354         }
2355
2356         *len = l;
2357         
2358         return( 0 );
2359 }
2360
2361 /*
2362  * convert to (supposedly) AD string representation, 
2363  * escaping with hex the UTF-8 stuff;
2364  * assume the destination has enough room for escaping
2365  */
2366 static int
2367 strval2ADstr( struct berval *val, char *str, unsigned flags, ber_len_t *len )
2368 {
2369         ber_len_t       s, d;
2370
2371         assert( val );
2372         assert( str );
2373         assert( len );
2374
2375         if ( val->bv_len == 0 ) {
2376                 *len = 0;
2377                 return( 0 );
2378         }
2379
2380         if ( flags & LDAP_AVA_NONPRINTABLE ) {
2381                 /*
2382                  * FIXME: Turn the value into a binary encoded BER?
2383                  */
2384                 *len = 0;
2385                 return( -1 );
2386                 
2387         } else {
2388
2389                 /* 
2390                  * we assume the string has enough room for the hex encoding
2391                  * of the value
2392                  */
2393
2394                 for ( s = 0, d = 0; s < val->bv_len; ) {
2395                         if ( LDAP_DN_NEEDESCAPE_AD( val->bv_val[ s ] ) ) {
2396                                 str[ d++ ] = '\\';
2397                         }
2398                         str[ d++ ] = val->bv_val[ s++ ];
2399                 }
2400         }
2401
2402         *len = d;
2403         
2404         return( 0 );
2405 }
2406
2407 /*
2408  * If the DN is terminated by single-AVA RDNs with attribute type of "dc",
2409  * the first part of the AD representation of the DN is written in DNS
2410  * form, i.e. dot separated domain name components (as suggested 
2411  * by Luke Howard, http://www.padl.com/~lukeh)
2412  */
2413 static int
2414 dn2domain( LDAPDN *dn, struct berval *bv, int pos, int *iRDN )
2415 {
2416         int             i;
2417         int             domain = 0, first = 1;
2418         ber_len_t       l = 1; /* we move the null also */
2419         char            *str;
2420
2421         /* we are guaranteed there's enough memory in str */
2422
2423         /* sanity */
2424         assert( dn );
2425         assert( bv );
2426         assert( iRDN );
2427         assert( *iRDN >= 0 );
2428
2429         str = bv->bv_val + pos;
2430
2431         for ( i = *iRDN; i >= 0; i-- ) {
2432                 LDAPRDN         *rdn;
2433                 LDAPAVA         *ava;
2434
2435                 assert( dn[ 0 ][ i ] );
2436                 rdn = dn[ 0 ][ i ];
2437
2438                 assert( rdn[ 0 ][ 0 ] );
2439                 ava = rdn[ 0 ][ 0 ];
2440
2441                 if ( !LDAP_DN_IS_RDN_DC( rdn ) ) {
2442                         break;
2443                 }
2444
2445                 domain = 1;
2446                 
2447                 if ( first ) {
2448                         first = 0;
2449                         AC_MEMCPY( str, ava->la_value.bv_val, 
2450                                         ava->la_value.bv_len + 1);
2451                         l += ava->la_value.bv_len;
2452
2453                 } else {
2454                         AC_MEMCPY( str + ava->la_value.bv_len + 1, bv->bv_val + pos, l);
2455                         AC_MEMCPY( str, ava->la_value.bv_val, 
2456                                         ava->la_value.bv_len );
2457                         str[ ava->la_value.bv_len ] = '.';
2458                         l += ava->la_value.bv_len + 1;
2459                 }
2460         }
2461
2462         *iRDN = i;
2463         bv->bv_len = pos + l - 1;
2464
2465         return( domain );
2466 }
2467
2468 static int
2469 rdn2strlen( LDAPRDN *rdn, unsigned flags, ber_len_t *len,
2470          int ( *s2l )( struct berval *v, unsigned f, ber_len_t *l ) )
2471 {
2472         int             iAVA;
2473         ber_len_t       l = 0;
2474
2475         *len = 0;
2476
2477         for ( iAVA = 0; rdn[ 0 ][ iAVA ]; iAVA++ ) {
2478                 LDAPAVA         *ava = rdn[ 0 ][ iAVA ];
2479
2480                 /* len(type) + '=' + '+' | ',' */
2481                 l += ava->la_attr.bv_len + 2;
2482
2483                 if ( ava->la_flags & LDAP_AVA_BINARY ) {
2484                         /* octothorpe + twice the length */
2485                         l += 1 + 2 * ava->la_value.bv_len;
2486
2487                 } else {
2488                         ber_len_t       vl;
2489                         unsigned        f = flags | ava->la_flags;
2490                         
2491                         if ( ( *s2l )( &ava->la_value, f, &vl ) ) {
2492                                 return( -1 );
2493                         }
2494                         l += vl;
2495                 }
2496         }
2497         
2498         *len = l;
2499         
2500         return( 0 );
2501 }
2502
2503 static int
2504 rdn2str( LDAPRDN *rdn, char *str, unsigned flags, ber_len_t *len,
2505         int ( *s2s ) ( struct berval *v, char * s, unsigned f, ber_len_t *l ) )
2506 {
2507         int             iAVA;
2508         ber_len_t       l = 0;
2509
2510         for ( iAVA = 0; rdn[ 0 ][ iAVA ]; iAVA++ ) {
2511                 LDAPAVA         *ava = rdn[ 0 ][ iAVA ];
2512
2513                 AC_MEMCPY( &str[ l ], ava->la_attr.bv_val, 
2514                                 ava->la_attr.bv_len );
2515                 l += ava->la_attr.bv_len;
2516
2517                 str[ l++ ] = '=';
2518
2519                 if ( ava->la_flags & LDAP_AVA_BINARY ) {
2520                         str[ l++ ] = '#';
2521                         if ( binval2hexstr( &ava->la_value, &str[ l ] ) ) {
2522                                 return( -1 );
2523                         }
2524                         l += 2 * ava->la_value.bv_len;
2525
2526                 } else {
2527                         ber_len_t       vl;
2528                         unsigned        f = flags | ava->la_flags;
2529
2530                         if ( ( *s2s )( &ava->la_value, &str[ l ], f, &vl ) ) {
2531                                 return( -1 );
2532                         }
2533                         l += vl;
2534                 }
2535                 str[ l++ ] = ( rdn[ 0 ][ iAVA + 1 ] ? '+' : ',' );
2536         }
2537
2538         *len = l;
2539
2540         return( 0 );
2541 }
2542
2543 static int
2544 rdn2DCEstrlen( LDAPRDN *rdn, unsigned flags, ber_len_t *len )
2545 {
2546         int             iAVA;
2547         ber_len_t       l = 0;
2548
2549         *len = 0;
2550
2551         for ( iAVA = 0; rdn[ 0 ][ iAVA ]; iAVA++ ) {
2552                 LDAPAVA         *ava = rdn[ 0 ][ iAVA ];
2553
2554                 /* len(type) + '=' + ',' | '/' */
2555                 l += ava->la_attr.bv_len + 2;
2556
2557                 switch ( ava->la_flags ) {
2558                 case LDAP_AVA_BINARY:
2559                         /* octothorpe + twice the length */
2560                         l += 1 + 2 * ava->la_value.bv_len;
2561                         break;
2562
2563                 case LDAP_AVA_STRING: {
2564                         ber_len_t       vl;
2565                         unsigned        f = flags | ava->la_flags;
2566                         
2567                         if ( strval2DCEstrlen( &ava->la_value, f, &vl ) ) {
2568                                 return( -1 );
2569                         }
2570                         l += vl;
2571                         break;
2572                 }
2573
2574                 default:
2575                         return( -1 );
2576                 }
2577         }
2578         
2579         *len = l;
2580         
2581         return( 0 );
2582 }
2583
2584 static int
2585 rdn2DCEstr( LDAPRDN *rdn, char *str, unsigned flags, ber_len_t *len, int first )
2586 {
2587         int             iAVA;
2588         ber_len_t       l = 0;
2589
2590         for ( iAVA = 0; rdn[ 0 ][ iAVA ]; iAVA++ ) {
2591                 LDAPAVA         *ava = rdn[ 0 ][ iAVA ];
2592
2593                 if ( first ) {
2594                         first = 0;
2595                 } else {
2596                         str[ l++ ] = ( iAVA ? ',' : '/' );
2597                 }
2598
2599                 AC_MEMCPY( &str[ l ], ava->la_attr.bv_val, 
2600                                 ava->la_attr.bv_len );
2601                 l += ava->la_attr.bv_len;
2602
2603                 str[ l++ ] = '=';
2604
2605                 switch ( ava->la_flags ) {
2606                         case LDAP_AVA_BINARY:
2607                         str[ l++ ] = '#';
2608                         if ( binval2hexstr( &ava->la_value, &str[ l ] ) ) {
2609                                 return( -1 );
2610                         }
2611                         l += 2 * ava->la_value.bv_len;
2612                         break;
2613
2614                 case LDAP_AVA_STRING: {
2615                         ber_len_t       vl;
2616                         unsigned        f = flags | ava->la_flags;
2617
2618                         if ( strval2DCEstr( &ava->la_value, &str[ l ], f, &vl ) ) {
2619                                 return( -1 );
2620                         }
2621                         l += vl;
2622                         break;
2623                 }
2624                                       
2625                 default:
2626                         return( -1 );
2627                 }
2628         }
2629
2630         *len = l;
2631
2632         return( 0 );
2633 }
2634
2635 static int
2636 rdn2UFNstrlen( LDAPRDN *rdn, unsigned flags, ber_len_t *len )
2637 {
2638         int             iAVA;
2639         ber_len_t       l = 0;
2640
2641         assert( rdn );
2642         assert( len );
2643
2644         *len = 0;
2645
2646         for ( iAVA = 0; rdn[ 0 ][ iAVA ]; iAVA++ ) {
2647                 LDAPAVA         *ava = rdn[ 0 ][ iAVA ];
2648
2649                 /* ' + ' | ', ' */
2650                 l += ( rdn[ 0 ][ iAVA + 1 ] ? 3 : 2 );
2651
2652                 /* FIXME: are binary values allowed in UFN? */
2653                 if ( ava->la_flags & LDAP_AVA_BINARY ) {
2654                         /* octothorpe + twice the value */
2655                         l += 1 + 2 * ava->la_value.bv_len;
2656
2657                 } else {
2658                         ber_len_t       vl;
2659                         unsigned        f = flags | ava->la_flags;
2660
2661                         if ( strval2strlen( &ava->la_value, f, &vl ) ) {
2662                                 return( -1 );
2663                         }
2664                         l += vl;
2665                 }
2666         }
2667         
2668         *len = l;
2669         
2670         return( 0 );
2671 }
2672
2673 static int
2674 rdn2UFNstr( LDAPRDN *rdn, char *str, unsigned flags, ber_len_t *len )
2675 {
2676         int             iAVA;
2677         ber_len_t       l = 0;
2678
2679         for ( iAVA = 0; rdn[ 0 ][ iAVA ]; iAVA++ ) {
2680                 LDAPAVA         *ava = rdn[ 0 ][ iAVA ];
2681
2682                 if ( ava->la_flags & LDAP_AVA_BINARY ) {
2683                         str[ l++ ] = '#';
2684                         if ( binval2hexstr( &ava->la_value, &str[ l ] ) ) {
2685                                 return( -1 );
2686                         }
2687                         l += 2 * ava->la_value.bv_len;
2688                         
2689                 } else {
2690                         ber_len_t       vl;
2691                         unsigned        f = flags | ava->la_flags;
2692                         
2693                         if ( strval2str( &ava->la_value, &str[ l ], f, &vl ) ) {
2694                                 return( -1 );
2695                         }
2696                         l += vl;
2697                 }
2698
2699                 if ( rdn[ 0 ][ iAVA + 1 ]) {
2700                         AC_MEMCPY( &str[ l ], " + ", 3 );
2701                         l += 3;
2702
2703                 } else {
2704                         AC_MEMCPY( &str[ l ], ", ", 2 );
2705                         l += 2;
2706                 }
2707         }
2708
2709         *len = l;
2710
2711         return( 0 );
2712 }
2713
2714 static int
2715 rdn2ADstrlen( LDAPRDN *rdn, unsigned flags, ber_len_t *len )
2716 {
2717         int             iAVA;
2718         ber_len_t       l = 0;
2719
2720         assert( rdn );
2721         assert( len );
2722
2723         *len = 0;
2724
2725         for ( iAVA = 0; rdn[ 0 ][ iAVA ]; iAVA++ ) {
2726                 LDAPAVA         *ava = rdn[ 0 ][ iAVA ];
2727
2728                 /* ',' | '/' */
2729                 l++;
2730
2731                 /* FIXME: are binary values allowed in UFN? */
2732                 switch ( ava->la_flags ) {
2733                 case LDAP_AVA_BINARY:
2734                         /* octothorpe + twice the value */
2735                         l += 1 + 2 * ava->la_value.bv_len;
2736                         break;
2737
2738                 case LDAP_AVA_STRING: {
2739                         ber_len_t       vl;
2740                         unsigned        f = flags | ava->la_flags;
2741
2742                         if ( strval2ADstrlen( &ava->la_value, f, &vl ) ) {
2743                                 return( -1 );
2744                         }
2745                         l += vl;
2746                         break;
2747                 }
2748
2749                 default:
2750                         return( -1 );
2751                 }
2752         }
2753         
2754         *len = l;
2755         
2756         return( 0 );
2757 }
2758
2759 static int
2760 rdn2ADstr( LDAPRDN *rdn, char *str, unsigned flags, ber_len_t *len, int first )
2761 {
2762         int             iAVA;
2763         ber_len_t       l = 0;
2764
2765         for ( iAVA = 0; rdn[ 0 ][ iAVA ]; iAVA++ ) {
2766                 LDAPAVA         *ava = rdn[ 0 ][ iAVA ];
2767
2768                 if ( first ) {
2769                         first = 0;
2770                 } else {
2771                         str[ l++ ] = ( iAVA ? ',' : '/' );
2772                 }
2773
2774                 switch ( ava->la_flags ) {
2775                 case LDAP_AVA_BINARY:
2776                         str[ l++ ] = '#';
2777                         if ( binval2hexstr( &ava->la_value, &str[ l ] ) ) {
2778                                 return( -1 );
2779                         }
2780                         l += 2 * ava->la_value.bv_len;
2781                         break;
2782                         
2783                 case LDAP_AVA_STRING: {
2784                         ber_len_t       vl;
2785                         unsigned        f = flags | ava->la_flags;
2786                         
2787                         if ( strval2ADstr( &ava->la_value, &str[ l ], f, &vl ) ) {
2788                                 return( -1 );
2789                         }
2790                         l += vl;
2791                         break;
2792                 }
2793
2794                 default:
2795                         return( -1 );
2796                 }
2797         }
2798
2799         *len = l;
2800
2801         return( 0 );
2802 }
2803
2804 /*
2805  * ldap_rdn2str
2806  *
2807  * Returns in str a string representation of rdn based on flags.
2808  * There is some duplication of code between this and ldap_dn2str;
2809  * this is wanted to reduce the allocation of temporary buffers.
2810  */
2811 int
2812 ldap_rdn2str( LDAPRDN *rdn, char **str, unsigned flags )
2813 {
2814         struct berval bv;
2815         int rc;
2816
2817         assert( str );
2818
2819         if((flags & LDAP_DN_FORMAT_MASK) == LDAP_DN_FORMAT_LBER) {
2820                 return LDAP_PARAM_ERROR;
2821         }
2822
2823         rc = ldap_rdn2bv( rdn, &bv, flags );
2824         *str = bv.bv_val;
2825         return rc;
2826 }
2827
2828 int
2829 ldap_rdn2bv( LDAPRDN *rdn, struct berval *bv, unsigned flags )
2830 {
2831         int             rc, back;
2832         ber_len_t       l;
2833         
2834         assert( bv );
2835
2836         bv->bv_len = 0;
2837         bv->bv_val = NULL;
2838
2839         if ( rdn == NULL ) {
2840                 bv->bv_val = LDAP_STRDUP( "" );
2841                 return( LDAP_SUCCESS );
2842         }
2843
2844         /*
2845          * This routine wastes "back" bytes at the end of the string
2846          */
2847
2848         switch ( LDAP_DN_FORMAT( flags ) ) {
2849         case LDAP_DN_FORMAT_LDAPV3:
2850                 if ( rdn2strlen( rdn, flags, &l, strval2strlen ) ) {
2851                         return LDAP_DECODING_ERROR;
2852                 }
2853                 break;
2854
2855         case LDAP_DN_FORMAT_LDAPV2:
2856                 if ( rdn2strlen( rdn, flags, &l, strval2IA5strlen ) ) {
2857                         return LDAP_DECODING_ERROR;
2858                 }
2859                 break;
2860
2861         case LDAP_DN_FORMAT_UFN:
2862                 if ( rdn2UFNstrlen( rdn, flags, &l ) ) {
2863                         return LDAP_DECODING_ERROR;
2864                 }
2865                 break;
2866
2867         case LDAP_DN_FORMAT_DCE:
2868                 if ( rdn2DCEstrlen( rdn, flags, &l ) ) {
2869                         return LDAP_DECODING_ERROR;
2870                 }
2871                 break;
2872
2873         case LDAP_DN_FORMAT_AD_CANONICAL:
2874                 if ( rdn2ADstrlen( rdn, flags, &l ) ) {
2875                         return LDAP_DECODING_ERROR;
2876                 }
2877                 break;
2878
2879         default:
2880                 return LDAP_PARAM_ERROR;
2881         }
2882
2883         bv->bv_val = LDAP_MALLOC( l + 1 );
2884
2885         switch ( LDAP_DN_FORMAT( flags ) ) {
2886         case LDAP_DN_FORMAT_LDAPV3:
2887                 rc = rdn2str( rdn, bv->bv_val, flags, &l, strval2str );
2888                 back = 1;
2889                 break;
2890
2891         case LDAP_DN_FORMAT_LDAPV2:
2892                 rc = rdn2str( rdn, bv->bv_val, flags, &l, strval2IA5str );
2893                 back = 1;
2894                 break;
2895
2896         case LDAP_DN_FORMAT_UFN:
2897                 rc = rdn2UFNstr( rdn, bv->bv_val, flags, &l );
2898                 back = 2;
2899                 break;
2900
2901         case LDAP_DN_FORMAT_DCE:
2902                 rc = rdn2DCEstr( rdn, bv->bv_val, flags, &l, 1 );
2903                 back = 0;
2904                 break;
2905
2906         case LDAP_DN_FORMAT_AD_CANONICAL:
2907                 rc = rdn2ADstr( rdn, bv->bv_val, flags, &l, 1 );
2908                 back = 0;
2909                 break;
2910
2911         default:
2912                 /* need at least one of the previous */
2913                 return LDAP_PARAM_ERROR;
2914         }
2915
2916         if ( rc ) {
2917                 ldap_memfree( bv->bv_val );
2918                 return rc;
2919         }
2920
2921         bv->bv_len = l - back;
2922         bv->bv_val[ bv->bv_len ] = '\0';
2923
2924         return LDAP_SUCCESS;
2925 }
2926
2927 /*
2928  * Very bulk implementation; many optimizations can be performed
2929  *   - a NULL dn results in an empty string ""
2930  * 
2931  * FIXME: doubts
2932  *   a) what do we do if a UTF-8 string must be converted in LDAPv2?
2933  *      we must encode it in binary form ('#' + HEXPAIRs)
2934  *   b) does DCE/AD support UTF-8?
2935  *      no clue; don't think so.
2936  *   c) what do we do when binary values must be converted in UTF/DCE/AD?
2937  *      use binary encoded BER
2938  */ 
2939 int ldap_dn2str( LDAPDN *dn, char **str, unsigned flags )
2940 {
2941         struct berval bv;
2942         int rc;
2943
2944         assert( str );
2945
2946         if((flags & LDAP_DN_FORMAT_MASK) == LDAP_DN_FORMAT_LBER) {
2947                 return LDAP_PARAM_ERROR;
2948         }
2949         
2950         rc = ldap_dn2bv( dn, &bv, flags );
2951         *str = bv.bv_val;
2952         return rc;
2953 }
2954
2955 int ldap_dn2bv( LDAPDN *dn, struct berval *bv, unsigned flags )
2956 {
2957         int             iRDN;
2958         int             rc = LDAP_ENCODING_ERROR;
2959         ber_len_t       len, l;
2960
2961         /* stringifying helpers for LDAPv3/LDAPv2 */
2962         int ( *sv2l ) ( struct berval *v, unsigned f, ber_len_t *l );
2963         int ( *sv2s ) ( struct berval *v, char *s, unsigned f, ber_len_t *l );
2964
2965         assert( bv );
2966         bv->bv_len = 0;
2967         bv->bv_val = NULL;
2968
2969 #ifdef NEW_LOGGING
2970         LDAP_LOG (( "getdn", LDAP_LEVEL_ARGS, "=> ldap_dn2bv(%u)\n%s%s", 
2971                 flags, "", "" ));
2972 #else
2973         Debug( LDAP_DEBUG_TRACE, "=> ldap_dn2bv(%u)\n%s%s", flags, "", "" );
2974 #endif
2975
2976         /* 
2977          * a null dn means an empty dn string 
2978          * FIXME: better raise an error?
2979          */
2980         if ( dn == NULL ) {
2981                 bv->bv_val = LDAP_STRDUP( "" );
2982                 return( LDAP_SUCCESS );
2983         }
2984
2985         switch ( LDAP_DN_FORMAT( flags ) ) {
2986         case LDAP_DN_FORMAT_LDAPV3:
2987                 sv2l = strval2strlen;
2988                 sv2s = strval2str;
2989
2990                 if( 0 ) {
2991         case LDAP_DN_FORMAT_LDAPV2:
2992                         sv2l = strval2IA5strlen;
2993                         sv2s = strval2IA5str;
2994                 }
2995
2996                 for ( iRDN = 0, len = 0; dn[ 0 ][ iRDN ]; iRDN++ ) {
2997                         ber_len_t       rdnl;
2998                         LDAPRDN         *rdn = dn[ 0 ][ iRDN ];
2999                         
3000                         if ( rdn2strlen( rdn, flags, &rdnl, sv2l ) ) {
3001                                 goto return_results;
3002                         }
3003
3004                         len += rdnl;
3005                 }
3006
3007                 if ( ( bv->bv_val = LDAP_MALLOC( len + 1 ) ) == NULL ) {
3008                         rc = LDAP_NO_MEMORY;
3009                         break;
3010                 }
3011
3012                 for ( l = 0, iRDN = 0; dn[ 0 ][ iRDN ]; iRDN++ ) {
3013                         ber_len_t       rdnl;
3014                         LDAPRDN         *rdn = dn[ 0 ][ iRDN ];
3015                         
3016                         if ( rdn2str( rdn, &bv->bv_val[ l ], flags, 
3017                                         &rdnl, sv2s ) ) {
3018                                 LDAP_FREE( bv->bv_val );
3019                                 bv->bv_val = NULL;
3020                                 goto return_results;
3021                         }
3022                         l += rdnl;
3023                 }
3024
3025                 assert( l == len );
3026
3027                 /* 
3028                  * trim the last ',' (the allocated memory 
3029                  * is one byte longer than required)
3030                  */
3031                 bv->bv_len = len - 1;
3032                 bv->bv_val[ bv->bv_len ] = '\0';
3033
3034                 rc = LDAP_SUCCESS;
3035                 break;
3036
3037         case LDAP_DN_FORMAT_UFN: {
3038                 /*
3039                  * FIXME: quoting from RFC 1781:
3040                  *
3041    To take a distinguished name, and generate a name of this format with
3042    attribute types omitted, the following steps are followed.
3043
3044     1.  If the first attribute is of type CommonName, the type may be
3045         omitted.
3046
3047     2.  If the last attribute is of type Country, the type may be
3048         omitted.
3049
3050     3.  If the last attribute is of type Country, the last
3051         Organisation attribute may have the type omitted.
3052
3053     4.  All attributes of type OrganisationalUnit may have the type
3054         omitted, unless they are after an Organisation attribute or
3055         the first attribute is of type OrganisationalUnit.
3056
3057          * this should be the pedantic implementation.
3058                  *
3059                  * Here the standard implementation reflects
3060                  * the one historically provided by OpenLDAP
3061                  * (and UMIch, I presume), with the variant
3062                  * of spaces and plusses (' + ') separating 
3063                  * rdn components.
3064                  * 
3065                  * A non-standard but nice implementation could
3066                  * be to turn the  final "dc" attributes into a 
3067                  * dot-separated domain.
3068                  *
3069                  * Other improvements could involve the use of
3070                  * friendly country names and so.
3071                  */
3072 #ifdef DC_IN_UFN
3073                 int     leftmost_dc = -1;
3074                 int     last_iRDN = -1;
3075 #endif /* DC_IN_UFN */
3076
3077                 for ( iRDN = 0, len = 0; dn[ 0 ][ iRDN ]; iRDN++ ) {
3078                         ber_len_t       rdnl;
3079                         LDAPRDN         *rdn = dn[ 0 ][ iRDN ];
3080                         
3081                         if ( rdn2UFNstrlen( rdn, flags, &rdnl ) ) {
3082                                 goto return_results;
3083                         }
3084                         len += rdnl;
3085
3086 #ifdef DC_IN_UFN
3087                         if ( LDAP_DN_IS_RDN_DC( rdn ) ) {
3088                                 if ( leftmost_dc == -1 ) {
3089                                         leftmost_dc = iRDN;
3090                                 }
3091                         } else {
3092                                 leftmost_dc = -1;
3093                         }
3094 #endif /* DC_IN_UFN */
3095                 }
3096
3097                 if ( ( bv->bv_val = LDAP_MALLOC( len + 1 ) ) == NULL ) {
3098                         rc = LDAP_NO_MEMORY;
3099                         break;
3100                 }
3101
3102 #ifdef DC_IN_UFN
3103                 if ( leftmost_dc == -1 ) {
3104 #endif /* DC_IN_UFN */
3105                         for ( l = 0, iRDN = 0; dn[ 0 ][ iRDN ]; iRDN++ ) {
3106                                 ber_len_t       vl;
3107                                 LDAPRDN         *rdn = dn[ 0 ][ iRDN ];
3108                         
3109                                 if ( rdn2UFNstr( rdn, &bv->bv_val[ l ], 
3110                                                 flags, &vl ) ) {
3111                                         LDAP_FREE( bv->bv_val );
3112                                         bv->bv_val = NULL;
3113                                         goto return_results;
3114                                 }
3115                                 l += vl;
3116                         }
3117
3118                         /* 
3119                          * trim the last ', ' (the allocated memory 
3120                          * is two bytes longer than required)
3121                          */
3122                         bv->bv_len = len - 2;
3123                         bv->bv_val[ bv->bv_len ] = '\0';
3124 #ifdef DC_IN_UFN
3125                 } else {
3126                         last_iRDN = iRDN - 1;
3127
3128                         for ( l = 0, iRDN = 0; iRDN < leftmost_dc; iRDN++ ) {
3129                                 ber_len_t       vl;
3130                                 LDAPRDN         *rdn = dn[ 0 ][ iRDN ];
3131                         
3132                                 if ( rdn2UFNstr( rdn, &bv->bv_val[ l ], 
3133                                                 flags, &vl ) ) {
3134                                         LDAP_FREE( bv->bv_val );
3135                                         bv->bv_val = NULL;
3136                                         goto return_results;
3137                                 }
3138                                 l += vl;
3139                         }
3140
3141                         if ( !dn2domain( dn, bv, l, &last_iRDN ) ) {
3142                                 LDAP_FREE( bv->bv_val );
3143                                 bv->bv_val = NULL;
3144                                 goto return_results;
3145                         }
3146
3147                         /* the string is correctly terminated by dn2domain */
3148                 }
3149 #endif /* DC_IN_UFN */
3150                 
3151                 rc = LDAP_SUCCESS;
3152
3153         } break;
3154
3155         case LDAP_DN_FORMAT_DCE:
3156                 for ( iRDN = 0, len = 0; dn[ 0 ][ iRDN ]; iRDN++ ) {
3157                         ber_len_t       rdnl;
3158                         LDAPRDN         *rdn = dn[ 0 ][ iRDN ];
3159                         
3160                         if ( rdn2DCEstrlen( rdn, flags, &rdnl ) ) {
3161                                 goto return_results;
3162                         }
3163
3164                         len += rdnl;
3165                 }
3166
3167                 if ( ( bv->bv_val = LDAP_MALLOC( len + 1 ) ) == NULL ) {
3168                         rc = LDAP_NO_MEMORY;
3169                         break;
3170                 }
3171
3172                 for ( l = 0; iRDN--; ) {
3173                         ber_len_t       rdnl;
3174                         LDAPRDN         *rdn = dn[ 0 ][ iRDN ];
3175                         
3176                         if ( rdn2DCEstr( rdn, &bv->bv_val[ l ], flags, 
3177                                         &rdnl, 0 ) ) {
3178                                 LDAP_FREE( bv->bv_val );
3179                                 bv->bv_val = NULL;
3180                                 goto return_results;
3181                         }
3182                         l += rdnl;
3183                 }
3184
3185                 assert( l == len );
3186
3187                 bv->bv_len = len;
3188                 bv->bv_val[ bv->bv_len ] = '\0';
3189
3190                 rc = LDAP_SUCCESS;
3191                 break;
3192
3193         case LDAP_DN_FORMAT_AD_CANONICAL: {
3194                 /*
3195                  * Sort of UFN for DCE DNs: a slash ('/') separated
3196                  * global->local DN with no types; strictly speaking,
3197                  * the naming context should be a domain, which is
3198                  * written in DNS-style, e.g. dot-deparated.
3199                  * 
3200                  * Example:
3201                  * 
3202                  *      "givenName=Bill+sn=Gates,ou=People,dc=microsoft,dc=com"
3203                  *
3204                  * will read
3205                  * 
3206                  *      "microsoft.com/People/Bill,Gates"
3207                  */ 
3208                 for ( iRDN = 0, len = -1; dn[ 0 ][ iRDN ]; iRDN++ ) {
3209                         ber_len_t       rdnl;
3210                         LDAPRDN         *rdn = dn[ 0 ][ iRDN ];
3211                         
3212                         if ( rdn2ADstrlen( rdn, flags, &rdnl ) ) {
3213                                 goto return_results;
3214                         }
3215
3216                         len += rdnl;
3217                 }
3218
3219                 if ( ( bv->bv_val = LDAP_MALLOC( len + 1 ) ) == NULL ) {
3220                         rc = LDAP_NO_MEMORY;
3221                         break;
3222                 }
3223
3224                 iRDN--;
3225                 if ( iRDN && dn2domain( dn, bv, 0, &iRDN ) ) {
3226                         for ( l = bv->bv_len; iRDN >= 0 ; iRDN-- ) {
3227                                 ber_len_t       rdnl;
3228                                 LDAPRDN         *rdn = dn[ 0 ][ iRDN ];
3229                         
3230                                 if ( rdn2ADstr( rdn, &bv->bv_val[ l ], 
3231                                                 flags, &rdnl, 0 ) ) {
3232                                         LDAP_FREE( bv->bv_val );
3233                                         bv->bv_val = NULL;
3234                                         goto return_results;
3235                                 }
3236                                 l += rdnl;
3237                         }
3238
3239                 } else {
3240                         int             first = 1;
3241
3242                         /*
3243                          * Strictly speaking, AD canonical requires
3244                          * a DN to be in the form "..., dc=smtg",
3245                          * i.e. terminated by a domain component
3246                          */
3247                         if ( flags & LDAP_DN_PEDANTIC ) {
3248                                 LDAP_FREE( bv->bv_val );
3249                                 bv->bv_val = NULL;
3250                                 rc = LDAP_ENCODING_ERROR;
3251                                 break;
3252                         }
3253
3254                         for ( l = 0; iRDN >= 0 ; iRDN-- ) {
3255                                 ber_len_t       rdnl;
3256                                 LDAPRDN         *rdn = dn[ 0 ][ iRDN ];
3257                         
3258                                 if ( rdn2ADstr( rdn, &bv->bv_val[ l ], 
3259                                                 flags, &rdnl, first ) ) {
3260                                         LDAP_FREE( bv->bv_val );
3261                                         bv->bv_val = NULL;
3262                                         goto return_results;
3263                                 }
3264                                 if ( first ) {
3265                                         first = 0;
3266                                 }
3267                                 l += rdnl;
3268                         }
3269                 }
3270
3271                 bv->bv_len = len;
3272                 bv->bv_val[ bv->bv_len ] = '\0';
3273
3274                 rc = LDAP_SUCCESS;
3275         } break;
3276
3277         default:
3278                 return LDAP_PARAM_ERROR;
3279         }
3280
3281 #ifdef NEW_LOGGING
3282         LDAP_LOG (( "getdn", LDAP_LEVEL_RESULTS, "<= ldap_dn2bv(%s,%u)=%d\n", 
3283                 bv->bv_val, flags, rc ));
3284 #else
3285         Debug( LDAP_DEBUG_TRACE, "<= ldap_dn2bv(%s,%u)=%d\n",
3286                 bv->bv_val, flags, rc );
3287 #endif
3288
3289 return_results:;
3290         return( rc );
3291 }
3292
3293 #ifdef HAVE_TLS
3294 #include <openssl/x509.h>
3295 #include <openssl/err.h>
3296
3297 /* Convert a structured DN from an X.509 certificate into an LDAPV3 DN.
3298  * x509_name must be an (X509_NAME *). If func is non-NULL, the
3299  * constructed DN will use numeric OIDs to identify attributeTypes,
3300  * and the func() will be invoked to rewrite the DN with the given
3301  * flags.
3302  *
3303  * Otherwise the DN will use shortNames as defined in the OpenSSL
3304  * library.
3305  *
3306  * It's preferable to let slapd do the OID to attributeType mapping,
3307  * because the OpenSSL tables are known to have many typos in versions
3308  * up to (at least) 0.9.6c. However, the LDAP client has no schema tables,
3309  * so we're forced to use OpenSSL's mapping there.
3310  *  -- Howard Chu 2002-04-18
3311  */
3312
3313 int
3314 ldap_X509dn2bv( void *x509_name, struct berval *bv, LDAPDN_rewrite_func *func,
3315         unsigned flags )
3316 {
3317         LDAPDN  *newDN;
3318         LDAPRDN *newRDN;
3319         LDAPAVA *newAVA, *baseAVA;
3320         X509_NAME_ENTRY *ne;
3321         ASN1_OBJECT *obj;
3322         ASN1_STRING *str;
3323         char oids[8192], *oidptr = oids, *oidbuf = NULL;
3324         void *ptrs[2048];
3325         int i, j, k = 0, navas, nrdns, rc = LDAP_SUCCESS;
3326         int set = -1;
3327         size_t dnsize, oidrem = sizeof(oids), oidsize = 0;
3328         int csize;
3329
3330         struct berval   Val;
3331
3332         assert( bv );
3333         bv->bv_len = 0;
3334         bv->bv_val = NULL;
3335
3336         /* Get the number of AVAs. This is not necessarily the same as
3337          * the number of RDNs.
3338          */
3339         navas = X509_NAME_entry_count( x509_name );
3340
3341         /* Get the last element, to see how many RDNs there are */
3342         ne = X509_NAME_get_entry( x509_name, navas - 1 );
3343         nrdns = ne->set + 1;
3344
3345         /* Allocate the DN/RDN/AVA stuff as a single block */    
3346         dnsize = sizeof(LDAPDN) + sizeof(LDAPRDN *) * (nrdns+1);
3347         dnsize += sizeof(LDAPRDN) * nrdns + sizeof(LDAPAVA *) * (navas+nrdns);
3348         dnsize += sizeof(LDAPAVA) * navas;
3349         if (dnsize > sizeof(ptrs)) {
3350                 newDN = (LDAPDN *)LDAP_MALLOC( dnsize );
3351                 if ( newDN == NULL )
3352                         return LDAP_NO_MEMORY;
3353         } else {
3354                 newDN = (LDAPDN *)ptrs;
3355         }
3356         
3357         newDN[0] = (LDAPRDN**)(newDN+1);
3358         newDN[0][nrdns] = NULL;
3359         newRDN = (LDAPRDN*)(newDN[0] + nrdns+1);
3360         newAVA = (LDAPAVA*)(newRDN + navas + nrdns*2);
3361         baseAVA = newAVA;
3362
3363         /* Retrieve RDNs in reverse order; LDAP is backwards from X.500. */
3364         for ( i = nrdns - 1, j = 0; i >= 0; i-- ) {
3365                 ne = X509_NAME_get_entry( x509_name, i );
3366                 obj = X509_NAME_ENTRY_get_object( ne );
3367                 str = X509_NAME_ENTRY_get_data( ne );
3368
3369                 /* If set changed, move to next RDN */
3370                 if ( set != ne->set ) {
3371                         /* If this is not the first time, end the
3372                          * previous RDN and advance.
3373                          */
3374                         if ( j > 0 ) {
3375                                 newRDN[0][k] = NULL;
3376                                 newRDN = (LDAPRDN*)(newRDN[0]+k+1);
3377                         }
3378                         newDN[0][j++] = newRDN;
3379
3380                         newRDN[0] = (LDAPAVA**)(newRDN+1);
3381                         k = 0;
3382                         set = ne->set;
3383                 }
3384                 newAVA->la_private = NULL;
3385                 newAVA->la_flags = LDAP_AVA_STRING;
3386
3387                 if ( !func ) {
3388                         int n = OBJ_obj2nid( obj );
3389
3390                         if (n == NID_undef)
3391                                 goto get_oid;
3392                         newAVA->la_attr.bv_val = (char *)OBJ_nid2sn( n );
3393                         newAVA->la_attr.bv_len = strlen( newAVA->la_attr.bv_val );
3394                 } else {
3395 get_oid:                newAVA->la_attr.bv_val = oidptr;
3396                         newAVA->la_attr.bv_len = OBJ_obj2txt( oidptr, oidrem, obj, 1 );
3397                         oidptr += newAVA->la_attr.bv_len + 1;
3398                         oidrem -= newAVA->la_attr.bv_len + 1;
3399
3400                         /* Running out of OID buffer space? */
3401                         if (oidrem < 128) {
3402                                 if ( oidsize == 0 ) {
3403                                         oidsize = sizeof(oids) * 2;
3404                                         oidrem = oidsize;
3405                                         oidbuf = LDAP_MALLOC( oidsize );
3406                                         if ( oidbuf == NULL ) goto nomem;
3407                                         oidptr = oidbuf;
3408                                 } else {
3409                                         char *old = oidbuf;
3410                                         oidbuf = LDAP_REALLOC( oidbuf, oidsize*2 );
3411                                         if ( oidbuf == NULL ) goto nomem;
3412                                         /* Buffer moved! Fix AVA pointers */
3413                                         if ( old != oidbuf ) {
3414                                                 LDAPAVA *a;
3415                                                 long dif = oidbuf - old;
3416
3417                                                 for (a=baseAVA; a<=newAVA; a++){
3418                                                         if (a->la_attr.bv_val >= old &&
3419                                                                 a->la_attr.bv_val <= (old + oidsize))
3420                                                                 a->la_attr.bv_val += dif;
3421                                                 }
3422                                         }
3423                                         oidptr = oidbuf + oidsize - oidrem;
3424                                         oidrem += oidsize;
3425                                         oidsize *= 2;
3426                                 }
3427                         }
3428                 }
3429                 Val.bv_val = str->data;
3430                 Val.bv_len = str->length;
3431                 switch( str->type ) {
3432                 case V_ASN1_UNIVERSALSTRING:
3433                         /* This uses 32-bit ISO 10646-1 */
3434                         csize = 4; goto to_utf8;
3435                 case V_ASN1_BMPSTRING:
3436                         /* This uses 16-bit ISO 10646-1 */
3437                         csize = 2; goto to_utf8;
3438                 case V_ASN1_T61STRING:
3439                         /* This uses 8-bit, assume ISO 8859-1 */
3440                         csize = 1;
3441 to_utf8:                rc = ldap_ucs_to_utf8s( &Val, csize, &newAVA->la_value );
3442                         if (rc != LDAP_SUCCESS) goto nomem;
3443                         newAVA->la_flags = LDAP_AVA_NONPRINTABLE;
3444                         break;
3445                 case V_ASN1_UTF8STRING:
3446                         newAVA->la_flags = LDAP_AVA_NONPRINTABLE;
3447                         /* This is already in UTF-8 encoding */
3448                 case V_ASN1_IA5STRING:
3449                 case V_ASN1_PRINTABLESTRING:
3450                         /* These are always 7-bit strings */
3451                         ber_dupbv( &newAVA->la_value, &Val );
3452                 default:
3453                         ;
3454                 }
3455                 newRDN[0][k] = newAVA;
3456                 newAVA++;
3457                 k++;
3458         }
3459         newRDN[0][k] = NULL;
3460
3461         if ( func ) {
3462                 rc = func( newDN, flags );
3463                 if ( rc != LDAP_SUCCESS )
3464                         goto nomem;
3465         }
3466
3467         rc = ldap_dn2bv( newDN, bv, LDAP_DN_FORMAT_LDAPV3 );
3468
3469 nomem:
3470         for (;baseAVA < newAVA; baseAVA++) {
3471                 LDAP_FREE( baseAVA->la_value.bv_val );
3472         }
3473
3474         if ( oidsize != 0 )
3475                 LDAP_FREE( oidbuf );
3476         if ( newDN != (LDAPDN*) ptrs )
3477                 LDAP_FREE( newDN );
3478         return rc;
3479 }
3480 #endif /* HAVE_TLS */
3481