]> git.sur5r.net Git - openldap/blob - servers/slapd/back-sql/search.c
d6524d160900041fe70cfebffcf9ae5f67b20588
[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 #ifdef BACKSQL_ALIASING_QUOTE
1293         backsql_strfcat( &bsi->bsi_sel, "lclcl",
1294                         (ber_len_t)STRLENOF( " " BACKSQL_ALIASING ),
1295                                 " " BACKSQL_ALIASING,
1296                         BACKSQL_ALIASING_QUOTE,
1297                         (ber_len_t)STRLENOF( "objectClass" ),
1298                                 "objectClass",
1299                         BACKSQL_ALIASING_QUOTE,
1300                         (ber_len_t)STRLENOF( ",ldap_entries.dn " BACKSQL_ALIASING "dn" ),
1301                                 ",ldap_entries.dn " BACKSQL_ALIASING "dn" );
1302 #else /* ! BACKSQL_ALIASING_QUOTE */
1303         backsql_strfcat( &bsi->bsi_sel, "l",
1304                         (ber_len_t)STRLENOF( " " BACKSQL_ALIASING "objectClass,ldap_entries.dn " BACKSQL_ALIASING "dn" ),
1305                                 " " BACKSQL_ALIASING "objectClass,ldap_entries.dn " BACKSQL_ALIASING "dn" );
1306 #endif /* ! BACKSQL_ALIASING_QUOTE */
1307
1308         backsql_strfcat( &bsi->bsi_from, "lb",
1309                         (ber_len_t)STRLENOF( " FROM ldap_entries," ),
1310                                 " FROM ldap_entries,",
1311                         &bsi->bsi_oc->bom_keytbl );
1312
1313         backsql_strfcat( &bsi->bsi_join_where, "lbcbl",
1314                         (ber_len_t)STRLENOF( " WHERE " ), " WHERE ",
1315                         &bsi->bsi_oc->bom_keytbl,
1316                         '.',
1317                         &bsi->bsi_oc->bom_keycol,
1318                         (ber_len_t)STRLENOF( "=ldap_entries.keyval AND ldap_entries.oc_map_id=? AND " ),
1319                                 "=ldap_entries.keyval AND ldap_entries.oc_map_id=? AND " );
1320
1321         switch ( bsi->bsi_scope ) {
1322         case LDAP_SCOPE_BASE:
1323                 if ( BACKSQL_CANUPPERCASE( bi ) ) {
1324                         backsql_strfcat( &bsi->bsi_join_where, "bl",
1325                                         &bi->sql_upper_func,
1326                                         (ber_len_t)STRLENOF( "(ldap_entries.dn)=?" ),
1327                                                 "(ldap_entries.dn)=?" );
1328                 } else {
1329                         backsql_strfcat( &bsi->bsi_join_where, "l",
1330                                         (ber_len_t)STRLENOF( "ldap_entries.dn=?" ),
1331                                                 "ldap_entries.dn=?" );
1332                 }
1333                 break;
1334                 
1335         case BACKSQL_SCOPE_BASE_LIKE:
1336                 if ( BACKSQL_CANUPPERCASE( bi ) ) {
1337                         backsql_strfcat( &bsi->bsi_join_where, "bl",
1338                                         &bi->sql_upper_func,
1339                                         (ber_len_t)STRLENOF( "(ldap_entries.dn) LIKE ?" ),
1340                                                 "(ldap_entries.dn) LIKE ?" );
1341                 } else {
1342                         backsql_strfcat( &bsi->bsi_join_where, "l",
1343                                         (ber_len_t)STRLENOF( "ldap_entries.dn LIKE ?" ),
1344                                                 "ldap_entries.dn LIKE ?" );
1345                 }
1346                 break;
1347                 
1348         case LDAP_SCOPE_ONELEVEL:
1349                 backsql_strfcat( &bsi->bsi_join_where, "l",
1350                                 (ber_len_t)STRLENOF( "ldap_entries.parent=?" ),
1351                                         "ldap_entries.parent=?" );
1352                 break;
1353
1354 #ifdef LDAP_SCOPE_SUBORDINATE
1355         case LDAP_SCOPE_SUBORDINATE:
1356 #endif /* LDAP_SCOPE_SUBORDINATE */
1357         case LDAP_SCOPE_SUBTREE:
1358                 if ( BACKSQL_USE_SUBTREE_SHORTCUT( bi ) ) {
1359                         int             i;
1360                         BackendDB       *bd = bsi->bsi_op->o_bd;
1361
1362                         assert( bd->be_nsuffix );
1363
1364                         for ( i = 0; !BER_BVISNULL( &bd->be_nsuffix[ i ] ); i++ )
1365                         {
1366                                 if ( dn_match( &bd->be_nsuffix[ i ],
1367                                                         bsi->bsi_base_ndn ) )
1368                                 {
1369                                         /* pass this to the candidate selection
1370                                          * routine so that the DN is not bound
1371                                          * to the select statement */
1372                                         bsi->bsi_use_subtree_shortcut = 1;
1373                                         break;
1374                                 }
1375                         }
1376                 }
1377
1378                 if ( bsi->bsi_use_subtree_shortcut ) {
1379                         /* Skip the base DN filter, as every entry will match it */
1380                         backsql_strfcat( &bsi->bsi_join_where, "l",
1381                                         (ber_len_t)STRLENOF( "9=9"), "9=9");
1382
1383                 } else if ( !BER_BVISNULL( &bi->sql_subtree_cond ) ) {
1384                         backsql_strfcat( &bsi->bsi_join_where, "b", &bi->sql_subtree_cond );
1385
1386                 } else if ( BACKSQL_CANUPPERCASE( bi ) ) {
1387                         backsql_strfcat( &bsi->bsi_join_where, "bl",
1388                                         &bi->sql_upper_func,
1389                                         (ber_len_t)STRLENOF( "(ldap_entries.dn) LIKE ?" ),
1390                                                 "(ldap_entries.dn) LIKE ?"  );
1391
1392                 } else {
1393                         backsql_strfcat( &bsi->bsi_join_where, "l",
1394                                         (ber_len_t)STRLENOF( "ldap_entries.dn LIKE ?" ),
1395                                                 "ldap_entries.dn LIKE ?" );
1396                 }
1397
1398                 break;
1399
1400         default:
1401                 assert( 0 );
1402         }
1403
1404         rc = backsql_process_filter( bsi, bsi->bsi_filter );
1405         if ( rc > 0 ) {
1406                 struct berbuf   bb = BB_NULL;
1407
1408                 backsql_strfcat( &bb, "bbblb",
1409                                 &bsi->bsi_sel.bb_val,
1410                                 &bsi->bsi_from.bb_val, 
1411                                 &bsi->bsi_join_where.bb_val,
1412                                 (ber_len_t)STRLENOF( " AND " ), " AND ",
1413                                 &bsi->bsi_flt_where.bb_val );
1414
1415                 *query = bb.bb_val;
1416
1417         } else if ( rc < 0 ) {
1418                 /* 
1419                  * Indicates that there's no possible way the filter matches
1420                  * anything.  No need to issue the query
1421                  */
1422                 free( query->bv_val );
1423                 BER_BVZERO( query );
1424         }
1425  
1426         free( bsi->bsi_sel.bb_val.bv_val );
1427         BER_BVZERO( &bsi->bsi_sel.bb_val );
1428         bsi->bsi_sel.bb_len = 0;
1429         free( bsi->bsi_from.bb_val.bv_val );
1430         BER_BVZERO( &bsi->bsi_from.bb_val );
1431         bsi->bsi_from.bb_len = 0;
1432         free( bsi->bsi_join_where.bb_val.bv_val );
1433         BER_BVZERO( &bsi->bsi_join_where.bb_val );
1434         bsi->bsi_join_where.bb_len = 0;
1435         free( bsi->bsi_flt_where.bb_val.bv_val );
1436         BER_BVZERO( &bsi->bsi_flt_where.bb_val );
1437         bsi->bsi_flt_where.bb_len = 0;
1438         
1439         Debug( LDAP_DEBUG_TRACE, "<==backsql_srch_query() returns %s\n",
1440                 query->bv_val ? query->bv_val : "NULL", 0, 0 );
1441         
1442         return ( rc <= 0 ? 1 : 0 );
1443 }
1444
1445 static int
1446 backsql_oc_get_candidates( void *v_oc, void *v_bsi )
1447 {
1448         backsql_oc_map_rec      *oc = v_oc;
1449         backsql_srch_info       *bsi = v_bsi;
1450         Operation               *op = bsi->bsi_op;
1451         backsql_info            *bi = (backsql_info *)bsi->bsi_op->o_bd->be_private;
1452         struct berval           query;
1453         SQLHSTMT                sth = SQL_NULL_HSTMT;
1454         RETCODE                 rc;
1455         int                     res;
1456         BACKSQL_ROW_NTS         row;
1457         int                     i;
1458         int                     j;
1459         int                     n_candidates = bsi->bsi_n_candidates;
1460
1461         /* 
1462          * + 1 because we need room for '%';
1463          * + 1 because we need room for ',' for LDAP_SCOPE_SUBORDINATE;
1464          * this makes a subtree
1465          * search for a DN BACKSQL_MAX_DN_LEN long legal 
1466          * if it returns that DN only
1467          */
1468         char                    tmp_base_ndn[ BACKSQL_MAX_DN_LEN + 1 + 1 ];
1469
1470         bsi->bsi_status = LDAP_SUCCESS;
1471  
1472         Debug( LDAP_DEBUG_TRACE, "==>backsql_oc_get_candidates(): oc=\"%s\"\n",
1473                         BACKSQL_OC_NAME( oc ), 0, 0 );
1474
1475         if ( bsi->bsi_n_candidates == -1 ) {
1476                 Debug( LDAP_DEBUG_TRACE, "backsql_oc_get_candidates(): "
1477                         "unchecked limit has been overcome\n", 0, 0, 0 );
1478                 /* should never get here */
1479                 assert( 0 );
1480                 bsi->bsi_status = LDAP_ADMINLIMIT_EXCEEDED;
1481                 return BACKSQL_AVL_STOP;
1482         }
1483         
1484         bsi->bsi_oc = oc;
1485         res = backsql_srch_query( bsi, &query );
1486         if ( res ) {
1487                 Debug( LDAP_DEBUG_TRACE, "backsql_oc_get_candidates(): "
1488                         "error while constructing query for objectclass \"%s\"\n",
1489                         oc->bom_oc->soc_cname.bv_val, 0, 0 );
1490                 /*
1491                  * FIXME: need to separate errors from legally
1492                  * impossible filters
1493                  */
1494                 switch ( bsi->bsi_status ) {
1495                 case LDAP_SUCCESS:
1496                 case LDAP_UNDEFINED_TYPE:
1497                 case LDAP_NO_SUCH_OBJECT:
1498                         /* we are conservative... */
1499                 default:
1500                         bsi->bsi_status = LDAP_SUCCESS;
1501                         /* try next */
1502                         return BACKSQL_AVL_CONTINUE;
1503
1504                 case LDAP_ADMINLIMIT_EXCEEDED:
1505                 case LDAP_OTHER:
1506                         /* don't try any more */
1507                         return BACKSQL_AVL_STOP;
1508                 }
1509         }
1510
1511         if ( BER_BVISNULL( &query ) ) {
1512                 Debug( LDAP_DEBUG_TRACE, "backsql_oc_get_candidates(): "
1513                         "could not construct query for objectclass \"%s\"\n",
1514                         oc->bom_oc->soc_cname.bv_val, 0, 0 );
1515                 bsi->bsi_status = LDAP_SUCCESS;
1516                 return BACKSQL_AVL_CONTINUE;
1517         }
1518
1519         Debug( LDAP_DEBUG_TRACE, "Constructed query: %s\n", 
1520                         query.bv_val, 0, 0 );
1521
1522         rc = backsql_Prepare( bsi->bsi_dbh, &sth, query.bv_val, 0 );
1523         free( query.bv_val );
1524         BER_BVZERO( &query );
1525         if ( rc != SQL_SUCCESS ) {
1526                 Debug( LDAP_DEBUG_TRACE, "backsql_oc_get_candidates(): "
1527                         "error preparing query\n", 0, 0, 0 );
1528                 backsql_PrintErrors( bi->sql_db_env, bsi->bsi_dbh, sth, rc );
1529                 bsi->bsi_status = LDAP_OTHER;
1530                 return BACKSQL_AVL_CONTINUE;
1531         }
1532         
1533         Debug( LDAP_DEBUG_TRACE, "id: '%ld'\n", bsi->bsi_oc->bom_id, 0, 0 );
1534
1535         rc = backsql_BindParamInt( sth, 1, SQL_PARAM_INPUT,
1536                         &bsi->bsi_oc->bom_id );
1537         if ( rc != SQL_SUCCESS ) {
1538                 Debug( LDAP_DEBUG_TRACE, "backsql_oc_get_candidates(): "
1539                         "error binding objectclass id parameter\n", 0, 0, 0 );
1540                 bsi->bsi_status = LDAP_OTHER;
1541                 return BACKSQL_AVL_CONTINUE;
1542         }
1543
1544         switch ( bsi->bsi_scope ) {
1545         case LDAP_SCOPE_BASE:
1546         case BACKSQL_SCOPE_BASE_LIKE:
1547                 /*
1548                  * We do not accept DNs longer than BACKSQL_MAX_DN_LEN;
1549                  * however this should be handled earlier
1550                  */
1551                 if ( bsi->bsi_base_ndn->bv_len > BACKSQL_MAX_DN_LEN ) {
1552                         bsi->bsi_status = LDAP_OTHER;
1553                         return BACKSQL_AVL_CONTINUE;
1554                 }
1555
1556                 AC_MEMCPY( tmp_base_ndn, bsi->bsi_base_ndn->bv_val,
1557                                 bsi->bsi_base_ndn->bv_len + 1 );
1558
1559                 /* uppercase DN only if the stored DN can be uppercased
1560                  * for comparison */
1561                 if ( BACKSQL_CANUPPERCASE( bi ) ) {
1562                         ldap_pvt_str2upper( tmp_base_ndn );
1563                 }
1564
1565                 Debug( LDAP_DEBUG_TRACE, "(base)dn: \"%s\"\n",
1566                                 tmp_base_ndn, 0, 0 );
1567
1568                 rc = backsql_BindParamStr( sth, 2, SQL_PARAM_INPUT,
1569                                 tmp_base_ndn, BACKSQL_MAX_DN_LEN );
1570                 if ( rc != SQL_SUCCESS ) {
1571                         Debug( LDAP_DEBUG_TRACE, "backsql_oc_get_candidates(): "
1572                                 "error binding base_ndn parameter\n", 0, 0, 0 );
1573                         backsql_PrintErrors( bi->sql_db_env, bsi->bsi_dbh, 
1574                                         sth, rc );
1575                         bsi->bsi_status = LDAP_OTHER;
1576                         return BACKSQL_AVL_CONTINUE;
1577                 }
1578                 break;
1579
1580 #ifdef LDAP_SCOPE_SUBORDINATE
1581         case LDAP_SCOPE_SUBORDINATE:
1582 #endif /* LDAP_SCOPE_SUBORDINATE */
1583         case LDAP_SCOPE_SUBTREE:
1584         {
1585                 /* if short-cutting the search base,
1586                  * don't bind any parameter */
1587                 if ( bsi->bsi_use_subtree_shortcut ) {
1588                         break;
1589                 }
1590                 
1591                 /*
1592                  * We do not accept DNs longer than BACKSQL_MAX_DN_LEN;
1593                  * however this should be handled earlier
1594                  */
1595                 if ( bsi->bsi_base_ndn->bv_len > BACKSQL_MAX_DN_LEN ) {
1596                         bsi->bsi_status = LDAP_OTHER;
1597                         return BACKSQL_AVL_CONTINUE;
1598                 }
1599
1600                 /* 
1601                  * Sets the parameters for the SQL built earlier
1602                  * NOTE that all the databases could actually use 
1603                  * the TimesTen version, which would be cleaner 
1604                  * and would also eliminate the need for the
1605                  * subtree_cond line in the configuration file.  
1606                  * For now, I'm leaving it the way it is, 
1607                  * so non-TimesTen databases use the original code.
1608                  * But at some point this should get cleaned up.
1609                  *
1610                  * If "dn" is being used, do a suffix search.
1611                  * If "dn_ru" is being used, do a prefix search.
1612                  */
1613                 if ( BACKSQL_HAS_LDAPINFO_DN_RU( bi ) ) {
1614                         tmp_base_ndn[ 0 ] = '\0';
1615
1616                         for ( i = 0, j = bsi->bsi_base_ndn->bv_len - 1;
1617                                         j >= 0; i++, j--) {
1618                                 tmp_base_ndn[ i ] = bsi->bsi_base_ndn->bv_val[ j ];
1619                         }
1620
1621 #ifdef LDAP_SCOPE_SUBORDINATE
1622                         if ( bsi->bsi_scope == LDAP_SCOPE_SUBORDINATE ) {
1623                                 tmp_base_ndn[ i++ ] = ',';
1624                         }
1625 #endif /* LDAP_SCOPE_SUBORDINATE */
1626
1627                         tmp_base_ndn[ i ] = '%';
1628                         tmp_base_ndn[ i + 1 ] = '\0';
1629
1630                 } else {
1631                         i = 0;
1632
1633                         tmp_base_ndn[ i++ ] = '%';
1634
1635 #ifdef LDAP_SCOPE_SUBORDINATE
1636                         if ( bsi->bsi_scope == LDAP_SCOPE_SUBORDINATE ) {
1637                                 tmp_base_ndn[ i++ ] = ',';
1638                         }
1639 #endif /* LDAP_SCOPE_SUBORDINATE */
1640
1641                         AC_MEMCPY( &tmp_base_ndn[ i ], bsi->bsi_base_ndn->bv_val,
1642                                 bsi->bsi_base_ndn->bv_len + 1 );
1643                 }
1644
1645                 /* uppercase DN only if the stored DN can be uppercased
1646                  * for comparison */
1647                 if ( BACKSQL_CANUPPERCASE( bi ) ) {
1648                         ldap_pvt_str2upper( tmp_base_ndn );
1649                 }
1650
1651 #ifdef LDAP_SCOPE_SUBORDINATE
1652                 if ( bsi->bsi_scope == LDAP_SCOPE_SUBORDINATE ) {
1653                         Debug( LDAP_DEBUG_TRACE, "(children)dn: \"%s\"\n",
1654                                 tmp_base_ndn, 0, 0 );
1655                 } else 
1656 #endif /* LDAP_SCOPE_SUBORDINATE */
1657                 {
1658                         Debug( LDAP_DEBUG_TRACE, "(sub)dn: \"%s\"\n",
1659                                 tmp_base_ndn, 0, 0 );
1660                 }
1661
1662                 rc = backsql_BindParamStr( sth, 2, SQL_PARAM_INPUT,
1663                                 tmp_base_ndn, BACKSQL_MAX_DN_LEN );
1664                 if ( rc != SQL_SUCCESS ) {
1665                         Debug( LDAP_DEBUG_TRACE, "backsql_oc_get_candidates(): "
1666                                 "error binding base_ndn parameter (2)\n",
1667                                 0, 0, 0 );
1668                         backsql_PrintErrors( bi->sql_db_env, bsi->bsi_dbh, 
1669                                         sth, rc );
1670                         bsi->bsi_status = LDAP_OTHER;
1671                         return BACKSQL_AVL_CONTINUE;
1672                 }
1673                 break;
1674         }
1675
1676         case LDAP_SCOPE_ONELEVEL:
1677                 assert( !BER_BVISNULL( &bsi->bsi_base_id.eid_ndn ) );
1678
1679 #ifdef BACKSQL_ARBITRARY_KEY
1680                 Debug( LDAP_DEBUG_TRACE, "(one)id: \"%s\"\n",
1681                                 bsi->bsi_base_id.eid_id.bv_val, 0, 0 );
1682 #else /* ! BACKSQL_ARBITRARY_KEY */
1683                 Debug( LDAP_DEBUG_TRACE, "(one)id: '%lu'\n",
1684                                 bsi->bsi_base_id.eid_id, 0, 0 );
1685 #endif /* ! BACKSQL_ARBITRARY_KEY */
1686                 rc = backsql_BindParamID( sth, 2, SQL_PARAM_INPUT,
1687                                 &bsi->bsi_base_id.eid_id );
1688                 if ( rc != SQL_SUCCESS ) {
1689                         Debug( LDAP_DEBUG_TRACE, "backsql_oc_get_candidates(): "
1690                                 "error binding base id parameter\n", 0, 0, 0 );
1691                         bsi->bsi_status = LDAP_OTHER;
1692                         return BACKSQL_AVL_CONTINUE;
1693                 }
1694                 break;
1695         }
1696         
1697         rc = SQLExecute( sth );
1698         if ( !BACKSQL_SUCCESS( rc ) ) {
1699                 Debug( LDAP_DEBUG_TRACE, "backsql_oc_get_candidates(): "
1700                         "error executing query\n", 0, 0, 0 );
1701                 backsql_PrintErrors( bi->sql_db_env, bsi->bsi_dbh, sth, rc );
1702                 SQLFreeStmt( sth, SQL_DROP );
1703                 bsi->bsi_status = LDAP_OTHER;
1704                 return BACKSQL_AVL_CONTINUE;
1705         }
1706
1707         backsql_BindRowAsStrings( sth, &row );
1708         rc = SQLFetch( sth );
1709         for ( ; BACKSQL_SUCCESS( rc ); rc = SQLFetch( sth ) ) {
1710                 struct berval           dn, pdn, ndn;
1711                 backsql_entryID         *c_id = NULL;
1712                 int                     ret;
1713
1714                 ber_str2bv( row.cols[ 3 ], 0, 0, &dn );
1715
1716                 if ( backsql_api_odbc2dn( bsi->bsi_op, bsi->bsi_rs, &dn ) ) {
1717                         continue;
1718                 }
1719
1720                 ret = dnPrettyNormal( NULL, &dn, &pdn, &ndn, op->o_tmpmemctx );
1721                 if ( dn.bv_val != row.cols[ 3 ] ) {
1722                         free( dn.bv_val );
1723                 }
1724
1725                 if ( ret != LDAP_SUCCESS ) {
1726                         continue;
1727                 }
1728
1729                 if ( bi->sql_baseObject && dn_match( &ndn, &bi->sql_baseObject->e_nname ) ) {
1730                         op->o_tmpfree( pdn.bv_val, op->o_tmpmemctx );
1731                         op->o_tmpfree( ndn.bv_val, op->o_tmpmemctx );
1732                         continue;
1733                 }
1734
1735                 c_id = (backsql_entryID *)ch_calloc( 1, 
1736                                 sizeof( backsql_entryID ) );
1737 #ifdef BACKSQL_ARBITRARY_KEY
1738                 ber_str2bv_x( row.cols[ 0 ], 0, 1, &c_id->eid_id,
1739                                 op->o_tmpmemctx );
1740                 ber_str2bv_x( row.cols[ 1 ], 0, 1, &c_id->eid_keyval,
1741                                 op->o_tmpmemctx );
1742 #else /* ! BACKSQL_ARBITRARY_KEY */
1743                 c_id->eid_id = strtol( row.cols[ 0 ], NULL, 0 );
1744                 c_id->eid_keyval = strtol( row.cols[ 1 ], NULL, 0 );
1745 #endif /* ! BACKSQL_ARBITRARY_KEY */
1746                 c_id->eid_oc_id = bsi->bsi_oc->bom_id;
1747
1748                 c_id->eid_dn = pdn;
1749                 c_id->eid_ndn = ndn;
1750
1751                 /* append at end of list ... */
1752                 c_id->eid_next = NULL;
1753                 *bsi->bsi_id_listtail = c_id;
1754                 bsi->bsi_id_listtail = &c_id->eid_next;
1755
1756 #ifdef BACKSQL_ARBITRARY_KEY
1757                 Debug( LDAP_DEBUG_TRACE, "backsql_oc_get_candidates(): "
1758                         "added entry id=%s, keyval=%s dn=\"%s\"\n",
1759                         c_id->eid_id.bv_val, c_id->eid_keyval.bv_val,
1760                         row.cols[ 3 ] );
1761 #else /* ! BACKSQL_ARBITRARY_KEY */
1762                 Debug( LDAP_DEBUG_TRACE, "backsql_oc_get_candidates(): "
1763                         "added entry id=%ld, keyval=%ld dn=\"%s\"\n",
1764                         c_id->eid_id, c_id->eid_keyval, row.cols[ 3 ] );
1765 #endif /* ! BACKSQL_ARBITRARY_KEY */
1766
1767                 /* count candidates, for unchecked limit */
1768                 bsi->bsi_n_candidates--;
1769                 if ( bsi->bsi_n_candidates == -1 ) {
1770                         break;
1771                 }
1772         }
1773         backsql_FreeRow( &row );
1774         SQLFreeStmt( sth, SQL_DROP );
1775
1776         Debug( LDAP_DEBUG_TRACE, "<==backsql_oc_get_candidates(): %d\n",
1777                         n_candidates - bsi->bsi_n_candidates, 0, 0 );
1778
1779         return ( bsi->bsi_n_candidates == -1 ? BACKSQL_AVL_STOP : BACKSQL_AVL_CONTINUE );
1780 }
1781
1782 int
1783 backsql_search( Operation *op, SlapReply *rs )
1784 {
1785         backsql_info            *bi = (backsql_info *)op->o_bd->be_private;
1786         SQLHDBC                 dbh = SQL_NULL_HDBC;
1787         int                     sres;
1788         Entry                   user_entry = { 0 },
1789                                 base_entry = { 0 };
1790         int                     manageDSAit;
1791         time_t                  stoptime = 0;
1792         backsql_srch_info       bsi;
1793         backsql_entryID         *eid = NULL;
1794         struct berval           nbase = BER_BVNULL,
1795                                 realndn = BER_BVNULL;
1796
1797         manageDSAit = get_manageDSAit( op );
1798
1799         Debug( LDAP_DEBUG_TRACE, "==>backsql_search(): "
1800                 "base=\"%s\", filter=\"%s\", scope=%d,", 
1801                 op->o_req_ndn.bv_val,
1802                 op->ors_filterstr.bv_val ? op->ors_filterstr.bv_val : "(no filter)",
1803                 op->ors_scope );
1804         Debug( LDAP_DEBUG_TRACE, " deref=%d, attrsonly=%d, "
1805                 "attributes to load: %s\n",
1806                 op->ors_deref,
1807                 op->ors_attrsonly,
1808                 op->ors_attrs == NULL ? "all" : "custom list" );
1809
1810         if ( op->o_req_ndn.bv_len > BACKSQL_MAX_DN_LEN ) {
1811                 Debug( LDAP_DEBUG_TRACE, "backsql_search(): "
1812                         "search base length (%ld) exceeds max length (%d)\n", 
1813                         op->o_req_ndn.bv_len, BACKSQL_MAX_DN_LEN, 0 );
1814                 /*
1815                  * FIXME: a LDAP_NO_SUCH_OBJECT could be appropriate
1816                  * since it is impossible that such a long DN exists
1817                  * in the backend
1818                  */
1819                 rs->sr_err = LDAP_ADMINLIMIT_EXCEEDED;
1820                 send_ldap_result( op, rs );
1821                 return 1;
1822         }
1823
1824         sres = backsql_get_db_conn( op, &dbh );
1825         if ( sres != LDAP_SUCCESS ) {
1826                 Debug( LDAP_DEBUG_TRACE, "backsql_search(): "
1827                         "could not get connection handle - exiting\n", 
1828                         0, 0, 0 );
1829                 rs->sr_err = sres;
1830                 rs->sr_text = sres == LDAP_OTHER ?  "SQL-backend error" : NULL;
1831                 send_ldap_result( op, rs );
1832                 return 1;
1833         }
1834
1835         /* compute it anyway; root does not use it */
1836         stoptime = op->o_time + op->ors_tlimit;
1837
1838         realndn = op->o_req_ndn;
1839         if ( backsql_api_dn2odbc( op, rs, &realndn ) ) {
1840                 Debug( LDAP_DEBUG_TRACE, "   backsql_search(\"%s\"): "
1841                         "backsql_api_dn2odbc(\"%s\") failed\n", 
1842                         op->o_req_ndn.bv_val, realndn.bv_val, 0 );
1843                 rs->sr_err = LDAP_OTHER;
1844                 rs->sr_text = "SQL-backend error";
1845                 send_ldap_result( op, rs );
1846                 goto done;
1847         }
1848
1849         /* init search */
1850         bsi.bsi_e = &base_entry;
1851         rs->sr_err = backsql_init_search( &bsi, &realndn,
1852                         op->ors_scope,
1853                         op->ors_slimit, op->ors_tlimit,
1854                         stoptime, op->ors_filter,
1855                         dbh, op, rs, op->ors_attrs,
1856                         ( BACKSQL_ISF_MATCHED | BACKSQL_ISF_GET_ENTRY ) );
1857         if ( rs->sr_err != LDAP_SUCCESS ) {
1858 #ifdef SLAP_ACL_HONOR_DISCLOSE
1859                 if ( !BER_BVISNULL( &base_entry.e_nname )
1860                                 && ! access_allowed( op, &base_entry,
1861                                         slap_schema.si_ad_entry, NULL,
1862                                         ACL_DISCLOSE, NULL ) )
1863                 {
1864                         rs->sr_err = LDAP_NO_SUCH_OBJECT;
1865                         if ( rs->sr_ref ) {
1866                                 ber_bvarray_free( rs->sr_ref );
1867                         }
1868                         rs->sr_matched = NULL;
1869                         rs->sr_text = NULL;
1870                 }
1871 #endif /* SLAP_ACL_HONOR_DISCLOSE */
1872                 send_ldap_result( op, rs );
1873                 goto done;
1874
1875         }
1876 #ifdef SLAP_ACL_HONOR_DISCLOSE
1877         /* NOTE: __NEW__ "search" access is required
1878          * on searchBase object */
1879         else {
1880                 slap_mask_t     mask;
1881                 
1882                 if ( get_assert( op ) &&
1883                                 ( test_filter( op, &base_entry, get_assertion( op ) )
1884                                   != LDAP_COMPARE_TRUE ) )
1885                 {
1886                         rs->sr_err = LDAP_ASSERTION_FAILED;
1887                         
1888                 }
1889                 if ( ! access_allowed_mask( op, &base_entry,
1890                                         slap_schema.si_ad_entry,
1891                                         NULL, ACL_SEARCH, NULL, &mask ) )
1892                 {
1893                         if ( rs->sr_err == LDAP_SUCCESS ) {
1894                                 rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
1895                         }
1896                 }
1897
1898                 if ( rs->sr_err != LDAP_SUCCESS ) {
1899                         if ( !ACL_GRANT( mask, ACL_DISCLOSE ) ) {
1900                                 rs->sr_err = LDAP_NO_SUCH_OBJECT;
1901                                 rs->sr_text = NULL;
1902                         }
1903                         send_ldap_result( op, rs );
1904                         goto done;
1905                 }
1906         }
1907 #endif /* SLAP_ACL_HONOR_DISCLOSE */
1908
1909         bsi.bsi_e = NULL;
1910
1911         bsi.bsi_n_candidates =
1912                 ( op->ors_limit == NULL /* isroot == TRUE */ ? -2 : 
1913                 ( op->ors_limit->lms_s_unchecked == -1 ? -2 :
1914                 ( op->ors_limit->lms_s_unchecked ) ) );
1915
1916         switch ( bsi.bsi_scope ) {
1917         case LDAP_SCOPE_BASE:
1918         case BACKSQL_SCOPE_BASE_LIKE:
1919                 /*
1920                  * probably already found...
1921                  */
1922                 bsi.bsi_id_list = &bsi.bsi_base_id;
1923                 bsi.bsi_id_listtail = &bsi.bsi_base_id.eid_next;
1924                 break;
1925
1926         case LDAP_SCOPE_SUBTREE:
1927                 /*
1928                  * if baseObject is defined, and if it is the root 
1929                  * of the search, add it to the candidate list
1930                  */
1931                 if ( bi->sql_baseObject && BACKSQL_IS_BASEOBJECT_ID( &bsi.bsi_base_id.eid_id ) )
1932                 {
1933                         bsi.bsi_id_list = &bsi.bsi_base_id;
1934                         bsi.bsi_id_listtail = &bsi.bsi_base_id.eid_next;
1935                 }
1936
1937                 /* FALLTHRU */
1938         default:
1939
1940                 /*
1941                  * for each objectclass we try to construct query which gets IDs
1942                  * of entries matching LDAP query filter and scope (or at least 
1943                  * candidates), and get the IDs
1944                  */
1945                 avl_apply( bi->sql_oc_by_oc, backsql_oc_get_candidates,
1946                                 &bsi, BACKSQL_AVL_STOP, AVL_INORDER );
1947         }
1948
1949         if ( op->ors_limit != NULL      /* isroot == FALSE */
1950                         && op->ors_limit->lms_s_unchecked != -1
1951                         && bsi.bsi_n_candidates == -1 )
1952         {
1953                 rs->sr_err = LDAP_ADMINLIMIT_EXCEEDED;
1954                 send_ldap_result( op, rs );
1955                 goto done;
1956         }
1957
1958         /*
1959          * now we load candidate entries (only those attributes 
1960          * mentioned in attrs and filter), test it against full filter 
1961          * and then send to client; don't free entry_id if baseObject...
1962          */
1963         for ( eid = bsi.bsi_id_list;
1964                         eid != NULL; 
1965                         eid = backsql_free_entryID( op,
1966                                 eid, eid == &bsi.bsi_base_id ? 0 : 1 ) )
1967         {
1968                 int             rc;
1969                 Attribute       *a_hasSubordinate = NULL,
1970                                 *a_entryUUID = NULL,
1971                                 *a_entryCSN = NULL,
1972                                 **ap = NULL;
1973                 Entry           *e = NULL;
1974
1975                 /* check for abandon */
1976                 if ( op->o_abandon ) {
1977                         break;
1978                 }
1979
1980                 /* check time limit */
1981                 if ( op->ors_tlimit != SLAP_NO_LIMIT
1982                                 && slap_get_time() > stoptime )
1983                 {
1984                         rs->sr_err = LDAP_TIMELIMIT_EXCEEDED;
1985                         rs->sr_ctrls = NULL;
1986                         rs->sr_ref = rs->sr_v2ref;
1987                         rs->sr_err = (rs->sr_v2ref == NULL) ? LDAP_SUCCESS
1988                                 : LDAP_REFERRAL;
1989                         send_ldap_result( op, rs );
1990                         goto end_of_search;
1991                 }
1992
1993 #ifdef BACKSQL_ARBITRARY_KEY
1994                 Debug(LDAP_DEBUG_TRACE, "backsql_search(): loading data "
1995                         "for entry id=%s, oc_id=%ld, keyval=%s\n",
1996                         eid->eid_id.bv_val, eid->eid_oc_id,
1997                         eid->eid_keyval.bv_val );
1998 #else /* ! BACKSQL_ARBITRARY_KEY */
1999                 Debug(LDAP_DEBUG_TRACE, "backsql_search(): loading data "
2000                         "for entry id=%ld, oc_id=%ld, keyval=%ld\n",
2001                         eid->eid_id, eid->eid_oc_id, eid->eid_keyval );
2002 #endif /* ! BACKSQL_ARBITRARY_KEY */
2003
2004                 /* check scope */
2005                 switch ( op->ors_scope ) {
2006                 case LDAP_SCOPE_BASE:
2007                 case BACKSQL_SCOPE_BASE_LIKE:
2008                         if ( !dn_match( &eid->eid_ndn, &op->o_req_ndn ) ) {
2009                                 goto next_entry2;
2010                         }
2011                         break;
2012
2013                 case LDAP_SCOPE_ONE:
2014                 {
2015                         struct berval   rdn = eid->eid_ndn;
2016
2017                         rdn.bv_len -= op->o_req_ndn.bv_len + STRLENOF( "," );
2018                         if ( !dnIsOneLevelRDN( &rdn ) ) {
2019                                 goto next_entry2;
2020                         }
2021                         /* fall thru */
2022                 }
2023
2024 #ifdef LDAP_SCOPE_SUBORDINATE
2025                 case LDAP_SCOPE_SUBORDINATE:
2026                         /* discard the baseObject entry */
2027                         if ( dn_match( &eid->eid_ndn, &op->o_req_ndn ) ) {
2028                                 goto next_entry2;
2029                         }
2030                 /* FALLTHRU */
2031 #endif /* LDAP_SCOPE_SUBORDINATE */
2032
2033                 case LDAP_SCOPE_SUBTREE:
2034                         /* FIXME: this should never fail... */
2035                         if ( !dnIsSuffix( &eid->eid_ndn, &op->o_req_ndn ) ) {
2036                                 assert( 0 );
2037                                 goto next_entry2;
2038                         }
2039                         break;
2040                 }
2041
2042                 if ( BACKSQL_IS_BASEOBJECT_ID( &eid->eid_id ) ) {
2043                         /* don't recollect baseObject... */
2044                         e = bi->sql_baseObject;
2045
2046                 } else if ( eid == &bsi.bsi_base_id ) {
2047                         /* don't recollect searchBase object... */
2048                         e = &base_entry;
2049
2050                 } else {
2051                         bsi.bsi_e = &user_entry;
2052                         rc = backsql_id2entry( &bsi, eid );
2053                         if ( rc != LDAP_SUCCESS ) {
2054                                 Debug( LDAP_DEBUG_TRACE, "backsql_search(): "
2055                                         "error %d in backsql_id2entry() "
2056                                         "- skipping\n", rc, 0, 0 );
2057                                 continue;
2058                         }
2059                         e = &user_entry;
2060                 }
2061
2062                 if ( !manageDSAit &&
2063                                 op->ors_scope != LDAP_SCOPE_BASE &&
2064                                 op->ors_scope != BACKSQL_SCOPE_BASE_LIKE &&
2065                                 is_entry_referral( e ) )
2066                 {
2067                         BerVarray refs;
2068
2069                         refs = get_entry_referrals( op, e );
2070                         if ( !refs ) {
2071                                 backsql_srch_info       bsi2 = { 0 };
2072                                 Entry                   user_entry2 = { 0 };
2073
2074                                 /* retry with the full entry... */
2075                                 bsi2.bsi_e = &user_entry2;
2076                                 rc = backsql_init_search( &bsi2,
2077                                                 &e->e_nname,
2078                                                 LDAP_SCOPE_BASE, 
2079                                                 SLAP_NO_LIMIT, SLAP_NO_LIMIT,
2080                                                 (time_t)(-1), NULL,
2081                                                 dbh, op, rs, NULL,
2082                                                 BACKSQL_ISF_GET_ENTRY );
2083                                 if ( rc == LDAP_SUCCESS ) {
2084                                         if ( is_entry_referral( &user_entry2 ) )
2085                                         {
2086                                                 refs = get_entry_referrals( op,
2087                                                                 &user_entry2 );
2088                                         } else {
2089                                                 rs->sr_err = LDAP_OTHER;
2090                                         }
2091                                         entry_clean( &user_entry2 );
2092                                 }
2093                                 if ( bsi2.bsi_attrs != NULL ) {
2094                                         op->o_tmpfree( bsi2.bsi_attrs,
2095                                                         op->o_tmpmemctx );
2096                                 }
2097                         }
2098
2099                         if ( refs ) {
2100                                 rs->sr_ref = referral_rewrite( refs,
2101                                                 &e->e_name,
2102                                                 &op->o_req_dn,
2103                                                 op->ors_scope );
2104                                 ber_bvarray_free( refs );
2105                         }
2106
2107                         if ( rs->sr_ref ) {
2108                                 rs->sr_err = LDAP_REFERRAL;
2109
2110                         } else {
2111                                 rs->sr_text = "bad referral object";
2112                         }
2113
2114                         rs->sr_entry = e;
2115                         rs->sr_matched = user_entry.e_name.bv_val;
2116                         send_search_reference( op, rs );
2117
2118                         ber_bvarray_free( rs->sr_ref );
2119                         rs->sr_ref = NULL;
2120                         rs->sr_matched = NULL;
2121                         rs->sr_entry = NULL;
2122
2123                         goto next_entry;
2124                 }
2125
2126                 /*
2127                  * We use this flag since we need to parse the filter
2128                  * anyway; we should have used the frontend API function
2129                  * filter_has_subordinates()
2130                  */
2131                 if ( bsi.bsi_flags & BSQL_SF_FILTER_HASSUBORDINATE ) {
2132                         rc = backsql_has_children( bi, dbh, &e->e_nname );
2133
2134                         switch ( rc ) {
2135                         case LDAP_COMPARE_TRUE:
2136                         case LDAP_COMPARE_FALSE:
2137                                 a_hasSubordinate = slap_operational_hasSubordinate( rc == LDAP_COMPARE_TRUE );
2138                                 if ( a_hasSubordinate != NULL ) {
2139                                         for ( ap = &user_entry.e_attrs; 
2140                                                         *ap; 
2141                                                         ap = &(*ap)->a_next );
2142
2143                                         *ap = a_hasSubordinate;
2144                                 }
2145                                 rc = 0;
2146                                 break;
2147
2148                         default:
2149                                 Debug(LDAP_DEBUG_TRACE, 
2150                                         "backsql_search(): "
2151                                         "has_children failed( %d)\n", 
2152                                         rc, 0, 0 );
2153                                 rc = 1;
2154                                 goto next_entry;
2155                         }
2156                 }
2157
2158                 if ( bsi.bsi_flags & BSQL_SF_FILTER_ENTRYUUID ) {
2159                         a_entryUUID = backsql_operational_entryUUID( bi, eid );
2160                         if ( a_entryUUID != NULL ) {
2161                                 if ( ap == NULL ) {
2162                                         ap = &user_entry.e_attrs;
2163                                 }
2164
2165                                 for ( ; *ap; ap = &(*ap)->a_next );
2166
2167                                 *ap = a_entryUUID;
2168                         }
2169                 }
2170
2171 #ifdef BACKSQL_SYNCPROV
2172                 if ( bsi.bsi_flags & BSQL_SF_FILTER_ENTRYCSN ) {
2173                         a_entryCSN = backsql_operational_entryCSN( op );
2174                         if ( a_entryCSN != NULL ) {
2175                                 if ( ap == NULL ) {
2176                                         ap = &user_entry.e_attrs;
2177                                 }
2178
2179                                 for ( ; *ap; ap = &(*ap)->a_next );
2180
2181                                 *ap = a_entryCSN;
2182                         }
2183                 }
2184 #endif /* BACKSQL_SYNCPROV */
2185
2186                 if ( test_filter( op, e, op->ors_filter ) == LDAP_COMPARE_TRUE )
2187                 {
2188                         rs->sr_attrs = op->ors_attrs;
2189                         rs->sr_operational_attrs = NULL;
2190                         rs->sr_entry = e;
2191                         if ( e == &user_entry ) {
2192                                 rs->sr_flags = REP_ENTRY_MODIFIABLE;
2193                         }
2194                         /* FIXME: need the whole entry (ITS#3480) */
2195                         sres = send_search_entry( op, rs );
2196                         rs->sr_entry = NULL;
2197                         rs->sr_attrs = NULL;
2198                         rs->sr_operational_attrs = NULL;
2199
2200                         if ( sres == -1 ) {
2201                                 /*
2202                                  * FIXME: send_search_entry failed;
2203                                  * better stop
2204                                  */
2205                                 Debug( LDAP_DEBUG_TRACE, "backsql_search(): "
2206                                         "connection lost\n", 0, 0, 0 );
2207                                 goto end_of_search;
2208                         }
2209                 }
2210
2211 next_entry:;
2212                 if ( e == &user_entry ) {
2213                         entry_clean( &user_entry );
2214                 }
2215
2216 next_entry2:;
2217                 if ( op->ors_slimit != SLAP_NO_LIMIT
2218                                 && rs->sr_nentries >= op->ors_slimit )
2219                 {
2220                         rs->sr_err = LDAP_SIZELIMIT_EXCEEDED;
2221                         send_ldap_result( op, rs );
2222                         goto end_of_search;
2223                 }
2224         }
2225
2226 end_of_search:;
2227         entry_clean( &base_entry );
2228
2229         /* in case we got here accidentally */
2230         entry_clean( &user_entry );
2231
2232         if ( rs->sr_nentries > 0 ) {
2233                 rs->sr_ref = rs->sr_v2ref;
2234                 rs->sr_err = (rs->sr_v2ref == NULL) ? LDAP_SUCCESS
2235                         : LDAP_REFERRAL;
2236
2237         } else {
2238                 rs->sr_err = bsi.bsi_status;
2239         }
2240         send_ldap_result( op, rs );
2241
2242         if ( rs->sr_v2ref ) {
2243                 ber_bvarray_free( rs->sr_v2ref );
2244                 rs->sr_v2ref = NULL;
2245         }
2246
2247 #ifdef BACKSQL_SYNCPROV
2248         if ( op->o_sync ) {
2249                 Operation       op2 = *op;
2250                 SlapReply       rs2 = { 0 };
2251                 Entry           e = { 0 };
2252                 slap_callback   cb = { 0 };
2253
2254                 op2.o_tag = LDAP_REQ_ADD;
2255                 op2.o_bd = select_backend( &op->o_bd->be_nsuffix[0], 0, 0 );
2256                 op2.ora_e = &e;
2257                 op2.o_callback = &cb;
2258
2259                 e.e_name = op->o_bd->be_suffix[0];
2260                 e.e_nname = op->o_bd->be_nsuffix[0];
2261
2262                 cb.sc_response = slap_null_cb;
2263
2264                 op2.o_bd->be_add( &op2, &rs2 );
2265         }
2266 #endif /* BACKSQL_SYNCPROV */
2267
2268 done:;
2269         if ( !BER_BVISNULL( &realndn ) && realndn.bv_val != op->o_req_ndn.bv_val ) {
2270                 ch_free( realndn.bv_val );
2271         }
2272
2273         (void)backsql_free_entryID( op, &bsi.bsi_base_id, 0 );
2274
2275         if ( bsi.bsi_attrs != NULL ) {
2276                 op->o_tmpfree( bsi.bsi_attrs, op->o_tmpmemctx );
2277         }
2278
2279         if ( !BER_BVISNULL( &nbase )
2280                         && nbase.bv_val != op->o_req_ndn.bv_val )
2281         {
2282                 ch_free( nbase.bv_val );
2283         }
2284
2285         /* restore scope ... FIXME: this should be done before ANY
2286          * frontend call that uses op */
2287         if ( op->ors_scope == BACKSQL_SCOPE_BASE_LIKE ) {
2288                 op->ors_scope = LDAP_SCOPE_BASE;
2289         }
2290
2291         Debug( LDAP_DEBUG_TRACE, "<==backsql_search()\n", 0, 0, 0 );
2292         return 0;
2293 }
2294
2295 /* return LDAP_SUCCESS IFF we can retrieve the specified entry.
2296  */
2297 int
2298 backsql_entry_get(
2299                 Operation               *op,
2300                 struct berval           *ndn,
2301                 ObjectClass             *oc,
2302                 AttributeDescription    *at,
2303                 int                     rw,
2304                 Entry                   **ent )
2305 {
2306         backsql_srch_info       bsi;
2307         SQLHDBC                 dbh = SQL_NULL_HDBC;
2308         int                     rc;
2309         SlapReply               rs = { 0 };
2310         AttributeName           anlist[ 2 ];
2311
2312         *ent = NULL;
2313
2314         rc = backsql_get_db_conn( op, &dbh );
2315         if ( !dbh ) {
2316                 return LDAP_OTHER;
2317         }
2318
2319         if ( at ) {
2320                 anlist[ 0 ].an_name = at->ad_cname;
2321                 anlist[ 0 ].an_desc = at;
2322                 BER_BVZERO( &anlist[ 1 ].an_name );
2323         }
2324
2325         bsi.bsi_e = ch_malloc( sizeof( Entry ) );
2326         rc = backsql_init_search( &bsi,
2327                         ndn,
2328                         LDAP_SCOPE_BASE, 
2329                         SLAP_NO_LIMIT, SLAP_NO_LIMIT,
2330                         (time_t)(-1), NULL,
2331                         dbh, op, &rs, at ? anlist : NULL,
2332                         BACKSQL_ISF_GET_ENTRY );
2333
2334         (void)backsql_free_entryID( op, &bsi.bsi_base_id, 0 );
2335
2336         if ( rc == LDAP_SUCCESS ) {
2337
2338 #if 0 /* not supported at present */
2339                 /* find attribute values */
2340                 if ( is_entry_alias( bsi.bsi_e ) ) {
2341                         Debug( LDAP_DEBUG_ACL,
2342                                 "<= backsql_entry_get: entry is an alias\n",
2343                                 0, 0, 0 );
2344                         rc = LDAP_ALIAS_PROBLEM;
2345                         goto return_results;
2346                 }
2347 #endif
2348
2349                 if ( is_entry_referral( bsi.bsi_e ) ) {
2350                         Debug( LDAP_DEBUG_ACL,
2351                                 "<= backsql_entry_get: entry is a referral\n",
2352                                 0, 0, 0 );
2353                         rc = LDAP_REFERRAL;
2354                         goto return_results;
2355                 }
2356
2357                 if ( oc && !is_entry_objectclass( bsi.bsi_e, oc, 0 ) ) {
2358                         Debug( LDAP_DEBUG_ACL,
2359                                         "<= backsql_entry_get: "
2360                                         "failed to find objectClass\n",
2361                                         0, 0, 0 ); 
2362                         rc = LDAP_NO_SUCH_ATTRIBUTE;
2363                         goto return_results;
2364                 }
2365
2366                 *ent = bsi.bsi_e;
2367         }
2368
2369 return_results:;
2370         if ( bsi.bsi_attrs != NULL ) {
2371                 op->o_tmpfree( bsi.bsi_attrs, op->o_tmpmemctx );
2372         }
2373
2374         if ( rc != LDAP_SUCCESS ) {
2375                 if ( bsi.bsi_e ) {
2376                         entry_free( bsi.bsi_e );
2377                 }
2378         }
2379
2380         return rc;
2381 }
2382