]> git.sur5r.net Git - openldap/blob - servers/slapd/back-sql/search.c
accaa533e7b426137e0d17ff1dea984ad49b2132
[openldap] / servers / slapd / back-sql / search.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 1999-2005 The OpenLDAP Foundation.
5  * Portions Copyright 1999 Dmitry Kovalev.
6  * Portions Copyright 2002 Pierangelo Masarati.
7  * Portions Copyright 2004 Mark Adamson.
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted only as authorized by the OpenLDAP
12  * Public License.
13  *
14  * A copy of this license is available in the file LICENSE in the
15  * top-level directory of the distribution or, alternatively, at
16  * <http://www.OpenLDAP.org/license.html>.
17  */
18 /* ACKNOWLEDGEMENTS:
19  * This work was initially developed by Dmitry Kovalev for inclusion
20  * by OpenLDAP Software.  Additional significant contributors include
21  * Pierangelo Masarati and Mark Adamson.
22  */
23
24 #include "portable.h"
25
26 #include <stdio.h>
27 #include <sys/types.h>
28 #include "ac/string.h"
29 #include "ac/ctype.h"
30
31 #include "slap.h"
32 #include "proto-sql.h"
33
34 static int backsql_process_filter( backsql_srch_info *bsi, Filter *f );
35 static int backsql_process_filter_eq( backsql_srch_info *bsi, 
36                 backsql_at_map_rec *at,
37                 int casefold, struct berval *filter_value );
38 static int backsql_process_filter_like( backsql_srch_info *bsi, 
39                 backsql_at_map_rec *at,
40                 int casefold, struct berval *filter_value );
41 static int backsql_process_filter_attr( backsql_srch_info *bsi, Filter *f, 
42                 backsql_at_map_rec *at );
43
44 static int
45 backsql_attrlist_add( backsql_srch_info *bsi, AttributeDescription *ad )
46 {
47         int             n_attrs = 0;
48         AttributeName   *an = NULL;
49
50         if ( bsi->bsi_attrs == NULL ) {
51                 return 1;
52         }
53
54         /*
55          * clear the list (retrieve all attrs)
56          */
57         if ( ad == NULL ) {
58                 bsi->bsi_op->o_tmpfree( bsi->bsi_attrs, bsi->bsi_op->o_tmpmemctx );
59                 bsi->bsi_attrs = NULL;
60                 bsi->bsi_flags |= BSQL_SF_ALL_ATTRS;
61                 return 1;
62         }
63
64         for ( ; !BER_BVISNULL( &bsi->bsi_attrs[ n_attrs ].an_name ); n_attrs++ ) {
65                 an = &bsi->bsi_attrs[ n_attrs ];
66                 
67                 Debug( LDAP_DEBUG_TRACE, "==>backsql_attrlist_add(): "
68                         "attribute \"%s\" is in list\n", 
69                         an->an_name.bv_val, 0, 0 );
70                 /*
71                  * We can live with strcmp because the attribute 
72                  * list has been normalized before calling be_search
73                  */
74                 if ( !BACKSQL_NCMP( &an->an_name, &ad->ad_cname ) ) {
75                         return 1;
76                 }
77         }
78         
79         Debug( LDAP_DEBUG_TRACE, "==>backsql_attrlist_add(): "
80                 "adding \"%s\" to list\n", ad->ad_cname.bv_val, 0, 0 );
81
82         an = (AttributeName *)bsi->bsi_op->o_tmprealloc( bsi->bsi_attrs,
83                         sizeof( AttributeName ) * ( n_attrs + 2 ),
84                         bsi->bsi_op->o_tmpmemctx );
85         if ( an == NULL ) {
86                 return -1;
87         }
88
89         an[ n_attrs ].an_name = ad->ad_cname;
90         an[ n_attrs ].an_desc = ad;
91         BER_BVZERO( &an[ n_attrs + 1 ].an_name );
92
93         bsi->bsi_attrs = an;
94         
95         return 1;
96 }
97
98 /*
99  * Initializes the search structure.
100  * 
101  * If get_base_id != 0, the field bsi_base_id is filled 
102  * with the entryID of bsi_base_ndn; it must be freed
103  * by backsql_free_entryID() when no longer required.
104  *
105  * NOTE: base must be normalized
106  */
107 int
108 backsql_init_search(
109         backsql_srch_info       *bsi, 
110         struct berval           *nbase, 
111         int                     scope, 
112         int                     slimit,
113         int                     tlimit,
114         time_t                  stoptime, 
115         Filter                  *filter, 
116         SQLHDBC                 dbh,
117         Operation               *op,
118         SlapReply               *rs,
119         AttributeName           *attrs,
120         unsigned                flags )
121 {
122         backsql_info            *bi = (backsql_info *)op->o_bd->be_private;
123         int                     rc = LDAP_SUCCESS;
124
125         bsi->bsi_base_ndn = nbase;
126         bsi->bsi_use_subtree_shortcut = 0;
127         BER_BVZERO( &bsi->bsi_base_id.eid_dn );
128         BER_BVZERO( &bsi->bsi_base_id.eid_ndn );
129         bsi->bsi_scope = scope;
130         bsi->bsi_slimit = slimit;
131         bsi->bsi_tlimit = tlimit;
132         bsi->bsi_filter = filter;
133         bsi->bsi_dbh = dbh;
134         bsi->bsi_op = op;
135         bsi->bsi_rs = rs;
136         bsi->bsi_flags = BSQL_SF_NONE;
137
138         bsi->bsi_attrs = NULL;
139
140         if ( BACKSQL_FETCH_ALL_ATTRS( bi ) ) {
141                 /*
142                  * if requested, simply try to fetch all attributes
143                  */
144                 bsi->bsi_flags |= BSQL_SF_ALL_ATTRS;
145
146         } else {
147                 if ( BACKSQL_FETCH_ALL_USERATTRS( bi ) ) {
148                         bsi->bsi_flags |= BSQL_SF_ALL_USER;
149
150                 } else if ( BACKSQL_FETCH_ALL_OPATTRS( bi ) ) {
151                         bsi->bsi_flags |= BSQL_SF_ALL_OPER;
152                 }
153
154                 if ( attrs == NULL ) {
155                         /* NULL means all user attributes */
156                         bsi->bsi_flags |= BSQL_SF_ALL_USER;
157
158                 } else {
159                         AttributeName   *p;
160                         int             got_oc = 0;
161
162                         bsi->bsi_attrs = (AttributeName *)bsi->bsi_op->o_tmpalloc(
163                                         sizeof( AttributeName ),
164                                         bsi->bsi_op->o_tmpmemctx );
165                         BER_BVZERO( &bsi->bsi_attrs[ 0 ].an_name );
166         
167                         for ( p = attrs; !BER_BVISNULL( &p->an_name ); p++ ) {
168                                 if ( BACKSQL_NCMP( &p->an_name, &AllUser ) == 0 ) {
169                                         /* handle "*" */
170                                         bsi->bsi_flags |= BSQL_SF_ALL_USER;
171
172                                         /* if all attrs are requested, there's
173                                          * no need to continue */
174                                         if ( BSQL_ISF_ALL_ATTRS( bsi ) ) {
175                                                 bsi->bsi_op->o_tmpfree( bsi->bsi_attrs,
176                                                                 bsi->bsi_op->o_tmpmemctx );
177                                                 bsi->bsi_attrs = NULL;
178                                                 break;
179                                         }
180                                         continue;
181
182                                 } else if ( BACKSQL_NCMP( &p->an_name, &AllOper ) == 0 ) {
183                                         /* handle "+" */
184                                         bsi->bsi_flags |= BSQL_SF_ALL_OPER;
185
186                                         /* if all attrs are requested, there's
187                                          * no need to continue */
188                                         if ( BSQL_ISF_ALL_ATTRS( bsi ) ) {
189                                                 bsi->bsi_op->o_tmpfree( bsi->bsi_attrs,
190                                                                 bsi->bsi_op->o_tmpmemctx );
191                                                 bsi->bsi_attrs = NULL;
192                                                 break;
193                                         }
194                                         continue;
195
196                                 } else if ( BACKSQL_NCMP( &p->an_name, &NoAttrs ) == 0 ) {
197                                         /* ignore "1.1" */
198                                         continue;
199
200                                 } else if ( p->an_desc == slap_schema.si_ad_objectClass ) {
201                                         got_oc = 1;
202                                 }
203
204                                 backsql_attrlist_add( bsi, p->an_desc );
205                         }
206
207                         if ( got_oc == 0 && !( bsi->bsi_flags & BSQL_SF_ALL_USER ) ) {
208                                 /* add objectClass if not present,
209                                  * because it is required to understand
210                                  * if an entry is a referral, an alias 
211                                  * or so... */
212                                 backsql_attrlist_add( bsi, slap_schema.si_ad_objectClass );
213                         }
214                 }
215
216                 if ( !BSQL_ISF_ALL_ATTRS( bsi ) && bi->sql_anlist ) {
217                         AttributeName   *p;
218                         
219                         /* use hints if available */
220                         for ( p = bi->sql_anlist; !BER_BVISNULL( &p->an_name ); p++ ) {
221                                 if ( BACKSQL_NCMP( &p->an_name, &AllUser ) == 0 ) {
222                                         /* handle "*" */
223                                         bsi->bsi_flags |= BSQL_SF_ALL_USER;
224
225                                         /* if all attrs are requested, there's
226                                          * no need to continue */
227                                         if ( BSQL_ISF_ALL_ATTRS( bsi ) ) {
228                                                 bsi->bsi_op->o_tmpfree( bsi->bsi_attrs,
229                                                                 bsi->bsi_op->o_tmpmemctx );
230                                                 bsi->bsi_attrs = NULL;
231                                                 break;
232                                         }
233                                         continue;
234
235                                 } else if ( BACKSQL_NCMP( &p->an_name, &AllOper ) == 0 ) {
236                                         /* handle "+" */
237                                         bsi->bsi_flags |= BSQL_SF_ALL_OPER;
238
239                                         /* if all attrs are requested, there's
240                                          * no need to continue */
241                                         if ( BSQL_ISF_ALL_ATTRS( bsi ) ) {
242                                                 bsi->bsi_op->o_tmpfree( bsi->bsi_attrs,
243                                                                 bsi->bsi_op->o_tmpmemctx );
244                                                 bsi->bsi_attrs = NULL;
245                                                 break;
246                                         }
247                                         continue;
248                                 }
249
250                                 backsql_attrlist_add( bsi, p->an_desc );
251                         }
252
253                 }
254         }
255
256         bsi->bsi_abandon = 0;
257         bsi->bsi_id_list = NULL;
258         bsi->bsi_id_listtail = &bsi->bsi_id_list;
259         bsi->bsi_n_candidates = 0;
260         bsi->bsi_stoptime = stoptime;
261         BER_BVZERO( &bsi->bsi_sel.bb_val );
262         bsi->bsi_sel.bb_len = 0;
263         BER_BVZERO( &bsi->bsi_from.bb_val );
264         bsi->bsi_from.bb_len = 0;
265         BER_BVZERO( &bsi->bsi_join_where.bb_val );
266         bsi->bsi_join_where.bb_len = 0;
267         BER_BVZERO( &bsi->bsi_flt_where.bb_val );
268         bsi->bsi_flt_where.bb_len = 0;
269         bsi->bsi_filter_oc = NULL;
270
271         if ( BACKSQL_IS_GET_ID( flags ) ) {
272                 int     matched = BACKSQL_IS_MATCHED( flags );
273                 int     getentry = BACKSQL_IS_GET_ENTRY( flags );
274                 int     gotit = 0;
275
276                 assert( op->o_bd->be_private );
277
278                 rc = backsql_dn2id( op, rs, dbh, nbase, &bsi->bsi_base_id,
279                                 matched, 1 );
280
281                 /* the entry is collected either if requested for by getentry
282                  * or if get noSuchObject and requested to climb the tree,
283                  * so that a matchedDN or a referral can be returned */
284                 if ( ( rc == LDAP_NO_SUCH_OBJECT && matched ) || getentry ) {
285                         if ( !BER_BVISNULL( &bsi->bsi_base_id.eid_ndn ) ) {
286                                 assert( bsi->bsi_e != NULL );
287                                 
288                                 if ( dn_match( nbase, &bsi->bsi_base_id.eid_ndn ) )
289                                 {
290                                         gotit = 1;
291                                 }
292                         
293                                 /*
294                                  * let's see if it is a referral and, in case, get it
295                                  */
296                                 backsql_attrlist_add( bsi, slap_schema.si_ad_ref );
297                                 rc = backsql_id2entry( bsi, &bsi->bsi_base_id );
298                                 if ( rc == LDAP_SUCCESS ) {
299                                         if ( is_entry_referral( bsi->bsi_e ) )
300                                         {
301                                                 BerVarray erefs = get_entry_referrals( op, bsi->bsi_e );
302                                                 if ( erefs ) {
303                                                         rc = rs->sr_err = LDAP_REFERRAL;
304                                                         rs->sr_ref = referral_rewrite( erefs,
305                                                                         &bsi->bsi_e->e_nname,
306                                                                         &op->o_req_dn,
307                                                                         scope );
308                                                         ber_bvarray_free( erefs );
309         
310                                                 } else {
311                                                         rc = rs->sr_err = LDAP_OTHER;
312                                                         rs->sr_text = "bad referral object";
313                                                 }
314
315                                         } else if ( !gotit ) {
316                                                 rc = rs->sr_err = LDAP_NO_SUCH_OBJECT;
317                                         }
318                                 }
319
320                         } else {
321                                 rs->sr_ref = referral_rewrite( default_referral,
322                                                 NULL, &op->o_req_dn, scope );
323                                 rc = rs->sr_err = LDAP_REFERRAL;
324                         }
325                 }
326         }
327
328         bsi->bsi_status = rc;
329
330         switch ( rc ) {
331         case LDAP_SUCCESS:
332         case LDAP_REFERRAL:
333                 break;
334
335         default:
336                 bsi->bsi_op->o_tmpfree( bsi->bsi_attrs,
337                                 bsi->bsi_op->o_tmpmemctx );
338                 break;
339         }
340
341         return rc;
342 }
343
344 static int
345 backsql_process_filter_list( backsql_srch_info *bsi, Filter *f, int op )
346 {
347         int             res;
348
349         if ( !f ) {
350                 return 0;
351         }
352
353         backsql_strfcat( &bsi->bsi_flt_where, "c", '(' /* ) */  );
354
355         while ( 1 ) {
356                 res = backsql_process_filter( bsi, f );
357                 if ( res < 0 ) {
358                         /*
359                          * TimesTen : If the query has no answers,
360                          * don't bother to run the query.
361                          */
362                         return -1;
363                 }
364  
365                 f = f->f_next;
366                 if ( f == NULL ) {
367                         break;
368                 }
369
370                 switch ( op ) {
371                 case LDAP_FILTER_AND:
372                         backsql_strfcat( &bsi->bsi_flt_where, "l",
373                                         (ber_len_t)STRLENOF( " AND " ), 
374                                                 " AND " );
375                         break;
376
377                 case LDAP_FILTER_OR:
378                         backsql_strfcat( &bsi->bsi_flt_where, "l",
379                                         (ber_len_t)STRLENOF( " OR " ),
380                                                 " OR " );
381                         break;
382                 }
383         }
384
385         backsql_strfcat( &bsi->bsi_flt_where, "c", /* ( */ ')' );
386
387         return 1;
388 }
389
390 static int
391 backsql_process_sub_filter( backsql_srch_info *bsi, Filter *f,
392         backsql_at_map_rec *at )
393 {
394         backsql_info            *bi = (backsql_info *)bsi->bsi_op->o_bd->be_private;
395         int                     i;
396         int                     casefold = 0;
397
398         if ( !f ) {
399                 return 0;
400         }
401
402         /* always uppercase strings by now */
403 #ifdef BACKSQL_UPPERCASE_FILTER
404         if ( f->f_sub_desc->ad_type->sat_substr &&
405                         SLAP_MR_ASSOCIATED( f->f_sub_desc->ad_type->sat_substr,
406                                 bi->sql_caseIgnoreMatch ) )
407 #endif /* BACKSQL_UPPERCASE_FILTER */
408         {
409                 casefold = 1;
410         }
411
412         if ( f->f_sub_desc->ad_type->sat_substr &&
413                         SLAP_MR_ASSOCIATED( f->f_sub_desc->ad_type->sat_substr,
414                                 bi->sql_telephoneNumberMatch ) )
415         {
416
417                 struct berval   bv;
418                 ber_len_t       i, s, a;
419
420                 /*
421                  * to check for matching telephone numbers
422                  * with intermixed chars, e.g. val='1234'
423                  * use
424                  * 
425                  * val LIKE '%1%2%3%4%'
426                  */
427
428                 BER_BVZERO( &bv );
429                 if ( f->f_sub_initial.bv_val ) {
430                         bv.bv_len += f->f_sub_initial.bv_len;
431                 }
432                 if ( f->f_sub_any != NULL ) {
433                         for ( a = 0; f->f_sub_any[ a ].bv_val != NULL; a++ ) {
434                                 bv.bv_len += f->f_sub_any[ a ].bv_len;
435                         }
436                 }
437                 if ( f->f_sub_final.bv_val ) {
438                         bv.bv_len += f->f_sub_final.bv_len;
439                 }
440                 bv.bv_len = 2 * bv.bv_len - 1;
441                 bv.bv_val = ch_malloc( bv.bv_len + 1 );
442
443                 s = 0;
444                 if ( !BER_BVISNULL( &f->f_sub_initial ) ) {
445                         bv.bv_val[ s ] = f->f_sub_initial.bv_val[ 0 ];
446                         for ( i = 1; i < f->f_sub_initial.bv_len; i++ ) {
447                                 bv.bv_val[ s + 2 * i - 1 ] = '%';
448                                 bv.bv_val[ s + 2 * i ] = f->f_sub_initial.bv_val[ i ];
449                         }
450                         bv.bv_val[ s + 2 * i - 1 ] = '%';
451                         s += 2 * i;
452                 }
453
454                 if ( f->f_sub_any != NULL ) {
455                         for ( a = 0; !BER_BVISNULL( &f->f_sub_any[ a ] ); a++ ) {
456                                 bv.bv_val[ s ] = f->f_sub_any[ a ].bv_val[ 0 ];
457                                 for ( i = 1; i < f->f_sub_any[ a ].bv_len; i++ ) {
458                                         bv.bv_val[ s + 2 * i - 1 ] = '%';
459                                         bv.bv_val[ s + 2 * i ] = f->f_sub_any[ a ].bv_val[ i ];
460                                 }
461                                 bv.bv_val[ s + 2 * i - 1 ] = '%';
462                                 s += 2 * i;
463                         }
464                 }
465
466                 if ( !BER_BVISNULL( &f->f_sub_final ) ) {
467                         bv.bv_val[ s ] = f->f_sub_final.bv_val[ 0 ];
468                         for ( i = 1; i < f->f_sub_final.bv_len; i++ ) {
469                                 bv.bv_val[ s + 2 * i - 1 ] = '%';
470                                 bv.bv_val[ s + 2 * i ] = f->f_sub_final.bv_val[ i ];
471                         }
472                                 bv.bv_val[ s + 2 * i - 1 ] = '%';
473                         s += 2 * i;
474                 }
475
476                 bv.bv_val[ s - 1 ] = '\0';
477
478                 (void)backsql_process_filter_like( bsi, at, casefold, &bv );
479                 ch_free( bv.bv_val );
480
481                 return 1;
482         }
483
484         /*
485          * When dealing with case-sensitive strings 
486          * we may omit normalization; however, normalized
487          * SQL filters are more liberal.
488          */
489
490         backsql_strfcat( &bsi->bsi_flt_where, "c", '(' /* ) */  );
491
492         /* TimesTen */
493         Debug( LDAP_DEBUG_TRACE, "backsql_process_sub_filter(%s):\n",
494                 at->bam_ad->ad_cname.bv_val, 0, 0 );
495         Debug(LDAP_DEBUG_TRACE, "   expr: '%s%s%s'\n", at->bam_sel_expr.bv_val,
496                 at->bam_sel_expr_u.bv_val ? "' '" : "",
497                 at->bam_sel_expr_u.bv_val ? at->bam_sel_expr_u.bv_val : "" );
498         if ( casefold && BACKSQL_AT_CANUPPERCASE( at ) ) {
499                 /*
500                  * If a pre-upper-cased version of the column 
501                  * or a precompiled upper function exists, use it
502                  */
503                 backsql_strfcat( &bsi->bsi_flt_where, 
504                                 "bl",
505                                 &at->bam_sel_expr_u,
506                                 (ber_len_t)STRLENOF( " LIKE '" ),
507                                         " LIKE '" );
508
509         } else {
510                 backsql_strfcat( &bsi->bsi_flt_where, "bl",
511                                 &at->bam_sel_expr,
512                                 (ber_len_t)STRLENOF( " LIKE '" ), " LIKE '" );
513         }
514  
515         if ( !BER_BVISNULL( &f->f_sub_initial ) ) {
516                 ber_len_t       start;
517
518 #ifdef BACKSQL_TRACE
519                 Debug( LDAP_DEBUG_TRACE, 
520                         "==>backsql_process_sub_filter(%s): "
521                         "sub_initial=\"%s\"\n", at->bam_ad->ad_cname.bv_val,
522                         f->f_sub_initial.bv_val, 0 );
523 #endif /* BACKSQL_TRACE */
524
525                 start = bsi->bsi_flt_where.bb_val.bv_len;
526                 backsql_strfcat( &bsi->bsi_flt_where, "b",
527                                 &f->f_sub_initial );
528                 if ( casefold && BACKSQL_AT_CANUPPERCASE( at ) ) {
529                         ldap_pvt_str2upper( &bsi->bsi_flt_where.bb_val.bv_val[ start ] );
530                 }
531         }
532
533         backsql_strfcat( &bsi->bsi_flt_where, "c", '%' );
534
535         if ( f->f_sub_any != NULL ) {
536                 for ( i = 0; !BER_BVISNULL( &f->f_sub_any[ i ] ); i++ ) {
537                         ber_len_t       start;
538
539 #ifdef BACKSQL_TRACE
540                         Debug( LDAP_DEBUG_TRACE, 
541                                 "==>backsql_process_sub_filter(%s): "
542                                 "sub_any[%d]=\"%s\"\n", at->bam_ad->ad_cname.bv_val, 
543                                 i, f->f_sub_any[ i ].bv_val );
544 #endif /* BACKSQL_TRACE */
545
546                         start = bsi->bsi_flt_where.bb_val.bv_len;
547                         backsql_strfcat( &bsi->bsi_flt_where,
548                                         "bc",
549                                         &f->f_sub_any[ i ],
550                                         '%' );
551                         if ( casefold && BACKSQL_AT_CANUPPERCASE( at ) ) {
552                                 /*
553                                  * Note: toupper('%') = '%'
554                                  */
555                                 ldap_pvt_str2upper( &bsi->bsi_flt_where.bb_val.bv_val[ start ] );
556                         }
557                 }
558         }
559
560         if ( !BER_BVISNULL( &f->f_sub_final ) ) {
561                 ber_len_t       start;
562
563 #ifdef BACKSQL_TRACE
564                 Debug( LDAP_DEBUG_TRACE, 
565                         "==>backsql_process_sub_filter(%s): "
566                         "sub_final=\"%s\"\n", at->bam_ad->ad_cname.bv_val,
567                         f->f_sub_final.bv_val, 0 );
568 #endif /* BACKSQL_TRACE */
569
570                 start = bsi->bsi_flt_where.bb_val.bv_len;
571                 backsql_strfcat( &bsi->bsi_flt_where, "b",
572                                 &f->f_sub_final );
573                 if ( casefold && BACKSQL_AT_CANUPPERCASE( at ) ) {
574                         ldap_pvt_str2upper( &bsi->bsi_flt_where.bb_val.bv_val[ start ] );
575                 }
576         }
577
578         backsql_strfcat( &bsi->bsi_flt_where, "l", 
579                         (ber_len_t)STRLENOF( /* (' */ "')" ), /* (' */ "')" );
580  
581         return 1;
582 }
583
584 static int
585 backsql_merge_from_tbls( backsql_srch_info *bsi, struct berval *from_tbls )
586 {
587         if ( BER_BVISNULL( from_tbls ) ) {
588                 return LDAP_SUCCESS;
589         }
590
591         if ( !BER_BVISNULL( &bsi->bsi_from.bb_val ) ) {
592                 char    *start, *end, *tmp;
593
594                 tmp = ch_strdup( from_tbls->bv_val );
595
596                 for ( start = tmp, end = strchr( start, ',' ); start; ) {
597                         if ( end ) {
598                                 end[0] = '\0';
599                         }
600
601                         if ( strstr( bsi->bsi_from.bb_val.bv_val, start) == NULL )
602                         {
603                                 backsql_strfcat( &bsi->bsi_from, "cs", ',', start );
604                         }
605
606                         if ( end ) {
607                                 /* in case there are spaces after the comma... */
608                                 for ( start = &end[1]; isspace( start[0] ); start++ );
609                                 if ( start[0] ) {
610                                         end = strchr( start, ',' );
611                                 } else {
612                                         start = NULL;
613                                 }
614                         } else {
615                                 start = NULL;
616                         }
617                 }
618
619                 ch_free( tmp );
620
621         } else {
622                 backsql_strfcat( &bsi->bsi_from, "b", from_tbls );
623         }
624
625         return LDAP_SUCCESS;
626 }
627
628 static int
629 backsql_process_filter( backsql_srch_info *bsi, Filter *f )
630 {
631         backsql_at_map_rec      **vat = NULL;
632         AttributeDescription    *ad = NULL;
633         unsigned                i;
634         int                     done = 0;
635         int                     rc = 0;
636
637         Debug( LDAP_DEBUG_TRACE, "==>backsql_process_filter()\n", 0, 0, 0 );
638         if ( f->f_choice == SLAPD_FILTER_COMPUTED ) {
639                 Debug( LDAP_DEBUG_TRACE, "backsql_process_filter(): "
640                         "invalid filter\n", 0, 0, 0 );
641                 rc = -1;
642                 goto done;
643         }
644
645         switch( f->f_choice ) {
646         case LDAP_FILTER_OR:
647                 rc = backsql_process_filter_list( bsi, f->f_or, 
648                                 LDAP_FILTER_OR );
649                 done = 1;
650                 break;
651                 
652         case LDAP_FILTER_AND:
653                 rc = backsql_process_filter_list( bsi, f->f_and,
654                                 LDAP_FILTER_AND );
655                 done = 1;
656                 break;
657
658         case LDAP_FILTER_NOT:
659                 backsql_strfcat( &bsi->bsi_flt_where, "l",
660                                 (ber_len_t)STRLENOF( "NOT (" /* ) */ ),
661                                         "NOT (" /* ) */ );
662                 rc = backsql_process_filter( bsi, f->f_not );
663                 backsql_strfcat( &bsi->bsi_flt_where, "c", /* ( */ ')' );
664                 done = 1;
665                 break;
666
667         case LDAP_FILTER_PRESENT:
668                 ad = f->f_desc;
669                 break;
670                 
671         case LDAP_FILTER_EXT:
672                 ad = f->f_mra->ma_desc;
673                 if ( f->f_mr_dnattrs ) {
674                         /*
675                          * if dn attrs filtering is requested, better return 
676                          * success and let test_filter() deal with candidate
677                          * selection; otherwise we'd need to set conditions
678                          * on the contents of the DN, e.g. "SELECT ... FROM
679                          * ldap_entries AS attributeName WHERE attributeName.dn
680                          * like '%attributeName=value%'"
681                          */
682                         backsql_strfcat( &bsi->bsi_flt_where, "l",
683                                         (ber_len_t)STRLENOF( "1=1" ), "1=1" );
684                         bsi->bsi_status = LDAP_SUCCESS;
685                         rc = 1;
686                         goto done;
687                 }
688                 break;
689                 
690         default:
691                 ad = f->f_av_desc;
692                 break;
693         }
694
695         if ( rc == -1 ) {
696                 goto done;
697         }
698  
699         if ( done ) {
700                 rc = 1;
701                 goto done;
702         }
703
704         /*
705          * Turn structuralObjectClass into objectClass
706          */
707         if ( ad == slap_schema.si_ad_objectClass 
708                         || ad == slap_schema.si_ad_structuralObjectClass )
709         {
710                 /*
711                  * If the filter is LDAP_FILTER_PRESENT, then it's done;
712                  * otherwise, let's see if we are lucky: filtering
713                  * for "structural" objectclass or ancestor...
714                  */
715                 switch ( f->f_choice ) {
716                 case LDAP_FILTER_EQUALITY:
717                 {
718                         ObjectClass     *oc = oc_bvfind( &f->f_av_value );
719
720                         if ( oc == NULL ) {
721                                 Debug( LDAP_DEBUG_TRACE,
722                                                 "backsql_process_filter(): "
723                                                 "unknown objectClass \"%s\" "
724                                                 "in filter\n",
725                                                 f->f_av_value.bv_val, 0, 0 );
726                                 bsi->bsi_status = LDAP_OTHER;
727                                 rc = -1;
728                                 goto done;
729                         }
730
731                         /*
732                          * "structural" objectClass inheritance:
733                          * - a search for "person" will also return 
734                          *   "inetOrgPerson"
735                          * - a search for "top" will return everything
736                          */
737                         if ( is_object_subclass( oc, bsi->bsi_oc->bom_oc ) ) {
738                                 static struct berval ldap_entry_objclasses = BER_BVC( "ldap_entry_objclasses" );
739
740                                 backsql_merge_from_tbls( bsi, &ldap_entry_objclasses );
741
742                                 backsql_strfcat( &bsi->bsi_flt_where, "lbl",
743                                                 (ber_len_t)STRLENOF( "(2=2 OR (ldap_entries.id=ldap_entry_objclasses.entry_id AND ldap_entry_objclasses.oc_name='" /* ')) */ ),
744                                                         "(2=2 OR (ldap_entries.id=ldap_entry_objclasses.entry_id AND ldap_entry_objclasses.oc_name='" /* ')) */,
745                                                 &bsi->bsi_oc->bom_oc->soc_cname,
746                                                 (ber_len_t)STRLENOF( /* ((' */ "'))" ),
747                                                         /* ((' */ "'))" );
748                                 bsi->bsi_status = LDAP_SUCCESS;
749                                 rc = 1;
750                                 goto done;
751                         }
752
753                         break;
754                 }
755
756                 case LDAP_FILTER_PRESENT:
757                         backsql_strfcat( &bsi->bsi_flt_where, "l",
758                                         (ber_len_t)STRLENOF( "3=3" ), "3=3" );
759                         bsi->bsi_status = LDAP_SUCCESS;
760                         rc = 1;
761                         goto done;
762
763                         /* FIXME: LDAP_FILTER_EXT? */
764                         
765                 default:
766                         Debug( LDAP_DEBUG_TRACE,
767                                         "backsql_process_filter(): "
768                                         "illegal/unhandled filter "
769                                         "on objectClass attribute",
770                                         0, 0, 0 );
771                         bsi->bsi_status = LDAP_OTHER;
772                         rc = -1;
773                         goto done;
774                 }
775
776         } else if ( ad == slap_schema.si_ad_entryUUID ) {
777                 unsigned long   oc_id;
778 #ifdef BACKSQL_ARBITRARY_KEY
779                 struct berval   keyval;
780 #else /* ! BACKSQL_ARBITRARY_KEY */
781                 unsigned long   keyval;
782                 char            keyvalbuf[] = "18446744073709551615";
783 #endif /* ! BACKSQL_ARBITRARY_KEY */
784
785                 switch ( f->f_choice ) {
786                 case LDAP_FILTER_EQUALITY:
787                         backsql_entryUUID_decode( &f->f_av_value, &oc_id, &keyval );
788
789                         if ( oc_id != bsi->bsi_oc->bom_id ) {
790                                 bsi->bsi_status = LDAP_SUCCESS;
791                                 rc = -1;
792                                 goto done;
793                         }
794
795 #ifdef BACKSQL_ARBITRARY_KEY
796                         backsql_strfcat( &bsi->bsi_flt_where, "bcblbc",
797                                         &bsi->bsi_oc->bom_keytbl, '.',
798                                         &bsi->bsi_oc->bom_keycol,
799                                         STRLENOF( " LIKE '" ), " LIKE '",
800                                         &keyval, '\'' );
801 #else /* ! BACKSQL_ARBITRARY_KEY */
802                         snprintf( keyvalbuf, sizeof( keyvalbuf ), "%lu", keyval );
803                         backsql_strfcat( &bsi->bsi_flt_where, "bcbcs",
804                                         &bsi->bsi_oc->bom_keytbl, '.',
805                                         &bsi->bsi_oc->bom_keycol, '=', keyvalbuf );
806 #endif /* ! BACKSQL_ARBITRARY_KEY */
807                         break;
808
809                 case LDAP_FILTER_PRESENT:
810                         backsql_strfcat( &bsi->bsi_flt_where, "l",
811                                         (ber_len_t)STRLENOF( "4=4" ), "4=4" );
812                         break;
813
814                 default:
815                         rc = -1;
816                         goto done;
817                 }
818
819                 bsi->bsi_flags |= BSQL_SF_FILTER_ENTRYUUID;
820                 rc = 1;
821                 goto done;
822
823 #ifdef BACKSQL_SYNCPROV
824         } else if ( ad == slap_schema.si_ad_entryCSN ) {
825                 /*
826                  * support for syncrepl as producer...
827                  */
828                 if ( !bsi->bsi_op->o_sync ) {
829                         /* unsupported at present... */
830                         bsi->bsi_status = LDAP_OTHER;
831                         rc = -1;
832                         goto done;
833                 }
834
835                 bsi->bsi_flags |= ( BSQL_SF_FILTER_ENTRYCSN | BSQL_SF_RETURN_ENTRYUUID);
836
837                 /* if doing a syncrepl, try to return as much as possible,
838                  * and always match the filter */
839                 backsql_strfcat( &bsi->bsi_flt_where, "l",
840                                 (ber_len_t)STRLENOF( "5=5" ), "5=5" );
841
842                 /* save for later use in operational attributes */
843                 /* FIXME: saves only the first occurrence, because 
844                  * the filter during updates is written as
845                  * "(&(entryCSN<={contextCSN})(entryCSN>={oldContextCSN})({filter}))"
846                  * so we want our fake entryCSN to match the greatest
847                  * value
848                  */
849                 if ( bsi->bsi_op->o_private == NULL ) {
850                         bsi->bsi_op->o_private = &f->f_av_value;
851                 }
852                 bsi->bsi_status = LDAP_SUCCESS;
853
854                 rc = 1;
855                 goto done;
856 #endif /* BACKSQL_SYNCPROV */
857
858         } else if ( ad == slap_schema.si_ad_hasSubordinates || ad == NULL ) {
859                 /*
860                  * FIXME: this is not robust; e.g. a filter
861                  * '(!(hasSubordinates=TRUE))' fails because
862                  * in SQL it would read 'NOT (1=1)' instead 
863                  * of no condition.  
864                  * Note however that hasSubordinates is boolean, 
865                  * so a more appropriate filter would be 
866                  * '(hasSubordinates=FALSE)'
867                  *
868                  * A more robust search for hasSubordinates
869                  * would * require joining the ldap_entries table
870                  * selecting if there are descendants of the
871                  * candidate.
872                  */
873                 backsql_strfcat( &bsi->bsi_flt_where, "l",
874                                 (ber_len_t)STRLENOF( "6=6" ), "6=6" );
875                 if ( ad == slap_schema.si_ad_hasSubordinates ) {
876                         /*
877                          * instruct candidate selection algorithm
878                          * and attribute list to try to detect
879                          * if an entry has subordinates
880                          */
881                         bsi->bsi_flags |= BSQL_SF_FILTER_HASSUBORDINATE;
882
883                 } else {
884                         /*
885                          * clear attributes to fetch, to require ALL
886                          * and try extended match on all attributes
887                          */
888                         backsql_attrlist_add( bsi, NULL );
889                 }
890                 rc = 1;
891                 goto done;
892         }
893
894         /*
895          * attribute inheritance:
896          */
897         if ( backsql_supad2at( bsi->bsi_oc, ad, &vat ) ) {
898                 bsi->bsi_status = LDAP_OTHER;
899                 rc = -1;
900                 goto done;
901         }
902
903         if ( vat == NULL ) {
904                 /* search anyway; other parts of the filter
905                  * may succeeed */
906                 backsql_strfcat( &bsi->bsi_flt_where, "l",
907                                 (ber_len_t)STRLENOF( "7=7" ), "7=7" );
908                 bsi->bsi_status = LDAP_SUCCESS;
909                 rc = 1;
910                 goto done;
911         }
912
913         /* if required, open extra level of parens */
914         done = 0;
915         if ( vat[0]->bam_next || vat[1] ) {
916                 backsql_strfcat( &bsi->bsi_flt_where, "c", '(' );
917                 done = 1;
918         }
919
920         i = 0;
921 next:;
922         /* apply attr */
923         if ( backsql_process_filter_attr( bsi, f, vat[i] ) == -1 ) {
924                 return -1;
925         }
926
927         /* if more definitions of the same attr, apply */
928         if ( vat[i]->bam_next ) {
929                 backsql_strfcat( &bsi->bsi_flt_where, "l",
930                         STRLENOF( " OR " ), " OR " );
931                 vat[i] = vat[i]->bam_next;
932                 goto next;
933         }
934
935         /* if more descendants of the same attr, apply */
936         i++;
937         if ( vat[i] ) {
938                 backsql_strfcat( &bsi->bsi_flt_where, "l",
939                         STRLENOF( " OR " ), " OR " );
940                 goto next;
941         }
942
943         /* if needed, close extra level of parens */
944         if ( done ) {
945                 backsql_strfcat( &bsi->bsi_flt_where, "c", ')' );
946         }
947
948         rc = 1;
949
950 done:;
951         if ( vat ) {
952                 ch_free( vat );
953         }
954
955         Debug( LDAP_DEBUG_TRACE,
956                         "<==backsql_process_filter() %s\n",
957                         rc == 1 ? "succeeded" : "failed", 0, 0);
958
959         return rc;
960 }
961
962 static int
963 backsql_process_filter_eq( backsql_srch_info *bsi, backsql_at_map_rec *at,
964                 int casefold, struct berval *filter_value )
965 {
966         /*
967          * maybe we should check type of at->sel_expr here somehow,
968          * to know whether upper_func is applicable, but for now
969          * upper_func stuff is made for Oracle, where UPPER is
970          * safely applicable to NUMBER etc.
971          */
972         if ( casefold && BACKSQL_AT_CANUPPERCASE( at ) ) {
973                 ber_len_t       start;
974
975                 backsql_strfcat( &bsi->bsi_flt_where, "cbl",
976                                 '(', /* ) */
977                                 &at->bam_sel_expr_u, 
978                                 (ber_len_t)STRLENOF( "='" ),
979                                         "='" );
980
981                 start = bsi->bsi_flt_where.bb_val.bv_len;
982
983                 backsql_strfcat( &bsi->bsi_flt_where, "bl",
984                                 filter_value, 
985                                 (ber_len_t)STRLENOF( /* (' */ "')" ),
986                                         /* (' */ "')" );
987
988                 ldap_pvt_str2upper( &bsi->bsi_flt_where.bb_val.bv_val[ start ] );
989
990         } else {
991                 backsql_strfcat( &bsi->bsi_flt_where, "cblbl",
992                                 '(', /* ) */
993                                 &at->bam_sel_expr,
994                                 (ber_len_t)STRLENOF( "='" ), "='",
995                                 filter_value,
996                                 (ber_len_t)STRLENOF( /* (' */ "')" ),
997                                         /* (' */ "')" );
998         }
999
1000         return 1;
1001 }
1002         
1003 static int
1004 backsql_process_filter_like( backsql_srch_info *bsi, backsql_at_map_rec *at,
1005                 int casefold, struct berval *filter_value )
1006 {
1007         /*
1008          * maybe we should check type of at->sel_expr here somehow,
1009          * to know whether upper_func is applicable, but for now
1010          * upper_func stuff is made for Oracle, where UPPER is
1011          * safely applicable to NUMBER etc.
1012          */
1013         if ( casefold && BACKSQL_AT_CANUPPERCASE( at ) ) {
1014                 ber_len_t       start;
1015
1016                 backsql_strfcat( &bsi->bsi_flt_where, "cbl",
1017                                 '(', /* ) */
1018                                 &at->bam_sel_expr_u, 
1019                                 (ber_len_t)STRLENOF( " LIKE '%" ),
1020                                         " LIKE '%" );
1021
1022                 start = bsi->bsi_flt_where.bb_val.bv_len;
1023
1024                 backsql_strfcat( &bsi->bsi_flt_where, "bl",
1025                                 filter_value, 
1026                                 (ber_len_t)STRLENOF( /* (' */ "%')" ),
1027                                         /* (' */ "%')" );
1028
1029                 ldap_pvt_str2upper( &bsi->bsi_flt_where.bb_val.bv_val[ start ] );
1030
1031         } else {
1032                 backsql_strfcat( &bsi->bsi_flt_where, "cblbl",
1033                                 '(', /* ) */
1034                                 &at->bam_sel_expr,
1035                                 (ber_len_t)STRLENOF( " LIKE '%" ),
1036                                         " LIKE '%",
1037                                 filter_value,
1038                                 (ber_len_t)STRLENOF( /* (' */ "%')" ),
1039                                         /* (' */ "%')" );
1040         }
1041
1042         return 1;
1043 }
1044
1045 static int
1046 backsql_process_filter_attr( backsql_srch_info *bsi, Filter *f, backsql_at_map_rec *at )
1047 {
1048         backsql_info            *bi = (backsql_info *)bsi->bsi_op->o_bd->be_private;
1049         int                     casefold = 0;
1050         struct berval           *filter_value = NULL;
1051         MatchingRule            *matching_rule = NULL;
1052         struct berval           ordering = BER_BVC("<=");
1053
1054         Debug( LDAP_DEBUG_TRACE, "==>backsql_process_filter_attr(%s)\n",
1055                 at->bam_ad->ad_cname.bv_val, 0, 0 );
1056
1057         /*
1058          * need to add this attribute to list of attrs to load,
1059          * so that we can do test_filter() later
1060          */
1061         backsql_attrlist_add( bsi, at->bam_ad );
1062
1063         backsql_merge_from_tbls( bsi, &at->bam_from_tbls );
1064
1065         if ( !BER_BVISNULL( &at->bam_join_where )
1066                         && strstr( bsi->bsi_join_where.bb_val.bv_val,
1067                                 at->bam_join_where.bv_val ) == NULL )
1068         {
1069                 backsql_strfcat( &bsi->bsi_join_where, "lb",
1070                                 (ber_len_t)STRLENOF( " AND " ), " AND ",
1071                                 &at->bam_join_where );
1072         }
1073
1074         switch ( f->f_choice ) {
1075         case LDAP_FILTER_EQUALITY:
1076                 filter_value = &f->f_av_value;
1077                 matching_rule = at->bam_ad->ad_type->sat_equality;
1078
1079                 goto equality_match;
1080
1081                 /* fail over into next case */
1082                 
1083         case LDAP_FILTER_EXT:
1084                 filter_value = &f->f_mra->ma_value;
1085                 matching_rule = f->f_mr_rule;
1086
1087 equality_match:;
1088                 /* always uppercase strings by now */
1089 #ifdef BACKSQL_UPPERCASE_FILTER
1090                 if ( SLAP_MR_ASSOCIATED( matching_rule,
1091                                         bi->sql_caseIgnoreMatch ) )
1092 #endif /* BACKSQL_UPPERCASE_FILTER */
1093                 {
1094                         casefold = 1;
1095                 }
1096
1097                 /* FIXME: directoryString filtering should use a similar
1098                  * approach to deal with non-prettified values like
1099                  * " A  non    prettified   value  ", by using a LIKE
1100                  * filter with all whitespaces collapsed to a single '%' */
1101                 if ( SLAP_MR_ASSOCIATED( matching_rule,
1102                                         bi->sql_telephoneNumberMatch ) )
1103                 {
1104                         struct berval   bv;
1105                         ber_len_t       i;
1106
1107                         /*
1108                          * to check for matching telephone numbers
1109                          * with intermized chars, e.g. val='1234'
1110                          * use
1111                          * 
1112                          * val LIKE '%1%2%3%4%'
1113                          */
1114
1115                         bv.bv_len = 2 * filter_value->bv_len - 1;
1116                         bv.bv_val = ch_malloc( bv.bv_len + 1 );
1117
1118                         bv.bv_val[ 0 ] = filter_value->bv_val[ 0 ];
1119                         for ( i = 1; i < filter_value->bv_len; i++ ) {
1120                                 bv.bv_val[ 2 * i - 1 ] = '%';
1121                                 bv.bv_val[ 2 * i ] = filter_value->bv_val[ i ];
1122                         }
1123                         bv.bv_val[ 2 * i - 1 ] = '\0';
1124
1125                         (void)backsql_process_filter_like( bsi, at, casefold, &bv );
1126                         ch_free( bv.bv_val );
1127
1128                         break;
1129                 }
1130
1131                 /* NOTE: this is required by objectClass inheritance 
1132                  * and auxiliary objectClass use in filters for slightly
1133                  * more efficient candidate selection. */
1134                 /* FIXME: a bit too many specializations to deal with
1135                  * very specific cases... */
1136                 if ( at->bam_ad == slap_schema.si_ad_objectClass
1137                                 || at->bam_ad == slap_schema.si_ad_structuralObjectClass )
1138                 {
1139                         backsql_strfcat( &bsi->bsi_flt_where, "lbl",
1140                                         (ber_len_t)STRLENOF( "(ldap_entries.id=ldap_entry_objclasses.entry_id AND ldap_entry_objclasses.oc_name='" /* ') */ ),
1141                                                 "(ldap_entries.id=ldap_entry_objclasses.entry_id AND ldap_entry_objclasses.oc_name='" /* ') */,
1142                                         filter_value,
1143                                         (ber_len_t)STRLENOF( /* (' */ "')" ),
1144                                                 /* (' */ "')" );
1145                         break;
1146                 }
1147
1148                 /*
1149                  * maybe we should check type of at->sel_expr here somehow,
1150                  * to know whether upper_func is applicable, but for now
1151                  * upper_func stuff is made for Oracle, where UPPER is
1152                  * safely applicable to NUMBER etc.
1153                  */
1154                 (void)backsql_process_filter_eq( bsi, at, casefold, filter_value );
1155                 break;
1156
1157         case LDAP_FILTER_GE:
1158                 ordering.bv_val = ">=";
1159
1160                 /* fall thru to next case */
1161                 
1162         case LDAP_FILTER_LE:
1163                 filter_value = &f->f_av_value;
1164                 
1165                 /* always uppercase strings by now */
1166 #ifdef BACKSQL_UPPERCASE_FILTER
1167                 if ( at->bam_ad->ad_type->sat_ordering &&
1168                                 SLAP_MR_ASSOCIATED( at->bam_ad->ad_type->sat_ordering,
1169                                         bi->sql_caseIgnoreMatch ) )
1170 #endif /* BACKSQL_UPPERCASE_FILTER */
1171                 {
1172                         casefold = 1;
1173                 }
1174
1175                 /*
1176                  * FIXME: should we uppercase the operands?
1177                  */
1178                 if ( casefold && BACKSQL_AT_CANUPPERCASE( at ) ) {
1179                         ber_len_t       start;
1180
1181                         backsql_strfcat( &bsi->bsi_flt_where, "cbbc",
1182                                         '(', /* ) */
1183                                         &at->bam_sel_expr_u, 
1184                                         &ordering,
1185                                         '\'' );
1186
1187                         start = bsi->bsi_flt_where.bb_val.bv_len;
1188
1189                         backsql_strfcat( &bsi->bsi_flt_where, "bl",
1190                                         filter_value, 
1191                                         (ber_len_t)STRLENOF( /* (' */ "')" ),
1192                                                 /* (' */ "')" );
1193
1194                         ldap_pvt_str2upper( &bsi->bsi_flt_where.bb_val.bv_val[ start ] );
1195                 
1196                 } else {
1197                         backsql_strfcat( &bsi->bsi_flt_where, "cbbcbl",
1198                                         '(' /* ) */ ,
1199                                         &at->bam_sel_expr,
1200                                         &ordering,
1201                                         '\'',
1202                                         &f->f_av_value,
1203                                         (ber_len_t)STRLENOF( /* (' */ "')" ),
1204                                                 /* ( */ "')" );
1205                 }
1206                 break;
1207
1208         case LDAP_FILTER_PRESENT:
1209                 backsql_strfcat( &bsi->bsi_flt_where, "lbl",
1210                                 (ber_len_t)STRLENOF( "NOT (" /* ) */),
1211                                         "NOT (", /* ) */
1212                                 &at->bam_sel_expr, 
1213                                 (ber_len_t)STRLENOF( /* ( */ " IS NULL)" ),
1214                                         /* ( */ " IS NULL)" );
1215                 break;
1216
1217         case LDAP_FILTER_SUBSTRINGS:
1218                 backsql_process_sub_filter( bsi, f, at );
1219                 break;
1220
1221         case LDAP_FILTER_APPROX:
1222                 /* we do our best */
1223
1224                 /*
1225                  * maybe we should check type of at->sel_expr here somehow,
1226                  * to know whether upper_func is applicable, but for now
1227                  * upper_func stuff is made for Oracle, where UPPER is
1228                  * safely applicable to NUMBER etc.
1229                  */
1230                 (void)backsql_process_filter_like( bsi, at, 1, &f->f_av_value );
1231                 break;
1232
1233         default:
1234                 /* unhandled filter type; should not happen */
1235                 assert( 0 );
1236                 backsql_strfcat( &bsi->bsi_flt_where, "l",
1237                                 (ber_len_t)STRLENOF( "8=8" ), "8=8" );
1238                 break;
1239
1240         }
1241
1242         Debug( LDAP_DEBUG_TRACE, "<==backsql_process_filter_attr(%s)\n",
1243                 at->bam_ad->ad_cname.bv_val, 0, 0 );
1244
1245         return 1;
1246 }
1247
1248 static int
1249 backsql_srch_query( backsql_srch_info *bsi, struct berval *query )
1250 {
1251         backsql_info    *bi = (backsql_info *)bsi->bsi_op->o_bd->be_private;
1252         int             rc;
1253
1254         assert( query );
1255         BER_BVZERO( query );
1256
1257         bsi->bsi_use_subtree_shortcut = 0;
1258
1259         Debug( LDAP_DEBUG_TRACE, "==>backsql_srch_query()\n", 0, 0, 0 );
1260         BER_BVZERO( &bsi->bsi_sel.bb_val );
1261         BER_BVZERO( &bsi->bsi_sel.bb_val );
1262         bsi->bsi_sel.bb_len = 0;
1263         BER_BVZERO( &bsi->bsi_from.bb_val );
1264         bsi->bsi_from.bb_len = 0;
1265         BER_BVZERO( &bsi->bsi_join_where.bb_val );
1266         bsi->bsi_join_where.bb_len = 0;
1267         BER_BVZERO( &bsi->bsi_flt_where.bb_val );
1268         bsi->bsi_flt_where.bb_len = 0;
1269
1270         backsql_strfcat( &bsi->bsi_sel, "lbcbc",
1271                         (ber_len_t)STRLENOF( "SELECT DISTINCT ldap_entries.id," ),
1272                                 "SELECT DISTINCT ldap_entries.id,", 
1273                         &bsi->bsi_oc->bom_keytbl, 
1274                         '.', 
1275                         &bsi->bsi_oc->bom_keycol, 
1276                         ',' );
1277
1278         if ( !BER_BVISNULL( &bi->sql_strcast_func ) ) {
1279                 backsql_strfcat( &bsi->bsi_sel, "blbl",
1280                                 &bi->sql_strcast_func, 
1281                                 (ber_len_t)STRLENOF( "('" /* ') */ ),
1282                                         "('" /* ') */ ,
1283                                 &bsi->bsi_oc->bom_oc->soc_cname,
1284                                 (ber_len_t)STRLENOF( /* (' */ "')" ),
1285                                         /* (' */ "')" );
1286         } else {
1287                 backsql_strfcat( &bsi->bsi_sel, "cbc",
1288                                 '\'',
1289                                 &bsi->bsi_oc->bom_oc->soc_cname,
1290                                 '\'' );
1291         }
1292         backsql_strfcat( &bsi->bsi_sel, "l",
1293                         (ber_len_t)STRLENOF( " " BACKSQL_ALIASING 
1294                                         BACKSQL_ALIASING_QUOTE "objectClass" BACKSQL_ALIASING_QUOTE 
1295                                         ",ldap_entries.dn " BACKSQL_ALIASING BACKSQL_ALIASING_QUOTE "dn" BACKSQL_ALIASING_QUOTE ),
1296                                 " " BACKSQL_ALIASING 
1297                                         BACKSQL_ALIASING_QUOTE "objectClass" BACKSQL_ALIASING_QUOTE
1298                                         ",ldap_entries.dn " BACKSQL_ALIASING BACKSQL_ALIASING_QUOTE "dn" BACKSQL_ALIASING_QUOTE );
1299
1300         backsql_strfcat( &bsi->bsi_from, "lb",
1301                         (ber_len_t)STRLENOF( " FROM ldap_entries," ),
1302                                 " FROM ldap_entries,",
1303                         &bsi->bsi_oc->bom_keytbl );
1304
1305         backsql_strfcat( &bsi->bsi_join_where, "lbcbl",
1306                         (ber_len_t)STRLENOF( " WHERE " ), " WHERE ",
1307                         &bsi->bsi_oc->bom_keytbl,
1308                         '.',
1309                         &bsi->bsi_oc->bom_keycol,
1310                         (ber_len_t)STRLENOF( "=ldap_entries.keyval AND ldap_entries.oc_map_id=? AND " ),
1311                                 "=ldap_entries.keyval AND ldap_entries.oc_map_id=? AND " );
1312
1313         switch ( bsi->bsi_scope ) {
1314         case LDAP_SCOPE_BASE:
1315                 if ( BACKSQL_CANUPPERCASE( bi ) ) {
1316                         backsql_strfcat( &bsi->bsi_join_where, "bl",
1317                                         &bi->sql_upper_func,
1318                                         (ber_len_t)STRLENOF( "(ldap_entries.dn)=?" ),
1319                                                 "(ldap_entries.dn)=?" );
1320                 } else {
1321                         backsql_strfcat( &bsi->bsi_join_where, "l",
1322                                         (ber_len_t)STRLENOF( "ldap_entries.dn=?" ),
1323                                                 "ldap_entries.dn=?" );
1324                 }
1325                 break;
1326                 
1327         case BACKSQL_SCOPE_BASE_LIKE:
1328                 if ( BACKSQL_CANUPPERCASE( bi ) ) {
1329                         backsql_strfcat( &bsi->bsi_join_where, "bl",
1330                                         &bi->sql_upper_func,
1331                                         (ber_len_t)STRLENOF( "(ldap_entries.dn) LIKE ?" ),
1332                                                 "(ldap_entries.dn) LIKE ?" );
1333                 } else {
1334                         backsql_strfcat( &bsi->bsi_join_where, "l",
1335                                         (ber_len_t)STRLENOF( "ldap_entries.dn LIKE ?" ),
1336                                                 "ldap_entries.dn LIKE ?" );
1337                 }
1338                 break;
1339                 
1340         case LDAP_SCOPE_ONELEVEL:
1341                 backsql_strfcat( &bsi->bsi_join_where, "l",
1342                                 (ber_len_t)STRLENOF( "ldap_entries.parent=?" ),
1343                                         "ldap_entries.parent=?" );
1344                 break;
1345
1346 #ifdef LDAP_SCOPE_SUBORDINATE
1347         case LDAP_SCOPE_SUBORDINATE:
1348 #endif /* LDAP_SCOPE_SUBORDINATE */
1349         case LDAP_SCOPE_SUBTREE:
1350                 if ( BACKSQL_USE_SUBTREE_SHORTCUT( bi ) ) {
1351                         int             i;
1352                         BackendDB       *bd = bsi->bsi_op->o_bd;
1353
1354                         assert( bd->be_nsuffix );
1355
1356                         for ( i = 0; !BER_BVISNULL( &bd->be_nsuffix[ i ] ); i++ )
1357                         {
1358                                 if ( dn_match( &bd->be_nsuffix[ i ],
1359                                                         bsi->bsi_base_ndn ) )
1360                                 {
1361                                         /* pass this to the candidate selection
1362                                          * routine so that the DN is not bound
1363                                          * to the select statement */
1364                                         bsi->bsi_use_subtree_shortcut = 1;
1365                                         break;
1366                                 }
1367                         }
1368                 }
1369
1370                 if ( bsi->bsi_use_subtree_shortcut ) {
1371                         /* Skip the base DN filter, as every entry will match it */
1372                         backsql_strfcat( &bsi->bsi_join_where, "l",
1373                                         (ber_len_t)STRLENOF( "9=9"), "9=9");
1374
1375                 } else if ( !BER_BVISNULL( &bi->sql_subtree_cond ) ) {
1376                         backsql_strfcat( &bsi->bsi_join_where, "b", &bi->sql_subtree_cond );
1377
1378                 } else if ( BACKSQL_CANUPPERCASE( bi ) ) {
1379                         backsql_strfcat( &bsi->bsi_join_where, "bl",
1380                                         &bi->sql_upper_func,
1381                                         (ber_len_t)STRLENOF( "(ldap_entries.dn) LIKE ?" ),
1382                                                 "(ldap_entries.dn) LIKE ?"  );
1383
1384                 } else {
1385                         backsql_strfcat( &bsi->bsi_join_where, "l",
1386                                         (ber_len_t)STRLENOF( "ldap_entries.dn LIKE ?" ),
1387                                                 "ldap_entries.dn LIKE ?" );
1388                 }
1389
1390                 break;
1391
1392         default:
1393                 assert( 0 );
1394         }
1395
1396         rc = backsql_process_filter( bsi, bsi->bsi_filter );
1397         if ( rc > 0 ) {
1398                 struct berbuf   bb = BB_NULL;
1399
1400                 backsql_strfcat( &bb, "bbblb",
1401                                 &bsi->bsi_sel.bb_val,
1402                                 &bsi->bsi_from.bb_val, 
1403                                 &bsi->bsi_join_where.bb_val,
1404                                 (ber_len_t)STRLENOF( " AND " ), " AND ",
1405                                 &bsi->bsi_flt_where.bb_val );
1406
1407                 *query = bb.bb_val;
1408
1409         } else if ( rc < 0 ) {
1410                 /* 
1411                  * Indicates that there's no possible way the filter matches
1412                  * anything.  No need to issue the query
1413                  */
1414                 free( query->bv_val );
1415                 BER_BVZERO( query );
1416         }
1417  
1418         free( bsi->bsi_sel.bb_val.bv_val );
1419         BER_BVZERO( &bsi->bsi_sel.bb_val );
1420         bsi->bsi_sel.bb_len = 0;
1421         free( bsi->bsi_from.bb_val.bv_val );
1422         BER_BVZERO( &bsi->bsi_from.bb_val );
1423         bsi->bsi_from.bb_len = 0;
1424         free( bsi->bsi_join_where.bb_val.bv_val );
1425         BER_BVZERO( &bsi->bsi_join_where.bb_val );
1426         bsi->bsi_join_where.bb_len = 0;
1427         free( bsi->bsi_flt_where.bb_val.bv_val );
1428         BER_BVZERO( &bsi->bsi_flt_where.bb_val );
1429         bsi->bsi_flt_where.bb_len = 0;
1430         
1431         Debug( LDAP_DEBUG_TRACE, "<==backsql_srch_query() returns %s\n",
1432                 query->bv_val ? query->bv_val : "NULL", 0, 0 );
1433         
1434         return ( rc <= 0 ? 1 : 0 );
1435 }
1436
1437 static int
1438 backsql_oc_get_candidates( void *v_oc, void *v_bsi )
1439 {
1440         backsql_oc_map_rec      *oc = v_oc;
1441         backsql_srch_info       *bsi = v_bsi;
1442         Operation               *op = bsi->bsi_op;
1443         backsql_info            *bi = (backsql_info *)bsi->bsi_op->o_bd->be_private;
1444         struct berval           query;
1445         SQLHSTMT                sth = SQL_NULL_HSTMT;
1446         RETCODE                 rc;
1447         int                     res;
1448         BACKSQL_ROW_NTS         row;
1449         int                     i;
1450         int                     j;
1451         int                     n_candidates = bsi->bsi_n_candidates;
1452
1453         /* 
1454          * + 1 because we need room for '%';
1455          * + 1 because we need room for ',' for LDAP_SCOPE_SUBORDINATE;
1456          * this makes a subtree
1457          * search for a DN BACKSQL_MAX_DN_LEN long legal 
1458          * if it returns that DN only
1459          */
1460         char                    tmp_base_ndn[ BACKSQL_MAX_DN_LEN + 1 + 1 ];
1461
1462         bsi->bsi_status = LDAP_SUCCESS;
1463  
1464         Debug( LDAP_DEBUG_TRACE, "==>backsql_oc_get_candidates(): oc=\"%s\"\n",
1465                         BACKSQL_OC_NAME( oc ), 0, 0 );
1466
1467         if ( bsi->bsi_n_candidates == -1 ) {
1468                 Debug( LDAP_DEBUG_TRACE, "backsql_oc_get_candidates(): "
1469                         "unchecked limit has been overcome\n", 0, 0, 0 );
1470                 /* should never get here */
1471                 assert( 0 );
1472                 bsi->bsi_status = LDAP_ADMINLIMIT_EXCEEDED;
1473                 return BACKSQL_AVL_STOP;
1474         }
1475         
1476         bsi->bsi_oc = oc;
1477         res = backsql_srch_query( bsi, &query );
1478         if ( res ) {
1479                 Debug( LDAP_DEBUG_TRACE, "backsql_oc_get_candidates(): "
1480                         "error while constructing query for objectclass \"%s\"\n",
1481                         oc->bom_oc->soc_cname.bv_val, 0, 0 );
1482                 /*
1483                  * FIXME: need to separate errors from legally
1484                  * impossible filters
1485                  */
1486                 switch ( bsi->bsi_status ) {
1487                 case LDAP_SUCCESS:
1488                 case LDAP_UNDEFINED_TYPE:
1489                 case LDAP_NO_SUCH_OBJECT:
1490                         /* we are conservative... */
1491                 default:
1492                         bsi->bsi_status = LDAP_SUCCESS;
1493                         /* try next */
1494                         return BACKSQL_AVL_CONTINUE;
1495
1496                 case LDAP_ADMINLIMIT_EXCEEDED:
1497                 case LDAP_OTHER:
1498                         /* don't try any more */
1499                         return BACKSQL_AVL_STOP;
1500                 }
1501         }
1502
1503         if ( BER_BVISNULL( &query ) ) {
1504                 Debug( LDAP_DEBUG_TRACE, "backsql_oc_get_candidates(): "
1505                         "could not construct query for objectclass \"%s\"\n",
1506                         oc->bom_oc->soc_cname.bv_val, 0, 0 );
1507                 bsi->bsi_status = LDAP_SUCCESS;
1508                 return BACKSQL_AVL_CONTINUE;
1509         }
1510
1511         Debug( LDAP_DEBUG_TRACE, "Constructed query: %s\n", 
1512                         query.bv_val, 0, 0 );
1513
1514         rc = backsql_Prepare( bsi->bsi_dbh, &sth, query.bv_val, 0 );
1515         free( query.bv_val );
1516         BER_BVZERO( &query );
1517         if ( rc != SQL_SUCCESS ) {
1518                 Debug( LDAP_DEBUG_TRACE, "backsql_oc_get_candidates(): "
1519                         "error preparing query\n", 0, 0, 0 );
1520                 backsql_PrintErrors( bi->sql_db_env, bsi->bsi_dbh, sth, rc );
1521                 bsi->bsi_status = LDAP_OTHER;
1522                 return BACKSQL_AVL_CONTINUE;
1523         }
1524         
1525         Debug( LDAP_DEBUG_TRACE, "id: '%ld'\n", bsi->bsi_oc->bom_id, 0, 0 );
1526
1527         rc = backsql_BindParamInt( sth, 1, SQL_PARAM_INPUT,
1528                         &bsi->bsi_oc->bom_id );
1529         if ( rc != SQL_SUCCESS ) {
1530                 Debug( LDAP_DEBUG_TRACE, "backsql_oc_get_candidates(): "
1531                         "error binding objectclass id parameter\n", 0, 0, 0 );
1532                 bsi->bsi_status = LDAP_OTHER;
1533                 return BACKSQL_AVL_CONTINUE;
1534         }
1535
1536         switch ( bsi->bsi_scope ) {
1537         case LDAP_SCOPE_BASE:
1538         case BACKSQL_SCOPE_BASE_LIKE:
1539                 /*
1540                  * We do not accept DNs longer than BACKSQL_MAX_DN_LEN;
1541                  * however this should be handled earlier
1542                  */
1543                 if ( bsi->bsi_base_ndn->bv_len > BACKSQL_MAX_DN_LEN ) {
1544                         bsi->bsi_status = LDAP_OTHER;
1545                         return BACKSQL_AVL_CONTINUE;
1546                 }
1547
1548                 AC_MEMCPY( tmp_base_ndn, bsi->bsi_base_ndn->bv_val,
1549                                 bsi->bsi_base_ndn->bv_len + 1 );
1550
1551                 /* uppercase DN only if the stored DN can be uppercased
1552                  * for comparison */
1553                 if ( BACKSQL_CANUPPERCASE( bi ) ) {
1554                         ldap_pvt_str2upper( tmp_base_ndn );
1555                 }
1556
1557                 Debug( LDAP_DEBUG_TRACE, "(base)dn: \"%s\"\n",
1558                                 tmp_base_ndn, 0, 0 );
1559
1560                 rc = backsql_BindParamStr( sth, 2, SQL_PARAM_INPUT,
1561                                 tmp_base_ndn, BACKSQL_MAX_DN_LEN );
1562                 if ( rc != SQL_SUCCESS ) {
1563                         Debug( LDAP_DEBUG_TRACE, "backsql_oc_get_candidates(): "
1564                                 "error binding base_ndn parameter\n", 0, 0, 0 );
1565                         backsql_PrintErrors( bi->sql_db_env, bsi->bsi_dbh, 
1566                                         sth, rc );
1567                         bsi->bsi_status = LDAP_OTHER;
1568                         return BACKSQL_AVL_CONTINUE;
1569                 }
1570                 break;
1571
1572 #ifdef LDAP_SCOPE_SUBORDINATE
1573         case LDAP_SCOPE_SUBORDINATE:
1574 #endif /* LDAP_SCOPE_SUBORDINATE */
1575         case LDAP_SCOPE_SUBTREE:
1576         {
1577                 /* if short-cutting the search base,
1578                  * don't bind any parameter */
1579                 if ( bsi->bsi_use_subtree_shortcut ) {
1580                         break;
1581                 }
1582                 
1583                 /*
1584                  * We do not accept DNs longer than BACKSQL_MAX_DN_LEN;
1585                  * however this should be handled earlier
1586                  */
1587                 if ( bsi->bsi_base_ndn->bv_len > BACKSQL_MAX_DN_LEN ) {
1588                         bsi->bsi_status = LDAP_OTHER;
1589                         return BACKSQL_AVL_CONTINUE;
1590                 }
1591
1592                 /* 
1593                  * Sets the parameters for the SQL built earlier
1594                  * NOTE that all the databases could actually use 
1595                  * the TimesTen version, which would be cleaner 
1596                  * and would also eliminate the need for the
1597                  * subtree_cond line in the configuration file.  
1598                  * For now, I'm leaving it the way it is, 
1599                  * so non-TimesTen databases use the original code.
1600                  * But at some point this should get cleaned up.
1601                  *
1602                  * If "dn" is being used, do a suffix search.
1603                  * If "dn_ru" is being used, do a prefix search.
1604                  */
1605                 if ( BACKSQL_HAS_LDAPINFO_DN_RU( bi ) ) {
1606                         tmp_base_ndn[ 0 ] = '\0';
1607
1608                         for ( i = 0, j = bsi->bsi_base_ndn->bv_len - 1;
1609                                         j >= 0; i++, j--) {
1610                                 tmp_base_ndn[ i ] = bsi->bsi_base_ndn->bv_val[ j ];
1611                         }
1612
1613 #ifdef LDAP_SCOPE_SUBORDINATE
1614                         if ( bsi->bsi_scope == LDAP_SCOPE_SUBORDINATE ) {
1615                                 tmp_base_ndn[ i++ ] = ',';
1616                         }
1617 #endif /* LDAP_SCOPE_SUBORDINATE */
1618
1619                         tmp_base_ndn[ i ] = '%';
1620                         tmp_base_ndn[ i + 1 ] = '\0';
1621
1622                 } else {
1623                         i = 0;
1624
1625                         tmp_base_ndn[ i++ ] = '%';
1626
1627 #ifdef LDAP_SCOPE_SUBORDINATE
1628                         if ( bsi->bsi_scope == LDAP_SCOPE_SUBORDINATE ) {
1629                                 tmp_base_ndn[ i++ ] = ',';
1630                         }
1631 #endif /* LDAP_SCOPE_SUBORDINATE */
1632
1633                         AC_MEMCPY( &tmp_base_ndn[ i ], bsi->bsi_base_ndn->bv_val,
1634                                 bsi->bsi_base_ndn->bv_len + 1 );
1635                 }
1636
1637                 /* uppercase DN only if the stored DN can be uppercased
1638                  * for comparison */
1639                 if ( BACKSQL_CANUPPERCASE( bi ) ) {
1640                         ldap_pvt_str2upper( tmp_base_ndn );
1641                 }
1642
1643 #ifdef LDAP_SCOPE_SUBORDINATE
1644                 if ( bsi->bsi_scope == LDAP_SCOPE_SUBORDINATE ) {
1645                         Debug( LDAP_DEBUG_TRACE, "(children)dn: \"%s\"\n",
1646                                 tmp_base_ndn, 0, 0 );
1647                 } else 
1648 #endif /* LDAP_SCOPE_SUBORDINATE */
1649                 {
1650                         Debug( LDAP_DEBUG_TRACE, "(sub)dn: \"%s\"\n",
1651                                 tmp_base_ndn, 0, 0 );
1652                 }
1653
1654                 rc = backsql_BindParamStr( sth, 2, SQL_PARAM_INPUT,
1655                                 tmp_base_ndn, BACKSQL_MAX_DN_LEN );
1656                 if ( rc != SQL_SUCCESS ) {
1657                         Debug( LDAP_DEBUG_TRACE, "backsql_oc_get_candidates(): "
1658                                 "error binding base_ndn parameter (2)\n",
1659                                 0, 0, 0 );
1660                         backsql_PrintErrors( bi->sql_db_env, bsi->bsi_dbh, 
1661                                         sth, rc );
1662                         bsi->bsi_status = LDAP_OTHER;
1663                         return BACKSQL_AVL_CONTINUE;
1664                 }
1665                 break;
1666         }
1667
1668         case LDAP_SCOPE_ONELEVEL:
1669                 assert( !BER_BVISNULL( &bsi->bsi_base_id.eid_ndn ) );
1670
1671 #ifdef BACKSQL_ARBITRARY_KEY
1672                 Debug( LDAP_DEBUG_TRACE, "(one)id: \"%s\"\n",
1673                                 bsi->bsi_base_id.eid_id.bv_val, 0, 0 );
1674 #else /* ! BACKSQL_ARBITRARY_KEY */
1675                 Debug( LDAP_DEBUG_TRACE, "(one)id: '%lu'\n",
1676                                 bsi->bsi_base_id.eid_id, 0, 0 );
1677 #endif /* ! BACKSQL_ARBITRARY_KEY */
1678                 rc = backsql_BindParamID( sth, 2, SQL_PARAM_INPUT,
1679                                 &bsi->bsi_base_id.eid_id );
1680                 if ( rc != SQL_SUCCESS ) {
1681                         Debug( LDAP_DEBUG_TRACE, "backsql_oc_get_candidates(): "
1682                                 "error binding base id parameter\n", 0, 0, 0 );
1683                         bsi->bsi_status = LDAP_OTHER;
1684                         return BACKSQL_AVL_CONTINUE;
1685                 }
1686                 break;
1687         }
1688         
1689         rc = SQLExecute( sth );
1690         if ( !BACKSQL_SUCCESS( rc ) ) {
1691                 Debug( LDAP_DEBUG_TRACE, "backsql_oc_get_candidates(): "
1692                         "error executing query\n", 0, 0, 0 );
1693                 backsql_PrintErrors( bi->sql_db_env, bsi->bsi_dbh, sth, rc );
1694                 SQLFreeStmt( sth, SQL_DROP );
1695                 bsi->bsi_status = LDAP_OTHER;
1696                 return BACKSQL_AVL_CONTINUE;
1697         }
1698
1699         backsql_BindRowAsStrings( sth, &row );
1700         rc = SQLFetch( sth );
1701         for ( ; BACKSQL_SUCCESS( rc ); rc = SQLFetch( sth ) ) {
1702                 struct berval           dn, pdn, ndn;
1703                 backsql_entryID         *c_id = NULL;
1704                 int                     ret;
1705
1706                 ber_str2bv( row.cols[ 3 ], 0, 0, &dn );
1707
1708                 if ( backsql_api_odbc2dn( bsi->bsi_op, bsi->bsi_rs, &dn ) ) {
1709                         continue;
1710                 }
1711
1712                 ret = dnPrettyNormal( NULL, &dn, &pdn, &ndn, op->o_tmpmemctx );
1713                 if ( dn.bv_val != row.cols[ 3 ] ) {
1714                         free( dn.bv_val );
1715                 }
1716
1717                 if ( ret != LDAP_SUCCESS ) {
1718                         continue;
1719                 }
1720
1721                 if ( bi->sql_baseObject && dn_match( &ndn, &bi->sql_baseObject->e_nname ) ) {
1722                         op->o_tmpfree( pdn.bv_val, op->o_tmpmemctx );
1723                         op->o_tmpfree( ndn.bv_val, op->o_tmpmemctx );
1724                         continue;
1725                 }
1726
1727                 c_id = (backsql_entryID *)ch_calloc( 1, 
1728                                 sizeof( backsql_entryID ) );
1729 #ifdef BACKSQL_ARBITRARY_KEY
1730                 ber_str2bv_x( row.cols[ 0 ], 0, 1, &c_id->eid_id,
1731                                 op->o_tmpmemctx );
1732                 ber_str2bv_x( row.cols[ 1 ], 0, 1, &c_id->eid_keyval,
1733                                 op->o_tmpmemctx );
1734 #else /* ! BACKSQL_ARBITRARY_KEY */
1735                 c_id->eid_id = strtol( row.cols[ 0 ], NULL, 0 );
1736                 c_id->eid_keyval = strtol( row.cols[ 1 ], NULL, 0 );
1737 #endif /* ! BACKSQL_ARBITRARY_KEY */
1738                 c_id->eid_oc_id = bsi->bsi_oc->bom_id;
1739
1740                 c_id->eid_dn = pdn;
1741                 c_id->eid_ndn = ndn;
1742
1743                 /* append at end of list ... */
1744                 c_id->eid_next = NULL;
1745                 *bsi->bsi_id_listtail = c_id;
1746                 bsi->bsi_id_listtail = &c_id->eid_next;
1747
1748 #ifdef BACKSQL_ARBITRARY_KEY
1749                 Debug( LDAP_DEBUG_TRACE, "backsql_oc_get_candidates(): "
1750                         "added entry id=%s, keyval=%s dn=\"%s\"\n",
1751                         c_id->eid_id.bv_val, c_id->eid_keyval.bv_val,
1752                         row.cols[ 3 ] );
1753 #else /* ! BACKSQL_ARBITRARY_KEY */
1754                 Debug( LDAP_DEBUG_TRACE, "backsql_oc_get_candidates(): "
1755                         "added entry id=%ld, keyval=%ld dn=\"%s\"\n",
1756                         c_id->eid_id, c_id->eid_keyval, row.cols[ 3 ] );
1757 #endif /* ! BACKSQL_ARBITRARY_KEY */
1758
1759                 /* count candidates, for unchecked limit */
1760                 bsi->bsi_n_candidates--;
1761                 if ( bsi->bsi_n_candidates == -1 ) {
1762                         break;
1763                 }
1764         }
1765         backsql_FreeRow( &row );
1766         SQLFreeStmt( sth, SQL_DROP );
1767
1768         Debug( LDAP_DEBUG_TRACE, "<==backsql_oc_get_candidates(): %d\n",
1769                         n_candidates - bsi->bsi_n_candidates, 0, 0 );
1770
1771         return ( bsi->bsi_n_candidates == -1 ? BACKSQL_AVL_STOP : BACKSQL_AVL_CONTINUE );
1772 }
1773
1774 int
1775 backsql_search( Operation *op, SlapReply *rs )
1776 {
1777         backsql_info            *bi = (backsql_info *)op->o_bd->be_private;
1778         SQLHDBC                 dbh = SQL_NULL_HDBC;
1779         int                     sres;
1780         Entry                   user_entry = { 0 },
1781                                 base_entry = { 0 };
1782         int                     manageDSAit = get_manageDSAit( op );
1783         time_t                  stoptime = 0;
1784         backsql_srch_info       bsi = { 0 };
1785         backsql_entryID         *eid = NULL;
1786         struct berval           nbase = BER_BVNULL;
1787
1788         Debug( LDAP_DEBUG_TRACE, "==>backsql_search(): "
1789                 "base=\"%s\", filter=\"%s\", scope=%d,", 
1790                 op->o_req_ndn.bv_val,
1791                 op->ors_filterstr.bv_val ? op->ors_filterstr.bv_val : "(no filter)",
1792                 op->ors_scope );
1793         Debug( LDAP_DEBUG_TRACE, " deref=%d, attrsonly=%d, "
1794                 "attributes to load: %s\n",
1795                 op->ors_deref,
1796                 op->ors_attrsonly,
1797                 op->ors_attrs == NULL ? "all" : "custom list" );
1798
1799         if ( op->o_req_ndn.bv_len > BACKSQL_MAX_DN_LEN ) {
1800                 Debug( LDAP_DEBUG_TRACE, "backsql_search(): "
1801                         "search base length (%ld) exceeds max length (%d)\n", 
1802                         op->o_req_ndn.bv_len, BACKSQL_MAX_DN_LEN, 0 );
1803                 /*
1804                  * FIXME: a LDAP_NO_SUCH_OBJECT could be appropriate
1805                  * since it is impossible that such a long DN exists
1806                  * in the backend
1807                  */
1808                 rs->sr_err = LDAP_ADMINLIMIT_EXCEEDED;
1809                 send_ldap_result( op, rs );
1810                 return 1;
1811         }
1812
1813         sres = backsql_get_db_conn( op, &dbh );
1814         if ( sres != LDAP_SUCCESS ) {
1815                 Debug( LDAP_DEBUG_TRACE, "backsql_search(): "
1816                         "could not get connection handle - exiting\n", 
1817                         0, 0, 0 );
1818                 rs->sr_err = sres;
1819                 rs->sr_text = sres == LDAP_OTHER ?  "SQL-backend error" : NULL;
1820                 send_ldap_result( op, rs );
1821                 return 1;
1822         }
1823
1824         /* compute it anyway; root does not use it */
1825         stoptime = op->o_time + op->ors_tlimit;
1826
1827         /* init search */
1828         bsi.bsi_e = &base_entry;
1829         rs->sr_err = backsql_init_search( &bsi, &op->o_req_ndn,
1830                         op->ors_scope,
1831                         op->ors_slimit, op->ors_tlimit,
1832                         stoptime, op->ors_filter,
1833                         dbh, op, rs, op->ors_attrs,
1834                         ( BACKSQL_ISF_MATCHED | BACKSQL_ISF_GET_ENTRY ) );
1835         switch ( rs->sr_err ) {
1836         case LDAP_SUCCESS:
1837                 break;
1838
1839         case LDAP_REFERRAL:
1840                 if ( manageDSAit && !BER_BVISNULL( &bsi.bsi_e->e_nname ) &&
1841                                 dn_match( &op->o_req_ndn, &bsi.bsi_e->e_nname ) )
1842                 {
1843                         rs->sr_err = LDAP_SUCCESS;
1844                         rs->sr_text = NULL;
1845                         rs->sr_matched = NULL;
1846                         if ( rs->sr_ref ) {
1847                                 ber_bvarray_free( rs->sr_ref );
1848                                 rs->sr_ref = NULL;
1849                         }
1850                         break;
1851                 }
1852                 /* fall thru */
1853
1854         default:
1855 #ifdef SLAP_ACL_HONOR_DISCLOSE
1856                 if ( !BER_BVISNULL( &base_entry.e_nname )
1857                                 && ! access_allowed( op, &base_entry,
1858                                         slap_schema.si_ad_entry, NULL,
1859                                         ACL_DISCLOSE, NULL ) )
1860                 {
1861                         rs->sr_err = LDAP_NO_SUCH_OBJECT;
1862                         if ( rs->sr_ref ) {
1863                                 ber_bvarray_free( rs->sr_ref );
1864                                 rs->sr_ref = NULL;
1865                         }
1866                         rs->sr_matched = NULL;
1867                         rs->sr_text = NULL;
1868                 }
1869 #endif /* SLAP_ACL_HONOR_DISCLOSE */
1870
1871                 send_ldap_result( op, rs );
1872                 goto done;
1873
1874         }
1875 #ifdef SLAP_ACL_HONOR_DISCLOSE
1876         /* NOTE: __NEW__ "search" access is required
1877          * on searchBase object */
1878         {
1879                 slap_mask_t     mask;
1880                 
1881                 if ( get_assert( op ) &&
1882                                 ( test_filter( op, &base_entry, get_assertion( op ) )
1883                                   != LDAP_COMPARE_TRUE ) )
1884                 {
1885                         rs->sr_err = LDAP_ASSERTION_FAILED;
1886                         
1887                 }
1888                 if ( ! access_allowed_mask( op, &base_entry,
1889                                         slap_schema.si_ad_entry,
1890                                         NULL, ACL_SEARCH, NULL, &mask ) )
1891                 {
1892                         if ( rs->sr_err == LDAP_SUCCESS ) {
1893                                 rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
1894                         }
1895                 }
1896
1897                 if ( rs->sr_err != LDAP_SUCCESS ) {
1898                         if ( !ACL_GRANT( mask, ACL_DISCLOSE ) ) {
1899                                 rs->sr_err = LDAP_NO_SUCH_OBJECT;
1900                                 rs->sr_text = NULL;
1901                         }
1902                         send_ldap_result( op, rs );
1903                         goto done;
1904                 }
1905         }
1906 #endif /* SLAP_ACL_HONOR_DISCLOSE */
1907
1908         bsi.bsi_e = NULL;
1909
1910         bsi.bsi_n_candidates =
1911                 ( op->ors_limit == NULL /* isroot == TRUE */ ? -2 : 
1912                 ( op->ors_limit->lms_s_unchecked == -1 ? -2 :
1913                 ( op->ors_limit->lms_s_unchecked ) ) );
1914
1915         switch ( bsi.bsi_scope ) {
1916         case LDAP_SCOPE_BASE:
1917         case BACKSQL_SCOPE_BASE_LIKE:
1918                 /*
1919                  * probably already found...
1920                  */
1921                 bsi.bsi_id_list = &bsi.bsi_base_id;
1922                 bsi.bsi_id_listtail = &bsi.bsi_base_id.eid_next;
1923                 break;
1924
1925         case LDAP_SCOPE_SUBTREE:
1926                 /*
1927                  * if baseObject is defined, and if it is the root 
1928                  * of the search, add it to the candidate list
1929                  */
1930                 if ( bi->sql_baseObject && BACKSQL_IS_BASEOBJECT_ID( &bsi.bsi_base_id.eid_id ) )
1931                 {
1932                         bsi.bsi_id_list = &bsi.bsi_base_id;
1933                         bsi.bsi_id_listtail = &bsi.bsi_base_id.eid_next;
1934                 }
1935
1936                 /* FALLTHRU */
1937         default:
1938
1939                 /*
1940                  * for each objectclass we try to construct query which gets IDs
1941                  * of entries matching LDAP query filter and scope (or at least 
1942                  * candidates), and get the IDs
1943                  */
1944                 avl_apply( bi->sql_oc_by_oc, backsql_oc_get_candidates,
1945                                 &bsi, BACKSQL_AVL_STOP, AVL_INORDER );
1946         }
1947
1948         if ( op->ors_limit != NULL      /* isroot == FALSE */
1949                         && op->ors_limit->lms_s_unchecked != -1
1950                         && bsi.bsi_n_candidates == -1 )
1951         {
1952                 rs->sr_err = LDAP_ADMINLIMIT_EXCEEDED;
1953                 send_ldap_result( op, rs );
1954                 goto done;
1955         }
1956
1957         /*
1958          * now we load candidate entries (only those attributes 
1959          * mentioned in attrs and filter), test it against full filter 
1960          * and then send to client; don't free entry_id if baseObject...
1961          */
1962         for ( eid = bsi.bsi_id_list;
1963                         eid != NULL; 
1964                         eid = backsql_free_entryID( op,
1965                                 eid, eid == &bsi.bsi_base_id ? 0 : 1 ) )
1966         {
1967                 int             rc;
1968                 Attribute       *a_hasSubordinate = NULL,
1969                                 *a_entryUUID = NULL,
1970                                 *a_entryCSN = NULL,
1971                                 **ap = NULL;
1972                 Entry           *e = NULL;
1973
1974                 /* check for abandon */
1975                 if ( op->o_abandon ) {
1976                         break;
1977                 }
1978
1979                 /* check time limit */
1980                 if ( op->ors_tlimit != SLAP_NO_LIMIT
1981                                 && slap_get_time() > stoptime )
1982                 {
1983                         rs->sr_err = LDAP_TIMELIMIT_EXCEEDED;
1984                         rs->sr_ctrls = NULL;
1985                         rs->sr_ref = rs->sr_v2ref;
1986                         goto send_results;
1987                 }
1988
1989 #ifdef BACKSQL_ARBITRARY_KEY
1990                 Debug(LDAP_DEBUG_TRACE, "backsql_search(): loading data "
1991                         "for entry id=%s, oc_id=%ld, keyval=%s\n",
1992                         eid->eid_id.bv_val, eid->eid_oc_id,
1993                         eid->eid_keyval.bv_val );
1994 #else /* ! BACKSQL_ARBITRARY_KEY */
1995                 Debug(LDAP_DEBUG_TRACE, "backsql_search(): loading data "
1996                         "for entry id=%ld, oc_id=%ld, keyval=%ld\n",
1997                         eid->eid_id, eid->eid_oc_id, eid->eid_keyval );
1998 #endif /* ! BACKSQL_ARBITRARY_KEY */
1999
2000                 /* check scope */
2001                 switch ( op->ors_scope ) {
2002                 case LDAP_SCOPE_BASE:
2003                 case BACKSQL_SCOPE_BASE_LIKE:
2004                         if ( !dn_match( &eid->eid_ndn, &op->o_req_ndn ) ) {
2005                                 goto next_entry2;
2006                         }
2007                         break;
2008
2009                 case LDAP_SCOPE_ONE:
2010                 {
2011                         struct berval   rdn = eid->eid_ndn;
2012
2013                         rdn.bv_len -= op->o_req_ndn.bv_len + STRLENOF( "," );
2014                         if ( !dnIsOneLevelRDN( &rdn ) ) {
2015                                 goto next_entry2;
2016                         }
2017                         /* fall thru */
2018                 }
2019
2020 #ifdef LDAP_SCOPE_SUBORDINATE
2021                 case LDAP_SCOPE_SUBORDINATE:
2022                         /* discard the baseObject entry */
2023                         if ( dn_match( &eid->eid_ndn, &op->o_req_ndn ) ) {
2024                                 goto next_entry2;
2025                         }
2026                 /* FALLTHRU */
2027 #endif /* LDAP_SCOPE_SUBORDINATE */
2028
2029                 case LDAP_SCOPE_SUBTREE:
2030                         /* FIXME: this should never fail... */
2031                         if ( !dnIsSuffix( &eid->eid_ndn, &op->o_req_ndn ) ) {
2032                                 assert( 0 );
2033                                 goto next_entry2;
2034                         }
2035                         break;
2036                 }
2037
2038                 if ( BACKSQL_IS_BASEOBJECT_ID( &eid->eid_id ) ) {
2039                         /* don't recollect baseObject... */
2040                         e = bi->sql_baseObject;
2041
2042                 } else if ( eid == &bsi.bsi_base_id ) {
2043                         /* don't recollect searchBase object... */
2044                         e = &base_entry;
2045
2046                 } else {
2047                         bsi.bsi_e = &user_entry;
2048                         rc = backsql_id2entry( &bsi, eid );
2049                         if ( rc != LDAP_SUCCESS ) {
2050                                 Debug( LDAP_DEBUG_TRACE, "backsql_search(): "
2051                                         "error %d in backsql_id2entry() "
2052                                         "- skipping\n", rc, 0, 0 );
2053                                 continue;
2054                         }
2055                         e = &user_entry;
2056                 }
2057
2058                 if ( !manageDSAit &&
2059                                 op->ors_scope != LDAP_SCOPE_BASE &&
2060                                 op->ors_scope != BACKSQL_SCOPE_BASE_LIKE &&
2061                                 is_entry_referral( e ) )
2062                 {
2063                         BerVarray refs;
2064
2065                         refs = get_entry_referrals( op, e );
2066                         if ( !refs ) {
2067                                 backsql_srch_info       bsi2 = { 0 };
2068                                 Entry                   user_entry2 = { 0 };
2069
2070                                 /* retry with the full entry... */
2071                                 bsi2.bsi_e = &user_entry2;
2072                                 rc = backsql_init_search( &bsi2,
2073                                                 &e->e_nname,
2074                                                 LDAP_SCOPE_BASE, 
2075                                                 SLAP_NO_LIMIT, SLAP_NO_LIMIT,
2076                                                 (time_t)(-1), NULL,
2077                                                 dbh, op, rs, NULL,
2078                                                 BACKSQL_ISF_GET_ENTRY );
2079                                 if ( rc == LDAP_SUCCESS ) {
2080                                         if ( is_entry_referral( &user_entry2 ) )
2081                                         {
2082                                                 refs = get_entry_referrals( op,
2083                                                                 &user_entry2 );
2084                                         } else {
2085                                                 rs->sr_err = LDAP_OTHER;
2086                                         }
2087                                         entry_clean( &user_entry2 );
2088                                 }
2089                                 if ( bsi2.bsi_attrs != NULL ) {
2090                                         op->o_tmpfree( bsi2.bsi_attrs,
2091                                                         op->o_tmpmemctx );
2092                                 }
2093                         }
2094
2095                         if ( refs ) {
2096                                 rs->sr_ref = referral_rewrite( refs,
2097                                                 &e->e_name,
2098                                                 &op->o_req_dn,
2099                                                 op->ors_scope );
2100                                 ber_bvarray_free( refs );
2101                         }
2102
2103                         if ( rs->sr_ref ) {
2104                                 rs->sr_err = LDAP_REFERRAL;
2105
2106                         } else {
2107                                 rs->sr_text = "bad referral object";
2108                         }
2109
2110                         rs->sr_entry = e;
2111                         rs->sr_matched = user_entry.e_name.bv_val;
2112                         send_search_reference( op, rs );
2113
2114                         ber_bvarray_free( rs->sr_ref );
2115                         rs->sr_ref = NULL;
2116                         rs->sr_matched = NULL;
2117                         rs->sr_entry = NULL;
2118
2119                         goto next_entry;
2120                 }
2121
2122                 /*
2123                  * We use this flag since we need to parse the filter
2124                  * anyway; we should have used the frontend API function
2125                  * filter_has_subordinates()
2126                  */
2127                 if ( bsi.bsi_flags & BSQL_SF_FILTER_HASSUBORDINATE ) {
2128                         rc = backsql_has_children( bi, dbh, &e->e_nname );
2129
2130                         switch ( rc ) {
2131                         case LDAP_COMPARE_TRUE:
2132                         case LDAP_COMPARE_FALSE:
2133                                 a_hasSubordinate = slap_operational_hasSubordinate( rc == LDAP_COMPARE_TRUE );
2134                                 if ( a_hasSubordinate != NULL ) {
2135                                         for ( ap = &user_entry.e_attrs; 
2136                                                         *ap; 
2137                                                         ap = &(*ap)->a_next );
2138
2139                                         *ap = a_hasSubordinate;
2140                                 }
2141                                 rc = 0;
2142                                 break;
2143
2144                         default:
2145                                 Debug(LDAP_DEBUG_TRACE, 
2146                                         "backsql_search(): "
2147                                         "has_children failed( %d)\n", 
2148                                         rc, 0, 0 );
2149                                 rc = 1;
2150                                 goto next_entry;
2151                         }
2152                 }
2153
2154                 if ( bsi.bsi_flags & BSQL_SF_FILTER_ENTRYUUID ) {
2155                         a_entryUUID = backsql_operational_entryUUID( bi, eid );
2156                         if ( a_entryUUID != NULL ) {
2157                                 if ( ap == NULL ) {
2158                                         ap = &user_entry.e_attrs;
2159                                 }
2160
2161                                 for ( ; *ap; ap = &(*ap)->a_next );
2162
2163                                 *ap = a_entryUUID;
2164                         }
2165                 }
2166
2167 #ifdef BACKSQL_SYNCPROV
2168                 if ( bsi.bsi_flags & BSQL_SF_FILTER_ENTRYCSN ) {
2169                         a_entryCSN = backsql_operational_entryCSN( op );
2170                         if ( a_entryCSN != NULL ) {
2171                                 if ( ap == NULL ) {
2172                                         ap = &user_entry.e_attrs;
2173                                 }
2174
2175                                 for ( ; *ap; ap = &(*ap)->a_next );
2176
2177                                 *ap = a_entryCSN;
2178                         }
2179                 }
2180 #endif /* BACKSQL_SYNCPROV */
2181
2182                 if ( test_filter( op, e, op->ors_filter ) == LDAP_COMPARE_TRUE )
2183                 {
2184                         rs->sr_attrs = op->ors_attrs;
2185                         rs->sr_operational_attrs = NULL;
2186                         rs->sr_entry = e;
2187                         if ( e == &user_entry ) {
2188                                 rs->sr_flags = REP_ENTRY_MODIFIABLE;
2189                         }
2190                         /* FIXME: need the whole entry (ITS#3480) */
2191                         sres = send_search_entry( op, rs );
2192                         rs->sr_entry = NULL;
2193                         rs->sr_attrs = NULL;
2194                         rs->sr_operational_attrs = NULL;
2195
2196                         if ( sres == -1 ) {
2197                                 /*
2198                                  * FIXME: send_search_entry failed;
2199                                  * better stop
2200                                  */
2201                                 Debug( LDAP_DEBUG_TRACE, "backsql_search(): "
2202                                         "connection lost\n", 0, 0, 0 );
2203                                 goto end_of_search;
2204                         }
2205                 }
2206
2207 next_entry:;
2208                 if ( e == &user_entry ) {
2209                         entry_clean( &user_entry );
2210                 }
2211
2212 next_entry2:;
2213                 if ( op->ors_slimit != SLAP_NO_LIMIT
2214                                 && rs->sr_nentries >= op->ors_slimit )
2215                 {
2216                         rs->sr_err = LDAP_SIZELIMIT_EXCEEDED;
2217                         goto send_results;
2218                 }
2219         }
2220
2221 end_of_search:;
2222         if ( rs->sr_nentries > 0 ) {
2223                 rs->sr_ref = rs->sr_v2ref;
2224                 rs->sr_err = (rs->sr_v2ref == NULL) ? LDAP_SUCCESS
2225                         : LDAP_REFERRAL;
2226
2227         } else {
2228                 rs->sr_err = bsi.bsi_status;
2229         }
2230
2231 send_results:;
2232         send_ldap_result( op, rs );
2233
2234         entry_clean( &base_entry );
2235
2236         /* in case we got here accidentally */
2237         entry_clean( &user_entry );
2238
2239         if ( rs->sr_v2ref ) {
2240                 ber_bvarray_free( rs->sr_v2ref );
2241                 rs->sr_v2ref = NULL;
2242         }
2243
2244 #ifdef BACKSQL_SYNCPROV
2245         if ( op->o_sync ) {
2246                 Operation       op2 = *op;
2247                 SlapReply       rs2 = { 0 };
2248                 Entry           e = { 0 };
2249                 slap_callback   cb = { 0 };
2250
2251                 op2.o_tag = LDAP_REQ_ADD;
2252                 op2.o_bd = select_backend( &op->o_bd->be_nsuffix[0], 0, 0 );
2253                 op2.ora_e = &e;
2254                 op2.o_callback = &cb;
2255
2256                 e.e_name = op->o_bd->be_suffix[0];
2257                 e.e_nname = op->o_bd->be_nsuffix[0];
2258
2259                 cb.sc_response = slap_null_cb;
2260
2261                 op2.o_bd->be_add( &op2, &rs2 );
2262         }
2263 #endif /* BACKSQL_SYNCPROV */
2264
2265 done:;
2266         (void)backsql_free_entryID( op, &bsi.bsi_base_id, 0 );
2267
2268         if ( bsi.bsi_attrs != NULL ) {
2269                 op->o_tmpfree( bsi.bsi_attrs, op->o_tmpmemctx );
2270         }
2271
2272         if ( !BER_BVISNULL( &nbase )
2273                         && nbase.bv_val != op->o_req_ndn.bv_val )
2274         {
2275                 ch_free( nbase.bv_val );
2276         }
2277
2278         /* restore scope ... FIXME: this should be done before ANY
2279          * frontend call that uses op */
2280         if ( op->ors_scope == BACKSQL_SCOPE_BASE_LIKE ) {
2281                 op->ors_scope = LDAP_SCOPE_BASE;
2282         }
2283
2284         Debug( LDAP_DEBUG_TRACE, "<==backsql_search()\n", 0, 0, 0 );
2285         return 0;
2286 }
2287
2288 /* return LDAP_SUCCESS IFF we can retrieve the specified entry.
2289  */
2290 int
2291 backsql_entry_get(
2292                 Operation               *op,
2293                 struct berval           *ndn,
2294                 ObjectClass             *oc,
2295                 AttributeDescription    *at,
2296                 int                     rw,
2297                 Entry                   **ent )
2298 {
2299         backsql_srch_info       bsi = { 0 };
2300         SQLHDBC                 dbh = SQL_NULL_HDBC;
2301         int                     rc;
2302         SlapReply               rs = { 0 };
2303         AttributeName           anlist[ 2 ];
2304
2305         *ent = NULL;
2306
2307         rc = backsql_get_db_conn( op, &dbh );
2308         if ( !dbh ) {
2309                 return LDAP_OTHER;
2310         }
2311
2312         if ( at ) {
2313                 anlist[ 0 ].an_name = at->ad_cname;
2314                 anlist[ 0 ].an_desc = at;
2315                 BER_BVZERO( &anlist[ 1 ].an_name );
2316         }
2317
2318         bsi.bsi_e = ch_malloc( sizeof( Entry ) );
2319         rc = backsql_init_search( &bsi,
2320                         ndn,
2321                         LDAP_SCOPE_BASE, 
2322                         SLAP_NO_LIMIT, SLAP_NO_LIMIT,
2323                         (time_t)(-1), NULL,
2324                         dbh, op, &rs, at ? anlist : NULL,
2325                         BACKSQL_ISF_GET_ENTRY );
2326
2327         if ( !BER_BVISNULL( &bsi.bsi_base_id.eid_ndn ) ) {
2328                 (void)backsql_free_entryID( op, &bsi.bsi_base_id, 0 );
2329         }
2330
2331         if ( rc == LDAP_SUCCESS ) {
2332
2333 #if 0 /* not supported at present */
2334                 /* find attribute values */
2335                 if ( is_entry_alias( bsi.bsi_e ) ) {
2336                         Debug( LDAP_DEBUG_ACL,
2337                                 "<= backsql_entry_get: entry is an alias\n",
2338                                 0, 0, 0 );
2339                         rc = LDAP_ALIAS_PROBLEM;
2340                         goto return_results;
2341                 }
2342 #endif
2343
2344                 if ( is_entry_referral( bsi.bsi_e ) ) {
2345                         Debug( LDAP_DEBUG_ACL,
2346                                 "<= backsql_entry_get: entry is a referral\n",
2347                                 0, 0, 0 );
2348                         rc = LDAP_REFERRAL;
2349                         goto return_results;
2350                 }
2351
2352                 if ( oc && !is_entry_objectclass( bsi.bsi_e, oc, 0 ) ) {
2353                         Debug( LDAP_DEBUG_ACL,
2354                                         "<= backsql_entry_get: "
2355                                         "failed to find objectClass\n",
2356                                         0, 0, 0 ); 
2357                         rc = LDAP_NO_SUCH_ATTRIBUTE;
2358                         goto return_results;
2359                 }
2360
2361                 *ent = bsi.bsi_e;
2362         }
2363
2364 return_results:;
2365         if ( bsi.bsi_attrs != NULL ) {
2366                 op->o_tmpfree( bsi.bsi_attrs, op->o_tmpmemctx );
2367         }
2368
2369         if ( rc != LDAP_SUCCESS ) {
2370                 if ( bsi.bsi_e ) {
2371                         entry_free( bsi.bsi_e );
2372                 }
2373         }
2374
2375         return rc;
2376 }
2377