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