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