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