Back to index

openldap  2.4.31
syncprov.c
Go to the documentation of this file.
00001 /* $OpenLDAP$ */
00002 /* syncprov.c - syncrepl provider */
00003 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
00004  *
00005  * Copyright 2004-2012 The OpenLDAP Foundation.
00006  * All rights reserved.
00007  *
00008  * Redistribution and use in source and binary forms, with or without
00009  * modification, are permitted only as authorized by the OpenLDAP
00010  * Public License.
00011  *
00012  * A copy of this license is available in the file LICENSE in the
00013  * top-level directory of the distribution or, alternatively, at
00014  * <http://www.OpenLDAP.org/license.html>.
00015  */
00016 /* ACKNOWLEDGEMENTS:
00017  * This work was initially developed by Howard Chu for inclusion in
00018  * OpenLDAP Software.
00019  */
00020 
00021 #include "portable.h"
00022 
00023 #ifdef SLAPD_OVER_SYNCPROV
00024 
00025 #include <ac/string.h>
00026 #include "lutil.h"
00027 #include "slap.h"
00028 #include "config.h"
00029 #include "ldap_rq.h"
00030 
00031 #ifdef LDAP_DEVEL
00032 #define       CHECK_CSN     1
00033 #endif
00034 
00035 /* A modify request on a particular entry */
00036 typedef struct modinst {
00037        struct modinst *mi_next;
00038        Operation *mi_op;
00039 } modinst;
00040 
00041 typedef struct modtarget {
00042        struct modinst *mt_mods;
00043        struct modinst *mt_tail;
00044        Operation *mt_op;
00045        ldap_pvt_thread_mutex_t mt_mutex;
00046 } modtarget;
00047 
00048 /* A queued result of a persistent search */
00049 typedef struct syncres {
00050        struct syncres *s_next;
00051        Entry *s_e;
00052        struct berval s_dn;
00053        struct berval s_ndn;
00054        struct berval s_uuid;
00055        struct berval s_csn;
00056        char s_mode;
00057        char s_isreference;
00058 } syncres;
00059 
00060 /* Record of a persistent search */
00061 typedef struct syncops {
00062        struct syncops *s_next;
00063        struct berval s_base;              /* ndn of search base */
00064        ID            s_eid;        /* entryID of search base */
00065        Operation     *s_op;        /* search op */
00066        int           s_rid;
00067        int           s_sid;
00068        struct berval s_filterstr;
00069        int           s_flags;      /* search status */
00070 #define       PS_IS_REFRESHING     0x01
00071 #define       PS_IS_DETACHED              0x02
00072 #define       PS_WROTE_BASE        0x04
00073 #define       PS_FIND_BASE         0x08
00074 #define       PS_FIX_FILTER        0x10
00075 #define       PS_TASK_QUEUED              0x20
00076 
00077        int           s_inuse;      /* reference count */
00078        struct syncres *s_res;
00079        struct syncres *s_restail;
00080        ldap_pvt_thread_mutex_t     s_mutex;
00081 } syncops;
00082 
00083 /* A received sync control */
00084 typedef struct sync_control {
00085        struct sync_cookie sr_state;
00086        int sr_rhint;
00087 } sync_control;
00088 
00089 #if 0 /* moved back to slap.h */
00090 #define       o_sync o_ctrlflag[slap_cids.sc_LDAPsync]
00091 #endif
00092 /* o_sync_mode uses data bits of o_sync */
00093 #define       o_sync_mode   o_ctrlflag[slap_cids.sc_LDAPsync]
00094 
00095 #define SLAP_SYNC_NONE                                  (LDAP_SYNC_NONE<<SLAP_CONTROL_SHIFT)
00096 #define SLAP_SYNC_REFRESH                        (LDAP_SYNC_REFRESH_ONLY<<SLAP_CONTROL_SHIFT)
00097 #define SLAP_SYNC_PERSIST                        (LDAP_SYNC_RESERVED<<SLAP_CONTROL_SHIFT)
00098 #define SLAP_SYNC_REFRESH_AND_PERSIST     (LDAP_SYNC_REFRESH_AND_PERSIST<<SLAP_CONTROL_SHIFT)
00099 
00100 /* Record of which searches matched at premodify step */
00101 typedef struct syncmatches {
00102        struct syncmatches *sm_next;
00103        syncops *sm_op;
00104 } syncmatches;
00105 
00106 /* Session log data */
00107 typedef struct slog_entry {
00108        struct slog_entry *se_next;
00109        struct berval se_uuid;
00110        struct berval se_csn;
00111        int    se_sid;
00112        ber_tag_t     se_tag;
00113 } slog_entry;
00114 
00115 typedef struct sessionlog {
00116        BerVarray     sl_mincsn;
00117        int           *sl_sids;
00118        int           sl_numcsns;
00119        int           sl_num;
00120        int           sl_size;
00121        slog_entry *sl_head;
00122        slog_entry *sl_tail;
00123        ldap_pvt_thread_mutex_t sl_mutex;
00124 } sessionlog;
00125 
00126 /* The main state for this overlay */
00127 typedef struct syncprov_info_t {
00128        syncops              *si_ops;
00129        struct berval si_contextdn;
00130        BerVarray     si_ctxcsn;    /* ldapsync context */
00131        int           *si_sids;
00132        int           si_numcsns;
00133        int           si_chkops;    /* checkpointing info */
00134        int           si_chktime;
00135        int           si_numops;    /* number of ops since last checkpoint */
00136        int           si_nopres;    /* Skip present phase */
00137        int           si_usehint;   /* use reload hint */
00138        int           si_active;    /* True if there are active mods */
00139        int           si_dirty;     /* True if the context is dirty, i.e changes
00140                                            * have been made without updating the csn. */
00141        time_t si_chklast;   /* time of last checkpoint */
00142        Avlnode       *si_mods;     /* entries being modified */
00143        sessionlog    *si_logs;
00144        ldap_pvt_thread_rdwr_t      si_csn_rwlock;
00145        ldap_pvt_thread_mutex_t     si_ops_mutex;
00146        ldap_pvt_thread_mutex_t     si_mods_mutex;
00147        ldap_pvt_thread_mutex_t     si_resp_mutex;
00148 } syncprov_info_t;
00149 
00150 typedef struct opcookie {
00151        slap_overinst *son;
00152        syncmatches *smatches;
00153        modtarget *smt;
00154        Entry *se;
00155        struct berval sdn;   /* DN of entry, for deletes */
00156        struct berval sndn;
00157        struct berval suuid; /* UUID of entry */
00158        struct berval sctxcsn;
00159        short osid;   /* sid of op csn */
00160        short rsid;   /* sid of relay */
00161        short sreference;    /* Is the entry a reference? */
00162 } opcookie;
00163 
00164 typedef struct mutexint {
00165        ldap_pvt_thread_mutex_t mi_mutex;
00166        int mi_int;
00167 } mutexint;
00168 
00169 typedef struct fbase_cookie {
00170        struct berval *fdn;  /* DN of a modified entry, for scope testing */
00171        syncops *fss; /* persistent search we're testing against */
00172        int fbase;    /* if TRUE we found the search base and it's still valid */
00173        int fscope;   /* if TRUE then fdn is within the psearch scope */
00174 } fbase_cookie;
00175 
00176 static AttributeName csn_anlist[3];
00177 static AttributeName uuid_anlist[2];
00178 
00179 /* Build a LDAPsync intermediate state control */
00180 static int
00181 syncprov_state_ctrl(
00182        Operation     *op,
00183        SlapReply     *rs,
00184        Entry         *e,
00185        int           entry_sync_state,
00186        LDAPControl   **ctrls,
00187        int           num_ctrls,
00188        int           send_cookie,
00189        struct berval *cookie )
00190 {
00191        Attribute* a;
00192        int ret;
00193 
00194        BerElementBuffer berbuf;
00195        BerElement *ber = (BerElement *)&berbuf;
00196 
00197        struct berval entryuuid_bv = BER_BVNULL;
00198 
00199        ber_init2( ber, 0, LBER_USE_DER );
00200        ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
00201 
00202        ctrls[num_ctrls] = op->o_tmpalloc( sizeof ( LDAPControl ), op->o_tmpmemctx );
00203 
00204        for ( a = e->e_attrs; a != NULL; a = a->a_next ) {
00205               AttributeDescription *desc = a->a_desc;
00206               if ( desc == slap_schema.si_ad_entryUUID ) {
00207                      entryuuid_bv = a->a_nvals[0];
00208                      break;
00209               }
00210        }
00211 
00212        /* FIXME: what if entryuuid is NULL or empty ? */
00213 
00214        if ( send_cookie && cookie ) {
00215               ber_printf( ber, "{eOON}",
00216                      entry_sync_state, &entryuuid_bv, cookie );
00217        } else {
00218               ber_printf( ber, "{eON}",
00219                      entry_sync_state, &entryuuid_bv );
00220        }
00221 
00222        ctrls[num_ctrls]->ldctl_oid = LDAP_CONTROL_SYNC_STATE;
00223        ctrls[num_ctrls]->ldctl_iscritical = (op->o_sync == SLAP_CONTROL_CRITICAL);
00224        ret = ber_flatten2( ber, &ctrls[num_ctrls]->ldctl_value, 1 );
00225 
00226        ber_free_buf( ber );
00227 
00228        if ( ret < 0 ) {
00229               Debug( LDAP_DEBUG_TRACE,
00230                      "slap_build_sync_ctrl: ber_flatten2 failed (%d)\n",
00231                      ret, 0, 0 );
00232               send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
00233               return LDAP_OTHER;
00234        }
00235 
00236        return LDAP_SUCCESS;
00237 }
00238 
00239 /* Build a LDAPsync final state control */
00240 static int
00241 syncprov_done_ctrl(
00242        Operation     *op,
00243        SlapReply     *rs,
00244        LDAPControl   **ctrls,
00245        int                  num_ctrls,
00246        int                  send_cookie,
00247        struct berval *cookie,
00248        int                  refreshDeletes )
00249 {
00250        int ret;
00251        BerElementBuffer berbuf;
00252        BerElement *ber = (BerElement *)&berbuf;
00253 
00254        ber_init2( ber, NULL, LBER_USE_DER );
00255        ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
00256 
00257        ctrls[num_ctrls] = op->o_tmpalloc( sizeof ( LDAPControl ), op->o_tmpmemctx );
00258 
00259        ber_printf( ber, "{" );
00260        if ( send_cookie && cookie ) {
00261               ber_printf( ber, "O", cookie );
00262        }
00263        if ( refreshDeletes == LDAP_SYNC_REFRESH_DELETES ) {
00264               ber_printf( ber, "b", refreshDeletes );
00265        }
00266        ber_printf( ber, "N}" );
00267 
00268        ctrls[num_ctrls]->ldctl_oid = LDAP_CONTROL_SYNC_DONE;
00269        ctrls[num_ctrls]->ldctl_iscritical = (op->o_sync == SLAP_CONTROL_CRITICAL);
00270        ret = ber_flatten2( ber, &ctrls[num_ctrls]->ldctl_value, 1 );
00271 
00272        ber_free_buf( ber );
00273 
00274        if ( ret < 0 ) {
00275               Debug( LDAP_DEBUG_TRACE,
00276                      "syncprov_done_ctrl: ber_flatten2 failed (%d)\n",
00277                      ret, 0, 0 );
00278               send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
00279               return LDAP_OTHER;
00280        }
00281 
00282        return LDAP_SUCCESS;
00283 }
00284 
00285 static int
00286 syncprov_sendinfo(
00287        Operation     *op,
00288        SlapReply     *rs,
00289        int                  type,
00290        struct berval *cookie,
00291        int                  refreshDone,
00292        BerVarray     syncUUIDs,
00293        int                  refreshDeletes )
00294 {
00295        BerElementBuffer berbuf;
00296        BerElement *ber = (BerElement *)&berbuf;
00297        struct berval rspdata;
00298 
00299        int ret;
00300 
00301        ber_init2( ber, NULL, LBER_USE_DER );
00302        ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
00303 
00304        if ( type ) {
00305               switch ( type ) {
00306               case LDAP_TAG_SYNC_NEW_COOKIE:
00307                      ber_printf( ber, "tO", type, cookie );
00308                      break;
00309               case LDAP_TAG_SYNC_REFRESH_DELETE:
00310               case LDAP_TAG_SYNC_REFRESH_PRESENT:
00311                      ber_printf( ber, "t{", type );
00312                      if ( cookie ) {
00313                             ber_printf( ber, "O", cookie );
00314                      }
00315                      if ( refreshDone == 0 ) {
00316                             ber_printf( ber, "b", refreshDone );
00317                      }
00318                      ber_printf( ber, "N}" );
00319                      break;
00320               case LDAP_TAG_SYNC_ID_SET:
00321                      ber_printf( ber, "t{", type );
00322                      if ( cookie ) {
00323                             ber_printf( ber, "O", cookie );
00324                      }
00325                      if ( refreshDeletes == 1 ) {
00326                             ber_printf( ber, "b", refreshDeletes );
00327                      }
00328                      ber_printf( ber, "[W]", syncUUIDs );
00329                      ber_printf( ber, "N}" );
00330                      break;
00331               default:
00332                      Debug( LDAP_DEBUG_TRACE,
00333                             "syncprov_sendinfo: invalid syncinfo type (%d)\n",
00334                             type, 0, 0 );
00335                      return LDAP_OTHER;
00336               }
00337        }
00338 
00339        ret = ber_flatten2( ber, &rspdata, 0 );
00340 
00341        if ( ret < 0 ) {
00342               Debug( LDAP_DEBUG_TRACE,
00343                      "syncprov_sendinfo: ber_flatten2 failed (%d)\n",
00344                      ret, 0, 0 );
00345               send_ldap_error( op, rs, LDAP_OTHER, "internal error" );
00346               return LDAP_OTHER;
00347        }
00348 
00349        rs->sr_rspoid = LDAP_SYNC_INFO;
00350        rs->sr_rspdata = &rspdata;
00351        send_ldap_intermediate( op, rs );
00352        rs->sr_rspdata = NULL;
00353        ber_free_buf( ber );
00354 
00355        return LDAP_SUCCESS;
00356 }
00357 
00358 /* Find a modtarget in an AVL tree */
00359 static int
00360 sp_avl_cmp( const void *c1, const void *c2 )
00361 {
00362        const modtarget *m1, *m2;
00363        int rc;
00364 
00365        m1 = c1; m2 = c2;
00366        rc = m1->mt_op->o_req_ndn.bv_len - m2->mt_op->o_req_ndn.bv_len;
00367 
00368        if ( rc ) return rc;
00369        return ber_bvcmp( &m1->mt_op->o_req_ndn, &m2->mt_op->o_req_ndn );
00370 }
00371 
00372 /* syncprov_findbase:
00373  *   finds the true DN of the base of a search (with alias dereferencing) and
00374  * checks to make sure the base entry doesn't get replaced with a different
00375  * entry (e.g., swapping trees via ModDN, or retargeting an alias). If a
00376  * change is detected, any persistent search on this base must be terminated /
00377  * reloaded.
00378  *   On the first call, we just save the DN and entryID. On subsequent calls
00379  * we compare the DN and entryID with the saved values.
00380  */
00381 static int
00382 findbase_cb( Operation *op, SlapReply *rs )
00383 {
00384        slap_callback *sc = op->o_callback;
00385 
00386        if ( rs->sr_type == REP_SEARCH && rs->sr_err == LDAP_SUCCESS ) {
00387               fbase_cookie *fc = sc->sc_private;
00388 
00389               /* If no entryID, we're looking for the first time.
00390                * Just store whatever we got.
00391                */
00392               if ( fc->fss->s_eid == NOID ) {
00393                      fc->fbase = 2;
00394                      fc->fss->s_eid = rs->sr_entry->e_id;
00395                      ber_dupbv( &fc->fss->s_base, &rs->sr_entry->e_nname );
00396 
00397               } else if ( rs->sr_entry->e_id == fc->fss->s_eid &&
00398                      dn_match( &rs->sr_entry->e_nname, &fc->fss->s_base )) {
00399 
00400               /* OK, the DN is the same and the entryID is the same. */
00401                      fc->fbase = 1;
00402               }
00403        }
00404        if ( rs->sr_err != LDAP_SUCCESS ) {
00405               Debug( LDAP_DEBUG_ANY, "findbase failed! %d\n", rs->sr_err,0,0 );
00406        }
00407        return LDAP_SUCCESS;
00408 }
00409 
00410 static Filter generic_filter = { LDAP_FILTER_PRESENT, { 0 }, NULL };
00411 static struct berval generic_filterstr = BER_BVC("(objectclass=*)");
00412 
00413 static int
00414 syncprov_findbase( Operation *op, fbase_cookie *fc )
00415 {
00416        /* Use basic parameters from syncrepl search, but use
00417         * current op's threadctx / tmpmemctx
00418         */
00419        ldap_pvt_thread_mutex_lock( &fc->fss->s_mutex );
00420        if ( fc->fss->s_flags & PS_FIND_BASE ) {
00421               slap_callback cb = {0};
00422               Operation fop;
00423               SlapReply frs = { REP_RESULT };
00424               int rc;
00425 
00426               fc->fss->s_flags ^= PS_FIND_BASE;
00427               ldap_pvt_thread_mutex_unlock( &fc->fss->s_mutex );
00428 
00429               fop = *fc->fss->s_op;
00430 
00431               fop.o_bd = fop.o_bd->bd_self;
00432               fop.o_hdr = op->o_hdr;
00433               fop.o_time = op->o_time;
00434               fop.o_tincr = op->o_tincr;
00435 
00436               cb.sc_response = findbase_cb;
00437               cb.sc_private = fc;
00438 
00439               fop.o_sync_mode = 0; /* turn off sync mode */
00440               fop.o_managedsait = SLAP_CONTROL_CRITICAL;
00441               fop.o_callback = &cb;
00442               LDAP_SLIST_INIT( &fop.o_extra );
00443               fop.o_tag = LDAP_REQ_SEARCH;
00444               fop.ors_scope = LDAP_SCOPE_BASE;
00445               fop.ors_limit = NULL;
00446               fop.ors_slimit = 1;
00447               fop.ors_tlimit = SLAP_NO_LIMIT;
00448               fop.ors_attrs = slap_anlist_no_attrs;
00449               fop.ors_attrsonly = 1;
00450               fop.ors_filter = &generic_filter;
00451               fop.ors_filterstr = generic_filterstr;
00452 
00453               rc = fop.o_bd->be_search( &fop, &frs );
00454        } else {
00455               ldap_pvt_thread_mutex_unlock( &fc->fss->s_mutex );
00456               fc->fbase = 1;
00457        }
00458 
00459        /* After the first call, see if the fdn resides in the scope */
00460        if ( fc->fbase == 1 ) {
00461               switch ( fc->fss->s_op->ors_scope ) {
00462               case LDAP_SCOPE_BASE:
00463                      fc->fscope = dn_match( fc->fdn, &fc->fss->s_base );
00464                      break;
00465               case LDAP_SCOPE_ONELEVEL: {
00466                      struct berval pdn;
00467                      dnParent( fc->fdn, &pdn );
00468                      fc->fscope = dn_match( &pdn, &fc->fss->s_base );
00469                      break; }
00470               case LDAP_SCOPE_SUBTREE:
00471                      fc->fscope = dnIsSuffix( fc->fdn, &fc->fss->s_base );
00472                      break;
00473               case LDAP_SCOPE_SUBORDINATE:
00474                      fc->fscope = dnIsSuffix( fc->fdn, &fc->fss->s_base ) &&
00475                             !dn_match( fc->fdn, &fc->fss->s_base );
00476                      break;
00477               }
00478        }
00479 
00480        if ( fc->fbase )
00481               return LDAP_SUCCESS;
00482 
00483        /* If entryID has changed, then the base of this search has
00484         * changed. Invalidate the psearch.
00485         */
00486        return LDAP_NO_SUCH_OBJECT;
00487 }
00488 
00489 /* syncprov_findcsn:
00490  *   This function has three different purposes, but they all use a search
00491  * that filters on entryCSN so they're combined here.
00492  * 1: at startup time, after a contextCSN has been read from the database,
00493  * we search for all entries with CSN >= contextCSN in case the contextCSN
00494  * was not checkpointed at the previous shutdown.
00495  *
00496  * 2: when the current contextCSN is known and we have a sync cookie, we search
00497  * for one entry with CSN = the cookie CSN. If not found, try <= cookie CSN.
00498  * If an entry is found, the cookie CSN is valid, otherwise it is stale.
00499  *
00500  * 3: during a refresh phase, we search for all entries with CSN <= the cookie
00501  * CSN, and generate Present records for them. We always collect this result
00502  * in SyncID sets, even if there's only one match.
00503  */
00504 typedef enum find_csn_t {
00505        FIND_MAXCSN   = 1,
00506        FIND_CSN      = 2,
00507        FIND_PRESENT  = 3
00508 } find_csn_t;
00509 
00510 static int
00511 findmax_cb( Operation *op, SlapReply *rs )
00512 {
00513        if ( rs->sr_type == REP_SEARCH && rs->sr_err == LDAP_SUCCESS ) {
00514               struct berval *maxcsn = op->o_callback->sc_private;
00515               Attribute *a = attr_find( rs->sr_entry->e_attrs,
00516                      slap_schema.si_ad_entryCSN );
00517 
00518               if ( a && ber_bvcmp( &a->a_vals[0], maxcsn ) > 0 &&
00519                      slap_parse_csn_sid( &a->a_vals[0] ) == slap_serverID ) {
00520                      maxcsn->bv_len = a->a_vals[0].bv_len;
00521                      strcpy( maxcsn->bv_val, a->a_vals[0].bv_val );
00522               }
00523        }
00524        return LDAP_SUCCESS;
00525 }
00526 
00527 static int
00528 findcsn_cb( Operation *op, SlapReply *rs )
00529 {
00530        slap_callback *sc = op->o_callback;
00531 
00532        /* We just want to know that at least one exists, so it's OK if
00533         * we exceed the unchecked limit.
00534         */
00535        if ( rs->sr_err == LDAP_ADMINLIMIT_EXCEEDED ||
00536               (rs->sr_type == REP_SEARCH && rs->sr_err == LDAP_SUCCESS )) {
00537               sc->sc_private = (void *)1;
00538        }
00539        return LDAP_SUCCESS;
00540 }
00541 
00542 /* Build a list of entryUUIDs for sending in a SyncID set */
00543 
00544 #define UUID_LEN     16
00545 
00546 typedef struct fpres_cookie {
00547        int num;
00548        BerVarray uuids;
00549        char *last;
00550 } fpres_cookie;
00551 
00552 static int
00553 findpres_cb( Operation *op, SlapReply *rs )
00554 {
00555        slap_callback *sc = op->o_callback;
00556        fpres_cookie *pc = sc->sc_private;
00557        Attribute *a;
00558        int ret = SLAP_CB_CONTINUE;
00559 
00560        switch ( rs->sr_type ) {
00561        case REP_SEARCH:
00562               a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_entryUUID );
00563               if ( a ) {
00564                      pc->uuids[pc->num].bv_val = pc->last;
00565                      AC_MEMCPY( pc->uuids[pc->num].bv_val, a->a_nvals[0].bv_val,
00566                             pc->uuids[pc->num].bv_len );
00567                      pc->num++;
00568                      pc->last = pc->uuids[pc->num].bv_val;
00569                      pc->uuids[pc->num].bv_val = NULL;
00570               }
00571               ret = LDAP_SUCCESS;
00572               if ( pc->num != SLAP_SYNCUUID_SET_SIZE )
00573                      break;
00574               /* FALLTHRU */
00575        case REP_RESULT:
00576               ret = rs->sr_err;
00577               if ( pc->num ) {
00578                      ret = syncprov_sendinfo( op, rs, LDAP_TAG_SYNC_ID_SET, NULL,
00579                             0, pc->uuids, 0 );
00580                      pc->uuids[pc->num].bv_val = pc->last;
00581                      pc->num = 0;
00582                      pc->last = pc->uuids[0].bv_val;
00583               }
00584               break;
00585        default:
00586               break;
00587        }
00588        return ret;
00589 }
00590 
00591 static int
00592 syncprov_findcsn( Operation *op, find_csn_t mode, struct berval *csn )
00593 {
00594        slap_overinst        *on = (slap_overinst *)op->o_bd->bd_info;
00595        syncprov_info_t             *si = on->on_bi.bi_private;
00596 
00597        slap_callback cb = {0};
00598        Operation fop;
00599        SlapReply frs = { REP_RESULT };
00600        char buf[LDAP_PVT_CSNSTR_BUFSIZE + STRLENOF("(entryCSN<=)")];
00601        char cbuf[LDAP_PVT_CSNSTR_BUFSIZE];
00602        struct berval maxcsn;
00603        Filter cf;
00604        AttributeAssertion eq = ATTRIBUTEASSERTION_INIT;
00605        fpres_cookie pcookie;
00606        sync_control *srs = NULL;
00607        struct slap_limits_set fc_limits;
00608        int i, rc = LDAP_SUCCESS, findcsn_retry = 1;
00609        int maxid;
00610 
00611        if ( mode != FIND_MAXCSN ) {
00612               srs = op->o_controls[slap_cids.sc_LDAPsync];
00613        }
00614 
00615        fop = *op;
00616        fop.o_sync_mode &= SLAP_CONTROL_MASK;     /* turn off sync_mode */
00617        /* We want pure entries, not referrals */
00618        fop.o_managedsait = SLAP_CONTROL_CRITICAL;
00619 
00620        cf.f_ava = &eq;
00621        cf.f_av_desc = slap_schema.si_ad_entryCSN;
00622        BER_BVZERO( &cf.f_av_value );
00623        cf.f_next = NULL;
00624 
00625        fop.o_callback = &cb;
00626        fop.ors_limit = NULL;
00627        fop.ors_tlimit = SLAP_NO_LIMIT;
00628        fop.ors_filter = &cf;
00629        fop.ors_filterstr.bv_val = buf;
00630 
00631 again:
00632        switch( mode ) {
00633        case FIND_MAXCSN:
00634               cf.f_choice = LDAP_FILTER_GE;
00635               /* If there are multiple CSNs, use the one with our serverID */
00636               for ( i=0; i<si->si_numcsns; i++) {
00637                      if ( slap_serverID == si->si_sids[i] ) {
00638                             maxid = i;
00639                             break;
00640                      }
00641               }
00642               if ( i == si->si_numcsns ) {
00643                      /* No match: this is multimaster, and none of the content in the DB
00644                       * originated locally. Treat like no CSN.
00645                       */
00646                      return LDAP_NO_SUCH_OBJECT;
00647               }
00648               cf.f_av_value = si->si_ctxcsn[maxid];
00649               fop.ors_filterstr.bv_len = snprintf( buf, sizeof( buf ),
00650                      "(entryCSN>=%s)", cf.f_av_value.bv_val );
00651               if ( fop.ors_filterstr.bv_len >= sizeof( buf ) ) {
00652                      return LDAP_OTHER;
00653               }
00654               fop.ors_attrsonly = 0;
00655               fop.ors_attrs = csn_anlist;
00656               fop.ors_slimit = SLAP_NO_LIMIT;
00657               cb.sc_private = &maxcsn;
00658               cb.sc_response = findmax_cb;
00659               strcpy( cbuf, cf.f_av_value.bv_val );
00660               maxcsn.bv_val = cbuf;
00661               maxcsn.bv_len = cf.f_av_value.bv_len;
00662               break;
00663        case FIND_CSN:
00664               if ( BER_BVISEMPTY( &cf.f_av_value )) {
00665                      cf.f_av_value = *csn;
00666               }
00667               fop.o_dn = op->o_bd->be_rootdn;
00668               fop.o_ndn = op->o_bd->be_rootndn;
00669               fop.o_req_dn = op->o_bd->be_suffix[0];
00670               fop.o_req_ndn = op->o_bd->be_nsuffix[0];
00671               /* Look for exact match the first time */
00672               if ( findcsn_retry ) {
00673                      cf.f_choice = LDAP_FILTER_EQUALITY;
00674                      fop.ors_filterstr.bv_len = snprintf( buf, sizeof( buf ),
00675                             "(entryCSN=%s)", cf.f_av_value.bv_val );
00676               /* On retry, look for <= */
00677               } else {
00678                      cf.f_choice = LDAP_FILTER_LE;
00679                      fop.ors_limit = &fc_limits;
00680                      memset( &fc_limits, 0, sizeof( fc_limits ));
00681                      fc_limits.lms_s_unchecked = 1;
00682                      fop.ors_filterstr.bv_len = snprintf( buf, sizeof( buf ),
00683                             "(entryCSN<=%s)", cf.f_av_value.bv_val );
00684               }
00685               if ( fop.ors_filterstr.bv_len >= sizeof( buf ) ) {
00686                      return LDAP_OTHER;
00687               }
00688               fop.ors_attrsonly = 1;
00689               fop.ors_attrs = slap_anlist_no_attrs;
00690               fop.ors_slimit = 1;
00691               cb.sc_private = NULL;
00692               cb.sc_response = findcsn_cb;
00693               break;
00694        case FIND_PRESENT:
00695               fop.ors_filter = op->ors_filter;
00696               fop.ors_filterstr = op->ors_filterstr;
00697               fop.ors_attrsonly = 0;
00698               fop.ors_attrs = uuid_anlist;
00699               fop.ors_slimit = SLAP_NO_LIMIT;
00700               cb.sc_private = &pcookie;
00701               cb.sc_response = findpres_cb;
00702               pcookie.num = 0;
00703 
00704               /* preallocate storage for a full set */
00705               pcookie.uuids = op->o_tmpalloc( (SLAP_SYNCUUID_SET_SIZE+1) *
00706                      sizeof(struct berval) + SLAP_SYNCUUID_SET_SIZE * UUID_LEN,
00707                      op->o_tmpmemctx );
00708               pcookie.last = (char *)(pcookie.uuids + SLAP_SYNCUUID_SET_SIZE+1);
00709               pcookie.uuids[0].bv_val = pcookie.last;
00710               pcookie.uuids[0].bv_len = UUID_LEN;
00711               for (i=1; i<SLAP_SYNCUUID_SET_SIZE; i++) {
00712                      pcookie.uuids[i].bv_val = pcookie.uuids[i-1].bv_val + UUID_LEN;
00713                      pcookie.uuids[i].bv_len = UUID_LEN;
00714               }
00715               break;
00716        }
00717 
00718        fop.o_bd->bd_info = (BackendInfo *)on->on_info;
00719        fop.o_bd->be_search( &fop, &frs );
00720        fop.o_bd->bd_info = (BackendInfo *)on;
00721 
00722        switch( mode ) {
00723        case FIND_MAXCSN:
00724               if ( ber_bvcmp( &si->si_ctxcsn[maxid], &maxcsn )) {
00725 #ifdef CHECK_CSN
00726                      Syntax *syn = slap_schema.si_ad_contextCSN->ad_type->sat_syntax;
00727                      assert( !syn->ssyn_validate( syn, &maxcsn ));
00728 #endif
00729                      ber_bvreplace( &si->si_ctxcsn[maxid], &maxcsn );
00730                      si->si_numops++;     /* ensure a checkpoint */
00731               }
00732               break;
00733        case FIND_CSN:
00734               /* If matching CSN was not found, invalidate the context. */
00735               if ( !cb.sc_private ) {
00736                      /* If we didn't find an exact match, then try for <= */
00737                      if ( findcsn_retry ) {
00738                             findcsn_retry = 0;
00739                             rs_reinit( &frs, REP_RESULT );
00740                             goto again;
00741                      }
00742                      rc = LDAP_NO_SUCH_OBJECT;
00743               }
00744               break;
00745        case FIND_PRESENT:
00746               op->o_tmpfree( pcookie.uuids, op->o_tmpmemctx );
00747               break;
00748        }
00749 
00750        return rc;
00751 }
00752 
00753 /* Should find a place to cache these */
00754 static mutexint *get_mutexint()
00755 {
00756        mutexint *mi = ch_malloc( sizeof( mutexint ));
00757        ldap_pvt_thread_mutex_init( &mi->mi_mutex );
00758        mi->mi_int = 1;
00759        return mi;
00760 }
00761 
00762 static void inc_mutexint( mutexint *mi )
00763 {
00764        ldap_pvt_thread_mutex_lock( &mi->mi_mutex );
00765        mi->mi_int++;
00766        ldap_pvt_thread_mutex_unlock( &mi->mi_mutex );
00767 }
00768 
00769 /* return resulting counter */
00770 static int dec_mutexint( mutexint *mi )
00771 {
00772        int i;
00773        ldap_pvt_thread_mutex_lock( &mi->mi_mutex );
00774        i = --mi->mi_int;
00775        ldap_pvt_thread_mutex_unlock( &mi->mi_mutex );
00776        if ( !i ) {
00777               ldap_pvt_thread_mutex_destroy( &mi->mi_mutex );
00778               ch_free( mi );
00779        }
00780        return i;
00781 }
00782 
00783 static void
00784 syncprov_free_syncop( syncops *so )
00785 {
00786        syncres *sr, *srnext;
00787        GroupAssertion *ga, *gnext;
00788 
00789        ldap_pvt_thread_mutex_lock( &so->s_mutex );
00790        /* already being freed, or still in use */
00791        if ( !so->s_inuse || --so->s_inuse > 0 ) {
00792               ldap_pvt_thread_mutex_unlock( &so->s_mutex );
00793               return;
00794        }
00795        ldap_pvt_thread_mutex_unlock( &so->s_mutex );
00796        if ( so->s_flags & PS_IS_DETACHED ) {
00797               filter_free( so->s_op->ors_filter );
00798               for ( ga = so->s_op->o_groups; ga; ga=gnext ) {
00799                      gnext = ga->ga_next;
00800                      ch_free( ga );
00801               }
00802               ch_free( so->s_op );
00803        }
00804        ch_free( so->s_base.bv_val );
00805        for ( sr=so->s_res; sr; sr=srnext ) {
00806               srnext = sr->s_next;
00807               if ( sr->s_e ) {
00808                      if ( !dec_mutexint( sr->s_e->e_private )) {
00809                             sr->s_e->e_private = NULL;
00810                             entry_free( sr->s_e );
00811                      }
00812               }
00813               ch_free( sr );
00814        }
00815        ldap_pvt_thread_mutex_destroy( &so->s_mutex );
00816        ch_free( so );
00817 }
00818 
00819 /* Send a persistent search response */
00820 static int
00821 syncprov_sendresp( Operation *op, opcookie *opc, syncops *so, int mode )
00822 {
00823        SlapReply rs = { REP_SEARCH };
00824        LDAPControl *ctrls[2];
00825        struct berval cookie, csns[2];
00826        Entry e_uuid = {0};
00827        Attribute a_uuid = {0};
00828 
00829        if ( so->s_op->o_abandon )
00830               return SLAPD_ABANDON;
00831 
00832        ctrls[1] = NULL;
00833        csns[0] = opc->sctxcsn;
00834        BER_BVZERO( &csns[1] );
00835        slap_compose_sync_cookie( op, &cookie, csns, so->s_rid, slap_serverID ? slap_serverID : -1 );
00836 
00837 #ifdef LDAP_DEBUG
00838        if ( so->s_sid > 0 ) {
00839               Debug( LDAP_DEBUG_SYNC, "syncprov_sendresp: to=%03x, cookie=%s\n",
00840                      so->s_sid, cookie.bv_val, 0 );
00841        } else {
00842               Debug( LDAP_DEBUG_SYNC, "syncprov_sendresp: cookie=%s\n",
00843                      cookie.bv_val, 0, 0 );
00844        }
00845 #endif
00846 
00847        e_uuid.e_attrs = &a_uuid;
00848        a_uuid.a_desc = slap_schema.si_ad_entryUUID;
00849        a_uuid.a_nvals = &opc->suuid;
00850        rs.sr_err = syncprov_state_ctrl( op, &rs, &e_uuid,
00851               mode, ctrls, 0, 1, &cookie );
00852        op->o_tmpfree( cookie.bv_val, op->o_tmpmemctx );
00853 
00854        rs.sr_ctrls = ctrls;
00855        rs.sr_entry = &e_uuid;
00856        if ( mode == LDAP_SYNC_ADD || mode == LDAP_SYNC_MODIFY ) {
00857               e_uuid = *opc->se;
00858               e_uuid.e_private = NULL;
00859        }
00860 
00861        switch( mode ) {
00862        case LDAP_SYNC_ADD:
00863               if ( opc->sreference && so->s_op->o_managedsait <= SLAP_CONTROL_IGNORED ) {
00864                      rs.sr_ref = get_entry_referrals( op, rs.sr_entry );
00865                      rs.sr_err = send_search_reference( op, &rs );
00866                      ber_bvarray_free( rs.sr_ref );
00867                      break;
00868               }
00869               /* fallthru */
00870        case LDAP_SYNC_MODIFY:
00871               rs.sr_attrs = op->ors_attrs;
00872               rs.sr_err = send_search_entry( op, &rs );
00873               break;
00874        case LDAP_SYNC_DELETE:
00875               e_uuid.e_attrs = NULL;
00876               e_uuid.e_name = opc->sdn;
00877               e_uuid.e_nname = opc->sndn;
00878               if ( opc->sreference && so->s_op->o_managedsait <= SLAP_CONTROL_IGNORED ) {
00879                      struct berval bv = BER_BVNULL;
00880                      rs.sr_ref = &bv;
00881                      rs.sr_err = send_search_reference( op, &rs );
00882               } else {
00883                      rs.sr_err = send_search_entry( op, &rs );
00884               }
00885               break;
00886        default:
00887               assert(0);
00888        }
00889        /* In case someone else freed it already? */
00890        if ( rs.sr_ctrls ) {
00891               int i;
00892               for ( i=0; rs.sr_ctrls[i]; i++ ) {
00893                      if ( rs.sr_ctrls[i] == ctrls[0] ) {
00894                             op->o_tmpfree( ctrls[0]->ldctl_value.bv_val, op->o_tmpmemctx );
00895                             ctrls[0]->ldctl_value.bv_val = NULL;
00896                             break;
00897                      }
00898               }
00899               rs.sr_ctrls = NULL;
00900        }
00901 
00902        return rs.sr_err;
00903 }
00904 
00905 static void
00906 syncprov_qstart( syncops *so );
00907 
00908 /* Play back queued responses */
00909 static int
00910 syncprov_qplay( Operation *op, syncops *so )
00911 {
00912        slap_overinst *on = LDAP_SLIST_FIRST(&so->s_op->o_extra)->oe_key;
00913        syncres *sr;
00914        opcookie opc;
00915        int rc = 0;
00916 
00917        opc.son = on;
00918 
00919        do {
00920               ldap_pvt_thread_mutex_lock( &so->s_mutex );
00921               sr = so->s_res;
00922               if ( sr )
00923                      so->s_res = sr->s_next;
00924               if ( !so->s_res )
00925                      so->s_restail = NULL;
00926               /* Exit loop with mutex held */
00927               if ( !sr || so->s_op->o_abandon )
00928                      break;
00929               ldap_pvt_thread_mutex_unlock( &so->s_mutex );
00930 
00931               if ( sr->s_mode == LDAP_SYNC_NEW_COOKIE ) {
00932                      SlapReply rs = { REP_INTERMEDIATE };
00933 
00934                      rc = syncprov_sendinfo( op, &rs, LDAP_TAG_SYNC_NEW_COOKIE,
00935                             &sr->s_csn, 0, NULL, 0 );
00936               } else {
00937                      opc.sdn = sr->s_dn;
00938                      opc.sndn = sr->s_ndn;
00939                      opc.suuid = sr->s_uuid;
00940                      opc.sctxcsn = sr->s_csn;
00941                      opc.sreference = sr->s_isreference;
00942                      opc.se = sr->s_e;
00943 
00944                      rc = syncprov_sendresp( op, &opc, so, sr->s_mode );
00945 
00946               }
00947               if ( sr->s_e ) {
00948                      if ( !dec_mutexint( sr->s_e->e_private )) {
00949                             sr->s_e->e_private = NULL;
00950                             entry_free ( sr->s_e );
00951                      }
00952               }
00953 
00954               ch_free( sr );
00955 
00956               /* Exit loop with mutex held */
00957               ldap_pvt_thread_mutex_lock( &so->s_mutex );
00958 
00959        } while (0);
00960 
00961        /* We now only send one change at a time, to prevent one
00962         * psearch from hogging all the CPU. Resubmit this task if
00963         * there are more responses queued and no errors occurred.
00964         */
00965 
00966        if ( rc == 0 && so->s_res ) {
00967               syncprov_qstart( so );
00968        } else {
00969               so->s_flags ^= PS_TASK_QUEUED;
00970        }
00971 
00972        ldap_pvt_thread_mutex_unlock( &so->s_mutex );
00973        return rc;
00974 }
00975 
00976 /* task for playing back queued responses */
00977 static void *
00978 syncprov_qtask( void *ctx, void *arg )
00979 {
00980        syncops *so = arg;
00981        OperationBuffer opbuf;
00982        Operation *op;
00983        BackendDB be;
00984        int rc;
00985 
00986        op = &opbuf.ob_op;
00987        *op = *so->s_op;
00988        op->o_hdr = &opbuf.ob_hdr;
00989        op->o_controls = opbuf.ob_controls;
00990        memset( op->o_controls, 0, sizeof(opbuf.ob_controls) );
00991        op->o_sync = SLAP_CONTROL_IGNORED;
00992 
00993        *op->o_hdr = *so->s_op->o_hdr;
00994 
00995        op->o_tmpmemctx = slap_sl_mem_create(SLAP_SLAB_SIZE, SLAP_SLAB_STACK, ctx, 1);
00996        op->o_tmpmfuncs = &slap_sl_mfuncs;
00997        op->o_threadctx = ctx;
00998 
00999        /* syncprov_qplay expects a fake db */
01000        be = *so->s_op->o_bd;
01001        be.be_flags |= SLAP_DBFLAG_OVERLAY;
01002        op->o_bd = &be;
01003        LDAP_SLIST_FIRST(&op->o_extra) = NULL;
01004        op->o_callback = NULL;
01005 
01006        rc = syncprov_qplay( op, so );
01007 
01008        /* decrement use count... */
01009        syncprov_free_syncop( so );
01010 
01011        return NULL;
01012 }
01013 
01014 /* Start the task to play back queued psearch responses */
01015 static void
01016 syncprov_qstart( syncops *so )
01017 {
01018        so->s_flags |= PS_TASK_QUEUED;
01019        so->s_inuse++;
01020        ldap_pvt_thread_pool_submit( &connection_pool, 
01021               syncprov_qtask, so );
01022 }
01023 
01024 /* Queue a persistent search response */
01025 static int
01026 syncprov_qresp( opcookie *opc, syncops *so, int mode )
01027 {
01028        syncres *sr;
01029        int srsize;
01030        struct berval cookie = opc->sctxcsn;
01031 
01032        if ( mode == LDAP_SYNC_NEW_COOKIE ) {
01033               syncprov_info_t      *si = opc->son->on_bi.bi_private;
01034 
01035               slap_compose_sync_cookie( NULL, &cookie, si->si_ctxcsn,
01036                      so->s_rid, slap_serverID ? slap_serverID : -1);
01037        }
01038 
01039        srsize = sizeof(syncres) + opc->suuid.bv_len + 1 +
01040               opc->sdn.bv_len + 1 + opc->sndn.bv_len + 1;
01041        if ( cookie.bv_len )
01042               srsize += cookie.bv_len + 1;
01043        sr = ch_malloc( srsize );
01044        sr->s_next = NULL;
01045        sr->s_e = opc->se;
01046        /* bump refcount on this entry */
01047        if ( opc->se )
01048               inc_mutexint( opc->se->e_private );
01049        sr->s_dn.bv_val = (char *)(sr + 1);
01050        sr->s_dn.bv_len = opc->sdn.bv_len;
01051        sr->s_mode = mode;
01052        sr->s_isreference = opc->sreference;
01053        sr->s_ndn.bv_val = lutil_strcopy( sr->s_dn.bv_val,
01054                opc->sdn.bv_val ) + 1;
01055        sr->s_ndn.bv_len = opc->sndn.bv_len;
01056        sr->s_uuid.bv_val = lutil_strcopy( sr->s_ndn.bv_val,
01057                opc->sndn.bv_val ) + 1;
01058        sr->s_uuid.bv_len = opc->suuid.bv_len;
01059        AC_MEMCPY( sr->s_uuid.bv_val, opc->suuid.bv_val, opc->suuid.bv_len );
01060        if ( cookie.bv_len ) {
01061               sr->s_csn.bv_val = sr->s_uuid.bv_val + sr->s_uuid.bv_len + 1;
01062               strcpy( sr->s_csn.bv_val, cookie.bv_val );
01063        } else {
01064               sr->s_csn.bv_val = NULL;
01065        }
01066        sr->s_csn.bv_len = cookie.bv_len;
01067 
01068        if ( mode == LDAP_SYNC_NEW_COOKIE && cookie.bv_val ) {
01069               ch_free( cookie.bv_val );
01070        }
01071 
01072        ldap_pvt_thread_mutex_lock( &so->s_mutex );
01073        if ( !so->s_res ) {
01074               so->s_res = sr;
01075        } else {
01076               so->s_restail->s_next = sr;
01077        }
01078        so->s_restail = sr;
01079 
01080        /* If the base of the psearch was modified, check it next time round */
01081        if ( so->s_flags & PS_WROTE_BASE ) {
01082               so->s_flags ^= PS_WROTE_BASE;
01083               so->s_flags |= PS_FIND_BASE;
01084        }
01085        if (( so->s_flags & (PS_IS_DETACHED|PS_TASK_QUEUED)) == PS_IS_DETACHED ) {
01086               syncprov_qstart( so );
01087        }
01088        ldap_pvt_thread_mutex_unlock( &so->s_mutex );
01089        return LDAP_SUCCESS;
01090 }
01091 
01092 static int
01093 syncprov_drop_psearch( syncops *so, int lock )
01094 {
01095        if ( so->s_flags & PS_IS_DETACHED ) {
01096               if ( lock )
01097                      ldap_pvt_thread_mutex_lock( &so->s_op->o_conn->c_mutex );
01098               so->s_op->o_conn->c_n_ops_executing--;
01099               so->s_op->o_conn->c_n_ops_completed++;
01100               LDAP_STAILQ_REMOVE( &so->s_op->o_conn->c_ops, so->s_op, Operation,
01101                      o_next );
01102               if ( lock )
01103                      ldap_pvt_thread_mutex_unlock( &so->s_op->o_conn->c_mutex );
01104        }
01105        syncprov_free_syncop( so );
01106 
01107        return 0;
01108 }
01109 
01110 static int
01111 syncprov_ab_cleanup( Operation *op, SlapReply *rs )
01112 {
01113        slap_callback *sc = op->o_callback;
01114        op->o_callback = sc->sc_next;
01115        syncprov_drop_psearch( op->o_callback->sc_private, 0 );
01116        op->o_tmpfree( sc, op->o_tmpmemctx );
01117        return 0;
01118 }
01119 
01120 static int
01121 syncprov_op_abandon( Operation *op, SlapReply *rs )
01122 {
01123        slap_overinst        *on = (slap_overinst *)op->o_bd->bd_info;
01124        syncprov_info_t             *si = on->on_bi.bi_private;
01125        syncops *so, *soprev;
01126 
01127        ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
01128        for ( so=si->si_ops, soprev = (syncops *)&si->si_ops; so;
01129               soprev=so, so=so->s_next ) {
01130               if ( so->s_op->o_connid == op->o_connid &&
01131                      so->s_op->o_msgid == op->orn_msgid ) {
01132                             so->s_op->o_abandon = 1;
01133                             soprev->s_next = so->s_next;
01134                             break;
01135               }
01136        }
01137        ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
01138        if ( so ) {
01139               /* Is this really a Cancel exop? */
01140               if ( op->o_tag != LDAP_REQ_ABANDON ) {
01141                      so->s_op->o_cancel = SLAP_CANCEL_ACK;
01142                      rs->sr_err = LDAP_CANCELLED;
01143                      send_ldap_result( so->s_op, rs );
01144                      if ( so->s_flags & PS_IS_DETACHED ) {
01145                             slap_callback *cb;
01146                             cb = op->o_tmpcalloc( 1, sizeof(slap_callback), op->o_tmpmemctx );
01147                             cb->sc_cleanup = syncprov_ab_cleanup;
01148                             cb->sc_next = op->o_callback;
01149                             cb->sc_private = so;
01150                             return SLAP_CB_CONTINUE;
01151                      }
01152               }
01153               syncprov_drop_psearch( so, 0 );
01154        }
01155        return SLAP_CB_CONTINUE;
01156 }
01157 
01158 /* Find which persistent searches are affected by this operation */
01159 static void
01160 syncprov_matchops( Operation *op, opcookie *opc, int saveit )
01161 {
01162        slap_overinst *on = opc->son;
01163        syncprov_info_t             *si = on->on_bi.bi_private;
01164 
01165        fbase_cookie fc;
01166        syncops *ss, *sprev, *snext;
01167        Entry *e = NULL;
01168        Attribute *a;
01169        int rc;
01170        struct berval newdn;
01171        int freefdn = 0;
01172        BackendDB *b0 = op->o_bd, db;
01173 
01174        fc.fdn = &op->o_req_ndn;
01175        /* compute new DN */
01176        if ( op->o_tag == LDAP_REQ_MODRDN && !saveit ) {
01177               struct berval pdn;
01178               if ( op->orr_nnewSup ) pdn = *op->orr_nnewSup;
01179               else dnParent( fc.fdn, &pdn );
01180               build_new_dn( &newdn, &pdn, &op->orr_nnewrdn, op->o_tmpmemctx );
01181               fc.fdn = &newdn;
01182               freefdn = 1;
01183        }
01184        if ( op->o_tag != LDAP_REQ_ADD ) {
01185               if ( !SLAP_ISOVERLAY( op->o_bd )) {
01186                      db = *op->o_bd;
01187                      op->o_bd = &db;
01188               }
01189               rc = overlay_entry_get_ov( op, fc.fdn, NULL, NULL, 0, &e, on );
01190               /* If we're sending responses now, make a copy and unlock the DB */
01191               if ( e && !saveit ) {
01192                      if ( !opc->se ) {
01193                             opc->se = entry_dup( e );
01194                             opc->se->e_private = get_mutexint();
01195                      }
01196                      overlay_entry_release_ov( op, e, 0, on );
01197                      e = opc->se;
01198               }
01199               if ( rc ) {
01200                      op->o_bd = b0;
01201                      return;
01202               }
01203        } else {
01204               e = op->ora_e;
01205               if ( !saveit ) {
01206                      if ( !opc->se ) {
01207                             opc->se = entry_dup( e );
01208                             opc->se->e_private = get_mutexint();
01209                      }
01210                      e = opc->se;
01211               }
01212        }
01213 
01214        if ( saveit || op->o_tag == LDAP_REQ_ADD ) {
01215               ber_dupbv_x( &opc->sdn, &e->e_name, op->o_tmpmemctx );
01216               ber_dupbv_x( &opc->sndn, &e->e_nname, op->o_tmpmemctx );
01217               opc->sreference = is_entry_referral( e );
01218               a = attr_find( e->e_attrs, slap_schema.si_ad_entryUUID );
01219               if ( a )
01220                      ber_dupbv_x( &opc->suuid, &a->a_nvals[0], op->o_tmpmemctx );
01221        } else if ( op->o_tag == LDAP_REQ_MODRDN && !saveit ) {
01222               op->o_tmpfree( opc->sndn.bv_val, op->o_tmpmemctx );
01223               op->o_tmpfree( opc->sdn.bv_val, op->o_tmpmemctx );
01224               ber_dupbv_x( &opc->sdn, &e->e_name, op->o_tmpmemctx );
01225               ber_dupbv_x( &opc->sndn, &e->e_nname, op->o_tmpmemctx );
01226        }
01227 
01228        ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
01229        for (ss = si->si_ops, sprev = (syncops *)&si->si_ops; ss;
01230               sprev = ss, ss=snext)
01231        {
01232               Operation op2;
01233               Opheader oh;
01234               syncmatches *sm;
01235               int found = 0;
01236 
01237               snext = ss->s_next;
01238               if ( ss->s_op->o_abandon )
01239                      continue;
01240 
01241               /* Don't send ops back to the originator */
01242               if ( opc->osid > 0 && opc->osid == ss->s_sid ) {
01243                      Debug( LDAP_DEBUG_SYNC, "syncprov_matchops: skipping original sid %03x\n",
01244                             opc->osid, 0, 0 );
01245                      continue;
01246               }
01247 
01248               /* Don't send ops back to the messenger */
01249               if ( opc->rsid > 0 && opc->rsid == ss->s_sid ) {
01250                      Debug( LDAP_DEBUG_SYNC, "syncprov_matchops: skipping relayed sid %03x\n",
01251                             opc->rsid, 0, 0 );
01252                      continue;
01253               }
01254 
01255               /* validate base */
01256               fc.fss = ss;
01257               fc.fbase = 0;
01258               fc.fscope = 0;
01259 
01260               /* If the base of the search is missing, signal a refresh */
01261               rc = syncprov_findbase( op, &fc );
01262               if ( rc != LDAP_SUCCESS ) {
01263                      SlapReply rs = {REP_RESULT};
01264                      send_ldap_error( ss->s_op, &rs, LDAP_SYNC_REFRESH_REQUIRED,
01265                             "search base has changed" );
01266                      sprev->s_next = snext;
01267                      syncprov_drop_psearch( ss, 1 );
01268                      ss = sprev;
01269                      continue;
01270               }
01271 
01272               /* If we're sending results now, look for this op in old matches */
01273               if ( !saveit ) {
01274                      syncmatches *old;
01275 
01276                      /* Did we modify the search base? */
01277                      if ( dn_match( &op->o_req_ndn, &ss->s_base )) {
01278                             ldap_pvt_thread_mutex_lock( &ss->s_mutex );
01279                             ss->s_flags |= PS_WROTE_BASE;
01280                             ldap_pvt_thread_mutex_unlock( &ss->s_mutex );
01281                      }
01282 
01283                      for ( sm=opc->smatches, old=(syncmatches *)&opc->smatches; sm;
01284                             old=sm, sm=sm->sm_next ) {
01285                             if ( sm->sm_op == ss ) {
01286                                    found = 1;
01287                                    old->sm_next = sm->sm_next;
01288                                    op->o_tmpfree( sm, op->o_tmpmemctx );
01289                                    break;
01290                             }
01291                      }
01292               }
01293 
01294               if ( fc.fscope ) {
01295                      ldap_pvt_thread_mutex_lock( &ss->s_mutex );
01296                      op2 = *ss->s_op;
01297                      oh = *op->o_hdr;
01298                      oh.oh_conn = ss->s_op->o_conn;
01299                      oh.oh_connid = ss->s_op->o_connid;
01300                      op2.o_bd = op->o_bd->bd_self;
01301                      op2.o_hdr = &oh;
01302                      op2.o_extra = op->o_extra;
01303                      op2.o_callback = NULL;
01304                      if (ss->s_flags & PS_FIX_FILTER) {
01305                             /* Skip the AND/GE clause that we stuck on in front. We
01306                                would lose deletes/mods that happen during the refresh
01307                                phase otherwise (ITS#6555) */
01308                             op2.ors_filter = ss->s_op->ors_filter->f_and->f_next;
01309                      }
01310                      ldap_pvt_thread_mutex_unlock( &ss->s_mutex );
01311                      rc = test_filter( &op2, e, op2.ors_filter );
01312               }
01313 
01314               Debug( LDAP_DEBUG_TRACE, "syncprov_matchops: sid %03x fscope %d rc %d\n",
01315                      ss->s_sid, fc.fscope, rc );
01316 
01317               /* check if current o_req_dn is in scope and matches filter */
01318               if ( fc.fscope && rc == LDAP_COMPARE_TRUE ) {
01319                      if ( saveit ) {
01320                             sm = op->o_tmpalloc( sizeof(syncmatches), op->o_tmpmemctx );
01321                             sm->sm_next = opc->smatches;
01322                             sm->sm_op = ss;
01323                             ldap_pvt_thread_mutex_lock( &ss->s_mutex );
01324                             ++ss->s_inuse;
01325                             ldap_pvt_thread_mutex_unlock( &ss->s_mutex );
01326                             opc->smatches = sm;
01327                      } else {
01328                             /* if found send UPDATE else send ADD */
01329                             syncprov_qresp( opc, ss,
01330                                    found ? LDAP_SYNC_MODIFY : LDAP_SYNC_ADD );
01331                      }
01332               } else if ( !saveit && found ) {
01333                      /* send DELETE */
01334                      syncprov_qresp( opc, ss, LDAP_SYNC_DELETE );
01335               } else if ( !saveit ) {
01336                      syncprov_qresp( opc, ss, LDAP_SYNC_NEW_COOKIE );
01337               }
01338               if ( !saveit && found ) {
01339                      /* Decrement s_inuse, was incremented when called
01340                       * with saveit == TRUE
01341                       */
01342                      syncprov_free_syncop( ss );
01343               }
01344        }
01345        ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
01346 
01347        if ( op->o_tag != LDAP_REQ_ADD && e ) {
01348               if ( !SLAP_ISOVERLAY( op->o_bd )) {
01349                      op->o_bd = &db;
01350               }
01351               if ( saveit )
01352                      overlay_entry_release_ov( op, e, 0, on );
01353               op->o_bd = b0;
01354        }
01355        if ( opc->se && !saveit ) {
01356               if ( !dec_mutexint( opc->se->e_private )) {
01357                      opc->se->e_private = NULL;
01358                      entry_free( opc->se );
01359                      opc->se = NULL;
01360               }
01361        }
01362        if ( freefdn ) {
01363               op->o_tmpfree( fc.fdn->bv_val, op->o_tmpmemctx );
01364        }
01365        op->o_bd = b0;
01366 }
01367 
01368 static int
01369 syncprov_op_cleanup( Operation *op, SlapReply *rs )
01370 {
01371        slap_callback *cb = op->o_callback;
01372        opcookie *opc = cb->sc_private;
01373        slap_overinst *on = opc->son;
01374        syncprov_info_t             *si = on->on_bi.bi_private;
01375        syncmatches *sm, *snext;
01376        modtarget *mt;
01377 
01378        ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
01379        if ( si->si_active )
01380               si->si_active--;
01381        ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
01382 
01383        for (sm = opc->smatches; sm; sm=snext) {
01384               snext = sm->sm_next;
01385               syncprov_free_syncop( sm->sm_op );
01386               op->o_tmpfree( sm, op->o_tmpmemctx );
01387        }
01388 
01389        /* Remove op from lock table */
01390        mt = opc->smt;
01391        if ( mt ) {
01392               ldap_pvt_thread_mutex_lock( &mt->mt_mutex );
01393               mt->mt_mods = mt->mt_mods->mi_next;
01394               /* If there are more, promote the next one */
01395               if ( mt->mt_mods ) {
01396                      mt->mt_op = mt->mt_mods->mi_op;
01397                      ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
01398               } else {
01399                      ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
01400                      ldap_pvt_thread_mutex_lock( &si->si_mods_mutex );
01401                      avl_delete( &si->si_mods, mt, sp_avl_cmp );
01402                      ldap_pvt_thread_mutex_unlock( &si->si_mods_mutex );
01403                      ldap_pvt_thread_mutex_destroy( &mt->mt_mutex );
01404                      ch_free( mt );
01405               }
01406        }
01407        if ( !BER_BVISNULL( &opc->suuid ))
01408               op->o_tmpfree( opc->suuid.bv_val, op->o_tmpmemctx );
01409        if ( !BER_BVISNULL( &opc->sndn ))
01410               op->o_tmpfree( opc->sndn.bv_val, op->o_tmpmemctx );
01411        if ( !BER_BVISNULL( &opc->sdn ))
01412               op->o_tmpfree( opc->sdn.bv_val, op->o_tmpmemctx );
01413        op->o_callback = cb->sc_next;
01414        op->o_tmpfree(cb, op->o_tmpmemctx);
01415 
01416        return 0;
01417 }
01418 
01419 static void
01420 syncprov_checkpoint( Operation *op, slap_overinst *on )
01421 {
01422        syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
01423        Modifications mod;
01424        Operation opm;
01425        SlapReply rsm = {REP_RESULT};
01426        slap_callback cb = {0};
01427        BackendDB be;
01428        BackendInfo *bi;
01429 
01430 #ifdef CHECK_CSN
01431        Syntax *syn = slap_schema.si_ad_contextCSN->ad_type->sat_syntax;
01432 
01433        int i;
01434        for ( i=0; i<si->si_numcsns; i++ ) {
01435               assert( !syn->ssyn_validate( syn, si->si_ctxcsn+i ));
01436        }
01437 #endif
01438        mod.sml_numvals = si->si_numcsns;
01439        mod.sml_values = si->si_ctxcsn;
01440        mod.sml_nvalues = NULL;
01441        mod.sml_desc = slap_schema.si_ad_contextCSN;
01442        mod.sml_op = LDAP_MOD_REPLACE;
01443        mod.sml_flags = SLAP_MOD_INTERNAL;
01444        mod.sml_next = NULL;
01445 
01446        cb.sc_response = slap_null_cb;
01447        opm = *op;
01448        opm.o_tag = LDAP_REQ_MODIFY;
01449        opm.o_callback = &cb;
01450        opm.orm_modlist = &mod;
01451        opm.orm_no_opattrs = 1;
01452        if ( SLAP_GLUE_SUBORDINATE( op->o_bd )) {
01453               be = *on->on_info->oi_origdb;
01454               opm.o_bd = &be;
01455        }
01456        opm.o_req_dn = si->si_contextdn;
01457        opm.o_req_ndn = si->si_contextdn;
01458        bi = opm.o_bd->bd_info;
01459        opm.o_bd->bd_info = on->on_info->oi_orig;
01460        opm.o_managedsait = SLAP_CONTROL_NONCRITICAL;
01461        opm.o_no_schema_check = 1;
01462        opm.o_bd->be_modify( &opm, &rsm );
01463 
01464        if ( rsm.sr_err == LDAP_NO_SUCH_OBJECT &&
01465               SLAP_SYNC_SUBENTRY( opm.o_bd )) {
01466               const char    *text;
01467               char txtbuf[SLAP_TEXT_BUFLEN];
01468               size_t textlen = sizeof txtbuf;
01469               Entry *e = slap_create_context_csn_entry( opm.o_bd, NULL );
01470               rs_reinit( &rsm, REP_RESULT );
01471               slap_mods2entry( &mod, &e, 0, 1, &text, txtbuf, textlen);
01472               opm.ora_e = e;
01473               opm.o_bd->be_add( &opm, &rsm );
01474               if ( e == opm.ora_e )
01475                      be_entry_release_w( &opm, opm.ora_e );
01476        }
01477        opm.o_bd->bd_info = bi;
01478 
01479        if ( mod.sml_next != NULL ) {
01480               slap_mods_free( mod.sml_next, 1 );
01481        }
01482 #ifdef CHECK_CSN
01483        for ( i=0; i<si->si_numcsns; i++ ) {
01484               assert( !syn->ssyn_validate( syn, si->si_ctxcsn+i ));
01485        }
01486 #endif
01487 }
01488 
01489 static void
01490 syncprov_add_slog( Operation *op )
01491 {
01492        opcookie *opc = op->o_callback->sc_private;
01493        slap_overinst *on = opc->son;
01494        syncprov_info_t             *si = on->on_bi.bi_private;
01495        sessionlog *sl;
01496        slog_entry *se;
01497 
01498        sl = si->si_logs;
01499        {
01500               if ( BER_BVISEMPTY( &op->o_csn ) ) {
01501                      /* During the syncrepl refresh phase we can receive operations
01502                       * without a csn.  We cannot reliably determine the consumers
01503                       * state with respect to such operations, so we ignore them and
01504                       * wipe out anything in the log if we see them.
01505                       */
01506                      ldap_pvt_thread_mutex_lock( &sl->sl_mutex );
01507                      while ( se = sl->sl_head ) {
01508                             sl->sl_head = se->se_next;
01509                             ch_free( se );
01510                      }
01511                      sl->sl_tail = NULL;
01512                      sl->sl_num = 0;
01513                      ldap_pvt_thread_mutex_unlock( &sl->sl_mutex );
01514                      return;
01515               }
01516 
01517               /* Allocate a record. UUIDs are not NUL-terminated. */
01518               se = ch_malloc( sizeof( slog_entry ) + opc->suuid.bv_len + 
01519                      op->o_csn.bv_len + 1 );
01520               se->se_next = NULL;
01521               se->se_tag = op->o_tag;
01522 
01523               se->se_uuid.bv_val = (char *)(&se[1]);
01524               AC_MEMCPY( se->se_uuid.bv_val, opc->suuid.bv_val, opc->suuid.bv_len );
01525               se->se_uuid.bv_len = opc->suuid.bv_len;
01526 
01527               se->se_csn.bv_val = se->se_uuid.bv_val + opc->suuid.bv_len;
01528               AC_MEMCPY( se->se_csn.bv_val, op->o_csn.bv_val, op->o_csn.bv_len );
01529               se->se_csn.bv_val[op->o_csn.bv_len] = '\0';
01530               se->se_csn.bv_len = op->o_csn.bv_len;
01531               se->se_sid = slap_parse_csn_sid( &se->se_csn );
01532 
01533               ldap_pvt_thread_mutex_lock( &sl->sl_mutex );
01534               if ( sl->sl_head ) {
01535                      /* Keep the list in csn order. */
01536                      if ( ber_bvcmp( &sl->sl_tail->se_csn, &se->se_csn ) <= 0 ) {
01537                             sl->sl_tail->se_next = se;
01538                             sl->sl_tail = se;
01539                      } else {
01540                             slog_entry **sep;
01541 
01542                             for ( sep = &sl->sl_head; *sep; sep = &(*sep)->se_next ) {
01543                                    if ( ber_bvcmp( &se->se_csn, &(*sep)->se_csn ) < 0 ) {
01544                                           se->se_next = *sep;
01545                                           *sep = se;
01546                                           break;
01547                                    }
01548                             }
01549                      }
01550               } else {
01551                      sl->sl_head = se;
01552                      sl->sl_tail = se;
01553                      if ( !sl->sl_mincsn ) {
01554                             sl->sl_numcsns = 1;
01555                             sl->sl_mincsn = ch_malloc( 2*sizeof( struct berval ));
01556                             sl->sl_sids = ch_malloc( sizeof( int ));
01557                             sl->sl_sids[0] = se->se_sid;
01558                             ber_dupbv( sl->sl_mincsn, &se->se_csn );
01559                             BER_BVZERO( &sl->sl_mincsn[1] );
01560                      }
01561               }
01562               sl->sl_num++;
01563               while ( sl->sl_num > sl->sl_size ) {
01564                      int i, j;
01565                      se = sl->sl_head;
01566                      sl->sl_head = se->se_next;
01567                      for ( i=0; i<sl->sl_numcsns; i++ )
01568                             if ( sl->sl_sids[i] >= se->se_sid )
01569                                    break;
01570                      if  ( i == sl->sl_numcsns || sl->sl_sids[i] != se->se_sid ) {
01571                             slap_insert_csn_sids( (struct sync_cookie *)sl,
01572                                    i, se->se_sid, &se->se_csn );
01573                      } else {
01574                             ber_bvreplace( &sl->sl_mincsn[i], &se->se_csn );
01575                      }
01576                      ch_free( se );
01577                      sl->sl_num--;
01578               }
01579               ldap_pvt_thread_mutex_unlock( &sl->sl_mutex );
01580        }
01581 }
01582 
01583 /* Just set a flag if we found the matching entry */
01584 static int
01585 playlog_cb( Operation *op, SlapReply *rs )
01586 {
01587        if ( rs->sr_type == REP_SEARCH ) {
01588               op->o_callback->sc_private = (void *)1;
01589        }
01590        return rs->sr_err;
01591 }
01592 
01593 /* enter with sl->sl_mutex locked, release before returning */
01594 static void
01595 syncprov_playlog( Operation *op, SlapReply *rs, sessionlog *sl,
01596        sync_control *srs, BerVarray ctxcsn, int numcsns, int *sids )
01597 {
01598        slap_overinst        *on = (slap_overinst *)op->o_bd->bd_info;
01599        slog_entry *se;
01600        int i, j, ndel, num, nmods, mmods;
01601        char cbuf[LDAP_PVT_CSNSTR_BUFSIZE];
01602        BerVarray uuids;
01603        struct berval delcsn[2];
01604 
01605        if ( !sl->sl_num ) {
01606               ldap_pvt_thread_mutex_unlock( &sl->sl_mutex );
01607               return;
01608        }
01609 
01610        num = sl->sl_num;
01611        i = 0;
01612        nmods = 0;
01613 
01614        uuids = op->o_tmpalloc( (num+1) * sizeof( struct berval ) +
01615               num * UUID_LEN, op->o_tmpmemctx );
01616        uuids[0].bv_val = (char *)(uuids + num + 1);
01617 
01618        delcsn[0].bv_len = 0;
01619        delcsn[0].bv_val = cbuf;
01620        BER_BVZERO(&delcsn[1]);
01621 
01622        /* Make a copy of the relevant UUIDs. Put the Deletes up front
01623         * and everything else at the end. Do this first so we can
01624         * unlock the list mutex.
01625         */
01626        Debug( LDAP_DEBUG_SYNC, "srs csn %s\n",
01627               srs->sr_state.ctxcsn[0].bv_val, 0, 0 );
01628        for ( se=sl->sl_head; se; se=se->se_next ) {
01629               int k;
01630               Debug( LDAP_DEBUG_SYNC, "log csn %s\n", se->se_csn.bv_val, 0, 0 );
01631               ndel = 1;
01632               for ( k=0; k<srs->sr_state.numcsns; k++ ) {
01633                      if ( se->se_sid == srs->sr_state.sids[k] ) {
01634                             ndel = ber_bvcmp( &se->se_csn, &srs->sr_state.ctxcsn[k] );
01635                             break;
01636                      }
01637               }
01638               if ( ndel <= 0 ) {
01639                      Debug( LDAP_DEBUG_SYNC, "cmp %d, too old\n", ndel, 0, 0 );
01640                      continue;
01641               }
01642               ndel = 0;
01643               for ( k=0; k<numcsns; k++ ) {
01644                      if ( se->se_sid == sids[k] ) {
01645                             ndel = ber_bvcmp( &se->se_csn, &ctxcsn[k] );
01646                             break;
01647                      }
01648               }
01649               if ( ndel > 0 ) {
01650                      Debug( LDAP_DEBUG_SYNC, "cmp %d, too new\n", ndel, 0, 0 );
01651                      break;
01652               }
01653               if ( se->se_tag == LDAP_REQ_DELETE ) {
01654                      j = i;
01655                      i++;
01656                      AC_MEMCPY( cbuf, se->se_csn.bv_val, se->se_csn.bv_len );
01657                      delcsn[0].bv_len = se->se_csn.bv_len;
01658                      delcsn[0].bv_val[delcsn[0].bv_len] = '\0';
01659               } else {
01660                      if ( se->se_tag == LDAP_REQ_ADD )
01661                             continue;
01662                      nmods++;
01663                      j = num - nmods;
01664               }
01665               uuids[j].bv_val = uuids[0].bv_val + (j * UUID_LEN);
01666               AC_MEMCPY(uuids[j].bv_val, se->se_uuid.bv_val, UUID_LEN);
01667               uuids[j].bv_len = UUID_LEN;
01668        }
01669        ldap_pvt_thread_mutex_unlock( &sl->sl_mutex );
01670 
01671        ndel = i;
01672 
01673        /* Zero out unused slots */
01674        for ( i=ndel; i < num - nmods; i++ )
01675               uuids[i].bv_len = 0;
01676 
01677        /* Mods must be validated to see if they belong in this delete set.
01678         */
01679 
01680        mmods = nmods;
01681        /* Strip any duplicates */
01682        for ( i=0; i<nmods; i++ ) {
01683               for ( j=0; j<ndel; j++ ) {
01684                      if ( bvmatch( &uuids[j], &uuids[num - 1 - i] )) {
01685                             uuids[num - 1 - i].bv_len = 0;
01686                             mmods --;
01687                             break;
01688                      }
01689               }
01690               if ( uuids[num - 1 - i].bv_len == 0 ) continue;
01691               for ( j=0; j<i; j++ ) {
01692                      if ( bvmatch( &uuids[num - 1 - j], &uuids[num - 1 - i] )) {
01693                             uuids[num - 1 - i].bv_len = 0;
01694                             mmods --;
01695                             break;
01696                      }
01697               }
01698        }
01699 
01700        if ( mmods ) {
01701               Operation fop;
01702               int rc;
01703               Filter mf, af;
01704               AttributeAssertion eq = ATTRIBUTEASSERTION_INIT;
01705               slap_callback cb = {0};
01706 
01707               fop = *op;
01708 
01709               fop.o_sync_mode = 0;
01710               fop.o_callback = &cb;
01711               fop.ors_limit = NULL;
01712               fop.ors_tlimit = SLAP_NO_LIMIT;
01713               fop.ors_attrs = slap_anlist_all_attributes;
01714               fop.ors_attrsonly = 0;
01715               fop.o_managedsait = SLAP_CONTROL_CRITICAL;
01716 
01717               af.f_choice = LDAP_FILTER_AND;
01718               af.f_next = NULL;
01719               af.f_and = &mf;
01720               mf.f_choice = LDAP_FILTER_EQUALITY;
01721               mf.f_ava = &eq;
01722               mf.f_av_desc = slap_schema.si_ad_entryUUID;
01723               mf.f_next = fop.ors_filter;
01724 
01725               fop.ors_filter = &af;
01726 
01727               cb.sc_response = playlog_cb;
01728               fop.o_bd->bd_info = (BackendInfo *)on->on_info;
01729 
01730               for ( i=ndel; i<num; i++ ) {
01731                 if ( uuids[i].bv_len != 0 ) {
01732                      SlapReply frs = { REP_RESULT };
01733 
01734                      mf.f_av_value = uuids[i];
01735                      cb.sc_private = NULL;
01736                      fop.ors_slimit = 1;
01737                      rc = fop.o_bd->be_search( &fop, &frs );
01738 
01739                      /* If entry was not found, add to delete list */
01740                      if ( !cb.sc_private ) {
01741                             uuids[ndel++] = uuids[i];
01742                      }
01743                 }
01744               }
01745               fop.o_bd->bd_info = (BackendInfo *)on;
01746        }
01747        if ( ndel ) {
01748               struct berval cookie;
01749 
01750               if ( delcsn[0].bv_len ) {
01751                      slap_compose_sync_cookie( op, &cookie, delcsn, srs->sr_state.rid,
01752                             slap_serverID ? slap_serverID : -1 );
01753 
01754                      Debug( LDAP_DEBUG_SYNC, "syncprov_playlog: cookie=%s\n", cookie.bv_val, 0, 0 );
01755               }
01756 
01757               uuids[ndel].bv_val = NULL;
01758               syncprov_sendinfo( op, rs, LDAP_TAG_SYNC_ID_SET,
01759                      delcsn[0].bv_len ? &cookie : NULL, 0, uuids, 1 );
01760               if ( delcsn[0].bv_len ) {
01761                      op->o_tmpfree( cookie.bv_val, op->o_tmpmemctx );
01762               }
01763        }
01764        op->o_tmpfree( uuids, op->o_tmpmemctx );
01765 }
01766 
01767 static int
01768 syncprov_op_response( Operation *op, SlapReply *rs )
01769 {
01770        opcookie *opc = op->o_callback->sc_private;
01771        slap_overinst *on = opc->son;
01772        syncprov_info_t             *si = on->on_bi.bi_private;
01773        syncmatches *sm;
01774 
01775        if ( rs->sr_err == LDAP_SUCCESS )
01776        {
01777               struct berval maxcsn;
01778               char cbuf[LDAP_PVT_CSNSTR_BUFSIZE];
01779               int do_check = 0, have_psearches, foundit, csn_changed = 0;
01780 
01781               ldap_pvt_thread_mutex_lock( &si->si_resp_mutex );
01782 
01783               /* Update our context CSN */
01784               cbuf[0] = '\0';
01785               maxcsn.bv_val = cbuf;
01786               maxcsn.bv_len = sizeof(cbuf);
01787               ldap_pvt_thread_rdwr_wlock( &si->si_csn_rwlock );
01788 
01789               slap_get_commit_csn( op, &maxcsn, &foundit );
01790               if ( BER_BVISEMPTY( &maxcsn ) && SLAP_GLUE_SUBORDINATE( op->o_bd )) {
01791                      /* syncrepl queues the CSN values in the db where
01792                       * it is configured , not where the changes are made.
01793                       * So look for a value in the glue db if we didn't
01794                       * find any in this db.
01795                       */
01796                      BackendDB *be = op->o_bd;
01797                      op->o_bd = select_backend( &be->be_nsuffix[0], 1);
01798                      maxcsn.bv_val = cbuf;
01799                      maxcsn.bv_len = sizeof(cbuf);
01800                      slap_get_commit_csn( op, &maxcsn, &foundit );
01801                      op->o_bd = be;
01802               }
01803               if ( !BER_BVISEMPTY( &maxcsn ) ) {
01804                      int i, sid;
01805 #ifdef CHECK_CSN
01806                      Syntax *syn = slap_schema.si_ad_contextCSN->ad_type->sat_syntax;
01807                      assert( !syn->ssyn_validate( syn, &maxcsn ));
01808 #endif
01809                      sid = slap_parse_csn_sid( &maxcsn );
01810                      for ( i=0; i<si->si_numcsns; i++ ) {
01811                             if ( sid < si->si_sids[i] )
01812                                    break;
01813                             if ( sid == si->si_sids[i] ) {
01814                                    if ( ber_bvcmp( &maxcsn, &si->si_ctxcsn[i] ) > 0 ) {
01815                                           ber_bvreplace( &si->si_ctxcsn[i], &maxcsn );
01816                                           csn_changed = 1;
01817                                    }
01818                                    break;
01819                             }
01820                      }
01821                      /* It's a new SID for us */
01822                      if ( i == si->si_numcsns || sid != si->si_sids[i] ) {
01823                             slap_insert_csn_sids((struct sync_cookie *)&(si->si_ctxcsn),
01824                                    i, sid, &maxcsn );
01825                             csn_changed = 1;
01826                      }
01827               }
01828 
01829               /* Don't do any processing for consumer contextCSN updates */
01830               if ( op->o_dont_replicate ) {
01831                      if ( op->o_tag == LDAP_REQ_MODIFY &&
01832                             op->orm_modlist->sml_op == LDAP_MOD_REPLACE &&
01833                             op->orm_modlist->sml_desc == slap_schema.si_ad_contextCSN ) {
01834                      /* Catch contextCSN updates from syncrepl. We have to look at
01835                       * all the attribute values, as there may be more than one csn
01836                       * that changed, and only one can be passed in the csn queue.
01837                       */
01838                      Modifications *mod = op->orm_modlist;
01839                      unsigned i;
01840                      int j, sid;
01841 
01842                      for ( i=0; i<mod->sml_numvals; i++ ) {
01843                             sid = slap_parse_csn_sid( &mod->sml_values[i] );
01844                             for ( j=0; j<si->si_numcsns; j++ ) {
01845                                    if ( sid < si->si_sids[j] )
01846                                           break;
01847                                    if ( sid == si->si_sids[j] ) {
01848                                           if ( ber_bvcmp( &mod->sml_values[i], &si->si_ctxcsn[j] ) > 0 ) {
01849                                                  ber_bvreplace( &si->si_ctxcsn[j], &mod->sml_values[i] );
01850                                                  csn_changed = 1;
01851                                           }
01852                                           break;
01853                                    }
01854                             }
01855 
01856                             if ( j == si->si_numcsns || sid != si->si_sids[j] ) {
01857                                    slap_insert_csn_sids( (struct sync_cookie *)&si->si_ctxcsn,
01858                                           j, sid, &mod->sml_values[i] );
01859                                    csn_changed = 1;
01860                             }
01861                      }
01862                      if ( csn_changed )
01863                             si->si_dirty = 0;
01864                      ldap_pvt_thread_rdwr_wunlock( &si->si_csn_rwlock );
01865 
01866                      if ( csn_changed ) {
01867                             syncops *ss;
01868                             ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
01869                             for ( ss = si->si_ops; ss; ss = ss->s_next ) {
01870                                    if ( ss->s_op->o_abandon )
01871                                           continue;
01872                                    /* Send the updated csn to all syncrepl consumers,
01873                                     * including the server from which it originated.
01874                                     * The syncrepl consumer and syncprov provider on
01875                                     * the originating server may be configured to store
01876                                     * their csn values in different entries.
01877                                     */
01878                                    syncprov_qresp( opc, ss, LDAP_SYNC_NEW_COOKIE );
01879                             }
01880                             ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
01881                      }
01882                      } else {
01883                      ldap_pvt_thread_rdwr_wunlock( &si->si_csn_rwlock );
01884                      }
01885                      goto leave;
01886               }
01887 
01888               si->si_numops++;
01889               if ( si->si_chkops || si->si_chktime ) {
01890                      /* Never checkpoint adding the context entry,
01891                       * it will deadlock
01892                       */
01893                      if ( op->o_tag != LDAP_REQ_ADD ||
01894                             !dn_match( &op->o_req_ndn, &si->si_contextdn )) {
01895                             if ( si->si_chkops && si->si_numops >= si->si_chkops ) {
01896                                    do_check = 1;
01897                                    si->si_numops = 0;
01898                             }
01899                             if ( si->si_chktime &&
01900                                    (op->o_time - si->si_chklast >= si->si_chktime )) {
01901                                    if ( si->si_chklast ) {
01902                                           do_check = 1;
01903                                           si->si_chklast = op->o_time;
01904                                    } else {
01905                                           si->si_chklast = 1;
01906                                    }
01907                             }
01908                      }
01909               }
01910               si->si_dirty = !csn_changed;
01911               ldap_pvt_thread_rdwr_wunlock( &si->si_csn_rwlock );
01912 
01913               if ( do_check ) {
01914                      ldap_pvt_thread_rdwr_rlock( &si->si_csn_rwlock );
01915                      syncprov_checkpoint( op, on );
01916                      ldap_pvt_thread_rdwr_runlock( &si->si_csn_rwlock );
01917               }
01918 
01919               /* only update consumer ctx if this is a newer csn */
01920               if ( csn_changed ) {
01921                      opc->sctxcsn = maxcsn;
01922               }
01923 
01924               /* Handle any persistent searches */
01925               ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
01926               have_psearches = ( si->si_ops != NULL );
01927               ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
01928               if ( have_psearches ) {
01929                      switch(op->o_tag) {
01930                      case LDAP_REQ_ADD:
01931                      case LDAP_REQ_MODIFY:
01932                      case LDAP_REQ_MODRDN:
01933                      case LDAP_REQ_EXTENDED:
01934                             syncprov_matchops( op, opc, 0 );
01935                             break;
01936                      case LDAP_REQ_DELETE:
01937                             /* for each match in opc->smatches:
01938                              *   send DELETE msg
01939                              */
01940                             for ( sm = opc->smatches; sm; sm=sm->sm_next ) {
01941                                    if ( sm->sm_op->s_op->o_abandon )
01942                                           continue;
01943                                    syncprov_qresp( opc, sm->sm_op, LDAP_SYNC_DELETE );
01944                             }
01945                             break;
01946                      }
01947               }
01948 
01949               /* Add any log records */
01950               if ( si->si_logs ) {
01951                      syncprov_add_slog( op );
01952               }
01953 leave:        ldap_pvt_thread_mutex_unlock( &si->si_resp_mutex );
01954        }
01955        return SLAP_CB_CONTINUE;
01956 }
01957 
01958 /* We don't use a subentry to store the context CSN any more.
01959  * We expose the current context CSN as an operational attribute
01960  * of the suffix entry.
01961  */
01962 static int
01963 syncprov_op_compare( Operation *op, SlapReply *rs )
01964 {
01965        slap_overinst        *on = (slap_overinst *)op->o_bd->bd_info;
01966        syncprov_info_t             *si = on->on_bi.bi_private;
01967        int rc = SLAP_CB_CONTINUE;
01968 
01969        if ( dn_match( &op->o_req_ndn, &si->si_contextdn ) &&
01970               op->oq_compare.rs_ava->aa_desc == slap_schema.si_ad_contextCSN )
01971        {
01972               Entry e = {0};
01973               Attribute a = {0};
01974 
01975               e.e_name = si->si_contextdn;
01976               e.e_nname = si->si_contextdn;
01977               e.e_attrs = &a;
01978 
01979               a.a_desc = slap_schema.si_ad_contextCSN;
01980 
01981               ldap_pvt_thread_rdwr_rlock( &si->si_csn_rwlock );
01982 
01983               a.a_vals = si->si_ctxcsn;
01984               a.a_nvals = a.a_vals;
01985               a.a_numvals = si->si_numcsns;
01986 
01987               rs->sr_err = access_allowed( op, &e, op->oq_compare.rs_ava->aa_desc,
01988                      &op->oq_compare.rs_ava->aa_value, ACL_COMPARE, NULL );
01989               if ( ! rs->sr_err ) {
01990                      rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
01991                      goto return_results;
01992               }
01993 
01994               if ( get_assert( op ) &&
01995                      ( test_filter( op, &e, get_assertion( op ) ) != LDAP_COMPARE_TRUE ) )
01996               {
01997                      rs->sr_err = LDAP_ASSERTION_FAILED;
01998                      goto return_results;
01999               }
02000 
02001 
02002               rs->sr_err = LDAP_COMPARE_FALSE;
02003 
02004               if ( attr_valfind( &a,
02005                      SLAP_MR_ATTRIBUTE_VALUE_NORMALIZED_MATCH |
02006                             SLAP_MR_ASSERTED_VALUE_NORMALIZED_MATCH,
02007                             &op->oq_compare.rs_ava->aa_value, NULL, op->o_tmpmemctx ) == 0 )
02008               {
02009                      rs->sr_err = LDAP_COMPARE_TRUE;
02010               }
02011 
02012 return_results:;
02013 
02014               ldap_pvt_thread_rdwr_runlock( &si->si_csn_rwlock );
02015 
02016               send_ldap_result( op, rs );
02017 
02018               if( rs->sr_err == LDAP_COMPARE_FALSE || rs->sr_err == LDAP_COMPARE_TRUE ) {
02019                      rs->sr_err = LDAP_SUCCESS;
02020               }
02021               rc = rs->sr_err;
02022        }
02023 
02024        return rc;
02025 }
02026 
02027 static int
02028 syncprov_op_mod( Operation *op, SlapReply *rs )
02029 {
02030        slap_overinst        *on = (slap_overinst *)op->o_bd->bd_info;
02031        syncprov_info_t             *si = on->on_bi.bi_private;
02032        slap_callback *cb;
02033        opcookie *opc;
02034        int have_psearches, cbsize;
02035 
02036        ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
02037        have_psearches = ( si->si_ops != NULL );
02038        si->si_active++;
02039        ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
02040 
02041        cbsize = sizeof(slap_callback) + sizeof(opcookie) +
02042               (have_psearches ? sizeof(modinst) : 0 );
02043 
02044        cb = op->o_tmpcalloc(1, cbsize, op->o_tmpmemctx);
02045        opc = (opcookie *)(cb+1);
02046        opc->son = on;
02047        cb->sc_response = syncprov_op_response;
02048        cb->sc_cleanup = syncprov_op_cleanup;
02049        cb->sc_private = opc;
02050        cb->sc_next = op->o_callback;
02051        op->o_callback = cb;
02052 
02053        opc->osid = -1;
02054        opc->rsid = -1;
02055        if ( op->o_csn.bv_val ) {
02056               opc->osid = slap_parse_csn_sid( &op->o_csn );
02057        }
02058        if ( op->o_controls ) {
02059               struct sync_cookie *scook =
02060               op->o_controls[slap_cids.sc_LDAPsync];
02061               if ( scook )
02062                      opc->rsid = scook->sid;
02063        }
02064 
02065        if ( op->o_dont_replicate )
02066               return SLAP_CB_CONTINUE;
02067 
02068        /* If there are active persistent searches, lock this operation.
02069         * See seqmod.c for the locking logic on its own.
02070         */
02071        if ( have_psearches ) {
02072               modtarget *mt, mtdummy;
02073               modinst *mi;
02074 
02075               mi = (modinst *)(opc+1);
02076               mi->mi_op = op;
02077 
02078               /* See if we're already modifying this entry... */
02079               mtdummy.mt_op = op;
02080               ldap_pvt_thread_mutex_lock( &si->si_mods_mutex );
02081               mt = avl_find( si->si_mods, &mtdummy, sp_avl_cmp );
02082               if ( mt ) {
02083                      ldap_pvt_thread_mutex_lock( &mt->mt_mutex );
02084                      if ( mt->mt_mods == NULL ) {
02085                             /* Cannot reuse this mt, as another thread is about
02086                              * to release it in syncprov_op_cleanup.
02087                              */
02088                             ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
02089                             mt = NULL;
02090                      }
02091               }
02092               if ( mt ) {
02093                      ldap_pvt_thread_mutex_unlock( &si->si_mods_mutex );
02094                      mt->mt_tail->mi_next = mi;
02095                      mt->mt_tail = mi;
02096                      /* wait for this op to get to head of list */
02097                      while ( mt->mt_mods != mi ) {
02098                             ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
02099                             /* FIXME: if dynamic config can delete overlays or
02100                              * databases we'll have to check for cleanup here.
02101                              * Currently it's not an issue because there are
02102                              * no dynamic config deletes...
02103                              */
02104                             if ( slapd_shutdown )
02105                                    return SLAPD_ABANDON;
02106 
02107                             if ( !ldap_pvt_thread_pool_pausecheck( &connection_pool ))
02108                                    ldap_pvt_thread_yield();
02109                             ldap_pvt_thread_mutex_lock( &mt->mt_mutex );
02110 
02111                             /* clean up if the caller is giving up */
02112                             if ( op->o_abandon ) {
02113                                    modinst *m2;
02114                                    for ( m2 = mt->mt_mods; m2 && m2->mi_next != mi;
02115                                           m2 = m2->mi_next );
02116                                    if ( m2 ) {
02117                                           m2->mi_next = mi->mi_next;
02118                                           if ( mt->mt_tail == mi ) mt->mt_tail = m2;
02119                                    }
02120                                    op->o_tmpfree( cb, op->o_tmpmemctx );
02121                                    ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
02122                                    return SLAPD_ABANDON;
02123                             }
02124                      }
02125                      ldap_pvt_thread_mutex_unlock( &mt->mt_mutex );
02126               } else {
02127                      /* Record that we're modifying this entry now */
02128                      mt = ch_malloc( sizeof(modtarget) );
02129                      mt->mt_mods = mi;
02130                      mt->mt_tail = mi;
02131                      mt->mt_op = mi->mi_op;
02132                      ldap_pvt_thread_mutex_init( &mt->mt_mutex );
02133                      avl_insert( &si->si_mods, mt, sp_avl_cmp, avl_dup_error );
02134                      ldap_pvt_thread_mutex_unlock( &si->si_mods_mutex );
02135               }
02136               opc->smt = mt;
02137        }
02138 
02139        if (( have_psearches || si->si_logs ) && op->o_tag != LDAP_REQ_ADD )
02140               syncprov_matchops( op, opc, 1 );
02141 
02142        return SLAP_CB_CONTINUE;
02143 }
02144 
02145 static int
02146 syncprov_op_extended( Operation *op, SlapReply *rs )
02147 {
02148        if ( exop_is_write( op ))
02149               return syncprov_op_mod( op, rs );
02150 
02151        return SLAP_CB_CONTINUE;
02152 }
02153 
02154 typedef struct searchstate {
02155        slap_overinst *ss_on;
02156        syncops *ss_so;
02157        BerVarray ss_ctxcsn;
02158        int *ss_sids;
02159        int ss_numcsns;
02160 #define       SS_PRESENT    0x01
02161 #define       SS_CHANGED    0x02
02162        int ss_flags;
02163 } searchstate;
02164 
02165 static int
02166 syncprov_search_cleanup( Operation *op, SlapReply *rs )
02167 {
02168        if ( rs->sr_ctrls ) {
02169               op->o_tmpfree( rs->sr_ctrls[0], op->o_tmpmemctx );
02170               op->o_tmpfree( rs->sr_ctrls, op->o_tmpmemctx );
02171               rs->sr_ctrls = NULL;
02172        }
02173        return 0;
02174 }
02175 
02176 typedef struct SyncOperationBuffer {
02177        Operation            sob_op;
02178        Opheader             sob_hdr;
02179        OpExtra                     sob_oe;
02180        AttributeName sob_extra;    /* not always present */
02181        /* Further data allocated here */
02182 } SyncOperationBuffer;
02183 
02184 static void
02185 syncprov_detach_op( Operation *op, syncops *so, slap_overinst *on )
02186 {
02187        SyncOperationBuffer *sopbuf2;
02188        Operation *op2;
02189        int i, alen = 0;
02190        size_t size;
02191        char *ptr;
02192        GroupAssertion *g1, *g2;
02193 
02194        /* count the search attrs */
02195        for (i=0; op->ors_attrs && !BER_BVISNULL( &op->ors_attrs[i].an_name ); i++) {
02196               alen += op->ors_attrs[i].an_name.bv_len + 1;
02197        }
02198        /* Make a new copy of the operation */
02199        size = offsetof( SyncOperationBuffer, sob_extra ) +
02200               (i ? ( (i+1) * sizeof(AttributeName) + alen) : 0) +
02201               op->o_req_dn.bv_len + 1 +
02202               op->o_req_ndn.bv_len + 1 +
02203               op->o_ndn.bv_len + 1 +
02204               so->s_filterstr.bv_len + 1;
02205        sopbuf2 = ch_calloc( 1, size );
02206        op2 = &sopbuf2->sob_op;
02207        op2->o_hdr = &sopbuf2->sob_hdr;
02208        LDAP_SLIST_FIRST(&op2->o_extra) = &sopbuf2->sob_oe;
02209 
02210        /* Copy the fields we care about explicitly, leave the rest alone */
02211        *op2->o_hdr = *op->o_hdr;
02212        op2->o_tag = op->o_tag;
02213        op2->o_time = op->o_time;
02214        op2->o_bd = on->on_info->oi_origdb;
02215        op2->o_request = op->o_request;
02216        op2->o_managedsait = op->o_managedsait;
02217        LDAP_SLIST_FIRST(&op2->o_extra)->oe_key = on;
02218        LDAP_SLIST_NEXT(LDAP_SLIST_FIRST(&op2->o_extra), oe_next) = NULL;
02219 
02220        ptr = (char *) sopbuf2 + offsetof( SyncOperationBuffer, sob_extra );
02221        if ( i ) {
02222               op2->ors_attrs = (AttributeName *) ptr;
02223               ptr = (char *) &op2->ors_attrs[i+1];
02224               for (i=0; !BER_BVISNULL( &op->ors_attrs[i].an_name ); i++) {
02225                      op2->ors_attrs[i] = op->ors_attrs[i];
02226                      op2->ors_attrs[i].an_name.bv_val = ptr;
02227                      ptr = lutil_strcopy( ptr, op->ors_attrs[i].an_name.bv_val ) + 1;
02228               }
02229               BER_BVZERO( &op2->ors_attrs[i].an_name );
02230        }
02231 
02232        op2->o_authz = op->o_authz;
02233        op2->o_ndn.bv_val = ptr;
02234        ptr = lutil_strcopy(ptr, op->o_ndn.bv_val) + 1;
02235        op2->o_dn = op2->o_ndn;
02236        op2->o_req_dn.bv_len = op->o_req_dn.bv_len;
02237        op2->o_req_dn.bv_val = ptr;
02238        ptr = lutil_strcopy(ptr, op->o_req_dn.bv_val) + 1;
02239        op2->o_req_ndn.bv_len = op->o_req_ndn.bv_len;
02240        op2->o_req_ndn.bv_val = ptr;
02241        ptr = lutil_strcopy(ptr, op->o_req_ndn.bv_val) + 1;
02242        op2->ors_filterstr.bv_val = ptr;
02243        strcpy( ptr, so->s_filterstr.bv_val );
02244        op2->ors_filterstr.bv_len = so->s_filterstr.bv_len;
02245 
02246        /* Skip the AND/GE clause that we stuck on in front */
02247        if ( so->s_flags & PS_FIX_FILTER ) {
02248               op2->ors_filter = op->ors_filter->f_and->f_next;
02249               so->s_flags ^= PS_FIX_FILTER;
02250        } else {
02251               op2->ors_filter = op->ors_filter;
02252        }
02253        op2->ors_filter = filter_dup( op2->ors_filter, NULL );
02254        so->s_op = op2;
02255 
02256        /* Copy any cached group ACLs individually */
02257        op2->o_groups = NULL;
02258        for ( g1=op->o_groups; g1; g1=g1->ga_next ) {
02259               g2 = ch_malloc( sizeof(GroupAssertion) + g1->ga_len );
02260               *g2 = *g1;
02261               strcpy( g2->ga_ndn, g1->ga_ndn );
02262               g2->ga_next = op2->o_groups;
02263               op2->o_groups = g2;
02264        }
02265        /* Don't allow any further group caching */
02266        op2->o_do_not_cache = 1;
02267 
02268        /* Add op2 to conn so abandon will find us */
02269        op->o_conn->c_n_ops_executing++;
02270        op->o_conn->c_n_ops_completed--;
02271        LDAP_STAILQ_INSERT_TAIL( &op->o_conn->c_ops, op2, o_next );
02272        so->s_flags |= PS_IS_DETACHED;
02273 
02274        /* Prevent anyone else from trying to send a result for this op */
02275        op->o_abandon = 1;
02276 }
02277 
02278 static int
02279 syncprov_search_response( Operation *op, SlapReply *rs )
02280 {
02281        searchstate *ss = op->o_callback->sc_private;
02282        slap_overinst *on = ss->ss_on;
02283        syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
02284        sync_control *srs = op->o_controls[slap_cids.sc_LDAPsync];
02285 
02286        if ( rs->sr_type == REP_SEARCH || rs->sr_type == REP_SEARCHREF ) {
02287               Attribute *a;
02288               /* If we got a referral without a referral object, there's
02289                * something missing that we cannot replicate. Just ignore it.
02290                * The consumer will abort because we didn't send the expected
02291                * control.
02292                */
02293               if ( !rs->sr_entry ) {
02294                      assert( rs->sr_entry != NULL );
02295                      Debug( LDAP_DEBUG_ANY, "bogus referral in context\n",0,0,0 );
02296                      return SLAP_CB_CONTINUE;
02297               }
02298               a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_entryCSN );
02299               if ( a == NULL && rs->sr_operational_attrs != NULL ) {
02300                      a = attr_find( rs->sr_operational_attrs, slap_schema.si_ad_entryCSN );
02301               }
02302               if ( a ) {
02303                      int i, sid;
02304                      sid = slap_parse_csn_sid( &a->a_nvals[0] );
02305 
02306                      /* Don't send changed entries back to the originator */
02307                      if ( sid == srs->sr_state.sid && srs->sr_state.numcsns ) {
02308                             Debug( LDAP_DEBUG_SYNC,
02309                                    "Entry %s changed by peer, ignored\n",
02310                                    rs->sr_entry->e_name.bv_val, 0, 0 );
02311                             return LDAP_SUCCESS;
02312                      }
02313 
02314                      /* If not a persistent search */
02315                      if ( !ss->ss_so ) {
02316                             /* Make sure entry is less than the snapshot'd contextCSN */
02317                             for ( i=0; i<ss->ss_numcsns; i++ ) {
02318                                    if ( sid == ss->ss_sids[i] && ber_bvcmp( &a->a_nvals[0],
02319                                           &ss->ss_ctxcsn[i] ) > 0 ) {
02320                                           Debug( LDAP_DEBUG_SYNC,
02321                                                  "Entry %s CSN %s greater than snapshot %s\n",
02322                                                  rs->sr_entry->e_name.bv_val,
02323                                                  a->a_nvals[0].bv_val,
02324                                                  ss->ss_ctxcsn[i].bv_val );
02325                                           return LDAP_SUCCESS;
02326                                    }
02327                             }
02328                      }
02329 
02330                      /* Don't send old entries twice */
02331                      if ( srs->sr_state.ctxcsn ) {
02332                             for ( i=0; i<srs->sr_state.numcsns; i++ ) {
02333                                    if ( sid == srs->sr_state.sids[i] &&
02334                                           ber_bvcmp( &a->a_nvals[0],
02335                                                  &srs->sr_state.ctxcsn[i] )<= 0 ) {
02336                                           Debug( LDAP_DEBUG_SYNC,
02337                                                  "Entry %s CSN %s older or equal to ctx %s\n",
02338                                                  rs->sr_entry->e_name.bv_val,
02339                                                  a->a_nvals[0].bv_val,
02340                                                  srs->sr_state.ctxcsn[i].bv_val );
02341                                           return LDAP_SUCCESS;
02342                                    }
02343                             }
02344                      }
02345               }
02346               rs->sr_ctrls = op->o_tmpalloc( sizeof(LDAPControl *)*2,
02347                      op->o_tmpmemctx );
02348               rs->sr_ctrls[1] = NULL;
02349               rs->sr_flags |= REP_CTRLS_MUSTBEFREED;
02350               /* If we're in delta-sync mode, always send a cookie */
02351               if ( si->si_nopres && si->si_usehint && a ) {
02352                      struct berval cookie;
02353                      slap_compose_sync_cookie( op, &cookie, a->a_nvals, srs->sr_state.rid, slap_serverID ? slap_serverID : -1 );
02354                      rs->sr_err = syncprov_state_ctrl( op, rs, rs->sr_entry,
02355                             LDAP_SYNC_ADD, rs->sr_ctrls, 0, 1, &cookie );
02356               } else {
02357                      rs->sr_err = syncprov_state_ctrl( op, rs, rs->sr_entry,
02358                             LDAP_SYNC_ADD, rs->sr_ctrls, 0, 0, NULL );
02359               }
02360        } else if ( rs->sr_type == REP_RESULT && rs->sr_err == LDAP_SUCCESS ) {
02361               struct berval cookie = BER_BVNULL;
02362 
02363               if ( ( ss->ss_flags & SS_CHANGED ) &&
02364                      ss->ss_ctxcsn && !BER_BVISNULL( &ss->ss_ctxcsn[0] )) {
02365                      slap_compose_sync_cookie( op, &cookie, ss->ss_ctxcsn,
02366                             srs->sr_state.rid, slap_serverID ? slap_serverID : -1 );
02367 
02368                      Debug( LDAP_DEBUG_SYNC, "syncprov_search_response: cookie=%s\n", cookie.bv_val, 0, 0 );
02369               }
02370 
02371               /* Is this a regular refresh?
02372                * Note: refresh never gets here if there were no changes
02373                */
02374               if ( !ss->ss_so ) {
02375                      rs->sr_ctrls = op->o_tmpalloc( sizeof(LDAPControl *)*2,
02376                             op->o_tmpmemctx );
02377                      rs->sr_ctrls[1] = NULL;
02378                      rs->sr_err = syncprov_done_ctrl( op, rs, rs->sr_ctrls,
02379                             0, 1, &cookie, ( ss->ss_flags & SS_PRESENT ) ?  LDAP_SYNC_REFRESH_PRESENTS :
02380                                    LDAP_SYNC_REFRESH_DELETES );
02381                      op->o_tmpfree( cookie.bv_val, op->o_tmpmemctx );
02382               } else {
02383               /* It's RefreshAndPersist, transition to Persist phase */
02384                      syncprov_sendinfo( op, rs, ( ss->ss_flags & SS_PRESENT ) ?
02385                             LDAP_TAG_SYNC_REFRESH_PRESENT : LDAP_TAG_SYNC_REFRESH_DELETE,
02386                             ( ss->ss_flags & SS_CHANGED ) ? &cookie : NULL,
02387                             1, NULL, 0 );
02388                      if ( !BER_BVISNULL( &cookie ))
02389                             op->o_tmpfree( cookie.bv_val, op->o_tmpmemctx );
02390 
02391                      /* Detach this Op from frontend control */
02392                      ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
02393 
02394                      /* But not if this connection was closed along the way */
02395                      if ( op->o_abandon ) {
02396                             ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
02397                             /* syncprov_ab_cleanup will free this syncop */
02398                             return SLAPD_ABANDON;
02399 
02400                      } else {
02401                             ldap_pvt_thread_mutex_lock( &ss->ss_so->s_mutex );
02402                             /* Turn off the refreshing flag */
02403                             ss->ss_so->s_flags ^= PS_IS_REFRESHING;
02404 
02405                             syncprov_detach_op( op, ss->ss_so, on );
02406 
02407                             ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
02408 
02409                             /* If there are queued responses, fire them off */
02410                             if ( ss->ss_so->s_res )
02411                                    syncprov_qstart( ss->ss_so );
02412                             ldap_pvt_thread_mutex_unlock( &ss->ss_so->s_mutex );
02413                      }
02414 
02415                      return LDAP_SUCCESS;
02416               }
02417        }
02418 
02419        return SLAP_CB_CONTINUE;
02420 }
02421 
02422 static int
02423 syncprov_op_search( Operation *op, SlapReply *rs )
02424 {
02425        slap_overinst        *on = (slap_overinst *)op->o_bd->bd_info;
02426        syncprov_info_t             *si = (syncprov_info_t *)on->on_bi.bi_private;
02427        slap_callback *cb;
02428        int gotstate = 0, changed = 0, do_present = 0;
02429        syncops *sop = NULL;
02430        searchstate *ss;
02431        sync_control *srs;
02432        BerVarray ctxcsn;
02433        int i, *sids, numcsns;
02434        struct berval mincsn, maxcsn;
02435        int minsid, maxsid;
02436        int dirty = 0;
02437 
02438        if ( !(op->o_sync_mode & SLAP_SYNC_REFRESH) ) return SLAP_CB_CONTINUE;
02439 
02440        if ( op->ors_deref & LDAP_DEREF_SEARCHING ) {
02441               send_ldap_error( op, rs, LDAP_PROTOCOL_ERROR, "illegal value for derefAliases" );
02442               return rs->sr_err;
02443        }
02444 
02445        srs = op->o_controls[slap_cids.sc_LDAPsync];
02446 
02447        /* If this is a persistent search, set it up right away */
02448        if ( op->o_sync_mode & SLAP_SYNC_PERSIST ) {
02449               syncops so = {0};
02450               fbase_cookie fc;
02451               opcookie opc;
02452               slap_callback sc;
02453 
02454               fc.fss = &so;
02455               fc.fbase = 0;
02456               so.s_eid = NOID;
02457               so.s_op = op;
02458               so.s_flags = PS_IS_REFRESHING | PS_FIND_BASE;
02459               /* syncprov_findbase expects to be called as a callback... */
02460               sc.sc_private = &opc;
02461               opc.son = on;
02462               ldap_pvt_thread_mutex_init( &so.s_mutex );
02463               cb = op->o_callback;
02464               op->o_callback = &sc;
02465               rs->sr_err = syncprov_findbase( op, &fc );
02466               op->o_callback = cb;
02467               ldap_pvt_thread_mutex_destroy( &so.s_mutex );
02468 
02469               if ( rs->sr_err != LDAP_SUCCESS ) {
02470                      send_ldap_result( op, rs );
02471                      return rs->sr_err;
02472               }
02473               sop = ch_malloc( sizeof( syncops ));
02474               *sop = so;
02475               ldap_pvt_thread_mutex_init( &sop->s_mutex );
02476               sop->s_rid = srs->sr_state.rid;
02477               sop->s_sid = srs->sr_state.sid;
02478               /* set refcount=2 to prevent being freed out from under us
02479                * by abandons that occur while we're running here
02480                */
02481               sop->s_inuse = 2;
02482 
02483               ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
02484               while ( si->si_active ) {
02485                      /* Wait for active mods to finish before proceeding, as they
02486                       * may already have inspected the si_ops list looking for
02487                       * consumers to replicate the change to.  Using the log
02488                       * doesn't help, as we may finish playing it before the
02489                       * active mods gets added to it.
02490                       */
02491                      ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
02492                      if ( slapd_shutdown )
02493                             return SLAPD_ABANDON;
02494                      if ( !ldap_pvt_thread_pool_pausecheck( &connection_pool ))
02495                             ldap_pvt_thread_yield();
02496                      ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
02497               }
02498               sop->s_next = si->si_ops;
02499               si->si_ops = sop;
02500               ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
02501        }
02502 
02503        /* snapshot the ctxcsn */
02504        ldap_pvt_thread_rdwr_rlock( &si->si_csn_rwlock );
02505        numcsns = si->si_numcsns;
02506        if ( numcsns ) {
02507               ber_bvarray_dup_x( &ctxcsn, si->si_ctxcsn, op->o_tmpmemctx );
02508               sids = op->o_tmpalloc( numcsns * sizeof(int), op->o_tmpmemctx );
02509               for ( i=0; i<numcsns; i++ )
02510                      sids[i] = si->si_sids[i];
02511        } else {
02512               ctxcsn = NULL;
02513               sids = NULL;
02514        }
02515        dirty = si->si_dirty;
02516        ldap_pvt_thread_rdwr_runlock( &si->si_csn_rwlock );
02517        
02518        /* If we have a cookie, handle the PRESENT lookups */
02519        if ( srs->sr_state.ctxcsn ) {
02520               sessionlog *sl;
02521               int i, j;
02522 
02523               /* If we don't have any CSN of our own yet, pretend nothing
02524                * has changed.
02525                */
02526               if ( !numcsns )
02527                      goto no_change;
02528 
02529               if ( !si->si_nopres )
02530                      do_present = SS_PRESENT;
02531 
02532               /* If there are SIDs we don't recognize in the cookie, drop them */
02533               for (i=0; i<srs->sr_state.numcsns; ) {
02534                      for (j=i; j<numcsns; j++) {
02535                             if ( srs->sr_state.sids[i] <= sids[j] ) {
02536                                    break;
02537                             }
02538                      }
02539                      /* not found */
02540                      if ( j == numcsns || srs->sr_state.sids[i] != sids[j] ) {
02541                             char *tmp = srs->sr_state.ctxcsn[i].bv_val;
02542                             srs->sr_state.numcsns--;
02543                             for ( j=i; j<srs->sr_state.numcsns; j++ ) {
02544                                    srs->sr_state.ctxcsn[j] = srs->sr_state.ctxcsn[j+1];
02545                                    srs->sr_state.sids[j] = srs->sr_state.sids[j+1];
02546                             }
02547                             srs->sr_state.ctxcsn[j].bv_val = tmp;
02548                             srs->sr_state.ctxcsn[j].bv_len = 0;
02549                             continue;
02550                      }
02551                      i++;
02552               }
02553 
02554               if (srs->sr_state.numcsns != numcsns) {
02555                      /* consumer doesn't have the right number of CSNs */
02556                      changed = SS_CHANGED;
02557                      if ( srs->sr_state.ctxcsn ) {
02558                             ber_bvarray_free_x( srs->sr_state.ctxcsn, op->o_tmpmemctx );
02559                             srs->sr_state.ctxcsn = NULL;
02560                      }
02561                      if ( srs->sr_state.sids ) {
02562                             slap_sl_free( srs->sr_state.sids, op->o_tmpmemctx );
02563                             srs->sr_state.sids = NULL;
02564                      }
02565                      srs->sr_state.numcsns = 0;
02566                      goto shortcut;
02567               }
02568 
02569               /* Find the smallest CSN which differs from contextCSN */
02570               mincsn.bv_len = 0;
02571               maxcsn.bv_len = 0;
02572               for ( i=0,j=0; i<srs->sr_state.numcsns; i++ ) {
02573                      int newer;
02574                      while ( srs->sr_state.sids[i] != sids[j] ) j++;
02575                      if ( BER_BVISEMPTY( &maxcsn ) || ber_bvcmp( &maxcsn,
02576                             &srs->sr_state.ctxcsn[i] ) < 0 ) {
02577                             maxcsn = srs->sr_state.ctxcsn[i];
02578                             maxsid = sids[j];
02579                      }
02580                      newer = ber_bvcmp( &srs->sr_state.ctxcsn[i], &ctxcsn[j] );
02581                      /* If our state is newer, tell consumer about changes */
02582                      if ( newer < 0) {
02583                             changed = SS_CHANGED;
02584                             if ( BER_BVISEMPTY( &mincsn ) || ber_bvcmp( &mincsn,
02585                                    &srs->sr_state.ctxcsn[i] ) > 0 ) {
02586                                    mincsn = srs->sr_state.ctxcsn[i];
02587                                    minsid = sids[j];
02588                             }
02589                      } else if ( newer > 0 && sids[j] == slap_serverID ) {
02590                      /* our state is older, complain to consumer */
02591                             rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
02592                             rs->sr_text = "consumer state is newer than provider!";
02593 bailout:
02594                             if ( sop ) {
02595                                    syncops **sp = &si->si_ops;
02596 
02597                                    ldap_pvt_thread_mutex_lock( &si->si_ops_mutex );
02598                                    while ( *sp != sop )
02599                                           sp = &(*sp)->s_next;
02600                                    *sp = sop->s_next;
02601                                    ldap_pvt_thread_mutex_unlock( &si->si_ops_mutex );
02602                                    ch_free( sop );
02603                             }
02604                             rs->sr_ctrls = NULL;
02605                             send_ldap_result( op, rs );
02606                             return rs->sr_err;
02607                      }
02608               }
02609               if ( BER_BVISEMPTY( &mincsn )) {
02610                      mincsn = maxcsn;
02611                      minsid = maxsid;
02612               }
02613 
02614               /* If nothing has changed, shortcut it */
02615               if ( !changed && !dirty ) {
02616                      do_present = 0;
02617 no_change:           if ( !(op->o_sync_mode & SLAP_SYNC_PERSIST) ) {
02618                             LDAPControl   *ctrls[2];
02619 
02620                             ctrls[0] = NULL;
02621                             ctrls[1] = NULL;
02622                             syncprov_done_ctrl( op, rs, ctrls, 0, 0,
02623                                    NULL, LDAP_SYNC_REFRESH_DELETES );
02624                             rs->sr_ctrls = ctrls;
02625                             rs->sr_err = LDAP_SUCCESS;
02626                             send_ldap_result( op, rs );
02627                             rs->sr_ctrls = NULL;
02628                             return rs->sr_err;
02629                      }
02630                      goto shortcut;
02631               }
02632 
02633               /* Do we have a sessionlog for this search? */
02634               sl=si->si_logs;
02635               if ( sl ) {
02636                      int do_play = 0;
02637                      ldap_pvt_thread_mutex_lock( &sl->sl_mutex );
02638                      /* Are there any log entries, and is the consumer state
02639                       * present in the session log?
02640                       */
02641                      if ( sl->sl_num > 0 ) {
02642                             int i;
02643                             for ( i=0; i<sl->sl_numcsns; i++ ) {
02644                                    /* SID not present == new enough */
02645                                    if ( minsid < sl->sl_sids[i] ) {
02646                                           do_play = 1;
02647                                           break;
02648                                    }
02649                                    /* SID present */
02650                                    if ( minsid == sl->sl_sids[i] ) {
02651                                           /* new enough? */
02652                                           if ( ber_bvcmp( &mincsn, &sl->sl_mincsn[i] ) >= 0 )
02653                                                  do_play = 1;
02654                                           break;
02655                                    }
02656                             }
02657                             /* SID not present == new enough */
02658                             if ( i == sl->sl_numcsns )
02659                                    do_play = 1;
02660                      }
02661                      if ( do_play ) {
02662                             do_present = 0;
02663                             /* mutex is unlocked in playlog */
02664                             syncprov_playlog( op, rs, sl, srs, ctxcsn, numcsns, sids );
02665                      } else {
02666                             ldap_pvt_thread_mutex_unlock( &sl->sl_mutex );
02667                      }
02668               }
02669               /* Is the CSN still present in the database? */
02670               if ( syncprov_findcsn( op, FIND_CSN, &mincsn ) != LDAP_SUCCESS ) {
02671                      /* No, so a reload is required */
02672                      /* the 2.2 consumer doesn't send this hint */
02673                      if ( si->si_usehint && srs->sr_rhint == 0 ) {
02674                             if ( ctxcsn )
02675                                    ber_bvarray_free_x( ctxcsn, op->o_tmpmemctx );
02676                             if ( sids )
02677                                    op->o_tmpfree( sids, op->o_tmpmemctx );
02678                             rs->sr_err = LDAP_SYNC_REFRESH_REQUIRED;
02679                             rs->sr_text = "sync cookie is stale";
02680                             goto bailout;
02681                      }
02682                      if ( srs->sr_state.ctxcsn ) {
02683                             ber_bvarray_free_x( srs->sr_state.ctxcsn, op->o_tmpmemctx );
02684                             srs->sr_state.ctxcsn = NULL;
02685                      }
02686                      if ( srs->sr_state.sids ) {
02687                             slap_sl_free( srs->sr_state.sids, op->o_tmpmemctx );
02688                             srs->sr_state.sids = NULL;
02689                      }
02690                      srs->sr_state.numcsns = 0;
02691               } else {
02692                      gotstate = 1;
02693                      /* If changed and doing Present lookup, send Present UUIDs */
02694                      if ( do_present && syncprov_findcsn( op, FIND_PRESENT, 0 ) !=
02695                             LDAP_SUCCESS ) {
02696                             if ( ctxcsn )
02697                                    ber_bvarray_free_x( ctxcsn, op->o_tmpmemctx );
02698                             if ( sids )
02699                                    op->o_tmpfree( sids, op->o_tmpmemctx );
02700                             goto bailout;
02701                      }
02702               }
02703        } else {
02704               /* No consumer state, assume something has changed */
02705               changed = SS_CHANGED;
02706        }
02707 
02708 shortcut:
02709        /* Append CSN range to search filter, save original filter
02710         * for persistent search evaluation
02711         */
02712        if ( sop ) {
02713               ldap_pvt_thread_mutex_lock( &sop->s_mutex );
02714               sop->s_filterstr = op->ors_filterstr;
02715               /* correct the refcount that was set to 2 before */
02716               sop->s_inuse--;
02717        }
02718 
02719        /* If something changed, find the changes */
02720        if ( gotstate && ( changed || dirty ) ) {
02721               Filter *fand, *fava;
02722 
02723               fand = op->o_tmpalloc( sizeof(Filter), op->o_tmpmemctx );
02724               fand->f_choice = LDAP_FILTER_AND;
02725               fand->f_next = NULL;
02726               fava = op->o_tmpalloc( sizeof(Filter), op->o_tmpmemctx );
02727               fand->f_and = fava;
02728               fava->f_choice = LDAP_FILTER_GE;
02729               fava->f_ava = op->o_tmpalloc( sizeof(AttributeAssertion), op->o_tmpmemctx );
02730               fava->f_ava->aa_desc = slap_schema.si_ad_entryCSN;
02731 #ifdef LDAP_COMP_MATCH
02732               fava->f_ava->aa_cf = NULL;
02733 #endif
02734               ber_dupbv_x( &fava->f_ava->aa_value, &mincsn, op->o_tmpmemctx );
02735               fava->f_next = op->ors_filter;
02736               op->ors_filter = fand;
02737               filter2bv_x( op, op->ors_filter, &op->ors_filterstr );
02738               if ( sop ) {
02739                      sop->s_flags |= PS_FIX_FILTER;
02740               }
02741        }
02742        if ( sop ) {
02743               ldap_pvt_thread_mutex_unlock( &sop->s_mutex );
02744        }
02745 
02746        /* Let our callback add needed info to returned entries */
02747        cb = op->o_tmpcalloc(1, sizeof(slap_callback)+sizeof(searchstate), op->o_tmpmemctx);
02748        ss = (searchstate *)(cb+1);
02749        ss->ss_on = on;
02750        ss->ss_so = sop;
02751        ss->ss_flags = do_present | changed;
02752        ss->ss_ctxcsn = ctxcsn;
02753        ss->ss_numcsns = numcsns;
02754        ss->ss_sids = sids;
02755        cb->sc_response = syncprov_search_response;
02756        cb->sc_cleanup = syncprov_search_cleanup;
02757        cb->sc_private = ss;
02758        cb->sc_next = op->o_callback;
02759        op->o_callback = cb;
02760 
02761        /* If this is a persistent search and no changes were reported during
02762         * the refresh phase, just invoke the response callback to transition
02763         * us into persist phase
02764         */
02765        if ( !changed && !dirty ) {
02766               rs->sr_err = LDAP_SUCCESS;
02767               rs->sr_nentries = 0;
02768               send_ldap_result( op, rs );
02769               return rs->sr_err;
02770        }
02771        return SLAP_CB_CONTINUE;
02772 }
02773 
02774 static int
02775 syncprov_operational(
02776        Operation *op,
02777        SlapReply *rs )
02778 {
02779        slap_overinst        *on = (slap_overinst *)op->o_bd->bd_info;
02780        syncprov_info_t             *si = (syncprov_info_t *)on->on_bi.bi_private;
02781 
02782        /* This prevents generating unnecessarily; frontend will strip
02783         * any statically stored copy.
02784         */
02785        if ( op->o_sync != SLAP_CONTROL_NONE )
02786               return SLAP_CB_CONTINUE;
02787 
02788        if ( rs->sr_entry &&
02789               dn_match( &rs->sr_entry->e_nname, &si->si_contextdn )) {
02790 
02791               if ( SLAP_OPATTRS( rs->sr_attr_flags ) ||
02792                      ad_inlist( slap_schema.si_ad_contextCSN, rs->sr_attrs )) {
02793                      Attribute *a, **ap = NULL;
02794 
02795                      for ( a=rs->sr_entry->e_attrs; a; a=a->a_next ) {
02796                             if ( a->a_desc == slap_schema.si_ad_contextCSN )
02797                                    break;
02798                      }
02799 
02800                      ldap_pvt_thread_rdwr_rlock( &si->si_csn_rwlock );
02801                      if ( si->si_ctxcsn ) {
02802                             if ( !a ) {
02803                                    for ( ap = &rs->sr_operational_attrs; *ap;
02804                                           ap=&(*ap)->a_next );
02805 
02806                                    a = attr_alloc( slap_schema.si_ad_contextCSN );
02807                                    *ap = a;
02808                             }
02809 
02810                             if ( !ap ) {
02811                                    if ( rs_entry2modifiable( op, rs, on )) {
02812                                           a = attr_find( rs->sr_entry->e_attrs,
02813                                                  slap_schema.si_ad_contextCSN );
02814                                    }
02815                                    if ( a->a_nvals != a->a_vals ) {
02816                                           ber_bvarray_free( a->a_nvals );
02817                                    }
02818                                    a->a_nvals = NULL;
02819                                    ber_bvarray_free( a->a_vals );
02820                                    a->a_vals = NULL;
02821                                    a->a_numvals = 0;
02822                             }
02823                             attr_valadd( a, si->si_ctxcsn, si->si_ctxcsn, si->si_numcsns );
02824                      }
02825                      ldap_pvt_thread_rdwr_runlock( &si->si_csn_rwlock );
02826               }
02827        }
02828        return SLAP_CB_CONTINUE;
02829 }
02830 
02831 enum {
02832        SP_CHKPT = 1,
02833        SP_SESSL,
02834        SP_NOPRES,
02835        SP_USEHINT
02836 };
02837 
02838 static ConfigDriver sp_cf_gen;
02839 
02840 static ConfigTable spcfg[] = {
02841        { "syncprov-checkpoint", "ops> <minutes", 3, 3, 0, ARG_MAGIC|SP_CHKPT,
02842               sp_cf_gen, "( OLcfgOvAt:1.1 NAME 'olcSpCheckpoint' "
02843                      "DESC 'ContextCSN checkpoint interval in ops and minutes' "
02844                      "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
02845        { "syncprov-sessionlog", "ops", 2, 2, 0, ARG_INT|ARG_MAGIC|SP_SESSL,
02846               sp_cf_gen, "( OLcfgOvAt:1.2 NAME 'olcSpSessionlog' "
02847                      "DESC 'Session log size in ops' "
02848                      "SYNTAX OMsInteger SINGLE-VALUE )", NULL, NULL },
02849        { "syncprov-nopresent", NULL, 2, 2, 0, ARG_ON_OFF|ARG_MAGIC|SP_NOPRES,
02850               sp_cf_gen, "( OLcfgOvAt:1.3 NAME 'olcSpNoPresent' "
02851                      "DESC 'Omit Present phase processing' "
02852                      "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
02853        { "syncprov-reloadhint", NULL, 2, 2, 0, ARG_ON_OFF|ARG_MAGIC|SP_USEHINT,
02854               sp_cf_gen, "( OLcfgOvAt:1.4 NAME 'olcSpReloadHint' "
02855                      "DESC 'Observe Reload Hint in Request control' "
02856                      "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
02857        { NULL, NULL, 0, 0, 0, ARG_IGNORED }
02858 };
02859 
02860 static ConfigOCs spocs[] = {
02861        { "( OLcfgOvOc:1.1 "
02862               "NAME 'olcSyncProvConfig' "
02863               "DESC 'SyncRepl Provider configuration' "
02864               "SUP olcOverlayConfig "
02865               "MAY ( olcSpCheckpoint "
02866                      "$ olcSpSessionlog "
02867                      "$ olcSpNoPresent "
02868                      "$ olcSpReloadHint "
02869               ") )",
02870                      Cft_Overlay, spcfg },
02871        { NULL, 0, NULL }
02872 };
02873 
02874 static int
02875 sp_cf_gen(ConfigArgs *c)
02876 {
02877        slap_overinst        *on = (slap_overinst *)c->bi;
02878        syncprov_info_t             *si = (syncprov_info_t *)on->on_bi.bi_private;
02879        int rc = 0;
02880 
02881        if ( c->op == SLAP_CONFIG_EMIT ) {
02882               switch ( c->type ) {
02883               case SP_CHKPT:
02884                      if ( si->si_chkops || si->si_chktime ) {
02885                             struct berval bv;
02886                             /* we assume si_chktime is a multiple of 60
02887                              * because the parsed value was originally
02888                              * multiplied by 60 */
02889                             bv.bv_len = snprintf( c->cr_msg, sizeof( c->cr_msg ),
02890                                    "%d %d", si->si_chkops, si->si_chktime/60 );
02891                             if ( bv.bv_len >= sizeof( c->cr_msg ) ) {
02892                                    rc = 1;
02893                             } else {
02894                                    bv.bv_val = c->cr_msg;
02895                                    value_add_one( &c->rvalue_vals, &bv );
02896                             }
02897                      } else {
02898                             rc = 1;
02899                      }
02900                      break;
02901               case SP_SESSL:
02902                      if ( si->si_logs ) {
02903                             c->value_int = si->si_logs->sl_size;
02904                      } else {
02905                             rc = 1;
02906                      }
02907                      break;
02908               case SP_NOPRES:
02909                      if ( si->si_nopres ) {
02910                             c->value_int = 1;
02911                      } else {
02912                             rc = 1;
02913                      }
02914                      break;
02915               case SP_USEHINT:
02916                      if ( si->si_usehint ) {
02917                             c->value_int = 1;
02918                      } else {
02919                             rc = 1;
02920                      }
02921                      break;
02922               }
02923               return rc;
02924        } else if ( c->op == LDAP_MOD_DELETE ) {
02925               switch ( c->type ) {
02926               case SP_CHKPT:
02927                      si->si_chkops = 0;
02928                      si->si_chktime = 0;
02929                      break;
02930               case SP_SESSL:
02931                      if ( si->si_logs )
02932                             si->si_logs->sl_size = 0;
02933                      else
02934                             rc = LDAP_NO_SUCH_ATTRIBUTE;
02935                      break;
02936               case SP_NOPRES:
02937                      if ( si->si_nopres )
02938                             si->si_nopres = 0;
02939                      else
02940                             rc = LDAP_NO_SUCH_ATTRIBUTE;
02941                      break;
02942               case SP_USEHINT:
02943                      if ( si->si_usehint )
02944                             si->si_usehint = 0;
02945                      else
02946                             rc = LDAP_NO_SUCH_ATTRIBUTE;
02947                      break;
02948               }
02949               return rc;
02950        }
02951        switch ( c->type ) {
02952        case SP_CHKPT:
02953               if ( lutil_atoi( &si->si_chkops, c->argv[1] ) != 0 ) {
02954                      snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s unable to parse checkpoint ops # \"%s\"",
02955                             c->argv[0], c->argv[1] );
02956                      Debug( LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE,
02957                             "%s: %s\n", c->log, c->cr_msg, 0 );
02958                      return ARG_BAD_CONF;
02959               }
02960               if ( si->si_chkops <= 0 ) {
02961                      snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s invalid checkpoint ops # \"%d\"",
02962                             c->argv[0], si->si_chkops );
02963                      Debug( LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE,
02964                             "%s: %s\n", c->log, c->cr_msg, 0 );
02965                      return ARG_BAD_CONF;
02966               }
02967               if ( lutil_atoi( &si->si_chktime, c->argv[2] ) != 0 ) {
02968                      snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s unable to parse checkpoint time \"%s\"",
02969                             c->argv[0], c->argv[1] );
02970                      Debug( LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE,
02971                             "%s: %s\n", c->log, c->cr_msg, 0 );
02972                      return ARG_BAD_CONF;
02973               }
02974               if ( si->si_chktime <= 0 ) {
02975                      snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s invalid checkpoint time \"%d\"",
02976                             c->argv[0], si->si_chkops );
02977                      Debug( LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE,
02978                             "%s: %s\n", c->log, c->cr_msg, 0 );
02979                      return ARG_BAD_CONF;
02980               }
02981               si->si_chktime *= 60;
02982               break;
02983        case SP_SESSL: {
02984               sessionlog *sl;
02985               int size = c->value_int;
02986 
02987               if ( size < 0 ) {
02988                      snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s size %d is negative",
02989                             c->argv[0], size );
02990                      Debug( LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE,
02991                             "%s: %s\n", c->log, c->cr_msg, 0 );
02992                      return ARG_BAD_CONF;
02993               }
02994               sl = si->si_logs;
02995               if ( !sl ) {
02996                      sl = ch_malloc( sizeof( sessionlog ));
02997                      sl->sl_mincsn = NULL;
02998                      sl->sl_sids = NULL;
02999                      sl->sl_num = 0;
03000                      sl->sl_numcsns = 0;
03001                      sl->sl_head = sl->sl_tail = NULL;
03002                      ldap_pvt_thread_mutex_init( &sl->sl_mutex );
03003                      si->si_logs = sl;
03004               }
03005               sl->sl_size = size;
03006               }
03007               break;
03008        case SP_NOPRES:
03009               si->si_nopres = c->value_int;
03010               break;
03011        case SP_USEHINT:
03012               si->si_usehint = c->value_int;
03013               break;
03014        }
03015        return rc;
03016 }
03017 
03018 /* ITS#3456 we cannot run this search on the main thread, must use a
03019  * child thread in order to insure we have a big enough stack.
03020  */
03021 static void *
03022 syncprov_db_otask(
03023        void *ptr
03024 )
03025 {
03026        syncprov_findcsn( ptr, FIND_MAXCSN, 0 );
03027        return NULL;
03028 }
03029 
03030 
03031 /* Read any existing contextCSN from the underlying db.
03032  * Then search for any entries newer than that. If no value exists,
03033  * just generate it. Cache whatever result.
03034  */
03035 static int
03036 syncprov_db_open(
03037        BackendDB *be,
03038        ConfigReply *cr
03039 )
03040 {
03041        slap_overinst   *on = (slap_overinst *) be->bd_info;
03042        syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
03043 
03044        Connection conn = { 0 };
03045        OperationBuffer opbuf;
03046        Operation *op;
03047        Entry *e = NULL;
03048        Attribute *a;
03049        int rc;
03050        void *thrctx = NULL;
03051 
03052        if ( !SLAP_LASTMOD( be )) {
03053               Debug( LDAP_DEBUG_ANY,
03054                      "syncprov_db_open: invalid config, lastmod must be enabled\n", 0, 0, 0 );
03055               return -1;
03056        }
03057 
03058        if ( slapMode & SLAP_TOOL_MODE ) {
03059               return 0;
03060        }
03061 
03062        rc = overlay_register_control( be, LDAP_CONTROL_SYNC );
03063        if ( rc ) {
03064               return rc;
03065        }
03066 
03067        thrctx = ldap_pvt_thread_pool_context();
03068        connection_fake_init2( &conn, &opbuf, thrctx, 0 );
03069        op = &opbuf.ob_op;
03070        op->o_bd = be;
03071        op->o_dn = be->be_rootdn;
03072        op->o_ndn = be->be_rootndn;
03073 
03074        if ( SLAP_SYNC_SUBENTRY( be )) {
03075               build_new_dn( &si->si_contextdn, be->be_nsuffix,
03076                      (struct berval *)&slap_ldapsync_cn_bv, NULL );
03077        } else {
03078               si->si_contextdn = be->be_nsuffix[0];
03079        }
03080        rc = overlay_entry_get_ov( op, &si->si_contextdn, NULL,
03081               slap_schema.si_ad_contextCSN, 0, &e, on );
03082 
03083        if ( e ) {
03084               ldap_pvt_thread_t tid;
03085 
03086               a = attr_find( e->e_attrs, slap_schema.si_ad_contextCSN );
03087               if ( a ) {
03088                      ber_bvarray_dup_x( &si->si_ctxcsn, a->a_vals, NULL );
03089                      si->si_numcsns = a->a_numvals;
03090                      si->si_sids = slap_parse_csn_sids( si->si_ctxcsn, a->a_numvals, NULL );
03091                      slap_sort_csn_sids( si->si_ctxcsn, si->si_sids, si->si_numcsns, NULL );
03092               }
03093               overlay_entry_release_ov( op, e, 0, on );
03094               if ( si->si_ctxcsn && !SLAP_DBCLEAN( be )) {
03095                      op->o_tag = LDAP_REQ_SEARCH;
03096                      op->o_req_dn = be->be_suffix[0];
03097                      op->o_req_ndn = be->be_nsuffix[0];
03098                      op->ors_scope = LDAP_SCOPE_SUBTREE;
03099                      ldap_pvt_thread_create( &tid, 0, syncprov_db_otask, op );
03100                      ldap_pvt_thread_join( tid, NULL );
03101               }
03102        }
03103 
03104        /* Didn't find a contextCSN, should we generate one? */
03105        if ( !si->si_ctxcsn ) {
03106               char csnbuf[ LDAP_PVT_CSNSTR_BUFSIZE ];
03107               struct berval csn;
03108 
03109               if ( SLAP_SYNC_SHADOW( op->o_bd )) {
03110               /* If we're also a consumer, then don't generate anything.
03111                * Wait for our provider to send it to us, or for a local
03112                * modify if we have multimaster.
03113                */
03114                      goto out;
03115               }
03116               csn.bv_val = csnbuf;
03117               csn.bv_len = sizeof( csnbuf );
03118               slap_get_csn( op, &csn, 0 );
03119               value_add_one( &si->si_ctxcsn, &csn );
03120               si->si_numcsns = 1;
03121               si->si_sids = ch_malloc( sizeof(int) );
03122               si->si_sids[0] = slap_serverID;
03123 
03124               /* make sure we do a checkpoint on close */
03125               si->si_numops++;
03126        }
03127 
03128        /* Initialize the sessionlog mincsn */
03129        if ( si->si_logs && si->si_numcsns ) {
03130               sessionlog *sl = si->si_logs;
03131               int i;
03132               ber_bvarray_dup_x( &sl->sl_mincsn, si->si_ctxcsn, NULL );
03133               sl->sl_numcsns = si->si_numcsns;
03134               sl->sl_sids = ch_malloc( si->si_numcsns * sizeof(int) );
03135               for ( i=0; i < si->si_numcsns; i++ )
03136                      sl->sl_sids[i] = si->si_sids[i];
03137        }
03138 
03139 out:
03140        op->o_bd->bd_info = (BackendInfo *)on;
03141        return 0;
03142 }
03143 
03144 /* Write the current contextCSN into the underlying db.
03145  */
03146 static int
03147 syncprov_db_close(
03148        BackendDB *be,
03149        ConfigReply *cr
03150 )
03151 {
03152     slap_overinst   *on = (slap_overinst *) be->bd_info;
03153     syncprov_info_t *si = (syncprov_info_t *)on->on_bi.bi_private;
03154 #ifdef SLAP_CONFIG_DELETE
03155        syncops *so, *sonext;
03156 #endif /* SLAP_CONFIG_DELETE */
03157 
03158        if ( slapMode & SLAP_TOOL_MODE ) {
03159               return 0;
03160        }
03161        if ( si->si_numops ) {
03162               Connection conn = {0};
03163               OperationBuffer opbuf;
03164               Operation *op;
03165               void *thrctx;
03166 
03167               thrctx = ldap_pvt_thread_pool_context();
03168               connection_fake_init2( &conn, &opbuf, thrctx, 0 );
03169               op = &opbuf.ob_op;
03170               op->o_bd = be;
03171               op->o_dn = be->be_rootdn;
03172               op->o_ndn = be->be_rootndn;
03173               syncprov_checkpoint( op, on );
03174        }
03175 
03176 #ifdef SLAP_CONFIG_DELETE
03177        if ( !slapd_shutdown ) {
03178               for ( so=si->si_ops, sonext=so;  so; so=sonext  ) {
03179                      SlapReply rs = {REP_RESULT};
03180                      rs.sr_err = LDAP_UNAVAILABLE;
03181                      send_ldap_result( so->s_op, &rs );
03182                      sonext=so->s_next;
03183                      syncprov_drop_psearch( so, 0);
03184               }
03185               si->si_ops=NULL;
03186        }
03187        overlay_unregister_control( be, LDAP_CONTROL_SYNC );
03188 #endif /* SLAP_CONFIG_DELETE */
03189 
03190     return 0;
03191 }
03192 
03193 static int
03194 syncprov_db_init(
03195        BackendDB *be,
03196        ConfigReply *cr
03197 )
03198 {
03199        slap_overinst *on = (slap_overinst *)be->bd_info;
03200        syncprov_info_t      *si;
03201 
03202        if ( SLAP_ISGLOBALOVERLAY( be ) ) {
03203               Debug( LDAP_DEBUG_ANY,
03204                      "syncprov must be instantiated within a database.\n",
03205                      0, 0, 0 );
03206               return 1;
03207        }
03208 
03209        si = ch_calloc(1, sizeof(syncprov_info_t));
03210        on->on_bi.bi_private = si;
03211        ldap_pvt_thread_rdwr_init( &si->si_csn_rwlock );
03212        ldap_pvt_thread_mutex_init( &si->si_ops_mutex );
03213        ldap_pvt_thread_mutex_init( &si->si_mods_mutex );
03214        ldap_pvt_thread_mutex_init( &si->si_resp_mutex );
03215 
03216        csn_anlist[0].an_desc = slap_schema.si_ad_entryCSN;
03217        csn_anlist[0].an_name = slap_schema.si_ad_entryCSN->ad_cname;
03218        csn_anlist[1].an_desc = slap_schema.si_ad_entryUUID;
03219        csn_anlist[1].an_name = slap_schema.si_ad_entryUUID->ad_cname;
03220 
03221        uuid_anlist[0].an_desc = slap_schema.si_ad_entryUUID;
03222        uuid_anlist[0].an_name = slap_schema.si_ad_entryUUID->ad_cname;
03223 
03224        return 0;
03225 }
03226 
03227 static int
03228 syncprov_db_destroy(
03229        BackendDB *be,
03230        ConfigReply *cr
03231 )
03232 {
03233        slap_overinst *on = (slap_overinst *)be->bd_info;
03234        syncprov_info_t      *si = (syncprov_info_t *)on->on_bi.bi_private;
03235 
03236        if ( si ) {
03237               if ( si->si_logs ) {
03238                      sessionlog *sl = si->si_logs;
03239                      slog_entry *se = sl->sl_head;
03240 
03241                      while ( se ) {
03242                             slog_entry *se_next = se->se_next;
03243                             ch_free( se );
03244                             se = se_next;
03245                      }
03246                      if ( sl->sl_mincsn )
03247                             ber_bvarray_free( sl->sl_mincsn );
03248                      if ( sl->sl_sids )
03249                             ch_free( sl->sl_sids );
03250 
03251                      ldap_pvt_thread_mutex_destroy(&si->si_logs->sl_mutex);
03252                      ch_free( si->si_logs );
03253               }
03254               if ( si->si_ctxcsn )
03255                      ber_bvarray_free( si->si_ctxcsn );
03256               if ( si->si_sids )
03257                      ch_free( si->si_sids );
03258               ldap_pvt_thread_mutex_destroy( &si->si_resp_mutex );
03259               ldap_pvt_thread_mutex_destroy( &si->si_mods_mutex );
03260               ldap_pvt_thread_mutex_destroy( &si->si_ops_mutex );
03261               ldap_pvt_thread_rdwr_destroy( &si->si_csn_rwlock );
03262               ch_free( si );
03263        }
03264 
03265        return 0;
03266 }
03267 
03268 static int syncprov_parseCtrl (
03269        Operation *op,
03270        SlapReply *rs,
03271        LDAPControl *ctrl )
03272 {
03273        ber_tag_t tag;
03274        BerElementBuffer berbuf;
03275        BerElement *ber = (BerElement *)&berbuf;
03276        ber_int_t mode;
03277        ber_len_t len;
03278        struct berval cookie = BER_BVNULL;
03279        sync_control *sr;
03280        int rhint = 0;
03281 
03282        if ( op->o_sync != SLAP_CONTROL_NONE ) {
03283               rs->sr_text = "Sync control specified multiple times";
03284               return LDAP_PROTOCOL_ERROR;
03285        }
03286 
03287        if ( op->o_pagedresults != SLAP_CONTROL_NONE ) {
03288               rs->sr_text = "Sync control specified with pagedResults control";
03289               return LDAP_PROTOCOL_ERROR;
03290        }
03291 
03292        if ( BER_BVISNULL( &ctrl->ldctl_value ) ) {
03293               rs->sr_text = "Sync control value is absent";
03294               return LDAP_PROTOCOL_ERROR;
03295        }
03296 
03297        if ( BER_BVISEMPTY( &ctrl->ldctl_value ) ) {
03298               rs->sr_text = "Sync control value is empty";
03299               return LDAP_PROTOCOL_ERROR;
03300        }
03301 
03302        /* Parse the control value
03303         *      syncRequestValue ::= SEQUENCE {
03304         *              mode   ENUMERATED {
03305         *                      -- 0 unused
03306         *                      refreshOnly              (1),
03307         *                      -- 2 reserved
03308         *                      refreshAndPersist (3)
03309         *              },
03310         *              cookie  syncCookie OPTIONAL
03311         *      }
03312         */
03313 
03314        ber_init2( ber, &ctrl->ldctl_value, 0 );
03315 
03316        if ( (tag = ber_scanf( ber, "{i" /*}*/, &mode )) == LBER_ERROR ) {
03317               rs->sr_text = "Sync control : mode decoding error";
03318               return LDAP_PROTOCOL_ERROR;
03319        }
03320 
03321        switch( mode ) {
03322        case LDAP_SYNC_REFRESH_ONLY:
03323               mode = SLAP_SYNC_REFRESH;
03324               break;
03325        case LDAP_SYNC_REFRESH_AND_PERSIST:
03326               mode = SLAP_SYNC_REFRESH_AND_PERSIST;
03327               break;
03328        default:
03329               rs->sr_text = "Sync control : unknown update mode";
03330               return LDAP_PROTOCOL_ERROR;
03331        }
03332 
03333        tag = ber_peek_tag( ber, &len );
03334 
03335        if ( tag == LDAP_TAG_SYNC_COOKIE ) {
03336               if (( ber_scanf( ber, /*{*/ "m", &cookie )) == LBER_ERROR ) {
03337                      rs->sr_text = "Sync control : cookie decoding error";
03338                      return LDAP_PROTOCOL_ERROR;
03339               }
03340               tag = ber_peek_tag( ber, &len );
03341        }
03342        if ( tag == LDAP_TAG_RELOAD_HINT ) {
03343               if (( ber_scanf( ber, /*{*/ "b", &rhint )) == LBER_ERROR ) {
03344                      rs->sr_text = "Sync control : rhint decoding error";
03345                      return LDAP_PROTOCOL_ERROR;
03346               }
03347        }
03348        if (( ber_scanf( ber, /*{*/ "}")) == LBER_ERROR ) {
03349                      rs->sr_text = "Sync control : decoding error";
03350                      return LDAP_PROTOCOL_ERROR;
03351        }
03352        sr = op->o_tmpcalloc( 1, sizeof(struct sync_control), op->o_tmpmemctx );
03353        sr->sr_rhint = rhint;
03354        if (!BER_BVISNULL(&cookie)) {
03355               ber_dupbv_x( &sr->sr_state.octet_str, &cookie, op->o_tmpmemctx );
03356               /* If parse fails, pretend no cookie was sent */
03357               if ( slap_parse_sync_cookie( &sr->sr_state, op->o_tmpmemctx ) ||
03358                      sr->sr_state.rid == -1 ) {
03359                      if ( sr->sr_state.ctxcsn ) {
03360                             ber_bvarray_free_x( sr->sr_state.ctxcsn, op->o_tmpmemctx );
03361                             sr->sr_state.ctxcsn = NULL;
03362                      }
03363                      sr->sr_state.numcsns = 0;
03364               }
03365        }
03366 
03367        op->o_controls[slap_cids.sc_LDAPsync] = sr;
03368 
03369        op->o_sync = ctrl->ldctl_iscritical
03370               ? SLAP_CONTROL_CRITICAL
03371               : SLAP_CONTROL_NONCRITICAL;
03372 
03373        op->o_sync_mode |= mode;    /* o_sync_mode shares o_sync */
03374 
03375        return LDAP_SUCCESS;
03376 }
03377 
03378 /* This overlay is set up for dynamic loading via moduleload. For static
03379  * configuration, you'll need to arrange for the slap_overinst to be
03380  * initialized and registered by some other function inside slapd.
03381  */
03382 
03383 static slap_overinst               syncprov;
03384 
03385 int
03386 syncprov_initialize()
03387 {
03388        int rc;
03389 
03390        rc = register_supported_control( LDAP_CONTROL_SYNC,
03391               SLAP_CTRL_SEARCH, NULL,
03392               syncprov_parseCtrl, &slap_cids.sc_LDAPsync );
03393        if ( rc != LDAP_SUCCESS ) {
03394               Debug( LDAP_DEBUG_ANY,
03395                      "syncprov_init: Failed to register control %d\n", rc, 0, 0 );
03396               return rc;
03397        }
03398 
03399        syncprov.on_bi.bi_type = "syncprov";
03400        syncprov.on_bi.bi_db_init = syncprov_db_init;
03401        syncprov.on_bi.bi_db_destroy = syncprov_db_destroy;
03402        syncprov.on_bi.bi_db_open = syncprov_db_open;
03403        syncprov.on_bi.bi_db_close = syncprov_db_close;
03404 
03405        syncprov.on_bi.bi_op_abandon = syncprov_op_abandon;
03406        syncprov.on_bi.bi_op_cancel = syncprov_op_abandon;
03407 
03408        syncprov.on_bi.bi_op_add = syncprov_op_mod;
03409        syncprov.on_bi.bi_op_compare = syncprov_op_compare;
03410        syncprov.on_bi.bi_op_delete = syncprov_op_mod;
03411        syncprov.on_bi.bi_op_modify = syncprov_op_mod;
03412        syncprov.on_bi.bi_op_modrdn = syncprov_op_mod;
03413        syncprov.on_bi.bi_op_search = syncprov_op_search;
03414        syncprov.on_bi.bi_extended = syncprov_op_extended;
03415        syncprov.on_bi.bi_operational = syncprov_operational;
03416 
03417        syncprov.on_bi.bi_cf_ocs = spocs;
03418 
03419        generic_filter.f_desc = slap_schema.si_ad_objectClass;
03420 
03421        rc = config_register_schema( spcfg, spocs );
03422        if ( rc ) return rc;
03423 
03424        return overlay_register( &syncprov );
03425 }
03426 
03427 #if SLAPD_OVER_SYNCPROV == SLAPD_MOD_DYNAMIC
03428 int
03429 init_module( int argc, char *argv[] )
03430 {
03431        return syncprov_initialize();
03432 }
03433 #endif /* SLAPD_OVER_SYNCPROV == SLAPD_MOD_DYNAMIC */
03434 
03435 #endif /* defined(SLAPD_OVER_SYNCPROV) */