Back to index

openldap  2.4.31
search.c
Go to the documentation of this file.
00001 /* $OpenLDAP$ */
00002 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
00003  *
00004  * Copyright 1999-2012 The OpenLDAP Foundation.
00005  * Portions Copyright 1999 Dmitry Kovalev.
00006  * Portions Copyright 2002 Pierangelo Masarati.
00007  * Portions Copyright 2004 Mark Adamson.
00008  * All rights reserved.
00009  *
00010  * Redistribution and use in source and binary forms, with or without
00011  * modification, are permitted only as authorized by the OpenLDAP
00012  * Public License.
00013  *
00014  * A copy of this license is available in the file LICENSE in the
00015  * top-level directory of the distribution or, alternatively, at
00016  * <http://www.OpenLDAP.org/license.html>.
00017  */
00018 /* ACKNOWLEDGEMENTS:
00019  * This work was initially developed by Dmitry Kovalev for inclusion
00020  * by OpenLDAP Software.  Additional significant contributors include
00021  * Pierangelo Masarati and Mark Adamson.
00022  */
00023 
00024 #include "portable.h"
00025 
00026 #include <stdio.h>
00027 #include <sys/types.h>
00028 #include "ac/string.h"
00029 #include "ac/ctype.h"
00030 
00031 #include "lutil.h"
00032 #include "slap.h"
00033 #include "proto-sql.h"
00034 
00035 static int backsql_process_filter( backsql_srch_info *bsi, Filter *f );
00036 static int backsql_process_filter_eq( backsql_srch_info *bsi, 
00037               backsql_at_map_rec *at,
00038               int casefold, struct berval *filter_value );
00039 static int backsql_process_filter_like( backsql_srch_info *bsi, 
00040               backsql_at_map_rec *at,
00041               int casefold, struct berval *filter_value );
00042 static int backsql_process_filter_attr( backsql_srch_info *bsi, Filter *f, 
00043               backsql_at_map_rec *at );
00044 
00045 /* For LDAP_CONTROL_PAGEDRESULTS, a 32 bit cookie is available to keep track of
00046    the state of paged results. The ldap_entries.id and oc_map_id values of the
00047    last entry returned are used as the cookie, so 6 bits are used for the OC id
00048    and the other 26 for ldap_entries ID number. If your max(oc_map_id) is more
00049    than 63, you will need to steal more bits from ldap_entries ID number and
00050    put them into the OC ID part of the cookie. */
00051 
00052 /* NOTE: not supported when BACKSQL_ARBITRARY_KEY is defined */
00053 #ifndef BACKSQL_ARBITRARY_KEY
00054 #define SQL_TO_PAGECOOKIE(id, oc) (((id) << 6 ) | ((oc) & 0x3F))
00055 #define PAGECOOKIE_TO_SQL_ID(pc) ((pc) >> 6)
00056 #define PAGECOOKIE_TO_SQL_OC(pc) ((pc) & 0x3F)
00057 
00058 static int parse_paged_cookie( Operation *op, SlapReply *rs );
00059 
00060 static void send_paged_response( 
00061        Operation *op,
00062        SlapReply *rs,
00063        ID  *lastid );
00064 #endif /* ! BACKSQL_ARBITRARY_KEY */
00065 
00066 static int
00067 backsql_attrlist_add( backsql_srch_info *bsi, AttributeDescription *ad )
00068 {
00069        int           n_attrs = 0;
00070        AttributeName *an = NULL;
00071 
00072        if ( bsi->bsi_attrs == NULL ) {
00073               return 1;
00074        }
00075 
00076        /*
00077         * clear the list (retrieve all attrs)
00078         */
00079        if ( ad == NULL ) {
00080               bsi->bsi_op->o_tmpfree( bsi->bsi_attrs, bsi->bsi_op->o_tmpmemctx );
00081               bsi->bsi_attrs = NULL;
00082               bsi->bsi_flags |= BSQL_SF_ALL_ATTRS;
00083               return 1;
00084        }
00085 
00086        /* strip ';binary' */
00087        if ( slap_ad_is_binary( ad ) ) {
00088               ad = ad->ad_type->sat_ad;
00089        }
00090 
00091        for ( ; !BER_BVISNULL( &bsi->bsi_attrs[ n_attrs ].an_name ); n_attrs++ ) {
00092               an = &bsi->bsi_attrs[ n_attrs ];
00093               
00094               Debug( LDAP_DEBUG_TRACE, "==>backsql_attrlist_add(): "
00095                      "attribute \"%s\" is in list\n", 
00096                      an->an_name.bv_val, 0, 0 );
00097               /*
00098                * We can live with strcmp because the attribute 
00099                * list has been normalized before calling be_search
00100                */
00101               if ( !BACKSQL_NCMP( &an->an_name, &ad->ad_cname ) ) {
00102                      return 1;
00103               }
00104        }
00105        
00106        Debug( LDAP_DEBUG_TRACE, "==>backsql_attrlist_add(): "
00107               "adding \"%s\" to list\n", ad->ad_cname.bv_val, 0, 0 );
00108 
00109        an = (AttributeName *)bsi->bsi_op->o_tmprealloc( bsi->bsi_attrs,
00110                      sizeof( AttributeName ) * ( n_attrs + 2 ),
00111                      bsi->bsi_op->o_tmpmemctx );
00112        if ( an == NULL ) {
00113               return -1;
00114        }
00115 
00116        an[ n_attrs ].an_name = ad->ad_cname;
00117        an[ n_attrs ].an_desc = ad;
00118        BER_BVZERO( &an[ n_attrs + 1 ].an_name );
00119 
00120        bsi->bsi_attrs = an;
00121        
00122        return 1;
00123 }
00124 
00125 /*
00126  * Initializes the search structure.
00127  * 
00128  * If get_base_id != 0, the field bsi_base_id is filled 
00129  * with the entryID of bsi_base_ndn; it must be freed
00130  * by backsql_free_entryID() when no longer required.
00131  *
00132  * NOTE: base must be normalized
00133  */
00134 int
00135 backsql_init_search(
00136        backsql_srch_info    *bsi, 
00137        struct berval        *nbase, 
00138        int                  scope, 
00139        time_t                      stoptime, 
00140        Filter                      *filter, 
00141        SQLHDBC              dbh,
00142        Operation            *op,
00143        SlapReply            *rs,
00144        AttributeName               *attrs,
00145        unsigned             flags )
00146 {
00147        backsql_info         *bi = (backsql_info *)op->o_bd->be_private;
00148        int                  rc = LDAP_SUCCESS;
00149 
00150        bsi->bsi_base_ndn = nbase;
00151        bsi->bsi_use_subtree_shortcut = 0;
00152        BER_BVZERO( &bsi->bsi_base_id.eid_dn );
00153        BER_BVZERO( &bsi->bsi_base_id.eid_ndn );
00154        bsi->bsi_scope = scope;
00155        bsi->bsi_filter = filter;
00156        bsi->bsi_dbh = dbh;
00157        bsi->bsi_op = op;
00158        bsi->bsi_rs = rs;
00159        bsi->bsi_flags = BSQL_SF_NONE;
00160 
00161        bsi->bsi_attrs = NULL;
00162 
00163        if ( BACKSQL_FETCH_ALL_ATTRS( bi ) ) {
00164               /*
00165                * if requested, simply try to fetch all attributes
00166                */
00167               bsi->bsi_flags |= BSQL_SF_ALL_ATTRS;
00168 
00169        } else {
00170               if ( BACKSQL_FETCH_ALL_USERATTRS( bi ) ) {
00171                      bsi->bsi_flags |= BSQL_SF_ALL_USER;
00172 
00173               } else if ( BACKSQL_FETCH_ALL_OPATTRS( bi ) ) {
00174                      bsi->bsi_flags |= BSQL_SF_ALL_OPER;
00175               }
00176 
00177               if ( attrs == NULL ) {
00178                      /* NULL means all user attributes */
00179                      bsi->bsi_flags |= BSQL_SF_ALL_USER;
00180 
00181               } else {
00182                      AttributeName *p;
00183                      int           got_oc = 0;
00184 
00185                      bsi->bsi_attrs = (AttributeName *)bsi->bsi_op->o_tmpalloc(
00186                                    sizeof( AttributeName ),
00187                                    bsi->bsi_op->o_tmpmemctx );
00188                      BER_BVZERO( &bsi->bsi_attrs[ 0 ].an_name );
00189        
00190                      for ( p = attrs; !BER_BVISNULL( &p->an_name ); p++ ) {
00191                             if ( BACKSQL_NCMP( &p->an_name, slap_bv_all_user_attrs ) == 0 ) {
00192                                    /* handle "*" */
00193                                    bsi->bsi_flags |= BSQL_SF_ALL_USER;
00194 
00195                                    /* if all attrs are requested, there's
00196                                     * no need to continue */
00197                                    if ( BSQL_ISF_ALL_ATTRS( bsi ) ) {
00198                                           bsi->bsi_op->o_tmpfree( bsi->bsi_attrs,
00199                                                         bsi->bsi_op->o_tmpmemctx );
00200                                           bsi->bsi_attrs = NULL;
00201                                           break;
00202                                    }
00203                                    continue;
00204 
00205                             } else if ( BACKSQL_NCMP( &p->an_name, slap_bv_all_operational_attrs ) == 0 ) {
00206                                    /* handle "+" */
00207                                    bsi->bsi_flags |= BSQL_SF_ALL_OPER;
00208 
00209                                    /* if all attrs are requested, there's
00210                                     * no need to continue */
00211                                    if ( BSQL_ISF_ALL_ATTRS( bsi ) ) {
00212                                           bsi->bsi_op->o_tmpfree( bsi->bsi_attrs,
00213                                                         bsi->bsi_op->o_tmpmemctx );
00214                                           bsi->bsi_attrs = NULL;
00215                                           break;
00216                                    }
00217                                    continue;
00218 
00219                             } else if ( BACKSQL_NCMP( &p->an_name, slap_bv_no_attrs ) == 0 ) {
00220                                    /* ignore "1.1" */
00221                                    continue;
00222 
00223                             } else if ( p->an_desc == slap_schema.si_ad_objectClass ) {
00224                                    got_oc = 1;
00225                             }
00226 
00227                             backsql_attrlist_add( bsi, p->an_desc );
00228                      }
00229 
00230                      if ( got_oc == 0 && !( bsi->bsi_flags & BSQL_SF_ALL_USER ) ) {
00231                             /* add objectClass if not present,
00232                              * because it is required to understand
00233                              * if an entry is a referral, an alias 
00234                              * or so... */
00235                             backsql_attrlist_add( bsi, slap_schema.si_ad_objectClass );
00236                      }
00237               }
00238 
00239               if ( !BSQL_ISF_ALL_ATTRS( bsi ) && bi->sql_anlist ) {
00240                      AttributeName *p;
00241                      
00242                      /* use hints if available */
00243                      for ( p = bi->sql_anlist; !BER_BVISNULL( &p->an_name ); p++ ) {
00244                             if ( BACKSQL_NCMP( &p->an_name, slap_bv_all_user_attrs ) == 0 ) {
00245                                    /* handle "*" */
00246                                    bsi->bsi_flags |= BSQL_SF_ALL_USER;
00247 
00248                                    /* if all attrs are requested, there's
00249                                     * no need to continue */
00250                                    if ( BSQL_ISF_ALL_ATTRS( bsi ) ) {
00251                                           bsi->bsi_op->o_tmpfree( bsi->bsi_attrs,
00252                                                         bsi->bsi_op->o_tmpmemctx );
00253                                           bsi->bsi_attrs = NULL;
00254                                           break;
00255                                    }
00256                                    continue;
00257 
00258                             } else if ( BACKSQL_NCMP( &p->an_name, slap_bv_all_operational_attrs ) == 0 ) {
00259                                    /* handle "+" */
00260                                    bsi->bsi_flags |= BSQL_SF_ALL_OPER;
00261 
00262                                    /* if all attrs are requested, there's
00263                                     * no need to continue */
00264                                    if ( BSQL_ISF_ALL_ATTRS( bsi ) ) {
00265                                           bsi->bsi_op->o_tmpfree( bsi->bsi_attrs,
00266                                                         bsi->bsi_op->o_tmpmemctx );
00267                                           bsi->bsi_attrs = NULL;
00268                                           break;
00269                                    }
00270                                    continue;
00271                             }
00272 
00273                             backsql_attrlist_add( bsi, p->an_desc );
00274                      }
00275 
00276               }
00277        }
00278 
00279        bsi->bsi_id_list = NULL;
00280        bsi->bsi_id_listtail = &bsi->bsi_id_list;
00281        bsi->bsi_n_candidates = 0;
00282        bsi->bsi_stoptime = stoptime;
00283        BER_BVZERO( &bsi->bsi_sel.bb_val );
00284        bsi->bsi_sel.bb_len = 0;
00285        BER_BVZERO( &bsi->bsi_from.bb_val );
00286        bsi->bsi_from.bb_len = 0;
00287        BER_BVZERO( &bsi->bsi_join_where.bb_val );
00288        bsi->bsi_join_where.bb_len = 0;
00289        BER_BVZERO( &bsi->bsi_flt_where.bb_val );
00290        bsi->bsi_flt_where.bb_len = 0;
00291        bsi->bsi_filter_oc = NULL;
00292 
00293        if ( BACKSQL_IS_GET_ID( flags ) ) {
00294               int    matched = BACKSQL_IS_MATCHED( flags );
00295               int    getentry = BACKSQL_IS_GET_ENTRY( flags );
00296               int    gotit = 0;
00297 
00298               assert( op->o_bd->be_private != NULL );
00299 
00300               rc = backsql_dn2id( op, rs, dbh, nbase, &bsi->bsi_base_id,
00301                             matched, 1 );
00302 
00303               /* the entry is collected either if requested for by getentry
00304                * or if get noSuchObject and requested to climb the tree,
00305                * so that a matchedDN or a referral can be returned */
00306               if ( ( rc == LDAP_NO_SUCH_OBJECT && matched ) || getentry ) {
00307                      if ( !BER_BVISNULL( &bsi->bsi_base_id.eid_ndn ) ) {
00308                             assert( bsi->bsi_e != NULL );
00309                             
00310                             if ( dn_match( nbase, &bsi->bsi_base_id.eid_ndn ) )
00311                             {
00312                                    gotit = 1;
00313                             }
00314                      
00315                             /*
00316                              * let's see if it is a referral and, in case, get it
00317                              */
00318                             backsql_attrlist_add( bsi, slap_schema.si_ad_ref );
00319                             rc = backsql_id2entry( bsi, &bsi->bsi_base_id );
00320                             if ( rc == LDAP_SUCCESS ) {
00321                                    if ( is_entry_referral( bsi->bsi_e ) )
00322                                    {
00323                                           BerVarray erefs = get_entry_referrals( op, bsi->bsi_e );
00324                                           if ( erefs ) {
00325                                                  rc = rs->sr_err = LDAP_REFERRAL;
00326                                                  rs->sr_ref = referral_rewrite( erefs,
00327                                                                &bsi->bsi_e->e_nname,
00328                                                                &op->o_req_dn,
00329                                                                scope );
00330                                                  ber_bvarray_free( erefs );
00331        
00332                                           } else {
00333                                                  rc = rs->sr_err = LDAP_OTHER;
00334                                                  rs->sr_text = "bad referral object";
00335                                           }
00336 
00337                                    } else if ( !gotit ) {
00338                                           rc = rs->sr_err = LDAP_NO_SUCH_OBJECT;
00339                                    }
00340                             }
00341 
00342                      } else {
00343                             rs->sr_err = rc;
00344                      }
00345               }
00346 
00347               if ( gotit && BACKSQL_IS_GET_OC( flags ) ) {
00348                      bsi->bsi_base_id.eid_oc = backsql_id2oc( bi,
00349                             bsi->bsi_base_id.eid_oc_id );
00350                      if ( bsi->bsi_base_id.eid_oc == NULL ) {
00351                             /* error? */
00352                             backsql_free_entryID( &bsi->bsi_base_id, 1,
00353                                    op->o_tmpmemctx );
00354                             rc = rs->sr_err = LDAP_OTHER;
00355                      }
00356               }
00357        }
00358 
00359        bsi->bsi_status = rc;
00360 
00361        switch ( rc ) {
00362        case LDAP_SUCCESS:
00363        case LDAP_REFERRAL:
00364               break;
00365 
00366        default:
00367               bsi->bsi_op->o_tmpfree( bsi->bsi_attrs,
00368                             bsi->bsi_op->o_tmpmemctx );
00369               break;
00370        }
00371 
00372        return rc;
00373 }
00374 
00375 static int
00376 backsql_process_filter_list( backsql_srch_info *bsi, Filter *f, int op )
00377 {
00378        int           res;
00379 
00380        if ( !f ) {
00381               return 0;
00382        }
00383 
00384        backsql_strfcat_x( &bsi->bsi_flt_where,
00385                      bsi->bsi_op->o_tmpmemctx, "c", '(' /* ) */  );
00386 
00387        while ( 1 ) {
00388               res = backsql_process_filter( bsi, f );
00389               if ( res < 0 ) {
00390                      /*
00391                       * TimesTen : If the query has no answers,
00392                       * don't bother to run the query.
00393                       */
00394                      return -1;
00395               }
00396  
00397               f = f->f_next;
00398               if ( f == NULL ) {
00399                      break;
00400               }
00401 
00402               switch ( op ) {
00403               case LDAP_FILTER_AND:
00404                      backsql_strfcat_x( &bsi->bsi_flt_where,
00405                                    bsi->bsi_op->o_tmpmemctx, "l",
00406                                    (ber_len_t)STRLENOF( " AND " ), 
00407                                           " AND " );
00408                      break;
00409 
00410               case LDAP_FILTER_OR:
00411                      backsql_strfcat_x( &bsi->bsi_flt_where,
00412                                    bsi->bsi_op->o_tmpmemctx, "l",
00413                                    (ber_len_t)STRLENOF( " OR " ),
00414                                           " OR " );
00415                      break;
00416               }
00417        }
00418 
00419        backsql_strfcat_x( &bsi->bsi_flt_where,
00420                      bsi->bsi_op->o_tmpmemctx, "c", /* ( */ ')' );
00421 
00422        return 1;
00423 }
00424 
00425 static int
00426 backsql_process_sub_filter( backsql_srch_info *bsi, Filter *f,
00427        backsql_at_map_rec *at )
00428 {
00429        backsql_info         *bi = (backsql_info *)bsi->bsi_op->o_bd->be_private;
00430        int                  i;
00431        int                  casefold = 0;
00432 
00433        if ( !f ) {
00434               return 0;
00435        }
00436 
00437        /* always uppercase strings by now */
00438 #ifdef BACKSQL_UPPERCASE_FILTER
00439        if ( f->f_sub_desc->ad_type->sat_substr &&
00440                      SLAP_MR_ASSOCIATED( f->f_sub_desc->ad_type->sat_substr,
00441                             bi->sql_caseIgnoreMatch ) )
00442 #endif /* BACKSQL_UPPERCASE_FILTER */
00443        {
00444               casefold = 1;
00445        }
00446 
00447        if ( f->f_sub_desc->ad_type->sat_substr &&
00448                      SLAP_MR_ASSOCIATED( f->f_sub_desc->ad_type->sat_substr,
00449                             bi->sql_telephoneNumberMatch ) )
00450        {
00451 
00452               struct berval bv;
00453               ber_len_t     i, s, a;
00454 
00455               /*
00456                * to check for matching telephone numbers
00457                * with intermixed chars, e.g. val='1234'
00458                * use
00459                * 
00460                * val LIKE '%1%2%3%4%'
00461                */
00462 
00463               BER_BVZERO( &bv );
00464               if ( f->f_sub_initial.bv_val ) {
00465                      bv.bv_len += f->f_sub_initial.bv_len;
00466               }
00467               if ( f->f_sub_any != NULL ) {
00468                      for ( a = 0; f->f_sub_any[ a ].bv_val != NULL; a++ ) {
00469                             bv.bv_len += f->f_sub_any[ a ].bv_len;
00470                      }
00471               }
00472               if ( f->f_sub_final.bv_val ) {
00473                      bv.bv_len += f->f_sub_final.bv_len;
00474               }
00475               bv.bv_len = 2 * bv.bv_len - 1;
00476               bv.bv_val = ch_malloc( bv.bv_len + 1 );
00477 
00478               s = 0;
00479               if ( !BER_BVISNULL( &f->f_sub_initial ) ) {
00480                      bv.bv_val[ s ] = f->f_sub_initial.bv_val[ 0 ];
00481                      for ( i = 1; i < f->f_sub_initial.bv_len; i++ ) {
00482                             bv.bv_val[ s + 2 * i - 1 ] = '%';
00483                             bv.bv_val[ s + 2 * i ] = f->f_sub_initial.bv_val[ i ];
00484                      }
00485                      bv.bv_val[ s + 2 * i - 1 ] = '%';
00486                      s += 2 * i;
00487               }
00488 
00489               if ( f->f_sub_any != NULL ) {
00490                      for ( a = 0; !BER_BVISNULL( &f->f_sub_any[ a ] ); a++ ) {
00491                             bv.bv_val[ s ] = f->f_sub_any[ a ].bv_val[ 0 ];
00492                             for ( i = 1; i < f->f_sub_any[ a ].bv_len; i++ ) {
00493                                    bv.bv_val[ s + 2 * i - 1 ] = '%';
00494                                    bv.bv_val[ s + 2 * i ] = f->f_sub_any[ a ].bv_val[ i ];
00495                             }
00496                             bv.bv_val[ s + 2 * i - 1 ] = '%';
00497                             s += 2 * i;
00498                      }
00499               }
00500 
00501               if ( !BER_BVISNULL( &f->f_sub_final ) ) {
00502                      bv.bv_val[ s ] = f->f_sub_final.bv_val[ 0 ];
00503                      for ( i = 1; i < f->f_sub_final.bv_len; i++ ) {
00504                             bv.bv_val[ s + 2 * i - 1 ] = '%';
00505                             bv.bv_val[ s + 2 * i ] = f->f_sub_final.bv_val[ i ];
00506                      }
00507                             bv.bv_val[ s + 2 * i - 1 ] = '%';
00508                      s += 2 * i;
00509               }
00510 
00511               bv.bv_val[ s - 1 ] = '\0';
00512 
00513               (void)backsql_process_filter_like( bsi, at, casefold, &bv );
00514               ch_free( bv.bv_val );
00515 
00516               return 1;
00517        }
00518 
00519        /*
00520         * When dealing with case-sensitive strings 
00521         * we may omit normalization; however, normalized
00522         * SQL filters are more liberal.
00523         */
00524 
00525        backsql_strfcat_x( &bsi->bsi_flt_where,
00526                      bsi->bsi_op->o_tmpmemctx, "c", '(' /* ) */  );
00527 
00528        /* TimesTen */
00529        Debug( LDAP_DEBUG_TRACE, "backsql_process_sub_filter(%s):\n",
00530               at->bam_ad->ad_cname.bv_val, 0, 0 );
00531        Debug(LDAP_DEBUG_TRACE, "   expr: '%s%s%s'\n", at->bam_sel_expr.bv_val,
00532               at->bam_sel_expr_u.bv_val ? "' '" : "",
00533               at->bam_sel_expr_u.bv_val ? at->bam_sel_expr_u.bv_val : "" );
00534        if ( casefold && BACKSQL_AT_CANUPPERCASE( at ) ) {
00535               /*
00536                * If a pre-upper-cased version of the column 
00537                * or a precompiled upper function exists, use it
00538                */
00539               backsql_strfcat_x( &bsi->bsi_flt_where, 
00540                             bsi->bsi_op->o_tmpmemctx,
00541                             "bl",
00542                             &at->bam_sel_expr_u,
00543                             (ber_len_t)STRLENOF( " LIKE '" ),
00544                                    " LIKE '" );
00545 
00546        } else {
00547               backsql_strfcat_x( &bsi->bsi_flt_where,
00548                             bsi->bsi_op->o_tmpmemctx,
00549                             "bl",
00550                             &at->bam_sel_expr,
00551                             (ber_len_t)STRLENOF( " LIKE '" ), " LIKE '" );
00552        }
00553  
00554        if ( !BER_BVISNULL( &f->f_sub_initial ) ) {
00555               ber_len_t     start;
00556 
00557 #ifdef BACKSQL_TRACE
00558               Debug( LDAP_DEBUG_TRACE, 
00559                      "==>backsql_process_sub_filter(%s): "
00560                      "sub_initial=\"%s\"\n", at->bam_ad->ad_cname.bv_val,
00561                      f->f_sub_initial.bv_val, 0 );
00562 #endif /* BACKSQL_TRACE */
00563 
00564               start = bsi->bsi_flt_where.bb_val.bv_len;
00565               backsql_strfcat_x( &bsi->bsi_flt_where,
00566                             bsi->bsi_op->o_tmpmemctx,
00567                             "b",
00568                             &f->f_sub_initial );
00569               if ( casefold && BACKSQL_AT_CANUPPERCASE( at ) ) {
00570                      ldap_pvt_str2upper( &bsi->bsi_flt_where.bb_val.bv_val[ start ] );
00571               }
00572        }
00573 
00574        backsql_strfcat_x( &bsi->bsi_flt_where,
00575                      bsi->bsi_op->o_tmpmemctx,
00576                      "c", '%' );
00577 
00578        if ( f->f_sub_any != NULL ) {
00579               for ( i = 0; !BER_BVISNULL( &f->f_sub_any[ i ] ); i++ ) {
00580                      ber_len_t     start;
00581 
00582 #ifdef BACKSQL_TRACE
00583                      Debug( LDAP_DEBUG_TRACE, 
00584                             "==>backsql_process_sub_filter(%s): "
00585                             "sub_any[%d]=\"%s\"\n", at->bam_ad->ad_cname.bv_val, 
00586                             i, f->f_sub_any[ i ].bv_val );
00587 #endif /* BACKSQL_TRACE */
00588 
00589                      start = bsi->bsi_flt_where.bb_val.bv_len;
00590                      backsql_strfcat_x( &bsi->bsi_flt_where,
00591                                    bsi->bsi_op->o_tmpmemctx,
00592                                    "bc",
00593                                    &f->f_sub_any[ i ],
00594                                    '%' );
00595                      if ( casefold && BACKSQL_AT_CANUPPERCASE( at ) ) {
00596                             /*
00597                              * Note: toupper('%') = '%'
00598                              */
00599                             ldap_pvt_str2upper( &bsi->bsi_flt_where.bb_val.bv_val[ start ] );
00600                      }
00601               }
00602        }
00603 
00604        if ( !BER_BVISNULL( &f->f_sub_final ) ) {
00605               ber_len_t     start;
00606 
00607 #ifdef BACKSQL_TRACE
00608               Debug( LDAP_DEBUG_TRACE, 
00609                      "==>backsql_process_sub_filter(%s): "
00610                      "sub_final=\"%s\"\n", at->bam_ad->ad_cname.bv_val,
00611                      f->f_sub_final.bv_val, 0 );
00612 #endif /* BACKSQL_TRACE */
00613 
00614               start = bsi->bsi_flt_where.bb_val.bv_len;
00615               backsql_strfcat_x( &bsi->bsi_flt_where,
00616                             bsi->bsi_op->o_tmpmemctx,
00617                             "b",
00618                             &f->f_sub_final );
00619               if ( casefold && BACKSQL_AT_CANUPPERCASE( at ) ) {
00620                      ldap_pvt_str2upper( &bsi->bsi_flt_where.bb_val.bv_val[ start ] );
00621               }
00622        }
00623 
00624        backsql_strfcat_x( &bsi->bsi_flt_where,
00625                      bsi->bsi_op->o_tmpmemctx,
00626                      "l", 
00627                      (ber_len_t)STRLENOF( /* (' */ "')" ), /* (' */ "')" );
00628  
00629        return 1;
00630 }
00631 
00632 static int
00633 backsql_merge_from_tbls( backsql_srch_info *bsi, struct berval *from_tbls )
00634 {
00635        if ( BER_BVISNULL( from_tbls ) ) {
00636               return LDAP_SUCCESS;
00637        }
00638 
00639        if ( !BER_BVISNULL( &bsi->bsi_from.bb_val ) ) {
00640               char          *start, *end;
00641               struct berval tmp;
00642 
00643               ber_dupbv_x( &tmp, from_tbls, bsi->bsi_op->o_tmpmemctx );
00644 
00645               for ( start = tmp.bv_val, end = strchr( start, ',' ); start; ) {
00646                      if ( end ) {
00647                             end[0] = '\0';
00648                      }
00649 
00650                      if ( strstr( bsi->bsi_from.bb_val.bv_val, start) == NULL )
00651                      {
00652                             backsql_strfcat_x( &bsi->bsi_from,
00653                                           bsi->bsi_op->o_tmpmemctx,
00654                                           "cs", ',', start );
00655                      }
00656 
00657                      if ( end ) {
00658                             /* in case there are spaces after the comma... */
00659                             for ( start = &end[1]; isspace( start[0] ); start++ );
00660                             if ( start[0] ) {
00661                                    end = strchr( start, ',' );
00662                             } else {
00663                                    start = NULL;
00664                             }
00665                      } else {
00666                             start = NULL;
00667                      }
00668               }
00669 
00670               bsi->bsi_op->o_tmpfree( tmp.bv_val, bsi->bsi_op->o_tmpmemctx );
00671 
00672        } else {
00673               backsql_strfcat_x( &bsi->bsi_from,
00674                             bsi->bsi_op->o_tmpmemctx,
00675                             "b", from_tbls );
00676        }
00677 
00678        return LDAP_SUCCESS;
00679 }
00680 
00681 static int
00682 backsql_process_filter( backsql_srch_info *bsi, Filter *f )
00683 {
00684        backsql_at_map_rec   **vat = NULL;
00685        AttributeDescription *ad = NULL;
00686        unsigned             i;
00687        int                  done = 0;
00688        int                  rc = 0;
00689 
00690        Debug( LDAP_DEBUG_TRACE, "==>backsql_process_filter()\n", 0, 0, 0 );
00691        if ( f->f_choice == SLAPD_FILTER_COMPUTED ) {
00692               struct berval flt;
00693               char          *msg = NULL;
00694 
00695               switch ( f->f_result ) {
00696               case LDAP_COMPARE_TRUE:
00697                      BER_BVSTR( &flt, "10=10" );
00698                      msg = "TRUE";
00699                      break;
00700 
00701               case LDAP_COMPARE_FALSE:
00702                      BER_BVSTR( &flt, "11=0" );
00703                      msg = "FALSE";
00704                      break;
00705 
00706               case SLAPD_COMPARE_UNDEFINED:
00707                      BER_BVSTR( &flt, "12=0" );
00708                      msg = "UNDEFINED";
00709                      break;
00710 
00711               default:
00712                      rc = -1;
00713                      goto done;
00714               }
00715 
00716               Debug( LDAP_DEBUG_TRACE, "backsql_process_filter(): "
00717                      "filter computed (%s)\n", msg, 0, 0 );
00718               backsql_strfcat_x( &bsi->bsi_flt_where,
00719                             bsi->bsi_op->o_tmpmemctx, "b", &flt );
00720               rc = 1;
00721               goto done;
00722        }
00723 
00724        if ( f->f_choice & SLAPD_FILTER_UNDEFINED ) {
00725               backsql_strfcat_x( &bsi->bsi_flt_where,
00726                      bsi->bsi_op->o_tmpmemctx,
00727                      "l",
00728                      (ber_len_t)STRLENOF( "1=0" ), "1=0" );
00729               done = 1;
00730               rc = 1;
00731               goto done;
00732        }
00733 
00734        switch( f->f_choice ) {
00735        case LDAP_FILTER_OR:
00736               rc = backsql_process_filter_list( bsi, f->f_or, 
00737                             LDAP_FILTER_OR );
00738               done = 1;
00739               break;
00740               
00741        case LDAP_FILTER_AND:
00742               rc = backsql_process_filter_list( bsi, f->f_and,
00743                             LDAP_FILTER_AND );
00744               done = 1;
00745               break;
00746 
00747        case LDAP_FILTER_NOT:
00748               backsql_strfcat_x( &bsi->bsi_flt_where,
00749                             bsi->bsi_op->o_tmpmemctx,
00750                             "l",
00751                             (ber_len_t)STRLENOF( "NOT (" /* ) */ ),
00752                                    "NOT (" /* ) */ );
00753               rc = backsql_process_filter( bsi, f->f_not );
00754               backsql_strfcat_x( &bsi->bsi_flt_where,
00755                             bsi->bsi_op->o_tmpmemctx,
00756                             "c", /* ( */ ')' );
00757               done = 1;
00758               break;
00759 
00760        case LDAP_FILTER_PRESENT:
00761               ad = f->f_desc;
00762               break;
00763               
00764        case LDAP_FILTER_EXT:
00765               ad = f->f_mra->ma_desc;
00766               if ( f->f_mr_dnattrs ) {
00767                      /*
00768                       * if dn attrs filtering is requested, better return 
00769                       * success and let test_filter() deal with candidate
00770                       * selection; otherwise we'd need to set conditions
00771                       * on the contents of the DN, e.g. "SELECT ... FROM
00772                       * ldap_entries AS attributeName WHERE attributeName.dn
00773                       * like '%attributeName=value%'"
00774                       */
00775                      backsql_strfcat_x( &bsi->bsi_flt_where,
00776                                    bsi->bsi_op->o_tmpmemctx,
00777                                    "l",
00778                                    (ber_len_t)STRLENOF( "1=1" ), "1=1" );
00779                      bsi->bsi_status = LDAP_SUCCESS;
00780                      rc = 1;
00781                      goto done;
00782               }
00783               break;
00784               
00785        default:
00786               ad = f->f_av_desc;
00787               break;
00788        }
00789 
00790        if ( rc == -1 ) {
00791               goto done;
00792        }
00793  
00794        if ( done ) {
00795               rc = 1;
00796               goto done;
00797        }
00798 
00799        /*
00800         * Turn structuralObjectClass into objectClass
00801         */
00802        if ( ad == slap_schema.si_ad_objectClass 
00803                      || ad == slap_schema.si_ad_structuralObjectClass )
00804        {
00805               /*
00806                * If the filter is LDAP_FILTER_PRESENT, then it's done;
00807                * otherwise, let's see if we are lucky: filtering
00808                * for "structural" objectclass or ancestor...
00809                */
00810               switch ( f->f_choice ) {
00811               case LDAP_FILTER_EQUALITY:
00812               {
00813                      ObjectClass   *oc = oc_bvfind( &f->f_av_value );
00814 
00815                      if ( oc == NULL ) {
00816                             Debug( LDAP_DEBUG_TRACE,
00817                                           "backsql_process_filter(): "
00818                                           "unknown objectClass \"%s\" "
00819                                           "in filter\n",
00820                                           f->f_av_value.bv_val, 0, 0 );
00821                             bsi->bsi_status = LDAP_OTHER;
00822                             rc = -1;
00823                             goto done;
00824                      }
00825 
00826                      /*
00827                       * "structural" objectClass inheritance:
00828                       * - a search for "person" will also return 
00829                       *   "inetOrgPerson"
00830                       * - a search for "top" will return everything
00831                       */
00832                      if ( is_object_subclass( oc, bsi->bsi_oc->bom_oc ) ) {
00833                             static struct berval ldap_entry_objclasses = BER_BVC( "ldap_entry_objclasses" );
00834 
00835                             backsql_merge_from_tbls( bsi, &ldap_entry_objclasses );
00836 
00837                             backsql_strfcat_x( &bsi->bsi_flt_where,
00838                                           bsi->bsi_op->o_tmpmemctx,
00839                                           "lbl",
00840                                           (ber_len_t)STRLENOF( "(2=2 OR (ldap_entries.id=ldap_entry_objclasses.entry_id AND ldap_entry_objclasses.oc_name='" /* ')) */ ),
00841                                                  "(2=2 OR (ldap_entries.id=ldap_entry_objclasses.entry_id AND ldap_entry_objclasses.oc_name='" /* ')) */,
00842                                           &bsi->bsi_oc->bom_oc->soc_cname,
00843                                           (ber_len_t)STRLENOF( /* ((' */ "'))" ),
00844                                                  /* ((' */ "'))" );
00845                             bsi->bsi_status = LDAP_SUCCESS;
00846                             rc = 1;
00847                             goto done;
00848                      }
00849 
00850                      break;
00851               }
00852 
00853               case LDAP_FILTER_PRESENT:
00854                      backsql_strfcat_x( &bsi->bsi_flt_where,
00855                                    bsi->bsi_op->o_tmpmemctx,
00856                                    "l",
00857                                    (ber_len_t)STRLENOF( "3=3" ), "3=3" );
00858                      bsi->bsi_status = LDAP_SUCCESS;
00859                      rc = 1;
00860                      goto done;
00861 
00862                      /* FIXME: LDAP_FILTER_EXT? */
00863                      
00864               default:
00865                      Debug( LDAP_DEBUG_TRACE,
00866                                    "backsql_process_filter(): "
00867                                    "illegal/unhandled filter "
00868                                    "on objectClass attribute",
00869                                    0, 0, 0 );
00870                      bsi->bsi_status = LDAP_OTHER;
00871                      rc = -1;
00872                      goto done;
00873               }
00874 
00875        } else if ( ad == slap_schema.si_ad_entryUUID ) {
00876               unsigned long oc_id;
00877 #ifdef BACKSQL_ARBITRARY_KEY
00878               struct berval keyval;
00879 #else /* ! BACKSQL_ARBITRARY_KEY */
00880               unsigned long keyval;
00881               char          keyvalbuf[LDAP_PVT_INTTYPE_CHARS(unsigned long)];
00882 #endif /* ! BACKSQL_ARBITRARY_KEY */
00883 
00884               switch ( f->f_choice ) {
00885               case LDAP_FILTER_EQUALITY:
00886                      backsql_entryUUID_decode( &f->f_av_value, &oc_id, &keyval );
00887 
00888                      if ( oc_id != bsi->bsi_oc->bom_id ) {
00889                             bsi->bsi_status = LDAP_SUCCESS;
00890                             rc = -1;
00891                             goto done;
00892                      }
00893 
00894 #ifdef BACKSQL_ARBITRARY_KEY
00895                      backsql_strfcat_x( &bsi->bsi_flt_where,
00896                                    bsi->bsi_op->o_tmpmemctx,
00897                                    "bcblbc",
00898                                    &bsi->bsi_oc->bom_keytbl, '.',
00899                                    &bsi->bsi_oc->bom_keycol,
00900                                    STRLENOF( " LIKE '" ), " LIKE '",
00901                                    &keyval, '\'' );
00902 #else /* ! BACKSQL_ARBITRARY_KEY */
00903                      snprintf( keyvalbuf, sizeof( keyvalbuf ), "%lu", keyval );
00904                      backsql_strfcat_x( &bsi->bsi_flt_where,
00905                                    bsi->bsi_op->o_tmpmemctx,
00906                                    "bcbcs",
00907                                    &bsi->bsi_oc->bom_keytbl, '.',
00908                                    &bsi->bsi_oc->bom_keycol, '=', keyvalbuf );
00909 #endif /* ! BACKSQL_ARBITRARY_KEY */
00910                      break;
00911 
00912               case LDAP_FILTER_PRESENT:
00913                      backsql_strfcat_x( &bsi->bsi_flt_where,
00914                                    bsi->bsi_op->o_tmpmemctx,
00915                                    "l",
00916                                    (ber_len_t)STRLENOF( "4=4" ), "4=4" );
00917                      break;
00918 
00919               default:
00920                      rc = -1;
00921                      goto done;
00922               }
00923 
00924               bsi->bsi_flags |= BSQL_SF_FILTER_ENTRYUUID;
00925               rc = 1;
00926               goto done;
00927 
00928 #ifdef BACKSQL_SYNCPROV
00929        } else if ( ad == slap_schema.si_ad_entryCSN ) {
00930               /*
00931                * support for syncrepl as provider...
00932                */
00933 #if 0
00934               if ( !bsi->bsi_op->o_sync ) {
00935                      /* unsupported at present... */
00936                      bsi->bsi_status = LDAP_OTHER;
00937                      rc = -1;
00938                      goto done;
00939               }
00940 #endif
00941 
00942               bsi->bsi_flags |= ( BSQL_SF_FILTER_ENTRYCSN | BSQL_SF_RETURN_ENTRYUUID);
00943 
00944               /* if doing a syncrepl, try to return as much as possible,
00945                * and always match the filter */
00946               backsql_strfcat_x( &bsi->bsi_flt_where,
00947                             bsi->bsi_op->o_tmpmemctx,
00948                             "l",
00949                             (ber_len_t)STRLENOF( "5=5" ), "5=5" );
00950 
00951               /* save for later use in operational attributes */
00952               /* FIXME: saves only the first occurrence, because 
00953                * the filter during updates is written as
00954                * "(&(entryCSN<={contextCSN})(entryCSN>={oldContextCSN})({filter}))"
00955                * so we want our fake entryCSN to match the greatest
00956                * value
00957                */
00958               if ( bsi->bsi_op->o_private == NULL ) {
00959                      bsi->bsi_op->o_private = &f->f_av_value;
00960               }
00961               bsi->bsi_status = LDAP_SUCCESS;
00962 
00963               rc = 1;
00964               goto done;
00965 #endif /* BACKSQL_SYNCPROV */
00966 
00967        } else if ( ad == slap_schema.si_ad_hasSubordinates || ad == NULL ) {
00968               /*
00969                * FIXME: this is not robust; e.g. a filter
00970                * '(!(hasSubordinates=TRUE))' fails because
00971                * in SQL it would read 'NOT (1=1)' instead 
00972                * of no condition.  
00973                * Note however that hasSubordinates is boolean, 
00974                * so a more appropriate filter would be 
00975                * '(hasSubordinates=FALSE)'
00976                *
00977                * A more robust search for hasSubordinates
00978                * would * require joining the ldap_entries table
00979                * selecting if there are descendants of the
00980                * candidate.
00981                */
00982               backsql_strfcat_x( &bsi->bsi_flt_where,
00983                             bsi->bsi_op->o_tmpmemctx,
00984                             "l",
00985                             (ber_len_t)STRLENOF( "6=6" ), "6=6" );
00986               if ( ad == slap_schema.si_ad_hasSubordinates ) {
00987                      /*
00988                       * instruct candidate selection algorithm
00989                       * and attribute list to try to detect
00990                       * if an entry has subordinates
00991                       */
00992                      bsi->bsi_flags |= BSQL_SF_FILTER_HASSUBORDINATE;
00993 
00994               } else {
00995                      /*
00996                       * clear attributes to fetch, to require ALL
00997                       * and try extended match on all attributes
00998                       */
00999                      backsql_attrlist_add( bsi, NULL );
01000               }
01001               rc = 1;
01002               goto done;
01003        }
01004 
01005        /*
01006         * attribute inheritance:
01007         */
01008        if ( backsql_supad2at( bsi->bsi_oc, ad, &vat ) ) {
01009               bsi->bsi_status = LDAP_OTHER;
01010               rc = -1;
01011               goto done;
01012        }
01013 
01014        if ( vat == NULL ) {
01015               /* search anyway; other parts of the filter
01016                * may succeeed */
01017               backsql_strfcat_x( &bsi->bsi_flt_where,
01018                             bsi->bsi_op->o_tmpmemctx,
01019                             "l",
01020                             (ber_len_t)STRLENOF( "7=7" ), "7=7" );
01021               bsi->bsi_status = LDAP_SUCCESS;
01022               rc = 1;
01023               goto done;
01024        }
01025 
01026        /* if required, open extra level of parens */
01027        done = 0;
01028        if ( vat[0]->bam_next || vat[1] ) {
01029               backsql_strfcat_x( &bsi->bsi_flt_where,
01030                             bsi->bsi_op->o_tmpmemctx,
01031                             "c", '(' );
01032               done = 1;
01033        }
01034 
01035        i = 0;
01036 next:;
01037        /* apply attr */
01038        if ( backsql_process_filter_attr( bsi, f, vat[i] ) == -1 ) {
01039               return -1;
01040        }
01041 
01042        /* if more definitions of the same attr, apply */
01043        if ( vat[i]->bam_next ) {
01044               backsql_strfcat_x( &bsi->bsi_flt_where,
01045                             bsi->bsi_op->o_tmpmemctx,
01046                             "l",
01047                      STRLENOF( " OR " ), " OR " );
01048               vat[i] = vat[i]->bam_next;
01049               goto next;
01050        }
01051 
01052        /* if more descendants of the same attr, apply */
01053        i++;
01054        if ( vat[i] ) {
01055               backsql_strfcat_x( &bsi->bsi_flt_where,
01056                             bsi->bsi_op->o_tmpmemctx,
01057                             "l",
01058                      STRLENOF( " OR " ), " OR " );
01059               goto next;
01060        }
01061 
01062        /* if needed, close extra level of parens */
01063        if ( done ) {
01064               backsql_strfcat_x( &bsi->bsi_flt_where,
01065                             bsi->bsi_op->o_tmpmemctx,
01066                             "c", ')' );
01067        }
01068 
01069        rc = 1;
01070 
01071 done:;
01072        if ( vat ) {
01073               ch_free( vat );
01074        }
01075 
01076        Debug( LDAP_DEBUG_TRACE,
01077                      "<==backsql_process_filter() %s\n",
01078                      rc == 1 ? "succeeded" : "failed", 0, 0);
01079 
01080        return rc;
01081 }
01082 
01083 static int
01084 backsql_process_filter_eq( backsql_srch_info *bsi, backsql_at_map_rec *at,
01085               int casefold, struct berval *filter_value )
01086 {
01087        /*
01088         * maybe we should check type of at->sel_expr here somehow,
01089         * to know whether upper_func is applicable, but for now
01090         * upper_func stuff is made for Oracle, where UPPER is
01091         * safely applicable to NUMBER etc.
01092         */
01093        if ( casefold && BACKSQL_AT_CANUPPERCASE( at ) ) {
01094               ber_len_t     start;
01095 
01096               backsql_strfcat_x( &bsi->bsi_flt_where,
01097                             bsi->bsi_op->o_tmpmemctx,
01098                             "cbl",
01099                             '(', /* ) */
01100                             &at->bam_sel_expr_u, 
01101                             (ber_len_t)STRLENOF( "='" ),
01102                                    "='" );
01103 
01104               start = bsi->bsi_flt_where.bb_val.bv_len;
01105 
01106               backsql_strfcat_x( &bsi->bsi_flt_where,
01107                             bsi->bsi_op->o_tmpmemctx,
01108                             "bl",
01109                             filter_value, 
01110                             (ber_len_t)STRLENOF( /* (' */ "')" ),
01111                                    /* (' */ "')" );
01112 
01113               ldap_pvt_str2upper( &bsi->bsi_flt_where.bb_val.bv_val[ start ] );
01114 
01115        } else {
01116               backsql_strfcat_x( &bsi->bsi_flt_where,
01117                             bsi->bsi_op->o_tmpmemctx,
01118                             "cblbl",
01119                             '(', /* ) */
01120                             &at->bam_sel_expr,
01121                             (ber_len_t)STRLENOF( "='" ), "='",
01122                             filter_value,
01123                             (ber_len_t)STRLENOF( /* (' */ "')" ),
01124                                    /* (' */ "')" );
01125        }
01126 
01127        return 1;
01128 }
01129        
01130 static int
01131 backsql_process_filter_like( backsql_srch_info *bsi, backsql_at_map_rec *at,
01132               int casefold, struct berval *filter_value )
01133 {
01134        /*
01135         * maybe we should check type of at->sel_expr here somehow,
01136         * to know whether upper_func is applicable, but for now
01137         * upper_func stuff is made for Oracle, where UPPER is
01138         * safely applicable to NUMBER etc.
01139         */
01140        if ( casefold && BACKSQL_AT_CANUPPERCASE( at ) ) {
01141               ber_len_t     start;
01142 
01143               backsql_strfcat_x( &bsi->bsi_flt_where,
01144                             bsi->bsi_op->o_tmpmemctx,
01145                             "cbl",
01146                             '(', /* ) */
01147                             &at->bam_sel_expr_u, 
01148                             (ber_len_t)STRLENOF( " LIKE '%" ),
01149                                    " LIKE '%" );
01150 
01151               start = bsi->bsi_flt_where.bb_val.bv_len;
01152 
01153               backsql_strfcat_x( &bsi->bsi_flt_where,
01154                             bsi->bsi_op->o_tmpmemctx,
01155                             "bl",
01156                             filter_value, 
01157                             (ber_len_t)STRLENOF( /* (' */ "%')" ),
01158                                    /* (' */ "%')" );
01159 
01160               ldap_pvt_str2upper( &bsi->bsi_flt_where.bb_val.bv_val[ start ] );
01161 
01162        } else {
01163               backsql_strfcat_x( &bsi->bsi_flt_where,
01164                             bsi->bsi_op->o_tmpmemctx,
01165                             "cblbl",
01166                             '(', /* ) */
01167                             &at->bam_sel_expr,
01168                             (ber_len_t)STRLENOF( " LIKE '%" ),
01169                                    " LIKE '%",
01170                             filter_value,
01171                             (ber_len_t)STRLENOF( /* (' */ "%')" ),
01172                                    /* (' */ "%')" );
01173        }
01174 
01175        return 1;
01176 }
01177 
01178 static int
01179 backsql_process_filter_attr( backsql_srch_info *bsi, Filter *f, backsql_at_map_rec *at )
01180 {
01181        backsql_info         *bi = (backsql_info *)bsi->bsi_op->o_bd->be_private;
01182        int                  casefold = 0;
01183        struct berval        *filter_value = NULL;
01184        MatchingRule         *matching_rule = NULL;
01185        struct berval        ordering = BER_BVC("<=");
01186 
01187        Debug( LDAP_DEBUG_TRACE, "==>backsql_process_filter_attr(%s)\n",
01188               at->bam_ad->ad_cname.bv_val, 0, 0 );
01189 
01190        /*
01191         * need to add this attribute to list of attrs to load,
01192         * so that we can do test_filter() later
01193         */
01194        backsql_attrlist_add( bsi, at->bam_ad );
01195 
01196        backsql_merge_from_tbls( bsi, &at->bam_from_tbls );
01197 
01198        if ( !BER_BVISNULL( &at->bam_join_where )
01199                      && strstr( bsi->bsi_join_where.bb_val.bv_val,
01200                             at->bam_join_where.bv_val ) == NULL )
01201        {
01202                      backsql_strfcat_x( &bsi->bsi_join_where,
01203                             bsi->bsi_op->o_tmpmemctx,
01204                             "lb",
01205                             (ber_len_t)STRLENOF( " AND " ), " AND ",
01206                             &at->bam_join_where );
01207        }
01208 
01209        if ( f->f_choice & SLAPD_FILTER_UNDEFINED ) {
01210               backsql_strfcat_x( &bsi->bsi_flt_where,
01211                      bsi->bsi_op->o_tmpmemctx,
01212                      "l",
01213                      (ber_len_t)STRLENOF( "1=0" ), "1=0" );
01214               return 1;
01215        }
01216 
01217        switch ( f->f_choice ) {
01218        case LDAP_FILTER_EQUALITY:
01219               filter_value = &f->f_av_value;
01220               matching_rule = at->bam_ad->ad_type->sat_equality;
01221 
01222               goto equality_match;
01223 
01224               /* fail over into next case */
01225               
01226        case LDAP_FILTER_EXT:
01227               filter_value = &f->f_mra->ma_value;
01228               matching_rule = f->f_mr_rule;
01229 
01230 equality_match:;
01231               /* always uppercase strings by now */
01232 #ifdef BACKSQL_UPPERCASE_FILTER
01233               if ( SLAP_MR_ASSOCIATED( matching_rule,
01234                                    bi->sql_caseIgnoreMatch ) )
01235 #endif /* BACKSQL_UPPERCASE_FILTER */
01236               {
01237                      casefold = 1;
01238               }
01239 
01240               /* FIXME: directoryString filtering should use a similar
01241                * approach to deal with non-prettified values like
01242                * " A  non    prettified   value  ", by using a LIKE
01243                * filter with all whitespaces collapsed to a single '%' */
01244               if ( SLAP_MR_ASSOCIATED( matching_rule,
01245                                    bi->sql_telephoneNumberMatch ) )
01246               {
01247                      struct berval bv;
01248                      ber_len_t     i;
01249 
01250                      /*
01251                       * to check for matching telephone numbers
01252                       * with intermized chars, e.g. val='1234'
01253                       * use
01254                       * 
01255                       * val LIKE '%1%2%3%4%'
01256                       */
01257 
01258                      bv.bv_len = 2 * filter_value->bv_len - 1;
01259                      bv.bv_val = ch_malloc( bv.bv_len + 1 );
01260 
01261                      bv.bv_val[ 0 ] = filter_value->bv_val[ 0 ];
01262                      for ( i = 1; i < filter_value->bv_len; i++ ) {
01263                             bv.bv_val[ 2 * i - 1 ] = '%';
01264                             bv.bv_val[ 2 * i ] = filter_value->bv_val[ i ];
01265                      }
01266                      bv.bv_val[ 2 * i - 1 ] = '\0';
01267 
01268                      (void)backsql_process_filter_like( bsi, at, casefold, &bv );
01269                      ch_free( bv.bv_val );
01270 
01271                      break;
01272               }
01273 
01274               /* NOTE: this is required by objectClass inheritance 
01275                * and auxiliary objectClass use in filters for slightly
01276                * more efficient candidate selection. */
01277               /* FIXME: a bit too many specializations to deal with
01278                * very specific cases... */
01279               if ( at->bam_ad == slap_schema.si_ad_objectClass
01280                             || at->bam_ad == slap_schema.si_ad_structuralObjectClass )
01281               {
01282                      backsql_strfcat_x( &bsi->bsi_flt_where,
01283                                    bsi->bsi_op->o_tmpmemctx,
01284                                    "lbl",
01285                                    (ber_len_t)STRLENOF( "(ldap_entries.id=ldap_entry_objclasses.entry_id AND ldap_entry_objclasses.oc_name='" /* ') */ ),
01286                                           "(ldap_entries.id=ldap_entry_objclasses.entry_id AND ldap_entry_objclasses.oc_name='" /* ') */,
01287                                    filter_value,
01288                                    (ber_len_t)STRLENOF( /* (' */ "')" ),
01289                                           /* (' */ "')" );
01290                      break;
01291               }
01292 
01293               /*
01294                * maybe we should check type of at->sel_expr here somehow,
01295                * to know whether upper_func is applicable, but for now
01296                * upper_func stuff is made for Oracle, where UPPER is
01297                * safely applicable to NUMBER etc.
01298                */
01299               (void)backsql_process_filter_eq( bsi, at, casefold, filter_value );
01300               break;
01301 
01302        case LDAP_FILTER_GE:
01303               ordering.bv_val = ">=";
01304 
01305               /* fall thru to next case */
01306               
01307        case LDAP_FILTER_LE:
01308               filter_value = &f->f_av_value;
01309               
01310               /* always uppercase strings by now */
01311 #ifdef BACKSQL_UPPERCASE_FILTER
01312               if ( at->bam_ad->ad_type->sat_ordering &&
01313                             SLAP_MR_ASSOCIATED( at->bam_ad->ad_type->sat_ordering,
01314                                    bi->sql_caseIgnoreMatch ) )
01315 #endif /* BACKSQL_UPPERCASE_FILTER */
01316               {
01317                      casefold = 1;
01318               }
01319 
01320               /*
01321                * FIXME: should we uppercase the operands?
01322                */
01323               if ( casefold && BACKSQL_AT_CANUPPERCASE( at ) ) {
01324                      ber_len_t     start;
01325 
01326                      backsql_strfcat_x( &bsi->bsi_flt_where,
01327                                    bsi->bsi_op->o_tmpmemctx,
01328                                    "cbbc",
01329                                    '(', /* ) */
01330                                    &at->bam_sel_expr_u, 
01331                                    &ordering,
01332                                    '\'' );
01333 
01334                      start = bsi->bsi_flt_where.bb_val.bv_len;
01335 
01336                      backsql_strfcat_x( &bsi->bsi_flt_where,
01337                                    bsi->bsi_op->o_tmpmemctx,
01338                                    "bl",
01339                                    filter_value, 
01340                                    (ber_len_t)STRLENOF( /* (' */ "')" ),
01341                                           /* (' */ "')" );
01342 
01343                      ldap_pvt_str2upper( &bsi->bsi_flt_where.bb_val.bv_val[ start ] );
01344               
01345               } else {
01346                      backsql_strfcat_x( &bsi->bsi_flt_where,
01347                                    bsi->bsi_op->o_tmpmemctx,
01348                                    "cbbcbl",
01349                                    '(' /* ) */ ,
01350                                    &at->bam_sel_expr,
01351                                    &ordering,
01352                                    '\'',
01353                                    &f->f_av_value,
01354                                    (ber_len_t)STRLENOF( /* (' */ "')" ),
01355                                           /* ( */ "')" );
01356               }
01357               break;
01358 
01359        case LDAP_FILTER_PRESENT:
01360               backsql_strfcat_x( &bsi->bsi_flt_where,
01361                             bsi->bsi_op->o_tmpmemctx,
01362                             "lbl",
01363                             (ber_len_t)STRLENOF( "NOT (" /* ) */),
01364                                    "NOT (", /* ) */
01365                             &at->bam_sel_expr, 
01366                             (ber_len_t)STRLENOF( /* ( */ " IS NULL)" ),
01367                                    /* ( */ " IS NULL)" );
01368               break;
01369 
01370        case LDAP_FILTER_SUBSTRINGS:
01371               backsql_process_sub_filter( bsi, f, at );
01372               break;
01373 
01374        case LDAP_FILTER_APPROX:
01375               /* we do our best */
01376 
01377               /*
01378                * maybe we should check type of at->sel_expr here somehow,
01379                * to know whether upper_func is applicable, but for now
01380                * upper_func stuff is made for Oracle, where UPPER is
01381                * safely applicable to NUMBER etc.
01382                */
01383               (void)backsql_process_filter_like( bsi, at, 1, &f->f_av_value );
01384               break;
01385 
01386        default:
01387               /* unhandled filter type; should not happen */
01388               assert( 0 );
01389               backsql_strfcat_x( &bsi->bsi_flt_where,
01390                             bsi->bsi_op->o_tmpmemctx,
01391                             "l",
01392                             (ber_len_t)STRLENOF( "8=8" ), "8=8" );
01393               break;
01394 
01395        }
01396 
01397        Debug( LDAP_DEBUG_TRACE, "<==backsql_process_filter_attr(%s)\n",
01398               at->bam_ad->ad_cname.bv_val, 0, 0 );
01399 
01400        return 1;
01401 }
01402 
01403 static int
01404 backsql_srch_query( backsql_srch_info *bsi, struct berval *query )
01405 {
01406        backsql_info         *bi = (backsql_info *)bsi->bsi_op->o_bd->be_private;
01407        int                  rc;
01408 
01409        assert( query != NULL );
01410        BER_BVZERO( query );
01411 
01412        bsi->bsi_use_subtree_shortcut = 0;
01413 
01414        Debug( LDAP_DEBUG_TRACE, "==>backsql_srch_query()\n", 0, 0, 0 );
01415        BER_BVZERO( &bsi->bsi_sel.bb_val );
01416        BER_BVZERO( &bsi->bsi_sel.bb_val );
01417        bsi->bsi_sel.bb_len = 0;
01418        BER_BVZERO( &bsi->bsi_from.bb_val );
01419        bsi->bsi_from.bb_len = 0;
01420        BER_BVZERO( &bsi->bsi_join_where.bb_val );
01421        bsi->bsi_join_where.bb_len = 0;
01422        BER_BVZERO( &bsi->bsi_flt_where.bb_val );
01423        bsi->bsi_flt_where.bb_len = 0;
01424 
01425        backsql_strfcat_x( &bsi->bsi_sel,
01426                      bsi->bsi_op->o_tmpmemctx,
01427                      "lbcbc",
01428                      (ber_len_t)STRLENOF( "SELECT DISTINCT ldap_entries.id," ),
01429                             "SELECT DISTINCT ldap_entries.id,", 
01430                      &bsi->bsi_oc->bom_keytbl, 
01431                      '.', 
01432                      &bsi->bsi_oc->bom_keycol, 
01433                      ',' );
01434 
01435        if ( !BER_BVISNULL( &bi->sql_strcast_func ) ) {
01436               backsql_strfcat_x( &bsi->bsi_sel,
01437                             bsi->bsi_op->o_tmpmemctx,
01438                             "blbl",
01439                             &bi->sql_strcast_func, 
01440                             (ber_len_t)STRLENOF( "('" /* ') */ ),
01441                                    "('" /* ') */ ,
01442                             &bsi->bsi_oc->bom_oc->soc_cname,
01443                             (ber_len_t)STRLENOF( /* (' */ "')" ),
01444                                    /* (' */ "')" );
01445        } else {
01446               backsql_strfcat_x( &bsi->bsi_sel,
01447                             bsi->bsi_op->o_tmpmemctx,
01448                             "cbc",
01449                             '\'',
01450                             &bsi->bsi_oc->bom_oc->soc_cname,
01451                             '\'' );
01452        }
01453 
01454        backsql_strfcat_x( &bsi->bsi_sel,
01455                      bsi->bsi_op->o_tmpmemctx,
01456                      "b",
01457                      &bi->sql_dn_oc_aliasing );
01458        backsql_strfcat_x( &bsi->bsi_from,
01459                      bsi->bsi_op->o_tmpmemctx,
01460                      "lb",
01461                      (ber_len_t)STRLENOF( " FROM ldap_entries," ),
01462                             " FROM ldap_entries,",
01463                      &bsi->bsi_oc->bom_keytbl );
01464 
01465        backsql_strfcat_x( &bsi->bsi_join_where,
01466                      bsi->bsi_op->o_tmpmemctx,
01467                      "lbcbl",
01468                      (ber_len_t)STRLENOF( " WHERE " ), " WHERE ",
01469                      &bsi->bsi_oc->bom_keytbl,
01470                      '.',
01471                      &bsi->bsi_oc->bom_keycol,
01472                      (ber_len_t)STRLENOF( "=ldap_entries.keyval AND ldap_entries.oc_map_id=? AND " ),
01473                             "=ldap_entries.keyval AND ldap_entries.oc_map_id=? AND " );
01474 
01475        switch ( bsi->bsi_scope ) {
01476        case LDAP_SCOPE_BASE:
01477               if ( BACKSQL_CANUPPERCASE( bi ) ) {
01478                      backsql_strfcat_x( &bsi->bsi_join_where,
01479                                    bsi->bsi_op->o_tmpmemctx, 
01480                                    "bl",
01481                                    &bi->sql_upper_func,
01482                                    (ber_len_t)STRLENOF( "(ldap_entries.dn)=?" ),
01483                                           "(ldap_entries.dn)=?" );
01484               } else {
01485                      backsql_strfcat_x( &bsi->bsi_join_where,
01486                                    bsi->bsi_op->o_tmpmemctx,
01487                                    "l",
01488                                    (ber_len_t)STRLENOF( "ldap_entries.dn=?" ),
01489                                           "ldap_entries.dn=?" );
01490               }
01491               break;
01492               
01493        case BACKSQL_SCOPE_BASE_LIKE:
01494               if ( BACKSQL_CANUPPERCASE( bi ) ) {
01495                      backsql_strfcat_x( &bsi->bsi_join_where,
01496                                    bsi->bsi_op->o_tmpmemctx,
01497                                    "bl",
01498                                    &bi->sql_upper_func,
01499                                    (ber_len_t)STRLENOF( "(ldap_entries.dn) LIKE ?" ),
01500                                           "(ldap_entries.dn) LIKE ?" );
01501               } else {
01502                      backsql_strfcat_x( &bsi->bsi_join_where,
01503                                    bsi->bsi_op->o_tmpmemctx,
01504                                    "l",
01505                                    (ber_len_t)STRLENOF( "ldap_entries.dn LIKE ?" ),
01506                                           "ldap_entries.dn LIKE ?" );
01507               }
01508               break;
01509               
01510        case LDAP_SCOPE_ONELEVEL:
01511               backsql_strfcat_x( &bsi->bsi_join_where,
01512                             bsi->bsi_op->o_tmpmemctx,
01513                             "l",
01514                             (ber_len_t)STRLENOF( "ldap_entries.parent=?" ),
01515                                    "ldap_entries.parent=?" );
01516               break;
01517 
01518        case LDAP_SCOPE_SUBORDINATE:
01519        case LDAP_SCOPE_SUBTREE:
01520               if ( BACKSQL_USE_SUBTREE_SHORTCUT( bi ) ) {
01521                      int           i;
01522                      BackendDB     *bd = bsi->bsi_op->o_bd;
01523 
01524                      assert( bd->be_nsuffix != NULL );
01525 
01526                      for ( i = 0; !BER_BVISNULL( &bd->be_nsuffix[ i ] ); i++ )
01527                      {
01528                             if ( dn_match( &bd->be_nsuffix[ i ],
01529                                                  bsi->bsi_base_ndn ) )
01530                             {
01531                                    /* pass this to the candidate selection
01532                                     * routine so that the DN is not bound
01533                                     * to the select statement */
01534                                    bsi->bsi_use_subtree_shortcut = 1;
01535                                    break;
01536                             }
01537                      }
01538               }
01539 
01540               if ( bsi->bsi_use_subtree_shortcut ) {
01541                      /* Skip the base DN filter, as every entry will match it */
01542                      backsql_strfcat_x( &bsi->bsi_join_where,
01543                                    bsi->bsi_op->o_tmpmemctx,
01544                                    "l",
01545                                    (ber_len_t)STRLENOF( "9=9"), "9=9");
01546 
01547               } else if ( !BER_BVISNULL( &bi->sql_subtree_cond ) ) {
01548                      /* This should always be true... */
01549                      backsql_strfcat_x( &bsi->bsi_join_where,
01550                                    bsi->bsi_op->o_tmpmemctx,
01551                                    "b",
01552                                    &bi->sql_subtree_cond );
01553 
01554               } else if ( BACKSQL_CANUPPERCASE( bi ) ) {
01555                      backsql_strfcat_x( &bsi->bsi_join_where,
01556                                    bsi->bsi_op->o_tmpmemctx,
01557                                    "bl",
01558                                    &bi->sql_upper_func,
01559                                    (ber_len_t)STRLENOF( "(ldap_entries.dn) LIKE ?" ),
01560                                           "(ldap_entries.dn) LIKE ?"  );
01561 
01562               } else {
01563                      backsql_strfcat_x( &bsi->bsi_join_where,
01564                                    bsi->bsi_op->o_tmpmemctx,
01565                                    "l",
01566                                    (ber_len_t)STRLENOF( "ldap_entries.dn LIKE ?" ),
01567                                           "ldap_entries.dn LIKE ?" );
01568               }
01569 
01570               break;
01571 
01572        default:
01573               assert( 0 );
01574        }
01575 
01576 #ifndef BACKSQL_ARBITRARY_KEY
01577        /* If paged results are in effect, ignore low ldap_entries.id numbers */
01578        if ( get_pagedresults(bsi->bsi_op) > SLAP_CONTROL_IGNORED ) {
01579               unsigned long lowid = 0;
01580 
01581               /* Pick up the previous ldap_entries.id if the previous page ended in this objectClass */
01582               if ( bsi->bsi_oc->bom_id == PAGECOOKIE_TO_SQL_OC( ((PagedResultsState *)bsi->bsi_op->o_pagedresults_state)->ps_cookie ) )
01583               {
01584                      lowid = PAGECOOKIE_TO_SQL_ID( ((PagedResultsState *)bsi->bsi_op->o_pagedresults_state)->ps_cookie );
01585               }
01586 
01587               if ( lowid ) {
01588                      char lowidstring[48];
01589                      int  lowidlen;
01590 
01591                      lowidlen = snprintf( lowidstring, sizeof( lowidstring ),
01592                             " AND ldap_entries.id>%lu", lowid );
01593                      backsql_strfcat_x( &bsi->bsi_join_where,
01594                                    bsi->bsi_op->o_tmpmemctx,
01595                                    "l",
01596                                    (ber_len_t)lowidlen,
01597                                    lowidstring );
01598               }
01599        }
01600 #endif /* ! BACKSQL_ARBITRARY_KEY */
01601 
01602        rc = backsql_process_filter( bsi, bsi->bsi_filter );
01603        if ( rc > 0 ) {
01604               struct berbuf bb = BB_NULL;
01605 
01606               backsql_strfcat_x( &bb,
01607                             bsi->bsi_op->o_tmpmemctx,
01608                             "bbblb",
01609                             &bsi->bsi_sel.bb_val,
01610                             &bsi->bsi_from.bb_val, 
01611                             &bsi->bsi_join_where.bb_val,
01612                             (ber_len_t)STRLENOF( " AND " ), " AND ",
01613                             &bsi->bsi_flt_where.bb_val );
01614 
01615               *query = bb.bb_val;
01616 
01617        } else if ( rc < 0 ) {
01618               /* 
01619                * Indicates that there's no possible way the filter matches
01620                * anything.  No need to issue the query
01621                */
01622               free( query->bv_val );
01623               BER_BVZERO( query );
01624        }
01625  
01626        bsi->bsi_op->o_tmpfree( bsi->bsi_sel.bb_val.bv_val, bsi->bsi_op->o_tmpmemctx );
01627        BER_BVZERO( &bsi->bsi_sel.bb_val );
01628        bsi->bsi_sel.bb_len = 0;
01629        bsi->bsi_op->o_tmpfree( bsi->bsi_from.bb_val.bv_val, bsi->bsi_op->o_tmpmemctx );
01630        BER_BVZERO( &bsi->bsi_from.bb_val );
01631        bsi->bsi_from.bb_len = 0;
01632        bsi->bsi_op->o_tmpfree( bsi->bsi_join_where.bb_val.bv_val, bsi->bsi_op->o_tmpmemctx );
01633        BER_BVZERO( &bsi->bsi_join_where.bb_val );
01634        bsi->bsi_join_where.bb_len = 0;
01635        bsi->bsi_op->o_tmpfree( bsi->bsi_flt_where.bb_val.bv_val, bsi->bsi_op->o_tmpmemctx );
01636        BER_BVZERO( &bsi->bsi_flt_where.bb_val );
01637        bsi->bsi_flt_where.bb_len = 0;
01638        
01639        Debug( LDAP_DEBUG_TRACE, "<==backsql_srch_query() returns %s\n",
01640               query->bv_val ? query->bv_val : "NULL", 0, 0 );
01641        
01642        return ( rc <= 0 ? 1 : 0 );
01643 }
01644 
01645 static int
01646 backsql_oc_get_candidates( void *v_oc, void *v_bsi )
01647 {
01648        backsql_oc_map_rec   *oc = v_oc;
01649        backsql_srch_info    *bsi = v_bsi;
01650        Operation            *op = bsi->bsi_op;
01651        backsql_info         *bi = (backsql_info *)bsi->bsi_op->o_bd->be_private;
01652        struct berval        query;
01653        SQLHSTMT             sth = SQL_NULL_HSTMT;
01654        RETCODE                     rc;
01655        int                  res;
01656        BACKSQL_ROW_NTS             row;
01657        int                  i;
01658        int                  j;
01659        int                  n_candidates = bsi->bsi_n_candidates;
01660 
01661        /* 
01662         * + 1 because we need room for '%';
01663         * + 1 because we need room for ',' for LDAP_SCOPE_SUBORDINATE;
01664         * this makes a subtree
01665         * search for a DN BACKSQL_MAX_DN_LEN long legal 
01666         * if it returns that DN only
01667         */
01668        char                 tmp_base_ndn[ BACKSQL_MAX_DN_LEN + 1 + 1 ];
01669 
01670        bsi->bsi_status = LDAP_SUCCESS;
01671  
01672        Debug( LDAP_DEBUG_TRACE, "==>backsql_oc_get_candidates(): oc=\"%s\"\n",
01673                      BACKSQL_OC_NAME( oc ), 0, 0 );
01674 
01675        /* check for abandon */
01676        if ( op->o_abandon ) {
01677               bsi->bsi_status = SLAPD_ABANDON;
01678               return BACKSQL_AVL_STOP;
01679        }
01680 
01681 #ifndef BACKSQL_ARBITRARY_KEY
01682        /* If paged results have already completed this objectClass, skip it */
01683        if ( get_pagedresults(op) > SLAP_CONTROL_IGNORED ) {
01684               if ( oc->bom_id < PAGECOOKIE_TO_SQL_OC( ((PagedResultsState *)op->o_pagedresults_state)->ps_cookie ) )
01685               {
01686                      return BACKSQL_AVL_CONTINUE;
01687               }
01688        }
01689 #endif /* ! BACKSQL_ARBITRARY_KEY */
01690 
01691        if ( bsi->bsi_n_candidates == -1 ) {
01692               Debug( LDAP_DEBUG_TRACE, "backsql_oc_get_candidates(): "
01693                      "unchecked limit has been overcome\n", 0, 0, 0 );
01694               /* should never get here */
01695               assert( 0 );
01696               bsi->bsi_status = LDAP_ADMINLIMIT_EXCEEDED;
01697               return BACKSQL_AVL_STOP;
01698        }
01699        
01700        bsi->bsi_oc = oc;
01701        res = backsql_srch_query( bsi, &query );
01702        if ( res ) {
01703               Debug( LDAP_DEBUG_TRACE, "backsql_oc_get_candidates(): "
01704                      "error while constructing query for objectclass \"%s\"\n",
01705                      oc->bom_oc->soc_cname.bv_val, 0, 0 );
01706               /*
01707                * FIXME: need to separate errors from legally
01708                * impossible filters
01709                */
01710               switch ( bsi->bsi_status ) {
01711               case LDAP_SUCCESS:
01712               case LDAP_UNDEFINED_TYPE:
01713               case LDAP_NO_SUCH_OBJECT:
01714                      /* we are conservative... */
01715               default:
01716                      bsi->bsi_status = LDAP_SUCCESS;
01717                      /* try next */
01718                      return BACKSQL_AVL_CONTINUE;
01719 
01720               case LDAP_ADMINLIMIT_EXCEEDED:
01721               case LDAP_OTHER:
01722                      /* don't try any more */
01723                      return BACKSQL_AVL_STOP;
01724               }
01725        }
01726 
01727        if ( BER_BVISNULL( &query ) ) {
01728               Debug( LDAP_DEBUG_TRACE, "backsql_oc_get_candidates(): "
01729                      "could not construct query for objectclass \"%s\"\n",
01730                      oc->bom_oc->soc_cname.bv_val, 0, 0 );
01731               bsi->bsi_status = LDAP_SUCCESS;
01732               return BACKSQL_AVL_CONTINUE;
01733        }
01734 
01735        Debug( LDAP_DEBUG_TRACE, "Constructed query: %s\n", 
01736                      query.bv_val, 0, 0 );
01737 
01738        rc = backsql_Prepare( bsi->bsi_dbh, &sth, query.bv_val, 0 );
01739        bsi->bsi_op->o_tmpfree( query.bv_val, bsi->bsi_op->o_tmpmemctx );
01740        BER_BVZERO( &query );
01741        if ( rc != SQL_SUCCESS ) {
01742               Debug( LDAP_DEBUG_TRACE, "backsql_oc_get_candidates(): "
01743                      "error preparing query\n", 0, 0, 0 );
01744               backsql_PrintErrors( bi->sql_db_env, bsi->bsi_dbh, sth, rc );
01745               bsi->bsi_status = LDAP_OTHER;
01746               return BACKSQL_AVL_CONTINUE;
01747        }
01748        
01749        Debug( LDAP_DEBUG_TRACE, "id: '" BACKSQL_IDNUMFMT "'\n",
01750               bsi->bsi_oc->bom_id, 0, 0 );
01751 
01752        rc = backsql_BindParamNumID( sth, 1, SQL_PARAM_INPUT,
01753                      &bsi->bsi_oc->bom_id );
01754        if ( rc != SQL_SUCCESS ) {
01755               Debug( LDAP_DEBUG_TRACE, "backsql_oc_get_candidates(): "
01756                      "error binding objectclass id parameter\n", 0, 0, 0 );
01757               bsi->bsi_status = LDAP_OTHER;
01758               return BACKSQL_AVL_CONTINUE;
01759        }
01760 
01761        switch ( bsi->bsi_scope ) {
01762        case LDAP_SCOPE_BASE:
01763        case BACKSQL_SCOPE_BASE_LIKE:
01764               /*
01765                * We do not accept DNs longer than BACKSQL_MAX_DN_LEN;
01766                * however this should be handled earlier
01767                */
01768               if ( bsi->bsi_base_ndn->bv_len > BACKSQL_MAX_DN_LEN ) {
01769                      bsi->bsi_status = LDAP_OTHER;
01770                      return BACKSQL_AVL_CONTINUE;
01771               }
01772 
01773               AC_MEMCPY( tmp_base_ndn, bsi->bsi_base_ndn->bv_val,
01774                             bsi->bsi_base_ndn->bv_len + 1 );
01775 
01776               /* uppercase DN only if the stored DN can be uppercased
01777                * for comparison */
01778               if ( BACKSQL_CANUPPERCASE( bi ) ) {
01779                      ldap_pvt_str2upper( tmp_base_ndn );
01780               }
01781 
01782               Debug( LDAP_DEBUG_TRACE, "(base)dn: \"%s\"\n",
01783                             tmp_base_ndn, 0, 0 );
01784 
01785               rc = backsql_BindParamStr( sth, 2, SQL_PARAM_INPUT,
01786                             tmp_base_ndn, BACKSQL_MAX_DN_LEN );
01787               if ( rc != SQL_SUCCESS ) {
01788                      Debug( LDAP_DEBUG_TRACE, "backsql_oc_get_candidates(): "
01789                             "error binding base_ndn parameter\n", 0, 0, 0 );
01790                      backsql_PrintErrors( bi->sql_db_env, bsi->bsi_dbh, 
01791                                    sth, rc );
01792                      bsi->bsi_status = LDAP_OTHER;
01793                      return BACKSQL_AVL_CONTINUE;
01794               }
01795               break;
01796 
01797        case LDAP_SCOPE_SUBORDINATE:
01798        case LDAP_SCOPE_SUBTREE:
01799        {
01800               /* if short-cutting the search base,
01801                * don't bind any parameter */
01802               if ( bsi->bsi_use_subtree_shortcut ) {
01803                      break;
01804               }
01805               
01806               /*
01807                * We do not accept DNs longer than BACKSQL_MAX_DN_LEN;
01808                * however this should be handled earlier
01809                */
01810               if ( bsi->bsi_base_ndn->bv_len > BACKSQL_MAX_DN_LEN ) {
01811                      bsi->bsi_status = LDAP_OTHER;
01812                      return BACKSQL_AVL_CONTINUE;
01813               }
01814 
01815               /* 
01816                * Sets the parameters for the SQL built earlier
01817                * NOTE that all the databases could actually use 
01818                * the TimesTen version, which would be cleaner 
01819                * and would also eliminate the need for the
01820                * subtree_cond line in the configuration file.  
01821                * For now, I'm leaving it the way it is, 
01822                * so non-TimesTen databases use the original code.
01823                * But at some point this should get cleaned up.
01824                *
01825                * If "dn" is being used, do a suffix search.
01826                * If "dn_ru" is being used, do a prefix search.
01827                */
01828               if ( BACKSQL_HAS_LDAPINFO_DN_RU( bi ) ) {
01829                      tmp_base_ndn[ 0 ] = '\0';
01830 
01831                      for ( i = 0, j = bsi->bsi_base_ndn->bv_len - 1;
01832                                    j >= 0; i++, j--) {
01833                             tmp_base_ndn[ i ] = bsi->bsi_base_ndn->bv_val[ j ];
01834                      }
01835 
01836                      if ( bsi->bsi_scope == LDAP_SCOPE_SUBORDINATE ) {
01837                             tmp_base_ndn[ i++ ] = ',';
01838                      }
01839 
01840                      tmp_base_ndn[ i ] = '%';
01841                      tmp_base_ndn[ i + 1 ] = '\0';
01842 
01843               } else {
01844                      i = 0;
01845 
01846                      tmp_base_ndn[ i++ ] = '%';
01847 
01848                      if ( bsi->bsi_scope == LDAP_SCOPE_SUBORDINATE ) {
01849                             tmp_base_ndn[ i++ ] = ',';
01850                      }
01851 
01852                      AC_MEMCPY( &tmp_base_ndn[ i ], bsi->bsi_base_ndn->bv_val,
01853                             bsi->bsi_base_ndn->bv_len + 1 );
01854               }
01855 
01856               /* uppercase DN only if the stored DN can be uppercased
01857                * for comparison */
01858               if ( BACKSQL_CANUPPERCASE( bi ) ) {
01859                      ldap_pvt_str2upper( tmp_base_ndn );
01860               }
01861 
01862               if ( bsi->bsi_scope == LDAP_SCOPE_SUBORDINATE ) {
01863                      Debug( LDAP_DEBUG_TRACE, "(children)dn: \"%s\"\n",
01864                             tmp_base_ndn, 0, 0 );
01865               } else {
01866                      Debug( LDAP_DEBUG_TRACE, "(sub)dn: \"%s\"\n",
01867                             tmp_base_ndn, 0, 0 );
01868               }
01869 
01870               rc = backsql_BindParamStr( sth, 2, SQL_PARAM_INPUT,
01871                             tmp_base_ndn, BACKSQL_MAX_DN_LEN );
01872               if ( rc != SQL_SUCCESS ) {
01873                      Debug( LDAP_DEBUG_TRACE, "backsql_oc_get_candidates(): "
01874                             "error binding base_ndn parameter (2)\n",
01875                             0, 0, 0 );
01876                      backsql_PrintErrors( bi->sql_db_env, bsi->bsi_dbh, 
01877                                    sth, rc );
01878                      bsi->bsi_status = LDAP_OTHER;
01879                      return BACKSQL_AVL_CONTINUE;
01880               }
01881               break;
01882        }
01883 
01884        case LDAP_SCOPE_ONELEVEL:
01885               assert( !BER_BVISNULL( &bsi->bsi_base_id.eid_ndn ) );
01886 
01887               Debug( LDAP_DEBUG_TRACE, "(one)id=" BACKSQL_IDFMT "\n",
01888                      BACKSQL_IDARG(bsi->bsi_base_id.eid_id), 0, 0 );
01889               rc = backsql_BindParamID( sth, 2, SQL_PARAM_INPUT,
01890                             &bsi->bsi_base_id.eid_id );
01891               if ( rc != SQL_SUCCESS ) {
01892                      Debug( LDAP_DEBUG_TRACE, "backsql_oc_get_candidates(): "
01893                             "error binding base id parameter\n", 0, 0, 0 );
01894                      bsi->bsi_status = LDAP_OTHER;
01895                      return BACKSQL_AVL_CONTINUE;
01896               }
01897               break;
01898        }
01899        
01900        rc = SQLExecute( sth );
01901        if ( !BACKSQL_SUCCESS( rc ) ) {
01902               Debug( LDAP_DEBUG_TRACE, "backsql_oc_get_candidates(): "
01903                      "error executing query\n", 0, 0, 0 );
01904               backsql_PrintErrors( bi->sql_db_env, bsi->bsi_dbh, sth, rc );
01905               SQLFreeStmt( sth, SQL_DROP );
01906               bsi->bsi_status = LDAP_OTHER;
01907               return BACKSQL_AVL_CONTINUE;
01908        }
01909 
01910        backsql_BindRowAsStrings_x( sth, &row, bsi->bsi_op->o_tmpmemctx );
01911        rc = SQLFetch( sth );
01912        for ( ; BACKSQL_SUCCESS( rc ); rc = SQLFetch( sth ) ) {
01913               struct berval        dn, pdn, ndn;
01914               backsql_entryID             *c_id = NULL;
01915               int                  ret;
01916 
01917               ber_str2bv( row.cols[ 3 ], 0, 0, &dn );
01918 
01919               if ( backsql_api_odbc2dn( bsi->bsi_op, bsi->bsi_rs, &dn ) ) {
01920                      continue;
01921               }
01922 
01923               ret = dnPrettyNormal( NULL, &dn, &pdn, &ndn, op->o_tmpmemctx );
01924               if ( dn.bv_val != row.cols[ 3 ] ) {
01925                      free( dn.bv_val );
01926               }
01927 
01928               if ( ret != LDAP_SUCCESS ) {
01929                      continue;
01930               }
01931 
01932               if ( bi->sql_baseObject && dn_match( &ndn, &bi->sql_baseObject->e_nname ) ) {
01933                      goto cleanup;
01934               }
01935 
01936               c_id = (backsql_entryID *)op->o_tmpcalloc( 1, 
01937                             sizeof( backsql_entryID ), op->o_tmpmemctx );
01938 #ifdef BACKSQL_ARBITRARY_KEY
01939               ber_str2bv_x( row.cols[ 0 ], 0, 1, &c_id->eid_id,
01940                             op->o_tmpmemctx );
01941               ber_str2bv_x( row.cols[ 1 ], 0, 1, &c_id->eid_keyval,
01942                             op->o_tmpmemctx );
01943 #else /* ! BACKSQL_ARBITRARY_KEY */
01944               if ( BACKSQL_STR2ID( &c_id->eid_id, row.cols[ 0 ], 0 ) != 0 ) {
01945                      goto cleanup;
01946               }
01947               if ( BACKSQL_STR2ID( &c_id->eid_keyval, row.cols[ 1 ], 0 ) != 0 ) {
01948                      goto cleanup;
01949               }
01950 #endif /* ! BACKSQL_ARBITRARY_KEY */
01951               c_id->eid_oc = bsi->bsi_oc;
01952               c_id->eid_oc_id = bsi->bsi_oc->bom_id;
01953 
01954               c_id->eid_dn = pdn;
01955               c_id->eid_ndn = ndn;
01956 
01957               /* append at end of list ... */
01958               c_id->eid_next = NULL;
01959               *bsi->bsi_id_listtail = c_id;
01960               bsi->bsi_id_listtail = &c_id->eid_next;
01961 
01962               Debug( LDAP_DEBUG_TRACE, "backsql_oc_get_candidates(): "
01963                      "added entry id=" BACKSQL_IDFMT " keyval=" BACKSQL_IDFMT " dn=\"%s\"\n",
01964                      BACKSQL_IDARG(c_id->eid_id),
01965                      BACKSQL_IDARG(c_id->eid_keyval),
01966                      row.cols[ 3 ] );
01967 
01968               /* count candidates, for unchecked limit */
01969               bsi->bsi_n_candidates--;
01970               if ( bsi->bsi_n_candidates == -1 ) {
01971                      break;
01972               }
01973               continue;
01974 
01975 cleanup:;
01976               if ( !BER_BVISNULL( &pdn ) ) {
01977                      op->o_tmpfree( pdn.bv_val, op->o_tmpmemctx );
01978               }
01979               if ( !BER_BVISNULL( &ndn ) ) {
01980                      op->o_tmpfree( ndn.bv_val, op->o_tmpmemctx );
01981               }
01982               if ( c_id != NULL ) {
01983                      ch_free( c_id );
01984               }
01985        }
01986        backsql_FreeRow_x( &row, bsi->bsi_op->o_tmpmemctx );
01987        SQLFreeStmt( sth, SQL_DROP );
01988 
01989        Debug( LDAP_DEBUG_TRACE, "<==backsql_oc_get_candidates(): %d\n",
01990                      n_candidates - bsi->bsi_n_candidates, 0, 0 );
01991 
01992        return ( bsi->bsi_n_candidates == -1 ? BACKSQL_AVL_STOP : BACKSQL_AVL_CONTINUE );
01993 }
01994 
01995 int
01996 backsql_search( Operation *op, SlapReply *rs )
01997 {
01998        backsql_info         *bi = (backsql_info *)op->o_bd->be_private;
01999        SQLHDBC                     dbh = SQL_NULL_HDBC;
02000        int                  sres;
02001        Entry                user_entry = { 0 },
02002                             base_entry = { 0 };
02003        int                  manageDSAit = get_manageDSAit( op );
02004        time_t               stoptime = 0;
02005        backsql_srch_info    bsi = { 0 };
02006        backsql_entryID             *eid = NULL;
02007        struct berval        nbase = BER_BVNULL;
02008 #ifndef BACKSQL_ARBITRARY_KEY
02009        ID                   lastid = 0;
02010 #endif /* ! BACKSQL_ARBITRARY_KEY */
02011 
02012        Debug( LDAP_DEBUG_TRACE, "==>backsql_search(): "
02013               "base=\"%s\", filter=\"%s\", scope=%d,", 
02014               op->o_req_ndn.bv_val,
02015               op->ors_filterstr.bv_val,
02016               op->ors_scope );
02017        Debug( LDAP_DEBUG_TRACE, " deref=%d, attrsonly=%d, "
02018               "attributes to load: %s\n",
02019               op->ors_deref,
02020               op->ors_attrsonly,
02021               op->ors_attrs == NULL ? "all" : "custom list" );
02022 
02023        if ( op->o_req_ndn.bv_len > BACKSQL_MAX_DN_LEN ) {
02024               Debug( LDAP_DEBUG_TRACE, "backsql_search(): "
02025                      "search base length (%ld) exceeds max length (%d)\n", 
02026                      op->o_req_ndn.bv_len, BACKSQL_MAX_DN_LEN, 0 );
02027               /*
02028                * FIXME: a LDAP_NO_SUCH_OBJECT could be appropriate
02029                * since it is impossible that such a long DN exists
02030                * in the backend
02031                */
02032               rs->sr_err = LDAP_ADMINLIMIT_EXCEEDED;
02033               send_ldap_result( op, rs );
02034               return 1;
02035        }
02036 
02037        sres = backsql_get_db_conn( op, &dbh );
02038        if ( sres != LDAP_SUCCESS ) {
02039               Debug( LDAP_DEBUG_TRACE, "backsql_search(): "
02040                      "could not get connection handle - exiting\n", 
02041                      0, 0, 0 );
02042               rs->sr_err = sres;
02043               rs->sr_text = sres == LDAP_OTHER ?  "SQL-backend error" : NULL;
02044               send_ldap_result( op, rs );
02045               return 1;
02046        }
02047 
02048        /* compute it anyway; root does not use it */
02049        stoptime = op->o_time + op->ors_tlimit;
02050 
02051        /* init search */
02052        bsi.bsi_e = &base_entry;
02053        rs->sr_err = backsql_init_search( &bsi, &op->o_req_ndn,
02054                      op->ors_scope,
02055                      stoptime, op->ors_filter,
02056                      dbh, op, rs, op->ors_attrs,
02057                      ( BACKSQL_ISF_MATCHED | BACKSQL_ISF_GET_ENTRY ) );
02058        switch ( rs->sr_err ) {
02059        case LDAP_SUCCESS:
02060               break;
02061 
02062        case LDAP_REFERRAL:
02063               if ( manageDSAit && !BER_BVISNULL( &bsi.bsi_e->e_nname ) &&
02064                             dn_match( &op->o_req_ndn, &bsi.bsi_e->e_nname ) )
02065               {
02066                      rs->sr_err = LDAP_SUCCESS;
02067                      rs->sr_text = NULL;
02068                      rs->sr_matched = NULL;
02069                      if ( rs->sr_ref ) {
02070                             ber_bvarray_free( rs->sr_ref );
02071                             rs->sr_ref = NULL;
02072                      }
02073                      break;
02074               }
02075 
02076               /* an entry was created; free it */
02077               entry_clean( bsi.bsi_e );
02078 
02079               /* fall thru */
02080 
02081        default:
02082               if ( !BER_BVISNULL( &base_entry.e_nname )
02083                             && !access_allowed( op, &base_entry,
02084                                    slap_schema.si_ad_entry, NULL,
02085                                    ACL_DISCLOSE, NULL ) )
02086               {
02087                      rs->sr_err = LDAP_NO_SUCH_OBJECT;
02088                      if ( rs->sr_ref ) {
02089                             ber_bvarray_free( rs->sr_ref );
02090                             rs->sr_ref = NULL;
02091                      }
02092                      rs->sr_matched = NULL;
02093                      rs->sr_text = NULL;
02094               }
02095 
02096               send_ldap_result( op, rs );
02097 
02098               if ( rs->sr_ref ) {
02099                      ber_bvarray_free( rs->sr_ref );
02100                      rs->sr_ref = NULL;
02101               }
02102 
02103               if ( !BER_BVISNULL( &base_entry.e_nname ) ) {
02104                      entry_clean( &base_entry );
02105               }
02106 
02107               goto done;
02108        }
02109        /* NOTE: __NEW__ "search" access is required
02110         * on searchBase object */
02111        {
02112               slap_mask_t   mask;
02113               
02114               if ( get_assert( op ) &&
02115                             ( test_filter( op, &base_entry, get_assertion( op ) )
02116                               != LDAP_COMPARE_TRUE ) )
02117               {
02118                      rs->sr_err = LDAP_ASSERTION_FAILED;
02119                      
02120               }
02121               if ( ! access_allowed_mask( op, &base_entry,
02122                                    slap_schema.si_ad_entry,
02123                                    NULL, ACL_SEARCH, NULL, &mask ) )
02124               {
02125                      if ( rs->sr_err == LDAP_SUCCESS ) {
02126                             rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
02127                      }
02128               }
02129 
02130               if ( rs->sr_err != LDAP_SUCCESS ) {
02131                      if ( !ACL_GRANT( mask, ACL_DISCLOSE ) ) {
02132                             rs->sr_err = LDAP_NO_SUCH_OBJECT;
02133                             rs->sr_text = NULL;
02134                      }
02135                      send_ldap_result( op, rs );
02136                      goto done;
02137               }
02138        }
02139 
02140        bsi.bsi_e = NULL;
02141 
02142        bsi.bsi_n_candidates =
02143               ( op->ors_limit == NULL     /* isroot == TRUE */ ? -2 : 
02144               ( op->ors_limit->lms_s_unchecked == -1 ? -2 :
02145               ( op->ors_limit->lms_s_unchecked ) ) );
02146 
02147 #ifndef BACKSQL_ARBITRARY_KEY
02148        /* If paged results are in effect, check the paging cookie */
02149        if ( get_pagedresults( op ) > SLAP_CONTROL_IGNORED ) {
02150               rs->sr_err = parse_paged_cookie( op, rs );
02151               if ( rs->sr_err != LDAP_SUCCESS ) {
02152                      send_ldap_result( op, rs );
02153                      goto done;
02154               }
02155        }
02156 #endif /* ! BACKSQL_ARBITRARY_KEY */
02157 
02158        switch ( bsi.bsi_scope ) {
02159        case LDAP_SCOPE_BASE:
02160        case BACKSQL_SCOPE_BASE_LIKE:
02161               /*
02162                * probably already found...
02163                */
02164               bsi.bsi_id_list = &bsi.bsi_base_id;
02165               bsi.bsi_id_listtail = &bsi.bsi_base_id.eid_next;
02166               break;
02167 
02168        case LDAP_SCOPE_SUBTREE:
02169               /*
02170                * if baseObject is defined, and if it is the root 
02171                * of the search, add it to the candidate list
02172                */
02173               if ( bi->sql_baseObject && BACKSQL_IS_BASEOBJECT_ID( &bsi.bsi_base_id.eid_id ) )
02174               {
02175                      bsi.bsi_id_list = &bsi.bsi_base_id;
02176                      bsi.bsi_id_listtail = &bsi.bsi_base_id.eid_next;
02177               }
02178 
02179               /* FALLTHRU */
02180        default:
02181 
02182               /*
02183                * for each objectclass we try to construct query which gets IDs
02184                * of entries matching LDAP query filter and scope (or at least 
02185                * candidates), and get the IDs. Do this in ID order for paging.
02186                */
02187               avl_apply( bi->sql_oc_by_id, backsql_oc_get_candidates,
02188                             &bsi, BACKSQL_AVL_STOP, AVL_INORDER );
02189 
02190               /* check for abandon */
02191               if ( op->o_abandon ) {
02192                      eid = bsi.bsi_id_list;
02193                      rs->sr_err = SLAPD_ABANDON;
02194                      goto send_results;
02195               }
02196        }
02197 
02198        if ( op->ors_limit != NULL  /* isroot == FALSE */
02199                      && op->ors_limit->lms_s_unchecked != -1
02200                      && bsi.bsi_n_candidates == -1 )
02201        {
02202               rs->sr_err = LDAP_ADMINLIMIT_EXCEEDED;
02203               send_ldap_result( op, rs );
02204               goto done;
02205        }
02206 
02207        /*
02208         * now we load candidate entries (only those attributes 
02209         * mentioned in attrs and filter), test it against full filter 
02210         * and then send to client; don't free entry_id if baseObject...
02211         */
02212        for ( eid = bsi.bsi_id_list;
02213               eid != NULL; 
02214               eid = backsql_free_entryID( 
02215                      eid, eid == &bsi.bsi_base_id ? 0 : 1, op->o_tmpmemctx ) )
02216        {
02217               int           rc;
02218               Attribute     *a_hasSubordinate = NULL,
02219                             *a_entryUUID = NULL,
02220                             *a_entryCSN = NULL,
02221                             **ap = NULL;
02222               Entry         *e = NULL;
02223 
02224               /* check for abandon */
02225               if ( op->o_abandon ) {
02226                      rs->sr_err = SLAPD_ABANDON;
02227                      goto send_results;
02228               }
02229 
02230               /* check time limit */
02231               if ( op->ors_tlimit != SLAP_NO_LIMIT
02232                             && slap_get_time() > stoptime )
02233               {
02234                      rs->sr_err = LDAP_TIMELIMIT_EXCEEDED;
02235                      rs->sr_ctrls = NULL;
02236                      rs->sr_ref = rs->sr_v2ref;
02237                      goto send_results;
02238               }
02239 
02240               Debug(LDAP_DEBUG_TRACE, "backsql_search(): loading data "
02241                      "for entry id=" BACKSQL_IDFMT " oc_id=" BACKSQL_IDNUMFMT ", keyval=" BACKSQL_IDFMT "\n",
02242                      BACKSQL_IDARG(eid->eid_id),
02243                      eid->eid_oc_id,
02244                      BACKSQL_IDARG(eid->eid_keyval) );
02245 
02246               /* check scope */
02247               switch ( op->ors_scope ) {
02248               case LDAP_SCOPE_BASE:
02249               case BACKSQL_SCOPE_BASE_LIKE:
02250                      if ( !dn_match( &eid->eid_ndn, &op->o_req_ndn ) ) {
02251                             goto next_entry2;
02252                      }
02253                      break;
02254 
02255               case LDAP_SCOPE_ONE:
02256               {
02257                      struct berval rdn = eid->eid_ndn;
02258 
02259                      rdn.bv_len -= op->o_req_ndn.bv_len + STRLENOF( "," );
02260                      if ( !dnIsOneLevelRDN( &rdn ) ) {
02261                             goto next_entry2;
02262                      }
02263                      /* fall thru */
02264               }
02265 
02266               case LDAP_SCOPE_SUBORDINATE:
02267                      /* discard the baseObject entry */
02268                      if ( dn_match( &eid->eid_ndn, &op->o_req_ndn ) ) {
02269                             goto next_entry2;
02270                      }
02271                      /* FALLTHRU */
02272               case LDAP_SCOPE_SUBTREE:
02273                      /* FIXME: this should never fail... */
02274                      if ( !dnIsSuffix( &eid->eid_ndn, &op->o_req_ndn ) ) {
02275                             goto next_entry2;
02276                      }
02277                      break;
02278               }
02279 
02280               if ( BACKSQL_IS_BASEOBJECT_ID( &eid->eid_id ) ) {
02281                      /* don't recollect baseObject... */
02282                      e = bi->sql_baseObject;
02283 
02284               } else if ( eid == &bsi.bsi_base_id ) {
02285                      /* don't recollect searchBase object... */
02286                      e = &base_entry;
02287 
02288               } else {
02289                      bsi.bsi_e = &user_entry;
02290                      rc = backsql_id2entry( &bsi, eid );
02291                      if ( rc != LDAP_SUCCESS ) {
02292                             Debug( LDAP_DEBUG_TRACE, "backsql_search(): "
02293                                    "error %d in backsql_id2entry() "
02294                                    "- skipping\n", rc, 0, 0 );
02295                             continue;
02296                      }
02297                      e = &user_entry;
02298               }
02299 
02300               if ( !manageDSAit &&
02301                             op->ors_scope != LDAP_SCOPE_BASE &&
02302                             op->ors_scope != BACKSQL_SCOPE_BASE_LIKE &&
02303                             is_entry_referral( e ) )
02304               {
02305                      BerVarray refs;
02306 
02307                      refs = get_entry_referrals( op, e );
02308                      if ( !refs ) {
02309                             backsql_srch_info    bsi2 = { 0 };
02310                             Entry                user_entry2 = { 0 };
02311 
02312                             /* retry with the full entry... */
02313                             bsi2.bsi_e = &user_entry2;
02314                             rc = backsql_init_search( &bsi2,
02315                                           &e->e_nname,
02316                                           LDAP_SCOPE_BASE, 
02317                                           (time_t)(-1), NULL,
02318                                           dbh, op, rs, NULL,
02319                                           BACKSQL_ISF_GET_ENTRY );
02320                             if ( rc == LDAP_SUCCESS ) {
02321                                    if ( is_entry_referral( &user_entry2 ) )
02322                                    {
02323                                           refs = get_entry_referrals( op,
02324                                                         &user_entry2 );
02325                                    } else {
02326                                           rs->sr_err = LDAP_OTHER;
02327                                    }
02328                                    backsql_entry_clean( op, &user_entry2 );
02329                             }
02330                             if ( bsi2.bsi_attrs != NULL ) {
02331                                    op->o_tmpfree( bsi2.bsi_attrs,
02332                                                  op->o_tmpmemctx );
02333                             }
02334                      }
02335 
02336                      if ( refs ) {
02337                             rs->sr_ref = referral_rewrite( refs,
02338                                           &e->e_name,
02339                                           &op->o_req_dn,
02340                                           op->ors_scope );
02341                             ber_bvarray_free( refs );
02342                      }
02343 
02344                      if ( rs->sr_ref ) {
02345                             rs->sr_err = LDAP_REFERRAL;
02346 
02347                      } else {
02348                             rs->sr_text = "bad referral object";
02349                      }
02350 
02351                      rs->sr_entry = e;
02352                      rs->sr_matched = user_entry.e_name.bv_val;
02353                      send_search_reference( op, rs );
02354 
02355                      ber_bvarray_free( rs->sr_ref );
02356                      rs->sr_ref = NULL;
02357                      rs->sr_matched = NULL;
02358                      rs->sr_entry = NULL;
02359                      if ( rs->sr_err == LDAP_REFERRAL ) {
02360                             rs->sr_err = LDAP_SUCCESS;
02361                      }
02362 
02363                      goto next_entry;
02364               }
02365 
02366               /*
02367                * We use this flag since we need to parse the filter
02368                * anyway; we should have used the frontend API function
02369                * filter_has_subordinates()
02370                */
02371               if ( bsi.bsi_flags & BSQL_SF_FILTER_HASSUBORDINATE ) {
02372                      rc = backsql_has_children( op, dbh, &e->e_nname );
02373 
02374                      switch ( rc ) {
02375                      case LDAP_COMPARE_TRUE:
02376                      case LDAP_COMPARE_FALSE:
02377                             a_hasSubordinate = slap_operational_hasSubordinate( rc == LDAP_COMPARE_TRUE );
02378                             if ( a_hasSubordinate != NULL ) {
02379                                    for ( ap = &user_entry.e_attrs; 
02380                                                  *ap; 
02381                                                  ap = &(*ap)->a_next );
02382 
02383                                    *ap = a_hasSubordinate;
02384                             }
02385                             rc = 0;
02386                             break;
02387 
02388                      default:
02389                             Debug(LDAP_DEBUG_TRACE, 
02390                                    "backsql_search(): "
02391                                    "has_children failed( %d)\n", 
02392                                    rc, 0, 0 );
02393                             rc = 1;
02394                             goto next_entry;
02395                      }
02396               }
02397 
02398               if ( bsi.bsi_flags & BSQL_SF_FILTER_ENTRYUUID ) {
02399                      a_entryUUID = backsql_operational_entryUUID( bi, eid );
02400                      if ( a_entryUUID != NULL ) {
02401                             if ( ap == NULL ) {
02402                                    ap = &user_entry.e_attrs;
02403                             }
02404 
02405                             for ( ; *ap; ap = &(*ap)->a_next );
02406 
02407                             *ap = a_entryUUID;
02408                      }
02409               }
02410 
02411 #ifdef BACKSQL_SYNCPROV
02412               if ( bsi.bsi_flags & BSQL_SF_FILTER_ENTRYCSN ) {
02413                      a_entryCSN = backsql_operational_entryCSN( op );
02414                      if ( a_entryCSN != NULL ) {
02415                             if ( ap == NULL ) {
02416                                    ap = &user_entry.e_attrs;
02417                             }
02418 
02419                             for ( ; *ap; ap = &(*ap)->a_next );
02420 
02421                             *ap = a_entryCSN;
02422                      }
02423               }
02424 #endif /* BACKSQL_SYNCPROV */
02425 
02426               if ( test_filter( op, e, op->ors_filter ) == LDAP_COMPARE_TRUE )
02427               {
02428 #ifndef BACKSQL_ARBITRARY_KEY
02429                      /* If paged results are in effect, see if the page limit was exceeded */
02430                      if ( get_pagedresults(op) > SLAP_CONTROL_IGNORED ) {
02431                             if ( rs->sr_nentries >= ((PagedResultsState *)op->o_pagedresults_state)->ps_size )
02432                             {
02433                                    e = NULL;
02434                                    send_paged_response( op, rs, &lastid );
02435                                    goto done;
02436                             }
02437                             lastid = SQL_TO_PAGECOOKIE( eid->eid_id, eid->eid_oc_id );
02438                      }
02439 #endif /* ! BACKSQL_ARBITRARY_KEY */
02440                      rs->sr_attrs = op->ors_attrs;
02441                      rs->sr_operational_attrs = NULL;
02442                      rs->sr_entry = e;
02443                      e->e_private = (void *)eid;
02444                      rs->sr_flags = ( e == &user_entry ) ? REP_ENTRY_MODIFIABLE : 0;
02445                      /* FIXME: need the whole entry (ITS#3480) */
02446                      rs->sr_err = send_search_entry( op, rs );
02447                      e->e_private = NULL;
02448                      rs->sr_entry = NULL;
02449                      rs->sr_attrs = NULL;
02450                      rs->sr_operational_attrs = NULL;
02451 
02452                      switch ( rs->sr_err ) {
02453                      case LDAP_UNAVAILABLE:
02454                             /*
02455                              * FIXME: send_search_entry failed;
02456                              * better stop
02457                              */
02458                             Debug( LDAP_DEBUG_TRACE, "backsql_search(): "
02459                                    "connection lost\n", 0, 0, 0 );
02460                             goto end_of_search;
02461 
02462                      case LDAP_SIZELIMIT_EXCEEDED:
02463                             goto send_results;
02464                      }
02465               }
02466 
02467 next_entry:;
02468               if ( e == &user_entry ) {
02469                      backsql_entry_clean( op, &user_entry );
02470               }
02471 
02472 next_entry2:;
02473        }
02474 
02475 end_of_search:;
02476        if ( rs->sr_nentries > 0 ) {
02477               rs->sr_ref = rs->sr_v2ref;
02478               rs->sr_err = (rs->sr_v2ref == NULL) ? LDAP_SUCCESS
02479                      : LDAP_REFERRAL;
02480 
02481        } else {
02482               rs->sr_err = bsi.bsi_status;
02483        }
02484 
02485 send_results:;
02486        if ( rs->sr_err != SLAPD_ABANDON ) {
02487 #ifndef BACKSQL_ARBITRARY_KEY
02488               if ( get_pagedresults(op) > SLAP_CONTROL_IGNORED ) {
02489                      send_paged_response( op, rs, NULL );
02490               } else
02491 #endif /* ! BACKSQL_ARBITRARY_KEY */
02492               {
02493                      send_ldap_result( op, rs );
02494               }
02495        }
02496 
02497        /* cleanup in case of abandon */
02498        for ( ; eid != NULL; 
02499               eid = backsql_free_entryID(
02500                      eid, eid == &bsi.bsi_base_id ? 0 : 1, op->o_tmpmemctx ) )
02501               ;
02502 
02503        backsql_entry_clean( op, &base_entry );
02504 
02505        /* in case we got here accidentally */
02506        backsql_entry_clean( op, &user_entry );
02507 
02508        if ( rs->sr_v2ref ) {
02509               ber_bvarray_free( rs->sr_v2ref );
02510               rs->sr_v2ref = NULL;
02511        }
02512 
02513 #ifdef BACKSQL_SYNCPROV
02514        if ( op->o_sync ) {
02515               Operation     op2 = *op;
02516               SlapReply     rs2 = { REP_RESULT };
02517               Entry         *e = entry_alloc();
02518               slap_callback cb = { 0 };
02519 
02520               op2.o_tag = LDAP_REQ_ADD;
02521               op2.o_bd = select_backend( &op->o_bd->be_nsuffix[0], 0 );
02522               op2.ora_e = e;
02523               op2.o_callback = &cb;
02524 
02525               ber_dupbv( &e->e_name, op->o_bd->be_suffix );
02526               ber_dupbv( &e->e_nname, op->o_bd->be_nsuffix );
02527 
02528               cb.sc_response = slap_null_cb;
02529 
02530               op2.o_bd->be_add( &op2, &rs2 );
02531 
02532               if ( op2.ora_e == e )
02533                      entry_free( e );
02534        }
02535 #endif /* BACKSQL_SYNCPROV */
02536 
02537 done:;
02538        (void)backsql_free_entryID( &bsi.bsi_base_id, 0, op->o_tmpmemctx );
02539 
02540        if ( bsi.bsi_attrs != NULL ) {
02541               op->o_tmpfree( bsi.bsi_attrs, op->o_tmpmemctx );
02542        }
02543 
02544        if ( !BER_BVISNULL( &nbase )
02545                      && nbase.bv_val != op->o_req_ndn.bv_val )
02546        {
02547               ch_free( nbase.bv_val );
02548        }
02549 
02550        /* restore scope ... FIXME: this should be done before ANY
02551         * frontend call that uses op */
02552        if ( op->ors_scope == BACKSQL_SCOPE_BASE_LIKE ) {
02553               op->ors_scope = LDAP_SCOPE_BASE;
02554        }
02555 
02556        Debug( LDAP_DEBUG_TRACE, "<==backsql_search()\n", 0, 0, 0 );
02557 
02558        return rs->sr_err;
02559 }
02560 
02561 /* return LDAP_SUCCESS IFF we can retrieve the specified entry.
02562  */
02563 int
02564 backsql_entry_get(
02565               Operation            *op,
02566               struct berval        *ndn,
02567               ObjectClass          *oc,
02568               AttributeDescription *at,
02569               int                  rw,
02570               Entry                **ent )
02571 {
02572        backsql_srch_info    bsi = { 0 };
02573        SQLHDBC                     dbh = SQL_NULL_HDBC;
02574        int                  rc;
02575        SlapReply            rs = { 0 };
02576        AttributeName        anlist[ 2 ];
02577 
02578        *ent = NULL;
02579 
02580        rc = backsql_get_db_conn( op, &dbh );
02581        if ( rc != LDAP_SUCCESS ) {
02582               return rc;
02583        }
02584 
02585        if ( at ) {
02586               anlist[ 0 ].an_name = at->ad_cname;
02587               anlist[ 0 ].an_desc = at;
02588               BER_BVZERO( &anlist[ 1 ].an_name );
02589        }
02590 
02591        bsi.bsi_e = entry_alloc();
02592        rc = backsql_init_search( &bsi,
02593                      ndn,
02594                      LDAP_SCOPE_BASE, 
02595                      (time_t)(-1), NULL,
02596                      dbh, op, &rs, at ? anlist : NULL,
02597                      BACKSQL_ISF_GET_ENTRY );
02598 
02599        if ( !BER_BVISNULL( &bsi.bsi_base_id.eid_ndn ) ) {
02600               (void)backsql_free_entryID( &bsi.bsi_base_id, 0, op->o_tmpmemctx );
02601        }
02602 
02603        if ( rc == LDAP_SUCCESS ) {
02604 
02605 #if 0 /* not supported at present */
02606               /* find attribute values */
02607               if ( is_entry_alias( bsi.bsi_e ) ) {
02608                      Debug( LDAP_DEBUG_ACL,
02609                             "<= backsql_entry_get: entry is an alias\n",
02610                             0, 0, 0 );
02611                      rc = LDAP_ALIAS_PROBLEM;
02612                      goto return_results;
02613               }
02614 #endif
02615 
02616               if ( is_entry_referral( bsi.bsi_e ) ) {
02617                      Debug( LDAP_DEBUG_ACL,
02618                             "<= backsql_entry_get: entry is a referral\n",
02619                             0, 0, 0 );
02620                      rc = LDAP_REFERRAL;
02621                      goto return_results;
02622               }
02623 
02624               if ( oc && !is_entry_objectclass( bsi.bsi_e, oc, 0 ) ) {
02625                      Debug( LDAP_DEBUG_ACL,
02626                                    "<= backsql_entry_get: "
02627                                    "failed to find objectClass\n",
02628                                    0, 0, 0 ); 
02629                      rc = LDAP_NO_SUCH_ATTRIBUTE;
02630                      goto return_results;
02631               }
02632 
02633               *ent = bsi.bsi_e;
02634        }
02635 
02636 return_results:;
02637        if ( bsi.bsi_attrs != NULL ) {
02638               op->o_tmpfree( bsi.bsi_attrs, op->o_tmpmemctx );
02639        }
02640 
02641        if ( rc != LDAP_SUCCESS ) {
02642               if ( bsi.bsi_e ) {
02643                      entry_free( bsi.bsi_e );
02644               }
02645        }
02646 
02647        return rc;
02648 }
02649 
02650 void
02651 backsql_entry_clean(
02652               Operation     *op,
02653               Entry         *e )
02654 {
02655        void *ctx;
02656 
02657        ctx = ldap_pvt_thread_pool_context();
02658 
02659        if ( ctx == NULL || ctx != op->o_tmpmemctx ) {
02660               if ( !BER_BVISNULL( &e->e_name ) ) {
02661                      op->o_tmpfree( e->e_name.bv_val, op->o_tmpmemctx );
02662                      BER_BVZERO( &e->e_name );
02663               }
02664 
02665               if ( !BER_BVISNULL( &e->e_nname ) ) {
02666                      op->o_tmpfree( e->e_nname.bv_val, op->o_tmpmemctx );
02667                      BER_BVZERO( &e->e_nname );
02668               }
02669        }
02670 
02671        entry_clean( e );
02672 }
02673 
02674 int
02675 backsql_entry_release(
02676               Operation     *op,
02677               Entry         *e,
02678               int           rw )
02679 {
02680        backsql_entry_clean( op, e );
02681 
02682        entry_free( e );
02683 
02684        return 0;
02685 }
02686 
02687 #ifndef BACKSQL_ARBITRARY_KEY
02688 /* This function is copied verbatim from back-bdb/search.c */
02689 static int
02690 parse_paged_cookie( Operation *op, SlapReply *rs )
02691 {
02692        int           rc = LDAP_SUCCESS;
02693        PagedResultsState *ps = op->o_pagedresults_state;
02694 
02695        /* this function must be invoked only if the pagedResults
02696         * control has been detected, parsed and partially checked
02697         * by the frontend */
02698        assert( get_pagedresults( op ) > SLAP_CONTROL_IGNORED );
02699 
02700        /* cookie decoding/checks deferred to backend... */
02701        if ( ps->ps_cookieval.bv_len ) {
02702               PagedResultsCookie reqcookie;
02703               if( ps->ps_cookieval.bv_len != sizeof( reqcookie ) ) {
02704                      /* bad cookie */
02705                      rs->sr_text = "paged results cookie is invalid";
02706                      rc = LDAP_PROTOCOL_ERROR;
02707                      goto done;
02708               }
02709 
02710               AC_MEMCPY( &reqcookie, ps->ps_cookieval.bv_val, sizeof( reqcookie ));
02711 
02712               if ( reqcookie > ps->ps_cookie ) {
02713                      /* bad cookie */
02714                      rs->sr_text = "paged results cookie is invalid";
02715                      rc = LDAP_PROTOCOL_ERROR;
02716                      goto done;
02717 
02718               } else if ( reqcookie < ps->ps_cookie ) {
02719                      rs->sr_text = "paged results cookie is invalid or old";
02720                      rc = LDAP_UNWILLING_TO_PERFORM;
02721                      goto done;
02722               }
02723 
02724        } else {
02725               /* Initial request.  Initialize state. */
02726               ps->ps_cookie = 0;
02727               ps->ps_count = 0;
02728        }
02729 
02730 done:;
02731 
02732        return rc;
02733 }
02734 
02735 /* This function is copied nearly verbatim from back-bdb/search.c */
02736 static void
02737 send_paged_response( 
02738        Operation     *op,
02739        SlapReply     *rs,
02740        ID            *lastid )
02741 {
02742        LDAPControl   ctrl, *ctrls[2];
02743        BerElementBuffer berbuf;
02744        BerElement    *ber = (BerElement *)&berbuf;
02745        PagedResultsCookie respcookie;
02746        struct berval cookie;
02747 
02748        Debug(LDAP_DEBUG_ARGS,
02749               "send_paged_response: lastid=0x%08lx nentries=%d\n", 
02750               lastid ? *lastid : 0, rs->sr_nentries, NULL );
02751 
02752        BER_BVZERO( &ctrl.ldctl_value );
02753        ctrls[0] = &ctrl;
02754        ctrls[1] = NULL;
02755 
02756        ber_init2( ber, NULL, LBER_USE_DER );
02757 
02758        if ( lastid ) {
02759               respcookie = ( PagedResultsCookie )(*lastid);
02760               cookie.bv_len = sizeof( respcookie );
02761               cookie.bv_val = (char *)&respcookie;
02762 
02763        } else {
02764               respcookie = ( PagedResultsCookie )0;
02765               BER_BVSTR( &cookie, "" );
02766        }
02767 
02768        op->o_conn->c_pagedresults_state.ps_cookie = respcookie;
02769        op->o_conn->c_pagedresults_state.ps_count =
02770               ((PagedResultsState *)op->o_pagedresults_state)->ps_count +
02771               rs->sr_nentries;
02772 
02773        /* return size of 0 -- no estimate */
02774        ber_printf( ber, "{iO}", 0, &cookie ); 
02775 
02776        if ( ber_flatten2( ber, &ctrls[0]->ldctl_value, 0 ) == -1 ) {
02777               goto done;
02778        }
02779 
02780        ctrls[0]->ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
02781        ctrls[0]->ldctl_iscritical = 0;
02782 
02783        rs->sr_ctrls = ctrls;
02784        rs->sr_err = LDAP_SUCCESS;
02785        send_ldap_result( op, rs );
02786        rs->sr_ctrls = NULL;
02787 
02788 done:
02789        (void) ber_free_buf( ber );
02790 }
02791 #endif /* ! BACKSQL_ARBITRARY_KEY */