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