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