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