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