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