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